Skip to content

Commit

Permalink
wip: pairing
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonathansumner committed May 26, 2023
1 parent 487cff7 commit db28752
Show file tree
Hide file tree
Showing 18 changed files with 133 additions and 33 deletions.
2 changes: 2 additions & 0 deletions baseapp/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ 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())

fmt.Println("abci.go - 63")
res = app.initChainer(app.deliverState.ctx, req)
fmt.Println("abci.go - 65")

// sanity check
if len(req.Validators) > 0 {
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,7 @@ github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEW
github.com/golang/snappy v0.0.3-0.20201103224600-674baa8c7fc3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.3 h1:fHPg5GQYlCeLIPB9BZqMVR5nR9A+IM5zcgeTdjMYmLA=
github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golangci/golangci-lint v1.48.0 h1:hRiBNk9iRqdAKMa06ntfEiLyza1/3IE9rHLNJaek4a8=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo=
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
Expand Down
5 changes: 5 additions & 0 deletions proto/cosmos/staking/v1beta1/staking.proto
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,11 @@ message Params {
uint32 historical_entries = 4 [(gogoproto.moretags) = "yaml:\"historical_entries\""];
// bond_denom defines the bondable coin denomination.
string bond_denom = 5 [(gogoproto.moretags) = "yaml:\"bond_denom\""];
// string min_commission_rate = 200 [
// (gogoproto.moretags) = "yaml:\"min_commission_rate\"",
// (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec",
// (gogoproto.nullable) = true
// ];
}

// DelegationResponse is equivalent to Delegation except that it contains a
Expand Down
2 changes: 2 additions & 0 deletions simapp/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package simapp

import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
Expand Down Expand Up @@ -440,6 +441,7 @@ func (app *SimApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.
panic(err)
}
app.UpgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap())
fmt.Println("app.go - 74")
return app.mm.InitGenesis(ctx, app.appCodec, genesisState)
}

Expand Down
1 change: 0 additions & 1 deletion simapp/sim_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,6 @@ func TestAppStateDeterminism(t *testing.T) {
} else {
logger = log.NewNopLogger()
}

db := dbm.NewMemDB()
app := NewSimApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, FlagPeriodValue, MakeTestEncodingConfig(), EmptyAppOptions{}, interBlockCacheOpt())

Expand Down
2 changes: 2 additions & 0 deletions types/errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@ var (
// ErrPanic is only set when we recover from a panic, so we know to
// redact potentially sensitive system info
ErrPanic = Register(UndefinedCodespace, 111222, "panic")

ErrInvalidCommission = Register(RootCodespace, 41, "invalid commission rate")
)

// Register returns an error instance that should be used as the base for
Expand Down
2 changes: 2 additions & 0 deletions types/module/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -324,8 +324,10 @@ func (m *Manager) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, genesisData
continue
}

fmt.Println("module.go - 327")
moduleValUpdates := m.Modules[moduleName].InitGenesis(ctx, cdc, genesisData[moduleName])

fmt.Println("module.go - 330")
// use these validator updates if provided, the module manager assumes
// only one module will update the validator set
if len(moduleValUpdates) > 0 {
Expand Down
4 changes: 4 additions & 0 deletions x/params/types/subspace.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,15 +236,19 @@ func (s Subspace) GetParamSetIfExists(ctx sdk.Context, ps ParamSet) {
// corresponding parameter key in the Subspace's KVStore.
func (s Subspace) SetParamSet(ctx sdk.Context, ps ParamSet) {
for _, pair := range ps.ParamSetPairs() {
fmt.Println(pair.Key)
// pair.Field is a pointer to the field, so indirecting the ptr.
// go-amino automatically handles it but just for sure,
// since SetStruct is meant to be used in InitGenesis
// so this method will not be called frequently
fmt.Println("subspace.go - 243")
v := reflect.Indirect(reflect.ValueOf(pair.Value)).Interface()
fmt.Println("subspace.go - 245")

if err := pair.ValidatorFn(v); err != nil {
panic(fmt.Sprintf("value from ParamSetPair is invalid: %s", err))
}
fmt.Println("subspace.go - 250")

s.Set(ctx, pair.Key, v)
}
Expand Down
5 changes: 5 additions & 0 deletions x/simulation/simulate.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ func initChain(
ConsensusParams: consensusParams,
Time: genesisTimestamp,
}
fmt.Println("simulate.go - 42")
res := app.InitChain(req)
fmt.Println("simulate.go - 44")
validators := newMockValidators(r, res.Validators, params)

return validators, genesisTimestamp, accounts, chainID
Expand Down Expand Up @@ -67,16 +69,19 @@ func SimulateFromSeed(
params := RandomParams(r)
fmt.Fprintf(w, "Randomized simulation params: \n%s\n", mustMarshalJSONIndent(params))

fmt.Println("simulate.go - 70")
timeDiff := maxTimePerBlock - minTimePerBlock
accs := randAccFn(r, params.NumKeys())
eventStats := NewEventStats()
fmt.Println("simulate.go - 74")

// Second variable to keep pending validator set (delayed one block since
// TM 0.24) Initially this is the same as the initial validator set
validators, genesisTimestamp, accs, chainID := initChain(r, params, accs, app, appStateFn, config, cdc)
if len(accs) == 0 {
return true, params, fmt.Errorf("must have greater than zero genesis accounts")
}
fmt.Println("simulate.go - 82")

config.ChainID = chainID

Expand Down
17 changes: 17 additions & 0 deletions x/staking/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,11 @@ func InitGenesis(
// genesis.json are in block 0.
ctx = ctx.WithBlockHeight(1 - sdk.ValidatorUpdateDelay)

fmt.Println("staking/genesis.go - 35")
keeper.SetParams(ctx, data.Params)
fmt.Println("staking/genesis.go - 37")
keeper.SetLastTotalPower(ctx, data.LastTotalPower)
fmt.Println("staking/genesis.go - 39")

for _, validator := range data.Validators {
keeper.SetValidator(ctx, validator)
Expand Down Expand Up @@ -61,6 +64,7 @@ func InitGenesis(
panic("invalid validator status")
}
}
fmt.Println("staking/genesis.go - 67")

for _, delegation := range data.Delegations {
delegatorAddress := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress)
Expand All @@ -76,6 +80,7 @@ func InitGenesis(
keeper.AfterDelegationModified(ctx, delegatorAddress, delegation.GetValidatorAddr())
}
}
fmt.Println("staking/genesis.go - 83")

for _, ubd := range data.UnbondingDelegations {
keeper.SetUnbondingDelegation(ctx, ubd)
Expand All @@ -85,6 +90,7 @@ func InitGenesis(
notBondedTokens = notBondedTokens.Add(entry.Balance)
}
}
fmt.Println("staking/genesis.go - 93")

for _, red := range data.Redelegations {
keeper.SetRedelegation(ctx, red)
Expand All @@ -93,10 +99,12 @@ func InitGenesis(
keeper.InsertRedelegationQueue(ctx, red, entry.CompletionTime)
}
}
fmt.Println("staking/genesis.go - 102")

bondedCoins := sdk.NewCoins(sdk.NewCoin(data.Params.BondDenom, bondedTokens))
notBondedCoins := sdk.NewCoins(sdk.NewCoin(data.Params.BondDenom, notBondedTokens))

fmt.Println("staking/genesis.go - 107")
// check if the unbonded and bonded pools accounts exists
bondedPool := keeper.GetBondedPool(ctx)
if bondedPool == nil {
Expand All @@ -107,6 +115,7 @@ func InitGenesis(
if bondedBalance.IsZero() {
accountKeeper.SetModuleAccount(ctx, bondedPool)
}
fmt.Println("staking/genesis.go - 118")
// if balance is different from bonded coins panic because genesis is most likely malformed
if !bondedBalance.IsEqual(bondedCoins) {
panic(fmt.Sprintf("bonded pool balance is different from bonded coins: %s <-> %s", bondedBalance, bondedCoins))
Expand All @@ -116,6 +125,7 @@ func InitGenesis(
panic(fmt.Sprintf("%s module account has not been set", types.NotBondedPoolName))
}

fmt.Println("staking/genesis.go - 128")
notBondedBalance := bankKeeper.GetAllBalances(ctx, notBondedPool.GetAddress())
if notBondedBalance.IsZero() {
accountKeeper.SetModuleAccount(ctx, notBondedPool)
Expand All @@ -124,8 +134,11 @@ func InitGenesis(
if !notBondedBalance.IsEqual(notBondedCoins) {
panic(fmt.Sprintf("not bonded pool balance is different from not bonded coins: %s <-> %s", notBondedBalance, notBondedCoins))
}
fmt.Println("staking/genesis.go - 137")
fmt.Println(data.Exported)
// don't need to run Tendermint updates if we exported
if data.Exported {
fmt.Println("staking/genesis.go - 140")
for _, lv := range data.LastValidatorPowers {
valAddr, err := sdk.ValAddressFromBech32(lv.Address)
if err != nil {
Expand All @@ -143,12 +156,16 @@ func InitGenesis(
res = append(res, update)
}
} else {
fmt.Println("staking/genesis.go - 158")
var err error
fmt.Println("staking/genesis.go - 160")
res, err = keeper.ApplyAndReturnValidatorSetUpdates(ctx)
fmt.Println("staking/genesis.go - 162")
if err != nil {
log.Fatal(err)
}
}
fmt.Println("staking/genesis.go - 167")

return res
}
Expand Down
14 changes: 14 additions & 0 deletions x/staking/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ func (k msgServer) CreateValidator(goCtx context.Context, msg *types.MsgCreateVa
return nil, err
}

minRate := k.MinCommissionRate(ctx)
if minRate.GT(sdk.ZeroDec()) {
if msg.Commission.Rate.LT(*minRate) { // check to see if commission rate is less than minimum
return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidCommission, "Commission observed less than minimum, "+k.MinCommissionRate(ctx).String())
}
}

// check to see if the pubkey or sender has been registered before
if _, found := k.GetValidator(ctx, valAddr); found {
return nil, types.ErrValidatorOwnerExists
Expand Down Expand Up @@ -144,6 +151,13 @@ func (k msgServer) EditValidator(goCtx context.Context, msg *types.MsgEditValida
validator.Description = description

if msg.CommissionRate != nil {

minRate := k.MinCommissionRate(ctx)
if minRate.GT(sdk.ZeroDec()) {
if msg.CommissionRate.LT(*minRate) { // check to see if commission rate is less than minimum
return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidCommission, "Commission observed less than minimum, "+k.MinCommissionRate(ctx).String())
}
}
commission, err := k.UpdateValidatorCommission(ctx, validator, *msg.CommissionRate)
if err != nil {
return nil, err
Expand Down
8 changes: 8 additions & 0 deletions x/staking/keeper/params.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package keeper

import (
"fmt"
"time"

sdk "github.com/cosmos/cosmos-sdk/types"
Expand Down Expand Up @@ -39,6 +40,12 @@ func (k Keeper) BondDenom(ctx sdk.Context) (res string) {
return
}

func (k Keeper) MinCommissionRate(ctx sdk.Context) (res *sdk.Dec) {
fmt.Println(res)
k.paramstore.Get(ctx, types.KeyMinCommissionRate, res)
return
}

// PowerReduction - is the amount of staking tokens required for 1 unit of consensus-engine power.
// Currently, this returns a global variable that the app developer can tweak.
// TODO: we might turn this into an on-chain param:
Expand All @@ -55,6 +62,7 @@ func (k Keeper) GetParams(ctx sdk.Context) types.Params {
k.MaxEntries(ctx),
k.HistoricalEntries(ctx),
k.BondDenom(ctx),
k.MinCommissionRate(ctx),
)
}

Expand Down
7 changes: 6 additions & 1 deletion x/staking/keeper/val_state_change.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,15 +115,20 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab
// Retrieve the last validator set.
// The persistent set is updated later in this function.
// (see LastValidatorPowerKey).

fmt.Println("val_state_change.go - 119")
last, err := k.getLastValidatorsByAddr(ctx)
if err != nil {
return nil, err
}

fmt.Println("val_state_change.go - 125")

// Iterate over validators, highest power to lowest.
iterator := k.ValidatorsPowerStoreIterator(ctx)
defer iterator.Close()

fmt.Println("val_state_change.go - 130")
defer iterator.Close()
for count := 0; iterator.Valid() && count < int(maxValidators); iterator.Next() {
// everything that is iterated in this loop is becoming or already a
// part of the bonded validator set
Expand Down
2 changes: 1 addition & 1 deletion x/staking/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.
var genesisState types.GenesisState

cdc.MustUnmarshalJSON(data, &genesisState)

fmt.Println("staking/module.go - 152")
return InitGenesis(ctx, am.keeper, am.accountKeeper, am.bankKeeper, &genesisState)
}

Expand Down
9 changes: 8 additions & 1 deletion x/staking/simulation/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ func RandomizedGenState(simState *module.SimulationState) {
// NOTE: the slashing module need to be defined after the staking module on the
// NewSimulationManager constructor for this to work
simState.UnbondTime = unbondTime
params := types.NewParams(simState.UnbondTime, maxVals, 7, histEntries, sdk.DefaultBondDenom)
minCommission := sdk.NewDec(1)
params := types.NewParams(simState.UnbondTime, maxVals, 7, histEntries, sdk.DefaultBondDenom, &minCommission)

// validators & delegations
var (
Expand All @@ -72,6 +73,7 @@ func RandomizedGenState(simState *module.SimulationState) {
)

valAddrs := make([]sdk.ValAddress, simState.NumBonded)
fmt.Println("genesis.go - 76")

for i := 0; i < int(simState.NumBonded); i++ {
valAddr := sdk.ValAddress(simState.Accounts[i].Address)
Expand All @@ -97,13 +99,18 @@ func RandomizedGenState(simState *module.SimulationState) {
validators = append(validators, validator)
delegations = append(delegations, delegation)
}
fmt.Println("genesis.go - 102")

stakingGenesis := types.NewGenesisState(params, validators, delegations)
fmt.Println("genesis.go - 105")

bz, err := json.MarshalIndent(&stakingGenesis.Params, "", " ")
fmt.Println("genesis.go - 108")
if err != nil {
panic(err)
}
fmt.Printf("Selected randomly generated staking parameters:\n%s\n", bz)
fmt.Println("genesis.go - 113")
simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(stakingGenesis)
fmt.Println("genesis.go - 115")
}
Loading

0 comments on commit db28752

Please sign in to comment.