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

feat: unfork cosmos sdk #17

Merged
merged 10 commits into from
Nov 24, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import (
"github.com/classic-terra/core/v3/app/keepers"
terraappparams "github.com/classic-terra/core/v3/app/params"
anteauth "github.com/classic-terra/core/v3/custom/auth/ante"
customserver "github.com/classic-terra/core/v3/server"

// upgrades
"github.com/classic-terra/core/v3/app/upgrades"
Expand Down Expand Up @@ -150,6 +151,11 @@ func NewTerraApp(

invCheckPeriod := cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod))

iavlCacheSize := cast.ToInt(appOpts.Get(server.FlagIAVLCacheSize))
iavlDisableFastNode := cast.ToBool(appOpts.Get(server.FlagDisableIAVLFastNode))
baseAppOptions = append(baseAppOptions, baseapp.SetIAVLCacheSize(iavlCacheSize))
baseAppOptions = append(baseAppOptions, baseapp.SetIAVLDisableFastNode(iavlDisableFastNode))

bApp := baseapp.NewBaseApp(appName, logger, db, txConfig.TxDecoder(), baseAppOptions...)
bApp.SetCommitMultiStoreTracer(traceStore)
bApp.SetVersion(version.Version)
Expand Down Expand Up @@ -447,6 +453,9 @@ func (app *TerraApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIC
if apiConfig.Swagger {
RegisterSwaggerAPI(apiSvr.Router)
}

// Apply custom middleware
apiSvr.Router.Use(customserver.BlockHeightMiddleware)
}

// RegisterTxService implements the Application.RegisterTxService method.
Expand Down
4 changes: 2 additions & 2 deletions app/keepers/keepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ import (
"github.com/CosmWasm/wasmd/x/wasm"
wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper"
wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types"
customstaking "github.com/classic-terra/core/v3/custom/staking"
customwasmkeeper "github.com/classic-terra/core/v3/custom/wasm/keeper"
terrawasm "github.com/classic-terra/core/v3/wasmbinding"

dyncommkeeper "github.com/classic-terra/core/v3/x/dyncomm/keeper"
dyncommtypes "github.com/classic-terra/core/v3/x/dyncomm/types"
marketkeeper "github.com/classic-terra/core/v3/x/market/keeper"
Expand Down Expand Up @@ -273,7 +273,7 @@ func NewAppKeepers(
// register the staking hooks
// NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks
appKeepers.StakingKeeper.SetHooks(
stakingtypes.NewMultiStakingHooks(appKeepers.DistrKeeper.Hooks(), appKeepers.SlashingKeeper.Hooks()),
stakingtypes.NewMultiStakingHooks(appKeepers.DistrKeeper.Hooks(), appKeepers.SlashingKeeper.Hooks(), customstaking.NewTerraStakingHooks(*appKeepers.StakingKeeper)),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

given the nature of the hook, it might make sense to put it first (unless you would merge it with the distrhooks anyway).

Copy link
Author

@kien6034 kien6034 Nov 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agree on this

)

// Create IBC Keeper
Expand Down
12 changes: 12 additions & 0 deletions cmd/terrad/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ import (
serverconfig "github.com/cosmos/cosmos-sdk/server/config"
)

const (
// DefaultIAVLCacheSize defines the number of iavl cache item, which is supposed to be 100MB size.
// Each cache item consumes 128 bytes, 64 bytes for the left sibling, and 64 bytes for the right sibling.
// The number of cache item is calculated as 100 MB = 10,000,000 / 128 = 781_250
DefaultIAVLCacheSize = 781_250
IavlDisablefastNodeDefault = true
)

// TerraAppConfig terra specify app config
type TerraAppConfig struct {
serverconfig.Config
Expand Down Expand Up @@ -52,6 +60,10 @@ func initAppConfig() (string, interface{}) {
// server config.
srvCfg := serverconfig.DefaultConfig()

// Override default config
srvCfg.IAVLCacheSize = DefaultIAVLCacheSize
srvCfg.IAVLDisableFastNode = IavlDisablefastNodeDefault

// The SDK's default minimum gas price is set to "" (empty value) inside
// app.toml. If left empty by validators, the node will halt on startup.
// However, the chain developer can set a default app.toml value for their
Expand Down
92 changes: 92 additions & 0 deletions custom/staking/hook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package staking

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am aware it is "clean" to create a full hook file. Given that only one function is used, would it make sense to create a simple hook file that inherits the distribution hooks file and in the function you alter first calls the inherited hook and then the additional code? This would remove one hook from the multihook list in the stakingkeeper.

Copy link

@StrathCole StrathCole Nov 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I meant like this:

type TerraStakingHooks struct {
    distrkeeper.Hooks
    sk stakingkeeper.Keeper
}

func NewTerraStakingHooks(sk stakingkeeper.Keeper, distrHooks distrkeeper.Hooks) *TerraStakingHooks {
    return &TerraStakingHooks{
        Hooks: distrHooks,
        sk:    sk,
    }
}

func (h TerraStakingHooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error {
    if err := h.Hooks.AfterDelegationModified(ctx, delAddr, valAddr); err != nil {
        return err
    }

    /* your code from the power check in here */
    return nil
}

And in the app when setting up the hooks something like:

appKeepers.StakingKeeper.SetHooks(
    stakingtypes.NewMultiStakingHooks(customstaking.NewTerraStakingHooks(appKeepers.StakingKeeper, appKeepers.DistrKeeper.Hooks()),  appKeepers.SlashingKeeper.Hooks()),
)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the distribution hooks is used for supporting rewards operation stuff, and the hook that i used already have the implementation. Imo, i think keeping it as the separate file though make the code looks "long", but will be cleaner and easier to maintain in the future

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My only thought was to remove the small overhead of calling all the hook functions that aren't used anyway. But it's nothing I would insist in.


import (
sdk "github.com/cosmos/cosmos-sdk/types"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

const (
ColumbusChainID = "columbus-5"
)

var _ stakingtypes.StakingHooks = &TerraStakingHooks{}

// TerraStakingHooks implements staking hooks to enforce validator power limit
type TerraStakingHooks struct {
sk stakingkeeper.Keeper
}

func NewTerraStakingHooks(sk stakingkeeper.Keeper) *TerraStakingHooks {
return &TerraStakingHooks{sk: sk}
}

// Implement required staking hooks interface methods
func (h TerraStakingHooks) BeforeDelegationCreated(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) error {
return nil
}

func (h TerraStakingHooks) BeforeDelegationSharesModified(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) error {
return nil
}

// Other required hook methods with empty implementations
func (h TerraStakingHooks) AfterDelegationModified(ctx sdk.Context, _ sdk.AccAddress, valAddr sdk.ValAddress) error {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it make sense to modify and put the logic into the "BeforeDelegationCreated" and "BeforeDelegationSharesModified" functions using a helper function? This would allow an early exit like the current fork change does. Or is there a good reason to rather do it after?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason why i don't use those hooks is because the hooks only provide us with this context (ctx sdk.Context, _ sdk.AccAddress, valAddr sdk.ValAddress), which is not-sufficient to perform the pre-check behavior like in the current forks. (we need the types.Msg... to get the required information)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the clarification.

if ctx.ChainID() != ColumbusChainID {
return nil
}

validator, found := h.sk.GetValidator(ctx, valAddr)
if !found {
return nil
}

// Get validator's current power (after delegation modified)
validatorPower := sdk.TokensToConsensusPower(validator.Tokens, h.sk.PowerReduction(ctx))

// Get the total power of the validator set
totalPower := h.sk.GetLastTotalPower(ctx)

// Get validator delegation percent
validatorDelegationPercent := sdk.NewDec(validatorPower).QuoInt64(totalPower.Int64())

if validatorDelegationPercent.GT(sdk.NewDecWithPrec(20, 2)) {
panic("validator power is over the allowed limit")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to use a normal error instead of a panic here? I am not 100% sure why a panic was used in the original code, maybe you can clarify on that although you didn't write it.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if subtractAccount {
		if tokenSrc == types.Bonded {
			panic("delegation token source cannot be bonded")
		}

		var sendName string

		switch {
		case validator.IsBonded():
			sendName = types.BondedPoolName
		case validator.IsUnbonding(), validator.IsUnbonded():
			sendName = types.NotBondedPoolName
		default:
			panic("invalid validator status")
		}

i think it align with the current checks logic. I think we should keep it as it is, but lets me find out if it is better to return err here

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you also need to handle the event of creating a new validator?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@StrathCole the hook AfterDelegationModified is already embedded in the internal keeper.Delegate function, which is called by the CreateValidator function

}

return nil
}

func (h TerraStakingHooks) BeforeValidatorSlashed(_ sdk.Context, _ sdk.ValAddress, _ sdk.Dec) error {
return nil
}

func (h TerraStakingHooks) BeforeValidatorModified(_ sdk.Context, _ sdk.ValAddress) error {
return nil
}

func (h TerraStakingHooks) AfterValidatorBonded(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) error {
return nil
}

func (h TerraStakingHooks) AfterValidatorBeginUnbonding(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) error {
return nil
}

func (h TerraStakingHooks) AfterValidatorRemoved(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) error {
return nil
}

func (h TerraStakingHooks) AfterUnbondingInitiated(_ sdk.Context, _ uint64) error {
return nil
}

// Add this method to TerraStakingHooks
func (h TerraStakingHooks) AfterValidatorCreated(_ sdk.Context, _ sdk.ValAddress) error {
return nil
}

// Add the missing method
func (h TerraStakingHooks) BeforeDelegationRemoved(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) error {
return nil
}
50 changes: 50 additions & 0 deletions server/middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package server

import (
"net/http"
"strconv"

"github.com/cosmos/cosmos-sdk/codec/legacy"
grpctypes "github.com/cosmos/cosmos-sdk/types/grpc"
)

// BlockHeightMiddleware parses height query parameter and sets GRPCBlockHeightHeader
func BlockHeightMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
heightStr := r.FormValue("height")
if heightStr != "" {
height, err := strconv.ParseInt(heightStr, 10, 64)
if err != nil {
writeErrorResponse(w, http.StatusBadRequest, "syntax error")
return
}

if height < 0 {
writeErrorResponse(w, http.StatusBadRequest, "height must be equal or greater than zero")
return
}

if height > 0 {
r.Header.Set(grpctypes.GRPCBlockHeightHeader, heightStr)
}
}

next.ServeHTTP(w, r)
})
}

// writeErrorResponse prepares and writes an HTTP error
func writeErrorResponse(w http.ResponseWriter, status int, err string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, _ = w.Write(legacy.Cdc.MustMarshalJSON(newErrorResponse(0, err)))
}

type errorResponse struct {
Code int `json:"code,omitempty"`
Error string `json:"error"`
}

func newErrorResponse(code int, err string) errorResponse {
return errorResponse{Code: code, Error: err}
}