Skip to content

Commit

Permalink
gas meter logs
Browse files Browse the repository at this point in the history
  • Loading branch information
p0mvn committed Dec 19, 2023
1 parent 15259cc commit 5120fe5
Show file tree
Hide file tree
Showing 18 changed files with 56 additions and 37 deletions.
2 changes: 1 addition & 1 deletion baseapp/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitC
}

// add block gas meter for any genesis transactions (allow infinite gas)
app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter())
app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter(app.logger))

res = app.initChainer(app.deliverState.ctx, req)

Expand Down
9 changes: 5 additions & 4 deletions baseapp/abci_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

dbm "github.com/cometbft/cometbft-db"
abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/libs/log"
tmproto "github.com/cometbft/cometbft/proto/tendermint/types"
"github.com/cosmos/gogoproto/jsonpb"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -758,7 +759,7 @@ func TestABCI_Query_SimulateTx(t *testing.T) {
gasConsumed := uint64(5)
anteOpt := func(bapp *baseapp.BaseApp) {
bapp.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, err error) {
newCtx = ctx.WithGasMeter(sdk.NewGasMeter(gasConsumed))
newCtx = ctx.WithGasMeter(sdk.NewGasMeter(gasConsumed, log.NewNopLogger()))
return
})
}
Expand Down Expand Up @@ -923,7 +924,7 @@ func TestABCI_TxGasLimits(t *testing.T) {
gasGranted := uint64(10)
anteOpt := func(bapp *baseapp.BaseApp) {
bapp.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, err error) {
newCtx = ctx.WithGasMeter(sdk.NewGasMeter(gasGranted))
newCtx = ctx.WithGasMeter(sdk.NewGasMeter(gasGranted, log.NewNopLogger()))

// AnteHandlers must have their own defer/recover in order for the BaseApp
// to know how much gas was used! This is because the GasMeter is created in
Expand Down Expand Up @@ -1006,7 +1007,7 @@ func TestABCI_MaxBlockGasLimits(t *testing.T) {
gasGranted := uint64(10)
anteOpt := func(bapp *baseapp.BaseApp) {
bapp.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, err error) {
newCtx = ctx.WithGasMeter(sdk.NewGasMeter(gasGranted))
newCtx = ctx.WithGasMeter(sdk.NewGasMeter(gasGranted, log.NewNopLogger()))

defer func() {
if r := recover(); r != nil {
Expand Down Expand Up @@ -1101,7 +1102,7 @@ func TestABCI_GasConsumptionBadTx(t *testing.T) {
gasWanted := uint64(5)
anteOpt := func(bapp *baseapp.BaseApp) {
bapp.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, err error) {
newCtx = ctx.WithGasMeter(sdk.NewGasMeter(gasWanted))
newCtx = ctx.WithGasMeter(sdk.NewGasMeter(gasWanted, log.NewNopLogger()))

defer func() {
if r := recover(); r != nil {
Expand Down
4 changes: 2 additions & 2 deletions baseapp/baseapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -566,10 +566,10 @@ func (app *BaseApp) getState(mode runTxMode) *state {

func (app *BaseApp) getBlockGasMeter(ctx sdk.Context) storetypes.GasMeter {
if maxGas := app.GetMaximumBlockGas(ctx); maxGas > 0 {
return storetypes.NewGasMeter(maxGas)
return storetypes.NewGasMeter(maxGas, ctx.Logger())
}

return storetypes.NewInfiniteGasMeter()
return storetypes.NewInfiniteGasMeter(ctx.Logger())
}

// retrieve the context for the tx w/ txBytes and other memoized values.
Expand Down
9 changes: 5 additions & 4 deletions store/gaskv/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
dbm "github.com/cometbft/cometbft-db"
"github.com/stretchr/testify/require"

"github.com/cometbft/cometbft/libs/log"
"github.com/cosmos/cosmos-sdk/store/dbadapter"
"github.com/cosmos/cosmos-sdk/store/gaskv"
"github.com/cosmos/cosmos-sdk/store/types"
Expand All @@ -19,7 +20,7 @@ func valFmt(i int) []byte { return bz(fmt.Sprintf("value%0.8d", i)) }

func TestGasKVStoreBasic(t *testing.T) {
mem := dbadapter.Store{DB: dbm.NewMemDB()}
meter := types.NewGasMeter(10000)
meter := types.NewGasMeter(10000, log.NewNopLogger())
st := gaskv.NewStore(mem, meter, types.KVGasConfig())

require.Equal(t, types.StoreTypeDB, st.GetStoreType())
Expand All @@ -39,7 +40,7 @@ func TestGasKVStoreBasic(t *testing.T) {

func TestGasKVStoreIterator(t *testing.T) {
mem := dbadapter.Store{DB: dbm.NewMemDB()}
meter := types.NewGasMeter(100000)
meter := types.NewGasMeter(100000, log.NewNopLogger())
st := gaskv.NewStore(mem, meter, types.KVGasConfig())
require.False(t, st.Has(keyFmt(1)))
require.Empty(t, st.Get(keyFmt(1)), "Expected `key1` to be empty")
Expand Down Expand Up @@ -104,14 +105,14 @@ func TestGasKVStoreIterator(t *testing.T) {

func TestGasKVStoreOutOfGasSet(t *testing.T) {
mem := dbadapter.Store{DB: dbm.NewMemDB()}
meter := types.NewGasMeter(0)
meter := types.NewGasMeter(0, log.NewNopLogger())
st := gaskv.NewStore(mem, meter, types.KVGasConfig())
require.Panics(t, func() { st.Set(keyFmt(1), valFmt(1)) }, "Expected out-of-gas")
}

func TestGasKVStoreOutOfGasIterator(t *testing.T) {
mem := dbadapter.Store{DB: dbm.NewMemDB()}
meter := types.NewGasMeter(20000)
meter := types.NewGasMeter(20000, log.NewNopLogger())
st := gaskv.NewStore(mem, meter, types.KVGasConfig())
st.Set(keyFmt(1), valFmt(1))
iterator := st.Iterator(nil, nil)
Expand Down
14 changes: 12 additions & 2 deletions store/types/gas.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package types
import (
"fmt"
"math"

"github.com/cometbft/cometbft/libs/log"
)

// Gas consumption descriptors.
Expand Down Expand Up @@ -53,13 +55,15 @@ type GasMeter interface {
type basicGasMeter struct {
limit Gas
consumed Gas
logger log.Logger
}

// NewGasMeter returns a reference to a new basicGasMeter.
func NewGasMeter(limit Gas) GasMeter {
func NewGasMeter(limit Gas, logger log.Logger) GasMeter {
return &basicGasMeter{
limit: limit,
consumed: 0,
logger: logger,
}
}

Expand Down Expand Up @@ -105,6 +109,8 @@ func addUint64Overflow(a, b uint64) (uint64, bool) {

// ConsumeGas adds the given amount of gas to the gas consumed and panics if it overflows the limit or out of gas.
func (g *basicGasMeter) ConsumeGas(amount Gas, descriptor string) {
g.logger.Info("BasicGasMeter.ConsumeGas", "amount", amount, "descriptor", descriptor)

var overflow bool
g.consumed, overflow = addUint64Overflow(g.consumed, amount)
if overflow {
Expand Down Expand Up @@ -148,12 +154,14 @@ func (g *basicGasMeter) String() string {

type infiniteGasMeter struct {
consumed Gas
logger log.Logger
}

// NewInfiniteGasMeter returns a new gas meter without a limit.
func NewInfiniteGasMeter() GasMeter {
func NewInfiniteGasMeter(logger log.Logger) GasMeter {
return &infiniteGasMeter{
consumed: 0,
logger: logger,
}
}

Expand All @@ -180,6 +188,8 @@ func (g *infiniteGasMeter) Limit() Gas {

// ConsumeGas adds the given amount of gas to the gas consumed and panics if it overflows the limit.
func (g *infiniteGasMeter) ConsumeGas(amount Gas, descriptor string) {
g.logger.Info("InfiniteGasMeter.ConsumeGas", "amount", amount, "descriptor", descriptor)

var overflow bool
// TODO: Should we set the consumed field after overflow checking?
g.consumed, overflow = addUint64Overflow(g.consumed, amount)
Expand Down
2 changes: 1 addition & 1 deletion types/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ func NewContext(ms MultiStore, header tmproto.Header, isCheckTx bool, logger log
chainID: header.ChainID,
checkTx: isCheckTx,
logger: logger,
gasMeter: storetypes.NewInfiniteGasMeter(),
gasMeter: storetypes.NewInfiniteGasMeter(logger),
minGasPrice: DecCoins{},
eventManager: NewEventManager(),
kvGasConfig: storetypes.KVGasConfig(),
Expand Down
5 changes: 3 additions & 2 deletions types/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"time"

abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/libs/log"
tmproto "github.com/cometbft/cometbft/proto/tendermint/types"
tmtime "github.com/cometbft/cometbft/types/time"
"github.com/golang/mock/gomock"
Expand Down Expand Up @@ -90,8 +91,8 @@ func (s *contextTestSuite) TestContextWithCustom() {
txbytes := []byte("txbytes")
logger := mock.NewMockLogger(ctrl)
voteinfos := []abci.VoteInfo{{}}
meter := types.NewGasMeter(10000)
blockGasMeter := types.NewGasMeter(20000)
meter := types.NewGasMeter(10000, log.NewNopLogger())
blockGasMeter := types.NewGasMeter(20000, log.NewNopLogger())
minGasPrices := types.DecCoins{types.NewInt64DecCoin("feetoken", 1)}
headerHash := []byte("headerHash")
zeroGasCfg := storetypes.GasConfig{}
Expand Down
2 changes: 1 addition & 1 deletion types/module/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ func (m *Manager) ExportGenesisForModules(ctx sdk.Context, cdc codec.JSONCodec,
if module, ok := m.Modules[moduleName].(HasGenesis); ok {
channels[moduleName] = make(chan json.RawMessage)
go func(module HasGenesis, ch chan json.RawMessage) {
ctx := ctx.WithGasMeter(sdk.NewInfiniteGasMeter()) // avoid race conditions
ctx := ctx.WithGasMeter(sdk.NewInfiniteGasMeter(ctx.Logger())) // avoid race conditions
ch <- module.ExportGenesis(ctx, cdc)
}(module, channels[moduleName])
}
Expand Down
10 changes: 6 additions & 4 deletions types/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (

"github.com/cosmos/cosmos-sdk/store/types"
"github.com/cosmos/cosmos-sdk/types/kv"

"github.com/cometbft/cometbft/libs/log"
)

type (
Expand Down Expand Up @@ -156,10 +158,10 @@ type (
ErrorGasOverflow = types.ErrorGasOverflow
)

func NewGasMeter(limit Gas) GasMeter {
return types.NewGasMeter(limit)
func NewGasMeter(limit Gas, logger log.Logger) GasMeter {
return types.NewGasMeter(limit, logger)
}

func NewInfiniteGasMeter() GasMeter {
return types.NewInfiniteGasMeter()
func NewInfiniteGasMeter(log log.Logger) GasMeter {
return types.NewInfiniteGasMeter(log)
}
2 changes: 1 addition & 1 deletion types/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (s *storeTestSuite) TestNewTransientStoreKeys() {
}

func (s *storeTestSuite) TestNewInfiniteGasMeter() {
gm := sdk.NewInfiniteGasMeter()
gm := sdk.NewInfiniteGasMeter(log.NewNopLogger())
s.Require().NotNil(gm)
_, ok := gm.(types.GasMeter)
s.Require().True(ok)
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 @@ -75,8 +75,8 @@ func SetGasMeter(simulate bool, 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 simulate || ctx.BlockHeight() == 0 {
return ctx.WithGasMeter(sdk.NewInfiniteGasMeter())
return ctx.WithGasMeter(sdk.NewInfiniteGasMeter(ctx.Logger()))
}

return ctx.WithGasMeter(sdk.NewGasMeter(gasLimit))
return ctx.WithGasMeter(sdk.NewGasMeter(gasLimit, ctx.Logger()))
}
5 changes: 3 additions & 2 deletions x/auth/ante/setup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package ante_test
import (
"testing"

"github.com/cometbft/cometbft/libs/log"
tmproto "github.com/cometbft/cometbft/proto/tendermint/types"

cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
Expand Down Expand Up @@ -37,7 +38,7 @@ func TestSetupDecorator_BlockMaxGas(t *testing.T) {

suite.ctx = suite.ctx.
WithBlockHeight(1).
WithGasMeter(storetypes.NewGasMeter(0)).
WithGasMeter(storetypes.NewGasMeter(0, log.NewNopLogger())).
WithConsensusParams(&tmproto.ConsensusParams{
Block: &tmproto.BlockParams{
MaxGas: 100,
Expand Down Expand Up @@ -71,7 +72,7 @@ func TestSetup(t *testing.T) {
antehandler := sdk.ChainAnteDecorators(sud)

// Set height to non-zero value for GasMeter to be set
suite.ctx = suite.ctx.WithBlockHeight(1).WithGasMeter(sdk.NewGasMeter(0))
suite.ctx = suite.ctx.WithBlockHeight(1).WithGasMeter(sdk.NewGasMeter(0, log.NewNopLogger()))

// Context GasMeter Limit not set
require.Equal(t, uint64(0), suite.ctx.GasMeter().Limit(), "GasMeter set with limit before setup")
Expand Down
11 changes: 6 additions & 5 deletions x/auth/ante/sigverify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"testing"

"github.com/cometbft/cometbft/libs/log"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
Expand Down Expand Up @@ -95,11 +96,11 @@ func TestConsumeSignatureVerificationGas(t *testing.T) {
gasConsumed uint64
shouldErr bool
}{
{"PubKeyEd25519", args{sdk.NewInfiniteGasMeter(), nil, ed25519.GenPrivKey().PubKey(), params}, p.SigVerifyCostED25519, true},
{"PubKeySecp256k1", args{sdk.NewInfiniteGasMeter(), nil, secp256k1.GenPrivKey().PubKey(), params}, p.SigVerifyCostSecp256k1, false},
{"PubKeySecp256r1", args{sdk.NewInfiniteGasMeter(), nil, skR1.PubKey(), params}, p.SigVerifyCostSecp256r1(), false},
{"Multisig", args{sdk.NewInfiniteGasMeter(), multisignature1, multisigKey1, params}, expectedCost1, false},
{"unknown key", args{sdk.NewInfiniteGasMeter(), nil, nil, params}, 0, true},
{"PubKeyEd25519", args{sdk.NewInfiniteGasMeter(log.NewNopLogger()), nil, ed25519.GenPrivKey().PubKey(), params}, p.SigVerifyCostED25519, true},
{"PubKeySecp256k1", args{sdk.NewInfiniteGasMeter(log.NewNopLogger()), nil, secp256k1.GenPrivKey().PubKey(), params}, p.SigVerifyCostSecp256k1, false},
{"PubKeySecp256r1", args{sdk.NewInfiniteGasMeter(log.NewNopLogger()), nil, skR1.PubKey(), params}, p.SigVerifyCostSecp256r1(), false},
{"Multisig", args{sdk.NewInfiniteGasMeter(log.NewNopLogger()), multisignature1, multisigKey1, params}, expectedCost1, false},
{"unknown key", args{sdk.NewInfiniteGasMeter(log.NewNopLogger()), nil, nil, params}, 0, true},
}
for _, tt := range tests {
sigV2 := signing.SignatureV2{
Expand Down
2 changes: 1 addition & 1 deletion x/capability/capability_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ 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))
ctx = suite.app.BaseApp.NewContext(false, tmproto.Header{}).WithBlockGasMeter(sdk.NewGasMeter(50, ctx.Logger()))
prevGas := ctx.BlockGasMeter().GasConsumed()
restartedModule := capability.NewAppModule(suite.cdc, *newKeeper, true)
restartedModule.BeginBlock(ctx, abci.RequestBeginBlock{})
Expand Down
3 changes: 2 additions & 1 deletion x/capability/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package capability_test
import (
tmproto "github.com/cometbft/cometbft/proto/tendermint/types"

"github.com/cometbft/cometbft/libs/log"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
Expand Down Expand Up @@ -37,7 +38,7 @@ func (suite *CapabilityTestSuite) TestGenesis() {

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{}).WithBlockGasMeter(sdk.NewInfiniteGasMeter(log.NewNopLogger())).CacheContext()

capability.InitGenesis(deliverCtx, *newKeeper, *genState)

Expand Down
2 changes: 1 addition & 1 deletion x/capability/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ func (k *Keeper) InitMemStore(ctx sdk.Context) {
}

// create context with no block gas meter to ensure we do not consume gas during local initialization logic.
noGasCtx := ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter())
noGasCtx := ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter(ctx.Logger()))

// check if memory store has not been initialized yet by checking if initialized flag is nil.
if !k.IsInitialized(noGasCtx) {
Expand Down
5 changes: 3 additions & 2 deletions x/group/internal/orm/testsupport.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"

dbm "github.com/cometbft/cometbft-db"
"github.com/cometbft/cometbft/libs/log"
"github.com/cosmos/cosmos-sdk/store"
"github.com/cosmos/cosmos-sdk/store/gaskv"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
Expand Down Expand Up @@ -81,7 +82,7 @@ type GasCountingMockContext struct {

func NewGasCountingMockContext() *GasCountingMockContext {
return &GasCountingMockContext{
GasMeter: &debuggingGasMeter{sdk.NewInfiniteGasMeter()},
GasMeter: &debuggingGasMeter{sdk.NewInfiniteGasMeter(log.NewNopLogger())},
}
}

Expand All @@ -98,5 +99,5 @@ func (g GasCountingMockContext) GasRemaining() storetypes.Gas {
}

func (g *GasCountingMockContext) ResetGasMeter() {
g.GasMeter = sdk.NewInfiniteGasMeter()
g.GasMeter = sdk.NewInfiniteGasMeter(log.NewNopLogger())
}
2 changes: 1 addition & 1 deletion x/upgrade/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func BeginBlocker(k *keeper.Keeper, ctx sdk.Context, _ abci.RequestBeginBlock) {

// We have an upgrade handler for this upgrade name, so apply the upgrade
ctx.Logger().Info(fmt.Sprintf("applying upgrade \"%s\" at %s", plan.Name, plan.DueAt()))
ctx = ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter())
ctx = ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter(ctx.Logger()))
k.ApplyUpgrade(ctx, plan)
return
}
Expand Down

0 comments on commit 5120fe5

Please sign in to comment.