Skip to content

Commit

Permalink
fix: invalidate cache at failed (#52)
Browse files Browse the repository at this point in the history
* invalidate cache at failed

* fix to invalidate at failed, and invalidate at gov failed

* fix test
  • Loading branch information
beer-1 authored Jan 15, 2024
1 parent fd7bee4 commit c6e56e4
Show file tree
Hide file tree
Showing 12 changed files with 60 additions and 112 deletions.
1 change: 0 additions & 1 deletion app/ante/ante.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) {
anteDecorators := []sdk.AnteDecorator{
ante.NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first
ante.NewExtensionOptionsDecorator(options.ExtensionOptionChecker),
moveante.NewSimulationFlagDecorator(),
moveante.NewGasPricesDecorator(),
ante.NewValidateBasicDecorator(),
ante.NewTxTimeoutHeightDecorator(),
Expand Down
2 changes: 1 addition & 1 deletion app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -849,7 +849,7 @@ func NewInitiaApp(
capability.NewAppModule(appCodec, *app.CapabilityKeeper, false),
crisis.NewAppModule(app.CrisisKeeper, skipGenesisInvariants, nil),
feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, *app.FeeGrantKeeper, app.interfaceRegistry),
gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper),
gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper, app.MoveKeeper.GetPostHandler()),
reward.NewAppModule(appCodec, *app.RewardKeeper),
slashing.NewAppModule(appCodec, *app.SlashingKeeper),
distr.NewAppModule(appCodec, *app.DistrKeeper),
Expand Down
19 changes: 15 additions & 4 deletions x/gov/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import (
)

// EndBlocker called every block, process inflation, update validator set.
func EndBlocker(ctx sdk.Context, k *keeper.Keeper) error {
func EndBlocker(ctx sdk.Context, k *keeper.Keeper, postHandler sdk.PostHandler) error {
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker)

logger := k.Logger(ctx)
Expand Down Expand Up @@ -139,7 +139,7 @@ func EndBlocker(ctx sdk.Context, k *keeper.Keeper) error {
return false, err
}

err = handleTallyResult(ctx, k, proposal, passed, burnDeposits, tallyResults)
err = handleTallyResult(ctx, k, proposal, passed, burnDeposits, tallyResults, postHandler)
if err != nil {
return false, err
}
Expand Down Expand Up @@ -177,8 +177,8 @@ func EndBlocker(ctx sdk.Context, k *keeper.Keeper) error {
}
return false, err
}
cacheCtx, writeCache := ctx.CacheContext()

cacheCtx, writeCache := ctx.CacheContext()
quorumReached, passed, burnDeposits, tallyResults, err := k.Tally(cacheCtx, proposal)
if err != nil {
return false, err
Expand All @@ -199,7 +199,7 @@ func EndBlocker(ctx sdk.Context, k *keeper.Keeper) error {
// quorum reached; commit the state changes from k.Tally()
writeCache()

err = handleTallyResult(ctx, k, proposal, passed, burnDeposits, tallyResults)
err = handleTallyResult(ctx, k, proposal, passed, burnDeposits, tallyResults, postHandler)
if err != nil {
return false, err
}
Expand All @@ -216,6 +216,7 @@ func handleTallyResult(
proposal customtypes.Proposal,
passed, burnDeposits bool,
tallyResults v1.TallyResult,
postHandler sdk.PostHandler,
) (err error) {
// If an expedited proposal fails, we do not want to update
// the deposit at this point since the proposal is converted to regular.
Expand Down Expand Up @@ -283,6 +284,16 @@ func handleTallyResult(
events = append(events, res.GetEvents()...)
}

// run post handler (for move cache invalidate)
if postHandler != nil {
newCtx, err := postHandler(ctx, nil, false, err == nil)
if err != nil {
return err
}

ctx = newCtx
}

// `err == nil` when all handlers passed.
// Or else, `idx` and `err` are populated with the msg index and error.
if err == nil {
Expand Down
17 changes: 8 additions & 9 deletions x/gov/abci_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ func TestSimpleProposalPassedEndblocker(t *testing.T) {
ctx = ctx.WithBlockHeader(newHeader)

proposal, err = app.GovKeeper.Proposals.Get(ctx, 1)
require.NoError(t, err)
require.True(t, proposal.SubmitTime.Equal(initTime))
require.True(t, proposal.DepositEndTime.Equal(initTime.Add(depositPeriod)))
require.Equal(t, proposal.Status, v1.StatusVotingPeriod)
Expand All @@ -50,8 +51,10 @@ func TestSimpleProposalPassedEndblocker(t *testing.T) {

voteMsg := createVoteMsg(t, addrs[0], proposal.Id, v1.OptionYes)
_, err = govMsgSvr.Vote(ctx, voteMsg)
require.NoError(t, err)
voteMsg = createVoteMsg(t, addrs[1], proposal.Id, v1.OptionYes)
_, err = govMsgSvr.Vote(ctx, voteMsg)
require.NoError(t, err)
voteMsg = createVoteMsg(t, addrs[2], proposal.Id, v1.OptionYes)
_, err = govMsgSvr.Vote(ctx, voteMsg)
require.NoError(t, err)
Expand All @@ -60,7 +63,7 @@ func TestSimpleProposalPassedEndblocker(t *testing.T) {
newHeader.Time = ctx.BlockHeader().Time.Add(votingPeriod)
ctx = ctx.WithBlockHeader(newHeader)

err = gov.EndBlocker(ctx, app.GovKeeper)
err = gov.EndBlocker(ctx, app.GovKeeper, app.MoveKeeper.GetPostHandler())
require.NoError(t, err)

proposal, err = app.GovKeeper.Proposals.Get(ctx, 1)
Expand All @@ -83,6 +86,7 @@ func TestEmergencyProposalPassedEndblocker(t *testing.T) {
ctx = ctx.WithBlockHeader(newHeader)

proposal, err := app.GovKeeper.Proposals.Get(ctx, 1)
require.NoError(t, err)
require.True(t, proposal.Emergency)
require.True(t, proposal.EmergencyStartTime.Equal(ctx.BlockTime().Add(-time.Minute)))
require.True(t, proposal.EmergencyNextTallyTime.Equal(ctx.BlockTime().Add(emergencyTallyInterval-time.Minute)))
Expand Down Expand Up @@ -112,7 +116,7 @@ func TestEmergencyProposalPassedEndblocker(t *testing.T) {
newHeader.Time = ctx.BlockHeader().Time.Add(time.Minute)
ctx = ctx.WithBlockHeader(newHeader)

err = gov.EndBlocker(ctx, app.GovKeeper)
err = gov.EndBlocker(ctx, app.GovKeeper, app.MoveKeeper.GetPostHandler())
require.NoError(t, err)
proposal, err = app.GovKeeper.Proposals.Get(ctx, 1)
require.NoError(t, err)
Expand All @@ -124,18 +128,13 @@ func TestEmergencyProposalPassedEndblocker(t *testing.T) {

require.True(t, ctx.BlockHeader().Time.Equal(*proposal.EmergencyNextTallyTime))

err = gov.EndBlocker(ctx, app.GovKeeper)
err = gov.EndBlocker(ctx, app.GovKeeper, app.MoveKeeper.GetPostHandler())
require.NoError(t, err)
proposal, err = app.GovKeeper.Proposals.Get(ctx, 1)
require.NoError(t, err)
require.Equal(t, proposal.Status, v1.StatusPassed)
}

type tickTestResult struct {
status v1.ProposalStatus
emergency bool
}

func TestTickSingleProposal(t *testing.T) {
testCases := []struct {
name string
Expand Down Expand Up @@ -250,7 +249,7 @@ func TestTickSingleProposal(t *testing.T) {
voteCheck = true
}

err = gov.EndBlocker(ctx, app.GovKeeper)
err = gov.EndBlocker(ctx, app.GovKeeper, app.MoveKeeper.GetPostHandler())
require.NoError(t, err)
}
proposal, err := app.GovKeeper.Proposals.Get(ctx, 1)
Expand Down
12 changes: 1 addition & 11 deletions x/gov/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"time"

initiaapp "github.com/initia-labs/initia/app"
stakingtypes "github.com/initia-labs/initia/x/mstaking/types"
"github.com/stretchr/testify/require"

"cosmossdk.io/math"
Expand Down Expand Up @@ -42,14 +41,6 @@ var (
sdk.AccAddress(pubKeys[4].Address()),
}

valAddrs = []sdk.ValAddress{
sdk.ValAddress(pubKeys[0].Address()),
sdk.ValAddress(pubKeys[1].Address()),
sdk.ValAddress(pubKeys[2].Address()),
sdk.ValAddress(pubKeys[3].Address()),
sdk.ValAddress(pubKeys[4].Address()),
}

validators = []*cmtypes.Validator{
cmtypes.NewValidator(pubKeys[0], 1000000),
cmtypes.NewValidator(pubKeys[1], 1000000),
Expand All @@ -58,8 +49,6 @@ var (
cmtypes.NewValidator(pubKeys[4], 1000000),
}

commissionRates = stakingtypes.NewCommissionRates(math.LegacyZeroDec(), math.LegacyZeroDec(), math.LegacyZeroDec())

genCoins = sdk.NewCoins(sdk.NewCoin(bondDenom, math.NewInt(10000000))).Sort()

minDepositRatio = "0.01"
Expand Down Expand Up @@ -106,6 +95,7 @@ func createAppWithSimpleValidators(t *testing.T) *initiaapp.InitiaApp {
params.VotingPeriod = votingPeriod
params.EmergencyTallyInterval = emergencyTallyInterval
err = app.GovKeeper.Params.Set(ctx, params)
require.NoError(t, err)
_, err = app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: app.LastBlockHeight() + 1})
require.NoError(t, err)
return app
Expand Down
17 changes: 14 additions & 3 deletions x/gov/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,15 +131,24 @@ type AppModule struct {
keeper *keeper.Keeper
accountKeeper types.AccountKeeper
bankKeeper types.BankKeeper

postHandler sdk.PostHandler
}

// NewAppModule creates a new AppModule object
func NewAppModule(cdc codec.Codec, keeper *keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper) AppModule {
func NewAppModule(
cdc codec.Codec,
keeper *keeper.Keeper,
ak types.AccountKeeper,
bk types.BankKeeper,
postHandler sdk.PostHandler,
) AppModule {
return AppModule{
AppModuleBasic: AppModuleBasic{cdc: cdc},
keeper: keeper,
accountKeeper: ak,
bankKeeper: bk,
postHandler: postHandler,
}
}

Expand Down Expand Up @@ -169,6 +178,7 @@ type ModuleInputs struct {
BankKeeper types.BankKeeper
StakingKeeper customtypes.StakingKeeper
DistributionKeeper types.DistributionKeeper
PostHandler sdk.PostHandler
}

type ModuleOutputs struct {
Expand Down Expand Up @@ -202,7 +212,8 @@ func ProvideModule(in ModuleInputs) ModuleOutputs {
defaultConfig,
authority.String(),
)
m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper)

m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.PostHandler)
hr := v1beta1.HandlerRoute{Handler: v1beta1.ProposalHandler, RouteKey: types.RouterKey}

return ModuleOutputs{Module: m, Keeper: k, HandlerRoute: hr}
Expand Down Expand Up @@ -299,5 +310,5 @@ func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion }
// updates.
func (am AppModule) EndBlock(ctx context.Context) error {
c := sdk.UnwrapSDKContext(ctx)
return EndBlocker(c, am.keeper)
return EndBlocker(c, am.keeper, am.postHandler)
}
6 changes: 4 additions & 2 deletions x/move/ante/context_keys.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package ante

// private type creates an interface key for Context that cannot be accessed by any other package
type contextKey int

const (
SimulationFlagContextKey = iota
GasPricesContextKey
GasPricesContextKey contextKey = iota
)
24 changes: 0 additions & 24 deletions x/move/ante/simulation_flag.go

This file was deleted.

35 changes: 0 additions & 35 deletions x/move/ante/simulation_flag_test.go

This file was deleted.

27 changes: 11 additions & 16 deletions x/move/keeper/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,15 @@ import (
vmtypes "github.com/initia-labs/initiavm/types"
)

func isSimulationOrCheckTx(
func isSimulation(
ctx context.Context,
) bool {
sdkCtx := sdk.UnwrapSDKContext(ctx)
if sdkCtx.IsCheckTx() || sdkCtx.IsReCheckTx() {
return true
}

simulate := sdkCtx.Value(ante.SimulationFlagContextKey)
if simulate == nil {
return false
}

return simulate.(bool)
// only executed when ExecMode is
// * simulate
// * finalize
return sdkCtx.ExecMode() == sdk.ExecModeSimulate
}

// extract module address and module name from the compiled module bytes
Expand Down Expand Up @@ -157,8 +152,8 @@ func (k Keeper) ExecuteEntryFunctionWithMultiSenders(
gasMeter := sdkCtx.GasMeter()
gasForRuntime := gasMeter.Limit() - gasMeter.GasConsumedToLimit()

isSimulationOrCheckTx := isSimulationOrCheckTx(ctx)
if isSimulationOrCheckTx {
isSimulation := isSimulation(ctx)
if isSimulation {
vm = k.buildSimulationVM()
defer vm.Destroy()

Expand All @@ -182,7 +177,7 @@ func (k Keeper) ExecuteEntryFunctionWithMultiSenders(
)

// Mark loader cache loads new published modules.
if !isSimulationOrCheckTx {
if !isSimulation {
k.postHandler.SetNewPublishedModulesLoaded(execRes.NewPublishedModulesLoaded)
}

Expand Down Expand Up @@ -257,8 +252,8 @@ func (k Keeper) ExecuteScriptWithMultiSenders(
gasMeter := sdkCtx.GasMeter()
gasForRuntime := gasMeter.Limit() - gasMeter.GasConsumedToLimit()

isSimulationOrCheckTx := isSimulationOrCheckTx(ctx)
if isSimulationOrCheckTx {
isSimulation := isSimulation(ctx)
if isSimulation {
vm = k.buildSimulationVM()
defer vm.Destroy()

Expand All @@ -282,7 +277,7 @@ func (k Keeper) ExecuteScriptWithMultiSenders(
)

// Mark loader cache loads new published modules.
if !isSimulationOrCheckTx {
if !isSimulation {
k.postHandler.SetNewPublishedModulesLoaded(execRes.NewPublishedModulesLoaded)
}

Expand Down
Loading

0 comments on commit c6e56e4

Please sign in to comment.