diff --git a/CHANGELOG.md b/CHANGELOG.md index 3662b7b19233..87d7082312b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -134,7 +134,7 @@ BREAKING CHANGES * [\#2019](https://github.com/cosmos/cosmos-sdk/issues/2019) Cap total number of signatures. Current per-transaction limit is 7, and if that is exceeded transaction is rejected. * [\#2801](https://github.com/cosmos/cosmos-sdk/pull/2801) Remove AppInit structure. * [\#2798](https://github.com/cosmos/cosmos-sdk/issues/2798) Governance API has miss-spelled English word in JSON response ('depositer' -> 'depositor') - * [\#2943](https://github.com/cosmos/cosmos-sdk/pull/2943) Transaction action tags equal the message type. Stake EndBlocker tags are included. + * [\#2943](https://github.com/cosmos/cosmos-sdk/pull/2943) Transaction action tags equal the message type. Staking EndBlocker tags are included. * Tendermint * Update to Tendermint 0.27.0 @@ -1062,7 +1062,7 @@ BREAKING CHANGES * All module keepers now require a codespace, see basecoin or democoin for usage * Many changes to names throughout * Type as a prefix naming convention applied (ex. BondMsg -> MsgBond) - * Removed redundancy in names (ex. stake.StakeKeeper -> stake.Keeper) + * Removed redundancy in names (ex. stake.StakingKeeper -> stake.Keeper) * Removed SealedAccountMapper * gaiad init now requires use of `--name` flag * Removed Get from Msg interface diff --git a/Gopkg.lock b/Gopkg.lock index c6090bf2799d..1f46f7fd0648 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -452,11 +452,12 @@ version = "v0.12.0" [[projects]] - digest = "1:f94f468c7cd1fc3693ebc16011f26ec26538761cdcd182b3a28faa649a7d55e2" + digest = "1:cf5ca19b425df58000f12801db22c1c50840be194640d7b612312e4beffb0ff7" name = "github.com/tendermint/tendermint" packages = [ "abci/client", "abci/example/code", + "abci/example/counter", "abci/example/kvstore", "abci/server", "abci/types", @@ -517,7 +518,7 @@ "version", ] pruneopts = "UT" - revision = "v0.27.3" + revision = "v0.28.0-dev0" [[projects]] digest = "1:a7485b2a69f996923f9d3406a9a853fd8eb31818515e985a830d71f88f6a925b" diff --git a/Gopkg.toml b/Gopkg.toml index d730f62a1405..2b57eea073bf 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -40,7 +40,7 @@ [[override]] name = "github.com/tendermint/tendermint" - revision = "v0.27.3" + revision = "v0.28.0-dev0" [[constraint]] name = "github.com/zondax/ledger-cosmos-go" diff --git a/PENDING.md b/PENDING.md index 577ba6d14c4f..e8b191617f26 100644 --- a/PENDING.md +++ b/PENDING.md @@ -3,7 +3,9 @@ BREAKING CHANGES * Gaia REST API (`gaiacli advanced rest-server`) - * [gaia-lite] [\#2182] Renamed and merged all redelegations endpoints into `/stake/redelegations` + * [gaia-lite] [\#2182] Renamed and merged all redelegations endpoints into `/staking/redelegations` + * [\#3176](https://github.com/cosmos/cosmos-sdk/issues/3176) `tx/sign` endpoint now expects `BaseReq` fields as nested object. + * [\#2222] all endpoints renamed from `/stake` -> `/staking` * Gaia CLI (`gaiacli`) * [\#810](https://github.com/cosmos/cosmos-sdk/issues/810) Don't fallback to any default values for chain ID. @@ -11,21 +13,25 @@ BREAKING CHANGES * Change `chain_id` and `trust_node` in `gaiacli` configuration to `chain-id` and `trust-node` respectively. * [\#3069](https://github.com/cosmos/cosmos-sdk/pull/3069) `--fee` flag renamed to `--fees` to support multiple coins * [\#3156](https://github.com/cosmos/cosmos-sdk/pull/3156) Remove unimplemented `gaiacli init` command + * [\#2222] `gaiacli tx stake` -> `gaiacli tx staking`, `gaiacli query stake` -> `gaiacli query staking` * Gaia * https://github.com/cosmos/cosmos-sdk/issues/2838 - Move store keys to constants * [\#3162](https://github.com/cosmos/cosmos-sdk/issues/3162) The `--gas` flag now takes `auto` instead of `simulate` in order to trigger a simulation of the tx before the actual execution. -* Gaia REST API - * [\#3176](https://github.com/cosmos/cosmos-sdk/issues/3176) `tx/sign` endpoint now expects `BaseReq` fields as nested object. * SDK - * [stake] \#2513 Validator power type from Dec -> Int + * [staking] \#2513 Validator power type from Dec -> Int + * [staking] \#3233 key and value now contain duplicate fields to simplify code * [\#3064](https://github.com/cosmos/cosmos-sdk/issues/3064) Sanitize `sdk.Coin` denom. Coins denoms are now case insensitive, i.e. 100fooToken equals to 100FOOTOKEN. - + * [\#3195](https://github.com/cosmos/cosmos-sdk/issues/3195) Allows custom configuration for syncable strategy + * [\#3242](https://github.com/cosmos/cosmos-sdk/issues/3242) Fix infinite gas + meter utilization during aborted ante handler executions. + * [\#2222] [x/staking] `/stake` -> `/staking` module rename + * Tendermint - + * \#3279 Upgrade to Tendermint 0.28.0-dev0 FEATURES @@ -42,7 +48,7 @@ FEATURES `query gov proposer [proposal-id]` to query for a proposal's proposer. * Gaia - * [\#2182] [x/stake] Added querier for querying a single redelegation + * [\#2182] [x/staking] Added querier for querying a single redelegation * SDK * \#2996 Update the `AccountKeeper` to contain params used in the context of @@ -60,12 +66,14 @@ IMPROVEMENTS * [\#2948](https://github.com/cosmos/cosmos-sdk/issues/2948) Swagger UI now makes requests to light client node * Gaia CLI (`gaiacli`) + * [\#3224](https://github.com/cosmos/cosmos-sdk/pull/3224) Support adding offline public keys to the keystore * Gaia * [\#2186](https://github.com/cosmos/cosmos-sdk/issues/2186) Add Address Interface * [\#3158](https://github.com/cosmos/cosmos-sdk/pull/3158) Validate slashing genesis - * [\#3172](https://github.com/cosmos/cosmos-sdk/pull/3172) Support minimum fees - in a local testnet. + * [\#3172](https://github.com/cosmos/cosmos-sdk/pull/3172) Support minimum fees in a local testnet. + * [\#3250](https://github.com/cosmos/cosmos-sdk/pull/3250) Refactor integration tests and increase coverage + * [\#2859](https://github.com/cosmos/cosmos-sdk/issues/2859) Rename `TallyResult` in gov proposals to `FinalTallyResult` * SDK * [\#3137](https://github.com/cosmos/cosmos-sdk/pull/3137) Add tag documentation @@ -78,7 +86,7 @@ IMPROVEMENTS * CI * \#2498 Added macos CI job to CircleCI - * [#142](https://github.com/tendermint/devops/issues/142) Increased the number of blocks to be tested during multi-sim + * [#142](https://github.com/tendermint/devops/issues/142) Increased the number of blocks to be tested during multi-sim BUG FIXES @@ -86,12 +94,13 @@ BUG FIXES * Gaia CLI (`gaiacli`) * \#3141 Fix the bug in GetAccount when `len(res) == 0` and `err == nil` - + * Gaia * \#3148 Fix `gaiad export` by adding a boolean to `NewGaiaApp` determining whether or not to load the latest version * \#3181 Correctly reset total accum update height and jailed-validator bond height / unbonding height on export-for-zero-height * [\#3172](https://github.com/cosmos/cosmos-sdk/pull/3172) Fix parsing `gaiad.toml` when it already exists. + * \#3223 Fix unset governance proposal queues when importing state from old chain * [#3187](https://github.com/cosmos/cosmos-sdk/issues/3187) Fix `gaiad export` by resetting each validator's slashing period. diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 19944ced2f46..509493443422 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -503,6 +503,7 @@ func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeg } else { gasMeter = sdk.NewInfiniteGasMeter() } + app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(gasMeter) if app.beginBlocker != nil { @@ -732,7 +733,10 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk defer func() { if mode == runTxModeDeliver { ctx.BlockGasMeter().ConsumeGas( - ctx.GasMeter().GasConsumedToLimit(), "block gas meter") + ctx.GasMeter().GasConsumedToLimit(), + "block gas meter", + ) + if ctx.BlockGasMeter().GasConsumed() < startingGas { panic(sdk.ErrorGasOverflow{"tx gas summation"}) } @@ -751,23 +755,29 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk // Cache wrap context before anteHandler call in case it aborts. // This is required for both CheckTx and DeliverTx. - // https://github.com/cosmos/cosmos-sdk/issues/2772 + // Ref: https://github.com/cosmos/cosmos-sdk/issues/2772 + // // NOTE: Alternatively, we could require that anteHandler ensures that // writes do not happen if aborted/failed. This may have some // performance benefits, but it'll be more difficult to get right. anteCtx, msCache = app.cacheTxContext(ctx, txBytes) newCtx, result, abort := app.anteHandler(anteCtx, tx, (mode == runTxModeSimulate)) - if abort { - return result - } if !newCtx.IsZero() { - // At this point, newCtx.MultiStore() is cache wrapped, - // or something else replaced by anteHandler. - // We want the original ms, not one which was cache-wrapped - // for the ante handler. + // At this point, newCtx.MultiStore() is cache-wrapped, or something else + // replaced by the ante handler. We want the original multistore, not one + // which was cache-wrapped for the ante handler. + // + // Also, in the case of the tx aborting, we need to track gas consumed via + // the instantiated gas meter in the ante handler, so we update the context + // prior to returning. ctx = newCtx.WithMultiStore(ms) } + + if abort { + return result + } + msCache.Write() gasWanted = result.GasWanted } diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 8bde78585d10..d088b841fc45 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/binary" "fmt" + "github.com/cosmos/cosmos-sdk/store" "os" "testing" @@ -85,9 +86,10 @@ func TestMountStores(t *testing.T) { // Test that LoadLatestVersion actually does. func TestLoadVersion(t *testing.T) { logger := defaultLogger() + pruningOpt := SetPruning(store.PruneSyncable) db := dbm.NewMemDB() name := t.Name() - app := NewBaseApp(name, logger, db, nil) + app := NewBaseApp(name, logger, db, nil, pruningOpt) // make a cap key and mount the store capKey := sdk.NewKVStoreKey(MainStoreKey) @@ -116,7 +118,7 @@ func TestLoadVersion(t *testing.T) { commitID2 := sdk.CommitID{2, res.Data} // reload with LoadLatestVersion - app = NewBaseApp(name, logger, db, nil) + app = NewBaseApp(name, logger, db, nil, pruningOpt) app.MountStores(capKey) err = app.LoadLatestVersion(capKey) require.Nil(t, err) @@ -124,7 +126,7 @@ func TestLoadVersion(t *testing.T) { // reload with LoadVersion, see if you can commit the same block and get // the same result - app = NewBaseApp(name, logger, db, nil) + app = NewBaseApp(name, logger, db, nil, pruningOpt) app.MountStores(capKey) err = app.LoadVersion(1, capKey) require.Nil(t, err) diff --git a/baseapp/options.go b/baseapp/options.go index 9ec9db023897..8729e5ac1287 100644 --- a/baseapp/options.go +++ b/baseapp/options.go @@ -14,21 +14,8 @@ import ( // for options that need access to non-exported fields of the BaseApp // SetPruning sets a pruning option on the multistore associated with the app -func SetPruning(pruning string) func(*BaseApp) { - var pruningEnum sdk.PruningStrategy - switch pruning { - case "nothing": - pruningEnum = sdk.PruneNothing - case "everything": - pruningEnum = sdk.PruneEverything - case "syncable": - pruningEnum = sdk.PruneSyncable - default: - panic(fmt.Sprintf("invalid pruning strategy: %s", pruning)) - } - return func(bap *BaseApp) { - bap.cms.SetPruning(pruningEnum) - } +func SetPruning(opts sdk.PruningOptions) func(*BaseApp) { + return func(bap *BaseApp) { bap.cms.SetPruning(opts) } } // SetMinimumFees returns an option that sets the minimum fees on the app. diff --git a/client/keys/add.go b/client/keys/add.go index 8c2f666d833e..2a0890fbe65d 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -18,9 +18,11 @@ import ( ccrypto "github.com/cosmos/cosmos-sdk/crypto" "github.com/cosmos/cosmos-sdk/crypto/keys" "github.com/cosmos/cosmos-sdk/crypto/keys/hd" + sdk "github.com/cosmos/cosmos-sdk/types" ) const ( + flagPublicKey = "pubkey" flagInteractive = "interactive" flagBIP44Path = "bip44-path" flagRecover = "recover" @@ -36,16 +38,18 @@ func addKeyCommand() *cobra.Command { Short: "Add an encrypted private key (either newly generated or recovered), encrypt it, and save to disk", Long: `Derive a new private key and encrypt to disk. Optionally specify a BIP39 mnemonic, a BIP39 passphrase to further secure the mnemonic, -and a bip32 HD path to derive a specific account. The key will be stored under the given name +and a bip32 HD path to derive a specific account. The key will be stored under the given name and encrypted with the given password. The only input that is required is the encryption password. If run with -i, it will prompt the user for BIP44 path, BIP39 mnemonic, and passphrase. The flag --recover allows one to recover a key from a seed passphrase. If run with --dry-run, a key would be generated (or recovered) but not stored to the local keystore. +Use the --pubkey flag to add arbitrary public keys to the keystore for constructing multisig transactions. `, Args: cobra.ExactArgs(1), RunE: runAddCmd, } + cmd.Flags().String(FlagPublicKey, "", "Store only a public key (useful for constructing multisigs e.g. cosmospub1...)") cmd.Flags().BoolP(flagInteractive, "i", false, "Interactively prompt user for BIP39 passphrase and mnemonic") cmd.Flags().Bool(client.FlagUseLedger, false, "Store a local reference to a private key on a Ledger device") cmd.Flags().String(flagBIP44Path, "44'/118'/0'/0/0", "BIP44 path from which to derive a private key") @@ -73,6 +77,9 @@ func runAddCmd(cmd *cobra.Command, args []string) error { buf := client.BufferStdin() name := args[0] + + interactive := viper.GetBool(flagInteractive) + if viper.GetBool(flagDryRun) { // we throw this away, so don't enforce args, // we want to get a new random seed phrase quickly @@ -94,7 +101,7 @@ func runAddCmd(cmd *cobra.Command, args []string) error { } // ask for a password when generating a local key - if !viper.GetBool(client.FlagUseLedger) { + if viper.GetString(flagPublicKey) == "" && !viper.GetBool(client.FlagUseLedger) { encryptPassword, err = client.GetCheckPassword( "Enter a passphrase to encrypt your key to disk:", "Repeat the passphrase:", buf) @@ -104,10 +111,16 @@ func runAddCmd(cmd *cobra.Command, args []string) error { } } - interactive := viper.GetBool(flagInteractive) - flags := cmd.Flags() - bipFlag := flags.Lookup(flagBIP44Path) + if viper.GetString(flagPublicKey) != "" { + pk, err := sdk.GetAccPubKeyBech32(viper.GetString(flagPublicKey)) + if err != nil { + return err + } + kb.CreateOffline(name, pk) + return nil + } + bipFlag := cmd.Flags().Lookup(flagBIP44Path) bip44Params, err := getBIP44ParamsAndPath(bipFlag.Value.String(), bipFlag.Changed || !interactive) if err != nil { return err diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 1a9cdf236664..bb099711fd4a 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -28,8 +28,8 @@ import ( authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/stake" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) const ( @@ -41,7 +41,7 @@ const ( altPw = "12345678901" ) -var fees = sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 5)} +var fees = sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 5)} func init() { mintkey.BcryptSecurityParameter = 1 @@ -176,14 +176,14 @@ func TestCoinSend(t *testing.T) { coins := acc.GetCoins() expectedBalance := initialBalance[0].Minus(fees[0]) - require.Equal(t, stakeTypes.DefaultBondDenom, coins[0].Denom) + require.Equal(t, stakingTypes.DefaultBondDenom, coins[0].Denom) require.Equal(t, expectedBalance.Amount.SubRaw(1), coins[0].Amount) expectedBalance = coins[0] // query receiver acc2 := getAccount(t, port, receiveAddr) coins2 := acc2.GetCoins() - require.Equal(t, stakeTypes.DefaultBondDenom, coins2[0].Denom) + require.Equal(t, stakingTypes.DefaultBondDenom, coins2[0].Denom) require.Equal(t, int64(1), coins2[0].Amount.Int64()) // test failure with too little gas @@ -217,7 +217,7 @@ func TestCoinSend(t *testing.T) { require.Nil(t, json.Unmarshal([]byte(body), &responseBody)) acc = getAccount(t, port, addr) - require.Equal(t, expectedBalance.Amount, acc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount, acc.GetCoins().AmountOf(stakingTypes.DefaultBondDenom)) res, body, _ = doTransferWithGas(t, port, seed, name1, memo, pw, addr, fmt.Sprintf("%d", responseBody.GasEstimate), 1.0, false, false, fees) @@ -232,7 +232,7 @@ func TestCoinSend(t *testing.T) { acc = getAccount(t, port, addr) expectedBalance = expectedBalance.Minus(fees[0]) - require.Equal(t, expectedBalance.Amount.SubRaw(1), acc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount.SubRaw(1), acc.GetCoins().AmountOf(stakingTypes.DefaultBondDenom)) } func TestCoinSendGenerateSignAndBroadcast(t *testing.T) { @@ -338,14 +338,14 @@ func TestPoolParamsQuery(t *testing.T) { cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) defer cleanup() - defaultParams := stake.DefaultParams() + defaultParams := staking.DefaultParams() - params := getStakeParams(t, port) + params := getStakingParams(t, port) require.True(t, defaultParams.Equal(params)) - pool := getStakePool(t, port) + pool := getStakingPool(t, port) - initialPool := stake.InitialPool() + initialPool := staking.InitialPool() initialPool.LooseTokens = initialPool.LooseTokens.Add(sdk.NewInt(100)) initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewInt(100)) // Delegate tx on GaiaAppGenState initialPool.LooseTokens = initialPool.LooseTokens.Add(sdk.NewInt(50)) // freeFermionsAcc = 50 on GaiaAppGenState @@ -418,7 +418,7 @@ func TestBonding(t *testing.T) { acc = getAccount(t, port, addr) coins := acc.GetCoins() expectedBalance := initialBalance[0].Minus(fees[0]) - require.Equal(t, expectedBalance.Amount.SubRaw(60), coins.AmountOf(stakeTypes.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount.SubRaw(60), coins.AmountOf(stakingTypes.DefaultBondDenom)) expectedBalance = coins[0] // query delegation @@ -453,8 +453,8 @@ func TestBonding(t *testing.T) { coins = acc.GetCoins() expectedBalance = expectedBalance.Minus(fees[0]) require.True(t, - expectedBalance.Amount.LT(coins.AmountOf(stakeTypes.DefaultBondDenom)) || - expectedBalance.Amount.Equal(coins.AmountOf(stakeTypes.DefaultBondDenom)), + expectedBalance.Amount.LT(coins.AmountOf(stakingTypes.DefaultBondDenom)) || + expectedBalance.Amount.Equal(coins.AmountOf(stakingTypes.DefaultBondDenom)), "should get tokens back from automatic withdrawal after an unbonding delegation", ) expectedBalance = coins[0] @@ -481,8 +481,8 @@ func TestBonding(t *testing.T) { acc = getAccount(t, port, addr) expectedBalance = expectedBalance.Minus(fees[0]) require.True(t, - expectedBalance.Amount.LT(coins.AmountOf(stakeTypes.DefaultBondDenom)) || - expectedBalance.Amount.Equal(coins.AmountOf(stakeTypes.DefaultBondDenom)), + expectedBalance.Amount.LT(coins.AmountOf(stakingTypes.DefaultBondDenom)) || + expectedBalance.Amount.Equal(coins.AmountOf(stakingTypes.DefaultBondDenom)), "should get tokens back from automatic withdrawal after an unbonding delegation", ) @@ -559,7 +559,7 @@ func TestSubmitProposal(t *testing.T) { // verify balance acc = getAccount(t, port, addr) expectedBalance := initialBalance[0].Minus(fees[0]) - require.Equal(t, expectedBalance.Amount.SubRaw(5), acc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount.SubRaw(5), acc.GetCoins().AmountOf(stakingTypes.DefaultBondDenom)) // query proposal proposal := getProposal(t, port, proposalID) @@ -593,7 +593,7 @@ func TestDeposit(t *testing.T) { acc = getAccount(t, port, addr) coins := acc.GetCoins() expectedBalance := initialBalance[0].Minus(fees[0]) - require.Equal(t, expectedBalance.Amount.SubRaw(5), coins.AmountOf(stakeTypes.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount.SubRaw(5), coins.AmountOf(stakingTypes.DefaultBondDenom)) expectedBalance = coins[0] // query proposal @@ -607,7 +607,7 @@ func TestDeposit(t *testing.T) { // verify balance after deposit and fee acc = getAccount(t, port, addr) expectedBalance = expectedBalance.Minus(fees[0]) - require.Equal(t, expectedBalance.Amount.SubRaw(5), acc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount.SubRaw(5), acc.GetCoins().AmountOf(stakingTypes.DefaultBondDenom)) // query tx txs := getTransactions(t, port, fmt.Sprintf("action=deposit&depositor=%s", addr)) @@ -616,11 +616,11 @@ func TestDeposit(t *testing.T) { // query proposal proposal = getProposal(t, port, proposalID) - require.True(t, proposal.GetTotalDeposit().IsEqual(sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 10)})) + require.True(t, proposal.GetTotalDeposit().IsEqual(sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 10)})) // query deposit deposit := getDeposit(t, port, proposalID, addr) - require.True(t, deposit.Amount.IsEqual(sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 10)})) + require.True(t, deposit.Amount.IsEqual(sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 10)})) } func TestVote(t *testing.T) { @@ -646,7 +646,7 @@ func TestVote(t *testing.T) { acc = getAccount(t, port, addr) coins := acc.GetCoins() expectedBalance := initialBalance[0].Minus(fees[0]) - require.Equal(t, expectedBalance.Amount.SubRaw(10), coins.AmountOf(stakeTypes.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount.SubRaw(10), coins.AmountOf(stakingTypes.DefaultBondDenom)) expectedBalance = coins[0] // query proposal @@ -662,7 +662,7 @@ func TestVote(t *testing.T) { acc = getAccount(t, port, addr) coins = acc.GetCoins() expectedBalance = expectedBalance.Minus(fees[0]) - require.Equal(t, expectedBalance.Amount, coins.AmountOf(stakeTypes.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount, coins.AmountOf(stakingTypes.DefaultBondDenom)) expectedBalance = coins[0] // query tx @@ -685,7 +685,7 @@ func TestVote(t *testing.T) { acc = getAccount(t, port, addr) coins = acc.GetCoins() expectedBalance = expectedBalance.Minus(fees[0]) - require.Equal(t, expectedBalance.Amount.SubRaw(60), coins.AmountOf(stakeTypes.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount.SubRaw(60), coins.AmountOf(stakingTypes.DefaultBondDenom)) expectedBalance = coins[0] tally = getTally(t, port, proposalID) @@ -698,7 +698,7 @@ func TestVote(t *testing.T) { // verify balance acc = getAccount(t, port, addr) expectedBalance = expectedBalance.Minus(fees[0]) - require.Equal(t, expectedBalance.Amount, acc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom)) + require.Equal(t, expectedBalance.Amount, acc.GetCoins().AmountOf(stakingTypes.DefaultBondDenom)) tally = getTally(t, port, proposalID) require.Equal(t, sdk.ZeroDec(), tally.Yes, "tally should be 0 the user changed the option") @@ -727,7 +727,7 @@ func TestProposalsQuery(t *testing.T) { defer cleanup() depositParam := getDepositParam(t, port) - halfMinDeposit := depositParam.MinDeposit.AmountOf(stakeTypes.DefaultBondDenom).Int64() / 2 + halfMinDeposit := depositParam.MinDeposit.AmountOf(stakingTypes.DefaultBondDenom).Int64() / 2 getVotingParam(t, port) getTallyingParam(t, port) diff --git a/client/lcd/swagger-ui/swagger.yaml b/client/lcd/swagger-ui/swagger.yaml index 8257854f9395..a52f80c8be8d 100644 --- a/client/lcd/swagger-ui/swagger.yaml +++ b/client/lcd/swagger-ui/swagger.yaml @@ -18,12 +18,12 @@ tags: - name: ICS23 description: Slashing module APIs - name: ICS24 - description: Fee distribution module APIs + description: WIP - Fee distribution module APIs - name: version description: Query app version schemes: - https -host: fabo.interblock.io:26657 +host: fabo.interblock.io:1317 securityDefinitions: kms: type: basic @@ -611,7 +611,7 @@ paths: description: No content about this account address 500: description: Server internel error - /stake/delegators/{delegatorAddr}/delegations: + /staking/delegators/{delegatorAddr}/delegations: parameters: - in: path name: delegatorAddr @@ -669,7 +669,7 @@ paths: description: Key password is wrong 500: description: Internal Server Error - /stake/delegators/{delegatorAddr}/delegations/{validatorAddr}: + /staking/delegators/{delegatorAddr}/delegations/{validatorAddr}: parameters: - in: path name: delegatorAddr @@ -696,7 +696,7 @@ paths: description: Invalid delegator address or validator address 500: description: Internal Server Error - /stake/delegators/{delegatorAddr}/unbonding_delegations: + /staking/delegators/{delegatorAddr}/unbonding_delegations: parameters: - in: path name: delegatorAddr @@ -765,7 +765,7 @@ paths: description: Key password is wrong 500: description: Internal Server Error - /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}: + /staking/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}: parameters: - in: path name: delegatorAddr @@ -794,23 +794,23 @@ paths: description: Invalid delegator address or validator address 500: description: Internal Server Error - /stake/redelegations: + /staking/redelegations: parameters: - in: query - name: delegator - description: Bech32 AccAddress of Delegator - required: false - type: string + name: delegator + description: Bech32 AccAddress of Delegator + required: false + type: string - in: query - name: validator_from - description: Bech32 ValAddress of SrcValidator - required: false - type: string + name: validator_from + description: Bech32 ValAddress of SrcValidator + required: false + type: string - in: query - name: validator_to - description: Bech32 ValAddress of DstValidator - required: false - type: string + name: validator_to + description: Bech32 ValAddress of DstValidator + required: false + type: string get: summary: Get all redelegations (filter by query params) tags: @@ -826,7 +826,7 @@ paths: $ref: "#/definitions/Redelegation" 500: description: Internal Server Error - /stake/delegators/{delegatorAddr}/redelegations: + /staking/delegators/{delegatorAddr}/redelegations: parameters: - in: path name: delegatorAddr @@ -880,7 +880,7 @@ paths: description: Key password is wrong 500: description: Internal Server Error - /stake/delegators/{delegatorAddr}/validators: + /staking/delegators/{delegatorAddr}/validators: parameters: - in: path name: delegatorAddr @@ -904,7 +904,7 @@ paths: description: Invalid delegator address 500: description: Internal Server Error - /stake/delegators/{delegatorAddr}/validators/{validatorAddr}: + /staking/delegators/{delegatorAddr}/validators/{validatorAddr}: parameters: - in: path name: delegatorAddr @@ -931,7 +931,7 @@ paths: description: Invalid delegator address or validator address 500: description: Internal Server Error - /stake/delegators/{delegatorAddr}/txs: + /staking/delegators/{delegatorAddr}/txs: parameters: - in: path name: delegatorAddr @@ -957,7 +957,7 @@ paths: description: Invalid delegator address 500: description: Internal Server Error - /stake/validators: + /staking/validators: get: summary: Get all validator candidates tags: @@ -973,7 +973,7 @@ paths: $ref: "#/definitions/Validator" 500: description: Internal Server Error - /stake/validators/{validatorAddr}: + /staking/validators/{validatorAddr}: parameters: - in: path name: validatorAddr @@ -995,7 +995,7 @@ paths: description: Invalid validator address 500: description: Internal Server Error - /stake/validators/{validatorAddr}/delegations: + /staking/validators/{validatorAddr}/delegations: parameters: - in: path name: validatorAddr @@ -1019,7 +1019,7 @@ paths: description: Invalid validator address 500: description: Internal Server Error - /stake/validators/{validatorAddr}/unbonding_delegations: + /staking/validators/{validatorAddr}/unbonding_delegations: parameters: - in: path name: validatorAddr @@ -1043,7 +1043,7 @@ paths: description: Invalid validator address 500: description: Internal Server Error - /stake/pool: + /staking/pool: get: summary: Get the current state of the staking pool tags: @@ -1070,7 +1070,7 @@ paths: type: string 500: description: Internal Server Error - /stake/parameters: + /staking/parameters: get: summary: Get the current staking parameter values tags: @@ -2271,7 +2271,7 @@ definitions: type: string proposal_status: type: string - tally_result: + final_tally_result: $ref: "#/definitions/TallyResult" submit_time: type: string diff --git a/client/lcd/test_helpers.go b/client/lcd/test_helpers.go index 436b9d680134..428989ffdd83 100644 --- a/client/lcd/test_helpers.go +++ b/client/lcd/test_helpers.go @@ -22,7 +22,7 @@ import ( authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/slashing" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/keys" @@ -37,7 +37,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" "github.com/spf13/viper" "github.com/stretchr/testify/require" @@ -62,7 +62,7 @@ import ( bankRest "github.com/cosmos/cosmos-sdk/x/bank/client/rest" govRest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" slashingRest "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" - stakeRest "github.com/cosmos/cosmos-sdk/x/stake/client/rest" + stakingRest "github.com/cosmos/cosmos-sdk/x/staking/client/rest" ) // makePathname creates a unique pathname for each test. It will panic if it @@ -227,8 +227,8 @@ func InitializeTestLCD( logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) logger = log.NewFilter(logger, log.AllowError()) - privValidatorFile := config.PrivValidatorFile() - privVal := pvm.LoadOrGenFilePV(privValidatorFile) + privVal := pvm.LoadOrGenFilePV(config.PrivValidatorKeyFile(), + config.PrivValidatorStateFile()) privVal.Reset() db := dbm.NewMemDB() @@ -247,18 +247,18 @@ func InitializeTestLCD( for i := 0; i < nValidators; i++ { operPrivKey := secp256k1.GenPrivKey() operAddr := operPrivKey.PubKey().Address() - pubKey := privVal.PubKey + pubKey := privVal.GetPubKey() delegation := 100 if i > 0 { pubKey = ed25519.GenPrivKey().PubKey() delegation = 1 } - msg := stake.NewMsgCreateValidator( + msg := staking.NewMsgCreateValidator( sdk.ValAddress(operAddr), pubKey, - sdk.NewCoin(stakeTypes.DefaultBondDenom, sdk.NewInt(int64(delegation))), - stake.Description{Moniker: fmt.Sprintf("validator-%d", i+1)}, - stake.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), + sdk.NewCoin(stakingTypes.DefaultBondDenom, sdk.NewInt(int64(delegation))), + staking.Description{Moniker: fmt.Sprintf("validator-%d", i+1)}, + staking.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), ) stdSignMsg := txbuilder.StdSignMsg{ ChainID: genDoc.ChainID, @@ -274,7 +274,7 @@ func InitializeTestLCD( valOperAddrs = append(valOperAddrs, sdk.ValAddress(operAddr)) accAuth := auth.NewBaseAccountWithAddress(sdk.AccAddress(operAddr)) - accAuth.Coins = sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 150)} + accAuth.Coins = sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 150)} accs = append(accs, gapp.NewGenesisAccount(&accAuth)) } @@ -288,10 +288,10 @@ func InitializeTestLCD( // add some tokens to init accounts for _, addr := range initAddrs { accAuth := auth.NewBaseAccountWithAddress(addr) - accAuth.Coins = sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 100)} + accAuth.Coins = sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 100)} acc := gapp.NewGenesisAccount(&accAuth) genesisState.Accounts = append(genesisState.Accounts, acc) - genesisState.StakeData.Pool.LooseTokens = genesisState.StakeData.Pool.LooseTokens.Add(sdk.NewInt(100)) + genesisState.StakingData.Pool.LooseTokens = genesisState.StakingData.Pool.LooseTokens.Add(sdk.NewInt(100)) } appState, err := codec.MarshalJSONIndent(cdc, genesisState) @@ -390,7 +390,7 @@ func registerRoutes(rs *RestServer) { tx.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc) authRest.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, auth.StoreKey) bankRest.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) - stakeRest.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) + stakingRest.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) slashingRest.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) govRest.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc) } @@ -709,7 +709,7 @@ func doTransferWithGas(t *testing.T, port, seed, name, memo, password string, ad ) sr := sendReq{ - Amount: sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 1)}, + Amount: sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 1)}, BaseReq: baseReq, } @@ -729,7 +729,7 @@ type sendReq struct { // ICS 21 - Stake // ---------------------------------------------------------------------- -// POST /stake/delegators/{delegatorAddr}/delegations Submit delegation +// POST /staking/delegators/{delegatorAddr}/delegations Submit delegation func doDelegate(t *testing.T, port, name, password string, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount int64, fees sdk.Coins) (resultTx ctypes.ResultBroadcastTxCommit) { acc := getAccount(t, port, delAddr) @@ -741,11 +741,11 @@ func doDelegate(t *testing.T, port, name, password string, BaseReq: baseReq, DelegatorAddr: delAddr, ValidatorAddr: valAddr, - Delegation: sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, amount), + Delegation: sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, amount), } req, err := cdc.MarshalJSON(msg) require.NoError(t, err) - res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delAddr.String()), req) + res, body := Request(t, port, "POST", fmt.Sprintf("/staking/delegators/%s/delegations", delAddr.String()), req) require.Equal(t, http.StatusOK, res.StatusCode, body) var result ctypes.ResultBroadcastTxCommit @@ -762,7 +762,7 @@ type msgDelegationsInput struct { Delegation sdk.Coin `json:"delegation"` } -// POST /stake/delegators/{delegatorAddr}/delegations Submit delegation +// POST /staking/delegators/{delegatorAddr}/delegations Submit delegation func doBeginUnbonding(t *testing.T, port, name, password string, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount int64, fees sdk.Coins) (resultTx ctypes.ResultBroadcastTxCommit) { @@ -780,7 +780,7 @@ func doBeginUnbonding(t *testing.T, port, name, password string, req, err := cdc.MarshalJSON(msg) require.NoError(t, err) - res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/unbonding_delegations", delAddr), req) + res, body := Request(t, port, "POST", fmt.Sprintf("/staking/delegators/%s/unbonding_delegations", delAddr), req) require.Equal(t, http.StatusOK, res.StatusCode, body) var result ctypes.ResultBroadcastTxCommit @@ -797,7 +797,7 @@ type msgBeginUnbondingInput struct { SharesAmount sdk.Dec `json:"shares"` } -// POST /stake/delegators/{delegatorAddr}/delegations Submit delegation +// POST /staking/delegators/{delegatorAddr}/delegations Submit delegation func doBeginRedelegation(t *testing.T, port, name, password string, delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress, amount int64, fees sdk.Coins) (resultTx ctypes.ResultBroadcastTxCommit) { @@ -818,7 +818,7 @@ func doBeginRedelegation(t *testing.T, port, name, password string, req, err := cdc.MarshalJSON(msg) require.NoError(t, err) - res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/redelegations", delAddr), req) + res, body := Request(t, port, "POST", fmt.Sprintf("/staking/delegators/%s/redelegations", delAddr), req) require.Equal(t, http.StatusOK, res.StatusCode, body) var result ctypes.ResultBroadcastTxCommit @@ -836,12 +836,12 @@ type msgBeginRedelegateInput struct { SharesAmount sdk.Dec `json:"shares"` } -// GET /stake/delegators/{delegatorAddr}/delegations Get all delegations from a delegator -func getDelegatorDelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress) []stake.Delegation { - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/delegations", delegatorAddr), nil) +// GET /staking/delegators/{delegatorAddr}/delegations Get all delegations from a delegator +func getDelegatorDelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress) []staking.Delegation { + res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/delegations", delegatorAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var dels []stake.Delegation + var dels []staking.Delegation err := cdc.UnmarshalJSON([]byte(body), &dels) require.Nil(t, err) @@ -849,12 +849,12 @@ func getDelegatorDelegations(t *testing.T, port string, delegatorAddr sdk.AccAdd return dels } -// GET /stake/delegators/{delegatorAddr}/unbonding_delegations Get all unbonding delegations from a delegator -func getDelegatorUnbondingDelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress) []stake.UnbondingDelegation { - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/unbonding_delegations", delegatorAddr), nil) +// GET /staking/delegators/{delegatorAddr}/unbonding_delegations Get all unbonding delegations from a delegator +func getDelegatorUnbondingDelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress) []staking.UnbondingDelegation { + res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/unbonding_delegations", delegatorAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var ubds []stake.UnbondingDelegation + var ubds []staking.UnbondingDelegation err := cdc.UnmarshalJSON([]byte(body), &ubds) require.Nil(t, err) @@ -862,11 +862,11 @@ func getDelegatorUnbondingDelegations(t *testing.T, port string, delegatorAddr s return ubds } -// GET /stake/redelegations?delegator=0xdeadbeef&validator_from=0xdeadbeef&validator_to=0xdeadbeef& Get redelegations filters by params passed in -func getRedelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress, srcValidatorAddr sdk.ValAddress, dstValidatorAddr sdk.ValAddress) []stake.Redelegation { +// GET /staking/redelegations?delegator=0xdeadbeef&validator_from=0xdeadbeef&validator_to=0xdeadbeef& Get redelegations filters by params passed in +func getRedelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress, srcValidatorAddr sdk.ValAddress, dstValidatorAddr sdk.ValAddress) []staking.Redelegation { var res *http.Response var body string - endpoint := "/stake/redelegations?" + endpoint := "/staking/redelegations?" if !delegatorAddr.Empty() { endpoint += fmt.Sprintf("delegator=%s&", delegatorAddr) } @@ -878,18 +878,18 @@ func getRedelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress, s } res, body = Request(t, port, "GET", endpoint, nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var redels []stake.Redelegation + var redels []staking.Redelegation err := cdc.UnmarshalJSON([]byte(body), &redels) require.Nil(t, err) return redels } -// GET /stake/delegators/{delegatorAddr}/validators Query all validators that a delegator is bonded to -func getDelegatorValidators(t *testing.T, port string, delegatorAddr sdk.AccAddress) []stake.Validator { - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/validators", delegatorAddr), nil) +// GET /staking/delegators/{delegatorAddr}/validators Query all validators that a delegator is bonded to +func getDelegatorValidators(t *testing.T, port string, delegatorAddr sdk.AccAddress) []staking.Validator { + res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/validators", delegatorAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var bondedValidators []stake.Validator + var bondedValidators []staking.Validator err := cdc.UnmarshalJSON([]byte(body), &bondedValidators) require.Nil(t, err) @@ -897,27 +897,27 @@ func getDelegatorValidators(t *testing.T, port string, delegatorAddr sdk.AccAddr return bondedValidators } -// GET /stake/delegators/{delegatorAddr}/validators/{validatorAddr} Query a validator that a delegator is bonded to -func getDelegatorValidator(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) stake.Validator { - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/validators/%s", delegatorAddr, validatorAddr), nil) +// GET /staking/delegators/{delegatorAddr}/validators/{validatorAddr} Query a validator that a delegator is bonded to +func getDelegatorValidator(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) staking.Validator { + res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/validators/%s", delegatorAddr, validatorAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var bondedValidator stake.Validator + var bondedValidator staking.Validator err := cdc.UnmarshalJSON([]byte(body), &bondedValidator) require.Nil(t, err) return bondedValidator } -// GET /stake/delegators/{delegatorAddr}/txs Get all staking txs (i.e msgs) from a delegator +// GET /staking/delegators/{delegatorAddr}/txs Get all staking txs (i.e msgs) from a delegator func getBondingTxs(t *testing.T, port string, delegatorAddr sdk.AccAddress, query string) []tx.Info { var res *http.Response var body string if len(query) > 0 { - res, body = Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/txs?type=%s", delegatorAddr, query), nil) + res, body = Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/txs?type=%s", delegatorAddr, query), nil) } else { - res, body = Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/txs", delegatorAddr), nil) + res, body = Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/txs", delegatorAddr), nil) } require.Equal(t, http.StatusOK, res.StatusCode, body) @@ -929,95 +929,95 @@ func getBondingTxs(t *testing.T, port string, delegatorAddr sdk.AccAddress, quer return txs } -// GET /stake/delegators/{delegatorAddr}/delegations/{validatorAddr} Query the current delegation between a delegator and a validator -func getDelegation(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) stake.Delegation { - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/delegations/%s", delegatorAddr, validatorAddr), nil) +// GET /staking/delegators/{delegatorAddr}/delegations/{validatorAddr} Query the current delegation between a delegator and a validator +func getDelegation(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) staking.Delegation { + res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/delegations/%s", delegatorAddr, validatorAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var bond stake.Delegation + var bond staking.Delegation err := cdc.UnmarshalJSON([]byte(body), &bond) require.Nil(t, err) return bond } -// GET /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr} Query all unbonding delegations between a delegator and a validator -func getUndelegation(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) stake.UnbondingDelegation { - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/unbonding_delegations/%s", delegatorAddr, validatorAddr), nil) +// GET /staking/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr} Query all unbonding delegations between a delegator and a validator +func getUndelegation(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) staking.UnbondingDelegation { + res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/unbonding_delegations/%s", delegatorAddr, validatorAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var unbond stake.UnbondingDelegation + var unbond staking.UnbondingDelegation err := cdc.UnmarshalJSON([]byte(body), &unbond) require.Nil(t, err) return unbond } -// GET /stake/validators Get all validator candidates -func getValidators(t *testing.T, port string) []stake.Validator { - res, body := Request(t, port, "GET", "/stake/validators", nil) +// GET /staking/validators Get all validator candidates +func getValidators(t *testing.T, port string) []staking.Validator { + res, body := Request(t, port, "GET", "/staking/validators", nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var validators []stake.Validator + var validators []staking.Validator err := cdc.UnmarshalJSON([]byte(body), &validators) require.Nil(t, err) return validators } -// GET /stake/validators/{validatorAddr} Query the information from a single validator -func getValidator(t *testing.T, port string, validatorAddr sdk.ValAddress) stake.Validator { - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/validators/%s", validatorAddr.String()), nil) +// GET /staking/validators/{validatorAddr} Query the information from a single validator +func getValidator(t *testing.T, port string, validatorAddr sdk.ValAddress) staking.Validator { + res, body := Request(t, port, "GET", fmt.Sprintf("/staking/validators/%s", validatorAddr.String()), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var validator stake.Validator + var validator staking.Validator err := cdc.UnmarshalJSON([]byte(body), &validator) require.Nil(t, err) return validator } -// GET /stake/validators/{validatorAddr}/delegations Get all delegations from a validator -func getValidatorDelegations(t *testing.T, port string, validatorAddr sdk.ValAddress) []stake.Delegation { - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/validators/%s/delegations", validatorAddr.String()), nil) +// GET /staking/validators/{validatorAddr}/delegations Get all delegations from a validator +func getValidatorDelegations(t *testing.T, port string, validatorAddr sdk.ValAddress) []staking.Delegation { + res, body := Request(t, port, "GET", fmt.Sprintf("/staking/validators/%s/delegations", validatorAddr.String()), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var delegations []stake.Delegation + var delegations []staking.Delegation err := cdc.UnmarshalJSON([]byte(body), &delegations) require.Nil(t, err) return delegations } -// GET /stake/validators/{validatorAddr}/unbonding_delegations Get all unbonding delegations from a validator -func getValidatorUnbondingDelegations(t *testing.T, port string, validatorAddr sdk.ValAddress) []stake.UnbondingDelegation { - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/validators/%s/unbonding_delegations", validatorAddr.String()), nil) +// GET /staking/validators/{validatorAddr}/unbonding_delegations Get all unbonding delegations from a validator +func getValidatorUnbondingDelegations(t *testing.T, port string, validatorAddr sdk.ValAddress) []staking.UnbondingDelegation { + res, body := Request(t, port, "GET", fmt.Sprintf("/staking/validators/%s/unbonding_delegations", validatorAddr.String()), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var ubds []stake.UnbondingDelegation + var ubds []staking.UnbondingDelegation err := cdc.UnmarshalJSON([]byte(body), &ubds) require.Nil(t, err) return ubds } -// GET /stake/pool Get the current state of the staking pool -func getStakePool(t *testing.T, port string) stake.Pool { - res, body := Request(t, port, "GET", "/stake/pool", nil) +// GET /staking/pool Get the current state of the staking pool +func getStakingPool(t *testing.T, port string) staking.Pool { + res, body := Request(t, port, "GET", "/staking/pool", nil) require.Equal(t, http.StatusOK, res.StatusCode, body) require.NotNil(t, body) - var pool stake.Pool + var pool staking.Pool err := cdc.UnmarshalJSON([]byte(body), &pool) require.Nil(t, err) return pool } -// GET /stake/parameters Get the current staking parameter values -func getStakeParams(t *testing.T, port string) stake.Params { - res, body := Request(t, port, "GET", "/stake/parameters", nil) +// GET /staking/parameters Get the current staking parameter values +func getStakingParams(t *testing.T, port string) staking.Params { + res, body := Request(t, port, "GET", "/staking/parameters", nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var params stake.Params + var params staking.Params err := cdc.UnmarshalJSON([]byte(body), ¶ms) require.Nil(t, err) return params @@ -1039,7 +1039,7 @@ func doSubmitProposal(t *testing.T, port, seed, name, password string, proposerA Description: "test", ProposalType: "Text", Proposer: proposerAddr, - InitialDeposit: sdk.Coins{sdk.NewCoin(stakeTypes.DefaultBondDenom, sdk.NewInt(amount))}, + InitialDeposit: sdk.Coins{sdk.NewCoin(stakingTypes.DefaultBondDenom, sdk.NewInt(amount))}, BaseReq: baseReq, } @@ -1132,7 +1132,7 @@ func doDeposit(t *testing.T, port, seed, name, password string, proposerAddr sdk dr := depositReq{ Depositor: proposerAddr, - Amount: sdk.Coins{sdk.NewCoin(stakeTypes.DefaultBondDenom, sdk.NewInt(amount))}, + Amount: sdk.Coins{sdk.NewCoin(stakingTypes.DefaultBondDenom, sdk.NewInt(amount))}, BaseReq: baseReq, } diff --git a/client/utils/rest.go b/client/utils/rest.go index 2cdecab64c66..09663291e55b 100644 --- a/client/utils/rest.go +++ b/client/utils/rest.go @@ -203,7 +203,7 @@ func ReadRESTReq(w http.ResponseWriter, r *http.Request, cdc *codec.Codec, req i // supplied messages. Finally, it broadcasts the signed transaction to a node. // // NOTE: Also see CompleteAndBroadcastTxCli. -// NOTE: Also see x/stake/client/rest/tx.go delegationsRequestHandlerFn. +// NOTE: Also see x/staking/client/rest/tx.go delegationsRequestHandlerFn. func CompleteAndBroadcastTxREST(w http.ResponseWriter, r *http.Request, cliCtx context.CLIContext, baseReq BaseReq, msgs []sdk.Msg, cdc *codec.Codec) { gasAdjustment, ok := ParseFloat64OrReturnBadRequest(w, baseReq.GasAdjustment, client.DefaultGasAdjustment) if !ok { diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index dd5371e8d6b2..7945a8bc655d 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -21,7 +21,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" ) const ( @@ -44,8 +44,8 @@ type GaiaApp struct { // keys to access the substores keyMain *sdk.KVStoreKey keyAccount *sdk.KVStoreKey - keyStake *sdk.KVStoreKey - tkeyStake *sdk.TransientStoreKey + keyStaking *sdk.KVStoreKey + tkeyStaking *sdk.TransientStoreKey keySlashing *sdk.KVStoreKey keyMint *sdk.KVStoreKey keyDistr *sdk.KVStoreKey @@ -59,7 +59,7 @@ type GaiaApp struct { accountKeeper auth.AccountKeeper feeCollectionKeeper auth.FeeCollectionKeeper bankKeeper bank.Keeper - stakeKeeper stake.Keeper + stakingKeeper staking.Keeper slashingKeeper slashing.Keeper mintKeeper mint.Keeper distrKeeper distr.Keeper @@ -79,8 +79,8 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b cdc: cdc, keyMain: sdk.NewKVStoreKey(bam.MainStoreKey), keyAccount: sdk.NewKVStoreKey(auth.StoreKey), - keyStake: sdk.NewKVStoreKey(stake.StoreKey), - tkeyStake: sdk.NewTransientStoreKey(stake.TStoreKey), + keyStaking: sdk.NewKVStoreKey(staking.StoreKey), + tkeyStaking: sdk.NewTransientStoreKey(staking.TStoreKey), keyMint: sdk.NewKVStoreKey(mint.StoreKey), keyDistr: sdk.NewKVStoreKey(distr.StoreKey), tkeyDistr: sdk.NewTransientStoreKey(distr.TStoreKey), @@ -107,63 +107,63 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b app.cdc, app.keyFeeCollection, ) - stakeKeeper := stake.NewKeeper( + stakingKeeper := staking.NewKeeper( app.cdc, - app.keyStake, app.tkeyStake, - app.bankKeeper, app.paramsKeeper.Subspace(stake.DefaultParamspace), - stake.DefaultCodespace, + app.keyStaking, app.tkeyStaking, + app.bankKeeper, app.paramsKeeper.Subspace(staking.DefaultParamspace), + staking.DefaultCodespace, ) app.mintKeeper = mint.NewKeeper(app.cdc, app.keyMint, app.paramsKeeper.Subspace(mint.DefaultParamspace), - &stakeKeeper, app.feeCollectionKeeper, + &stakingKeeper, app.feeCollectionKeeper, ) app.distrKeeper = distr.NewKeeper( app.cdc, app.keyDistr, app.paramsKeeper.Subspace(distr.DefaultParamspace), - app.bankKeeper, &stakeKeeper, app.feeCollectionKeeper, + app.bankKeeper, &stakingKeeper, app.feeCollectionKeeper, distr.DefaultCodespace, ) app.slashingKeeper = slashing.NewKeeper( app.cdc, app.keySlashing, - &stakeKeeper, app.paramsKeeper.Subspace(slashing.DefaultParamspace), + &stakingKeeper, app.paramsKeeper.Subspace(slashing.DefaultParamspace), slashing.DefaultCodespace, ) app.govKeeper = gov.NewKeeper( app.cdc, app.keyGov, - app.paramsKeeper, app.paramsKeeper.Subspace(gov.DefaultParamspace), app.bankKeeper, &stakeKeeper, + app.paramsKeeper, app.paramsKeeper.Subspace(gov.DefaultParamspace), app.bankKeeper, &stakingKeeper, gov.DefaultCodespace, ) // register the staking hooks - // NOTE: The stakeKeeper above is passed by reference, so that it can be + // NOTE: The stakingKeeper above is passed by reference, so that it can be // modified like below: - app.stakeKeeper = *stakeKeeper.SetHooks( + app.stakingKeeper = *stakingKeeper.SetHooks( NewStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks()), ) // register message routes app.Router(). AddRoute(bank.RouterKey, bank.NewHandler(app.bankKeeper)). - AddRoute(stake.RouterKey, stake.NewHandler(app.stakeKeeper)). + AddRoute(staking.RouterKey, staking.NewHandler(app.stakingKeeper)). AddRoute(distr.RouterKey, distr.NewHandler(app.distrKeeper)). AddRoute(slashing.RouterKey, slashing.NewHandler(app.slashingKeeper)). AddRoute(gov.RouterKey, gov.NewHandler(app.govKeeper)) app.QueryRouter(). AddRoute(gov.QuerierRoute, gov.NewQuerier(app.govKeeper)). - AddRoute(slashing.QuerierRoute, slashing.NewQuerier(app.slashingKeeper, app.cdc)). - AddRoute(stake.QuerierRoute, stake.NewQuerier(app.stakeKeeper, app.cdc)) + AddRoute(slashing.QuerierRoute, slashing.NewQuerier(app.slashingKeeper, app.cdc)). + AddRoute(staking.QuerierRoute, staking.NewQuerier(app.stakingKeeper, app.cdc)) // initialize BaseApp - app.MountStores(app.keyMain, app.keyAccount, app.keyStake, app.keyMint, app.keyDistr, + app.MountStores(app.keyMain, app.keyAccount, app.keyStaking, app.keyMint, app.keyDistr, app.keySlashing, app.keyGov, app.keyFeeCollection, app.keyParams) app.SetInitChainer(app.initChainer) app.SetBeginBlocker(app.BeginBlocker) app.SetAnteHandler(auth.NewAnteHandler(app.accountKeeper, app.feeCollectionKeeper)) - app.MountStoresTransient(app.tkeyParams, app.tkeyStake, app.tkeyDistr) + app.MountStoresTransient(app.tkeyParams, app.tkeyStaking, app.tkeyDistr) app.SetEndBlocker(app.EndBlocker) if loadLatest { @@ -180,7 +180,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b func MakeCodec() *codec.Codec { var cdc = codec.New() bank.RegisterCodec(cdc) - stake.RegisterCodec(cdc) + staking.RegisterCodec(cdc) distr.RegisterCodec(cdc) slashing.RegisterCodec(cdc) gov.RegisterCodec(cdc) @@ -214,7 +214,7 @@ func (app *GaiaApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) ab // nolint: unparam func (app *GaiaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { tags := gov.EndBlocker(ctx, app.govKeeper) - validatorUpdates, endBlockerTags := stake.EndBlocker(ctx, app.stakeKeeper) + validatorUpdates, endBlockerTags := staking.EndBlocker(ctx, app.stakingKeeper) tags = append(tags, endBlockerTags...) app.assertRuntimeInvariants() @@ -238,15 +238,15 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt app.accountKeeper.SetAccount(ctx, acc) } - // load the initial stake information - validators, err := stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData) + // load the initial staking information + validators, err := staking.InitGenesis(ctx, app.stakingKeeper, genesisState.StakingData) if err != nil { panic(err) // TODO find a way to do this w/o panics } // initialize module-specific stores auth.InitGenesis(ctx, app.accountKeeper, app.feeCollectionKeeper, genesisState.AuthData) - slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.SlashingData, genesisState.StakeData) + slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.SlashingData, genesisState.StakingData) gov.InitGenesis(ctx, app.govKeeper, genesisState.GovData) mint.InitGenesis(ctx, app.mintKeeper, genesisState.MintData) distr.InitGenesis(ctx, app.distrKeeper, genesisState.DistrData) @@ -271,7 +271,7 @@ func (app *GaiaApp) initFromGenesisState(ctx sdk.Context, genesisState GenesisSt } } - validators = app.stakeKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + validators = app.stakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) } return validators } @@ -334,39 +334,39 @@ func NewStakingHooks(dh distr.Hooks, sh slashing.Hooks) StakingHooks { } // nolint -func (h StakingHooks) OnValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { - h.dh.OnValidatorCreated(ctx, valAddr) - h.sh.OnValidatorCreated(ctx, valAddr) +func (h StakingHooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { + h.dh.AfterValidatorCreated(ctx, valAddr) + h.sh.AfterValidatorCreated(ctx, valAddr) } -func (h StakingHooks) OnValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { - h.dh.OnValidatorModified(ctx, valAddr) - h.sh.OnValidatorModified(ctx, valAddr) +func (h StakingHooks) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { + h.dh.BeforeValidatorModified(ctx, valAddr) + h.sh.BeforeValidatorModified(ctx, valAddr) } -func (h StakingHooks) OnValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - h.dh.OnValidatorRemoved(ctx, consAddr, valAddr) - h.sh.OnValidatorRemoved(ctx, consAddr, valAddr) +func (h StakingHooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.AfterValidatorRemoved(ctx, consAddr, valAddr) + h.sh.AfterValidatorRemoved(ctx, consAddr, valAddr) } -func (h StakingHooks) OnValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - h.dh.OnValidatorBonded(ctx, consAddr, valAddr) - h.sh.OnValidatorBonded(ctx, consAddr, valAddr) +func (h StakingHooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.AfterValidatorBonded(ctx, consAddr, valAddr) + h.sh.AfterValidatorBonded(ctx, consAddr, valAddr) } -func (h StakingHooks) OnValidatorPowerDidChange(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - h.dh.OnValidatorPowerDidChange(ctx, consAddr, valAddr) - h.sh.OnValidatorPowerDidChange(ctx, consAddr, valAddr) +func (h StakingHooks) AfterValidatorPowerDidChange(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.AfterValidatorPowerDidChange(ctx, consAddr, valAddr) + h.sh.AfterValidatorPowerDidChange(ctx, consAddr, valAddr) } -func (h StakingHooks) OnValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - h.dh.OnValidatorBeginUnbonding(ctx, consAddr, valAddr) - h.sh.OnValidatorBeginUnbonding(ctx, consAddr, valAddr) +func (h StakingHooks) AfterValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.AfterValidatorBeginUnbonding(ctx, consAddr, valAddr) + h.sh.AfterValidatorBeginUnbonding(ctx, consAddr, valAddr) } -func (h StakingHooks) OnDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.dh.OnDelegationCreated(ctx, delAddr, valAddr) - h.sh.OnDelegationCreated(ctx, delAddr, valAddr) +func (h StakingHooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.BeforeDelegationCreated(ctx, delAddr, valAddr) + h.sh.BeforeDelegationCreated(ctx, delAddr, valAddr) } -func (h StakingHooks) OnDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.dh.OnDelegationSharesModified(ctx, delAddr, valAddr) - h.sh.OnDelegationSharesModified(ctx, delAddr, valAddr) +func (h StakingHooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.BeforeDelegationSharesModified(ctx, delAddr, valAddr) + h.sh.BeforeDelegationSharesModified(ctx, delAddr, valAddr) } -func (h StakingHooks) OnDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.dh.OnDelegationRemoved(ctx, delAddr, valAddr) - h.sh.OnDelegationRemoved(ctx, delAddr, valAddr) +func (h StakingHooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.BeforeDelegationRemoved(ctx, delAddr, valAddr) + h.sh.BeforeDelegationRemoved(ctx, delAddr, valAddr) } diff --git a/cmd/gaia/app/app_test.go b/cmd/gaia/app/app_test.go index 87b2ec2a9531..5f2b5b968772 100644 --- a/cmd/gaia/app/app_test.go +++ b/cmd/gaia/app/app_test.go @@ -14,7 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" abci "github.com/tendermint/tendermint/abci/types" ) @@ -28,7 +28,7 @@ func setGenesis(gapp *GaiaApp, accs ...*auth.BaseAccount) error { genesisState := NewGenesisState( genaccs, auth.DefaultGenesisState(), - stake.DefaultGenesisState(), + staking.DefaultGenesisState(), mint.DefaultGenesisState(), distr.DefaultGenesisState(), gov.DefaultGenesisState(), diff --git a/cmd/gaia/app/export.go b/cmd/gaia/app/export.go index ec2e83b2e720..05e8e29a348c 100644 --- a/cmd/gaia/app/export.go +++ b/cmd/gaia/app/export.go @@ -14,7 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/slashing" - stake "github.com/cosmos/cosmos-sdk/x/stake" + staking "github.com/cosmos/cosmos-sdk/x/staking" ) // export the state of gaia for a genesis file @@ -40,7 +40,7 @@ func (app *GaiaApp) ExportAppStateAndValidators(forZeroHeight bool) ( genState := NewGenesisState( accounts, auth.ExportGenesis(ctx, app.accountKeeper, app.feeCollectionKeeper), - stake.ExportGenesis(ctx, app.stakeKeeper), + staking.ExportGenesis(ctx, app.stakingKeeper), mint.ExportGenesis(ctx, app.mintKeeper), distr.ExportGenesis(ctx, app.distrKeeper), gov.ExportGenesis(ctx, app.govKeeper), @@ -50,7 +50,7 @@ func (app *GaiaApp) ExportAppStateAndValidators(forZeroHeight bool) ( if err != nil { return nil, nil, err } - validators = stake.WriteValidators(ctx, app.stakeKeeper) + validators = staking.WriteValidators(ctx, app.stakingKeeper) return appState, validators, nil } @@ -102,7 +102,7 @@ func (app *GaiaApp) prepForZeroHeightGenesis(ctx sdk.Context) { if !feePool.TotalValAccum.Accum.IsZero() { panic("unexpected leftover validator accum") } - bondDenom := app.stakeKeeper.GetParams(ctx).BondDenom + bondDenom := app.stakingKeeper.GetParams(ctx).BondDenom if !feePool.ValPool.AmountOf(bondDenom).IsZero() { panic(fmt.Sprintf("unexpected leftover validator pool coins: %v", feePool.ValPool.AmountOf(bondDenom).String())) @@ -112,32 +112,32 @@ func (app *GaiaApp) prepForZeroHeightGenesis(ctx sdk.Context) { feePool.TotalValAccum = distr.NewTotalAccum(0) app.distrKeeper.SetFeePool(ctx, feePool) - /* Handle stake state. */ + /* Handle staking state. */ // iterate through redelegations, reset creation height - app.stakeKeeper.IterateRedelegations(ctx, func(_ int64, red stake.Redelegation) (stop bool) { + app.stakingKeeper.IterateRedelegations(ctx, func(_ int64, red staking.Redelegation) (stop bool) { red.CreationHeight = 0 - app.stakeKeeper.SetRedelegation(ctx, red) + app.stakingKeeper.SetRedelegation(ctx, red) return false }) // iterate through unbonding delegations, reset creation height - app.stakeKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stake.UnbondingDelegation) (stop bool) { + app.stakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd staking.UnbondingDelegation) (stop bool) { ubd.CreationHeight = 0 - app.stakeKeeper.SetUnbondingDelegation(ctx, ubd) + app.stakingKeeper.SetUnbondingDelegation(ctx, ubd) return false }) // Iterate through validators by power descending, reset bond heights, and // update bond intra-tx counters. - store := ctx.KVStore(app.keyStake) - iter := sdk.KVStoreReversePrefixIterator(store, stake.ValidatorsKey) + store := ctx.KVStore(app.keyStaking) + iter := sdk.KVStoreReversePrefixIterator(store, staking.ValidatorsKey) counter := int16(0) var valConsAddrs []sdk.ConsAddress for ; iter.Valid(); iter.Next() { addr := sdk.ValAddress(iter.Key()[1:]) - validator, found := app.stakeKeeper.GetValidator(ctx, addr) + validator, found := app.stakingKeeper.GetValidator(ctx, addr) if !found { panic("expected validator, not found") } @@ -146,7 +146,7 @@ func (app *GaiaApp) prepForZeroHeightGenesis(ctx sdk.Context) { validator.UnbondingHeight = 0 valConsAddrs = append(valConsAddrs, validator.ConsAddress()) - app.stakeKeeper.SetValidator(ctx, validator) + app.stakingKeeper.SetValidator(ctx, validator) counter++ } @@ -154,19 +154,6 @@ func (app *GaiaApp) prepForZeroHeightGenesis(ctx sdk.Context) { /* Handle slashing state. */ - // remove all existing slashing periods and recreate one for each validator - app.slashingKeeper.DeleteValidatorSlashingPeriods(ctx) - - for _, valConsAddr := range valConsAddrs { - sp := slashing.ValidatorSlashingPeriod{ - ValidatorAddr: valConsAddr, - StartHeight: 0, - EndHeight: 0, - SlashedSoFar: sdk.ZeroDec(), - } - app.slashingKeeper.SetValidatorSlashingPeriod(ctx, sp) - } - // reset start height on signing infos app.slashingKeeper.IterateValidatorSigningInfos( ctx, diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index 19cc3faefffa..32c2555adacf 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -19,22 +19,22 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/stake" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( // bonded tokens given to genesis validators/accounts freeFermionVal = int64(100) freeFermionsAcc = sdk.NewInt(150) - bondDenom = stakeTypes.DefaultBondDenom + bondDenom = stakingTypes.DefaultBondDenom ) // State to Unmarshal type GenesisState struct { Accounts []GenesisAccount `json:"accounts"` AuthData auth.GenesisState `json:"auth"` - StakeData stake.GenesisState `json:"stake"` + StakingData staking.GenesisState `json:"staking"` MintData mint.GenesisState `json:"mint"` DistrData distr.GenesisState `json:"distr"` GovData gov.GenesisState `json:"gov"` @@ -43,14 +43,14 @@ type GenesisState struct { } func NewGenesisState(accounts []GenesisAccount, authData auth.GenesisState, - stakeData stake.GenesisState, mintData mint.GenesisState, + stakingData staking.GenesisState, mintData mint.GenesisState, distrData distr.GenesisState, govData gov.GenesisState, slashingData slashing.GenesisState) GenesisState { return GenesisState{ Accounts: accounts, AuthData: authData, - StakeData: stakeData, + StakingData: stakingData, MintData: mintData, DistrData: distrData, GovData: govData, @@ -108,7 +108,7 @@ func GaiaAppGenState(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []js return genesisState, errors.New("there must be at least one genesis tx") } - stakeData := genesisState.StakeData + stakingData := genesisState.StakingData for i, genTx := range appGenTxs { var tx auth.StdTx if err := cdc.UnmarshalJSON(genTx, &tx); err != nil { @@ -119,7 +119,7 @@ func GaiaAppGenState(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []js return genesisState, errors.New( "must provide genesis StdTx with exactly 1 CreateValidator message") } - if _, ok := msgs[0].(stake.MsgCreateValidator); !ok { + if _, ok := msgs[0].(staking.MsgCreateValidator); !ok { return genesisState, fmt.Errorf( "Genesis transaction %v does not contain a MsgCreateValidator", i) } @@ -129,12 +129,12 @@ func GaiaAppGenState(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []js // create the genesis account, give'm few steaks and a buncha token with there name for _, coin := range acc.Coins { if coin.Denom == bondDenom { - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens. + stakingData.Pool.LooseTokens = stakingData.Pool.LooseTokens. Add(coin.Amount) // increase the supply } } } - genesisState.StakeData = stakeData + genesisState.StakingData = stakingData genesisState.GenTxs = appGenTxs return genesisState, nil } @@ -144,7 +144,7 @@ func NewDefaultGenesisState() GenesisState { return GenesisState{ Accounts: nil, AuthData: auth.DefaultGenesisState(), - StakeData: stake.DefaultGenesisState(), + StakingData: staking.DefaultGenesisState(), MintData: mint.DefaultGenesisState(), DistrData: distr.DefaultGenesisState(), GovData: gov.DefaultGenesisState(), @@ -162,7 +162,7 @@ func GaiaValidateGenesisState(genesisState GenesisState) error { return err } - // skip stakeData validation as genesis is created from txs + // skip stakingData validation as genesis is created from txs if len(genesisState.GenTxs) > 0 { return nil } @@ -170,7 +170,7 @@ func GaiaValidateGenesisState(genesisState GenesisState) error { if err := auth.ValidateGenesis(genesisState.AuthData); err != nil { return err } - if err := stake.ValidateGenesis(genesisState.StakeData); err != nil { + if err := staking.ValidateGenesis(genesisState.StakingData); err != nil { return err } if err := mint.ValidateGenesis(genesisState.MintData); err != nil { @@ -272,7 +272,7 @@ func CollectStdTxs(cdc *codec.Codec, moniker string, genTxsDir string, genDoc tm "each genesis transaction must provide a single genesis message") } - msg := msgs[0].(stake.MsgCreateValidator) + msg := msgs[0].(staking.MsgCreateValidator) // validate delegator and validator addresses and funds against the accounts in the state delAddr := msg.DelegatorAddr.String() valAddr := sdk.AccAddress(msg.ValidatorAddr).String() diff --git a/cmd/gaia/app/genesis_test.go b/cmd/gaia/app/genesis_test.go index df541341d18a..90fcb86715b2 100644 --- a/cmd/gaia/app/genesis_test.go +++ b/cmd/gaia/app/genesis_test.go @@ -13,8 +13,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/stake" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( @@ -32,18 +32,18 @@ var ( func makeGenesisState(t *testing.T, genTxs []auth.StdTx) GenesisState { // start with the default staking genesis state appState := NewDefaultGenesisState() - stakeData := appState.StakeData + stakingData := appState.StakingData genAccs := make([]GenesisAccount, len(genTxs)) for i, genTx := range genTxs { msgs := genTx.GetMsgs() require.Equal(t, 1, len(msgs)) - msg := msgs[0].(stake.MsgCreateValidator) + msg := msgs[0].(staking.MsgCreateValidator) acc := auth.NewBaseAccountWithAddress(sdk.AccAddress(msg.ValidatorAddr)) acc.Coins = sdk.Coins{sdk.NewInt64Coin(bondDenom, 150)} genAccs[i] = NewGenesisAccount(&acc) - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewInt(150)) // increase the supply + stakingData.Pool.LooseTokens = stakingData.Pool.LooseTokens.Add(sdk.NewInt(150)) // increase the supply } // create the final app state @@ -91,9 +91,9 @@ func TestGaiaAppGenState(t *testing.T) { } func makeMsg(name string, pk crypto.PubKey) auth.StdTx { - desc := stake.NewDescription(name, "", "", "") - comm := stakeTypes.CommissionMsg{} - msg := stake.NewMsgCreateValidator(sdk.ValAddress(pk.Address()), pk, sdk.NewInt64Coin(bondDenom, + desc := staking.NewDescription(name, "", "", "") + comm := stakingTypes.CommissionMsg{} + msg := staking.NewMsgCreateValidator(sdk.ValAddress(pk.Address()), pk, sdk.NewInt64Coin(bondDenom, 50), desc, comm) return auth.NewStdTx([]sdk.Msg{msg}, auth.StdFee{}, nil, "") } @@ -108,18 +108,18 @@ func TestGaiaGenesisValidation(t *testing.T) { require.NotNil(t, err) // Test bonded + jailed validator fails genesisState = makeGenesisState(t, genTxs) - val1 := stakeTypes.NewValidator(addr1, pk1, stakeTypes.Description{Moniker: "test #2"}) + val1 := stakingTypes.NewValidator(addr1, pk1, stakingTypes.Description{Moniker: "test #2"}) val1.Jailed = true val1.Status = sdk.Bonded - genesisState.StakeData.Validators = append(genesisState.StakeData.Validators, val1) + genesisState.StakingData.Validators = append(genesisState.StakingData.Validators, val1) err = GaiaValidateGenesisState(genesisState) require.NotNil(t, err) // Test duplicate validator fails val1.Jailed = false genesisState = makeGenesisState(t, genTxs) - val2 := stakeTypes.NewValidator(addr1, pk1, stakeTypes.Description{Moniker: "test #3"}) - genesisState.StakeData.Validators = append(genesisState.StakeData.Validators, val1) - genesisState.StakeData.Validators = append(genesisState.StakeData.Validators, val2) + val2 := stakingTypes.NewValidator(addr1, pk1, stakingTypes.Description{Moniker: "test #3"}) + genesisState.StakingData.Validators = append(genesisState.StakingData.Validators, val1) + genesisState.StakingData.Validators = append(genesisState.StakingData.Validators, val2) err = GaiaValidateGenesisState(genesisState) require.NotNil(t, err) } diff --git a/cmd/gaia/app/invariants.go b/cmd/gaia/app/invariants.go index 4582457fcb24..bc5a7c5f30dd 100644 --- a/cmd/gaia/app/invariants.go +++ b/cmd/gaia/app/invariants.go @@ -10,16 +10,16 @@ import ( banksim "github.com/cosmos/cosmos-sdk/x/bank/simulation" distrsim "github.com/cosmos/cosmos-sdk/x/distribution/simulation" "github.com/cosmos/cosmos-sdk/x/mock/simulation" - stakesim "github.com/cosmos/cosmos-sdk/x/stake/simulation" + stakingsim "github.com/cosmos/cosmos-sdk/x/staking/simulation" ) func (app *GaiaApp) runtimeInvariants() []simulation.Invariant { return []simulation.Invariant{ banksim.NonnegativeBalanceInvariant(app.accountKeeper), - distrsim.ValAccumInvariants(app.distrKeeper, app.stakeKeeper), - stakesim.SupplyInvariants(app.bankKeeper, app.stakeKeeper, + distrsim.ValAccumInvariants(app.distrKeeper, app.stakingKeeper), + stakingsim.SupplyInvariants(app.bankKeeper, app.stakingKeeper, app.feeCollectionKeeper, app.distrKeeper, app.accountKeeper), - stakesim.NonNegativePowerInvariant(app.stakeKeeper), + stakingsim.NonNegativePowerInvariant(app.stakingKeeper), } } diff --git a/cmd/gaia/app/sim_test.go b/cmd/gaia/app/sim_test.go index 483ce621e13d..da72937415eb 100644 --- a/cmd/gaia/app/sim_test.go +++ b/cmd/gaia/app/sim_test.go @@ -29,9 +29,9 @@ import ( "github.com/cosmos/cosmos-sdk/x/mock/simulation" "github.com/cosmos/cosmos-sdk/x/slashing" slashingsim "github.com/cosmos/cosmos-sdk/x/slashing/simulation" - stake "github.com/cosmos/cosmos-sdk/x/stake" - stakesim "github.com/cosmos/cosmos-sdk/x/stake/simulation" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + staking "github.com/cosmos/cosmos-sdk/x/staking" + stakingsim "github.com/cosmos/cosmos-sdk/x/staking/simulation" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( @@ -69,7 +69,7 @@ func appStateFn(r *rand.Rand, accs []simulation.Account) json.RawMessage { // Randomly generate some genesis accounts for _, acc := range accs { - coins := sdk.Coins{sdk.NewCoin(stakeTypes.DefaultBondDenom, sdk.NewInt(amount))} + coins := sdk.Coins{sdk.NewCoin(stakingTypes.DefaultBondDenom, sdk.NewInt(amount))} genesisAccounts = append(genesisAccounts, GenesisAccount{ Address: acc.Address, Coins: coins, @@ -92,7 +92,7 @@ func appStateFn(r *rand.Rand, accs []simulation.Account) json.RawMessage { govGenesis := gov.GenesisState{ StartingProposalID: uint64(r.Intn(100)), DepositParams: gov.DepositParams{ - MinDeposit: sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, int64(r.Intn(1e3)))}, + MinDeposit: sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, int64(r.Intn(1e3)))}, MaxDepositPeriod: vp, }, VotingParams: gov.VotingParams{ @@ -106,25 +106,24 @@ func appStateFn(r *rand.Rand, accs []simulation.Account) json.RawMessage { } fmt.Printf("Selected randomly generated governance parameters:\n\t%+v\n", govGenesis) - stakeGenesis := stake.GenesisState{ - Pool: stake.InitialPool(), - Params: stake.Params{ + stakingGenesis := staking.GenesisState{ + Pool: staking.InitialPool(), + Params: staking.Params{ UnbondingTime: time.Duration(randIntBetween(r, 60, 60*60*24*3*2)) * time.Second, MaxValidators: uint16(r.Intn(250)), - BondDenom: stakeTypes.DefaultBondDenom, + BondDenom: stakingTypes.DefaultBondDenom, }, } - fmt.Printf("Selected randomly generated staking parameters:\n\t%+v\n", stakeGenesis) + fmt.Printf("Selected randomly generated staking parameters:\n\t%+v\n", stakingGenesis) slashingGenesis := slashing.GenesisState{ Params: slashing.Params{ - MaxEvidenceAge: stakeGenesis.Params.UnbondingTime, - DoubleSignUnbondDuration: time.Duration(randIntBetween(r, 60, 60*60*24)) * time.Second, - SignedBlocksWindow: int64(randIntBetween(r, 10, 1000)), - DowntimeUnbondDuration: time.Duration(randIntBetween(r, 60, 60*60*24)) * time.Second, - MinSignedPerWindow: sdk.NewDecWithPrec(int64(r.Intn(10)), 1), - SlashFractionDoubleSign: sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(50) + 1))), - SlashFractionDowntime: sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200) + 1))), + MaxEvidenceAge: stakingGenesis.Params.UnbondingTime, + SignedBlocksWindow: int64(randIntBetween(r, 10, 1000)), + DowntimeJailDuration: time.Duration(randIntBetween(r, 60, 60*60*24)) * time.Second, + MinSignedPerWindow: sdk.NewDecWithPrec(int64(r.Intn(10)), 1), + SlashFractionDoubleSign: sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(50) + 1))), + SlashFractionDowntime: sdk.NewDec(1).Quo(sdk.NewDec(int64(r.Intn(200) + 1))), }, } fmt.Printf("Selected randomly generated slashing parameters:\n\t%+v\n", slashingGenesis) @@ -133,7 +132,7 @@ func appStateFn(r *rand.Rand, accs []simulation.Account) json.RawMessage { Minter: mint.InitialMinter( sdk.NewDecWithPrec(int64(r.Intn(99)), 2)), Params: mint.NewParams( - stakeTypes.DefaultBondDenom, + stakingTypes.DefaultBondDenom, sdk.NewDecWithPrec(int64(r.Intn(99)), 2), sdk.NewDecWithPrec(20, 2), sdk.NewDecWithPrec(7, 2), @@ -142,29 +141,29 @@ func appStateFn(r *rand.Rand, accs []simulation.Account) json.RawMessage { } fmt.Printf("Selected randomly generated minting parameters:\n\t%+v\n", mintGenesis) - var validators []stake.Validator - var delegations []stake.Delegation + var validators []staking.Validator + var delegations []staking.Delegation valAddrs := make([]sdk.ValAddress, numInitiallyBonded) for i := 0; i < int(numInitiallyBonded); i++ { valAddr := sdk.ValAddress(accs[i].Address) valAddrs[i] = valAddr - validator := stake.NewValidator(valAddr, accs[i].PubKey, stake.Description{}) + validator := staking.NewValidator(valAddr, accs[i].PubKey, staking.Description{}) validator.Tokens = sdk.NewInt(amount) validator.DelegatorShares = sdk.NewDec(amount) - delegation := stake.Delegation{accs[i].Address, valAddr, sdk.NewDec(amount)} + delegation := staking.Delegation{accs[i].Address, valAddr, sdk.NewDec(amount)} validators = append(validators, validator) delegations = append(delegations, delegation) } - stakeGenesis.Pool.LooseTokens = sdk.NewInt((amount * numAccs) + (numInitiallyBonded * amount)) - stakeGenesis.Validators = validators - stakeGenesis.Bonds = delegations + stakingGenesis.Pool.LooseTokens = sdk.NewInt((amount * numAccs) + (numInitiallyBonded * amount)) + stakingGenesis.Validators = validators + stakingGenesis.Bonds = delegations genesis := GenesisState{ Accounts: genesisAccounts, AuthData: authGenesis, - StakeData: stakeGenesis, + StakingData: stakingGenesis, MintData: mintGenesis, DistrData: distr.DefaultGenesisWithValidators(valAddrs), SlashingData: slashingGenesis, @@ -192,13 +191,13 @@ func testAndRunTxs(app *GaiaApp) []simulation.WeightedOperation { {50, distrsim.SimulateMsgWithdrawDelegatorRewardsAll(app.accountKeeper, app.distrKeeper)}, {50, distrsim.SimulateMsgWithdrawDelegatorReward(app.accountKeeper, app.distrKeeper)}, {50, distrsim.SimulateMsgWithdrawValidatorRewardsAll(app.accountKeeper, app.distrKeeper)}, - {5, govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, app.stakeKeeper)}, + {5, govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, app.stakingKeeper)}, {100, govsim.SimulateMsgDeposit(app.govKeeper)}, - {100, stakesim.SimulateMsgCreateValidator(app.accountKeeper, app.stakeKeeper)}, - {5, stakesim.SimulateMsgEditValidator(app.stakeKeeper)}, - {100, stakesim.SimulateMsgDelegate(app.accountKeeper, app.stakeKeeper)}, - {100, stakesim.SimulateMsgBeginUnbonding(app.accountKeeper, app.stakeKeeper)}, - {100, stakesim.SimulateMsgBeginRedelegate(app.accountKeeper, app.stakeKeeper)}, + {100, stakingsim.SimulateMsgCreateValidator(app.accountKeeper, app.stakingKeeper)}, + {5, stakingsim.SimulateMsgEditValidator(app.stakingKeeper)}, + {100, stakingsim.SimulateMsgDelegate(app.accountKeeper, app.stakingKeeper)}, + {100, stakingsim.SimulateMsgBeginUnbonding(app.accountKeeper, app.stakingKeeper)}, + {100, stakingsim.SimulateMsgBeginRedelegate(app.accountKeeper, app.stakingKeeper)}, {100, slashingsim.SimulateMsgUnjail(app.slashingKeeper)}, } } @@ -207,8 +206,8 @@ func invariants(app *GaiaApp) []simulation.Invariant { return []simulation.Invariant{ simulation.PeriodicInvariant(banksim.NonnegativeBalanceInvariant(app.accountKeeper), period, 0), simulation.PeriodicInvariant(govsim.AllInvariants(), period, 0), - simulation.PeriodicInvariant(distrsim.AllInvariants(app.distrKeeper, app.stakeKeeper), period, 0), - simulation.PeriodicInvariant(stakesim.AllInvariants(app.bankKeeper, app.stakeKeeper, + simulation.PeriodicInvariant(distrsim.AllInvariants(app.distrKeeper, app.stakingKeeper), period, 0), + simulation.PeriodicInvariant(stakingsim.AllInvariants(app.bankKeeper, app.stakingKeeper, app.feeCollectionKeeper, app.distrKeeper, app.accountKeeper), period, 0), simulation.PeriodicInvariant(slashingsim.AllInvariants(), period, 0), } @@ -371,7 +370,7 @@ func TestGaiaImportExport(t *testing.T) { storeKeysPrefixes := []StoreKeysPrefixes{ {app.keyMain, newApp.keyMain, [][]byte{}}, {app.keyAccount, newApp.keyAccount, [][]byte{}}, - {app.keyStake, newApp.keyStake, [][]byte{stake.UnbondingQueueKey, stake.RedelegationQueueKey, stake.ValidatorQueueKey}}, // ordering may change but it doesn't matter + {app.keyStaking, newApp.keyStaking, [][]byte{staking.UnbondingQueueKey, staking.RedelegationQueueKey, staking.ValidatorQueueKey}}, // ordering may change but it doesn't matter {app.keySlashing, newApp.keySlashing, [][]byte{}}, {app.keyMint, newApp.keyMint, [][]byte{}}, {app.keyDistr, newApp.keyDistr, [][]byte{}}, diff --git a/cmd/gaia/cli_test/README.md b/cmd/gaia/cli_test/README.md new file mode 100644 index 000000000000..37fd41ce7eff --- /dev/null +++ b/cmd/gaia/cli_test/README.md @@ -0,0 +1,51 @@ +# Gaia CLI Integration tests + +The gaia cli integration tests live in this folder. You can run the full suite by running: + +```bash +$ go test -v -p 4 ./cmd/gaia/cli_test/... +# OR! +$ make test_cli +``` +> NOTE: While the full suite runs in parallel, some of the tests can take up to a minute to complete + +### Test Structure + +This integration suite [uses a thin wrapper](https://godoc.org/github.com/cosmos/cosmos-sdk/tests) over the [`os/exec`](https://golang.org/pkg/os/exec/) package. This allows the integration test to run against built binaries (both `gaiad` and `gaiacli` are used) while being written in golang. This allows tests to take advantage of the various golang code we have for operations like marshal/unmarshal, crypto, etc... + +> NOTE: The tests will use whatever `gaiad` or `gaiacli` binaries are available in your `$PATH`. You can check which binary will be run by the suite by running `which gaiad` or `which gaiacli`. If you have your `$GOPATH` properly setup they should be in `$GOPATH/bin/gaia*`. This will ensure that your test uses the latest binary you have built + +Tests generally follow this structure: + +```go +func TestMyNewCommand(t *testing.T) { + t.Parallel() + f := InitFixtures(t) + + // start gaiad server + proc := f.GDStart() + defer proc.Stop(false) + + // Your test code goes here... + + f.Cleanup() +} +``` + +This boilerplate above: +- Ensures the tests run in parallel. Because the tests are calling out to `os/exec` for many operations these tests can take a long time to run. +- Creates `.gaiad` and `.gaiacli` folders in a new temp folder. +- Uses `gaiacli` to create 2 accounts for use in testing: `foo` and `bar` +- Creates a genesis file with coins (`1000footoken,1000feetoken,150stake`) controlled by the `foo` key +- Generates an initial bonding transaction (`gentx`) to make the `foo` key a validator at genesis +- Starts `gaiad` and stops it once the test exits +- Cleans up test state on a successful run + +### Notes when adding/running tests + +- Because the tests run against a built binary, you should make sure you build every time the code changes and you want to test again, otherwise you will be testing against an older version. If you are adding new tests this can easily lead to confusing test results. +- The [`test_helpers.go`](./test_helpers.go) file is organized according to the format of `gaiacli` and `gaiad` commands. There are comments with section headers describing the different areas. Helper functions to call CLI functionality are generally named after the command (e.g. `gaiacli query staking validator` would be `QueryStakingValidator`). Try to keep functions grouped by their position in the command tree. +- Test state that is needed by `tx` and `query` commands (`home`, `chain_id`, etc...) is stored on the `Fixtures` object. This makes constructing your new tests almost trivial. +- Sometimes if you exit a test early there can be still running `gaiad` and `gaiacli` processes that will interrupt subsequent runs. Still running `gaiacli` processes will block access to the keybase while still running `gaiad` processes will block ports and prevent new tests from spinning up. You can ensure new tests spin up clean by running `pkill -9 gaiad && pkill -9 gaiacli` before each test run. +- Most `query` and `tx` commands take a variadic `flags` argument. This pattern allows for the creation of a general function which is easily modified by adding flags. See the `TxSend` function and its use for a good example. +- `Tx*` functions follow a general pattern and return `(success bool, stdout string, stderr string)`. This allows for easy testing of multiple different flag configurations. See `TestGaiaCLICreateValidator` or `TestGaiaCLISubmitProposal` for a good example of the pattern. diff --git a/cmd/gaia/cli_test/cli_test.go b/cmd/gaia/cli_test/cli_test.go index ad5782dbffcb..398f630ff321 100644 --- a/cmd/gaia/cli_test/cli_test.go +++ b/cmd/gaia/cli_test/cli_test.go @@ -1,345 +1,343 @@ package clitest import ( - "encoding/json" "fmt" "io/ioutil" "os" "path" "path/filepath" "testing" - - "github.com/cosmos/cosmos-sdk/x/slashing" + "time" "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" - cfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/crypto" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/cmd/gaia/app" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/tests" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/stake" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) func TestGaiaCLIMinimumFees(t *testing.T) { t.Parallel() - chainID, servAddr, port, gaiadHome, gaiacliHome, p2pAddr := initializeFixtures(t, nil) - flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", gaiacliHome, servAddr, chainID) + f := InitFixtures(t) // start gaiad server with minimum fees - proc := tests.GoExecuteTWithStdout(t, fmt.Sprintf("gaiad start --home=%s --rpc.laddr=%v --p2p.laddr=%v --minimum_fees=2feetoken", gaiadHome, servAddr, p2pAddr)) - + fees := fmt.Sprintf("--minimum_fees=%s,%s", sdk.NewInt64Coin(feeDenom, 2), sdk.NewInt64Coin(denom, 2)) + proc := f.GDStart(fees) defer proc.Stop(false) - tests.WaitForTMStart(port) - tests.WaitForNextNBlocksTM(1, port) - fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --home=%s", gaiacliHome)) - barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --home=%s", gaiacliHome)) + barAddr := f.KeyAddress(keyBar) + // fooAddr := f.KeyAddress(keyFoo) - fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) + // Check the amount of coins in the foo account to ensure that the right amount exists + fooAcc := f.QueryAccount(f.KeyAddress(keyFoo)) + require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf(denom).Int64()) - success := executeWrite(t, fmt.Sprintf( - "gaiacli tx send %v --amount=10%s --to=%s --from=foo", flags, stakeTypes.DefaultBondDenom, barAddr), app.DefaultKeyPass) - require.False(t, success) - cleanupDirs(gaiadHome, gaiacliHome) + // Send a transaction that will get rejected + success, _, _ := f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10)) + require.False(f.T, success) + tests.WaitForNextNBlocksTM(1, f.Port) + + // Ensure tx w/ correct fees (staking) pass + txFees := fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(denom, 23)) + success, _, _ = f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10), txFees) + require.True(f.T, success) + tests.WaitForNextNBlocksTM(1, f.Port) + + // Ensure tx w/ correct fees (feetoken) pass + txFees = fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(feeDenom, 23)) + success, _, _ = f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(feeDenom, 10), txFees) + require.True(f.T, success) + tests.WaitForNextNBlocksTM(1, f.Port) + + // Ensure tx w/ improper fees (footoken) fails + txFees = fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(fooDenom, 23)) + success, _, _ = f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, 10), txFees) + require.False(f.T, success) + + // Cleanup testing directories + f.Cleanup() } func TestGaiaCLIFeesDeduction(t *testing.T) { t.Parallel() - chainID, servAddr, port, gaiadHome, gaiacliHome, p2pAddr := initializeFixtures(t, nil) - flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", gaiacliHome, servAddr, chainID) + f := InitFixtures(t) // start gaiad server with minimum fees - proc := tests.GoExecuteTWithStdout(t, fmt.Sprintf("gaiad start --home=%s --rpc.laddr=%v --p2p.laddr=%v --minimum_fees=1footoken", gaiadHome, servAddr, p2pAddr)) - + proc := f.GDStart(fmt.Sprintf("--minimum_fees=%s", sdk.NewInt64Coin(fooDenom, 1))) defer proc.Stop(false) - tests.WaitForTMStart(port) - tests.WaitForNextNBlocksTM(1, port) - fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --home=%s", gaiacliHome)) - barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --home=%s", gaiacliHome)) + // Save key addresses for later use + fooAddr := f.KeyAddress(keyFoo) + barAddr := f.KeyAddress(keyBar) - fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(1000), fooAcc.GetCoins().AmountOf("footoken").Int64()) + fooAcc := f.QueryAccount(fooAddr) + require.Equal(t, int64(1000), fooAcc.GetCoins().AmountOf(fooDenom).Int64()) // test simulation - success := executeWrite(t, fmt.Sprintf( - "gaiacli tx send %v --amount=1000footoken --to=%s --from=foo --fees=1footoken --dry-run", flags, barAddr), app.DefaultKeyPass) + success, _, _ := f.TxSend( + keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, 1000), + fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(fooDenom, 1)), "--dry-run") require.True(t, success) - tests.WaitForNextNBlocksTM(1, port) + + // Wait for a block + tests.WaitForNextNBlocksTM(1, f.Port) + // ensure state didn't change - fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(1000), fooAcc.GetCoins().AmountOf("footoken").Int64()) + fooAcc = f.QueryAccount(fooAddr) + require.Equal(t, int64(1000), fooAcc.GetCoins().AmountOf(fooDenom).Int64()) - // insufficient funds (coins + fees) - success = executeWrite(t, fmt.Sprintf( - "gaiacli tx send %v --amount=1000footoken --to=%s --from=foo --fees=1footoken", flags, barAddr), app.DefaultKeyPass) + // insufficient funds (coins + fees) tx fails + success, _, _ = f.TxSend( + keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, 1000), + fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(fooDenom, 1))) require.False(t, success) - tests.WaitForNextNBlocksTM(1, port) + + // Wait for a block + tests.WaitForNextNBlocksTM(1, f.Port) + // ensure state didn't change - fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(1000), fooAcc.GetCoins().AmountOf("footoken").Int64()) + fooAcc = f.QueryAccount(fooAddr) + require.Equal(t, int64(1000), fooAcc.GetCoins().AmountOf(fooDenom).Int64()) // test success (transfer = coins + fees) - success = executeWrite(t, fmt.Sprintf( - "gaiacli tx send %v --fees=300footoken --amount=500footoken --to=%s --from=foo", flags, barAddr), app.DefaultKeyPass) + success, _, _ = f.TxSend( + keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, 500), + fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(fooDenom, 300))) require.True(t, success) - cleanupDirs(gaiadHome, gaiacliHome) + + f.Cleanup() } func TestGaiaCLISend(t *testing.T) { t.Parallel() - chainID, servAddr, port, gaiadHome, gaiacliHome, p2pAddr := initializeFixtures(t, nil) - flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", gaiacliHome, servAddr, chainID) + f := InitFixtures(t) // start gaiad server - proc := tests.GoExecuteTWithStdout(t, fmt.Sprintf("gaiad start --home=%s --rpc.laddr=%v --p2p.laddr=%v", gaiadHome, servAddr, p2pAddr)) + proc := f.GDStart() defer proc.Stop(false) - tests.WaitForTMStart(port) - tests.WaitForNextNBlocksTM(1, port) - fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --home=%s", gaiacliHome)) - barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --home=%s", gaiacliHome)) + // Save key addresses for later use + fooAddr := f.KeyAddress(keyFoo) + barAddr := f.KeyAddress(keyBar) - fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) + fooAcc := f.QueryAccount(fooAddr) + require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf(denom).Int64()) - executeWrite(t, fmt.Sprintf("gaiacli tx send %v --amount=10%s --to=%s --from=foo", flags, stakeTypes.DefaultBondDenom, barAddr), app.DefaultKeyPass) - tests.WaitForNextNBlocksTM(1, port) + // Send some tokens from one account to the other + f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10)) + tests.WaitForNextNBlocksTM(1, f.Port) - barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", barAddr, flags)) - require.Equal(t, int64(10), barAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) - fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) + // Ensure account balances match expected + barAcc := f.QueryAccount(barAddr) + require.Equal(t, int64(10), barAcc.GetCoins().AmountOf(denom).Int64()) + fooAcc = f.QueryAccount(fooAddr) + require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf(denom).Int64()) // Test --dry-run - success := executeWrite(t, fmt.Sprintf("gaiacli tx send %v --amount=10%s --to=%s --from=foo --dry-run", flags, stakeTypes.DefaultBondDenom, barAddr), app.DefaultKeyPass) + success, _, _ := f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10), "--dry-run") require.True(t, success) + // Check state didn't change - fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) + fooAcc = f.QueryAccount(fooAddr) + require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf(denom).Int64()) // test autosequencing - executeWrite(t, fmt.Sprintf("gaiacli tx send %v --amount=10%s --to=%s --from=foo", flags, stakeTypes.DefaultBondDenom, barAddr), app.DefaultKeyPass) - tests.WaitForNextNBlocksTM(1, port) + f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10)) + tests.WaitForNextNBlocksTM(1, f.Port) - barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", barAddr, flags)) - require.Equal(t, int64(20), barAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) - fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(30), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) + // Ensure account balances match expected + barAcc = f.QueryAccount(barAddr) + require.Equal(t, int64(20), barAcc.GetCoins().AmountOf(denom).Int64()) + fooAcc = f.QueryAccount(fooAddr) + require.Equal(t, int64(30), fooAcc.GetCoins().AmountOf(denom).Int64()) // test memo - executeWrite(t, fmt.Sprintf("gaiacli tx send %v --amount=10%s --to=%s --from=foo --memo 'testmemo'", flags, stakeTypes.DefaultBondDenom, barAddr), app.DefaultKeyPass) - tests.WaitForNextNBlocksTM(1, port) - - barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", barAddr, flags)) - require.Equal(t, int64(30), barAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) - fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(20), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) - cleanupDirs(gaiadHome, gaiacliHome) + f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10), "--memo='testmemo'") + tests.WaitForNextNBlocksTM(1, f.Port) + + // Ensure account balances match expected + barAcc = f.QueryAccount(barAddr) + require.Equal(t, int64(30), barAcc.GetCoins().AmountOf(denom).Int64()) + fooAcc = f.QueryAccount(fooAddr) + require.Equal(t, int64(20), fooAcc.GetCoins().AmountOf(denom).Int64()) + + f.Cleanup() } func TestGaiaCLIGasAuto(t *testing.T) { t.Parallel() - chainID, servAddr, port, gaiadHome, gaiacliHome, p2pAddr := initializeFixtures(t, nil) - flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", gaiacliHome, servAddr, chainID) + f := InitFixtures(t) // start gaiad server - proc := tests.GoExecuteTWithStdout(t, fmt.Sprintf("gaiad start --home=%s --rpc.laddr=%v --p2p.laddr=%v", gaiadHome, servAddr, p2pAddr)) - + proc := f.GDStart() defer proc.Stop(false) - tests.WaitForTMStart(port) - tests.WaitForNextNBlocksTM(1, port) - fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --home=%s", gaiacliHome)) - barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --home=%s", gaiacliHome)) + fooAddr := f.KeyAddress(keyFoo) + barAddr := f.KeyAddress(keyBar) - fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) + fooAcc := f.QueryAccount(fooAddr) + require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf(denom).Int64()) // Test failure with auto gas disabled and very little gas set by hand - success := executeWrite(t, fmt.Sprintf("gaiacli tx send %v --gas=10 --amount=10%s --to=%s --from=foo", flags, stakeTypes.DefaultBondDenom, barAddr), app.DefaultKeyPass) + success, _, _ := f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10), "--gas=10") require.False(t, success) - tests.WaitForNextNBlocksTM(1, port) + // Check state didn't change - fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) + fooAcc = f.QueryAccount(fooAddr) + require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf(denom).Int64()) // Test failure with negative gas - success = executeWrite(t, fmt.Sprintf("gaiacli tx send %v --gas=-100 --amount=10%s --to=%s --from=foo", flags, stakeTypes.DefaultBondDenom, barAddr), app.DefaultKeyPass) + success, _, _ = f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10), "--gas=-100") require.False(t, success) + // Check state didn't change + fooAcc = f.QueryAccount(fooAddr) + require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf(denom).Int64()) + // Test failure with 0 gas - success = executeWrite(t, fmt.Sprintf("gaiacli tx send %v --gas=0 --amount=10%s --to=%s --from=foo", flags, stakeTypes.DefaultBondDenom, barAddr), app.DefaultKeyPass) + success, _, _ = f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10), "--gas=0") require.False(t, success) + // Check state didn't change + fooAcc = f.QueryAccount(fooAddr) + require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf(denom).Int64()) + // Enable auto gas - success, stdout, _ := executeWriteRetStdStreams(t, fmt.Sprintf("gaiacli tx send %v --json --gas=auto --amount=10%s --to=%s --from=foo", flags, stakeTypes.DefaultBondDenom, barAddr), app.DefaultKeyPass) + success, stdout, stderr := f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10), "--gas=auto", "--json") + require.NotEmpty(t, stderr) require.True(t, success) - // check that gas wanted == gas used cdc := app.MakeCodec() - jsonOutput := struct { + sendResp := struct { Height int64 TxHash string Response abci.ResponseDeliverTx }{} - require.Nil(t, cdc.UnmarshalJSON([]byte(stdout), &jsonOutput)) - require.Equal(t, jsonOutput.Response.GasWanted, jsonOutput.Response.GasUsed) - tests.WaitForNextNBlocksTM(1, port) + err := cdc.UnmarshalJSON([]byte(stdout), &sendResp) + require.Nil(t, err) + require.Equal(t, sendResp.Response.GasWanted, sendResp.Response.GasUsed) + tests.WaitForNextNBlocksTM(1, f.Port) + // Check state has changed accordingly - fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) - cleanupDirs(gaiadHome, gaiacliHome) + fooAcc = f.QueryAccount(fooAddr) + require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf(denom).Int64()) + + f.Cleanup() } func TestGaiaCLICreateValidator(t *testing.T) { t.Parallel() - chainID, servAddr, port, gaiadHome, gaiacliHome, p2pAddr := initializeFixtures(t, nil) - flags := fmt.Sprintf("--home=%s --chain-id=%v --node=%s", gaiacliHome, chainID, servAddr) + f := InitFixtures(t) // start gaiad server - proc := tests.GoExecuteTWithStdout(t, fmt.Sprintf("gaiad start --home=%s --rpc.laddr=%v --p2p.laddr=%v", gaiadHome, servAddr, p2pAddr)) - + proc := f.GDStart() defer proc.Stop(false) - tests.WaitForTMStart(port) - tests.WaitForNextNBlocksTM(1, port) - fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --home=%s", gaiacliHome)) - barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --home=%s", gaiacliHome)) - consPubKey := sdk.MustBech32ifyConsPub(ed25519.GenPrivKey().PubKey()) + fooAddr := f.KeyAddress(keyFoo) + barAddr := f.KeyAddress(keyBar) + barVal := sdk.ValAddress(barAddr) - executeWrite(t, fmt.Sprintf("gaiacli tx send %v --amount=10%s --to=%s --from=foo", flags, stakeTypes.DefaultBondDenom, barAddr), app.DefaultKeyPass) - tests.WaitForNextNBlocksTM(1, port) + consPubKey := sdk.MustBech32ifyConsPub(ed25519.GenPrivKey().PubKey()) - barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", barAddr, flags)) - require.Equal(t, int64(10), barAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) - fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) + f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10)) + tests.WaitForNextNBlocksTM(1, f.Port) - defaultParams := stake.DefaultParams() - initialPool := stake.InitialPool() - initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewInt(100)) // Delegate tx on GaiaAppGenState + barAcc := f.QueryAccount(barAddr) + require.Equal(t, int64(10), barAcc.GetCoins().AmountOf(denom).Int64()) + fooAcc := f.QueryAccount(fooAddr) + require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf(denom).Int64()) - // create validator - cvStr := fmt.Sprintf("gaiacli tx stake create-validator %v", flags) - cvStr += fmt.Sprintf(" --from=%s", "bar") - cvStr += fmt.Sprintf(" --pubkey=%s", consPubKey) - cvStr += fmt.Sprintf(" --amount=%v", fmt.Sprintf("2%s", stakeTypes.DefaultBondDenom)) - cvStr += fmt.Sprintf(" --moniker=%v", "bar-vally") - cvStr += fmt.Sprintf(" --commission-rate=%v", "0.05") - cvStr += fmt.Sprintf(" --commission-max-rate=%v", "0.20") - cvStr += fmt.Sprintf(" --commission-max-change-rate=%v", "0.10") + defaultParams := staking.DefaultParams() + initialPool := staking.InitialPool() + initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewInt(101)) // Delegate tx on GaiaAppGenState - initialPool.BondedTokens = initialPool.BondedTokens.Add(sdk.NewInt(1)) + // Generate a create validator transaction and ensure correctness + success, stdout, stderr := f.TxStakingCreateValidator(keyBar, consPubKey, sdk.NewInt64Coin(denom, 2), "--generate-only") - // Test --generate-only - success, stdout, stderr := executeWriteRetStdStreams(t, cvStr+" --generate-only", app.DefaultKeyPass) - require.True(t, success) - require.True(t, success) - require.Empty(t, stderr) - msg := unmarshalStdTx(t, stdout) + require.True(f.T, success) + require.Empty(f.T, stderr) + msg := unmarshalStdTx(f.T, stdout) require.NotZero(t, msg.Fee.Gas) require.Equal(t, len(msg.Msgs), 1) require.Equal(t, 0, len(msg.GetSignatures())) // Test --dry-run - success = executeWrite(t, cvStr+" --dry-run", app.DefaultKeyPass) + success, _, _ = f.TxStakingCreateValidator(keyBar, consPubKey, sdk.NewInt64Coin(denom, 2), "--dry-run") require.True(t, success) - executeWrite(t, cvStr, app.DefaultKeyPass) - tests.WaitForNextNBlocksTM(1, port) + // Create the validator + f.TxStakingCreateValidator(keyBar, consPubKey, sdk.NewInt64Coin(denom, 2)) + tests.WaitForNextNBlocksTM(1, f.Port) - barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", barAddr, flags)) - require.Equal(t, int64(8), barAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64(), "%v", barAcc) + // Ensure funds were deducted properly + barAcc = f.QueryAccount(barAddr) + require.Equal(t, int64(8), barAcc.GetCoins().AmountOf(denom).Int64()) - validator := executeGetValidator(t, fmt.Sprintf("gaiacli query stake validator %s %v", sdk.ValAddress(barAddr), flags)) - require.Equal(t, validator.OperatorAddr, sdk.ValAddress(barAddr)) + // Ensure that validator state is as expected + validator := f.QueryStakingValidator(barVal) + require.Equal(t, validator.OperatorAddr, barVal) require.True(sdk.IntEq(t, sdk.NewInt(2), validator.Tokens)) - validatorDelegations := executeGetValidatorDelegations(t, fmt.Sprintf("gaiacli query stake delegations-to %s %v", sdk.ValAddress(barAddr), flags)) + // Query delegations to the validator + validatorDelegations := f.QueryStakingDelegationsTo(barVal) require.Len(t, validatorDelegations, 1) require.NotZero(t, validatorDelegations[0].Shares) // unbond a single share - unbondStr := fmt.Sprintf("gaiacli tx stake unbond %v", flags) - unbondStr += fmt.Sprintf(" --from=%s", "bar") - unbondStr += fmt.Sprintf(" --validator=%s", sdk.ValAddress(barAddr)) - unbondStr += fmt.Sprintf(" --shares-amount=%v", "1") - - success = executeWrite(t, unbondStr, app.DefaultKeyPass) + success = f.TxStakingUnbond(keyBar, "1", barVal) require.True(t, success) - tests.WaitForNextNBlocksTM(1, port) + tests.WaitForNextNBlocksTM(1, f.Port) - /* // this won't be what we expect because we've only started unbonding, haven't completed - barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %v %v", barCech, flags)) - require.Equal(t, int64(9), barAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64(), "%v", barAcc) - */ - validator = executeGetValidator(t, fmt.Sprintf("gaiacli query stake validator %s %v", sdk.ValAddress(barAddr), flags)) + // Ensure bonded staking is correct + validator = f.QueryStakingValidator(barVal) require.Equal(t, "1", validator.Tokens.String()) - validatorUbds := executeGetValidatorUnbondingDelegations(t, - fmt.Sprintf("gaiacli query stake unbonding-delegations-from %s %v", sdk.ValAddress(barAddr), flags)) + // Get unbonding delegations from the validator + validatorUbds := f.QueryStakingUnbondingDelegationsFrom(barVal) require.Len(t, validatorUbds, 1) require.Equal(t, "1", validatorUbds[0].Balance.Amount.String()) - params := executeGetParams(t, fmt.Sprintf("gaiacli query stake parameters %v", flags)) + // Query staking parameters + params := f.QueryStakingParameters() require.True(t, defaultParams.Equal(params)) - pool := executeGetPool(t, fmt.Sprintf("gaiacli query stake pool %v", flags)) + // Query staking pool + pool := f.QueryStakingPool() require.Equal(t, initialPool.BondedTokens, pool.BondedTokens) - cleanupDirs(gaiadHome, gaiacliHome) + + f.Cleanup() } func TestGaiaCLISubmitProposal(t *testing.T) { t.Parallel() - chainID, servAddr, port, gaiadHome, gaiacliHome, p2pAddr := initializeFixtures(t, nil) - flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", gaiacliHome, servAddr, chainID) + f := InitFixtures(t) // start gaiad server - proc := tests.GoExecuteTWithStdout(t, fmt.Sprintf("gaiad start --home=%s --rpc.laddr=%v --p2p.laddr=%v", gaiadHome, servAddr, p2pAddr)) - + proc := f.GDStart() defer proc.Stop(false) - tests.WaitForTMStart(port) - tests.WaitForNextNBlocksTM(1, port) - executeGetDepositParam(t, fmt.Sprintf("gaiacli query gov param deposit %v", flags)) - executeGetVotingParam(t, fmt.Sprintf("gaiacli query gov param voting %v", flags)) - executeGetTallyingParam(t, fmt.Sprintf("gaiacli query gov param tallying %v", flags)) + f.QueryGovParamDeposit() + f.QueryGovParamVoting() + f.QueryGovParamTallying() - fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --home=%s", gaiacliHome)) + fooAddr := f.KeyAddress(keyFoo) - fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) + fooAcc := f.QueryAccount(fooAddr) + require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf(stakingTypes.DefaultBondDenom).Int64()) - proposalsQuery, _ := tests.ExecuteT(t, fmt.Sprintf("gaiacli query gov proposals %v", flags), "") + proposalsQuery := f.QueryGovProposals() require.Equal(t, "No matching proposals found", proposalsQuery) - // submit a test proposal - spStr := fmt.Sprintf("gaiacli tx gov submit-proposal %v", flags) - spStr += fmt.Sprintf(" --from=%s", "foo") - spStr += fmt.Sprintf(" --deposit=%s", fmt.Sprintf("5%s", stakeTypes.DefaultBondDenom)) - spStr += fmt.Sprintf(" --type=%s", "Text") - spStr += fmt.Sprintf(" --title=%s", "Test") - spStr += fmt.Sprintf(" --description=%s", "test") - - // Test generate only - success, stdout, stderr := executeWriteRetStdStreams(t, spStr+" --generate-only", app.DefaultKeyPass) - require.True(t, success) + // Test submit generate only for submit proposal + success, stdout, stderr := f.TxGovSubmitProposal( + keyFoo, "Text", "Test", "test", sdk.NewInt64Coin(denom, 5), "--generate-only") require.True(t, success) require.Empty(t, stderr) msg := unmarshalStdTx(t, stdout) @@ -348,35 +346,36 @@ func TestGaiaCLISubmitProposal(t *testing.T) { require.Equal(t, 0, len(msg.GetSignatures())) // Test --dry-run - success = executeWrite(t, spStr+" --dry-run", app.DefaultKeyPass) + success, _, _ = f.TxGovSubmitProposal(keyFoo, "Text", "Test", "test", sdk.NewInt64Coin(denom, 5), "--dry-run") require.True(t, success) - executeWrite(t, spStr, app.DefaultKeyPass) - tests.WaitForNextNBlocksTM(1, port) + // Create the proposal + f.TxGovSubmitProposal(keyFoo, "Text", "Test", "test", sdk.NewInt64Coin(denom, 5)) + tests.WaitForNextNBlocksTM(1, f.Port) - txs := executeGetTxs(t, fmt.Sprintf("gaiacli query txs --tags='action:submit_proposal&proposer:%s' %v", fooAddr, flags)) + // Ensure transaction tags can be queried + txs := f.QueryTxs("action:submit_proposal", fmt.Sprintf("proposer:%s", fooAddr)) require.Len(t, txs, 1) - fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(45), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) + // Ensure deposit was deducted + fooAcc = f.QueryAccount(fooAddr) + require.Equal(t, int64(45), fooAcc.GetCoins().AmountOf(denom).Int64()) - proposal1 := executeGetProposal(t, fmt.Sprintf("gaiacli query gov proposal 1 %v", flags)) + // Ensure propsal is directly queryable + proposal1 := f.QueryGovProposal(1) require.Equal(t, uint64(1), proposal1.GetProposalID()) require.Equal(t, gov.StatusDepositPeriod, proposal1.GetStatus()) - proposalsQuery, _ = tests.ExecuteT(t, fmt.Sprintf("gaiacli query gov proposals %v", flags), "") + // Ensure query proposals returns properly + proposalsQuery = f.QueryGovProposals() require.Equal(t, " 1 - Test", proposalsQuery) - deposit := executeGetDeposit(t, - fmt.Sprintf("gaiacli query gov deposit 1 %s %v", fooAddr, flags)) - require.Equal(t, int64(5), deposit.Amount.AmountOf(stakeTypes.DefaultBondDenom).Int64()) + // Query the deposits on the proposal + deposit := f.QueryGovDeposit(1, fooAddr) + require.Equal(t, int64(5), deposit.Amount.AmountOf(denom).Int64()) - depositStr := fmt.Sprintf("gaiacli tx gov deposit 1 %s %v", fmt.Sprintf("10%s", stakeTypes.DefaultBondDenom), flags) - depositStr += fmt.Sprintf(" --from=%s", "foo") - - // Test generate only - success, stdout, stderr = executeWriteRetStdStreams(t, depositStr+" --generate-only", app.DefaultKeyPass) - require.True(t, success) + // Test deposit generate only + success, stdout, stderr = f.TxGovDeposit(1, keyFoo, sdk.NewInt64Coin(denom, 10), "--generate-only") require.True(t, success) require.Empty(t, stderr) msg = unmarshalStdTx(t, stdout) @@ -384,34 +383,34 @@ func TestGaiaCLISubmitProposal(t *testing.T) { require.Equal(t, len(msg.Msgs), 1) require.Equal(t, 0, len(msg.GetSignatures())) - executeWrite(t, depositStr, app.DefaultKeyPass) - tests.WaitForNextNBlocksTM(1, port) + // Run the deposit transaction + f.TxGovDeposit(1, keyFoo, sdk.NewInt64Coin(denom, 10)) + tests.WaitForNextNBlocksTM(1, f.Port) // test query deposit - deposits := executeGetDeposits(t, fmt.Sprintf("gaiacli query gov deposits 1 %v", flags)) + deposits := f.QueryGovDeposits(1) require.Len(t, deposits, 1) - require.Equal(t, int64(15), deposits[0].Amount.AmountOf(stakeTypes.DefaultBondDenom).Int64()) + require.Equal(t, int64(15), deposits[0].Amount.AmountOf(denom).Int64()) - deposit = executeGetDeposit(t, - fmt.Sprintf("gaiacli query gov deposit 1 %s %v", fooAddr, flags)) - require.Equal(t, int64(15), deposit.Amount.AmountOf(stakeTypes.DefaultBondDenom).Int64()) + // Ensure querying the deposit returns the proper amount + deposit = f.QueryGovDeposit(1, fooAddr) + require.Equal(t, int64(15), deposit.Amount.AmountOf(denom).Int64()) - txs = executeGetTxs(t, fmt.Sprintf("gaiacli query txs --tags=action:deposit&depositor:%s %v", fooAddr, flags)) + // Ensure tags are set on the transaction + txs = f.QueryTxs("action:deposit", fmt.Sprintf("depositor:%s", fooAddr)) require.Len(t, txs, 1) - fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) + // Ensure account has expected amount of funds + fooAcc = f.QueryAccount(fooAddr) + require.Equal(t, int64(35), fooAcc.GetCoins().AmountOf(denom).Int64()) - require.Equal(t, int64(35), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) - proposal1 = executeGetProposal(t, fmt.Sprintf("gaiacli query gov proposal 1 %v", flags)) + // Fetch the proposal and ensure it is now in the voting period + proposal1 = f.QueryGovProposal(1) require.Equal(t, uint64(1), proposal1.GetProposalID()) require.Equal(t, gov.StatusVotingPeriod, proposal1.GetStatus()) - voteStr := fmt.Sprintf("gaiacli tx gov vote 1 Yes %v", flags) - voteStr += fmt.Sprintf(" --from=%s", "foo") - - // Test generate only - success, stdout, stderr = executeWriteRetStdStreams(t, voteStr+" --generate-only", app.DefaultKeyPass) - require.True(t, success) + // Test vote generate only + success, stdout, stderr = f.TxGovVote(1, gov.OptionYes, keyFoo, "--generate-only") require.True(t, success) require.Empty(t, stderr) msg = unmarshalStdTx(t, stdout) @@ -419,70 +418,57 @@ func TestGaiaCLISubmitProposal(t *testing.T) { require.Equal(t, len(msg.Msgs), 1) require.Equal(t, 0, len(msg.GetSignatures())) - executeWrite(t, voteStr, app.DefaultKeyPass) - tests.WaitForNextNBlocksTM(1, port) + // Vote on the proposal + f.TxGovVote(1, gov.OptionYes, keyFoo) + tests.WaitForNextNBlocksTM(1, f.Port) - vote := executeGetVote(t, fmt.Sprintf("gaiacli query gov vote 1 %s %v", fooAddr, flags)) + // Query the vote + vote := f.QueryGovVote(1, fooAddr) require.Equal(t, uint64(1), vote.ProposalID) require.Equal(t, gov.OptionYes, vote.Option) - votes := executeGetVotes(t, fmt.Sprintf("gaiacli query gov votes 1 %v", flags)) + // Query the votes + votes := f.QueryGovVotes(1) require.Len(t, votes, 1) require.Equal(t, uint64(1), votes[0].ProposalID) require.Equal(t, gov.OptionYes, votes[0].Option) - txs = executeGetTxs(t, fmt.Sprintf("gaiacli query txs --tags=action:vote&voter:%s %v", fooAddr, flags)) + // Ensure tags are applied to voting transaction properly + txs = f.QueryTxs("action:vote", fmt.Sprintf("voter:%s", fooAddr)) require.Len(t, txs, 1) - proposalsQuery, _ = tests.ExecuteT(t, fmt.Sprintf("gaiacli query gov proposals --status=DepositPeriod %v", flags), "") + // Ensure no proposals in deposit period + proposalsQuery = f.QueryGovProposals("--status=DepositPeriod") require.Equal(t, "No matching proposals found", proposalsQuery) - proposalsQuery, _ = tests.ExecuteT(t, fmt.Sprintf("gaiacli query gov proposals --status=VotingPeriod %v", flags), "") + // Ensure the proposal returns as in the voting period + proposalsQuery = f.QueryGovProposals("--status=VotingPeriod") require.Equal(t, " 1 - Test", proposalsQuery) // submit a second test proposal - spStr = fmt.Sprintf("gaiacli tx gov submit-proposal %v", flags) - spStr += fmt.Sprintf(" --from=%s", "foo") - spStr += fmt.Sprintf(" --deposit=%s", fmt.Sprintf("5%s", stakeTypes.DefaultBondDenom)) - spStr += fmt.Sprintf(" --type=%s", "Text") - spStr += fmt.Sprintf(" --title=%s", "Apples") - spStr += fmt.Sprintf(" --description=%s", "test") - - executeWrite(t, spStr, app.DefaultKeyPass) - tests.WaitForNextNBlocksTM(1, port) + f.TxGovSubmitProposal(keyFoo, "Text", "Apples", "test", sdk.NewInt64Coin(denom, 5)) + tests.WaitForNextNBlocksTM(1, f.Port) - proposalsQuery, _ = tests.ExecuteT(t, fmt.Sprintf("gaiacli query gov proposals --limit=1 %v", flags), "") + // Test limit on proposals query + proposalsQuery = f.QueryGovProposals("--limit=1") require.Equal(t, " 2 - Apples", proposalsQuery) - cleanupDirs(gaiadHome, gaiacliHome) + + f.Cleanup() } func TestGaiaCLIValidateSignatures(t *testing.T) { t.Parallel() - chainID, servAddr, port, gaiadHome, gaiacliHome, p2pAddr := initializeFixtures(t, nil) - flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", gaiacliHome, servAddr, chainID) + f := InitFixtures(t) // start gaiad server - proc := tests.GoExecuteTWithStdout( - t, fmt.Sprintf( - "gaiad start --home=%s --rpc.laddr=%v --p2p.laddr=%v", gaiadHome, servAddr, p2pAddr, - ), - ) - + proc := f.GDStart() defer proc.Stop(false) - tests.WaitForTMStart(port) - tests.WaitForNextNBlocksTM(1, port) - fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --home=%s", gaiacliHome)) - barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --home=%s", gaiacliHome)) + fooAddr := f.KeyAddress(keyFoo) + barAddr := f.KeyAddress(keyBar) // generate sendTx with default gas - success, stdout, stderr := executeWriteRetStdStreams( - t, fmt.Sprintf( - "gaiacli tx send %v --amount=10%s --to=%s --from=foo --generate-only", - flags, stakeTypes.DefaultBondDenom, barAddr, - ), - []string{}..., - ) + success, stdout, stderr := f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10), "--generate-only") require.True(t, success) require.Empty(t, stderr) @@ -491,12 +477,9 @@ func TestGaiaCLIValidateSignatures(t *testing.T) { defer os.Remove(unsignedTxFile.Name()) // validate we can successfully sign - success, stdout, _ = executeWriteRetStdStreams( - t, fmt.Sprintf("gaiacli tx sign %v --name=foo %v", flags, unsignedTxFile.Name()), - app.DefaultKeyPass, - ) + success, stdout, stderr = f.TxSign(keyFoo, unsignedTxFile.Name()) require.True(t, success) - + require.Empty(t, stderr) stdTx := unmarshalStdTx(t, stdout) require.Equal(t, len(stdTx.Msgs), 1) require.Equal(t, 1, len(stdTx.GetSignatures())) @@ -507,9 +490,7 @@ func TestGaiaCLIValidateSignatures(t *testing.T) { defer os.Remove(signedTxFile.Name()) // validate signatures - success, _, _ = executeWriteRetStdStreams( - t, fmt.Sprintf("gaiacli tx sign %v --validate-signatures %v", flags, signedTxFile.Name()), - ) + success, _, _ = f.TxSign(keyFoo, signedTxFile.Name(), "--validate-signatures") require.True(t, success) // modify the transaction @@ -519,31 +500,25 @@ func TestGaiaCLIValidateSignatures(t *testing.T) { defer os.Remove(modSignedTxFile.Name()) // validate signature validation failure due to different transaction sig bytes - success, _, _ = executeWriteRetStdStreams( - t, fmt.Sprintf("gaiacli tx sign %v --validate-signatures %v", flags, modSignedTxFile.Name()), - ) + success, _, _ = f.TxSign(keyFoo, modSignedTxFile.Name(), "--validate-signatures") require.False(t, success) + + f.Cleanup() } func TestGaiaCLISendGenerateSignAndBroadcast(t *testing.T) { t.Parallel() - chainID, servAddr, port, gaiadHome, gaiacliHome, p2pAddr := initializeFixtures(t, nil) - flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", gaiacliHome, servAddr, chainID) + f := InitFixtures(t) // start gaiad server - proc := tests.GoExecuteTWithStdout(t, fmt.Sprintf("gaiad start --home=%s --rpc.laddr=%v --p2p.laddr=%v", gaiadHome, servAddr, p2pAddr)) - + proc := f.GDStart() defer proc.Stop(false) - tests.WaitForTMStart(port) - tests.WaitForNextNBlocksTM(1, port) - fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --home=%s", gaiacliHome)) - barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --home=%s", gaiacliHome)) + fooAddr := f.KeyAddress(keyFoo) + barAddr := f.KeyAddress(keyBar) // Test generate sendTx with default gas - success, stdout, stderr := executeWriteRetStdStreams(t, fmt.Sprintf( - "gaiacli tx send %v --amount=10%s --to=%s --from=foo --generate-only", - flags, stakeTypes.DefaultBondDenom, barAddr), []string{}...) + success, stdout, stderr := f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10), "--generate-only") require.True(t, success) require.Empty(t, stderr) msg := unmarshalStdTx(t, stdout) @@ -552,9 +527,7 @@ func TestGaiaCLISendGenerateSignAndBroadcast(t *testing.T) { require.Equal(t, 0, len(msg.GetSignatures())) // Test generate sendTx with --gas=$amount - success, stdout, stderr = executeWriteRetStdStreams(t, fmt.Sprintf( - "gaiacli tx send %v --amount=10%s --to=%s --from=foo --gas=100 --generate-only", - flags, stakeTypes.DefaultBondDenom, barAddr), []string{}...) + success, stdout, stderr = f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10), "--gas=100", "--generate-only") require.True(t, success) require.Empty(t, stderr) msg = unmarshalStdTx(t, stdout) @@ -563,9 +536,7 @@ func TestGaiaCLISendGenerateSignAndBroadcast(t *testing.T) { require.Equal(t, 0, len(msg.GetSignatures())) // Test generate sendTx, estimate gas - success, stdout, stderr = executeWriteRetStdStreams(t, fmt.Sprintf( - "gaiacli tx send %v --amount=10%s --to=%s --from=foo --gas=auto --generate-only", - flags, stakeTypes.DefaultBondDenom, barAddr), []string{}...) + success, stdout, stderr = f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(denom, 10), "--gas=auto", "--generate-only") require.True(t, success) require.NotEmpty(t, stderr) msg = unmarshalStdTx(t, stdout) @@ -577,14 +548,12 @@ func TestGaiaCLISendGenerateSignAndBroadcast(t *testing.T) { defer os.Remove(unsignedTxFile.Name()) // Test sign --validate-signatures - success, stdout, _ = executeWriteRetStdStreams(t, fmt.Sprintf( - "gaiacli tx sign %v --validate-signatures %v", flags, unsignedTxFile.Name())) + success, stdout, _ = f.TxSign(keyFoo, unsignedTxFile.Name(), "--validate-signatures", "--json") require.False(t, success) require.Equal(t, fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n\n", fooAddr.String()), stdout) // Test sign - success, stdout, _ = executeWriteRetStdStreams(t, fmt.Sprintf( - "gaiacli tx sign %v --name=foo %v", flags, unsignedTxFile.Name()), app.DefaultKeyPass) + success, stdout, _ = f.TxSign(keyFoo, unsignedTxFile.Name()) require.True(t, success) msg = unmarshalStdTx(t, stdout) require.Equal(t, len(msg.Msgs), 1) @@ -595,491 +564,110 @@ func TestGaiaCLISendGenerateSignAndBroadcast(t *testing.T) { signedTxFile := writeToNewTempFile(t, stdout) defer os.Remove(signedTxFile.Name()) - // Test sign --print-signatures - success, stdout, _ = executeWriteRetStdStreams(t, fmt.Sprintf( - "gaiacli tx sign %v --validate-signatures %v", flags, signedTxFile.Name())) + // Test sign --validate-signatures + success, stdout, _ = f.TxSign(keyFoo, signedTxFile.Name(), "--validate-signatures", "--json") require.True(t, success) require.Equal(t, fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n 0: %v\t[OK]\n\n", fooAddr.String(), fooAddr.String()), stdout) - // Test broadcast - fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) + // Ensure foo has right amount of funds + fooAcc := f.QueryAccount(fooAddr) + require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf(denom).Int64()) - success, stdout, _ = executeWriteRetStdStreams(t, fmt.Sprintf( - "gaiacli tx broadcast %v --json %v", flags, signedTxFile.Name())) + // Test broadcast + success, stdout, _ = f.TxBroadcast(signedTxFile.Name()) require.True(t, success) var result struct { Response abci.ResponseDeliverTx } + // Unmarshal the response and ensure that gas was properly used require.Nil(t, app.MakeCodec().UnmarshalJSON([]byte(stdout), &result)) require.Equal(t, msg.Fee.Gas, uint64(result.Response.GasUsed)) require.Equal(t, msg.Fee.Gas, uint64(result.Response.GasWanted)) - tests.WaitForNextNBlocksTM(1, port) + tests.WaitForNextNBlocksTM(1, f.Port) - barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", barAddr, flags)) - require.Equal(t, int64(10), barAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) + // Ensure account state + barAcc := f.QueryAccount(barAddr) + fooAcc = f.QueryAccount(fooAddr) + require.Equal(t, int64(10), barAcc.GetCoins().AmountOf(denom).Int64()) + require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf(denom).Int64()) - fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli query account %s %v", fooAddr, flags)) - require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom).Int64()) - cleanupDirs(gaiadHome, gaiacliHome) + f.Cleanup() } func TestGaiaCLIConfig(t *testing.T) { t.Parallel() - chainID, servAddr, port, gaiadHome, gaiacliHome, _ := initializeFixtures(t, nil) - node := fmt.Sprintf("%s:%s", servAddr, port) - executeWrite(t, fmt.Sprintf(`gaiacli --home=%s config node %s`, gaiacliHome, node)) - executeWrite(t, fmt.Sprintf(`gaiacli --home=%s config output text`, gaiacliHome)) - executeWrite(t, fmt.Sprintf(`gaiacli --home=%s config trust-node true`, gaiacliHome)) - executeWrite(t, fmt.Sprintf(`gaiacli --home=%s config chain-id %s`, gaiacliHome, chainID)) - executeWrite(t, fmt.Sprintf(`gaiacli --home=%s config trace false`, gaiacliHome)) - config, err := ioutil.ReadFile(path.Join(gaiacliHome, "config", "config.toml")) + f := InitFixtures(t) + node := fmt.Sprintf("%s:%s", f.RPCAddr, f.Port) + + // Set available configuration options + f.CLIConfig("node", node) + f.CLIConfig("output", "text") + f.CLIConfig("trust-node", "true") + f.CLIConfig("chain-id", f.ChainID) + f.CLIConfig("trace", "false") + + config, err := ioutil.ReadFile(path.Join(f.GCLIHome, "config", "config.toml")) require.NoError(t, err) expectedConfig := fmt.Sprintf(`chain-id = "%s" node = "%s" output = "text" trace = false trust-node = true -`, chainID, node) +`, f.ChainID, node) require.Equal(t, expectedConfig, string(config)) - cleanupDirs(gaiadHome, gaiacliHome) + + f.Cleanup() } func TestGaiadCollectGentxs(t *testing.T) { t.Parallel() + f := NewFixtures(t) + // Initialise temporary directories - gaiadHome, gaiacliHome := getTestingHomeDirs(t.Name()) gentxDir, err := ioutil.TempDir("", "") gentxDoc := filepath.Join(gentxDir, "gentx.json") require.NoError(t, err) - tests.ExecuteT(t, fmt.Sprintf("gaiad --home=%s unsafe-reset-all", gaiadHome), "") - os.RemoveAll(filepath.Join(gaiadHome, "config", "gentx")) - executeWrite(t, fmt.Sprintf("gaiacli keys delete --home=%s foo", gaiacliHome), app.DefaultKeyPass) - executeWrite(t, fmt.Sprintf("gaiacli keys delete --home=%s bar", gaiacliHome), app.DefaultKeyPass) - executeWriteCheckErr(t, fmt.Sprintf("gaiacli keys add --home=%s foo", gaiacliHome), app.DefaultKeyPass) - executeWriteCheckErr(t, fmt.Sprintf("gaiacli keys add --home=%s bar", gaiacliHome), app.DefaultKeyPass) - executeWriteCheckErr(t, fmt.Sprintf("gaiacli config --home=%s output json", gaiacliHome)) - fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --home=%s", gaiacliHome)) + // Reset testing path + f.UnsafeResetAll() - // Run init - _ = executeInit(t, fmt.Sprintf("gaiad init -o --moniker=foo --home=%s", gaiadHome)) - // Add account to genesis.json - executeWriteCheckErr(t, fmt.Sprintf( - "gaiad add-genesis-account %s 150%s,1000footoken --home=%s", fooAddr, stakeTypes.DefaultBondDenom, gaiadHome)) - executeWrite(t, fmt.Sprintf("cat %s%sconfig%sgenesis.json", gaiadHome, string(os.PathSeparator), string(os.PathSeparator))) - // Write gentx file - executeWriteCheckErr(t, fmt.Sprintf( - "gaiad gentx --name=foo --home=%s --home-client=%s --output-document=%s", gaiadHome, gaiacliHome, gentxDoc), app.DefaultKeyPass) - // Collect gentxs from a custom directory - executeWriteCheckErr(t, fmt.Sprintf("gaiad collect-gentxs --home=%s --gentx-dir=%s", gaiadHome, gentxDir), app.DefaultKeyPass) - cleanupDirs(gaiadHome, gaiacliHome, gentxDir) -} + // Initialize keys + f.KeysDelete(keyFoo) + f.KeysDelete(keyBar) + f.KeysAdd(keyFoo) + f.KeysAdd(keyBar) -// --------------------------------------------------------------------------- -// Slashing - -func TestSlashingGetParams(t *testing.T) { - t.Parallel() + // Configure json output + f.CLIConfig("output", "json") - cdc := app.MakeCodec() - chainID, servAddr, port, gaiadHome, gaiacliHome, p2pAddr := initializeFixtures(t, nil) - flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", gaiacliHome, servAddr, chainID) + // Run init + f.GDInit(keyFoo) - // start gaiad server - proc := tests.GoExecuteTWithStdout( - t, - fmt.Sprintf( - "gaiad start --home=%s --rpc.laddr=%v --p2p.laddr=%v", - gaiadHome, servAddr, p2pAddr, - ), - ) + // Add account to genesis.json + f.AddGenesisAccount(f.KeyAddress(keyFoo), startCoins) - defer proc.Stop(false) - tests.WaitForTMStart(port) - tests.WaitForNextNBlocksTM(1, port) + // Write gentx file + f.GenTx(keyFoo, fmt.Sprintf("--output-document=%s", gentxDoc)) - res, errStr := tests.ExecuteT(t, fmt.Sprintf("gaiacli query slashing params %s", flags), "") - require.Empty(t, errStr) + // Collect gentxs from a custom directory + f.CollectGenTxs(fmt.Sprintf("--gentx-dir=%s", gentxDir)) - var params slashing.Params - err := cdc.UnmarshalJSON([]byte(res), ¶ms) - require.NoError(t, err) + f.Cleanup(gentxDir) } -func TestGaiaCLIQueryTxPagination(t *testing.T) { +func TestSlashingGetParams(t *testing.T) { t.Parallel() - configOverride := cfg.DefaultConfig() - configOverride.TxIndex.IndexAllTags = true - configOverride.Consensus.SkipTimeoutCommit = true - chainID, servAddr, port, gaiadHome, gaiacliHome, _ := initializeFixtures(t, configOverride) - flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", gaiacliHome, servAddr, chainID) - - // start gaiad git server - proc := tests.GoExecuteTWithStdout(t, fmt.Sprintf( - "gaiad start --home=%s --rpc.laddr=%v", gaiadHome, servAddr)) + f := InitFixtures(t) + // start gaiad server + proc := f.GDStart() defer proc.Stop(false) - tests.WaitForTMStart(port) - tests.WaitForNextNBlocksTM(2, port) - - fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --output=json --home=%s", gaiacliHome)) - barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --output=json --home=%s", gaiacliHome)) - - for i := 1; i <= 30; i++ { - success := executeWrite(t, fmt.Sprintf( - "gaiacli tx send %v --amount=%dfootoken --to=%s --from=foo", - flags, i, barAddr), app.DefaultKeyPass) - require.True(t, success) - tests.WaitForNextNBlocksTM(1, port) - } - - // perPage = 15, 2 pages - txsPage1 := executeGetTxs(t, fmt.Sprintf("gaiacli query txs --tags='sender:%s' %v --limit=15 --page=1", fooAddr, flags)) - require.Len(t, txsPage1, 15) - txsPage2 := executeGetTxs(t, fmt.Sprintf("gaiacli query txs --tags='sender:%s' %v --limit=15 --page=2", fooAddr, flags)) - require.Len(t, txsPage2, 15) - require.NotEqual(t, txsPage1, txsPage2) - txsPage3 := executeGetTxs(t, fmt.Sprintf("gaiacli query txs --tags='sender:%s' %v --limit=15 --page=3", fooAddr, flags)) - require.Len(t, txsPage3, 15) - require.Equal(t, txsPage2, txsPage3) - - // perPage = 16, 2 pages - txsPage1 = executeGetTxs(t, fmt.Sprintf("gaiacli query txs --tags='sender:%s' %v --limit=16 --page=1", fooAddr, flags)) - require.Len(t, txsPage1, 16) - txsPage2 = executeGetTxs(t, fmt.Sprintf("gaiacli query txs --tags='sender:%s' %v --limit=16 --page=2", fooAddr, flags)) - require.Len(t, txsPage2, 14) - require.NotEqual(t, txsPage1, txsPage2) - - // perPage = 50 - txsPageFull := executeGetTxs(t, fmt.Sprintf("gaiacli query txs --tags='sender:%s' %v --limit=50 --page=1", fooAddr, flags)) - require.Len(t, txsPageFull, 30) - require.Equal(t, txsPageFull, append(txsPage1, txsPage2...)) - - // missing perPage - txsPageFull = executeGetTxs(t, fmt.Sprintf("gaiacli query txs --tags='sender:%s' %v --limit=50", fooAddr, flags)) - require.Len(t, txsPageFull, 30) - require.Equal(t, txsPageFull, append(txsPage1, txsPage2...)) - - // missing limit - txsPageFull = executeGetTxs(t, fmt.Sprintf("gaiacli query txs --tags='sender:%s' %v --page=1", fooAddr, flags)) - require.Len(t, txsPageFull, 30) - require.Equal(t, txsPageFull, append(txsPage1, txsPage2...)) - - // missing all - txsPageFull = executeGetTxs(t, fmt.Sprintf("gaiacli query txs --tags='sender:%s' %v", fooAddr, flags)) - require.Len(t, txsPageFull, 30) - require.Equal(t, txsPageFull, append(txsPage1, txsPage2...)) - - // perPage = 0 - executeGetTxsWrong(t, fmt.Sprintf("gaiacli query txs --tags='sender:%s' %v --limit=50 --page=0", fooAddr, flags), "ERROR: page must greater than 0") - - // limit = 0 - executeGetTxsWrong(t, fmt.Sprintf("gaiacli query txs --tags='sender:%s' %v --limit=0 --page=1", fooAddr, flags), "ERROR: limit must greater than 0") -} - -//___________________________________________________________________________________ -// helper methods - -func getTestingHomeDirs(name string) (string, string) { - tmpDir := os.TempDir() - gaiadHome := fmt.Sprintf("%s%s%s%s.test_gaiad", tmpDir, string(os.PathSeparator), name, string(os.PathSeparator)) - gaiacliHome := fmt.Sprintf("%s%s%s%s.test_gaiacli", tmpDir, string(os.PathSeparator), name, string(os.PathSeparator)) - return gaiadHome, gaiacliHome -} - -func initializeFixtures(t *testing.T, configOverride *cfg.Config) (chainID, servAddr, port, gaiadHome, gaiacliHome, p2pAddr string) { - gaiadHome, gaiacliHome = getTestingHomeDirs(t.Name()) - tests.ExecuteT(t, fmt.Sprintf("gaiad --home=%s unsafe-reset-all", gaiadHome), "") - os.RemoveAll(filepath.Join(gaiadHome, "config", "gentx")) - executeWrite(t, fmt.Sprintf("gaiacli keys delete --home=%s foo", gaiacliHome), app.DefaultKeyPass) - executeWrite(t, fmt.Sprintf("gaiacli keys delete --home=%s bar", gaiacliHome), app.DefaultKeyPass) - executeWriteCheckErr(t, fmt.Sprintf("gaiacli keys add --home=%s foo", gaiacliHome), app.DefaultKeyPass) - executeWriteCheckErr(t, fmt.Sprintf("gaiacli keys add --home=%s bar", gaiacliHome), app.DefaultKeyPass) - executeWriteCheckErr(t, fmt.Sprintf("gaiacli config --home=%s output json", gaiacliHome)) - fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --home=%s", gaiacliHome)) - chainID = executeInit(t, fmt.Sprintf("gaiad init -o --moniker=foo --home=%s", gaiadHome)) - - if configOverride != nil { - cfg.WriteConfigFile(filepath.Join(gaiadHome, "config", "config.toml"), configOverride) - } - executeWriteCheckErr(t, fmt.Sprintf( - "gaiad add-genesis-account %s 150%s,1000footoken --home=%s", fooAddr, stakeTypes.DefaultBondDenom, gaiadHome)) - executeWrite(t, fmt.Sprintf("cat %s%sconfig%sgenesis.json", gaiadHome, string(os.PathSeparator), string(os.PathSeparator))) - executeWriteCheckErr(t, fmt.Sprintf( - "gaiad gentx --name=foo --home=%s --home-client=%s", gaiadHome, gaiacliHome), app.DefaultKeyPass) - executeWriteCheckErr(t, fmt.Sprintf("gaiad collect-gentxs --home=%s", gaiadHome), app.DefaultKeyPass) - // get a free port, also setup some common flags - servAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) - p2pAddr, _, err = server.FreeTCPAddr() - require.NoError(t, err) - return -} - -func marshalStdTx(t *testing.T, stdTx auth.StdTx) []byte { - cdc := app.MakeCodec() - bz, err := cdc.MarshalBinaryBare(stdTx) - require.NoError(t, err) - return bz -} - -func unmarshalStdTx(t *testing.T, s string) (stdTx auth.StdTx) { - cdc := app.MakeCodec() - require.Nil(t, cdc.UnmarshalJSON([]byte(s), &stdTx)) - return -} - -func writeToNewTempFile(t *testing.T, s string) *os.File { - fp, err := ioutil.TempFile(os.TempDir(), "cosmos_cli_test_") - require.Nil(t, err) - _, err = fp.WriteString(s) - require.Nil(t, err) - return fp -} - -func readGenesisFile(t *testing.T, genFile string) types.GenesisDoc { - var genDoc types.GenesisDoc - fp, err := os.Open(genFile) - require.NoError(t, err) - fileContents, err := ioutil.ReadAll(fp) - require.NoError(t, err) - defer fp.Close() - err = codec.Cdc.UnmarshalJSON(fileContents, &genDoc) - require.NoError(t, err) - return genDoc -} - -//___________________________________________________________________________________ -// executors - -func executeWriteCheckErr(t *testing.T, cmdStr string, writes ...string) { - require.True(t, executeWrite(t, cmdStr, writes...)) -} - -func executeWrite(t *testing.T, cmdStr string, writes ...string) (exitSuccess bool) { - exitSuccess, _, _ = executeWriteRetStdStreams(t, cmdStr, writes...) - return -} - -func executeWriteRetStdStreams(t *testing.T, cmdStr string, writes ...string) (bool, string, string) { - proc := tests.GoExecuteT(t, cmdStr) - - for _, write := range writes { - _, err := proc.StdinPipe.Write([]byte(write + "\n")) - require.NoError(t, err) - } - stdout, stderr, err := proc.ReadAll() - if err != nil { - fmt.Println("Err on proc.ReadAll()", err, cmdStr) - } - // Log output. - if len(stdout) > 0 { - t.Log("Stdout:", cmn.Green(string(stdout))) - } - if len(stderr) > 0 { - t.Log("Stderr:", cmn.Red(string(stderr))) - } - - proc.Wait() - return proc.ExitState.Success(), string(stdout), string(stderr) -} - -func executeInit(t *testing.T, cmdStr string) (chainID string) { - _, stderr := tests.ExecuteT(t, cmdStr, app.DefaultKeyPass) - - var initRes map[string]json.RawMessage - err := json.Unmarshal([]byte(stderr), &initRes) - require.NoError(t, err) - - err = json.Unmarshal(initRes["chain_id"], &chainID) - require.NoError(t, err) - - return -} - -func executeGetAddrPK(t *testing.T, cmdStr string) (sdk.AccAddress, crypto.PubKey) { - out, _ := tests.ExecuteT(t, cmdStr, "") - var ko keys.KeyOutput - keys.UnmarshalJSON([]byte(out), &ko) - - pk, err := sdk.GetAccPubKeyBech32(ko.PubKey) - require.NoError(t, err) - - accAddr, err := sdk.AccAddressFromBech32(ko.Address) - require.NoError(t, err) - - return accAddr, pk -} - -func executeGetAccount(t *testing.T, cmdStr string) auth.BaseAccount { - out, _ := tests.ExecuteT(t, cmdStr, "") - var initRes map[string]json.RawMessage - err := json.Unmarshal([]byte(out), &initRes) - require.NoError(t, err, "out %v, err %v", out, err) - value := initRes["value"] - var acc auth.BaseAccount - cdc := codec.New() - codec.RegisterCrypto(cdc) - err = cdc.UnmarshalJSON(value, &acc) - require.NoError(t, err, "value %v, err %v", string(value), err) - return acc -} - -//___________________________________________________________________________________ -// txs - -func executeGetTxs(t *testing.T, cmdStr string) []tx.Info { - out, _ := tests.ExecuteT(t, cmdStr, "") - var txs []tx.Info - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &txs) - require.NoError(t, err, "out %v\n, err %v", out, err) - return txs -} - -func executeGetTxsWrong(t *testing.T, cmdStr string, expectedErr string) { - _, stderr := tests.ExecuteT(t, cmdStr, "") - require.Equal(t, stderr, expectedErr) -} -//___________________________________________________________________________________ -// stake - -func executeGetValidator(t *testing.T, cmdStr string) stake.Validator { - out, _ := tests.ExecuteT(t, cmdStr, "") - var validator stake.Validator - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &validator) - require.NoError(t, err, "out %v\n, err %v", out, err) - return validator -} - -func executeGetValidatorUnbondingDelegations(t *testing.T, cmdStr string) []stake.UnbondingDelegation { - out, _ := tests.ExecuteT(t, cmdStr, "") - var ubds []stake.UnbondingDelegation - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &ubds) - require.NoError(t, err, "out %v\n, err %v", out, err) - return ubds -} - -func executeGetValidatorRedelegations(t *testing.T, cmdStr string) []stake.Redelegation { - out, _ := tests.ExecuteT(t, cmdStr, "") - var reds []stake.Redelegation - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &reds) - require.NoError(t, err, "out %v\n, err %v", out, err) - return reds -} - -func executeGetValidatorDelegations(t *testing.T, cmdStr string) []stake.Delegation { - out, _ := tests.ExecuteT(t, cmdStr, "") - var delegations []stake.Delegation - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &delegations) - require.NoError(t, err, "out %v\n, err %v", out, err) - return delegations -} - -func executeGetPool(t *testing.T, cmdStr string) stake.Pool { - out, _ := tests.ExecuteT(t, cmdStr, "") - var pool stake.Pool - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &pool) - require.NoError(t, err, "out %v\n, err %v", out, err) - return pool -} - -func executeGetParams(t *testing.T, cmdStr string) stake.Params { - out, _ := tests.ExecuteT(t, cmdStr, "") - var params stake.Params - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), ¶ms) - require.NoError(t, err, "out %v\n, err %v", out, err) - return params -} - -//___________________________________________________________________________________ -// gov - -func executeGetDepositParam(t *testing.T, cmdStr string) gov.DepositParams { - out, _ := tests.ExecuteT(t, cmdStr, "") - var depositParam gov.DepositParams - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &depositParam) - require.NoError(t, err, "out %v\n, err %v", out, err) - return depositParam -} - -func executeGetVotingParam(t *testing.T, cmdStr string) gov.VotingParams { - out, _ := tests.ExecuteT(t, cmdStr, "") - var votingParam gov.VotingParams - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &votingParam) - require.NoError(t, err, "out %v\n, err %v", out, err) - return votingParam -} - -func executeGetTallyingParam(t *testing.T, cmdStr string) gov.TallyParams { - out, _ := tests.ExecuteT(t, cmdStr, "") - var tallyingParam gov.TallyParams - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &tallyingParam) - require.NoError(t, err, "out %v\n, err %v", out, err) - return tallyingParam -} - -func executeGetProposal(t *testing.T, cmdStr string) gov.Proposal { - out, _ := tests.ExecuteT(t, cmdStr, "") - var proposal gov.Proposal - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &proposal) - require.NoError(t, err, "out %v\n, err %v", out, err) - return proposal -} - -func executeGetVote(t *testing.T, cmdStr string) gov.Vote { - out, _ := tests.ExecuteT(t, cmdStr, "") - var vote gov.Vote - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &vote) - require.NoError(t, err, "out %v\n, err %v", out, err) - return vote -} - -func executeGetVotes(t *testing.T, cmdStr string) []gov.Vote { - out, _ := tests.ExecuteT(t, cmdStr, "") - var votes []gov.Vote - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &votes) - require.NoError(t, err, "out %v\n, err %v", out, err) - return votes -} - -func executeGetDeposit(t *testing.T, cmdStr string) gov.Deposit { - out, _ := tests.ExecuteT(t, cmdStr, "") - var deposit gov.Deposit - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &deposit) - require.NoError(t, err, "out %v\n, err %v", out, err) - return deposit -} - -func executeGetDeposits(t *testing.T, cmdStr string) []gov.Deposit { - out, _ := tests.ExecuteT(t, cmdStr, "") - var deposits []gov.Deposit - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &deposits) - require.NoError(t, err, "out %v\n, err %v", out, err) - return deposits -} - -func cleanupDirs(dirs ...string) { - for _, d := range dirs { - os.RemoveAll(d) - } + params := f.QuerySlashingParams() + require.Equal(t, time.Duration(120000000000), params.MaxEvidenceAge) + require.Equal(t, int64(100), params.SignedBlocksWindow) + require.Equal(t, sdk.NewDecWithPrec(5, 1), params.MinSignedPerWindow) } diff --git a/cmd/gaia/cli_test/test_helpers.go b/cmd/gaia/cli_test/test_helpers.go new file mode 100644 index 000000000000..3896fdf50b10 --- /dev/null +++ b/cmd/gaia/cli_test/test_helpers.go @@ -0,0 +1,558 @@ +package clitest + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/require" + + cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/cosmos/cosmos-sdk/cmd/gaia/app" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/tests" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/staking" +) + +const ( + denom = "stake" + keyFoo = "foo" + keyBar = "bar" + fooDenom = "footoken" + feeDenom = "feetoken" +) + +var startCoins = sdk.Coins{ + sdk.NewInt64Coin(feeDenom, 1000), + sdk.NewInt64Coin(fooDenom, 1000), + sdk.NewInt64Coin(denom, 150), +} + +//___________________________________________________________________________________ +// Fixtures + +// Fixtures is used to setup the testing environment +type Fixtures struct { + ChainID string + RPCAddr string + Port string + GDHome string + GCLIHome string + P2PAddr string + T *testing.T +} + +// NewFixtures creates a new instance of Fixtures with many vars set +func NewFixtures(t *testing.T) *Fixtures { + tmpDir := os.TempDir() + gaiadHome := fmt.Sprintf("%s%s%s%s.test_gaiad", tmpDir, string(os.PathSeparator), t.Name(), string(os.PathSeparator)) + gaiacliHome := fmt.Sprintf("%s%s%s%s.test_gaiacli", tmpDir, string(os.PathSeparator), t.Name(), string(os.PathSeparator)) + servAddr, port, err := server.FreeTCPAddr() + require.NoError(t, err) + p2pAddr, _, err := server.FreeTCPAddr() + require.NoError(t, err) + return &Fixtures{ + T: t, + GDHome: gaiadHome, + GCLIHome: gaiacliHome, + RPCAddr: servAddr, + P2PAddr: p2pAddr, + Port: port, + } +} + +// InitFixtures is called at the beginning of a test +// and initializes a chain with 1 validator +func InitFixtures(t *testing.T) (f *Fixtures) { + f = NewFixtures(t) + + // Reset test state + f.UnsafeResetAll() + + // Ensure keystore has foo and bar keys + f.KeysDelete(keyFoo) + f.KeysDelete(keyBar) + f.KeysAdd(keyFoo) + f.KeysAdd(keyBar) + + // Ensure that CLI output is in JSON format + f.CLIConfig("output", "json") + + // NOTE: GDInit sets the ChainID + f.GDInit(keyFoo) + + // Start an account with tokens + f.AddGenesisAccount(f.KeyAddress(keyFoo), startCoins) + f.GenTx(keyFoo) + f.CollectGenTxs() + return +} + +// Cleanup is meant to be run at the end of a test to clean up an remaining test state +func (f *Fixtures) Cleanup(dirs ...string) { + clean := append(dirs, f.GDHome, f.GCLIHome) + for _, d := range clean { + err := os.RemoveAll(d) + require.NoError(f.T, err) + } +} + +// Flags returns the flags necessary for making most CLI calls +func (f *Fixtures) Flags() string { + return fmt.Sprintf("--home=%s --node=%s --chain-id=%s", f.GCLIHome, f.RPCAddr, f.ChainID) +} + +//___________________________________________________________________________________ +// gaiad + +// UnsafeResetAll is gaiad unsafe-reset-all +func (f *Fixtures) UnsafeResetAll(flags ...string) { + cmd := fmt.Sprintf("gaiad --home=%s unsafe-reset-all", f.GDHome) + executeWrite(f.T, addFlags(cmd, flags)) + err := os.RemoveAll(filepath.Join(f.GDHome, "config", "gentx")) + require.NoError(f.T, err) +} + +// GDInit is gaiad init +// NOTE: GDInit sets the ChainID for the Fixtures instance +func (f *Fixtures) GDInit(moniker string, flags ...string) { + cmd := fmt.Sprintf("gaiad init -o --moniker=%s --home=%s", moniker, f.GDHome) + _, stderr := tests.ExecuteT(f.T, addFlags(cmd, flags), app.DefaultKeyPass) + + var chainID string + var initRes map[string]json.RawMessage + + err := json.Unmarshal([]byte(stderr), &initRes) + require.NoError(f.T, err) + + err = json.Unmarshal(initRes["chain_id"], &chainID) + require.NoError(f.T, err) + + f.ChainID = chainID +} + +// AddGenesisAccount is gaiad add-genesis-account +func (f *Fixtures) AddGenesisAccount(address sdk.AccAddress, coins sdk.Coins, flags ...string) { + cmd := fmt.Sprintf("gaiad add-genesis-account %s %s --home=%s", address, coins, f.GDHome) + executeWriteCheckErr(f.T, addFlags(cmd, flags)) +} + +// GenTx is gaiad gentx +func (f *Fixtures) GenTx(name string, flags ...string) { + cmd := fmt.Sprintf("gaiad gentx --name=%s --home=%s --home-client=%s", name, f.GDHome, f.GCLIHome) + executeWriteCheckErr(f.T, addFlags(cmd, flags), app.DefaultKeyPass) +} + +// CollectGenTxs is gaiad collect-gentxs +func (f *Fixtures) CollectGenTxs(flags ...string) { + cmd := fmt.Sprintf("gaiad collect-gentxs --home=%s", f.GDHome) + executeWriteCheckErr(f.T, addFlags(cmd, flags), app.DefaultKeyPass) +} + +// GDStart runs gaiad start with the appropriate flags and returns a process +func (f *Fixtures) GDStart(flags ...string) *tests.Process { + cmd := fmt.Sprintf("gaiad start --home=%s --rpc.laddr=%v --p2p.laddr=%v", f.GDHome, f.RPCAddr, f.P2PAddr) + proc := tests.GoExecuteTWithStdout(f.T, addFlags(cmd, flags)) + tests.WaitForTMStart(f.Port) + tests.WaitForNextNBlocksTM(1, f.Port) + return proc +} + +//___________________________________________________________________________________ +// gaiacli keys + +// KeysDelete is gaiacli keys delete +func (f *Fixtures) KeysDelete(name string, flags ...string) { + cmd := fmt.Sprintf("gaiacli keys delete --home=%s %s", f.GCLIHome, name) + executeWrite(f.T, addFlags(cmd, flags), app.DefaultKeyPass) +} + +// KeysAdd is gaiacli keys add +func (f *Fixtures) KeysAdd(name string, flags ...string) { + cmd := fmt.Sprintf("gaiacli keys add --home=%s %s", f.GCLIHome, name) + executeWriteCheckErr(f.T, addFlags(cmd, flags), app.DefaultKeyPass) +} + +// KeysShow is gaiacli keys show +func (f *Fixtures) KeysShow(name string, flags ...string) keys.KeyOutput { + cmd := fmt.Sprintf("gaiacli keys show --home=%s %s", f.GCLIHome, name) + out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") + var ko keys.KeyOutput + err := keys.UnmarshalJSON([]byte(out), &ko) + require.NoError(f.T, err) + return ko +} + +// KeyAddress returns the SDK account address from the key +func (f *Fixtures) KeyAddress(name string) sdk.AccAddress { + ko := f.KeysShow(name) + accAddr, err := sdk.AccAddressFromBech32(ko.Address) + require.NoError(f.T, err) + return accAddr +} + +//___________________________________________________________________________________ +// gaiacli config + +// CLIConfig is gaiacli config +func (f *Fixtures) CLIConfig(key, value string, flags ...string) { + cmd := fmt.Sprintf("gaiacli config --home=%s %s %s", f.GCLIHome, key, value) + executeWriteCheckErr(f.T, addFlags(cmd, flags)) +} + +//___________________________________________________________________________________ +// gaiacli tx send/sign/broadcast + +// TxSend is gaiacli tx send +func (f *Fixtures) TxSend(from string, to sdk.AccAddress, amount sdk.Coin, flags ...string) (bool, string, string) { + cmd := fmt.Sprintf("gaiacli tx send %v --amount=%s --to=%s --from=%s", f.Flags(), amount, to, from) + return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), app.DefaultKeyPass) +} + +// TxSign is gaiacli tx sign +func (f *Fixtures) TxSign(signer, fileName string, flags ...string) (bool, string, string) { + cmd := fmt.Sprintf("gaiacli tx sign %v --name=%s %v", f.Flags(), signer, fileName) + return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), app.DefaultKeyPass) +} + +// TxBroadcast is gaiacli tx sign +func (f *Fixtures) TxBroadcast(fileName string, flags ...string) (bool, string, string) { + cmd := fmt.Sprintf("gaiacli tx broadcast %v --json %v", f.Flags(), fileName) + return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), app.DefaultKeyPass) +} + +//___________________________________________________________________________________ +// gaiacli tx staking + +// TxStakingCreateValidator is gaiacli tx staking create-validator +func (f *Fixtures) TxStakingCreateValidator(from, consPubKey string, amount sdk.Coin, flags ...string) (bool, string, string) { + cmd := fmt.Sprintf("gaiacli tx staking create-validator %v --from=%s --pubkey=%s", f.Flags(), from, consPubKey) + cmd += fmt.Sprintf(" --amount=%v --moniker=%v --commission-rate=%v", amount, from, "0.05") + cmd += fmt.Sprintf(" --commission-max-rate=%v --commission-max-change-rate=%v", "0.20", "0.10") + return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), app.DefaultKeyPass) +} + +// TxStakingUnbond is gaiacli tx staking unbond +func (f *Fixtures) TxStakingUnbond(from, shares string, validator sdk.ValAddress, flags ...string) bool { + cmd := fmt.Sprintf("gaiacli tx staking unbond %v --from=%s --validator=%s --shares-amount=%v", f.Flags(), from, validator, shares) + return executeWrite(f.T, addFlags(cmd, flags), app.DefaultKeyPass) +} + +//___________________________________________________________________________________ +// gaiacli tx gov + +// TxGovSubmitProposal is gaiacli tx gov submit-proposal +func (f *Fixtures) TxGovSubmitProposal(from, typ, title, description string, deposit sdk.Coin, flags ...string) (bool, string, string) { + cmd := fmt.Sprintf("gaiacli tx gov submit-proposal %v --from=%s --type=%s", f.Flags(), from, typ) + cmd += fmt.Sprintf(" --title=%s --description=%s --deposit=%s", title, description, deposit) + return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), app.DefaultKeyPass) +} + +// TxGovDeposit is gaiacli tx gov deposit +func (f *Fixtures) TxGovDeposit(proposalID int, from string, amount sdk.Coin, flags ...string) (bool, string, string) { + cmd := fmt.Sprintf("gaiacli tx gov deposit %d %s --from=%s %v", proposalID, amount, from, f.Flags()) + return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), app.DefaultKeyPass) +} + +// TxGovVote is gaiacli tx gov vote +func (f *Fixtures) TxGovVote(proposalID int, option gov.VoteOption, from string, flags ...string) (bool, string, string) { + cmd := fmt.Sprintf("gaiacli tx gov vote %d %s --from=%s %v", proposalID, option, from, f.Flags()) + return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), app.DefaultKeyPass) +} + +//___________________________________________________________________________________ +// gaiacli query account + +// QueryAccount is gaiacli query account +func (f *Fixtures) QueryAccount(address sdk.AccAddress, flags ...string) auth.BaseAccount { + cmd := fmt.Sprintf("gaiacli query account %s %v", address, f.Flags()) + out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") + var initRes map[string]json.RawMessage + err := json.Unmarshal([]byte(out), &initRes) + require.NoError(f.T, err, "out %v, err %v", out, err) + value := initRes["value"] + var acc auth.BaseAccount + cdc := codec.New() + codec.RegisterCrypto(cdc) + err = cdc.UnmarshalJSON(value, &acc) + require.NoError(f.T, err, "value %v, err %v", string(value), err) + return acc +} + +//___________________________________________________________________________________ +// gaiacli query txs + +// QueryTxs is gaiacli query txs +func (f *Fixtures) QueryTxs(tags ...string) []tx.Info { + cmd := fmt.Sprintf("gaiacli query txs --tags='%s' %v", queryTags(tags), f.Flags()) + out, _ := tests.ExecuteT(f.T, cmd, "") + var txs []tx.Info + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &txs) + require.NoError(f.T, err, "out %v\n, err %v", out, err) + return txs +} + +//___________________________________________________________________________________ +// gaiacli query staking + +// QueryStakingValidator is gaiacli query staking validator +func (f *Fixtures) QueryStakingValidator(valAddr sdk.ValAddress, flags ...string) staking.Validator { + cmd := fmt.Sprintf("gaiacli query staking validator %s %v", valAddr, f.Flags()) + out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") + var validator staking.Validator + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &validator) + require.NoError(f.T, err, "out %v\n, err %v", out, err) + return validator +} + +// QueryStakingUnbondingDelegationsFrom is gaiacli query staking unbonding-delegations-from +func (f *Fixtures) QueryStakingUnbondingDelegationsFrom(valAddr sdk.ValAddress, flags ...string) []staking.UnbondingDelegation { + cmd := fmt.Sprintf("gaiacli query staking unbonding-delegations-from %s %v", valAddr, f.Flags()) + out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") + var ubds []staking.UnbondingDelegation + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &ubds) + require.NoError(f.T, err, "out %v\n, err %v", out, err) + return ubds +} + +// QueryStakingDelegationsTo is gaiacli query staking delegations-to +func (f *Fixtures) QueryStakingDelegationsTo(valAddr sdk.ValAddress, flags ...string) []staking.Delegation { + cmd := fmt.Sprintf("gaiacli query staking delegations-to %s %v", valAddr, f.Flags()) + out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") + var delegations []staking.Delegation + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &delegations) + require.NoError(f.T, err, "out %v\n, err %v", out, err) + return delegations +} + +// QueryStakingPool is gaiacli query staking pool +func (f *Fixtures) QueryStakingPool(flags ...string) staking.Pool { + cmd := fmt.Sprintf("gaiacli query staking pool %v", f.Flags()) + out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") + var pool staking.Pool + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &pool) + require.NoError(f.T, err, "out %v\n, err %v", out, err) + return pool +} + +// QueryStakingParameters is gaiacli query staking parameters +func (f *Fixtures) QueryStakingParameters(flags ...string) staking.Params { + cmd := fmt.Sprintf("gaiacli query staking parameters %v", f.Flags()) + out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") + var params staking.Params + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), ¶ms) + require.NoError(f.T, err, "out %v\n, err %v", out, err) + return params +} + +//___________________________________________________________________________________ +// gaiacli query gov + +// QueryGovParamDeposit is gaiacli query gov param deposit +func (f *Fixtures) QueryGovParamDeposit() gov.DepositParams { + cmd := fmt.Sprintf("gaiacli query gov param deposit %s", f.Flags()) + out, _ := tests.ExecuteT(f.T, cmd, "") + var depositParam gov.DepositParams + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &depositParam) + require.NoError(f.T, err, "out %v\n, err %v", out, err) + return depositParam +} + +// QueryGovParamVoting is gaiacli query gov param voting +func (f *Fixtures) QueryGovParamVoting() gov.VotingParams { + cmd := fmt.Sprintf("gaiacli query gov param voting %s", f.Flags()) + out, _ := tests.ExecuteT(f.T, cmd, "") + var votingParam gov.VotingParams + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &votingParam) + require.NoError(f.T, err, "out %v\n, err %v", out, err) + return votingParam +} + +// QueryGovParamTallying is gaiacli query gov param tallying +func (f *Fixtures) QueryGovParamTallying() gov.TallyParams { + cmd := fmt.Sprintf("gaiacli query gov param tallying %s", f.Flags()) + out, _ := tests.ExecuteT(f.T, cmd, "") + var tallyingParam gov.TallyParams + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &tallyingParam) + require.NoError(f.T, err, "out %v\n, err %v", out, err) + return tallyingParam +} + +// QueryGovProposals is gaiacli query gov proposals +func (f *Fixtures) QueryGovProposals(flags ...string) string { + cmd := fmt.Sprintf("gaiacli query gov proposals %v", f.Flags()) + stdout, stderr := tests.ExecuteT(f.T, addFlags(cmd, flags), "") + require.Empty(f.T, stderr) + return stdout +} + +// QueryGovProposal is gaiacli query gov proposal +func (f *Fixtures) QueryGovProposal(proposalID int, flags ...string) gov.Proposal { + cmd := fmt.Sprintf("gaiacli query gov proposal %d %v", proposalID, f.Flags()) + out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") + var proposal gov.Proposal + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &proposal) + require.NoError(f.T, err, "out %v\n, err %v", out, err) + return proposal +} + +// QueryGovVote is gaiacli query gov vote +func (f *Fixtures) QueryGovVote(proposalID int, voter sdk.AccAddress, flags ...string) gov.Vote { + cmd := fmt.Sprintf("gaiacli query gov vote %d %s %v", proposalID, voter, f.Flags()) + out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") + var vote gov.Vote + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &vote) + require.NoError(f.T, err, "out %v\n, err %v", out, err) + return vote +} + +// QueryGovVotes is gaiacli query gov votes +func (f *Fixtures) QueryGovVotes(proposalID int, flags ...string) []gov.Vote { + cmd := fmt.Sprintf("gaiacli query gov votes %d %v", proposalID, f.Flags()) + out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") + var votes []gov.Vote + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &votes) + require.NoError(f.T, err, "out %v\n, err %v", out, err) + return votes +} + +// QueryGovDeposit is gaiacli query gov deposit +func (f *Fixtures) QueryGovDeposit(proposalID int, depositor sdk.AccAddress, flags ...string) gov.Deposit { + cmd := fmt.Sprintf("gaiacli query gov deposit %d %s %v", proposalID, depositor, f.Flags()) + out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") + var deposit gov.Deposit + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &deposit) + require.NoError(f.T, err, "out %v\n, err %v", out, err) + return deposit +} + +// QueryGovDeposits is gaiacli query gov deposits +func (f *Fixtures) QueryGovDeposits(propsalID int, flags ...string) []gov.Deposit { + cmd := fmt.Sprintf("gaiacli query gov deposits %d %v", propsalID, f.Flags()) + out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") + var deposits []gov.Deposit + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &deposits) + require.NoError(f.T, err, "out %v\n, err %v", out, err) + return deposits +} + +//___________________________________________________________________________________ +// query slashing + +// QuerySlashingParams is gaiacli query slashing params +func (f *Fixtures) QuerySlashingParams() slashing.Params { + cmd := fmt.Sprintf("gaiacli query slashing params %s", f.Flags()) + res, errStr := tests.ExecuteT(f.T, cmd, "") + require.Empty(f.T, errStr) + cdc := app.MakeCodec() + var params slashing.Params + err := cdc.UnmarshalJSON([]byte(res), ¶ms) + require.NoError(f.T, err) + return params +} + +//___________________________________________________________________________________ +// executors + +func executeWriteCheckErr(t *testing.T, cmdStr string, writes ...string) { + require.True(t, executeWrite(t, cmdStr, writes...)) +} + +func executeWrite(t *testing.T, cmdStr string, writes ...string) (exitSuccess bool) { + exitSuccess, _, _ = executeWriteRetStdStreams(t, cmdStr, writes...) + return +} + +func executeWriteRetStdStreams(t *testing.T, cmdStr string, writes ...string) (bool, string, string) { + proc := tests.GoExecuteT(t, cmdStr) + + // Enables use of interactive commands + for _, write := range writes { + _, err := proc.StdinPipe.Write([]byte(write + "\n")) + require.NoError(t, err) + } + + // Read both stdout and stderr from the process + stdout, stderr, err := proc.ReadAll() + if err != nil { + fmt.Println("Err on proc.ReadAll()", err, cmdStr) + } + + // Log output. + if len(stdout) > 0 { + t.Log("Stdout:", cmn.Green(string(stdout))) + } + if len(stderr) > 0 { + t.Log("Stderr:", cmn.Red(string(stderr))) + } + + // Wait for process to exit + proc.Wait() + + // Return succes, stdout, stderr + return proc.ExitState.Success(), string(stdout), string(stderr) +} + +//___________________________________________________________________________________ +// utils + +func addFlags(cmd string, flags []string) string { + for _, f := range flags { + cmd += " " + f + } + return strings.TrimSpace(cmd) +} + +func queryTags(tags []string) (out string) { + for _, tag := range tags { + out += tag + "&" + } + return strings.TrimSuffix(out, "&") +} + +func writeToNewTempFile(t *testing.T, s string) *os.File { + fp, err := ioutil.TempFile(os.TempDir(), "cosmos_cli_test_") + require.Nil(t, err) + _, err = fp.WriteString(s) + require.Nil(t, err) + return fp +} + +func marshalStdTx(t *testing.T, stdTx auth.StdTx) []byte { + cdc := app.MakeCodec() + bz, err := cdc.MarshalBinaryBare(stdTx) + require.NoError(t, err) + return bz +} + +func unmarshalStdTx(t *testing.T, s string) (stdTx auth.StdTx) { + cdc := app.MakeCodec() + require.Nil(t, cdc.UnmarshalJSON([]byte(s), &stdTx)) + return +} diff --git a/cmd/gaia/cmd/gaiacli/main.go b/cmd/gaia/cmd/gaiacli/main.go index 823cb44fa7fe..176be4f97f92 100644 --- a/cmd/gaia/cmd/gaiacli/main.go +++ b/cmd/gaia/cmd/gaiacli/main.go @@ -30,15 +30,15 @@ import ( gov "github.com/cosmos/cosmos-sdk/x/gov/client/rest" sl "github.com/cosmos/cosmos-sdk/x/slashing" slashing "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" - st "github.com/cosmos/cosmos-sdk/x/stake" - stake "github.com/cosmos/cosmos-sdk/x/stake/client/rest" + st "github.com/cosmos/cosmos-sdk/x/staking" + staking "github.com/cosmos/cosmos-sdk/x/staking/client/rest" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" distClient "github.com/cosmos/cosmos-sdk/x/distribution/client" govClient "github.com/cosmos/cosmos-sdk/x/gov/client" slashingClient "github.com/cosmos/cosmos-sdk/x/slashing/client" - stakeClient "github.com/cosmos/cosmos-sdk/x/stake/client" + stakingClient "github.com/cosmos/cosmos-sdk/x/staking/client" _ "github.com/cosmos/cosmos-sdk/client/lcd/statik" ) @@ -66,7 +66,7 @@ func main() { mc := []sdk.ModuleClients{ govClient.NewModuleClient(gv.StoreKey, cdc), distClient.NewModuleClient(dist.StoreKey, cdc), - stakeClient.NewModuleClient(st.StoreKey, cdc), + stakingClient.NewModuleClient(st.StoreKey, cdc), slashingClient.NewModuleClient(sl.StoreKey, cdc), } @@ -157,7 +157,7 @@ func registerRoutes(rs *lcd.RestServer) { tx.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc) auth.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, at.StoreKey) bank.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) - stake.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) + staking.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) slashing.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) gov.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc) } diff --git a/cmd/gaia/cmd/gaiad/main.go b/cmd/gaia/cmd/gaiad/main.go index 2791415c9350..6d597eed7089 100644 --- a/cmd/gaia/cmd/gaiad/main.go +++ b/cmd/gaia/cmd/gaiad/main.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "github.com/cosmos/cosmos-sdk/store" "io" "github.com/cosmos/cosmos-sdk/baseapp" @@ -56,7 +57,7 @@ func main() { func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) abci.Application { return app.NewGaiaApp(logger, db, traceStore, true, - baseapp.SetPruning(viper.GetString("pruning")), + baseapp.SetPruning(store.NewPruningOptions(viper.GetString("pruning"))), baseapp.SetMinimumFees(viper.GetString("minimum_fees")), ) } diff --git a/cmd/gaia/cmd/gaiadebug/hack.go b/cmd/gaia/cmd/gaiadebug/hack.go index 41b9e41fafb3..022192861e37 100644 --- a/cmd/gaia/cmd/gaiadebug/hack.go +++ b/cmd/gaia/cmd/gaiadebug/hack.go @@ -7,6 +7,8 @@ import ( "os" "path" + "github.com/cosmos/cosmos-sdk/store" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/spf13/cobra" @@ -26,7 +28,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" gaia "github.com/cosmos/cosmos-sdk/cmd/gaia/app" ) @@ -48,7 +50,7 @@ func runHackCmd(cmd *cobra.Command, args []string) error { fmt.Println(err) os.Exit(1) } - app := NewGaiaApp(logger, db, baseapp.SetPruning(viper.GetString("pruning"))) + app := NewGaiaApp(logger, db, baseapp.SetPruning(store.NewPruningOptions(viper.GetString("pruning")))) // print some info id := app.LastCommitID() @@ -82,9 +84,9 @@ func runHackCmd(cmd *cobra.Command, args []string) error { ctx := app.NewContext(true, abci.Header{}) // check for the powerkey and the validator from the store - store := ctx.KVStore(app.keyStake) + store := ctx.KVStore(app.keyStaking) res := store.Get(powerKey) - val, _ := app.stakeKeeper.GetValidator(ctx, trouble) + val, _ := app.stakingKeeper.GetValidator(ctx, trouble) fmt.Println("checking height", checkHeight, res, val) if res == nil { bottomHeight = checkHeight @@ -131,8 +133,8 @@ type GaiaApp struct { // keys to access the substores keyMain *sdk.KVStoreKey keyAccount *sdk.KVStoreKey - keyStake *sdk.KVStoreKey - tkeyStake *sdk.TransientStoreKey + keyStaking *sdk.KVStoreKey + tkeyStaking *sdk.TransientStoreKey keySlashing *sdk.KVStoreKey keyParams *sdk.KVStoreKey tkeyParams *sdk.TransientStoreKey @@ -141,7 +143,7 @@ type GaiaApp struct { accountKeeper auth.AccountKeeper feeCollectionKeeper auth.FeeCollectionKeeper bankKeeper bank.Keeper - stakeKeeper stake.Keeper + stakingKeeper staking.Keeper slashingKeeper slashing.Keeper paramsKeeper params.Keeper } @@ -158,8 +160,8 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.BaseAp cdc: cdc, keyMain: sdk.NewKVStoreKey(bam.MainStoreKey), keyAccount: sdk.NewKVStoreKey(auth.StoreKey), - keyStake: sdk.NewKVStoreKey(stake.StoreKey), - tkeyStake: sdk.NewTransientStoreKey(stake.TStoreKey), + keyStaking: sdk.NewKVStoreKey(staking.StoreKey), + tkeyStaking: sdk.NewTransientStoreKey(staking.TStoreKey), keySlashing: sdk.NewKVStoreKey(slashing.StoreKey), keyParams: sdk.NewKVStoreKey(params.StoreKey), tkeyParams: sdk.NewTransientStoreKey(params.TStoreKey), @@ -177,20 +179,20 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.BaseAp // add handlers app.bankKeeper = bank.NewBaseKeeper(app.accountKeeper) - app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.tkeyStake, app.bankKeeper, app.paramsKeeper.Subspace(stake.DefaultParamspace), stake.DefaultCodespace) - app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.paramsKeeper.Subspace(slashing.DefaultParamspace), slashing.DefaultCodespace) + app.stakingKeeper = staking.NewKeeper(app.cdc, app.keyStaking, app.tkeyStaking, app.bankKeeper, app.paramsKeeper.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) + app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakingKeeper, app.paramsKeeper.Subspace(slashing.DefaultParamspace), slashing.DefaultCodespace) // register message routes app.Router(). AddRoute("bank", bank.NewHandler(app.bankKeeper)). - AddRoute(stake.RouterKey, stake.NewHandler(app.stakeKeeper)) + AddRoute(staking.RouterKey, staking.NewHandler(app.stakingKeeper)) // initialize BaseApp app.SetInitChainer(app.initChainer) app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) app.SetAnteHandler(auth.NewAnteHandler(app.accountKeeper, app.feeCollectionKeeper)) - app.MountStores(app.keyMain, app.keyAccount, app.keyStake, app.keySlashing, app.keyParams) + app.MountStores(app.keyMain, app.keyAccount, app.keyStaking, app.keySlashing, app.keyParams) app.MountStore(app.tkeyParams, sdk.StoreTypeTransient) err := app.LoadLatestVersion(app.keyMain) if err != nil { @@ -206,7 +208,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.BaseAp func MakeCodec() *codec.Codec { var cdc = codec.New() bank.RegisterCodec(cdc) - stake.RegisterCodec(cdc) + staking.RegisterCodec(cdc) slashing.RegisterCodec(cdc) auth.RegisterCodec(cdc) sdk.RegisterCodec(cdc) @@ -227,7 +229,7 @@ func (app *GaiaApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) ab // application updates every end block // nolint: unparam func (app *GaiaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - validatorUpdates, tags := stake.EndBlocker(ctx, app.stakeKeeper) + validatorUpdates, tags := staking.EndBlocker(ctx, app.stakingKeeper) return abci.ResponseEndBlock{ ValidatorUpdates: validatorUpdates, @@ -252,13 +254,13 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci app.accountKeeper.SetAccount(ctx, acc) } - // load the initial stake information - validators, err := stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData) + // load the initial staking information + validators, err := staking.InitGenesis(ctx, app.stakingKeeper, genesisState.StakingData) if err != nil { panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 // return sdk.ErrGenesisParse("").TraceCause(err, "") } - slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.SlashingData, genesisState.StakeData) + slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.SlashingData, genesisState.StakingData) return abci.ResponseInitChain{ Validators: validators, diff --git a/cmd/gaia/cmd/gaiareplay/main.go b/cmd/gaia/cmd/gaiareplay/main.go index 7e6392bf1230..cf946edce3c1 100644 --- a/cmd/gaia/cmd/gaiareplay/main.go +++ b/cmd/gaia/cmd/gaiareplay/main.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "github.com/cosmos/cosmos-sdk/store" "io" "os" "path/filepath" @@ -106,7 +107,7 @@ func run(rootDir string) { fmt.Println("Creating application") myapp := app.NewGaiaApp( ctx.Logger, appDB, traceStoreWriter, true, - baseapp.SetPruning("everything"), // nothing + baseapp.SetPruning(store.PruneEverything), // nothing ) // Genesis diff --git a/cmd/gaia/init/gentx.go b/cmd/gaia/init/gentx.go index 8e5480a541a1..13a7a3a879cb 100644 --- a/cmd/gaia/init/gentx.go +++ b/cmd/gaia/init/gentx.go @@ -26,12 +26,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/stake/client/cli" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/client/cli" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) const ( - defaultAmount = "100" + stakeTypes.DefaultBondDenom + defaultAmount = "100" + stakingTypes.DefaultBondDenom defaultCommissionRate = "0.1" defaultCommissionMaxRate = "0.2" defaultCommissionMaxChangeRate = "0.01" @@ -168,7 +168,7 @@ following delegation and commission default parameters: func accountInGenesis(genesisState app.GenesisState, key sdk.AccAddress, coins sdk.Coins) error { accountIsInGenesis := false - bondDenom := genesisState.StakeData.Params.BondDenom + bondDenom := genesisState.StakingData.Params.BondDenom // Check if the account is in genesis for _, acc := range genesisState.Accounts { diff --git a/cmd/gaia/init/testnet.go b/cmd/gaia/init/testnet.go index a5bca72c5107..5865827bb053 100644 --- a/cmd/gaia/init/testnet.go +++ b/cmd/gaia/init/testnet.go @@ -14,8 +14,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" authtx "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/stake" - staketypes "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -82,7 +82,7 @@ Example: client.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created", ) cmd.Flags().String( - flagMinimumFees, fmt.Sprintf("1%s", staketypes.DefaultBondDenom), "Validator minimum fees", + flagMinimumFees, fmt.Sprintf("1%s", stakingtypes.DefaultBondDenom), "Validator minimum fees", ) return cmd @@ -192,16 +192,16 @@ func initTestnet(config *tmconfig.Config, cdc *codec.Codec) error { Address: addr, Coins: sdk.Coins{ sdk.NewInt64Coin(fmt.Sprintf("%stoken", nodeDirName), 1000), - sdk.NewInt64Coin(staketypes.DefaultBondDenom, 500), + sdk.NewInt64Coin(stakingtypes.DefaultBondDenom, 500), }, }) - msg := stake.NewMsgCreateValidator( + msg := staking.NewMsgCreateValidator( sdk.ValAddress(addr), valPubKeys[i], - sdk.NewInt64Coin(staketypes.DefaultBondDenom, 100), - stake.NewDescription(nodeDirName, "", "", ""), - stake.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), + sdk.NewInt64Coin(stakingtypes.DefaultBondDenom, 100), + staking.NewDescription(nodeDirName, "", "", ""), + staking.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), ) tx := auth.NewStdTx([]sdk.Msg{msg}, auth.StdFee{}, []auth.StdSignature{}, memo) txBldr := authtx.NewTxBuilderFromCLI().WithChainID(chainID).WithMemo(memo) diff --git a/cmd/gaia/init/utils.go b/cmd/gaia/init/utils.go index 14c625d7f31e..149b4d10e1bb 100644 --- a/cmd/gaia/init/utils.go +++ b/cmd/gaia/init/utils.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "io/ioutil" + "path/filepath" "time" amino "github.com/tendermint/go-amino" @@ -16,6 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/cmd/gaia/app" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/server" ) // ExportGenesisFile creates and writes the genesis configuration to disk. An @@ -58,20 +60,6 @@ func ExportGenesisFileWithTime( return genDoc.SaveAs(genFile) } -// read of create the private key file for this config -func ReadOrCreatePrivValidator(privValFile string) crypto.PubKey { - var privValidator *privval.FilePV - - if common.FileExists(privValFile) { - privValidator = privval.LoadFilePV(privValFile) - } else { - privValidator = privval.GenFilePV(privValFile) - privValidator.Save() - } - - return privValidator.GetPubKey() -} - // InitializeNodeValidatorFiles creates private validator and p2p configuration files. func InitializeNodeValidatorFiles( config *cfg.Config) (nodeID string, valPubKey crypto.PubKey, err error, @@ -83,7 +71,19 @@ func InitializeNodeValidatorFiles( } nodeID = string(nodeKey.ID()) - valPubKey = ReadOrCreatePrivValidator(config.PrivValidatorFile()) + server.UpgradeOldPrivValFile(config) + + pvKeyFile := config.PrivValidatorKeyFile() + if err := common.EnsureDir(filepath.Dir(pvKeyFile), 0777); err != nil { + return nodeID, valPubKey, nil + } + + pvStateFile := config.PrivValidatorStateFile() + if err := common.EnsureDir(filepath.Dir(pvStateFile), 0777); err != nil { + return nodeID, valPubKey, nil + } + + valPubKey = privval.LoadOrGenFilePV(pvKeyFile, pvStateFile).GetPubKey() return nodeID, valPubKey, nil } diff --git a/docs/DOCS_README.md b/docs/DOCS_README.md index 60294769740f..5870d3e27e14 100644 --- a/docs/DOCS_README.md +++ b/docs/DOCS_README.md @@ -66,25 +66,25 @@ to send users to the GitHub. To build and serve the documentation locally, run: -``` +```bash npm install -g vuepress ``` then change the following line in the `config.js`: -``` +```js base: "/docs/", ``` to: -``` +```js base: "/", ``` Finally, go up one directory to the root of the repo and run: -``` +```bash # from root of repo vuepress build docs cd dist/docs @@ -113,14 +113,14 @@ much as possible with its [counterpart in the Tendermint Core repo](https://gith ### Update and Build the RPC docs 1. Execute the following command at the root directory to install the swagger-ui generate tool. - ``` + ```bash make tools ``` 2. Edit API docs 1. Directly Edit API docs manually: `client/lcd/swagger-ui/swagger.yaml`. - 2. Edit API docs within [SwaggerHub](https://app.swaggerhub.com). Please refer to this [document](https://app.swaggerhub.com/help/index) for how to use the about website to edit API docs. + 2. Edit API docs within the [Swagger Editor](https://editor.swagger.io/). Please refer to this [document](https://swagger.io/docs/specification/2-0/basic-structure/) for the correct structure in `.yaml`. 3. Download `swagger.yaml` and replace the old `swagger.yaml` under fold `client/lcd/swagger-ui`. 4. Compile gaiacli - ``` + ```bash make install ``` diff --git a/docs/examples/basecoin/cmd/basecli/main.go b/docs/examples/basecoin/cmd/basecli/main.go index 10fa9fd1e6b4..451494b02848 100644 --- a/docs/examples/basecoin/cmd/basecli/main.go +++ b/docs/examples/basecoin/cmd/basecli/main.go @@ -23,9 +23,9 @@ import ( sl "github.com/cosmos/cosmos-sdk/x/slashing" slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" slashing "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" - st "github.com/cosmos/cosmos-sdk/x/stake" - stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" - stake "github.com/cosmos/cosmos-sdk/x/stake/client/rest" + st "github.com/cosmos/cosmos-sdk/x/staking" + stakingcmd "github.com/cosmos/cosmos-sdk/x/staking/client/cli" + staking "github.com/cosmos/cosmos-sdk/x/staking/client/rest" ) // rootCmd is the entry point for this binary @@ -65,20 +65,20 @@ func main() { // add query/post commands (custom to binary) rootCmd.AddCommand( - stakecmd.GetCmdQueryValidator(st.StoreKey, cdc), - stakecmd.GetCmdQueryValidators(st.StoreKey, cdc), - stakecmd.GetCmdQueryValidatorUnbondingDelegations(st.StoreKey, cdc), - stakecmd.GetCmdQueryValidatorRedelegations(st.StoreKey, cdc), - stakecmd.GetCmdQueryDelegation(st.StoreKey, cdc), - stakecmd.GetCmdQueryDelegations(st.StoreKey, cdc), - stakecmd.GetCmdQueryPool(st.StoreKey, cdc), - stakecmd.GetCmdQueryParams(st.StoreKey, cdc), - stakecmd.GetCmdQueryUnbondingDelegation(st.StoreKey, cdc), - stakecmd.GetCmdQueryUnbondingDelegations(st.StoreKey, cdc), - stakecmd.GetCmdQueryRedelegation(st.StoreKey, cdc), - stakecmd.GetCmdQueryRedelegations(st.StoreKey, cdc), + stakingcmd.GetCmdQueryValidator(st.StoreKey, cdc), + stakingcmd.GetCmdQueryValidators(st.StoreKey, cdc), + stakingcmd.GetCmdQueryValidatorUnbondingDelegations(st.StoreKey, cdc), + stakingcmd.GetCmdQueryValidatorRedelegations(st.StoreKey, cdc), + stakingcmd.GetCmdQueryDelegation(st.StoreKey, cdc), + stakingcmd.GetCmdQueryDelegations(st.StoreKey, cdc), + stakingcmd.GetCmdQueryPool(st.StoreKey, cdc), + stakingcmd.GetCmdQueryParams(st.StoreKey, cdc), + stakingcmd.GetCmdQueryUnbondingDelegation(st.StoreKey, cdc), + stakingcmd.GetCmdQueryUnbondingDelegations(st.StoreKey, cdc), + stakingcmd.GetCmdQueryRedelegation(st.StoreKey, cdc), + stakingcmd.GetCmdQueryRedelegations(st.StoreKey, cdc), slashingcmd.GetCmdQuerySigningInfo(sl.StoreKey, cdc), - stakecmd.GetCmdQueryValidatorDelegations(st.StoreKey, cdc), + stakingcmd.GetCmdQueryValidatorDelegations(st.StoreKey, cdc), authcmd.GetAccountCmd(at.StoreKey, cdc), ) @@ -86,11 +86,11 @@ func main() { bankcmd.SendTxCmd(cdc), ibccmd.IBCTransferCmd(cdc), ibccmd.IBCRelayCmd(cdc), - stakecmd.GetCmdCreateValidator(cdc), - stakecmd.GetCmdEditValidator(cdc), - stakecmd.GetCmdDelegate(cdc), - stakecmd.GetCmdUnbond(st.StoreKey, cdc), - stakecmd.GetCmdRedelegate(st.StoreKey, cdc), + stakingcmd.GetCmdCreateValidator(cdc), + stakingcmd.GetCmdEditValidator(cdc), + stakingcmd.GetCmdDelegate(cdc), + stakingcmd.GetCmdUnbond(st.StoreKey, cdc), + stakingcmd.GetCmdRedelegate(st.StoreKey, cdc), slashingcmd.GetCmdUnjail(cdc), ) @@ -118,6 +118,6 @@ func registerRoutes(rs *lcd.RestServer) { tx.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc) auth.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, at.StoreKey) bank.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) - stake.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) + staking.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) slashing.RegisterRoutes(rs.CliCtx, rs.Mux, rs.Cdc, rs.KeyBase) } diff --git a/docs/examples/basecoin/cmd/basecoind/main.go b/docs/examples/basecoin/cmd/basecoind/main.go index 9cb246671858..cca6b2e42f52 100644 --- a/docs/examples/basecoin/cmd/basecoind/main.go +++ b/docs/examples/basecoin/cmd/basecoind/main.go @@ -6,7 +6,10 @@ import ( "io" "os" + "github.com/cosmos/cosmos-sdk/store" + "github.com/tendermint/tendermint/p2p" + "github.com/tendermint/tendermint/privval" "github.com/cosmos/cosmos-sdk/baseapp" gaiaInit "github.com/cosmos/cosmos-sdk/cmd/gaia/init" @@ -77,7 +80,8 @@ func InitCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { } nodeID := string(nodeKey.ID()) - pk := gaiaInit.ReadOrCreatePrivValidator(config.PrivValidatorFile()) + pk := privval.LoadOrGenFilePV(config.PrivValidatorKeyFile(), + config.PrivValidatorStateFile()).GetPubKey() genTx, appMessage, validator, err := server.SimpleAppGenTx(cdc, pk) if err != nil { return err @@ -122,7 +126,7 @@ func InitCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { } func newApp(logger log.Logger, db dbm.DB, storeTracer io.Writer) abci.Application { - return app.NewBasecoinApp(logger, db, baseapp.SetPruning(viper.GetString("pruning"))) + return app.NewBasecoinApp(logger, db, baseapp.SetPruning(store.NewPruningOptions(viper.GetString("pruning")))) } func exportAppStateAndTMValidators(logger log.Logger, db dbm.DB, storeTracer io.Writer, _ int64, _ bool) ( diff --git a/docs/examples/democoin/app/app.go b/docs/examples/democoin/app/app.go index cbfe6e5c330a..c22a20248b65 100644 --- a/docs/examples/democoin/app/app.go +++ b/docs/examples/democoin/app/app.go @@ -17,12 +17,12 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/ibc" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/docs/examples/democoin/types" "github.com/cosmos/cosmos-sdk/docs/examples/democoin/x/cool" "github.com/cosmos/cosmos-sdk/docs/examples/democoin/x/pow" - "github.com/cosmos/cosmos-sdk/docs/examples/democoin/x/simplestake" + "github.com/cosmos/cosmos-sdk/docs/examples/democoin/x/simplestaking" "github.com/cosmos/cosmos-sdk/docs/examples/democoin/x/sketchy" ) @@ -57,7 +57,7 @@ type DemocoinApp struct { coolKeeper cool.Keeper powKeeper pow.Keeper ibcMapper ibc.Mapper - stakeKeeper simplestake.Keeper + stakingKeeper simplestaking.Keeper // Manage getting and setting accounts accountKeeper auth.AccountKeeper @@ -76,7 +76,7 @@ func NewDemocoinApp(logger log.Logger, db dbm.DB) *DemocoinApp { capKeyAccountStore: sdk.NewKVStoreKey(auth.StoreKey), capKeyPowStore: sdk.NewKVStoreKey("pow"), capKeyIBCStore: sdk.NewKVStoreKey("ibc"), - capKeyStakingStore: sdk.NewKVStoreKey(stake.StoreKey), + capKeyStakingStore: sdk.NewKVStoreKey(staking.StoreKey), keyParams: sdk.NewKVStoreKey("params"), tkeyParams: sdk.NewTransientStoreKey("transient_params"), } @@ -96,14 +96,14 @@ func NewDemocoinApp(logger log.Logger, db dbm.DB) *DemocoinApp { app.coolKeeper = cool.NewKeeper(app.capKeyMainStore, app.bankKeeper, cool.DefaultCodespace) app.powKeeper = pow.NewKeeper(app.capKeyPowStore, pow.NewConfig("pow", int64(1)), app.bankKeeper, pow.DefaultCodespace) app.ibcMapper = ibc.NewMapper(app.cdc, app.capKeyIBCStore, ibc.DefaultCodespace) - app.stakeKeeper = simplestake.NewKeeper(app.capKeyStakingStore, app.bankKeeper, simplestake.DefaultCodespace) + app.stakingKeeper = simplestaking.NewKeeper(app.capKeyStakingStore, app.bankKeeper, simplestaking.DefaultCodespace) app.Router(). AddRoute("bank", bank.NewHandler(app.bankKeeper)). AddRoute("cool", cool.NewHandler(app.coolKeeper)). AddRoute("pow", app.powKeeper.Handler). AddRoute("sketchy", sketchy.NewHandler()). AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.bankKeeper)). - AddRoute("simplestake", simplestake.NewHandler(app.stakeKeeper)) + AddRoute("simplestaking", simplestaking.NewHandler(app.stakingKeeper)) // Initialize BaseApp. app.SetInitChainer(app.initChainerFn(app.coolKeeper, app.powKeeper)) @@ -128,7 +128,7 @@ func MakeCodec() *codec.Codec { pow.RegisterCodec(cdc) bank.RegisterCodec(cdc) ibc.RegisterCodec(cdc) - simplestake.RegisterCodec(cdc) + simplestaking.RegisterCodec(cdc) // Register AppAccount cdc.RegisterInterface((*auth.Account)(nil), nil) diff --git a/docs/examples/democoin/cmd/democli/main.go b/docs/examples/democoin/cmd/democli/main.go index c0843540aa30..07ded7f20651 100644 --- a/docs/examples/democoin/cmd/democli/main.go +++ b/docs/examples/democoin/cmd/democli/main.go @@ -21,7 +21,7 @@ import ( "github.com/cosmos/cosmos-sdk/docs/examples/democoin/app" coolcmd "github.com/cosmos/cosmos-sdk/docs/examples/democoin/x/cool/client/cli" powcmd "github.com/cosmos/cosmos-sdk/docs/examples/democoin/x/pow/client/cli" - simplestakingcmd "github.com/cosmos/cosmos-sdk/docs/examples/democoin/x/simplestake/client/cli" + simplestakingcmd "github.com/cosmos/cosmos-sdk/docs/examples/democoin/x/simplestaking/client/cli" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/docs/examples/democoin/cmd/democoind/main.go b/docs/examples/democoin/cmd/democoind/main.go index f0553ee5d3e7..8ac1b8cf4278 100644 --- a/docs/examples/democoin/cmd/democoind/main.go +++ b/docs/examples/democoin/cmd/democoind/main.go @@ -9,6 +9,7 @@ import ( "github.com/spf13/viper" "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/p2p" + "github.com/tendermint/tendermint/privval" "github.com/cosmos/cosmos-sdk/client" @@ -81,7 +82,8 @@ func InitCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { } nodeID := string(nodeKey.ID()) - pk := gaiaInit.ReadOrCreatePrivValidator(config.PrivValidatorFile()) + pk := privval.LoadOrGenFilePV(config.PrivValidatorKeyFile(), + config.PrivValidatorStateFile()).GetPubKey() genTx, appMessage, validator, err := server.SimpleAppGenTx(cdc, pk) if err != nil { return err diff --git a/docs/examples/democoin/x/simplestake/codec.go b/docs/examples/democoin/x/simplestake/codec.go deleted file mode 100644 index 7813fd64234f..000000000000 --- a/docs/examples/democoin/x/simplestake/codec.go +++ /dev/null @@ -1,11 +0,0 @@ -package simplestake - -import ( - "github.com/cosmos/cosmos-sdk/codec" -) - -// Register concrete types on codec codec -func RegisterCodec(cdc *codec.Codec) { - cdc.RegisterConcrete(MsgBond{}, "simplestake/BondMsg", nil) - cdc.RegisterConcrete(MsgUnbond{}, "simplestake/UnbondMsg", nil) -} diff --git a/docs/examples/democoin/x/simplestake/client/cli/commands.go b/docs/examples/democoin/x/simplestaking/client/cli/commands.go similarity index 87% rename from docs/examples/democoin/x/simplestake/client/cli/commands.go rename to docs/examples/democoin/x/simplestaking/client/cli/commands.go index 8717a5f3ba93..5a2b819f3f62 100644 --- a/docs/examples/democoin/x/simplestake/client/cli/commands.go +++ b/docs/examples/democoin/x/simplestaking/client/cli/commands.go @@ -6,7 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/docs/examples/democoin/x/simplestake" + "github.com/cosmos/cosmos-sdk/docs/examples/democoin/x/simplestaking" sdk "github.com/cosmos/cosmos-sdk/types" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" @@ -17,7 +17,7 @@ import ( ) const ( - flagStake = "stake" + flagStake = "staking" flagValidator = "validator" ) @@ -37,9 +37,9 @@ func BondTxCmd(cdc *codec.Codec) *cobra.Command { return err } - stakeString := viper.GetString(flagStake) - if len(stakeString) == 0 { - return fmt.Errorf("specify coins to bond with --stake") + stakingString := viper.GetString(flagStake) + if len(stakingString) == 0 { + return fmt.Errorf("specify coins to bond with --staking") } valString := viper.GetString(flagValidator) @@ -47,7 +47,7 @@ func BondTxCmd(cdc *codec.Codec) *cobra.Command { return fmt.Errorf("specify pubkey to bond to with --validator") } - stake, err := sdk.ParseCoin(stakeString) + staking, err := sdk.ParseCoin(stakingString) if err != nil { return err } @@ -60,7 +60,7 @@ func BondTxCmd(cdc *codec.Codec) *cobra.Command { var pubKeyEd ed25519.PubKeyEd25519 copy(pubKeyEd[:], rawPubKey) - msg := simplestake.NewMsgBond(from, stake, pubKeyEd) + msg := simplestaking.NewMsgBond(from, staking, pubKeyEd) // Build and sign the transaction, then broadcast to a Tendermint // node. @@ -89,7 +89,7 @@ func UnbondTxCmd(cdc *codec.Codec) *cobra.Command { return err } - msg := simplestake.NewMsgUnbond(from) + msg := simplestaking.NewMsgUnbond(from) // Build and sign the transaction, then broadcast to a Tendermint // node. diff --git a/docs/examples/democoin/x/simplestaking/codec.go b/docs/examples/democoin/x/simplestaking/codec.go new file mode 100644 index 000000000000..1bc866a39396 --- /dev/null +++ b/docs/examples/democoin/x/simplestaking/codec.go @@ -0,0 +1,11 @@ +package simplestaking + +import ( + "github.com/cosmos/cosmos-sdk/codec" +) + +// Register concrete types on codec codec +func RegisterCodec(cdc *codec.Codec) { + cdc.RegisterConcrete(MsgBond{}, "simplestaking/BondMsg", nil) + cdc.RegisterConcrete(MsgUnbond{}, "simplestaking/UnbondMsg", nil) +} diff --git a/docs/examples/democoin/x/simplestake/errors.go b/docs/examples/democoin/x/simplestaking/errors.go similarity index 89% rename from docs/examples/democoin/x/simplestake/errors.go rename to docs/examples/democoin/x/simplestaking/errors.go index a0fc6e1accd0..f5ec400085e4 100644 --- a/docs/examples/democoin/x/simplestake/errors.go +++ b/docs/examples/democoin/x/simplestaking/errors.go @@ -1,14 +1,14 @@ -package simplestake +package simplestaking import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// simple stake errors reserve 300 ~ 399. +// simple staking errors reserve 300 ~ 399. const ( DefaultCodespace sdk.CodespaceType = moduleName - // simplestake errors reserve 300 - 399. + // simplestaking errors reserve 300 - 399. CodeEmptyValidator sdk.CodeType = 300 CodeInvalidUnbond sdk.CodeType = 301 CodeEmptyStake sdk.CodeType = 302 diff --git a/docs/examples/democoin/x/simplestake/handler.go b/docs/examples/democoin/x/simplestaking/handler.go similarity index 87% rename from docs/examples/democoin/x/simplestake/handler.go rename to docs/examples/democoin/x/simplestaking/handler.go index 104058eec2c1..d8cb46e812dd 100644 --- a/docs/examples/democoin/x/simplestake/handler.go +++ b/docs/examples/democoin/x/simplestaking/handler.go @@ -1,10 +1,10 @@ -package simplestake +package simplestaking import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// NewHandler returns a handler for "simplestake" type messages. +// NewHandler returns a handler for "simplestaking" type messages. func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { switch msg.(type) { diff --git a/docs/examples/democoin/x/simplestake/keeper.go b/docs/examples/democoin/x/simplestaking/keeper.go similarity index 81% rename from docs/examples/democoin/x/simplestake/keeper.go rename to docs/examples/democoin/x/simplestaking/keeper.go index fe459267d43b..87551f1c0e0f 100644 --- a/docs/examples/democoin/x/simplestake/keeper.go +++ b/docs/examples/democoin/x/simplestaking/keeper.go @@ -1,4 +1,4 @@ -package simplestake +package simplestaking import ( "github.com/tendermint/tendermint/crypto" @@ -6,12 +6,12 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/bank" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) -const moduleName = "simplestake" +const moduleName = "simplestaking" -// simple stake keeper +// simple staking keeper type Keeper struct { ck bank.Keeper @@ -60,12 +60,12 @@ func (k Keeper) deleteBondInfo(ctx sdk.Context, addr sdk.AccAddress) { } // register a bond with the keeper -func (k Keeper) Bond(ctx sdk.Context, addr sdk.AccAddress, pubKey crypto.PubKey, stake sdk.Coin) (int64, sdk.Error) { - if stake.Denom != stakeTypes.DefaultBondDenom { +func (k Keeper) Bond(ctx sdk.Context, addr sdk.AccAddress, pubKey crypto.PubKey, staking sdk.Coin) (int64, sdk.Error) { + if staking.Denom != stakingTypes.DefaultBondDenom { return 0, ErrIncorrectStakingToken(k.codespace) } - _, _, err := k.ck.SubtractCoins(ctx, addr, []sdk.Coin{stake}) + _, _, err := k.ck.SubtractCoins(ctx, addr, []sdk.Coin{staking}) if err != nil { return 0, err } @@ -78,7 +78,7 @@ func (k Keeper) Bond(ctx sdk.Context, addr sdk.AccAddress, pubKey crypto.PubKey, } } - bi.Power = bi.Power + stake.Amount.Int64() + bi.Power = bi.Power + staking.Amount.Int64() k.setBondInfo(ctx, addr, bi) return bi.Power, nil @@ -92,7 +92,7 @@ func (k Keeper) Unbond(ctx sdk.Context, addr sdk.AccAddress) (crypto.PubKey, int } k.deleteBondInfo(ctx, addr) - returnedBond := sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, bi.Power) + returnedBond := sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, bi.Power) _, _, err := k.ck.AddCoins(ctx, addr, []sdk.Coin{returnedBond}) if err != nil { @@ -104,8 +104,8 @@ func (k Keeper) Unbond(ctx sdk.Context, addr sdk.AccAddress) (crypto.PubKey, int // FOR TESTING PURPOSES ------------------------------------------------- -func (k Keeper) bondWithoutCoins(ctx sdk.Context, addr sdk.AccAddress, pubKey crypto.PubKey, stake sdk.Coin) (int64, sdk.Error) { - if stake.Denom != stakeTypes.DefaultBondDenom { +func (k Keeper) bondWithoutCoins(ctx sdk.Context, addr sdk.AccAddress, pubKey crypto.PubKey, staking sdk.Coin) (int64, sdk.Error) { + if staking.Denom != stakingTypes.DefaultBondDenom { return 0, ErrIncorrectStakingToken(k.codespace) } @@ -117,7 +117,7 @@ func (k Keeper) bondWithoutCoins(ctx sdk.Context, addr sdk.AccAddress, pubKey cr } } - bi.Power = bi.Power + stake.Amount.Int64() + bi.Power = bi.Power + staking.Amount.Int64() k.setBondInfo(ctx, addr, bi) return bi.Power, nil diff --git a/docs/examples/democoin/x/simplestake/keeper_test.go b/docs/examples/democoin/x/simplestaking/keeper_test.go similarity index 74% rename from docs/examples/democoin/x/simplestake/keeper_test.go rename to docs/examples/democoin/x/simplestaking/keeper_test.go index 8ad87e530b27..ef83f4256716 100644 --- a/docs/examples/democoin/x/simplestake/keeper_test.go +++ b/docs/examples/democoin/x/simplestaking/keeper_test.go @@ -1,4 +1,4 @@ -package simplestake +package simplestaking import ( "fmt" @@ -17,7 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/params" - staketypes "github.com/cosmos/cosmos-sdk/x/stake/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) type testInput struct { @@ -55,10 +55,10 @@ func TestKeeperGetSet(t *testing.T) { input := setupTestInput() ctx := input.ctx - stakeKeeper := NewKeeper(input.capKey, input.bk, DefaultCodespace) + stakingKeeper := NewKeeper(input.capKey, input.bk, DefaultCodespace) addr := sdk.AccAddress([]byte("some-address")) - bi := stakeKeeper.getBondInfo(ctx, addr) + bi := stakingKeeper.getBondInfo(ctx, addr) require.Equal(t, bi, bondInfo{}) privKey := ed25519.GenPrivKey() @@ -68,9 +68,9 @@ func TestKeeperGetSet(t *testing.T) { Power: int64(10), } fmt.Printf("Pubkey: %v\n", privKey.PubKey()) - stakeKeeper.setBondInfo(ctx, addr, bi) + stakingKeeper.setBondInfo(ctx, addr, bi) - savedBi := stakeKeeper.getBondInfo(ctx, addr) + savedBi := stakingKeeper.getBondInfo(ctx, addr) require.NotNil(t, savedBi) fmt.Printf("Bond Info: %v\n", savedBi) require.Equal(t, int64(10), savedBi.Power) @@ -80,25 +80,25 @@ func TestBonding(t *testing.T) { input := setupTestInput() ctx := input.ctx - stakeKeeper := NewKeeper(input.capKey, input.bk, DefaultCodespace) + stakingKeeper := NewKeeper(input.capKey, input.bk, DefaultCodespace) addr := sdk.AccAddress([]byte("some-address")) privKey := ed25519.GenPrivKey() pubKey := privKey.PubKey() - _, _, err := stakeKeeper.unbondWithoutCoins(ctx, addr) + _, _, err := stakingKeeper.unbondWithoutCoins(ctx, addr) require.Equal(t, err, ErrInvalidUnbond(DefaultCodespace)) - _, err = stakeKeeper.bondWithoutCoins(ctx, addr, pubKey, sdk.NewInt64Coin(staketypes.DefaultBondDenom, 10)) + _, err = stakingKeeper.bondWithoutCoins(ctx, addr, pubKey, sdk.NewInt64Coin(stakingtypes.DefaultBondDenom, 10)) require.Nil(t, err) - power, err := stakeKeeper.bondWithoutCoins(ctx, addr, pubKey, sdk.NewInt64Coin(staketypes.DefaultBondDenom, 10)) + power, err := stakingKeeper.bondWithoutCoins(ctx, addr, pubKey, sdk.NewInt64Coin(stakingtypes.DefaultBondDenom, 10)) require.Nil(t, err) require.Equal(t, int64(20), power) - pk, _, err := stakeKeeper.unbondWithoutCoins(ctx, addr) + pk, _, err := stakingKeeper.unbondWithoutCoins(ctx, addr) require.Nil(t, err) require.Equal(t, pubKey, pk) - _, _, err = stakeKeeper.unbondWithoutCoins(ctx, addr) + _, _, err = stakingKeeper.unbondWithoutCoins(ctx, addr) require.Equal(t, err, ErrInvalidUnbond(DefaultCodespace)) } diff --git a/docs/examples/democoin/x/simplestake/msgs.go b/docs/examples/democoin/x/simplestaking/msgs.go similarity index 94% rename from docs/examples/democoin/x/simplestake/msgs.go rename to docs/examples/democoin/x/simplestaking/msgs.go index f3edb4ce0d84..1f3af1a6783a 100644 --- a/docs/examples/democoin/x/simplestake/msgs.go +++ b/docs/examples/democoin/x/simplestaking/msgs.go @@ -1,4 +1,4 @@ -package simplestake +package simplestaking import ( "encoding/json" @@ -26,7 +26,7 @@ func NewMsgBond(addr sdk.AccAddress, stake sdk.Coin, pubKey crypto.PubKey) MsgBo } //nolint -func (msg MsgBond) Route() string { return moduleName } //TODO update "stake/createvalidator" +func (msg MsgBond) Route() string { return moduleName } //TODO update "staking/createvalidator" func (msg MsgBond) Type() string { return "bond" } func (msg MsgBond) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Address} } @@ -66,7 +66,7 @@ func NewMsgUnbond(addr sdk.AccAddress) MsgUnbond { } //nolint -func (msg MsgUnbond) Route() string { return moduleName } //TODO update "stake/createvalidator" +func (msg MsgUnbond) Route() string { return moduleName } //TODO update "staking/createvalidator" func (msg MsgUnbond) Type() string { return "unbond" } func (msg MsgUnbond) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Address} } func (msg MsgUnbond) ValidateBasic() sdk.Error { return nil } diff --git a/docs/examples/democoin/x/simplestake/msgs_test.go b/docs/examples/democoin/x/simplestaking/msgs_test.go similarity index 96% rename from docs/examples/democoin/x/simplestake/msgs_test.go rename to docs/examples/democoin/x/simplestaking/msgs_test.go index 4eb4509d8935..c9e692407a4a 100644 --- a/docs/examples/democoin/x/simplestake/msgs_test.go +++ b/docs/examples/democoin/x/simplestaking/msgs_test.go @@ -1,4 +1,4 @@ -package simplestake +package simplestaking import ( "testing" diff --git a/docs/examples/democoin/x/simplestake/types.go b/docs/examples/democoin/x/simplestaking/types.go similarity index 90% rename from docs/examples/democoin/x/simplestake/types.go rename to docs/examples/democoin/x/simplestaking/types.go index 937d36d6506e..7e6d74d3ed69 100644 --- a/docs/examples/democoin/x/simplestake/types.go +++ b/docs/examples/democoin/x/simplestaking/types.go @@ -1,4 +1,4 @@ -package simplestake +package simplestaking import "github.com/tendermint/tendermint/crypto" diff --git a/docs/gaia/deploy-testnet.md b/docs/gaia/deploy-testnet.md index 7323585d871c..c617e2052bc8 100644 --- a/docs/gaia/deploy-testnet.md +++ b/docs/gaia/deploy-testnet.md @@ -33,7 +33,7 @@ gaiacli keys add validator # Add that key into the genesis.app_state.accounts array in the genesis file # NOTE: this command lets you set the number of coins. Make sure this account has some coins -# with the genesis.app_state.stake.params.bond_denom denom, the default is stake +# with the genesis.app_state.staking.params.bond_denom denom, the default is staking gaiad add-genesis-account $(gaiacli keys show validator -a) 1000stake,1000validatortoken # Generate the transaction that creates your validator diff --git a/docs/gaia/gaiacli.md b/docs/gaia/gaiacli.md index 50d4b4407279..7e7274ef9653 100644 --- a/docs/gaia/gaiacli.md +++ b/docs/gaia/gaiacli.md @@ -226,7 +226,7 @@ The action tag always equals the message type returned by the `Type()` function You can find a list of available `tags` on each of the SDK modules: - [Common tags](https://github.com/cosmos/cosmos-sdk/blob/d1e76221d8e28824bb4791cb4ad8662d2ae9051e/types/tags.go#L57-L63) -- [Staking tags](https://github.com/cosmos/cosmos-sdk/blob/d1e76221d8e28824bb4791cb4ad8662d2ae9051e/x/stake/tags/tags.go#L8-L24) +- [Staking tags](https://github.com/cosmos/cosmos-sdk/blob/d1e76221d8e28824bb4791cb4ad8662d2ae9051e/x/staking/tags/tags.go#L8-L24) - [Governance tags](https://github.com/cosmos/cosmos-sdk/blob/d1e76221d8e28824bb4791cb4ad8662d2ae9051e/x/gov/tags/tags.go#L8-L22) - [Slashing tags](https://github.com/cosmos/cosmos-sdk/blob/d1e76221d8e28824bb4791cb4ad8662d2ae9051e/x/slashing/handler.go#L52) - [Distribution tags](https://github.com/cosmos/cosmos-sdk/blob/develop/x/distribution/tags/tags.go#L8-L17) @@ -282,13 +282,13 @@ On the upcoming mainnet, you can delegate `atom` to a validator. These [delegato You can query the list of all validators of a specific chain: ```bash -gaiacli query stake validators +gaiacli query staking validators ``` If you want to get the information of a single validator you can check it with: ```bash -gaiacli query stake validator +gaiacli query staking validator ``` #### Bond Tokens @@ -296,7 +296,7 @@ gaiacli query stake validator On the testnet, we delegate `steak` instead of `atom`. Here's how you can bond tokens to a testnet validator (_i.e._ delegate): ```bash -gaiacli tx stake delegate \ +gaiacli tx staking delegate \ --amount=10steak \ --validator= \ --from= \ @@ -322,7 +322,7 @@ Don't use more `steak` thank you have! You can always get more by using the [Fau Once submitted a delegation to a validator, you can see it's information by using the following command: ```bash -gaiacli query stake delegation \ +gaiacli query staking delegation \ --address-delegator= \ --validator= ``` @@ -330,7 +330,7 @@ gaiacli query stake delegation \ Or if you want to check all your current delegations with disctinct validators: ```bash -gaiacli query stake delegations +gaiacli query staking delegations ``` You can also get previous delegation(s) status by adding the `--height` flag. @@ -340,7 +340,7 @@ You can also get previous delegation(s) status by adding the `--height` flag. If for any reason the validator misbehaves, or you just want to unbond a certain amount of tokens, use this following command. You can unbond a specific `shares-amount` (eg:`12.1`\) or a `shares-fraction` (eg:`0.25`) with the corresponding flags. ```bash -gaiacli tx stake unbond \ +gaiacli tx staking unbond \ --validator= \ --shares-fraction=0.5 \ --from= \ @@ -354,7 +354,7 @@ The unbonding will be automatically completed when the unbonding period has pass Once you begin an unbonding-delegation, you can see it's information by using the following command: ```bash -gaiacli query stake unbonding-delegation \ +gaiacli query staking unbonding-delegation \ --address-delegator= \ --validator= \ ``` @@ -362,13 +362,13 @@ gaiacli query stake unbonding-delegation \ Or if you want to check all your current unbonding-delegations with disctinct validators: ```bash -gaiacli query stake unbonding-delegations +gaiacli query staking unbonding-delegations ``` Additionally, as you can get all the unbonding-delegations from a particular validator: ```bash - gaiacli query stake unbonding-delegations-from + gaiacli query staking unbonding-delegations-from ``` To get previous unbonding-delegation(s) status on past blocks, try adding the `--height` flag. @@ -378,7 +378,7 @@ To get previous unbonding-delegation(s) status on past blocks, try adding the `- A redelegation is a type delegation that allows you to bond illiquid tokens from one validator to another: ```bash -gaiacli tx stake redelegate \ +gaiacli tx staking redelegate \ --addr-validator-source= \ --addr-validator-dest= \ --shares-fraction=50 \ @@ -395,7 +395,7 @@ The redelegation will be automatically completed when the unbonding period has p Once you begin an redelegation, you can see it's information by using the following command: ```bash -gaiacli query stake redelegation \ +gaiacli query staking redelegation \ --address-delegator= \ --addr-validator-source= \ --addr-validator-dest= \ @@ -404,13 +404,13 @@ gaiacli query stake redelegation \ Or if you want to check all your current unbonding-delegations with disctinct validators: ```bash -gaiacli query stake redelegations +gaiacli query staking redelegations ``` Additionally, as you can get all the outgoing redelegations from a particular validator: ```bash - gaiacli query stake redelegations-from + gaiacli query staking redelegations-from ``` To get previous redelegation(s) status on past blocks, try adding the `--height` flag. @@ -420,7 +420,7 @@ To get previous redelegation(s) status on past blocks, try adding the `--height` Parameters define high level settings for staking. You can get the current values by using: ```bash -gaiacli query stake parameters +gaiacli query staking parameters ``` With the above command you will get the values for: @@ -436,7 +436,7 @@ All these values will be subject to updates though a `governance` process by `Pa A staking `Pool` defines the dynamic parameters of the current state. You can query them with the following command: ```bash -gaiacli query stake pool +gaiacli query staking pool ``` With the `pool` command you will get the values for: diff --git a/docs/gaia/validators/validator-setup.md b/docs/gaia/validators/validator-setup.md index 1495a82d0d60..cac1508d0402 100644 --- a/docs/gaia/validators/validator-setup.md +++ b/docs/gaia/validators/validator-setup.md @@ -33,7 +33,7 @@ Don't use more `STAKE` thank you have! You can always get more by using the [Fau ::: ```bash -gaiacli tx stake create-validator \ +gaiacli tx staking create-validator \ --amount=5STAKE \ --pubkey=$(gaiad tendermint show-validator) \ --moniker="choose a moniker" \ @@ -91,7 +91,7 @@ A `gentx` is a JSON file carrying a self-delegation. All genesis transactions ar In this case, you need both the signature of the validator and the delegator. Start by creating an unsigned `create-validator` transaction, and save it in a file called `unsignedValTx`: ```bash -gaiacli tx stake create-validator \ +gaiacli tx staking create-validator \ --amount=5STAKE \ --pubkey=$(gaiad tendermint show-validator) \ --moniker="choose a moniker" \ @@ -140,7 +140,7 @@ Once you've collected all genesis transactions in `~/.gaiad/config/gentx`, you c gaiad collect-gentxs ``` -__Note:__ The accounts from which you delegate in the `gentx` transactions need to possess staking tokens in the genesis file, otherwise `collect-gentx` will fail. +__Note:__ The accounts from which you delegate in the `gentx` transactions need to possess stake tokens in the genesis file, otherwise `collect-gentx` will fail. The previous command will collect all genesis transactions and finalise `genesis.json`. To verify the correctness of the configuration and start the node run: @@ -155,7 +155,7 @@ You can edit your validator's public description. This info is to identify your The `--identity` can be used as to verify identity with systems like Keybase or UPort. When using with Keybase `--identity` should be populated with a 16-digit string that is generated with a [keybase.io](https://keybase.io) account. It's a cryptographically secure method of verifying your identity across multiple online networks. The Keybase API allows us to retrieve your Keybase avatar. This is how you can add a logo to your validator profile. ```bash -gaiacli tx stake edit-validator +gaiacli tx staking edit-validator --moniker="choose a moniker" \ --website="https://cosmos.network" \ --identity=6A0D65E29A4CBC8E \ @@ -177,7 +177,7 @@ __Note__: The `commission-rate` value must adhere to the following invariants: View the validator's information with this command: ```bash -gaiacli query stake validator +gaiacli query staking validator ``` ## Track Validator Signing Information diff --git a/docs/modules/README.md b/docs/modules/README.md index 53e02687ea78..665a26a78b67 100644 --- a/docs/modules/README.md +++ b/docs/modules/README.md @@ -6,9 +6,9 @@ See the [API docs](https://godoc.org/github.com/cosmos/cosmos-sdk/x/bank). # Stake -The `x/stake` module is for Cosmos Delegated-Proof-of-Stake. +The `x/staking` module is for Cosmos Delegated-Proof-of-Stake. -See the [API docs](https://godoc.org/github.com/cosmos/cosmos-sdk/x/stake). +See the [API docs](https://godoc.org/github.com/cosmos/cosmos-sdk/x/staking). See the [specification](https://github.com/cosmos/cosmos-sdk/tree/develop/docs/spec/staking) diff --git a/docs/spec/auth/vesting.md b/docs/spec/auth/vesting.md index b8785619b2aa..36a7a80b1ea4 100644 --- a/docs/spec/auth/vesting.md +++ b/docs/spec/auth/vesting.md @@ -333,7 +333,7 @@ func UndelegateCoins(to Account, amount Coins) { ## Keepers & Handlers The `VestingAccount` implementations reside in `x/auth`. However, any keeper in -a module (e.g. staking in `x/stake`) wishing to potentially utilize any vesting +a module (e.g. staking in `x/staking`) wishing to potentially utilize any vesting coins, must call explicit methods on the `x/bank` keeper (e.g. `DelegateCoins`) opposed to `SendCoins` and `SubtractCoins`. diff --git a/docs/spec/distribution/hooks.md b/docs/spec/distribution/hooks.md index 8c2b4b91a10a..ca18dad080db 100644 --- a/docs/spec/distribution/hooks.md +++ b/docs/spec/distribution/hooks.md @@ -2,7 +2,7 @@ ## Create or modify delegation distribution - - triggered-by: `stake.TxDelegate`, `stake.TxBeginRedelegate`, `stake.TxBeginUnbonding` + - triggered-by: `staking.TxDelegate`, `staking.TxBeginRedelegate`, `staking.TxBeginUnbonding` The pool of a new delegator bond will be 0 for the height at which the bond was added, or the withdrawal has taken place. This is achieved by setting @@ -10,7 +10,7 @@ added, or the withdrawal has taken place. This is achieved by setting ## Commission rate change - - triggered-by: `stake.TxEditValidator` + - triggered-by: `staking.TxEditValidator` If a validator changes its commission rate, all commission on fees must be simultaneously withdrawn using the transaction `TxWithdrawValidator`. @@ -19,7 +19,7 @@ Additionally the change and associated height must be recorded in a ## Change in Validator State - - triggered-by: `stake.Slash`, `stake.UpdateValidator` + - triggered-by: `staking.Slash`, `staking.UpdateValidator` Whenever a validator is slashed or enters/leaves the validator group all of the validator entitled reward tokens must be simultaneously withdrawn from diff --git a/docs/spec/distribution/transactions.md b/docs/spec/distribution/transactions.md index 821c4ba352e5..57c4d3103568 100644 --- a/docs/spec/distribution/transactions.md +++ b/docs/spec/distribution/transactions.md @@ -24,7 +24,7 @@ func GetDelegatorRewardsAll(delegatorAddr sdk.AccAddress, height int64) DecCoins // collect all entitled rewards withdraw = 0 - pool = stake.GetPool() + pool = staking.GetPool() feePool = GetFeePool() for delegation = range delegations delInfo = GetDelegationDistInfo(delegation.DelegatorAddr, @@ -55,7 +55,7 @@ func WithdrawDelegationReward(delegatorAddr, validatorAddr, withdrawAddr sdk.Acc height = GetHeight() // get all distribution scenarios - pool = stake.GetPool() + pool = staking.GetPool() feePool = GetFeePool() delInfo = GetDelegationDistInfo(delegatorAddr, validatorAddr) diff --git a/docs/spec/governance/state.md b/docs/spec/governance/state.md index abe2dc41b48d..f28a309a4486 100644 --- a/docs/spec/governance/state.md +++ b/docs/spec/governance/state.md @@ -160,14 +160,14 @@ And the pseudocode for the `ProposalProcessingQueue`: // Tally voterIterator = rangeQuery(Governance, ) //return all the addresses that voted on the proposal for each (voterAddress, vote) in voterIterator - delegations = stakeKeeper.getDelegations(voterAddress) // get all delegations for current voter + delegations = stakingKeeper.getDelegations(voterAddress) // get all delegations for current voter for each delegation in delegations // make sure delegation.Shares does NOT include shares being unbonded tmpValMap(delegation.ValidatorAddr).Minus += delegation.Shares proposal.updateTally(vote, delegation.Shares) - _, isVal = stakeKeeper.getValidator(voterAddress) + _, isVal = stakingKeeper.getValidator(voterAddress) if (isVal) tmpValMap(voterAddress).Vote = vote diff --git a/docs/spec/slashing/README.md b/docs/spec/slashing/README.md index dee91eb33078..2240930f8e80 100644 --- a/docs/spec/slashing/README.md +++ b/docs/spec/slashing/README.md @@ -19,15 +19,12 @@ This module will be used by the Cosmos Hub, the first hub in the Cosmos ecosyste 1. **[Overview](overview.md)** 1. **[State](state.md)** 1. [SigningInfo](state.md#signing-info) - 1. [SlashingPeriod](state.md#slashing-period) -1. **[Transactions](transactions.md)** +2. **[Transactions](transactions.md)** 1. [Unjail](transactions.md#unjail) -1. **[Hooks](hooks.md)** +3. **[Hooks](hooks.md)** 1. [Validator Bonded](hooks.md#validator-bonded) - 1. [Validator Unbonded](hooks.md#validator-unbonded) - 1. [Validator Slashed](hooks.md#validator-slashed) -1. **[Begin Block](begin-block.md)** +4. **[Begin Block](begin-block.md)** 1. [Evidence handling](begin-block.md#evidence-handling) - 1. [Uptime tracking](begin-block.md#uptime-tracking) -1. **[Future Improvements](future-improvements.md)** + 2. [Uptime tracking](begin-block.md#uptime-tracking) +5. **[Future Improvements](future-improvements.md)** 1. [State cleanup](future-improvements.md#state-cleanup) diff --git a/docs/spec/slashing/begin-block.md b/docs/spec/slashing/begin-block.md index 43691b38d211..4bc677ded534 100644 --- a/docs/spec/slashing/begin-block.md +++ b/docs/spec/slashing/begin-block.md @@ -59,7 +59,7 @@ for redel in redels { } ``` -We then slash the validator: +We then slash the validator and tombstone them: ``` curVal := validator @@ -70,17 +70,21 @@ slashAmount -= slashAmountUnbondings slashAmount -= slashAmountRedelegations curVal.Shares = max(0, curVal.Shares - slashAmount) + +signInfo = SigningInfo.Get(val.Address) +signInfo.JailedUntil = MAX_TIME +signInfo.Tombstoned = true +SigningInfo.Set(val.Address, signInfo) ``` This ensures that offending validators are punished the same amount whether they act as a single validator with X stake or as N validators with collectively X -stake. - -The amount slashed for all double signature infractions committed within a single slashing period is capped as described in [state-machine.md](state-machine.md). +stake. The amount slashed for all double signature infractions committed within a +single slashing period is capped as described in [overview.md](overview.md) under Tombstone Caps. ## Uptime tracking -At the beginning of each block, we update the signing info for each validator and check if they should be automatically unbonded: +At the beginning of each block, we update the signing info for each validator and check if they've dipped below the liveness threshhold over the tracked window. If so, they will be slashed by `LivenessSlashAmount` and will be Jailed for `LivenessJailPeriod`. Liveness slashes do NOT lead to a tombstombing. ``` height := block.Height @@ -114,9 +118,7 @@ for val in block.Validators: signInfo.IndexOffset = 0 signInfo.MissedBlocksCounter = 0 clearMissedBlockBitArray() - slash & unbond the validator + slash & jail the validator SigningInfo.Set(val.Address, signInfo) ``` - -The amount slashed for downtime slashes is *not* capped by the slashing period in which they are committed, although they do reset it (since the validator is unbonded). diff --git a/docs/spec/slashing/future-improvements.md b/docs/spec/slashing/future-improvements.md deleted file mode 100644 index 84be139e8cf9..000000000000 --- a/docs/spec/slashing/future-improvements.md +++ /dev/null @@ -1,4 +0,0 @@ -## State Cleanup - -Once no evidence for a given slashing period can possibly be valid (the end time plus the unbonding period is less than the current time), -old slashing periods should be cleaned up. This will be implemented post-launch. diff --git a/docs/spec/slashing/hooks.md b/docs/spec/slashing/hooks.md index 1888c1d2f847..74207891fb84 100644 --- a/docs/spec/slashing/hooks.md +++ b/docs/spec/slashing/hooks.md @@ -4,10 +4,8 @@ In this section we describe the "hooks" - slashing module code that runs when ot ### Validator Bonded -Upon successful bonding of a validator (a given validator entering the "bonded" state, -which may happen on delegation, on unjailing, etc), we create a new `SlashingPeriod` structure for the -now-bonded validator, which `StartHeight` of the current block, `EndHeight` of `0` (sentinel value for not-yet-ended), -and `SlashedSoFar` of `0`: +Upon successful first-time bonding of a new validator, we create a new `ValidatorSigningInfo` structure for the +now-bonded validator, which `StartHeight` of the current block. ``` onValidatorBonded(address sdk.ValAddress) @@ -18,52 +16,11 @@ onValidatorBonded(address sdk.ValAddress) StartHeight : CurrentHeight, IndexOffset : 0, JailedUntil : time.Unix(0, 0), + Tombstone : false, MissedBloskCounter : 0 } setValidatorSigningInfo(signingInfo) } - - slashingPeriod = SlashingPeriod{ - ValidatorAddr : address, - StartHeight : CurrentHeight, - EndHeight : 0, - SlashedSoFar : 0, - } - setSlashingPeriod(slashingPeriod) return ``` - -### Validator Unbonded - -When a validator is unbonded, we update the in-progress `SlashingPeriod` with the current block as the `EndHeight`: - -``` -onValidatorUnbonded(address sdk.ValAddress) - - slashingPeriod = getSlashingPeriod(address, CurrentHeight) - slashingPeriod.EndHeight = CurrentHeight - setSlashingPeriod(slashingPeriod) - - return -``` - -### Validator Slashed - -When a validator is slashed, we look up the appropriate `SlashingPeriod` based on the validator -address and the time of infraction, cap the fraction slashed as `max(SlashFraction, SlashedSoFar)` -(which may be `0`), and update the `SlashingPeriod` with the increased `SlashedSoFar`: - -``` -beforeValidatorSlashed(address sdk.ValAddress, fraction sdk.Rat, infractionHeight int64) - - slashingPeriod = getSlashingPeriod(address, infractionHeight) - totalToSlash = max(slashingPeriod.SlashedSoFar, fraction) - slashingPeriod.SlashedSoFar = totalToSlash - setSlashingPeriod(slashingPeriod) - - remainderToSlash = slashingPeriod.SlashedSoFar - totalToSlash - fraction = remainderToSlash - - continue with slashing -``` diff --git a/docs/spec/slashing/overview.md b/docs/spec/slashing/overview.md index aa42f6193985..63f0e494f856 100644 --- a/docs/spec/slashing/overview.md +++ b/docs/spec/slashing/overview.md @@ -6,18 +6,14 @@ At any given time, there are any number of validators registered in the state ma Each block, the top `n = MaximumBondedValidators` validators who are not jailed become *bonded*, meaning that they may propose and vote on blocks. Validators who are *bonded* are *at stake*, meaning that part or all of their stake and their delegators' stake is at risk if they commit a protocol fault. -### Slashing period +### Tombstone Caps In order to mitigate the impact of initially likely categories of non-malicious protocol faults, the Cosmos Hub implements for each validator -a *slashing period*, in which the amount by which a validator can be slashed is capped at the punishment for the worst violation. For example, -if you misconfigure your HSM and double-sign a bunch of old blocks, you'll only be punished for the first double-sign (and then immediately jailed, -so that you have a chance to reconfigure your setup). This will still be quite expensive and desirable to avoid, but slashing periods somewhat blunt -the economic impact of unintentional misconfiguration. +a *tombstone* cap, which only allows a validator to be slashed once for a double sign fault. For example, if you misconfigure your HSM and double-sign +a bunch of old blocks, you'll only be punished for the first double-sign (and then immediately tombstombed). This will still be quite expensive and desirable +to avoid, but tombstone caps somewhat blunt the economic impact of unintentional misconfiguration. -Unlike the unbonding period, the slashing period doesn't have a fixed length. A new slashing period starts whenever a validator is bonded and ends -whenever the validator is unbonded (which will happen if the validator is jailed). The amount of tokens slashed relative to validator power for infractions -committed within the slashing period, whenever they are discovered, is capped at the punishment for the worst infraction -(which for the Cosmos Hub at launch will be double-signing a block). +Liveness faults do not have caps, as they can't stack upon each other. Liveness bugs are "detected" as soon as the infraction occurs, and the validators are immediately put in jail, so it is not possible for them to commit multiple liveness faults without unjailing in between. #### ASCII timelines @@ -25,44 +21,22 @@ committed within the slashing period, whenever they are discovered, is capped at *[* : timeline start *]* : timeline end -*<* : slashing period start -*>* : slashing period end *Cn* : infraction `n` committed *Dn* : infraction `n` discovered *Vb* : validator bonded *Vu* : validator unbonded -*Single infraction* +*Single Double Sign Infraction* <-----------------> [----------C1----D1,Vu-----] A single infraction is committed then later discovered, at which point the validator is unbonded and slashed at the full amount for the infraction. -*Multiple infractions* +*Multiple Double Sign Infractions* <---------------------------> [----------C1--C2---C3---D1,D2,D3Vu-----] -Multiple infractions are committed within a single slashing period then later discovered, at which point the validator is unbonded and slashed for only the worst infraction. - -*Multiple infractions after rebonding* - - -<--------------------------->                        <-------------> -[----------C1--C2---C3---D1,D2,D3Vu---Vb---C4----D4,Vu--] - -Multiple infractions are committed within a single slashing period then later discovered, at which point the validator is unbonded and slashed for only the worst infraction. -The validator then unjails themself and rebonds, then commits a fourth infraction - which is discovered and punished at the full amount, since a new slashing period started -when they unjailed and rebonded. - -### Safety note - -Slashing is capped fractionally per period, but the amount of total bonded stake associated with any given validator can change (by an unbounded amount) over that period. - -For example, with MaxFractionSlashedPerPeriod = `0.5`, if a validator is initially slashed at `0.4` near the start of a period when they have 100 stake bonded, -then later slashed at `0.4` when they have `1000` stake bonded, the total amount slashed is just `40 + 100 = 140` (since the latter slash is capped at `0.1`) - -whereas if they had `1000` stake bonded initially, the first offense would have been slashed for `400` stake and the total amount slashed would have been `400 + 100 = 500`. - -This means that any slashing events which utilize the slashing period (are capped-per-period) **must also** jail the validator when the infraction is discovered. -Otherwise it would be possible for a validator to slash themselves intentionally at a low bond, then increase their bond but no longer be at stake since they would have already hit the `SlashedSoFar` cap. +Multiple infractions are committed and then later discovered, at which point the validator is jailed and slashed for only one infraction. +Because the validator is also tombstoned, they can not rejoin the validator set. \ No newline at end of file diff --git a/docs/spec/slashing/state.md b/docs/spec/slashing/state.md index 9a9a188ff2d2..556b9c3cc914 100644 --- a/docs/spec/slashing/state.md +++ b/docs/spec/slashing/state.md @@ -40,6 +40,7 @@ type ValidatorSigningInfo struct { IndexOffset int64 // Offset into the signed block bit array JailedUntilHeight int64 // Block height until which the validator is jailed, // or sentinel value of 0 for not jailed + Tombstoned bool // Whether a validator is tombstoned or not MissedBlocksCounter int64 // Running counter of missed blocks } @@ -49,32 +50,5 @@ Where: * `StartHeight` is set to the height that the candidate became an active validator (with non-zero voting power). * `IndexOffset` is incremented each time the candidate was a bonded validator in a block (and may have signed a precommit or not). * `JailedUntil` is set whenever the candidate is jailed due to downtime +* `Tombstoned` is set once a validator's first double sign evidence comes in * `MissedBlocksCounter` is a counter kept to avoid unnecessary array reads. `MissedBlocksBitArray.Sum() == MissedBlocksCounter` always. - -## Slashing Period - -A slashing period is a start and end block height associated with a particular validator, -within which only the "worst infraction counts" (see the [Overview](overview.md)): the total -amount of slashing for infractions committed within the period (and discovered whenever) is -capped at the penalty for the worst offense. - -This period starts when a validator is first bonded and ends when a validator is slashed & jailed -for any reason. When the validator rejoins the validator set (perhaps through unjailing themselves, -and perhaps also changing signing keys), they enter into a new period. - -Slashing periods are indexed in the store as follows: - -- SlashingPeriod: ` 0x03 | ValTendermintAddr | StartHeight -> amino(slashingPeriod) ` - -This allows us to look up slashing period by a validator's address, the only lookup necessary, -and iterate over start height to efficiently retrieve the most recent slashing period(s) -or those beginning after a given height. - -```go -type SlashingPeriod struct { - ValidatorAddr sdk.ValAddress // Tendermint address of the validator - StartHeight int64 // Block height at which slashing period begin - EndHeight int64 // Block height at which slashing period ended - SlashedSoFar sdk.Rat // Fraction slashed so far, cumulative -} -``` diff --git a/docs/spec/slashing/transactions.md b/docs/spec/slashing/transactions.md index c33e96047d61..6642acbb8e40 100644 --- a/docs/spec/slashing/transactions.md +++ b/docs/spec/slashing/transactions.md @@ -22,6 +22,8 @@ handleMsgUnjail(tx TxUnjail) fail with "Validator not jailed, cannot unjail" info = getValidatorSigningInfo(operator) + if info.Tombstoned + fail with "Tombstoned validator cannot be unjailed" if block time < info.JailedUntil fail with "Validator still jailed, cannot unjail until period has expired" diff --git a/docs/spec/spec-proposals/f1-fee-distribution/f1_fee_distr.pdf b/docs/spec/spec-proposals/f1-fee-distribution/f1_fee_distr.pdf index 0f7443104dec..b9995386957c 100644 Binary files a/docs/spec/spec-proposals/f1-fee-distribution/f1_fee_distr.pdf and b/docs/spec/spec-proposals/f1-fee-distribution/f1_fee_distr.pdf differ diff --git a/docs/spec/spec-proposals/f1-fee-distribution/f1_fee_distr.tex b/docs/spec/spec-proposals/f1-fee-distribution/f1_fee_distr.tex index 2a4c2ba3965c..b6bb6b3265a2 100644 --- a/docs/spec/spec-proposals/f1-fee-distribution/f1_fee_distr.tex +++ b/docs/spec/spec-proposals/f1-fee-distribution/f1_fee_distr.tex @@ -2,7 +2,7 @@ \usepackage{hyperref} %opening -\title{F1 Fee Distribution Draft-01} +\title{F1 Fee Distribution Draft-02} \author{Dev Ojha} \begin{document} @@ -12,7 +12,7 @@ \begin{abstract} In a proof of stake blockchain, validators need to split the rewards gained from transaction fees each block. Furthermore, these fees must be fairly distributed to each of a validator's constituent delegators. They accrue this reward throughout the entire time they are delegated, and they have a special operation to withdraw accrued rewards. - The F1 fee distribution scheme works for any algorithm to split funds between validators each block, with minimal iteration, and the only approximations being due to finite decimal precision. Per block there is a single iteration over the validator set, which enables only rewarding validators who signed a given block. No iteration is required to delegate, and withdrawing only requires iterating over all of that validators slashes since delegation it began. State usage is minimal as well, one state update per validator per block, and one state record per delegator. + The F1 fee distribution scheme works for any algorithm to split funds between validators each block, with minimal iteration, and the only approximations being due to finite decimal precision. Per block there is a single iteration over the validator set, to enable reward algorithms that differ by validator. No iteration is required to delegate, or withdraw. The state usage is one state update per validator per block, and one state entry per active delegation. It can optionally handle arbitrary inflation schemes, and auto-bonding of rewards. \end{abstract} \section{F1 Fee Distribution} @@ -22,13 +22,11 @@ \subsection{Context} Transaction fees get rewarded to validators based on the incentive scheme of the underlying proof of stake model. The fee distribution problem occurs in proof of stake blockchains supporting delegation, as there is a need to distribute a validator's fee rewards to its delegators. The trivial solution of just giving the rewards to each delegator every block is too expensive to perform on-chain. -So instead fee distribution algorithms have delegators perform an explicit withdraw transaction, which when performed yields the same total amount of fees as if they had received them at every block. +So instead fee distribution algorithms have delegators perform a withdraw action, which when performed yields the same total amount of fees as if they had received them at every block. This details F1, an approximation-free, slash-tolerant fee distribution algorithm which allows validator commission-rates, inflation rates, and fee proportions, which can all efficiently change per validator, every block. -The algorithm requires iterating over the validators every block, and withdraws require iterating over all of the corresponding validator's slashes whilst the delegator was bonded. -The former iteration is cheap, due to staking logic already requiring iteration over all validators, which causes the expensive state-reads to be cached. -The number of slashes is expected to be 0 or 1 for most validators, -so the latter term also meets the blockchain's efficiency needs. +The algorithm requires iterating over the bonded validators every block, and withdraws require no iteration. +This is cheap, due to staking logic already requiring iteration over all validators, which causes the expensive state-reads to be cached. The key point of how F1 works is that it tracks how much rewards a delegator with 1 stake for a given validator would be entitled to if it had bonded at block 0 until the latest block. When a delegator bonds at block $b$, the amount of rewards a delegator with 1 stake would have if bonded at block 0 until block $b$ is also persisted to state. @@ -98,17 +96,21 @@ \subsection{Slashing} \label{ssec:slashing} Slashing is distinct from withdrawals, since it lowers the stake of all of the delegator's by a fixed percentage. Since no one is charged gas for slashes, a slash cannot iterate over all delegators. -Thus we can no longer just multiply by $x$ over the difference in stake. +Thus we can no longer just multiply by $x$ over the difference in stake. +This section describes a simple solution that should suffice for most chains needs. An asymptotically optimal solution is provided in section 2.4. +TODO: Consider removing this section in favor of just using the current section 2.4? + The solution here is to instead store each period created by a slash in the validators state. Then when withdrawing, you must iterate over all slashes between when you started and ended. -Suppose you delegated at period $0$, a y\% slash occured at period $2$, and your withdrawal is period $4$. -Then you receive funds from $0$ to $2$ as normal. -The equations for funds you receive for $2$ to $4$ now uses $(1 - y)x$ for your stake instead of just $x$ stake. +Suppose you delegated at period $0$, a y\% slash occured at period $2$, and your withdrawal creates period $4$. +Then you receive funds from periods $0$ to $2$ as normal. +The equations for funds you receive for periods $2$ to $4$ now uses $(1 - y)x$ for your stake instead of just $x$ stake. When there are multiple slashes, you just account for the accumulated slash factor. -In practice this will not really be an efficiency hit, as we can expect most validators to have no slashes. -Validators that get slashed a lot will naturally lose their delegators. -A malicious validator that gets itself slashed many times would increase the gas to withdraw linearly, but the economic loss of funds due to the slashes should far out-weigh the extra overhead the honest withdrawer must pay for due to the gas. +In practice this will not really be an efficiency hit, as the number of slashes is expected to be 0 or 1 for most validators. +Validators that get slashed more will naturally lose their delegators. +A malicious validator that gets itself slashed many times would increase the gas to withdraw linearly, but the economic loss of funds due to the slashes is expected to far out-weigh the extra overhead the honest withdrawer must pay for due to the gas. +(TODO: frame that above sentence in terms of griefing factors, as thats more correct) \subsection{Inflation} Inflation is the idea that we want every staked coin to create more staking tokens as time progresses. @@ -158,7 +160,7 @@ \subsection{Inflation} Thus every block, each validator just has to add the total amount of fees (The $R_i$ term) that goes to delegates to some per-period term. When creating a new period, $n_{start(f)}$ can be cached in state, and the product is already stored in the previous periods state entry. -You then get the next period's $n_{start(f)}$ from the current tm-power entry. +You then get the next period's $n_{start(f)}$ from the consensus' power entry for this validator. This is thus extremely efficient per block. When withdrawing, you take the difference as before, @@ -166,20 +168,20 @@ \subsection{Inflation} $(\prod_0^{begin\ bonding\ period}1 + x)$ is known, since its included in the state entry for when you bonded. You then divide the entitled fees by $(\prod_0^{begin\ bonding\ period}1 + x)$ to normalize it to being the amount of rewards you're entitled to from 1 stake at that block to now. Then as before, you multiply by the amount of stake you had initially bonded. -TODO: (Does the difference equating to that make sense, or should it be shown explicitly) +\\TODO: (Does the difference equating to that make sense, or should it be shown explicitly) +\\TODO: Does this need to explain how the originally bonded tokens are refunded, or is that clear? -Note that the inflation function could vary per block, +The inflation function could vary per block, and per validator if ever a need rose. If the inflation rate is the same for everyone then there can be a single global store for the entries corresponding to the product of inflations. Inflation creation can trivially be epoched as long as inflation isn't required within the epoch, through changes to the $inflation$ function. -Again note that this process is extremely efficient. - \subsection{Withdrawing with no iteration over slashes} -TODO: Fill this out. -Core idea: you use the same mechanism as previously, but you just make that blocks $x_j$ term negative. -(So a $20\%$ slash would be equivalent to an inflation on that validator of $-20\%$) -This foregoes the constant inflation per validator, may or may not be worth it depending on expected number of slashes +Notice that a slash is the same as a negative inflation rate for a validator in one block. +For example a $20\%$ slash is equivalent to a $-20\%$ inflation for a validator in a block. +Given correctness of auto-bonding inflation with different inflation rates per-validator, +it follows that handling slashes can be correctly done by simply subtracting the validators inflation factor in that block to be the negative of the slash factor. +This significantly simplifies the withdrawal procedure. \subsection{Auto bonding fees} TODO: Fill this out. @@ -197,28 +199,22 @@ \subsection{Jailing / being kicked out of the validator set} So you simply don't update the "total accrued fees this period" variable for jailed / non-bonded validators. Withdrawing requires \textit{no} special casing here! -\section{State pruning} -You will notice that in the main scheme there was no note for pruning entries from state. -We can in fact prune quite effectively. +\section{State Requirements} +State entries can be pruned quite effectively. Suppose for the sake of exposition that there is at most one delegation / withdrawal to a particular validator in any given block. Then each delegation is responsible for one addition to state. Only the next period, and this delegator's withdrawal could depend on this entry. Thus once this delegator withdraws, this state entry can be pruned. For the entry created by the delegator's withdrawal, that is only required by the creation of the next period. Thus once the next period is created, that withdrawal's period can be deleted. -This can be easily adapted to the case where there are multiple delegations / withdrawals per block. -Keep a counter per state entry for how many delegations need to be cleared. -(So 1 for each delegation in that block which created that period, 0 for each withdrawal) -When creating a new period, check that the previous period (which had to be read anyway) doesn't have a count of 0. -If it does have a count of 0, delete it. -When withdrawing, decrement the period which created this delegation's counter by 1. -If that counter is now 0, delete that period. +This can be easily adapted to the case where there are multiple delegations / withdrawals per block, by maintaining a reference count in each period starting state entry. The slash entries for a validator can only be pruned when all of that validator's delegators have their bonding period starting after the slash. This seems ineffective to keep track of, thus it is not worth it. Each slash should instead remain in state until the validator unbonds and all delegators have their fees withdrawn. \section{Implementers Considerations} +TODO: Convert this section into a proper conclusion This is an extremely simple scheme with many nice benefits. \begin{itemize} @@ -238,11 +234,11 @@ \section{TO DOs} \begin{itemize} \item A global fee pool can be described. - \item Determine if auto-bonding fees is compatible with inflation and comission rates in conjunction - \item mention storage optimization in the uniform inflation and iteration over slashing case: only have one storage location w/ refcount of the product of inflation results - \item Remove iteration over slashes by the same normalization trick used in inflation + \item Mention storage optimization for how to prune slashing entries in the uniform inflation and iteration over slashing case \item Add equation numbers \item perhaps re-organize so that the no iteration + \item Section on decimal precision considerations (would unums help?), and mitigating errors in calculation with floats and decimals. -- This probably belongs in a corrollary markdown file in the implementation + \item Consider indicating that the withdraw action need not be a tx type and could instead happen 'transparently' when more coins are needed, if a chain desired this for UX / p2p efficiency. \end{itemize} diff --git a/docs/spec/staking/state.md b/docs/spec/staking/state.md index d2f461e103b8..1336e1e4ca67 100644 --- a/docs/spec/staking/state.md +++ b/docs/spec/staking/state.md @@ -18,7 +18,7 @@ type Pool struct { ### Params Params is global data structure that stores system parameters and defines -overall functioning of the stake module. +overall functioning of the staking module. - Params: `0x00 -> amino(params)` diff --git a/server/export.go b/server/export.go index aa30597da910..16187fa664e5 100644 --- a/server/export.go +++ b/server/export.go @@ -33,7 +33,7 @@ func ExportCmd(ctx *Context, cdc *codec.Codec, appExporter AppExporter) *cobra.C return err } - if emptyState { + if emptyState || appExporter == nil { fmt.Println("WARNING: State is not initialized. Returning genesis file.") genesisFile := path.Join(home, "config", "genesis.json") genesis, err := ioutil.ReadFile(genesisFile) diff --git a/server/mock/store.go b/server/mock/store.go index ec963a1bc22c..3aecc1734407 100644 --- a/server/mock/store.go +++ b/server/mock/store.go @@ -50,7 +50,7 @@ func (ms multiStore) LastCommitID() sdk.CommitID { panic("not implemented") } -func (ms multiStore) SetPruning(s sdk.PruningStrategy) { +func (ms multiStore) SetPruning(opts sdk.PruningOptions) { panic("not implemented") } diff --git a/server/start.go b/server/start.go index cf39ff71b62a..2b94bb934a6d 100644 --- a/server/start.go +++ b/server/start.go @@ -114,10 +114,11 @@ func startInProcess(ctx *Context, appCreator AppCreator) (*node.Node, error) { return nil, err } + UpgradeOldPrivValFile(cfg) // create & start tendermint node tmNode, err := node.NewNode( cfg, - pvm.LoadOrGenFilePV(cfg.PrivValidatorFile()), + pvm.LoadOrGenFilePV(cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile()), nodeKey, proxy.NewLocalClientCreator(app), node.DefaultGenesisDocProviderFunc(cfg), diff --git a/server/tm_cmds.go b/server/tm_cmds.go index 33994b0cbab0..9d8351711599 100644 --- a/server/tm_cmds.go +++ b/server/tm_cmds.go @@ -41,8 +41,10 @@ func ShowValidatorCmd(ctx *Context) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { cfg := ctx.Config - privValidator := pvm.LoadOrGenFilePV(cfg.PrivValidatorFile()) - valPubKey := privValidator.PubKey + UpgradeOldPrivValFile(cfg) + privValidator := pvm.LoadOrGenFilePV( + cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile()) + valPubKey := privValidator.GetPubKey() if viper.GetBool(client.FlagJson) { return printlnJSON(valPubKey) @@ -67,9 +69,12 @@ func ShowAddressCmd(ctx *Context) *cobra.Command { Use: "show-address", Short: "Shows this node's tendermint validator consensus address", RunE: func(cmd *cobra.Command, args []string) error { + cfg := ctx.Config - privValidator := pvm.LoadOrGenFilePV(cfg.PrivValidatorFile()) - valConsAddr := (sdk.ConsAddress)(privValidator.Address) + UpgradeOldPrivValFile(cfg) + privValidator := pvm.LoadOrGenFilePV( + cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile()) + valConsAddr := (sdk.ConsAddress)(privValidator.GetAddress()) if viper.GetBool(client.FlagJson) { return printlnJSON(valConsAddr) @@ -102,7 +107,7 @@ func UnsafeResetAllCmd(ctx *Context) *cobra.Command { Short: "Resets the blockchain database, removes address book files, and resets priv_validator.json to the genesis state", RunE: func(cmd *cobra.Command, args []string) error { cfg := ctx.Config - tcmd.ResetAll(cfg.DBDir(), cfg.P2P.AddrBookFile(), cfg.PrivValidatorFile(), ctx.Logger) + tcmd.ResetAll(cfg.DBDir(), cfg.P2P.AddrBookFile(), cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile(), ctx.Logger) return nil }, } diff --git a/server/util.go b/server/util.go index 4e834ce10d6b..dec3a6d4aa1e 100644 --- a/server/util.go +++ b/server/util.go @@ -18,6 +18,7 @@ import ( "github.com/tendermint/tendermint/libs/cli" tmflags "github.com/tendermint/tendermint/libs/cli/flags" "github.com/tendermint/tendermint/libs/log" + pvm "github.com/tendermint/tendermint/privval" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -221,6 +222,16 @@ func TrapSignal(cleanupFunc func()) { }() } +// UpgradeOldPrivValFile converts old priv_validator.json file (prior to Tendermint 0.28) +// to the new priv_validator_key.json and priv_validator_state.json files. +func UpgradeOldPrivValFile(config *cfg.Config) { + if _, err := os.Stat(config.OldPrivValidatorFile()); !os.IsNotExist(err) { + if oldFilePV, err := pvm.LoadOldFilePV(config.OldPrivValidatorFile()); err == nil { + oldFilePV.Upgrade(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile()) + } + } +} + func skipInterface(iface net.Interface) bool { if iface.Flags&net.FlagUp == 0 { return true // interface down diff --git a/store/codec.go b/store/codec.go index 353cd2e3cd77..181f12e511b7 100644 --- a/store/codec.go +++ b/store/codec.go @@ -7,7 +7,7 @@ import ( // Import cosmos-sdk/types/store.go for convenience. // nolint type ( - PruningStrategy = types.PruningStrategy + PruningOptions = types.PruningOptions Store = types.Store Committer = types.Committer CommitStore = types.CommitStore diff --git a/store/dbstoreadapter.go b/store/dbstoreadapter.go index 76e673de5a67..b662bcf45ddd 100644 --- a/store/dbstoreadapter.go +++ b/store/dbstoreadapter.go @@ -64,4 +64,4 @@ func (cdsa commitDBStoreAdapter) LastCommitID() CommitID { } } -func (cdsa commitDBStoreAdapter) SetPruning(_ PruningStrategy) {} +func (cdsa commitDBStoreAdapter) SetPruning(_ PruningOptions) {} diff --git a/store/iavlstore.go b/store/iavlstore.go index fccde38e27e0..26c739da3bf3 100644 --- a/store/iavlstore.go +++ b/store/iavlstore.go @@ -19,7 +19,7 @@ const ( ) // load the iavl store -func LoadIAVLStore(db dbm.DB, id CommitID, pruning sdk.PruningStrategy) (CommitStore, error) { +func LoadIAVLStore(db dbm.DB, id CommitID, pruning sdk.PruningOptions) (CommitStore, error) { tree := iavl.NewMutableTree(db, defaultIAVLCacheSize) _, err := tree.LoadVersion(id.Version) if err != nil { @@ -38,7 +38,6 @@ var _ Queryable = (*iavlStore)(nil) // iavlStore Implements KVStore and CommitStore. type iavlStore struct { - // The underlying tree. tree *iavl.MutableTree @@ -102,17 +101,9 @@ func (st *iavlStore) LastCommitID() CommitID { } // Implements Committer. -func (st *iavlStore) SetPruning(pruning sdk.PruningStrategy) { - switch pruning { - case sdk.PruneEverything: - st.numRecent = 0 - st.storeEvery = 0 - case sdk.PruneNothing: - st.storeEvery = 1 - case sdk.PruneSyncable: - st.numRecent = 100 - st.storeEvery = 10000 - } +func (st *iavlStore) SetPruning(opt sdk.PruningOptions) { + st.numRecent = opt.KeepRecent() + st.storeEvery = opt.KeepEvery() } // VersionExists returns whether or not a given version is stored. diff --git a/store/multistoreproof_test.go b/store/multistoreproof_test.go index 0f80657b84b6..3d70451e7273 100644 --- a/store/multistoreproof_test.go +++ b/store/multistoreproof_test.go @@ -13,7 +13,7 @@ import ( func TestVerifyIAVLStoreQueryProof(t *testing.T) { // Create main tree for testing. db := dbm.NewMemDB() - iStore, err := LoadIAVLStore(db, CommitID{}, sdk.PruneNothing) + iStore, err := LoadIAVLStore(db, CommitID{}, PruneNothing) store := iStore.(*iavlStore) require.Nil(t, err) store.Set([]byte("MYKEY"), []byte("MYVALUE")) diff --git a/store/pruning.go b/store/pruning.go new file mode 100644 index 000000000000..9a7aeb4d29e6 --- /dev/null +++ b/store/pruning.go @@ -0,0 +1,29 @@ +package store + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// default pruning strategies +var ( + // PruneEverything means all saved states will be deleted, storing only the current state + PruneEverything = sdk.NewPruningOptions(0, 0) + // PruneNothing means all historic states will be saved, nothing will be deleted + PruneNothing = sdk.NewPruningOptions(0, 1) + // PruneSyncable means only those states not needed for state syncing will be deleted (keeps last 100 + every 10000th) + PruneSyncable = sdk.NewPruningOptions(100, 10000) +) + +func NewPruningOptions(strategy string) (opt PruningOptions) { + switch strategy { + case "nothing": + opt = PruneNothing + case "everything": + opt = PruneEverything + case "syncable": + opt = PruneSyncable + default: + opt = PruneSyncable + } + return +} diff --git a/store/rootmultistore.go b/store/rootmultistore.go index c309f9e9b28a..fa576d3dcc6a 100644 --- a/store/rootmultistore.go +++ b/store/rootmultistore.go @@ -24,7 +24,7 @@ const ( type rootMultiStore struct { db dbm.DB lastCommitID CommitID - pruning sdk.PruningStrategy + pruningOpts sdk.PruningOptions storesParams map[StoreKey]storeParams stores map[StoreKey]CommitStore keysByName map[string]StoreKey @@ -47,10 +47,10 @@ func NewCommitMultiStore(db dbm.DB) *rootMultiStore { } // Implements CommitMultiStore -func (rs *rootMultiStore) SetPruning(pruning sdk.PruningStrategy) { - rs.pruning = pruning +func (rs *rootMultiStore) SetPruning(pruningOpts sdk.PruningOptions) { + rs.pruningOpts = pruningOpts for _, substore := range rs.stores { - substore.SetPruning(pruning) + substore.SetPruning(pruningOpts) } } @@ -355,7 +355,7 @@ func (rs *rootMultiStore) loadCommitStoreFromParams(key sdk.StoreKey, id CommitI // TODO: id? // return NewCommitMultiStore(db, id) case sdk.StoreTypeIAVL: - store, err = LoadIAVLStore(db, id, rs.pruning) + store, err = LoadIAVLStore(db, id, rs.pruningOpts) return case sdk.StoreTypeDB: store = commitDBStoreAdapter{dbStoreAdapter{db}} diff --git a/store/rootmultistore_test.go b/store/rootmultistore_test.go index cd555d6f2d5a..10f0956562ba 100644 --- a/store/rootmultistore_test.go +++ b/store/rootmultistore_test.go @@ -195,6 +195,7 @@ func TestMultiStoreQuery(t *testing.T) { func newMultiStoreWithMounts(db dbm.DB) *rootMultiStore { store := NewCommitMultiStore(db) + store.pruningOpts = PruneSyncable store.MountStoreWithDB( sdk.NewKVStoreKey("store1"), sdk.StoreTypeIAVL, nil) store.MountStoreWithDB( diff --git a/store/transientstore.go b/store/transientstore.go index 63b154c017f7..2de1197b977d 100644 --- a/store/transientstore.go +++ b/store/transientstore.go @@ -26,7 +26,7 @@ func (ts *transientStore) Commit() (id CommitID) { } // Implements CommitStore -func (ts *transientStore) SetPruning(pruning PruningStrategy) { +func (ts *transientStore) SetPruning(opts PruningOptions) { } // Implements CommitStore diff --git a/tests/gobash.go b/tests/gobash.go index 9c4312c6d089..e7bcaa100c82 100644 --- a/tests/gobash.go +++ b/tests/gobash.go @@ -93,18 +93,21 @@ func GoExecuteTWithStdout(t *testing.T, cmd string) (proc *Process) { // Without this, the test halts ?! // (theory: because stdout and/or err aren't connected to anything the process halts) - go func() { + go func(proc *Process) { _, err := ioutil.ReadAll(proc.StdoutPipe) if err != nil { fmt.Println("-------------ERR-----------------------", err) return } - _, err = ioutil.ReadAll(proc.StderrPipe) + }(proc) + + go func(proc *Process) { + _, err := ioutil.ReadAll(proc.StderrPipe) if err != nil { fmt.Println("-------------ERR-----------------------", err) return } - }() + }(proc) err = proc.Cmd.Start() require.NoError(t, err) diff --git a/types/coin.go b/types/coin.go index 8c504a83b2f7..a3cbf6b7d462 100644 --- a/types/coin.go +++ b/types/coin.go @@ -265,7 +265,7 @@ func (coins Coins) SafeMinus(coinsB Coins) (Coins, bool) { return diff, !diff.IsNotNegative() } -// IsAllGT returns true iff for every denom in coins, the denom is present at a +// IsAllGT returns true if for every denom in coins, the denom is present at a // greater amount in coinsB. func (coins Coins) IsAllGT(coinsB Coins) bool { diff, _ := coins.SafeMinus(coinsB) @@ -299,6 +299,41 @@ func (coins Coins) IsAllLTE(coinsB Coins) bool { return coinsB.IsAllGTE(coins) } +// IsAnyGTE returns true iff coins contains at least one denom that is present +// at a greater or equal amount in coinsB; it returns false otherwise. +// +// NOTE: IsAnyGTE operates under the invariant that coins are sorted by +// denominations. +func (coins Coins) IsAnyGTE(coinsB Coins) bool { + if len(coinsB) == 0 { + return false + } + + j := 0 + for _, coin := range coins { + searchOther := true // terminator in case coins breaks the sorted invariant + + for j < len(coinsB) && searchOther { + switch strings.Compare(coin.Denom, coinsB[j].Denom) { + case -1: + // coin denom in less than the current other coin, so move to next coin + searchOther = false + case 0: + if coin.IsGTE(coinsB[j]) { + return true + } + + fallthrough // skip to next other coin + case 1: + // coin denom is greater than the current other coin, so move to next other coin + j++ + } + } + } + + return false +} + // IsZero returns true if there are no coins or all coins are zero. func (coins Coins) IsZero() bool { for _, coin := range coins { diff --git a/types/coin_test.go b/types/coin_test.go index 3f69ad2ccff4..fb2d67acac78 100644 --- a/types/coin_test.go +++ b/types/coin_test.go @@ -368,6 +368,22 @@ func TestCoinsLTE(t *testing.T) { assert.True(t, Coins{}.IsAllLTE(Coins{{"a", one}})) } +func TestCoinsIsAnyGTE(t *testing.T) { + one := NewInt(1) + two := NewInt(2) + + assert.False(t, Coins{}.IsAnyGTE(Coins{})) + assert.False(t, Coins{{"a", one}}.IsAnyGTE(Coins{})) + assert.False(t, Coins{}.IsAnyGTE(Coins{{"a", one}})) + assert.False(t, Coins{{"a", one}}.IsAnyGTE(Coins{{"a", two}})) + assert.True(t, Coins{{"a", one}, {"b", two}}.IsAnyGTE(Coins{{"a", two}, {"b", one}})) + assert.True(t, Coins{{"a", one}}.IsAnyGTE(Coins{{"a", one}})) + assert.True(t, Coins{{"a", two}}.IsAnyGTE(Coins{{"a", one}})) + assert.True(t, Coins{{"a", one}}.IsAnyGTE(Coins{{"a", one}, {"b", two}})) + assert.True(t, Coins{{"a", one}, {"b", two}}.IsAnyGTE(Coins{{"a", one}, {"b", one}})) + assert.True(t, Coins{{"a", one}, {"b", one}}.IsAnyGTE(Coins{{"a", one}, {"b", two}})) +} + func TestParse(t *testing.T) { one := NewInt(1) diff --git a/types/stake.go b/types/stake.go index aeaa52d3465a..c95bb2192395 100644 --- a/types/stake.go +++ b/types/stake.go @@ -115,15 +115,15 @@ type DelegationSet interface { // event hooks for staking validator object type StakingHooks interface { - OnValidatorCreated(ctx Context, valAddr ValAddress) // Must be called when a validator is created - OnValidatorModified(ctx Context, valAddr ValAddress) // Must be called when a validator's state changes - OnValidatorRemoved(ctx Context, consAddr ConsAddress, valAddr ValAddress) // Must be called when a validator is deleted + AfterValidatorCreated(ctx Context, valAddr ValAddress) // Must be called when a validator is created + BeforeValidatorModified(ctx Context, valAddr ValAddress) // Must be called when a validator's state changes + AfterValidatorRemoved(ctx Context, consAddr ConsAddress, valAddr ValAddress) // Must be called when a validator is deleted - OnValidatorBonded(ctx Context, consAddr ConsAddress, valAddr ValAddress) // Must be called when a validator is bonded - OnValidatorBeginUnbonding(ctx Context, consAddr ConsAddress, valAddr ValAddress) // Must be called when a validator begins unbonding - OnValidatorPowerDidChange(ctx Context, consAddr ConsAddress, valAddr ValAddress) // Called at EndBlock when a validator's power did change + AfterValidatorBonded(ctx Context, consAddr ConsAddress, valAddr ValAddress) // Must be called when a validator is bonded + AfterValidatorBeginUnbonding(ctx Context, consAddr ConsAddress, valAddr ValAddress) // Must be called when a validator begins unbonding + AfterValidatorPowerDidChange(ctx Context, consAddr ConsAddress, valAddr ValAddress) // Called at EndBlock when a validator's power did change - OnDelegationCreated(ctx Context, delAddr AccAddress, valAddr ValAddress) // Must be called when a delegation is created - OnDelegationSharesModified(ctx Context, delAddr AccAddress, valAddr ValAddress) // Must be called when a delegation's shares are modified - OnDelegationRemoved(ctx Context, delAddr AccAddress, valAddr ValAddress) // Must be called when a delegation is removed + BeforeDelegationCreated(ctx Context, delAddr AccAddress, valAddr ValAddress) // Must be called when a delegation is created + BeforeDelegationSharesModified(ctx Context, delAddr AccAddress, valAddr ValAddress) // Must be called when a delegation's shares are modified + BeforeDelegationRemoved(ctx Context, delAddr AccAddress, valAddr ValAddress) // Must be called when a delegation is removed } diff --git a/types/store.go b/types/store.go index 671a881c28be..3118fba8f166 100644 --- a/types/store.go +++ b/types/store.go @@ -12,19 +12,29 @@ import ( // NOTE: These are implemented in cosmos-sdk/store. -// PruningStrategy specfies how old states will be deleted over time -type PruningStrategy uint8 +// PruningStrategy specifies how old states will be deleted over time where +// keepRecent can be used with keepEvery to create a pruning "strategy". +type PruningOptions struct { + keepRecent int64 + keepEvery int64 +} -const ( - // PruneSyncable means only those states not needed for state syncing will be deleted (keeps last 100 + every 10000th) - PruneSyncable PruningStrategy = iota +func NewPruningOptions(keepRecent, keepEvery int64) PruningOptions { + return PruningOptions{ + keepRecent: keepRecent, + keepEvery: keepEvery, + } +} - // PruneEverything means all saved states will be deleted, storing only the current state - PruneEverything PruningStrategy = iota +// How much recent state will be kept. Older state will be deleted. +func (po PruningOptions) KeepRecent() int64 { + return po.keepRecent +} - // PruneNothing means all historic states will be saved, nothing will be deleted - PruneNothing PruningStrategy = iota -) +// Keeps every N stated, deleting others. +func (po PruningOptions) KeepEvery() int64 { + return po.keepEvery +} type Store interface { //nolint GetStoreType() StoreType @@ -35,7 +45,7 @@ type Store interface { //nolint type Committer interface { Commit() CommitID LastCommitID() CommitID - SetPruning(PruningStrategy) + SetPruning(PruningOptions) } // Stores of MultiStore must implement CommitStore. diff --git a/x/auth/ante.go b/x/auth/ante.go index 60c50f3e697b..1008bdfa835c 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -29,7 +29,10 @@ func NewAnteHandler(ak AccountKeeper, fck FeeCollectionKeeper) sdk.AnteHandler { // all transactions must be of type auth.StdTx stdTx, ok := tx.(StdTx) if !ok { - return ctx, sdk.ErrInternal("tx must be StdTx").Result(), true + // Set a gas meter with limit 0 as to prevent an infinite gas meter attack + // during runTx. + newCtx = SetGasMeter(simulate, ctx, 0) + return newCtx, sdk.ErrInternal("tx must be StdTx").Result(), true } params := ak.GetParams(ctx) @@ -44,7 +47,7 @@ func NewAnteHandler(ak AccountKeeper, fck FeeCollectionKeeper) sdk.AnteHandler { } } - newCtx = SetGasMeter(simulate, ctx, stdTx) + newCtx = SetGasMeter(simulate, ctx, stdTx.Fee.Gas) // 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 @@ -294,7 +297,7 @@ func EnsureSufficientMempoolFees(ctx sdk.Context, stdTx StdTx) sdk.Result { requiredFees := adjustFeesByGas(ctx.MinimumFees(), stdTx.Fee.Gas) // NOTE: !A.IsAllGTE(B) is not the same as A.IsAllLT(B). - if !ctx.MinimumFees().IsZero() && !stdTx.Fee.Amount.IsAllGTE(requiredFees) { + if !ctx.MinimumFees().IsZero() && !stdTx.Fee.Amount.IsAnyGTE(requiredFees) { // validators reject any tx from the mempool with less than the minimum fee per gas * gas factor return sdk.ErrInsufficientFee( fmt.Sprintf( @@ -306,14 +309,14 @@ func EnsureSufficientMempoolFees(ctx sdk.Context, stdTx StdTx) sdk.Result { } // SetGasMeter returns a new context with a gas meter set from a given context. -func SetGasMeter(simulate bool, ctx sdk.Context, stdTx StdTx) sdk.Context { +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.NewGasMeter(stdTx.Fee.Gas)) + return ctx.WithGasMeter(sdk.NewGasMeter(gasLimit)) } // GetSignBytes returns a slice of bytes to sign over for a given transaction diff --git a/x/auth/ante_test.go b/x/auth/ante_test.go index f92e61274cee..9511798a57bd 100644 --- a/x/auth/ante_test.go +++ b/x/auth/ante_test.go @@ -620,23 +620,23 @@ func TestCountSubkeys(t *testing.T) { } return ret } - genMultiKey := func(n, k int, keysGen func(n int) []crypto.PubKey) crypto.PubKey { - return multisig.NewPubKeyMultisigThreshold(k, keysGen(n)) - } + singleKey := secp256k1.GenPrivKey().PubKey() + singleLevelMultiKey := multisig.NewPubKeyMultisigThreshold(4, genPubKeys(5)) + multiLevelSubKey1 := multisig.NewPubKeyMultisigThreshold(4, genPubKeys(5)) + multiLevelSubKey2 := multisig.NewPubKeyMultisigThreshold(4, genPubKeys(5)) + multiLevelMultiKey := multisig.NewPubKeyMultisigThreshold(2, []crypto.PubKey{ + multiLevelSubKey1, multiLevelSubKey2, secp256k1.GenPrivKey().PubKey()}) type args struct { pub crypto.PubKey } - mkey := genMultiKey(5, 4, genPubKeys) - mkeyType := mkey.(*multisig.PubKeyMultisigThreshold) - mkeyType.PubKeys = append(mkeyType.PubKeys, genMultiKey(6, 5, genPubKeys)) tests := []struct { name string args args want int }{ - {"single key", args{secp256k1.GenPrivKey().PubKey()}, 1}, - {"multi sig key", args{genMultiKey(5, 4, genPubKeys)}, 5}, - {"multi multi sig", args{mkey}, 11}, + {"single key", args{singleKey}, 1}, + {"single level multikey", args{singleLevelMultiKey}, 5}, + {"multi level multikey", args{multiLevelMultiKey}, 11}, } for _, tt := range tests { t.Run(tt.name, func(T *testing.T) { diff --git a/x/auth/client/txbuilder/txbuilder_test.go b/x/auth/client/txbuilder/txbuilder_test.go index f33c96be18df..7d3dfc7ec7bc 100644 --- a/x/auth/client/txbuilder/txbuilder_test.go +++ b/x/auth/client/txbuilder/txbuilder_test.go @@ -11,7 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( @@ -48,7 +48,7 @@ func TestTxBuilderBuild(t *testing.T) { SimulateGas: false, ChainID: "test-chain", Memo: "hello from Voyager !", - Fees: sdk.Coins{sdk.NewCoin(stakeTypes.DefaultBondDenom, sdk.NewInt(1))}, + Fees: sdk.Coins{sdk.NewCoin(stakingTypes.DefaultBondDenom, sdk.NewInt(1))}, }, defaultMsg, StdSignMsg{ @@ -57,7 +57,7 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager !", Msgs: defaultMsg, - Fee: auth.NewStdFee(100, sdk.Coins{sdk.NewCoin(stakeTypes.DefaultBondDenom, sdk.NewInt(1))}), + Fee: auth.NewStdFee(100, sdk.Coins{sdk.NewCoin(stakingTypes.DefaultBondDenom, sdk.NewInt(1))}), }, false, }, diff --git a/x/auth/params.go b/x/auth/params.go index 94cf69ff0b8e..9fcde581cdf1 100644 --- a/x/auth/params.go +++ b/x/auth/params.go @@ -42,7 +42,7 @@ type Params struct { SigVerifyCostSecp256k1 uint64 } -// ParamTable for stake module +// ParamTable for staking module func ParamTypeTable() params.TypeTable { return params.NewTypeTable().RegisterParamSet(&Params{}) } diff --git a/x/auth/stdtx.go b/x/auth/stdtx.go index 07469f81b789..f13e77457e0f 100644 --- a/x/auth/stdtx.go +++ b/x/auth/stdtx.go @@ -71,7 +71,7 @@ func (tx StdTx) ValidateBasic() sdk.Error { // countSubKeys counts the total number of keys for a multi-sig public key. func countSubKeys(pub crypto.PubKey) int { - v, ok := pub.(*multisig.PubKeyMultisigThreshold) + v, ok := pub.(multisig.PubKeyMultisigThreshold) if !ok { return 1 } diff --git a/x/distribution/alias.go b/x/distribution/alias.go index c9922e2c6313..2ca6d8e91cca 100644 --- a/x/distribution/alias.go +++ b/x/distribution/alias.go @@ -27,7 +27,7 @@ type ( GenesisState = types.GenesisState // expected keepers - StakeKeeper = types.StakeKeeper + StakingKeeper = types.StakingKeeper BankKeeper = types.BankKeeper FeeCollectionKeeper = types.FeeCollectionKeeper ) @@ -71,7 +71,7 @@ const ( StoreKey = types.StoreKey TStoreKey = types.TStoreKey RouterKey = types.RouterKey - QuerierRoute = types.QuerierRoute + QuerierRoute = types.QuerierRoute ) var ( diff --git a/x/distribution/keeper/allocation.go b/x/distribution/keeper/allocation.go index 97b1e4b379db..4468f7d3c4fc 100644 --- a/x/distribution/keeper/allocation.go +++ b/x/distribution/keeper/allocation.go @@ -9,7 +9,7 @@ import ( func (k Keeper) AllocateTokens(ctx sdk.Context, percentVotes sdk.Dec, proposer sdk.ConsAddress) { // get the proposer of this block - proposerValidator := k.stakeKeeper.ValidatorByConsAddr(ctx, proposer) + proposerValidator := k.stakingKeeper.ValidatorByConsAddr(ctx, proposer) proposerDist := k.GetValidatorDistInfo(ctx, proposerValidator.GetOperator()) @@ -21,7 +21,7 @@ func (k Keeper) AllocateTokens(ctx sdk.Context, percentVotes sdk.Dec, proposer s feePool := k.GetFeePool(ctx) // Temporary workaround to keep CanWithdrawInvariant happy. // General discussions here: https://github.com/cosmos/cosmos-sdk/issues/2906#issuecomment-441867634 - if k.stakeKeeper.GetLastTotalPower(ctx).IsZero() { + if k.stakingKeeper.GetLastTotalPower(ctx).IsZero() { feePool.CommunityPool = feePool.CommunityPool.Plus(feesCollectedDec) k.SetFeePool(ctx, feePool) k.feeCollectionKeeper.ClearCollectedFees(ctx) diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index b6b28ac456b0..dae7beee79ef 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -7,21 +7,21 @@ import ( "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" ) func TestAllocateTokensBasic(t *testing.T) { // no community tax on inputs ctx, _, keeper, sk, fck := CreateTestInputAdvanced(t, false, 100, sdk.ZeroDec()) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom //first make a validator totalPower := int64(10) totalPowerInt := sdk.NewInt(totalPower) - msgCreateValidator := stake.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, totalPower) - got := stakeHandler(ctx, msgCreateValidator) + msgCreateValidator := staking.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, totalPower) + got := stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) _ = sk.ApplyAndReturnValidatorSetUpdates(ctx) @@ -56,13 +56,13 @@ func TestAllocateTokensBasic(t *testing.T) { func TestAllocateTokensWithCommunityTax(t *testing.T) { communityTax := sdk.NewDecWithPrec(1, 2) //1% ctx, _, keeper, sk, fck := CreateTestInputAdvanced(t, false, 100, communityTax) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom //first make a validator totalPower := int64(10) - msgCreateValidator := stake.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, totalPower) - got := stakeHandler(ctx, msgCreateValidator) + msgCreateValidator := staking.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, totalPower) + got := stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) _ = sk.ApplyAndReturnValidatorSetUpdates(ctx) @@ -84,13 +84,13 @@ func TestAllocateTokensWithCommunityTax(t *testing.T) { func TestAllocateTokensWithPartialPrecommitPower(t *testing.T) { communityTax := sdk.NewDecWithPrec(1, 2) ctx, _, keeper, sk, fck := CreateTestInputAdvanced(t, false, 100, communityTax) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom //first make a validator totalPower := int64(100) - msgCreateValidator := stake.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, totalPower) - got := stakeHandler(ctx, msgCreateValidator) + msgCreateValidator := staking.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, totalPower) + got := stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) _ = sk.ApplyAndReturnValidatorSetUpdates(ctx) diff --git a/x/distribution/keeper/delegation.go b/x/distribution/keeper/delegation.go index dc54a6e4fe5f..93e068cec831 100644 --- a/x/distribution/keeper/delegation.go +++ b/x/distribution/keeper/delegation.go @@ -105,8 +105,8 @@ func (k Keeper) withdrawDelegationReward(ctx sdk.Context, wc := k.GetWithdrawContext(ctx, valAddr) valInfo := k.GetValidatorDistInfo(ctx, valAddr) delInfo := k.GetDelegationDistInfo(ctx, delAddr, valAddr) - validator := k.stakeKeeper.Validator(ctx, valAddr) - delegation := k.stakeKeeper.Delegation(ctx, delAddr, valAddr) + validator := k.stakingKeeper.Validator(ctx, valAddr) + delegation := k.stakingKeeper.Delegation(ctx, delAddr, valAddr) delInfo, valInfo, feePool, withdraw := delInfo.WithdrawRewards(wc, valInfo, validator.GetDelegatorShares(), delegation.GetShares()) @@ -122,8 +122,8 @@ func (k Keeper) currentDelegationReward(ctx sdk.Context, delAddr sdk.AccAddress, valInfo := k.GetValidatorDistInfo(ctx, valAddr) delInfo := k.GetDelegationDistInfo(ctx, delAddr, valAddr) - validator := k.stakeKeeper.Validator(ctx, valAddr) - delegation := k.stakeKeeper.Delegation(ctx, delAddr, valAddr) + validator := k.stakingKeeper.Validator(ctx, valAddr) + delegation := k.stakingKeeper.Delegation(ctx, delAddr, valAddr) estimation := delInfo.CurrentRewards(wc, valInfo, validator.GetDelegatorShares(), delegation.GetShares()) @@ -209,7 +209,7 @@ func (k Keeper) withdrawDelegationRewardsAll(ctx sdk.Context, return false } - k.stakeKeeper.IterateDelegations(ctx, delAddr, operationAtDelegation) + k.stakingKeeper.IterateDelegations(ctx, delAddr, operationAtDelegation) return withdraw } @@ -225,6 +225,6 @@ func (k Keeper) CurrentDelegationRewardsAll(ctx sdk.Context, total = total.Plus(est) return false } - k.stakeKeeper.IterateDelegations(ctx, delAddr, operationAtDelegation) + k.stakingKeeper.IterateDelegations(ctx, delAddr, operationAtDelegation) return total } diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index 67606cc842b8..114ec1b633b1 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -6,23 +6,23 @@ import ( "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" ) func TestWithdrawDelegationRewardBasic(t *testing.T) { ctx, accMapper, keeper, sk, fck := CreateTestInputAdvanced(t, false, 100, sdk.ZeroDec()) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom //first make a validator - msgCreateValidator := stake.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, 10) - got := stakeHandler(ctx, msgCreateValidator) + msgCreateValidator := staking.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, 10) + got := stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) _ = sk.ApplyAndReturnValidatorSetUpdates(ctx) // delegate - msgDelegate := stake.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) - got = stakeHandler(ctx, msgDelegate) + msgDelegate := staking.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) + got = stakingHandler(ctx, msgDelegate) require.True(t, got.IsOK()) amt := accMapper.GetAccount(ctx, delAddr1).GetCoins().AmountOf(denom) require.Equal(t, int64(90), amt.Int64()) @@ -46,19 +46,19 @@ func TestWithdrawDelegationRewardBasic(t *testing.T) { func TestWithdrawDelegationRewardWithCommission(t *testing.T) { ctx, accMapper, keeper, sk, fck := CreateTestInputAdvanced(t, false, 100, sdk.ZeroDec()) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom //first make a validator with 10% commission - msgCreateValidator := stake.NewTestMsgCreateValidatorWithCommission( + msgCreateValidator := staking.NewTestMsgCreateValidatorWithCommission( valOpAddr1, valConsPk1, 10, sdk.NewDecWithPrec(1, 1)) - got := stakeHandler(ctx, msgCreateValidator) + got := stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) _ = sk.ApplyAndReturnValidatorSetUpdates(ctx) // delegate - msgDelegate := stake.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) - got = stakeHandler(ctx, msgDelegate) + msgDelegate := staking.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) + got = stakingHandler(ctx, msgDelegate) require.True(t, got.IsOK()) amt := accMapper.GetAccount(ctx, delAddr1).GetCoins().AmountOf(denom) require.Equal(t, int64(90), amt.Int64()) @@ -80,25 +80,25 @@ func TestWithdrawDelegationRewardWithCommission(t *testing.T) { func TestWithdrawDelegationRewardTwoDelegators(t *testing.T) { ctx, accMapper, keeper, sk, fck := CreateTestInputAdvanced(t, false, 100, sdk.ZeroDec()) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom //first make a validator with 10% commission - msgCreateValidator := stake.NewTestMsgCreateValidatorWithCommission( + msgCreateValidator := staking.NewTestMsgCreateValidatorWithCommission( valOpAddr1, valConsPk1, 10, sdk.NewDecWithPrec(1, 1)) - got := stakeHandler(ctx, msgCreateValidator) + got := stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) _ = sk.ApplyAndReturnValidatorSetUpdates(ctx) // delegate - msgDelegate := stake.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) - got = stakeHandler(ctx, msgDelegate) + msgDelegate := staking.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) + got = stakingHandler(ctx, msgDelegate) require.True(t, got.IsOK()) amt := accMapper.GetAccount(ctx, delAddr1).GetCoins().AmountOf(denom) require.Equal(t, int64(90), amt.Int64()) - msgDelegate = stake.NewTestMsgDelegate(delAddr2, valOpAddr1, 20) - got = stakeHandler(ctx, msgDelegate) + msgDelegate = staking.NewTestMsgDelegate(delAddr2, valOpAddr1, 20) + got = stakingHandler(ctx, msgDelegate) require.True(t, got.IsOK()) amt = accMapper.GetAccount(ctx, delAddr2).GetCoins().AmountOf(denom) require.Equal(t, int64(80), amt.Int64()) @@ -122,25 +122,25 @@ func TestWithdrawDelegationRewardTwoDelegators(t *testing.T) { // with different rewards in the end func TestWithdrawDelegationRewardTwoDelegatorsUneven(t *testing.T) { ctx, accMapper, keeper, sk, fck := CreateTestInputAdvanced(t, false, 100, sdk.ZeroDec()) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom //first make a validator with no commission - msgCreateValidator := stake.NewTestMsgCreateValidatorWithCommission( + msgCreateValidator := staking.NewTestMsgCreateValidatorWithCommission( valOpAddr1, valConsPk1, 10, sdk.ZeroDec()) - got := stakeHandler(ctx, msgCreateValidator) + got := stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) _ = sk.ApplyAndReturnValidatorSetUpdates(ctx) // delegate - msgDelegate := stake.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) - got = stakeHandler(ctx, msgDelegate) + msgDelegate := staking.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) + got = stakingHandler(ctx, msgDelegate) require.True(t, got.IsOK()) amt := accMapper.GetAccount(ctx, delAddr1).GetCoins().AmountOf(denom) require.Equal(t, int64(90), amt.Int64()) - msgDelegate = stake.NewTestMsgDelegate(delAddr2, valOpAddr1, 10) - got = stakeHandler(ctx, msgDelegate) + msgDelegate = staking.NewTestMsgDelegate(delAddr2, valOpAddr1, 10) + got = stakingHandler(ctx, msgDelegate) require.True(t, got.IsOK()) amt = accMapper.GetAccount(ctx, delAddr2).GetCoins().AmountOf(denom) require.Equal(t, int64(90), amt.Int64()) @@ -188,32 +188,32 @@ func TestWithdrawDelegationRewardTwoDelegatorsUneven(t *testing.T) { func TestWithdrawDelegationRewardsAll(t *testing.T) { ctx, accMapper, keeper, sk, fck := CreateTestInputAdvanced(t, false, 100, sdk.ZeroDec()) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom //make some validators with different commissions - msgCreateValidator := stake.NewTestMsgCreateValidatorWithCommission( + msgCreateValidator := staking.NewTestMsgCreateValidatorWithCommission( valOpAddr1, valConsPk1, 10, sdk.NewDecWithPrec(1, 1)) - got := stakeHandler(ctx, msgCreateValidator) + got := stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) - msgCreateValidator = stake.NewTestMsgCreateValidatorWithCommission( + msgCreateValidator = staking.NewTestMsgCreateValidatorWithCommission( valOpAddr2, valConsPk2, 50, sdk.NewDecWithPrec(2, 1)) - got = stakeHandler(ctx, msgCreateValidator) + got = stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) - msgCreateValidator = stake.NewTestMsgCreateValidatorWithCommission( + msgCreateValidator = staking.NewTestMsgCreateValidatorWithCommission( valOpAddr3, valConsPk3, 40, sdk.NewDecWithPrec(3, 1)) - got = stakeHandler(ctx, msgCreateValidator) + got = stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) // delegate to all the validators - msgDelegate := stake.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) - require.True(t, stakeHandler(ctx, msgDelegate).IsOK()) - msgDelegate = stake.NewTestMsgDelegate(delAddr1, valOpAddr2, 20) - require.True(t, stakeHandler(ctx, msgDelegate).IsOK()) - msgDelegate = stake.NewTestMsgDelegate(delAddr1, valOpAddr3, 30) - require.True(t, stakeHandler(ctx, msgDelegate).IsOK()) + msgDelegate := staking.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) + require.True(t, stakingHandler(ctx, msgDelegate).IsOK()) + msgDelegate = staking.NewTestMsgDelegate(delAddr1, valOpAddr2, 20) + require.True(t, stakingHandler(ctx, msgDelegate).IsOK()) + msgDelegate = staking.NewTestMsgDelegate(delAddr1, valOpAddr3, 30) + require.True(t, stakingHandler(ctx, msgDelegate).IsOK()) // Update sk's LastValidatorPower/LastTotalPowers. _ = sk.ApplyAndReturnValidatorSetUpdates(ctx) diff --git a/x/distribution/keeper/hooks.go b/x/distribution/keeper/hooks.go index 910f6eafa262..10d4f059b1c1 100644 --- a/x/distribution/keeper/hooks.go +++ b/x/distribution/keeper/hooks.go @@ -8,7 +8,7 @@ import ( ) // Create a new validator distribution record -func (k Keeper) onValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { +func (k Keeper) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { // defensive check for existence if k.HasValidatorDistInfo(ctx, valAddr) { @@ -27,7 +27,7 @@ func (k Keeper) onValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { } // Withdraw all validator rewards -func (k Keeper) onValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { +func (k Keeper) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { // Move the validator's rewards from the global pool to the validator's pools // (dist info), but without actually withdrawing the rewards. This does not // need to happen during the genesis block. @@ -39,16 +39,16 @@ func (k Keeper) onValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { } // Withdraw all validator rewards -func (k Keeper) onValidatorBonded(ctx sdk.Context, valAddr sdk.ValAddress) { - lastPower := k.stakeKeeper.GetLastValidatorPower(ctx, valAddr) +func (k Keeper) AfterValidatorBonded(ctx sdk.Context, valAddr sdk.ValAddress) { + lastPower := k.stakingKeeper.GetLastValidatorPower(ctx, valAddr) if !lastPower.Equal(sdk.ZeroInt()) { panic("expected last power to be 0 for validator entering bonded state") } - k.onValidatorModified(ctx, valAddr) + k.BeforeValidatorModified(ctx, valAddr) } // Sanity check, very useful! -func (k Keeper) onValidatorPowerDidChange(ctx sdk.Context, valAddr sdk.ValAddress) { +func (k Keeper) AfterValidatorPowerDidChange(ctx sdk.Context, valAddr sdk.ValAddress) { vi := k.GetValidatorDistInfo(ctx, valAddr) if vi.FeePoolWithdrawalHeight != ctx.BlockHeight() { panic(fmt.Sprintf("expected validator (%v) dist info FeePoolWithdrawalHeight to be updated to %v, but was %v.", @@ -57,14 +57,14 @@ func (k Keeper) onValidatorPowerDidChange(ctx sdk.Context, valAddr sdk.ValAddres } // Withdrawal all validator distribution rewards and cleanup the distribution record -func (k Keeper) onValidatorRemoved(ctx sdk.Context, valAddr sdk.ValAddress) { +func (k Keeper) AfterValidatorRemoved(ctx sdk.Context, valAddr sdk.ValAddress) { k.RemoveValidatorDistInfo(ctx, valAddr) } //_________________________________________________________________________________________ // Create a new delegator distribution record -func (k Keeper) onDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, +func (k Keeper) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { ddi := types.DelegationDistInfo{ @@ -76,7 +76,7 @@ func (k Keeper) onDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, } // Withdrawal all validator rewards -func (k Keeper) onDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, +func (k Keeper) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { if err := k.WithdrawDelegationReward(ctx, delAddr, valAddr); err != nil { @@ -85,7 +85,7 @@ func (k Keeper) onDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddre } // Withdrawal all validator distribution rewards and cleanup the distribution record -func (k Keeper) onDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, +func (k Keeper) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { // Withdraw validator commission when validator self-bond is removed. // Because we maintain the invariant that all delegations must be removed @@ -115,32 +115,32 @@ var _ sdk.StakingHooks = Hooks{} func (k Keeper) Hooks() Hooks { return Hooks{k} } // nolint -func (h Hooks) OnValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { - h.k.onValidatorCreated(ctx, valAddr) +func (h Hooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { + h.k.AfterValidatorCreated(ctx, valAddr) } -func (h Hooks) OnValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { - h.k.onValidatorModified(ctx, valAddr) +func (h Hooks) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { + h.k.BeforeValidatorModified(ctx, valAddr) } -func (h Hooks) OnValidatorRemoved(ctx sdk.Context, _ sdk.ConsAddress, valAddr sdk.ValAddress) { - h.k.onValidatorRemoved(ctx, valAddr) +func (h Hooks) AfterValidatorRemoved(ctx sdk.Context, _ sdk.ConsAddress, valAddr sdk.ValAddress) { + h.k.AfterValidatorRemoved(ctx, valAddr) } -func (h Hooks) OnDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.k.onValidatorModified(ctx, valAddr) - h.k.onDelegationCreated(ctx, delAddr, valAddr) +func (h Hooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.k.BeforeValidatorModified(ctx, valAddr) + h.k.BeforeDelegationCreated(ctx, delAddr, valAddr) } -func (h Hooks) OnDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.k.onValidatorModified(ctx, valAddr) - h.k.onDelegationSharesModified(ctx, delAddr, valAddr) +func (h Hooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.k.BeforeValidatorModified(ctx, valAddr) + h.k.BeforeDelegationSharesModified(ctx, delAddr, valAddr) } -func (h Hooks) OnDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.k.onDelegationRemoved(ctx, delAddr, valAddr) +func (h Hooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.k.BeforeDelegationRemoved(ctx, delAddr, valAddr) } -func (h Hooks) OnValidatorBeginUnbonding(ctx sdk.Context, _ sdk.ConsAddress, valAddr sdk.ValAddress) { - h.k.onValidatorModified(ctx, valAddr) +func (h Hooks) AfterValidatorBeginUnbonding(ctx sdk.Context, _ sdk.ConsAddress, valAddr sdk.ValAddress) { + h.k.BeforeValidatorModified(ctx, valAddr) } -func (h Hooks) OnValidatorBonded(ctx sdk.Context, _ sdk.ConsAddress, valAddr sdk.ValAddress) { - h.k.onValidatorBonded(ctx, valAddr) +func (h Hooks) AfterValidatorBonded(ctx sdk.Context, _ sdk.ConsAddress, valAddr sdk.ValAddress) { + h.k.AfterValidatorBonded(ctx, valAddr) } -func (h Hooks) OnValidatorPowerDidChange(ctx sdk.Context, _ sdk.ConsAddress, valAddr sdk.ValAddress) { - h.k.onValidatorPowerDidChange(ctx, valAddr) +func (h Hooks) AfterValidatorPowerDidChange(ctx sdk.Context, _ sdk.ConsAddress, valAddr sdk.ValAddress) { + h.k.AfterValidatorPowerDidChange(ctx, valAddr) } diff --git a/x/distribution/keeper/keeper.go b/x/distribution/keeper/keeper.go index a6fed963586a..f2c68b8a0055 100644 --- a/x/distribution/keeper/keeper.go +++ b/x/distribution/keeper/keeper.go @@ -7,13 +7,13 @@ import ( "github.com/cosmos/cosmos-sdk/x/params" ) -// keeper of the stake store +// keeper of the staking store type Keeper struct { storeKey sdk.StoreKey cdc *codec.Codec paramSpace params.Subspace bankKeeper types.BankKeeper - stakeKeeper types.StakeKeeper + stakingKeeper types.StakingKeeper feeCollectionKeeper types.FeeCollectionKeeper // codespace @@ -21,14 +21,14 @@ type Keeper struct { } func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, paramSpace params.Subspace, ck types.BankKeeper, - sk types.StakeKeeper, fck types.FeeCollectionKeeper, codespace sdk.CodespaceType) Keeper { + sk types.StakingKeeper, fck types.FeeCollectionKeeper, codespace sdk.CodespaceType) Keeper { keeper := Keeper{ storeKey: key, cdc: cdc, paramSpace: paramSpace.WithTypeTable(ParamTypeTable()), bankKeeper: ck, - stakeKeeper: sk, + stakingKeeper: sk, feeCollectionKeeper: fck, codespace: codespace, } @@ -61,7 +61,7 @@ func (k Keeper) GetFeePoolValAccum(ctx sdk.Context) sdk.Dec { // withdraw self-delegation height := ctx.BlockHeight() - totalPower := sdk.NewDecFromInt(k.stakeKeeper.GetLastTotalPower(ctx)) + totalPower := sdk.NewDecFromInt(k.stakingKeeper.GetLastTotalPower(ctx)) fp := k.GetFeePool(ctx) return fp.GetTotalValAccum(height, totalPower) } @@ -96,9 +96,9 @@ func (k Keeper) GetWithdrawContext(ctx sdk.Context, feePool := k.GetFeePool(ctx) height := ctx.BlockHeight() - validator := k.stakeKeeper.Validator(ctx, valOperatorAddr) - lastValPower := k.stakeKeeper.GetLastValidatorPower(ctx, valOperatorAddr) - lastTotalPower := sdk.NewDecFromInt(k.stakeKeeper.GetLastTotalPower(ctx)) + validator := k.stakingKeeper.Validator(ctx, valOperatorAddr) + lastValPower := k.stakingKeeper.GetLastValidatorPower(ctx, valOperatorAddr) + lastTotalPower := sdk.NewDecFromInt(k.stakingKeeper.GetLastTotalPower(ctx)) return types.NewWithdrawContext( feePool, height, lastTotalPower, sdk.NewDecFromInt(lastValPower), diff --git a/x/distribution/keeper/test_common.go b/x/distribution/keeper/test_common.go index 64bd7d5e9c3e..793f557738d5 100644 --- a/x/distribution/keeper/test_common.go +++ b/x/distribution/keeper/test_common.go @@ -17,7 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/distribution/types" ) @@ -61,7 +61,7 @@ var ( func MakeTestCodec() *codec.Codec { var cdc = codec.New() bank.RegisterCodec(cdc) - stake.RegisterCodec(cdc) + staking.RegisterCodec(cdc) auth.RegisterCodec(cdc) sdk.RegisterCodec(cdc) codec.RegisterCrypto(cdc) @@ -72,7 +72,7 @@ func MakeTestCodec() *codec.Codec { // test input with default values func CreateTestInputDefault(t *testing.T, isCheckTx bool, initCoins int64) ( - sdk.Context, auth.AccountKeeper, Keeper, stake.Keeper, DummyFeeCollectionKeeper) { + sdk.Context, auth.AccountKeeper, Keeper, staking.Keeper, DummyFeeCollectionKeeper) { communityTax := sdk.NewDecWithPrec(2, 2) return CreateTestInputAdvanced(t, isCheckTx, initCoins, communityTax) @@ -81,11 +81,11 @@ func CreateTestInputDefault(t *testing.T, isCheckTx bool, initCoins int64) ( // hogpodge of all sorts of input required for testing func CreateTestInputAdvanced(t *testing.T, isCheckTx bool, initCoins int64, communityTax sdk.Dec) ( - sdk.Context, auth.AccountKeeper, Keeper, stake.Keeper, DummyFeeCollectionKeeper) { + sdk.Context, auth.AccountKeeper, Keeper, staking.Keeper, DummyFeeCollectionKeeper) { keyDistr := sdk.NewKVStoreKey(types.StoreKey) - keyStake := sdk.NewKVStoreKey(stake.StoreKey) - tkeyStake := sdk.NewTransientStoreKey(stake.TStoreKey) + keyStaking := sdk.NewKVStoreKey(staking.StoreKey) + tkeyStaking := sdk.NewTransientStoreKey(staking.TStoreKey) keyAcc := sdk.NewKVStoreKey(auth.StoreKey) keyFeeCollection := sdk.NewKVStoreKey(auth.FeeStoreKey) keyParams := sdk.NewKVStoreKey(params.StoreKey) @@ -95,8 +95,8 @@ func CreateTestInputAdvanced(t *testing.T, isCheckTx bool, initCoins int64, ms := store.NewCommitMultiStore(db) ms.MountStoreWithDB(keyDistr, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(tkeyStake, sdk.StoreTypeTransient, nil) - ms.MountStoreWithDB(keyStake, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(tkeyStaking, sdk.StoreTypeTransient, nil) + ms.MountStoreWithDB(keyStaking, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keyAcc, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keyFeeCollection, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) @@ -111,9 +111,9 @@ func CreateTestInputAdvanced(t *testing.T, isCheckTx bool, initCoins int64, ctx := sdk.NewContext(ms, abci.Header{ChainID: "foochainid"}, isCheckTx, log.NewNopLogger()) accountKeeper := auth.NewAccountKeeper(cdc, keyAcc, pk.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) ck := bank.NewBaseKeeper(accountKeeper) - sk := stake.NewKeeper(cdc, keyStake, tkeyStake, ck, pk.Subspace(stake.DefaultParamspace), stake.DefaultCodespace) - sk.SetPool(ctx, stake.InitialPool()) - sk.SetParams(ctx, stake.DefaultParams()) + sk := staking.NewKeeper(cdc, keyStaking, tkeyStaking, ck, pk.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) + sk.SetPool(ctx, staking.InitialPool()) + sk.SetParams(ctx, staking.DefaultParams()) // fill all the addresses with some coins, set the loose pool tokens simultaneously for _, addr := range addrs { diff --git a/x/distribution/keeper/validator.go b/x/distribution/keeper/validator.go index 8d861fef8043..76e5fe8d336a 100644 --- a/x/distribution/keeper/validator.go +++ b/x/distribution/keeper/validator.go @@ -87,7 +87,7 @@ func (k Keeper) GetValidatorAccum(ctx sdk.Context, operatorAddr sdk.ValAddress) // withdraw self-delegation height := ctx.BlockHeight() - lastValPower := k.stakeKeeper.GetLastValidatorPower(ctx, operatorAddr) + lastValPower := k.stakingKeeper.GetLastValidatorPower(ctx, operatorAddr) valInfo := k.GetValidatorDistInfo(ctx, operatorAddr) accum := valInfo.GetValAccum(height, sdk.NewDecFromInt(lastValPower)) diff --git a/x/distribution/keeper/validator_test.go b/x/distribution/keeper/validator_test.go index 58079241cc42..a6956fcc0cdc 100644 --- a/x/distribution/keeper/validator_test.go +++ b/x/distribution/keeper/validator_test.go @@ -6,17 +6,17 @@ import ( "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" ) func TestWithdrawValidatorRewardsAllNoDelegator(t *testing.T) { ctx, accMapper, keeper, sk, fck := CreateTestInputAdvanced(t, false, 100, sdk.ZeroDec()) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom // first make a validator - msgCreateValidator := stake.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, 10) - got := stakeHandler(ctx, msgCreateValidator) + msgCreateValidator := staking.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, 10) + got := stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) _ = sk.ApplyAndReturnValidatorSetUpdates(ctx) @@ -36,18 +36,18 @@ func TestWithdrawValidatorRewardsAllNoDelegator(t *testing.T) { func TestWithdrawValidatorRewardsAllDelegatorNoCommission(t *testing.T) { ctx, accMapper, keeper, sk, fck := CreateTestInputAdvanced(t, false, 100, sdk.ZeroDec()) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom //first make a validator - msgCreateValidator := stake.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, 10) - got := stakeHandler(ctx, msgCreateValidator) + msgCreateValidator := staking.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, 10) + got := stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) _ = sk.ApplyAndReturnValidatorSetUpdates(ctx) // delegate - msgDelegate := stake.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) - got = stakeHandler(ctx, msgDelegate) + msgDelegate := staking.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) + got = stakingHandler(ctx, msgDelegate) require.True(t, got.IsOK()) amt := accMapper.GetAccount(ctx, delAddr1).GetCoins().AmountOf(denom) require.Equal(t, int64(90), amt.Int64()) @@ -68,20 +68,20 @@ func TestWithdrawValidatorRewardsAllDelegatorNoCommission(t *testing.T) { func TestWithdrawValidatorRewardsAllDelegatorWithCommission(t *testing.T) { ctx, accMapper, keeper, sk, fck := CreateTestInputAdvanced(t, false, 100, sdk.ZeroDec()) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom //first make a validator commissionRate := sdk.NewDecWithPrec(1, 1) - msgCreateValidator := stake.NewTestMsgCreateValidatorWithCommission( + msgCreateValidator := staking.NewTestMsgCreateValidatorWithCommission( valOpAddr1, valConsPk1, 10, commissionRate) - got := stakeHandler(ctx, msgCreateValidator) + got := stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) _ = sk.ApplyAndReturnValidatorSetUpdates(ctx) // delegate - msgDelegate := stake.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) - got = stakeHandler(ctx, msgDelegate) + msgDelegate := staking.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) + got = stakingHandler(ctx, msgDelegate) require.True(t, got.IsOK()) amt := accMapper.GetAccount(ctx, delAddr1).GetCoins().AmountOf(denom) require.Equal(t, int64(90), amt.Int64()) @@ -105,26 +105,26 @@ func TestWithdrawValidatorRewardsAllDelegatorWithCommission(t *testing.T) { func TestWithdrawValidatorRewardsAllMultipleValidator(t *testing.T) { ctx, accMapper, keeper, sk, fck := CreateTestInputAdvanced(t, false, 100, sdk.ZeroDec()) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom // Make some validators with different commissions. // Bond 10 of 100 with 0.1 commission. - msgCreateValidator := stake.NewTestMsgCreateValidatorWithCommission( + msgCreateValidator := staking.NewTestMsgCreateValidatorWithCommission( valOpAddr1, valConsPk1, 10, sdk.NewDecWithPrec(1, 1)) - got := stakeHandler(ctx, msgCreateValidator) + got := stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) // Bond 50 of 100 with 0.2 commission. - msgCreateValidator = stake.NewTestMsgCreateValidatorWithCommission( + msgCreateValidator = staking.NewTestMsgCreateValidatorWithCommission( valOpAddr2, valConsPk2, 50, sdk.NewDecWithPrec(2, 1)) - got = stakeHandler(ctx, msgCreateValidator) + got = stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) // Bond 40 of 100 with 0.3 commission. - msgCreateValidator = stake.NewTestMsgCreateValidatorWithCommission( + msgCreateValidator = staking.NewTestMsgCreateValidatorWithCommission( valOpAddr3, valConsPk3, 40, sdk.NewDecWithPrec(3, 1)) - got = stakeHandler(ctx, msgCreateValidator) + got = stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) _ = sk.ApplyAndReturnValidatorSetUpdates(ctx) @@ -156,26 +156,26 @@ func TestWithdrawValidatorRewardsAllMultipleValidator(t *testing.T) { func TestWithdrawValidatorRewardsAllMultipleDelegator(t *testing.T) { ctx, accMapper, keeper, sk, fck := CreateTestInputAdvanced(t, false, 100, sdk.ZeroDec()) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom //first make a validator with 10% commission commissionRate := sdk.NewDecWithPrec(1, 1) - msgCreateValidator := stake.NewTestMsgCreateValidatorWithCommission( + msgCreateValidator := staking.NewTestMsgCreateValidatorWithCommission( valOpAddr1, valConsPk1, 10, sdk.NewDecWithPrec(1, 1)) - got := stakeHandler(ctx, msgCreateValidator) + got := stakingHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) _ = sk.ApplyAndReturnValidatorSetUpdates(ctx) // delegate - msgDelegate := stake.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) - got = stakeHandler(ctx, msgDelegate) + msgDelegate := staking.NewTestMsgDelegate(delAddr1, valOpAddr1, 10) + got = stakingHandler(ctx, msgDelegate) require.True(t, got.IsOK()) amt := accMapper.GetAccount(ctx, delAddr1).GetCoins().AmountOf(denom) require.Equal(t, int64(90), amt.Int64()) - msgDelegate = stake.NewTestMsgDelegate(delAddr2, valOpAddr1, 20) - got = stakeHandler(ctx, msgDelegate) + msgDelegate = staking.NewTestMsgDelegate(delAddr2, valOpAddr1, 20) + got = stakingHandler(ctx, msgDelegate) require.True(t, got.IsOK()) amt = accMapper.GetAccount(ctx, delAddr2).GetCoins().AmountOf(denom) require.Equal(t, int64(80), amt.Int64()) diff --git a/x/distribution/simulation/invariants.go b/x/distribution/simulation/invariants.go index 2f954d6e1204..cdebc98d2c81 100644 --- a/x/distribution/simulation/invariants.go +++ b/x/distribution/simulation/invariants.go @@ -6,13 +6,13 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" distr "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/mock/simulation" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" ) // AllInvariants runs all invariants of the distribution module // Currently: total supply, positive power -func AllInvariants(d distr.Keeper, stk stake.Keeper) simulation.Invariant { - sk := distr.StakeKeeper(stk) +func AllInvariants(d distr.Keeper, stk staking.Keeper) simulation.Invariant { + sk := distr.StakingKeeper(stk) return func(ctx sdk.Context) error { err := ValAccumInvariants(d, sk)(ctx) if err != nil { @@ -31,7 +31,7 @@ func AllInvariants(d distr.Keeper, stk stake.Keeper) simulation.Invariant { } // ValAccumInvariants checks that the fee pool accum == sum all validators' accum -func ValAccumInvariants(k distr.Keeper, sk distr.StakeKeeper) simulation.Invariant { +func ValAccumInvariants(k distr.Keeper, sk distr.StakingKeeper) simulation.Invariant { return func(ctx sdk.Context) error { height := ctx.BlockHeight() @@ -56,7 +56,7 @@ func ValAccumInvariants(k distr.Keeper, sk distr.StakeKeeper) simulation.Invaria } // DelAccumInvariants checks that each validator del accum == sum all delegators' accum -func DelAccumInvariants(k distr.Keeper, sk distr.StakeKeeper) simulation.Invariant { +func DelAccumInvariants(k distr.Keeper, sk distr.StakingKeeper) simulation.Invariant { return func(ctx sdk.Context) error { height := ctx.BlockHeight() @@ -133,7 +133,7 @@ func DelAccumInvariants(k distr.Keeper, sk distr.StakeKeeper) simulation.Invaria } // CanWithdrawInvariant checks that current rewards can be completely withdrawn -func CanWithdrawInvariant(k distr.Keeper, sk stake.Keeper) simulation.Invariant { +func CanWithdrawInvariant(k distr.Keeper, sk staking.Keeper) simulation.Invariant { return func(ctx sdk.Context) error { // we don't want to write the changes ctx, _ = ctx.CacheContext() diff --git a/x/distribution/types/delegation_info_test.go b/x/distribution/types/delegation_info_test.go index 9c2a4980f686..e97ea80510a6 100644 --- a/x/distribution/types/delegation_info_test.go +++ b/x/distribution/types/delegation_info_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/assert" sdk "github.com/cosmos/cosmos-sdk/types" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) func TestWithdrawRewards(t *testing.T) { @@ -28,7 +28,7 @@ func TestWithdrawRewards(t *testing.T) { // simulate adding some stake for inflation height = 10 - fp.ValPool = DecCoins{NewDecCoin(stakeTypes.DefaultBondDenom, 1000)} + fp.ValPool = DecCoins{NewDecCoin(stakingTypes.DefaultBondDenom, 1000)} // withdraw rewards wc := NewWithdrawContext(fp, height, diff --git a/x/distribution/types/keepers.go b/x/distribution/types/keepers.go index c44c0dedf271..4411ebc8de61 100644 --- a/x/distribution/types/keepers.go +++ b/x/distribution/types/keepers.go @@ -2,8 +2,8 @@ package types import sdk "github.com/cosmos/cosmos-sdk/types" -// expected stake keeper -type StakeKeeper interface { +// expected staking keeper +type StakingKeeper interface { IterateDelegations(ctx sdk.Context, delegator sdk.AccAddress, fn func(index int64, delegation sdk.Delegation) (stop bool)) Delegation(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) sdk.Delegation diff --git a/x/distribution/types/validator_info_test.go b/x/distribution/types/validator_info_test.go index 3761c4e7653e..9982a7dc1c69 100644 --- a/x/distribution/types/validator_info_test.go +++ b/x/distribution/types/validator_info_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) func TestTakeFeePoolRewards(t *testing.T) { @@ -28,7 +28,7 @@ func TestTakeFeePoolRewards(t *testing.T) { // simulate adding some stake for inflation height = 10 - fp.ValPool = DecCoins{NewDecCoin(stakeTypes.DefaultBondDenom, 1000)} + fp.ValPool = DecCoins{NewDecCoin(stakingTypes.DefaultBondDenom, 1000)} vi1, fp = vi1.TakeFeePoolRewards(NewWithdrawContext( fp, height, totalBondedTokens, validatorTokens1, commissionRate1)) @@ -68,7 +68,7 @@ func TestWithdrawCommission(t *testing.T) { // simulate adding some stake for inflation height = 10 - fp.ValPool = DecCoins{NewDecCoin(stakeTypes.DefaultBondDenom, 1000)} + fp.ValPool = DecCoins{NewDecCoin(stakingTypes.DefaultBondDenom, 1000)} // for a more fun staring condition, have an non-withdraw update vi, fp = vi.TakeFeePoolRewards(NewWithdrawContext( diff --git a/x/gov/endblocker_test.go b/x/gov/endblocker_test.go index 622d0968f085..1eb60c4f2b8a 100644 --- a/x/gov/endblocker_test.go +++ b/x/gov/endblocker_test.go @@ -9,11 +9,11 @@ import ( abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) func TestTickExpiredDepositPeriod(t *testing.T) { - mapp, keeper, _, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, _, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) govHandler := NewHandler(keeper) @@ -22,7 +22,7 @@ func TestTickExpiredDepositPeriod(t *testing.T) { require.False(t, inactiveQueue.Valid()) inactiveQueue.Close() - newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 5)}) + newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 5)}) res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) @@ -55,7 +55,7 @@ func TestTickExpiredDepositPeriod(t *testing.T) { } func TestTickMultipleExpiredDepositPeriod(t *testing.T) { - mapp, keeper, _, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, _, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) govHandler := NewHandler(keeper) @@ -64,7 +64,7 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { require.False(t, inactiveQueue.Valid()) inactiveQueue.Close() - newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 5)}) + newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 5)}) res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) @@ -81,7 +81,7 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { require.False(t, inactiveQueue.Valid()) inactiveQueue.Close() - newProposalMsg2 := NewMsgSubmitProposal("Test2", "test2", ProposalTypeText, addrs[1], sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 5)}) + newProposalMsg2 := NewMsgSubmitProposal("Test2", "test2", ProposalTypeText, addrs[1], sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 5)}) res = govHandler(ctx, newProposalMsg2) require.True(t, res.IsOK()) @@ -111,7 +111,7 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { } func TestTickPassedDepositPeriod(t *testing.T) { - mapp, keeper, _, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, _, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) govHandler := NewHandler(keeper) @@ -123,7 +123,7 @@ func TestTickPassedDepositPeriod(t *testing.T) { require.False(t, activeQueue.Valid()) activeQueue.Close() - newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 5)}) + newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 5)}) res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) @@ -142,7 +142,7 @@ func TestTickPassedDepositPeriod(t *testing.T) { require.False(t, inactiveQueue.Valid()) inactiveQueue.Close() - newDepositMsg := NewMsgDeposit(addrs[1], proposalID, sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 5)}) + newDepositMsg := NewMsgDeposit(addrs[1], proposalID, sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 5)}) res = govHandler(ctx, newDepositMsg) require.True(t, res.IsOK()) @@ -152,7 +152,7 @@ func TestTickPassedDepositPeriod(t *testing.T) { } func TestTickPassedVotingPeriod(t *testing.T) { - mapp, keeper, _, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, _, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) SortAddresses(addrs) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) @@ -165,7 +165,7 @@ func TestTickPassedVotingPeriod(t *testing.T) { require.False(t, activeQueue.Valid()) activeQueue.Close() - newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 5)}) + newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 5)}) res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) @@ -176,7 +176,7 @@ func TestTickPassedVotingPeriod(t *testing.T) { newHeader.Time = ctx.BlockHeader().Time.Add(time.Duration(1) * time.Second) ctx = ctx.WithBlockHeader(newHeader) - newDepositMsg := NewMsgDeposit(addrs[1], proposalID, sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 5)}) + newDepositMsg := NewMsgDeposit(addrs[1], proposalID, sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 5)}) res = govHandler(ctx, newDepositMsg) require.True(t, res.IsOK()) diff --git a/x/gov/genesis.go b/x/gov/genesis.go index 7a8fab0b63d6..e06d79b21fea 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -5,7 +5,7 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) // GenesisState - all staking state that must be provided at genesis @@ -45,7 +45,7 @@ func DefaultGenesisState() GenesisState { return GenesisState{ StartingProposalID: 1, DepositParams: DepositParams{ - MinDeposit: sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 10)}, + MinDeposit: sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 10)}, MaxDepositPeriod: time.Duration(172800) * time.Second, }, VotingParams: VotingParams{ @@ -60,6 +60,58 @@ func DefaultGenesisState() GenesisState { } } +// Checks whether 2 GenesisState structs are equivalent. +func (data GenesisState) Equal(data2 GenesisState) bool { + if data.StartingProposalID != data.StartingProposalID || + !data.DepositParams.Equal(data2.DepositParams) || + data.VotingParams != data2.VotingParams || + data.TallyParams != data2.TallyParams { + return false + } + + if len(data.Deposits) != len(data2.Deposits) { + return false + } + for i := range data.Deposits { + deposit1 := data.Deposits[i] + deposit2 := data2.Deposits[i] + if deposit1.ProposalID != deposit2.ProposalID || + !deposit1.Deposit.Equals(deposit2.Deposit) { + return false + } + } + + if len(data.Votes) != len(data2.Votes) { + return false + } + for i := range data.Votes { + vote1 := data.Votes[i] + vote2 := data2.Votes[i] + if vote1.ProposalID != vote2.ProposalID || + !vote1.Vote.Equals(vote2.Vote) { + return false + } + } + + if len(data.Proposals) != len(data2.Proposals) { + return false + } + for i := range data.Proposals { + if data.Proposals[i] != data.Proposals[i] { + return false + } + } + + return true + +} + +// Returns if a GenesisState is empty or has data in it +func (data GenesisState) IsEmpty() bool { + emptyGenState := GenesisState{} + return data.Equal(emptyGenState) +} + // ValidateGenesis TODO https://github.com/cosmos/cosmos-sdk/issues/3007 func ValidateGenesis(data GenesisState) error { threshold := data.TallyParams.Threshold @@ -110,6 +162,12 @@ func InitGenesis(ctx sdk.Context, k Keeper, data GenesisState) { k.setVote(ctx, vote.ProposalID, vote.Vote.Voter, vote.Vote) } for _, proposal := range data.Proposals { + switch proposal.GetStatus() { + case StatusDepositPeriod: + k.InsertInactiveProposalQueue(ctx, proposal.GetDepositEndTime(), proposal.GetProposalID()) + case StatusVotingPeriod: + k.InsertActiveProposalQueue(ctx, proposal.GetVotingEndTime(), proposal.GetProposalID()) + } k.SetProposal(ctx, proposal) } } diff --git a/x/gov/genesis_test.go b/x/gov/genesis_test.go new file mode 100644 index 000000000000..ab3810068520 --- /dev/null +++ b/x/gov/genesis_test.go @@ -0,0 +1,54 @@ +package gov + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/x/mock" + "github.com/stretchr/testify/require" + + abci "github.com/tendermint/tendermint/abci/types" +) + +func TestImportExportQueues(t *testing.T) { + + // Generate mock app and keepers + mapp, keeper, _, addrs, _, _ := getMockApp(t, 2, GenesisState{}, nil) + SortAddresses(addrs) + mapp.BeginBlock(abci.RequestBeginBlock{}) + ctx := mapp.BaseApp.NewContext(false, abci.Header{}) + + // Create two proposals, put the second into the voting period + proposal1 := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) + proposalID1 := proposal1.GetProposalID() + + proposal2 := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) + proposalID2 := proposal2.GetProposalID() + + _, votingStarted := keeper.AddDeposit(ctx, proposalID2, addrs[0], keeper.GetDepositParams(ctx).MinDeposit) + require.True(t, votingStarted) + + require.True(t, keeper.GetProposal(ctx, proposalID1).GetStatus() == StatusDepositPeriod) + require.True(t, keeper.GetProposal(ctx, proposalID2).GetStatus() == StatusVotingPeriod) + + genAccs := mock.GetAllAccounts(mapp.AccountKeeper, ctx) + + // Export the state and import it into a new Mock App + genState := ExportGenesis(ctx, keeper) + mapp2, keeper2, _, _, _, _ := getMockApp(t, 2, genState, genAccs) + + mapp2.BeginBlock(abci.RequestBeginBlock{}) + ctx2 := mapp2.BaseApp.NewContext(false, abci.Header{}) + + // Jump the time forward past the DepositPeriod and VotingPeriod + ctx2 = ctx2.WithBlockTime(ctx2.BlockHeader().Time.Add(keeper2.GetDepositParams(ctx2).MaxDepositPeriod).Add(keeper2.GetVotingParams(ctx2).VotingPeriod)) + + // Make sure that they are still in the DepositPeriod and VotingPeriod respectively + require.True(t, keeper2.GetProposal(ctx2, proposalID1).GetStatus() == StatusDepositPeriod) + require.True(t, keeper2.GetProposal(ctx2, proposalID2).GetStatus() == StatusVotingPeriod) + + // Run the endblocker. Check to make sure that proposal1 is removed from state, and proposal2 is finished VotingPeriod. + EndBlocker(ctx2, keeper2) + + require.Nil(t, keeper2.GetProposal(ctx2, proposalID1)) + require.True(t, keeper2.GetProposal(ctx2, proposalID2).GetStatus() == StatusRejected) +} diff --git a/x/gov/handler.go b/x/gov/handler.go index a39468967289..a5faab122cdf 100644 --- a/x/gov/handler.go +++ b/x/gov/handler.go @@ -136,7 +136,7 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) sdk.Tags { tagValue = tags.ActionProposalRejected } - activeProposal.SetTallyResult(tallyResults) + activeProposal.SetFinalTallyResult(tallyResults) keeper.SetProposal(ctx, activeProposal) keeper.RemoveFromActiveProposalQueue(ctx, activeProposal.GetVotingEndTime(), activeProposal.GetProposalID()) diff --git a/x/gov/keeper.go b/x/gov/keeper.go index abb9e77b2a8e..19fd65734bf1 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -99,14 +99,14 @@ func (keeper Keeper) NewTextProposal(ctx sdk.Context, title string, description return nil } var proposal Proposal = &TextProposal{ - ProposalID: proposalID, - Title: title, - Description: description, - ProposalType: proposalType, - Status: StatusDepositPeriod, - TallyResult: EmptyTallyResult(), - TotalDeposit: sdk.Coins{}, - SubmitTime: ctx.BlockHeader().Time, + ProposalID: proposalID, + Title: title, + Description: description, + ProposalType: proposalType, + Status: StatusDepositPeriod, + FinalTallyResult: EmptyTallyResult(), + TotalDeposit: sdk.Coins{}, + SubmitTime: ctx.BlockHeader().Time, } depositPeriod := keeper.GetDepositParams(ctx).MaxDepositPeriod diff --git a/x/gov/keeper_test.go b/x/gov/keeper_test.go index 83702920e1c8..f4308ef19cc0 100644 --- a/x/gov/keeper_test.go +++ b/x/gov/keeper_test.go @@ -9,11 +9,11 @@ import ( abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) func TestGetSetProposal(t *testing.T) { - mapp, keeper, _, _, _, _ := getMockApp(t, 0) + mapp, keeper, _, _, _, _ := getMockApp(t, 0, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) @@ -26,7 +26,7 @@ func TestGetSetProposal(t *testing.T) { } func TestIncrementProposalNumber(t *testing.T) { - mapp, keeper, _, _, _, _ := getMockApp(t, 0) + mapp, keeper, _, _, _, _ := getMockApp(t, 0, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) @@ -41,7 +41,7 @@ func TestIncrementProposalNumber(t *testing.T) { } func TestActivateVotingPeriod(t *testing.T) { - mapp, keeper, _, _, _, _ := getMockApp(t, 0) + mapp, keeper, _, _, _, _ := getMockApp(t, 0, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) @@ -62,7 +62,7 @@ func TestActivateVotingPeriod(t *testing.T) { } func TestDeposits(t *testing.T) { - mapp, keeper, _, addrs, _, _ := getMockApp(t, 2) + mapp, keeper, _, addrs, _, _ := getMockApp(t, 2, GenesisState{}, nil) SortAddresses(addrs) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) @@ -70,14 +70,14 @@ func TestDeposits(t *testing.T) { proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() - fourSteak := sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 4)} - fiveSteak := sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 5)} + fourSteak := sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 4)} + fiveSteak := sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 5)} addr0Initial := keeper.ck.GetCoins(ctx, addrs[0]) addr1Initial := keeper.ck.GetCoins(ctx, addrs[1]) - // require.True(t, addr0Initial.IsEqual(sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 42)})) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 42)}, addr0Initial) + // require.True(t, addr0Initial.IsEqual(sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 42)})) + require.Equal(t, sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 42)}, addr0Initial) require.True(t, proposal.GetTotalDeposit().IsEqual(sdk.Coins{})) @@ -149,7 +149,7 @@ func TestDeposits(t *testing.T) { } func TestVotes(t *testing.T) { - mapp, keeper, _, addrs, _, _ := getMockApp(t, 2) + mapp, keeper, _, addrs, _, _ := getMockApp(t, 2, GenesisState{}, nil) SortAddresses(addrs) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) @@ -205,7 +205,7 @@ func TestVotes(t *testing.T) { } func TestProposalQueues(t *testing.T) { - mapp, keeper, _, _, _, _ := getMockApp(t, 0) + mapp, keeper, _, _, _, _ := getMockApp(t, 0, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) mapp.InitChainer(ctx, abci.RequestInitChain{}) diff --git a/x/gov/msgs_test.go b/x/gov/msgs_test.go index 36bc10a6a076..83881834f86a 100644 --- a/x/gov/msgs_test.go +++ b/x/gov/msgs_test.go @@ -7,14 +7,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/mock" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( - coinsPos = sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 1000)} + coinsPos = sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 1000)} coinsZero = sdk.Coins{} coinsPosNotAtoms = sdk.Coins{sdk.NewInt64Coin("foo", 10000)} - coinsMulti = sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 1000), sdk.NewInt64Coin("foo", 10000)} + coinsMulti = sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 1000), sdk.NewInt64Coin("foo", 10000)} ) func init() { diff --git a/x/gov/params.go b/x/gov/params.go index 01da184d533a..20cf2f839379 100644 --- a/x/gov/params.go +++ b/x/gov/params.go @@ -12,6 +12,11 @@ type DepositParams struct { MaxDepositPeriod time.Duration `json:"max_deposit_period"` // Maximum period for Atom holders to deposit on a proposal. Initial value: 2 months } +// Checks equality of DepositParams +func (dp DepositParams) Equal(dp2 DepositParams) bool { + return dp.MinDeposit.IsEqual(dp2.MinDeposit) && dp.MaxDepositPeriod == dp2.MaxDepositPeriod +} + // Param around Tallying votes in governance type TallyParams struct { Quorum sdk.Dec `json:"quorum"` // Minimum percentage of total stake needed to vote for a result to be considered valid diff --git a/x/gov/proposals.go b/x/gov/proposals.go index e943fe1169ab..fd50e079dd91 100644 --- a/x/gov/proposals.go +++ b/x/gov/proposals.go @@ -28,8 +28,8 @@ type Proposal interface { GetStatus() ProposalStatus SetStatus(ProposalStatus) - GetTallyResult() TallyResult - SetTallyResult(TallyResult) + GetFinalTallyResult() TallyResult + SetFinalTallyResult(TallyResult) GetSubmitTime() time.Time SetSubmitTime(time.Time) @@ -54,7 +54,7 @@ func ProposalEqual(proposalA Proposal, proposalB Proposal) bool { proposalA.GetDescription() == proposalB.GetDescription() && proposalA.GetProposalType() == proposalB.GetProposalType() && proposalA.GetStatus() == proposalB.GetStatus() && - proposalA.GetTallyResult().Equals(proposalB.GetTallyResult()) && + proposalA.GetFinalTallyResult().Equals(proposalB.GetFinalTallyResult()) && proposalA.GetSubmitTime().Equal(proposalB.GetSubmitTime()) && proposalA.GetDepositEndTime().Equal(proposalB.GetDepositEndTime()) && proposalA.GetTotalDeposit().IsEqual(proposalB.GetTotalDeposit()) && @@ -73,8 +73,8 @@ type TextProposal struct { Description string `json:"description"` // Description of the proposal ProposalType ProposalKind `json:"proposal_type"` // Type of proposal. Initial set {PlainTextProposal, SoftwareUpgradeProposal} - Status ProposalStatus `json:"proposal_status"` // Status of the Proposal {Pending, Active, Passed, Rejected} - TallyResult TallyResult `json:"tally_result"` // Result of Tallys + Status ProposalStatus `json:"proposal_status"` // Status of the Proposal {Pending, Active, Passed, Rejected} + FinalTallyResult TallyResult `json:"final_tally_result"` // Result of Tallys SubmitTime time.Time `json:"submit_time"` // Time of the block where TxGovSubmitProposal was included DepositEndTime time.Time `json:"deposit_end_time"` // Time that the Proposal would expire if deposit amount isn't met @@ -98,11 +98,13 @@ func (tp TextProposal) GetProposalType() ProposalKind { return tp.P func (tp *TextProposal) SetProposalType(proposalType ProposalKind) { tp.ProposalType = proposalType } func (tp TextProposal) GetStatus() ProposalStatus { return tp.Status } func (tp *TextProposal) SetStatus(status ProposalStatus) { tp.Status = status } -func (tp TextProposal) GetTallyResult() TallyResult { return tp.TallyResult } -func (tp *TextProposal) SetTallyResult(tallyResult TallyResult) { tp.TallyResult = tallyResult } -func (tp TextProposal) GetSubmitTime() time.Time { return tp.SubmitTime } -func (tp *TextProposal) SetSubmitTime(submitTime time.Time) { tp.SubmitTime = submitTime } -func (tp TextProposal) GetDepositEndTime() time.Time { return tp.DepositEndTime } +func (tp TextProposal) GetFinalTallyResult() TallyResult { return tp.FinalTallyResult } +func (tp *TextProposal) SetFinalTallyResult(tallyResult TallyResult) { + tp.FinalTallyResult = tallyResult +} +func (tp TextProposal) GetSubmitTime() time.Time { return tp.SubmitTime } +func (tp *TextProposal) SetSubmitTime(submitTime time.Time) { tp.SubmitTime = submitTime } +func (tp TextProposal) GetDepositEndTime() time.Time { return tp.DepositEndTime } func (tp *TextProposal) SetDepositEndTime(depositEndTime time.Time) { tp.DepositEndTime = depositEndTime } diff --git a/x/gov/querier.go b/x/gov/querier.go index 8b985929ed86..bc4eb0d2baa7 100644 --- a/x/gov/querier.go +++ b/x/gov/querier.go @@ -214,7 +214,7 @@ func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Ke if proposal.GetStatus() == StatusDepositPeriod { tallyResult = EmptyTallyResult() } else if proposal.GetStatus() == StatusPassed || proposal.GetStatus() == StatusRejected { - tallyResult = proposal.GetTallyResult() + tallyResult = proposal.GetFinalTallyResult() } else { // proposal is in voting period _, tallyResult = tally(ctx, keeper, proposal) diff --git a/x/gov/querier_test.go b/x/gov/querier_test.go index b64a1b9b270a..25e8220b56a6 100644 --- a/x/gov/querier_test.go +++ b/x/gov/querier_test.go @@ -170,7 +170,7 @@ func getQueriedTally(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sd func testQueryParams(t *testing.T) { cdc := codec.New() - mapp, keeper, _, _, _, _ := getMockApp(t, 1000) + mapp, keeper, _, _, _, _ := getMockApp(t, 1000, GenesisState{}, nil) querier := NewQuerier(keeper) ctx := mapp.NewContext(false, abci.Header{}) @@ -179,7 +179,7 @@ func testQueryParams(t *testing.T) { func testQueries(t *testing.T) { cdc := codec.New() - mapp, keeper, _, addrs, _, _ := getMockApp(t, 1000) + mapp, keeper, _, addrs, _, _ := getMockApp(t, 1000, GenesisState{}, nil) querier := NewQuerier(keeper) handler := NewHandler(keeper) ctx := mapp.NewContext(false, abci.Header{}) diff --git a/x/gov/simulation/msgs.go b/x/gov/simulation/msgs.go index 5319ee7b2c0c..faca7ec8e9e6 100644 --- a/x/gov/simulation/msgs.go +++ b/x/gov/simulation/msgs.go @@ -10,12 +10,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/mock/simulation" - "github.com/cosmos/cosmos-sdk/x/stake" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) const ( - denom = stakeTypes.DefaultBondDenom + denom = stakingTypes.DefaultBondDenom ) // SimulateSubmittingVotingAndSlashingForProposal simulates creating a msg Submit Proposal @@ -23,7 +23,7 @@ const ( // future operations. // TODO: Vote more intelligently, so we can actually do some checks regarding votes passing or failing // TODO: Actually check that validator slashings happened -func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, sk stake.Keeper) simulation.Operation { +func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, sk staking.Keeper) simulation.Operation { handler := gov.NewHandler(k) // The states are: // column 1: All validators vote diff --git a/x/gov/tally_test.go b/x/gov/tally_test.go index fc5cac91082b..77a22996b0ad 100644 --- a/x/gov/tally_test.go +++ b/x/gov/tally_test.go @@ -11,43 +11,43 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( pubkeys = []crypto.PubKey{ed25519.GenPrivKey().PubKey(), ed25519.GenPrivKey().PubKey(), ed25519.GenPrivKey().PubKey()} - testDescription = stake.NewDescription("T", "E", "S", "T") - testCommissionMsg = stake.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) + testDescription = staking.NewDescription("T", "E", "S", "T") + testCommissionMsg = staking.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) ) -func createValidators(t *testing.T, stakeHandler sdk.Handler, ctx sdk.Context, addrs []sdk.ValAddress, coinAmt []int64) { +func createValidators(t *testing.T, stakingHandler sdk.Handler, ctx sdk.Context, addrs []sdk.ValAddress, coinAmt []int64) { require.True(t, len(addrs) <= len(pubkeys), "Not enough pubkeys specified at top of file.") for i := 0; i < len(addrs); i++ { - valCreateMsg := stake.NewMsgCreateValidator( - addrs[i], pubkeys[i], sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, coinAmt[i]), testDescription, testCommissionMsg, + valCreateMsg := staking.NewMsgCreateValidator( + addrs[i], pubkeys[i], sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, coinAmt[i]), testDescription, testCommissionMsg, ) - res := stakeHandler(ctx, valCreateMsg) + res := stakingHandler(ctx, valCreateMsg) require.True(t, res.IsOK()) } } func TestTallyNoOneVotes(t *testing.T) { - mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) valAddrs := make([]sdk.ValAddress, len(addrs[:2])) for i, addr := range addrs[:2] { valAddrs[i] = sdk.ValAddress(addr) } - createValidators(t, stakeHandler, ctx, valAddrs, []int64{5, 5}) - stake.EndBlocker(ctx, sk) + createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 5}) + staking.EndBlocker(ctx, sk) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -61,18 +61,18 @@ func TestTallyNoOneVotes(t *testing.T) { } func TestTallyNoQuorum(t *testing.T) { - mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) valAddrs := make([]sdk.ValAddress, len(addrs[:2])) for i, addr := range addrs[:2] { valAddrs[i] = sdk.ValAddress(addr) } - createValidators(t, stakeHandler, ctx, valAddrs, []int64{2, 5}) - stake.EndBlocker(ctx, sk) + createValidators(t, stakingHandler, ctx, valAddrs, []int64{2, 5}) + staking.EndBlocker(ctx, sk) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -87,18 +87,18 @@ func TestTallyNoQuorum(t *testing.T) { } func TestTallyOnlyValidatorsAllYes(t *testing.T) { - mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) valAddrs := make([]sdk.ValAddress, len(addrs[:2])) for i, addr := range addrs[:2] { valAddrs[i] = sdk.ValAddress(addr) } - createValidators(t, stakeHandler, ctx, valAddrs, []int64{5, 5}) - stake.EndBlocker(ctx, sk) + createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 5}) + staking.EndBlocker(ctx, sk) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -117,18 +117,18 @@ func TestTallyOnlyValidatorsAllYes(t *testing.T) { } func TestTallyOnlyValidators51No(t *testing.T) { - mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) valAddrs := make([]sdk.ValAddress, len(addrs[:2])) for i, addr := range addrs[:2] { valAddrs[i] = sdk.ValAddress(addr) } - createValidators(t, stakeHandler, ctx, valAddrs, []int64{5, 6}) - stake.EndBlocker(ctx, sk) + createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 6}) + staking.EndBlocker(ctx, sk) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -146,18 +146,18 @@ func TestTallyOnlyValidators51No(t *testing.T) { } func TestTallyOnlyValidators51Yes(t *testing.T) { - mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) valAddrs := make([]sdk.ValAddress, len(addrs[:3])) for i, addr := range addrs[:3] { valAddrs[i] = sdk.ValAddress(addr) } - createValidators(t, stakeHandler, ctx, valAddrs, []int64{6, 6, 7}) - stake.EndBlocker(ctx, sk) + createValidators(t, stakingHandler, ctx, valAddrs, []int64{6, 6, 7}) + staking.EndBlocker(ctx, sk) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -178,18 +178,18 @@ func TestTallyOnlyValidators51Yes(t *testing.T) { } func TestTallyOnlyValidatorsVetoed(t *testing.T) { - mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) valAddrs := make([]sdk.ValAddress, len(addrs[:3])) for i, addr := range addrs[:3] { valAddrs[i] = sdk.ValAddress(addr) } - createValidators(t, stakeHandler, ctx, valAddrs, []int64{6, 6, 7}) - stake.EndBlocker(ctx, sk) + createValidators(t, stakingHandler, ctx, valAddrs, []int64{6, 6, 7}) + staking.EndBlocker(ctx, sk) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -210,18 +210,18 @@ func TestTallyOnlyValidatorsVetoed(t *testing.T) { } func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { - mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) valAddrs := make([]sdk.ValAddress, len(addrs[:3])) for i, addr := range addrs[:3] { valAddrs[i] = sdk.ValAddress(addr) } - createValidators(t, stakeHandler, ctx, valAddrs, []int64{6, 6, 7}) - stake.EndBlocker(ctx, sk) + createValidators(t, stakingHandler, ctx, valAddrs, []int64{6, 6, 7}) + staking.EndBlocker(ctx, sk) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -242,18 +242,18 @@ func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { } func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { - mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) valAddrs := make([]sdk.ValAddress, len(addrs[:3])) for i, addr := range addrs[:3] { valAddrs[i] = sdk.ValAddress(addr) } - createValidators(t, stakeHandler, ctx, valAddrs, []int64{6, 6, 7}) - stake.EndBlocker(ctx, sk) + createValidators(t, stakingHandler, ctx, valAddrs, []int64{6, 6, 7}) + staking.EndBlocker(ctx, sk) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -274,18 +274,18 @@ func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { } func TestTallyOnlyValidatorsNonVoter(t *testing.T) { - mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) valAddrs := make([]sdk.ValAddress, len(addrs[:3])) for i, addr := range addrs[:3] { valAddrs[i] = sdk.ValAddress(addr) } - createValidators(t, stakeHandler, ctx, valAddrs, []int64{6, 6, 7}) - stake.EndBlocker(ctx, sk) + createValidators(t, stakingHandler, ctx, valAddrs, []int64{6, 6, 7}) + staking.EndBlocker(ctx, sk) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -304,21 +304,21 @@ func TestTallyOnlyValidatorsNonVoter(t *testing.T) { } func TestTallyDelgatorOverride(t *testing.T) { - mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) valAddrs := make([]sdk.ValAddress, len(addrs[:3])) for i, addr := range addrs[:3] { valAddrs[i] = sdk.ValAddress(addr) } - createValidators(t, stakeHandler, ctx, valAddrs, []int64{5, 6, 7}) - stake.EndBlocker(ctx, sk) + createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 6, 7}) + staking.EndBlocker(ctx, sk) - delegator1Msg := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 30)) - stakeHandler(ctx, delegator1Msg) + delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 30)) + stakingHandler(ctx, delegator1Msg) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -341,21 +341,21 @@ func TestTallyDelgatorOverride(t *testing.T) { } func TestTallyDelgatorInherit(t *testing.T) { - mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) valAddrs := make([]sdk.ValAddress, len(addrs[:3])) for i, addr := range addrs[:3] { valAddrs[i] = sdk.ValAddress(addr) } - createValidators(t, stakeHandler, ctx, valAddrs, []int64{5, 6, 7}) - stake.EndBlocker(ctx, sk) + createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 6, 7}) + staking.EndBlocker(ctx, sk) - delegator1Msg := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 30)) - stakeHandler(ctx, delegator1Msg) + delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 30)) + stakingHandler(ctx, delegator1Msg) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -376,23 +376,23 @@ func TestTallyDelgatorInherit(t *testing.T) { } func TestTallyDelgatorMultipleOverride(t *testing.T) { - mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) valAddrs := make([]sdk.ValAddress, len(addrs[:3])) for i, addr := range addrs[:3] { valAddrs[i] = sdk.ValAddress(addr) } - createValidators(t, stakeHandler, ctx, valAddrs, []int64{5, 6, 7}) - stake.EndBlocker(ctx, sk) + createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 6, 7}) + staking.EndBlocker(ctx, sk) - delegator1Msg := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 10)) - stakeHandler(ctx, delegator1Msg) - delegator1Msg2 := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 10)) - stakeHandler(ctx, delegator1Msg2) + delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 10)) + stakingHandler(ctx, delegator1Msg) + delegator1Msg2 := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 10)) + stakingHandler(ctx, delegator1Msg2) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -415,33 +415,33 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { } func TestTallyDelgatorMultipleInherit(t *testing.T) { - mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) - val1CreateMsg := stake.NewMsgCreateValidator( - sdk.ValAddress(addrs[0]), ed25519.GenPrivKey().PubKey(), sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 25), testDescription, testCommissionMsg, + val1CreateMsg := staking.NewMsgCreateValidator( + sdk.ValAddress(addrs[0]), ed25519.GenPrivKey().PubKey(), sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 25), testDescription, testCommissionMsg, ) - stakeHandler(ctx, val1CreateMsg) + stakingHandler(ctx, val1CreateMsg) - val2CreateMsg := stake.NewMsgCreateValidator( - sdk.ValAddress(addrs[1]), ed25519.GenPrivKey().PubKey(), sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 6), testDescription, testCommissionMsg, + val2CreateMsg := staking.NewMsgCreateValidator( + sdk.ValAddress(addrs[1]), ed25519.GenPrivKey().PubKey(), sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 6), testDescription, testCommissionMsg, ) - stakeHandler(ctx, val2CreateMsg) + stakingHandler(ctx, val2CreateMsg) - val3CreateMsg := stake.NewMsgCreateValidator( - sdk.ValAddress(addrs[2]), ed25519.GenPrivKey().PubKey(), sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 7), testDescription, testCommissionMsg, + val3CreateMsg := staking.NewMsgCreateValidator( + sdk.ValAddress(addrs[2]), ed25519.GenPrivKey().PubKey(), sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 7), testDescription, testCommissionMsg, ) - stakeHandler(ctx, val3CreateMsg) + stakingHandler(ctx, val3CreateMsg) - delegator1Msg := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 10)) - stakeHandler(ctx, delegator1Msg) + delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 10)) + stakingHandler(ctx, delegator1Msg) - delegator1Msg2 := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 10)) - stakeHandler(ctx, delegator1Msg2) + delegator1Msg2 := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 10)) + stakingHandler(ctx, delegator1Msg2) - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -462,30 +462,30 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { } func TestTallyJailedValidator(t *testing.T) { - mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10, GenesisState{}, nil) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - stakeHandler := stake.NewHandler(sk) + stakingHandler := staking.NewHandler(sk) valAddrs := make([]sdk.ValAddress, len(addrs[:3])) for i, addr := range addrs[:3] { valAddrs[i] = sdk.ValAddress(addr) } - createValidators(t, stakeHandler, ctx, valAddrs, []int64{25, 6, 7}) - stake.EndBlocker(ctx, sk) + createValidators(t, stakingHandler, ctx, valAddrs, []int64{25, 6, 7}) + staking.EndBlocker(ctx, sk) - delegator1Msg := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 10)) - stakeHandler(ctx, delegator1Msg) + delegator1Msg := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[2]), sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 10)) + stakingHandler(ctx, delegator1Msg) - delegator1Msg2 := stake.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 10)) - stakeHandler(ctx, delegator1Msg2) + delegator1Msg2 := staking.NewMsgDelegate(addrs[3], sdk.ValAddress(addrs[1]), sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 10)) + stakingHandler(ctx, delegator1Msg2) val2, found := sk.GetValidator(ctx, sdk.ValAddress(addrs[1])) require.True(t, found) sk.Jail(ctx, sdk.ConsAddress(val2.ConsPubKey.Address())) - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() diff --git a/x/gov/test_common.go b/x/gov/test_common.go index ce326aa6b094..4c6c2607d034 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -12,44 +12,47 @@ import ( "github.com/tendermint/tendermint/crypto" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/mock" - "github.com/cosmos/cosmos-sdk/x/stake" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) // initialize the mock application for this module -func getMockApp(t *testing.T, numGenAccs int) (*mock.App, Keeper, stake.Keeper, []sdk.AccAddress, []crypto.PubKey, []crypto.PrivKey) { - mapp := mock.NewApp() +func getMockApp(t *testing.T, numGenAccs int, genState GenesisState, genAccs []auth.Account) (mapp *mock.App, keeper Keeper, sk staking.Keeper, addrs []sdk.AccAddress, pubKeys []crypto.PubKey, privKeys []crypto.PrivKey) { + mapp = mock.NewApp() - stake.RegisterCodec(mapp.Cdc) + staking.RegisterCodec(mapp.Cdc) RegisterCodec(mapp.Cdc) - keyStake := sdk.NewKVStoreKey(stake.StoreKey) - tkeyStake := sdk.NewTransientStoreKey(stake.TStoreKey) + keyStaking := sdk.NewKVStoreKey(staking.StoreKey) + tkeyStaking := sdk.NewTransientStoreKey(staking.TStoreKey) keyGov := sdk.NewKVStoreKey(StoreKey) pk := mapp.ParamsKeeper ck := bank.NewBaseKeeper(mapp.AccountKeeper) - sk := stake.NewKeeper(mapp.Cdc, keyStake, tkeyStake, ck, pk.Subspace(stake.DefaultParamspace), stake.DefaultCodespace) - keeper := NewKeeper(mapp.Cdc, keyGov, pk, pk.Subspace("testgov"), ck, sk, DefaultCodespace) + sk = staking.NewKeeper(mapp.Cdc, keyStaking, tkeyStaking, ck, pk.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) + keeper = NewKeeper(mapp.Cdc, keyGov, pk, pk.Subspace("testgov"), ck, sk, DefaultCodespace) mapp.Router().AddRoute(RouterKey, NewHandler(keeper)) mapp.QueryRouter().AddRoute(QuerierRoute, NewQuerier(keeper)) mapp.SetEndBlocker(getEndBlocker(keeper)) - mapp.SetInitChainer(getInitChainer(mapp, keeper, sk)) + mapp.SetInitChainer(getInitChainer(mapp, keeper, sk, genState)) - require.NoError(t, mapp.CompleteSetup(keyStake, tkeyStake, keyGov)) + require.NoError(t, mapp.CompleteSetup(keyStaking, tkeyStaking, keyGov)) - genAccs, addrs, pubKeys, privKeys := mock.CreateGenAccounts(numGenAccs, sdk.Coins{sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 42)}) + if genAccs == nil || len(genAccs) == 0 { + genAccs, addrs, pubKeys, privKeys = mock.CreateGenAccounts(numGenAccs, sdk.Coins{sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 42)}) + } mock.SetGenesis(mapp, genAccs) return mapp, keeper, sk, addrs, pubKeys, privKeys } -// gov and stake endblocker +// gov and staking endblocker func getEndBlocker(keeper Keeper) sdk.EndBlocker { return func(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { tags := EndBlocker(ctx, keeper) @@ -59,19 +62,23 @@ func getEndBlocker(keeper Keeper) sdk.EndBlocker { } } -// gov and stake initchainer -func getInitChainer(mapp *mock.App, keeper Keeper, stakeKeeper stake.Keeper) sdk.InitChainer { +// gov and staking initchainer +func getInitChainer(mapp *mock.App, keeper Keeper, stakingKeeper staking.Keeper, genState GenesisState) sdk.InitChainer { return func(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { mapp.InitChainer(ctx, req) - stakeGenesis := stake.DefaultGenesisState() - stakeGenesis.Pool.LooseTokens = sdk.NewInt(100000) + stakingGenesis := staking.DefaultGenesisState() + stakingGenesis.Pool.LooseTokens = sdk.NewInt(100000) - validators, err := stake.InitGenesis(ctx, stakeKeeper, stakeGenesis) + validators, err := staking.InitGenesis(ctx, stakingKeeper, stakingGenesis) if err != nil { panic(err) } - InitGenesis(ctx, keeper, DefaultGenesisState()) + if genState.IsEmpty() { + InitGenesis(ctx, keeper, DefaultGenesisState()) + } else { + InitGenesis(ctx, keeper, genState) + } return abci.ResponseInitChain{ Validators: validators, } diff --git a/x/mint/expected_keepers.go b/x/mint/expected_keepers.go index 995f9aafe588..72bc36a5f5cd 100644 --- a/x/mint/expected_keepers.go +++ b/x/mint/expected_keepers.go @@ -4,8 +4,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// expected stake keeper -type StakeKeeper interface { +// expected staking keeper +type StakingKeeper interface { TotalPower(ctx sdk.Context) sdk.Int BondedRatio(ctx sdk.Context) sdk.Dec InflateSupply(ctx sdk.Context, newTokens sdk.Int) diff --git a/x/mint/keeper.go b/x/mint/keeper.go index 34e0826f6a1d..1a508dc2933b 100644 --- a/x/mint/keeper.go +++ b/x/mint/keeper.go @@ -6,17 +6,17 @@ import ( "github.com/cosmos/cosmos-sdk/x/params" ) -// keeper of the stake store +// keeper of the staking store type Keeper struct { storeKey sdk.StoreKey cdc *codec.Codec paramSpace params.Subspace - sk StakeKeeper + sk StakingKeeper fck FeeCollectionKeeper } func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, - paramSpace params.Subspace, sk StakeKeeper, fck FeeCollectionKeeper) Keeper { + paramSpace params.Subspace, sk StakingKeeper, fck FeeCollectionKeeper) Keeper { keeper := Keeper{ storeKey: key, @@ -38,7 +38,7 @@ var ( ParamStoreKeyParams = []byte("params") ) -// ParamTable for stake module +// ParamTable for staking module func ParamTypeTable() params.TypeTable { return params.NewTypeTable( ParamStoreKeyParams, Params{}, diff --git a/x/mint/params.go b/x/mint/params.go index e1acd3a63014..45a66f7fc1de 100644 --- a/x/mint/params.go +++ b/x/mint/params.go @@ -3,7 +3,7 @@ package mint import ( "fmt" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -34,7 +34,7 @@ func NewParams(mintDenom string, inflationRateChange, inflationMax, // default minting module parameters func DefaultParams() Params { return Params{ - MintDenom: stakeTypes.DefaultBondDenom, + MintDenom: stakingTypes.DefaultBondDenom, InflationRateChange: sdk.NewDecWithPrec(13, 2), InflationMax: sdk.NewDecWithPrec(20, 2), InflationMin: sdk.NewDecWithPrec(7, 2), diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index d5761758189b..b198aaa24804 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -11,8 +11,8 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/mock" - "github.com/cosmos/cosmos-sdk/x/stake" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( @@ -22,32 +22,32 @@ var ( ) // initialize the mock application for this module -func getMockApp(t *testing.T) (*mock.App, stake.Keeper, Keeper) { +func getMockApp(t *testing.T) (*mock.App, staking.Keeper, Keeper) { mapp := mock.NewApp() RegisterCodec(mapp.Cdc) - keyStake := sdk.NewKVStoreKey(stake.StoreKey) - tkeyStake := sdk.NewTransientStoreKey(stake.TStoreKey) + keyStaking := sdk.NewKVStoreKey(staking.StoreKey) + tkeyStaking := sdk.NewTransientStoreKey(staking.TStoreKey) keySlashing := sdk.NewKVStoreKey(StoreKey) bankKeeper := bank.NewBaseKeeper(mapp.AccountKeeper) - stakeKeeper := stake.NewKeeper(mapp.Cdc, keyStake, tkeyStake, bankKeeper, mapp.ParamsKeeper.Subspace(stake.DefaultParamspace), stake.DefaultCodespace) - keeper := NewKeeper(mapp.Cdc, keySlashing, stakeKeeper, mapp.ParamsKeeper.Subspace(DefaultParamspace), DefaultCodespace) - mapp.Router().AddRoute(stake.RouterKey, stake.NewHandler(stakeKeeper)) + stakingKeeper := staking.NewKeeper(mapp.Cdc, keyStaking, tkeyStaking, bankKeeper, mapp.ParamsKeeper.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) + keeper := NewKeeper(mapp.Cdc, keySlashing, stakingKeeper, mapp.ParamsKeeper.Subspace(DefaultParamspace), DefaultCodespace) + mapp.Router().AddRoute(staking.RouterKey, staking.NewHandler(stakingKeeper)) mapp.Router().AddRoute(RouterKey, NewHandler(keeper)) - mapp.SetEndBlocker(getEndBlocker(stakeKeeper)) - mapp.SetInitChainer(getInitChainer(mapp, stakeKeeper)) + mapp.SetEndBlocker(getEndBlocker(stakingKeeper)) + mapp.SetInitChainer(getInitChainer(mapp, stakingKeeper)) - require.NoError(t, mapp.CompleteSetup(keyStake, tkeyStake, keySlashing)) + require.NoError(t, mapp.CompleteSetup(keyStaking, tkeyStaking, keySlashing)) - return mapp, stakeKeeper, keeper + return mapp, stakingKeeper, keeper } -// stake endblocker -func getEndBlocker(keeper stake.Keeper) sdk.EndBlocker { +// staking endblocker +func getEndBlocker(keeper staking.Keeper) sdk.EndBlocker { return func(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - validatorUpdates, tags := stake.EndBlocker(ctx, keeper) + validatorUpdates, tags := staking.EndBlocker(ctx, keeper) return abci.ResponseEndBlock{ ValidatorUpdates: validatorUpdates, Tags: tags, @@ -56,12 +56,12 @@ func getEndBlocker(keeper stake.Keeper) sdk.EndBlocker { } // overwrite the mock init chainer -func getInitChainer(mapp *mock.App, keeper stake.Keeper) sdk.InitChainer { +func getInitChainer(mapp *mock.App, keeper staking.Keeper) sdk.InitChainer { return func(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { mapp.InitChainer(ctx, req) - stakeGenesis := stake.DefaultGenesisState() - stakeGenesis.Pool.LooseTokens = sdk.NewInt(100000) - validators, err := stake.InitGenesis(ctx, keeper, stakeGenesis) + stakingGenesis := staking.DefaultGenesisState() + stakingGenesis.Pool.LooseTokens = sdk.NewInt(100000) + validators, err := staking.InitGenesis(ctx, keeper, stakingGenesis) if err != nil { panic(err) } @@ -72,8 +72,8 @@ func getInitChainer(mapp *mock.App, keeper stake.Keeper) sdk.InitChainer { } } -func checkValidator(t *testing.T, mapp *mock.App, keeper stake.Keeper, - addr sdk.AccAddress, expFound bool) stake.Validator { +func checkValidator(t *testing.T, mapp *mock.App, keeper staking.Keeper, + addr sdk.AccAddress, expFound bool) staking.Validator { ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) validator, found := keeper.GetValidator(ctxCheck, sdk.ValAddress(addr1)) require.Equal(t, expFound, found) @@ -89,10 +89,10 @@ func checkValidatorSigningInfo(t *testing.T, mapp *mock.App, keeper Keeper, } func TestSlashingMsgs(t *testing.T) { - mapp, stakeKeeper, keeper := getMockApp(t) + mapp, stakingKeeper, keeper := getMockApp(t) - genCoin := sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 42) - bondCoin := sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 10) + genCoin := sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 42) + bondCoin := sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 10) acc1 := &auth.BaseAccount{ Address: addr1, @@ -101,17 +101,17 @@ func TestSlashingMsgs(t *testing.T) { accs := []auth.Account{acc1} mock.SetGenesis(mapp, accs) - description := stake.NewDescription("foo_moniker", "", "", "") - commission := stake.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) + description := staking.NewDescription("foo_moniker", "", "", "") + commission := staking.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) - createValidatorMsg := stake.NewMsgCreateValidator( + createValidatorMsg := staking.NewMsgCreateValidator( sdk.ValAddress(addr1), priv1.PubKey(), bondCoin, description, commission, ) mock.SignCheckDeliver(t, mapp.BaseApp, []sdk.Msg{createValidatorMsg}, []uint64{0}, []uint64{0}, true, true, priv1) mock.CheckBalance(t, mapp, addr1, sdk.Coins{genCoin.Minus(bondCoin)}) mapp.BeginBlock(abci.RequestBeginBlock{}) - validator := checkValidator(t, mapp, stakeKeeper, addr1, true) + validator := checkValidator(t, mapp, stakingKeeper, addr1, true) require.Equal(t, sdk.ValAddress(addr1), validator.OperatorAddr) require.Equal(t, sdk.Bonded, validator.Status) require.True(sdk.IntEq(t, sdk.NewInt(10), validator.BondedTokens())) diff --git a/x/slashing/genesis.go b/x/slashing/genesis.go index aa126f56a5dd..c3672c3d698b 100644 --- a/x/slashing/genesis.go +++ b/x/slashing/genesis.go @@ -5,15 +5,14 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // GenesisState - all slashing state that must be provided at genesis type GenesisState struct { - Params Params `json:"params"` - SigningInfos map[string]ValidatorSigningInfo `json:"signing_infos"` - MissedBlocks map[string][]MissedBlock `json:"missed_blocks"` - SlashingPeriods []ValidatorSlashingPeriod `json:"slashing_periods"` + Params Params `json:"params"` + SigningInfos map[string]ValidatorSigningInfo `json:"signing_infos"` + MissedBlocks map[string][]MissedBlock `json:"missed_blocks"` } // MissedBlock @@ -25,10 +24,9 @@ type MissedBlock struct { // HubDefaultGenesisState - default GenesisState used by Cosmos Hub func DefaultGenesisState() GenesisState { return GenesisState{ - Params: DefaultParams(), - SigningInfos: make(map[string]ValidatorSigningInfo), - MissedBlocks: make(map[string][]MissedBlock), - SlashingPeriods: []ValidatorSlashingPeriod{}, + Params: DefaultParams(), + SigningInfos: make(map[string]ValidatorSigningInfo), + MissedBlocks: make(map[string][]MissedBlock), } } @@ -54,14 +52,9 @@ func ValidateGenesis(data GenesisState) error { return fmt.Errorf("Max evidence age must be at least 1 minute, is %s", maxEvidence.String()) } - dblSignUnbond := data.Params.DoubleSignUnbondDuration - if dblSignUnbond < 1*time.Minute { - return fmt.Errorf("Double sign unblond duration must be at least 1 minute, is %s", dblSignUnbond.String()) - } - - downtimeUnbond := data.Params.DowntimeUnbondDuration - if downtimeUnbond < 1*time.Minute { - return fmt.Errorf("Downtime unblond duration must be at least 1 minute, is %s", downtimeUnbond.String()) + downtimeJail := data.Params.DowntimeJailDuration + if downtimeJail < 1*time.Minute { + return fmt.Errorf("Downtime unblond duration must be at least 1 minute, is %s", downtimeJail.String()) } signedWindow := data.Params.SignedBlocksWindow @@ -97,10 +90,6 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState, sdata types. } } - for _, slashingPeriod := range data.SlashingPeriods { - keeper.SetValidatorSlashingPeriod(ctx, slashingPeriod) - } - keeper.paramspace.SetParamSet(ctx, &data.Params) } @@ -127,16 +116,9 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) (data GenesisState) { return false }) - slashingPeriods := []ValidatorSlashingPeriod{} - keeper.IterateValidatorSlashingPeriods(ctx, func(slashingPeriod ValidatorSlashingPeriod) (stop bool) { - slashingPeriods = append(slashingPeriods, slashingPeriod) - return false - }) - return GenesisState{ - Params: params, - SigningInfos: signingInfos, - MissedBlocks: missedBlocks, - SlashingPeriods: slashingPeriods, + Params: params, + SigningInfos: signingInfos, + MissedBlocks: missedBlocks, } } diff --git a/x/slashing/handler.go b/x/slashing/handler.go index e55dfa0a82c8..2bed8db9423d 100644 --- a/x/slashing/handler.go +++ b/x/slashing/handler.go @@ -42,6 +42,10 @@ func handleMsgUnjail(ctx sdk.Context, msg MsgUnjail, k Keeper) sdk.Result { return ErrNoValidatorForAddress(k.codespace).Result() } + if info.Tombstoned { + return ErrValidatorJailed(k.codespace).Result() + } + // cannot be unjailed until out of jail if ctx.BlockHeader().Time.Before(info.JailedUntil) { return ErrValidatorJailed(k.codespace).Result() diff --git a/x/slashing/handler_test.go b/x/slashing/handler_test.go index b7a0e42ad061..516d1b2b99ae 100644 --- a/x/slashing/handler_test.go +++ b/x/slashing/handler_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" ) func TestCannotUnjailUnlessJailed(t *testing.T) { @@ -17,9 +17,9 @@ func TestCannotUnjailUnlessJailed(t *testing.T) { amtInt := int64(100) addr, val, amt := addrs[0], pks[0], sdk.NewInt(amtInt) msg := NewTestMsgCreateValidator(addr, val, amt) - got := stake.NewHandler(sk)(ctx, msg) + got := staking.NewHandler(sk)(ctx, msg) require.True(t, got.IsOK()) - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) require.Equal( t, ck.GetCoins(ctx, sdk.AccAddress(addr)), @@ -35,11 +35,11 @@ func TestCannotUnjailUnlessJailed(t *testing.T) { } func TestJailedValidatorDelegations(t *testing.T) { - ctx, _, stakeKeeper, _, slashingKeeper := createTestInput(t, DefaultParams()) + ctx, _, stakingKeeper, _, slashingKeeper := createTestInput(t, DefaultParams()) - stakeParams := stakeKeeper.GetParams(ctx) - stakeParams.UnbondingTime = 0 - stakeKeeper.SetParams(ctx, stakeParams) + stakingParams := stakingKeeper.GetParams(ctx) + stakingParams.UnbondingTime = 0 + stakingKeeper.SetParams(ctx, stakingParams) // create a validator amount := int64(10) @@ -47,11 +47,11 @@ func TestJailedValidatorDelegations(t *testing.T) { valAddr, consAddr := addrs[1], sdk.ConsAddress(addrs[0]) msgCreateVal := NewTestMsgCreateValidator(valAddr, valPubKey, bondAmount) - got := stake.NewHandler(stakeKeeper)(ctx, msgCreateVal) + got := staking.NewHandler(stakingKeeper)(ctx, msgCreateVal) require.True(t, got.IsOK(), "expected create validator msg to be ok, got: %v", got) // end block - stake.EndBlocker(ctx, stakeKeeper) + staking.EndBlocker(ctx, stakingKeeper) // set dummy signing info newInfo := ValidatorSigningInfo{ @@ -65,21 +65,21 @@ func TestJailedValidatorDelegations(t *testing.T) { // delegate tokens to the validator delAddr := sdk.AccAddress(addrs[2]) msgDelegate := newTestMsgDelegate(delAddr, valAddr, bondAmount) - got = stake.NewHandler(stakeKeeper)(ctx, msgDelegate) + got = staking.NewHandler(stakingKeeper)(ctx, msgDelegate) require.True(t, got.IsOK(), "expected delegation to be ok, got %v", got) unbondShares := sdk.NewDec(10) // unbond validator total self-delegations (which should jail the validator) - msgBeginUnbonding := stake.NewMsgBeginUnbonding(sdk.AccAddress(valAddr), valAddr, unbondShares) - got = stake.NewHandler(stakeKeeper)(ctx, msgBeginUnbonding) + msgBeginUnbonding := staking.NewMsgBeginUnbonding(sdk.AccAddress(valAddr), valAddr, unbondShares) + got = staking.NewHandler(stakingKeeper)(ctx, msgBeginUnbonding) require.True(t, got.IsOK(), "expected begin unbonding validator msg to be ok, got: %v", got) - err := stakeKeeper.CompleteUnbonding(ctx, sdk.AccAddress(valAddr), valAddr) + err := stakingKeeper.CompleteUnbonding(ctx, sdk.AccAddress(valAddr), valAddr) require.Nil(t, err, "expected complete unbonding validator to be ok, got: %v", err) // verify validator still exists and is jailed - validator, found := stakeKeeper.GetValidator(ctx, valAddr) + validator, found := stakingKeeper.GetValidator(ctx, valAddr) require.True(t, found) require.True(t, validator.GetJailed()) @@ -89,7 +89,7 @@ func TestJailedValidatorDelegations(t *testing.T) { // self-delegate to validator msgSelfDelegate := newTestMsgDelegate(sdk.AccAddress(valAddr), valAddr, bondAmount) - got = stake.NewHandler(stakeKeeper)(ctx, msgSelfDelegate) + got = staking.NewHandler(stakingKeeper)(ctx, msgSelfDelegate) require.True(t, got.IsOK(), "expected delegation to not be ok, got %v", got) // verify the validator can now unjail itself diff --git a/x/slashing/hooks.go b/x/slashing/hooks.go index 26770da49ace..8f90a5addd83 100644 --- a/x/slashing/hooks.go +++ b/x/slashing/hooks.go @@ -1,3 +1,4 @@ +// nolint package slashing import ( @@ -8,7 +9,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -func (k Keeper) onValidatorBonded(ctx sdk.Context, address sdk.ConsAddress, _ sdk.ValAddress) { +func (k Keeper) AfterValidatorBonded(ctx sdk.Context, address sdk.ConsAddress, _ sdk.ValAddress) { // Update the signing info start height or create a new signing info _, found := k.getValidatorSigningInfo(ctx, address) if !found { @@ -16,36 +17,21 @@ func (k Keeper) onValidatorBonded(ctx sdk.Context, address sdk.ConsAddress, _ sd StartHeight: ctx.BlockHeight(), IndexOffset: 0, JailedUntil: time.Unix(0, 0), + Tombstoned: false, MissedBlocksCounter: 0, } k.SetValidatorSigningInfo(ctx, address, signingInfo) } - - // Create a new slashing period when a validator is bonded - slashingPeriod := ValidatorSlashingPeriod{ - ValidatorAddr: address, - StartHeight: ctx.BlockHeight(), - EndHeight: 0, - SlashedSoFar: sdk.ZeroDec(), - } - k.SetValidatorSlashingPeriod(ctx, slashingPeriod) -} - -// Mark the slashing period as having ended when a validator begins unbonding -func (k Keeper) onValidatorBeginUnbonding(ctx sdk.Context, address sdk.ConsAddress, _ sdk.ValAddress) { - slashingPeriod := k.getValidatorSlashingPeriodForHeight(ctx, address, ctx.BlockHeight()) - slashingPeriod.EndHeight = ctx.BlockHeight() - k.SetValidatorSlashingPeriod(ctx, slashingPeriod) } // When a validator is created, add the address-pubkey relation. -func (k Keeper) onValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { +func (k Keeper) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { validator := k.validatorSet.Validator(ctx, valAddr) k.addPubkey(ctx, validator.GetConsPubKey()) } // When a validator is removed, delete the address-pubkey relation. -func (k Keeper) onValidatorRemoved(ctx sdk.Context, address sdk.ConsAddress) { +func (k Keeper) AfterValidatorRemoved(ctx sdk.Context, address sdk.ConsAddress) { k.deleteAddrPubkeyRelation(ctx, crypto.Address(address)) } @@ -64,29 +50,24 @@ func (k Keeper) Hooks() Hooks { } // Implements sdk.ValidatorHooks -func (h Hooks) OnValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - h.k.onValidatorBonded(ctx, consAddr, valAddr) +func (h Hooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.k.AfterValidatorBonded(ctx, consAddr, valAddr) } // Implements sdk.ValidatorHooks -func (h Hooks) OnValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - h.k.onValidatorBeginUnbonding(ctx, consAddr, valAddr) +func (h Hooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, _ sdk.ValAddress) { + h.k.AfterValidatorRemoved(ctx, consAddr) } // Implements sdk.ValidatorHooks -func (h Hooks) OnValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, _ sdk.ValAddress) { - h.k.onValidatorRemoved(ctx, consAddr) -} - -// Implements sdk.ValidatorHooks -func (h Hooks) OnValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { - h.k.onValidatorCreated(ctx, valAddr) +func (h Hooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { + h.k.AfterValidatorCreated(ctx, valAddr) } // nolint - unused hooks -func (h Hooks) OnValidatorPowerDidChange(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { -} -func (h Hooks) OnValidatorModified(_ sdk.Context, _ sdk.ValAddress) {} -func (h Hooks) OnDelegationCreated(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) {} -func (h Hooks) OnDelegationSharesModified(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) {} -func (h Hooks) OnDelegationRemoved(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) {} +func (h Hooks) AfterValidatorBeginUnbonding(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) {} +func (h Hooks) AfterValidatorPowerDidChange(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) {} +func (h Hooks) BeforeValidatorModified(_ sdk.Context, _ sdk.ValAddress) {} +func (h Hooks) BeforeDelegationCreated(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) {} +func (h Hooks) BeforeDelegationSharesModified(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) {} +func (h Hooks) BeforeDelegationRemoved(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) {} diff --git a/x/slashing/hooks_test.go b/x/slashing/hooks_test.go deleted file mode 100644 index eb7406764744..000000000000 --- a/x/slashing/hooks_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package slashing - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestHookOnValidatorBonded(t *testing.T) { - ctx, _, _, _, keeper := createTestInput(t, DefaultParams()) - addr := sdk.ConsAddress(addrs[0]) - keeper.onValidatorBonded(ctx, addr, nil) - period := keeper.getValidatorSlashingPeriodForHeight(ctx, addr, ctx.BlockHeight()) - require.Equal(t, ValidatorSlashingPeriod{addr, ctx.BlockHeight(), 0, sdk.ZeroDec()}, period) -} - -func TestHookOnValidatorBeginUnbonding(t *testing.T) { - ctx, _, _, _, keeper := createTestInput(t, DefaultParams()) - addr := sdk.ConsAddress(addrs[0]) - keeper.onValidatorBonded(ctx, addr, nil) - keeper.onValidatorBeginUnbonding(ctx, addr, addrs[0]) - period := keeper.getValidatorSlashingPeriodForHeight(ctx, addr, ctx.BlockHeight()) - require.Equal(t, ValidatorSlashingPeriod{addr, ctx.BlockHeight(), ctx.BlockHeight(), sdk.ZeroDec()}, period) -} diff --git a/x/slashing/keeper.go b/x/slashing/keeper.go index 5137b11981c5..f8494a8877b1 100644 --- a/x/slashing/keeper.go +++ b/x/slashing/keeper.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/params" - stake "github.com/cosmos/cosmos-sdk/x/stake/types" + staking "github.com/cosmos/cosmos-sdk/x/staking/types" ) // Keeper of the slashing store @@ -47,7 +47,13 @@ func (k Keeper) handleDoubleSign(ctx sdk.Context, addr crypto.Address, infractio panic(fmt.Sprintf("Validator consensus-address %v not found", consAddr)) } - // Get validator. + // Reject evidence if the double is too old + if age > k.MaxEvidenceAge(ctx) { + logger.Info(fmt.Sprintf("Ignored double sign from %s at height %d, age of %d past max age of %d", pubkey.Address(), infractionHeight, age, k.MaxEvidenceAge(ctx))) + return + } + + // Get validator and signing info validator := k.validatorSet.ValidatorByConsAddr(ctx, consAddr) if validator == nil || validator.GetStatus() == sdk.Unbonded { // Defensive. @@ -55,48 +61,49 @@ func (k Keeper) handleDoubleSign(ctx sdk.Context, addr crypto.Address, infractio // Tendermint might break this assumption at some point. return } + signInfo, found := k.getValidatorSigningInfo(ctx, consAddr) + if !found { + panic(fmt.Sprintf("Expected signing info for validator %s but not found", consAddr)) + } - // Double sign too old - maxEvidenceAge := k.MaxEvidenceAge(ctx) - if age > maxEvidenceAge { - logger.Info(fmt.Sprintf("Ignored double sign from %s at height %d, age of %d past max age of %d", pubkey.Address(), infractionHeight, age, maxEvidenceAge)) + // Validator is already tombstoned + if signInfo.Tombstoned { + logger.Info(fmt.Sprintf("Ignored double sign from %s at height %d, validator already tombstoned", pubkey.Address(), infractionHeight)) return } // Double sign confirmed - logger.Info(fmt.Sprintf("Confirmed double sign from %s at height %d, age of %d less than max age of %d", pubkey.Address(), infractionHeight, age, maxEvidenceAge)) + logger.Info(fmt.Sprintf("Confirmed double sign from %s at height %d, age of %d", pubkey.Address(), infractionHeight, age)) // We need to retrieve the stake distribution which signed the block, so we subtract ValidatorUpdateDelay from the evidence height. // Note that this *can* result in a negative "distributionHeight", up to -ValidatorUpdateDelay, // i.e. at the end of the pre-genesis block (none) = at the beginning of the genesis block. // That's fine since this is just used to filter unbonding delegations & redelegations. - distributionHeight := infractionHeight - stake.ValidatorUpdateDelay + distributionHeight := infractionHeight - staking.ValidatorUpdateDelay - // Cap the amount slashed to the penalty for the worst infraction - // within the slashing period when this infraction was committed + // get the percentage slash penalty fraction fraction := k.SlashFractionDoubleSign(ctx) - revisedFraction := k.capBySlashingPeriod(ctx, consAddr, fraction, distributionHeight) - logger.Info(fmt.Sprintf("Fraction slashed capped by slashing period from %v to %v", fraction, revisedFraction)) // Slash validator // `power` is the int64 power of the validator as provided to/by // Tendermint. This value is validator.Tokens as sent to Tendermint via // ABCI, and now received as evidence. - // The revisedFraction (which is the new fraction to be slashed) is passed - // in separately to separately slash unbonding and rebonding delegations. - k.validatorSet.Slash(ctx, consAddr, distributionHeight, power, revisedFraction) + // The fraction is passed in to separately to slash unbonding and rebonding delegations. + k.validatorSet.Slash(ctx, consAddr, distributionHeight, power, fraction) // Jail validator if not already jailed + // begin unbonding validator if not already unbonding (tombstone) if !validator.GetJailed() { k.validatorSet.Jail(ctx, consAddr) } - // Set or updated validator jail duration - signInfo, found := k.getValidatorSigningInfo(ctx, consAddr) - if !found { - panic(fmt.Sprintf("Expected signing info for validator %s but not found", consAddr)) - } - signInfo.JailedUntil = time.Add(k.DoubleSignUnbondDuration(ctx)) + // Set slashed so far to total slash + signInfo.Tombstoned = true + + // Set jailed until to be forever (max time) + signInfo.JailedUntil = DoubleSignJailEndTime + + // Set validator signing info k.SetValidatorSigningInfo(ctx, consAddr, signInfo) } @@ -153,10 +160,10 @@ func (k Keeper) handleValidatorSignature(ctx sdk.Context, addr crypto.Address, p // Note that this *can* result in a negative "distributionHeight" up to -ValidatorUpdateDelay-1, // i.e. at the end of the pre-genesis block (none) = at the beginning of the genesis block. // That's fine since this is just used to filter unbonding delegations & redelegations. - distributionHeight := height - stake.ValidatorUpdateDelay - 1 + distributionHeight := height - staking.ValidatorUpdateDelay - 1 k.validatorSet.Slash(ctx, consAddr, distributionHeight, power, k.SlashFractionDowntime(ctx)) k.validatorSet.Jail(ctx, consAddr) - signInfo.JailedUntil = ctx.BlockHeader().Time.Add(k.DowntimeUnbondDuration(ctx)) + signInfo.JailedUntil = ctx.BlockHeader().Time.Add(k.DowntimeJailDuration(ctx)) // We need to reset the counter & array so that the validator won't be immediately slashed for downtime upon rebonding. signInfo.MissedBlocksCounter = 0 signInfo.IndexOffset = 0 diff --git a/x/slashing/keeper_test.go b/x/slashing/keeper_test.go index e15215bf837b..9c9e7a28e967 100644 --- a/x/slashing/keeper_test.go +++ b/x/slashing/keeper_test.go @@ -8,7 +8,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" ) // Have to change these parameters for tests @@ -16,8 +16,7 @@ import ( func keeperTestParams() Params { params := DefaultParams() params.SignedBlocksWindow = 1000 - params.DowntimeUnbondDuration = 60 * 60 - params.DoubleSignUnbondDuration = 60 * 60 + params.DowntimeJailDuration = 60 * 60 return params } @@ -33,9 +32,9 @@ func TestHandleDoubleSign(t *testing.T) { ctx = ctx.WithBlockHeight(-1) amtInt := int64(100) operatorAddr, val, amt := addrs[0], pks[0], sdk.NewInt(amtInt) - got := stake.NewHandler(sk)(ctx, NewTestMsgCreateValidator(operatorAddr, val, amt)) + got := staking.NewHandler(sk)(ctx, NewTestMsgCreateValidator(operatorAddr, val, amt)) require.True(t, got.IsOK()) - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) require.Equal( t, ck.GetCoins(ctx, sdk.AccAddress(operatorAddr)), sdk.Coins{sdk.NewCoin(sk.GetParams(ctx).BondDenom, initCoins.Sub(amt))}, @@ -45,41 +44,54 @@ func TestHandleDoubleSign(t *testing.T) { // handle a signature to set signing info keeper.handleValidatorSignature(ctx, val.Address(), amtInt, true) + oldTokens := sk.Validator(ctx, operatorAddr).GetTokens() + // double sign less than max age keeper.handleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), amtInt) // should be jailed require.True(t, sk.Validator(ctx, operatorAddr).GetJailed()) - // unjail to measure power - sk.Unjail(ctx, sdk.ConsAddress(val.Address())) - // power should be reduced - require.True(sdk.IntEq( - t, amt.Mul(sdk.NewInt(19)).Div(sdk.NewInt(20)), - sk.Validator(ctx, operatorAddr).GetPower(), - )) - ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(1, 0).Add(keeper.MaxEvidenceAge(ctx))}) - // double sign past max age + // tokens should be decreased + newTokens := sk.Validator(ctx, operatorAddr).GetTokens() + require.True(t, newTokens.LT(oldTokens)) + + // New evidence keeper.handleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), amtInt) - require.True(sdk.IntEq( - t, amt.Mul(sdk.NewInt(19)).Div(sdk.NewInt(20)), - sk.Validator(ctx, operatorAddr).GetPower(), - )) + + // tokens should be the same (capped slash) + require.True(t, sk.Validator(ctx, operatorAddr).GetTokens().Equal(newTokens)) + + // Jump to past the unbonding period + ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(1, 0).Add(sk.GetParams(ctx).UnbondingTime)}) + + // Still shouldn't be able to unjail + msgUnjail := NewMsgUnjail(operatorAddr) + res := handleMsgUnjail(ctx, msgUnjail, keeper) + require.False(t, res.IsOK()) + + // Should be able to unbond now + del, _ := sk.GetDelegation(ctx, sdk.AccAddress(operatorAddr), operatorAddr) + msgUnbond := staking.NewMsgBeginUnbonding(sdk.AccAddress(operatorAddr), operatorAddr, del.GetShares()) + res = staking.NewHandler(sk)(ctx, msgUnbond) + require.True(t, res.IsOK()) } -// Test that the amount a validator is slashed for multiple double signs -// is correctly capped by the slashing period in which they were committed -func TestSlashingPeriodCap(t *testing.T) { +// ______________________________________________________________ + +// Test that a validator is slashed correctly +// when we discover evidence of infraction +func TestPastMaxEvidenceAge(t *testing.T) { // initial setup - ctx, ck, sk, _, keeper := createTestInput(t, DefaultParams()) + ctx, ck, sk, _, keeper := createTestInput(t, keeperTestParams()) + // validator added pre-genesis + ctx = ctx.WithBlockHeight(-1) amtInt := int64(100) - operatorAddr, amt := addrs[0], sdk.NewInt(amtInt) - valConsPubKey, valConsAddr := pks[0], pks[0].Address() - got := stake.NewHandler(sk)(ctx, NewTestMsgCreateValidator(operatorAddr, valConsPubKey, amt)) + operatorAddr, val, amt := addrs[0], pks[0], sdk.NewInt(amtInt) + got := staking.NewHandler(sk)(ctx, NewTestMsgCreateValidator(operatorAddr, val, amt)) require.True(t, got.IsOK()) - stake.EndBlocker(ctx, sk) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + staking.EndBlocker(ctx, sk) require.Equal( t, ck.GetCoins(ctx, sdk.AccAddress(operatorAddr)), sdk.Coins{sdk.NewCoin(sk.GetParams(ctx).BondDenom, initCoins.Sub(amt))}, @@ -87,51 +99,20 @@ func TestSlashingPeriodCap(t *testing.T) { require.True(sdk.IntEq(t, amt, sk.Validator(ctx, operatorAddr).GetPower())) // handle a signature to set signing info - keeper.handleValidatorSignature(ctx, valConsAddr, amtInt, true) + keeper.handleValidatorSignature(ctx, val.Address(), amtInt, true) - // double sign less than max age - keeper.handleDoubleSign(ctx, valConsAddr, 1, time.Unix(0, 0), amtInt) - // should be jailed - require.True(t, sk.Validator(ctx, operatorAddr).GetJailed()) - // end block - stake.EndBlocker(ctx, sk) - // update block height - ctx = ctx.WithBlockHeight(int64(2)) - // unjail to measure power - sk.Unjail(ctx, sdk.ConsAddress(valConsAddr)) - // end block - stake.EndBlocker(ctx, sk) - // power should be reduced - expectedPower := amt.Mul(sdk.NewInt(19)).Div(sdk.NewInt(20)) - require.True(sdk.IntEq(t, expectedPower, sk.Validator(ctx, operatorAddr).GetPower())) + ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(1, 0).Add(keeper.MaxEvidenceAge(ctx))}) - // double sign again, same slashing period - keeper.handleDoubleSign(ctx, valConsAddr, 1, time.Unix(0, 0), amtInt) - // should be jailed - require.True(t, sk.Validator(ctx, operatorAddr).GetJailed()) - // end block - stake.EndBlocker(ctx, sk) - // update block height - ctx = ctx.WithBlockHeight(int64(3)) - // unjail to measure power - sk.Unjail(ctx, sdk.ConsAddress(valConsAddr)) - // end block - stake.EndBlocker(ctx, sk) - // power should be equal, no more should have been slashed - expectedPower = amt.Mul(sdk.NewInt(19)).Div(sdk.NewInt(20)) - require.True(sdk.IntEq(t, expectedPower, sk.Validator(ctx, operatorAddr).GetPower())) + oldPower := sk.Validator(ctx, operatorAddr).GetPower() - // double sign again, new slashing period - keeper.handleDoubleSign(ctx, valConsAddr, 3, time.Unix(0, 0), amtInt) - // should be jailed - require.True(t, sk.Validator(ctx, operatorAddr).GetJailed()) - // unjail to measure power - sk.Unjail(ctx, sdk.ConsAddress(valConsAddr)) - // end block - stake.EndBlocker(ctx, sk) - // power should be reduced - expectedPower = amt.Mul(sdk.NewInt(18)).Div(sdk.NewInt(20)) - require.True(sdk.IntEq(t, expectedPower, sk.Validator(ctx, operatorAddr).GetPower())) + // double sign past max age + keeper.handleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), amtInt) + + // should still be bonded + require.True(t, sk.Validator(ctx, operatorAddr).GetStatus() == sdk.Bonded) + + // should still have same power + require.True(t, sk.Validator(ctx, operatorAddr).GetPower().Equal(oldPower)) } // Test a validator through uptime, downtime, revocation, @@ -142,11 +123,11 @@ func TestHandleAbsentValidator(t *testing.T) { ctx, ck, sk, _, keeper := createTestInput(t, keeperTestParams()) amtInt64 := int64(100) addr, val, amt := addrs[0], pks[0], sdk.NewInt(amtInt64) - sh := stake.NewHandler(sk) + sh := staking.NewHandler(sk) slh := NewHandler(keeper) got := sh(ctx, NewTestMsgCreateValidator(addr, val, amt)) require.True(t, got.IsOK()) - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) require.Equal( t, ck.GetCoins(ctx, sdk.AccAddress(addr)), @@ -199,7 +180,7 @@ func TestHandleAbsentValidator(t *testing.T) { require.Equal(t, int64(0), info.MissedBlocksCounter) // end block - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) // validator should have been jailed validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) @@ -220,31 +201,23 @@ func TestHandleAbsentValidator(t *testing.T) { require.Equal(t, int64(1), info.MissedBlocksCounter) // end block - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) // validator should not have been slashed any more, since it was already jailed validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) require.Equal(t, amtInt64-slashAmt, validator.GetTokens().Int64()) - // 502nd block *double signed* (oh no!) - keeper.handleDoubleSign(ctx, val.Address(), height, ctx.BlockHeader().Time, amtInt64) - - // validator should have been slashed - validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) - secondSlashAmt := sdk.NewDec(amtInt64).Mul(keeper.SlashFractionDoubleSign(ctx)).RoundInt64() - require.Equal(t, amtInt64-slashAmt-secondSlashAmt, validator.GetTokens().Int64()) - // unrevocation should fail prior to jail expiration got = slh(ctx, NewMsgUnjail(addr)) require.False(t, got.IsOK()) // unrevocation should succeed after jail expiration - ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(1, 0).Add(keeper.DowntimeUnbondDuration(ctx))}) + ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(1, 0).Add(keeper.DowntimeJailDuration(ctx))}) got = slh(ctx, NewMsgUnjail(addr)) require.True(t, got.IsOK()) // end block - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) // validator should be rebonded now validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) @@ -252,9 +225,9 @@ func TestHandleAbsentValidator(t *testing.T) { // validator should have been slashed pool = sk.GetPool(ctx) - require.Equal(t, amtInt64-slashAmt-secondSlashAmt, pool.BondedTokens.Int64()) + require.Equal(t, amtInt64-slashAmt, pool.BondedTokens.Int64()) - // validator start height should not have been changed + // Validator start height should not have been changed info, found = keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) @@ -276,7 +249,7 @@ func TestHandleAbsentValidator(t *testing.T) { } // end block - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) // validator should be jailed again after 500 unsigned blocks nextHeight = height + keeper.MinSignedPerWindow(ctx) + 1 @@ -286,7 +259,7 @@ func TestHandleAbsentValidator(t *testing.T) { } // end block - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) require.Equal(t, sdk.Unbonding, validator.GetStatus()) @@ -299,7 +272,7 @@ func TestHandleNewValidator(t *testing.T) { // initial setup ctx, ck, sk, _, keeper := createTestInput(t, keeperTestParams()) addr, val, amt := addrs[0], pks[0], int64(100) - sh := stake.NewHandler(sk) + sh := staking.NewHandler(sk) // 1000 first blocks not a validator ctx = ctx.WithBlockHeight(keeper.SignedBlocksWindow(ctx) + 1) @@ -307,7 +280,7 @@ func TestHandleNewValidator(t *testing.T) { // Validator created got := sh(ctx, NewTestMsgCreateValidator(addr, val, sdk.NewInt(amt))) require.True(t, got.IsOK()) - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) require.Equal( t, ck.GetCoins(ctx, sdk.AccAddress(addr)), @@ -342,10 +315,10 @@ func TestHandleAlreadyJailed(t *testing.T) { ctx, _, sk, _, keeper := createTestInput(t, DefaultParams()) amtInt := int64(100) addr, val, amt := addrs[0], pks[0], sdk.NewInt(amtInt) - sh := stake.NewHandler(sk) + sh := staking.NewHandler(sk) got := sh(ctx, NewTestMsgCreateValidator(addr, val, amt)) require.True(t, got.IsOK()) - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) // 1000 first blocks OK height := int64(0) @@ -361,7 +334,7 @@ func TestHandleAlreadyJailed(t *testing.T) { } // end block - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) // validator should have been jailed and slashed validator, _ := sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) @@ -394,10 +367,10 @@ func TestValidatorDippingInAndOut(t *testing.T) { amtInt := int64(100) addr, val, amt := addrs[0], pks[0], sdk.NewInt(amtInt) consAddr := sdk.ConsAddress(addr) - sh := stake.NewHandler(sk) + sh := staking.NewHandler(sk) got := sh(ctx, NewTestMsgCreateValidator(addr, val, amt)) require.True(t, got.IsOK()) - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) // 100 first blocks OK height := int64(0) @@ -410,7 +383,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { newAmt := int64(101) got = sh(ctx, NewTestMsgCreateValidator(addrs[1], pks[1], sdk.NewInt(newAmt))) require.True(t, got.IsOK()) - validatorUpdates, _ := stake.EndBlocker(ctx, sk) + validatorUpdates, _ := staking.EndBlocker(ctx, sk) require.Equal(t, 2, len(validatorUpdates)) validator, _ := sk.GetValidator(ctx, addr) require.Equal(t, sdk.Unbonding, validator.Status) @@ -422,7 +395,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { // validator added back in got = sh(ctx, newTestMsgDelegate(sdk.AccAddress(addrs[2]), addrs[0], sdk.NewInt(3))) require.True(t, got.IsOK()) - validatorUpdates, _ = stake.EndBlocker(ctx, sk) + validatorUpdates, _ = staking.EndBlocker(ctx, sk) require.Equal(t, 2, len(validatorUpdates)) validator, _ = sk.GetValidator(ctx, addr) require.Equal(t, sdk.Bonded, validator.Status) @@ -444,7 +417,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { } // should now be jailed & kicked - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) validator, _ = sk.GetValidator(ctx, addr) require.Equal(t, sdk.Unbonding, validator.Status) @@ -469,7 +442,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { height++ // validator should not be kicked since we reset counter/array when it was jailed - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) validator, _ = sk.GetValidator(ctx, addr) require.Equal(t, sdk.Bonded, validator.Status) @@ -481,7 +454,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { } // validator should now be jailed & kicked - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) validator, _ = sk.GetValidator(ctx, addr) require.Equal(t, sdk.Unbonding, validator.Status) diff --git a/x/slashing/keys.go b/x/slashing/keys.go index 4900c063e163..5e5b08a7f4d7 100644 --- a/x/slashing/keys.go +++ b/x/slashing/keys.go @@ -4,7 +4,7 @@ import ( "encoding/binary" sdk "github.com/cosmos/cosmos-sdk/types" - stake "github.com/cosmos/cosmos-sdk/x/stake/types" + staking "github.com/cosmos/cosmos-sdk/x/staking/types" ) const ( @@ -61,7 +61,7 @@ func GetValidatorSlashingPeriodPrefix(v sdk.ConsAddress) []byte { func GetValidatorSlashingPeriodKey(v sdk.ConsAddress, startHeight int64) []byte { b := make([]byte, 8) // this needs to be height + ValidatorUpdateDelay because the slashing period for genesis validators starts at height -ValidatorUpdateDelay - binary.BigEndian.PutUint64(b, uint64(startHeight+stake.ValidatorUpdateDelay)) + binary.BigEndian.PutUint64(b, uint64(startHeight+staking.ValidatorUpdateDelay)) return append(GetValidatorSlashingPeriodPrefix(v), b...) } diff --git a/x/slashing/params.go b/x/slashing/params.go index 6f95ca73e9fa..4e43c43de7fd 100644 --- a/x/slashing/params.go +++ b/x/slashing/params.go @@ -12,15 +12,19 @@ const ( DefaultParamspace = "slashing" ) +// The Double Sign Jail period ends at Max Time supported by Amino (Dec 31, 9999 - 23:59:59 GMT) +var ( + DoubleSignJailEndTime = time.Unix(253402300799, 0) +) + // Parameter store key var ( - KeyMaxEvidenceAge = []byte("MaxEvidenceAge") - KeySignedBlocksWindow = []byte("SignedBlocksWindow") - KeyMinSignedPerWindow = []byte("MinSignedPerWindow") - KeyDoubleSignUnbondDuration = []byte("DoubleSignUnbondDuration") - KeyDowntimeUnbondDuration = []byte("DowntimeUnbondDuration") - KeySlashFractionDoubleSign = []byte("SlashFractionDoubleSign") - KeySlashFractionDowntime = []byte("SlashFractionDowntime") + KeyMaxEvidenceAge = []byte("MaxEvidenceAge") + KeySignedBlocksWindow = []byte("SignedBlocksWindow") + KeyMinSignedPerWindow = []byte("MinSignedPerWindow") + KeyDowntimeJailDuration = []byte("DowntimeJailDuration") + KeySlashFractionDoubleSign = []byte("SlashFractionDoubleSign") + KeySlashFractionDowntime = []byte("SlashFractionDowntime") ) // ParamTypeTable for slashing module @@ -30,13 +34,12 @@ func ParamTypeTable() params.TypeTable { // Params - used for initializing default parameter for slashing at genesis type Params struct { - MaxEvidenceAge time.Duration `json:"max-evidence-age"` - SignedBlocksWindow int64 `json:"signed-blocks-window"` - MinSignedPerWindow sdk.Dec `json:"min-signed-per-window"` - DoubleSignUnbondDuration time.Duration `json:"double-sign-unbond-duration"` - DowntimeUnbondDuration time.Duration `json:"downtime-unbond-duration"` - SlashFractionDoubleSign sdk.Dec `json:"slash-fraction-double-sign"` - SlashFractionDowntime sdk.Dec `json:"slash-fraction-downtime"` + MaxEvidenceAge time.Duration `json:"max-evidence-age"` + SignedBlocksWindow int64 `json:"signed-blocks-window"` + MinSignedPerWindow sdk.Dec `json:"min-signed-per-window"` + DowntimeJailDuration time.Duration `json:"downtime-jail-duration"` + SlashFractionDoubleSign sdk.Dec `json:"slash-fraction-double-sign"` + SlashFractionDowntime sdk.Dec `json:"slash-fraction-downtime"` } // Implements params.ParamStruct @@ -45,8 +48,7 @@ func (p *Params) KeyValuePairs() params.KeyValuePairs { {KeyMaxEvidenceAge, &p.MaxEvidenceAge}, {KeySignedBlocksWindow, &p.SignedBlocksWindow}, {KeyMinSignedPerWindow, &p.MinSignedPerWindow}, - {KeyDoubleSignUnbondDuration, &p.DoubleSignUnbondDuration}, - {KeyDowntimeUnbondDuration, &p.DowntimeUnbondDuration}, + {KeyDowntimeJailDuration, &p.DowntimeJailDuration}, {KeySlashFractionDoubleSign, &p.SlashFractionDoubleSign}, {KeySlashFractionDowntime, &p.SlashFractionDowntime}, } @@ -59,14 +61,11 @@ func DefaultParams() Params { // TODO Temporarily set to 2 minutes for testnets. MaxEvidenceAge: 60 * 2 * time.Second, - // TODO Temporarily set to five minutes for testnets - DoubleSignUnbondDuration: 60 * 5 * time.Second, - // TODO Temporarily set to 100 blocks for testnets SignedBlocksWindow: 100, // TODO Temporarily set to 10 minutes for testnets - DowntimeUnbondDuration: 60 * 10 * time.Second, + DowntimeJailDuration: 60 * 10 * time.Second, MinSignedPerWindow: sdk.NewDecWithPrec(5, 1), @@ -97,15 +96,9 @@ func (k Keeper) MinSignedPerWindow(ctx sdk.Context) int64 { return sdk.NewDec(signedBlocksWindow).Mul(minSignedPerWindow).RoundInt64() } -// Double-sign unbond duration -func (k Keeper) DoubleSignUnbondDuration(ctx sdk.Context) (res time.Duration) { - k.paramspace.Get(ctx, KeyDoubleSignUnbondDuration, &res) - return -} - // Downtime unbond duration -func (k Keeper) DowntimeUnbondDuration(ctx sdk.Context) (res time.Duration) { - k.paramspace.Get(ctx, KeyDowntimeUnbondDuration, &res) +func (k Keeper) DowntimeJailDuration(ctx sdk.Context) (res time.Duration) { + k.paramspace.Get(ctx, KeyDowntimeJailDuration, &res) return } diff --git a/x/slashing/querier.go b/x/slashing/querier.go index 841925f79cef..a0faaeb509f7 100644 --- a/x/slashing/querier.go +++ b/x/slashing/querier.go @@ -19,7 +19,7 @@ func NewQuerier(k Keeper, cdc *codec.Codec) sdk.Querier { case QueryParameters: return queryParams(ctx, cdc, k) default: - return nil, sdk.ErrUnknownRequest("unknown stake query endpoint") + return nil, sdk.ErrUnknownRequest("unknown staking query endpoint") } } } diff --git a/x/slashing/signing_info.go b/x/slashing/signing_info.go index f4f2d2fde8cd..e8e20706558d 100644 --- a/x/slashing/signing_info.go +++ b/x/slashing/signing_info.go @@ -91,11 +91,12 @@ func (k Keeper) clearValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.C } // Construct a new `ValidatorSigningInfo` struct -func NewValidatorSigningInfo(startHeight int64, indexOffset int64, jailedUntil time.Time, missedBlocksCounter int64) ValidatorSigningInfo { +func NewValidatorSigningInfo(startHeight int64, indexOffset int64, jailedUntil time.Time, tombstoned bool, missedBlocksCounter int64) ValidatorSigningInfo { return ValidatorSigningInfo{ StartHeight: startHeight, IndexOffset: indexOffset, JailedUntil: jailedUntil, + Tombstoned: tombstoned, MissedBlocksCounter: missedBlocksCounter, } } @@ -105,6 +106,7 @@ type ValidatorSigningInfo struct { StartHeight int64 `json:"start_height"` // height at which validator was first a candidate OR was unjailed IndexOffset int64 `json:"index_offset"` // index offset into signed block bit array JailedUntil time.Time `json:"jailed_until"` // timestamp validator cannot be unjailed until + Tombstoned bool `json:"tombstoned"` // whether or not a validator has been tombstoned (killed out of validator set) MissedBlocksCounter int64 `json:"missed_blocks_counter"` // missed blocks counter (to avoid scanning the array every time) } diff --git a/x/slashing/slashing_period.go b/x/slashing/slashing_period.go deleted file mode 100644 index ee2c135875ff..000000000000 --- a/x/slashing/slashing_period.go +++ /dev/null @@ -1,134 +0,0 @@ -package slashing - -import ( - "encoding/binary" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - stake "github.com/cosmos/cosmos-sdk/x/stake/types" -) - -// Cap an infraction's slash amount by the slashing period in which it was committed -func (k Keeper) capBySlashingPeriod(ctx sdk.Context, address sdk.ConsAddress, fraction sdk.Dec, infractionHeight int64) (revisedFraction sdk.Dec) { - - // Fetch the newest slashing period starting before this infraction was committed - slashingPeriod := k.getValidatorSlashingPeriodForHeight(ctx, address, infractionHeight) - - // Sanity check - if slashingPeriod.EndHeight > 0 && slashingPeriod.EndHeight < infractionHeight { - panic(fmt.Sprintf("slashing period ended before infraction: validator %s, infraction height %d, slashing period ended at %d", address, infractionHeight, slashingPeriod.EndHeight)) - } - - // Calculate the updated total slash amount - // This is capped at the slashing fraction for the worst infraction within this slashing period - totalToSlash := sdk.MaxDec(slashingPeriod.SlashedSoFar, fraction) - - // Calculate the remainder which we now must slash - revisedFraction = totalToSlash.Sub(slashingPeriod.SlashedSoFar) - - // Update the slashing period struct - slashingPeriod.SlashedSoFar = totalToSlash - k.SetValidatorSlashingPeriod(ctx, slashingPeriod) - - return -} - -// Stored by validator Tendermint address (not operator address) -// This function retrieves the most recent slashing period starting -// before a particular height - so the slashing period that was "in effect" -// at the time of an infraction committed at that height. -// Slashing periods are created upon validator bonding. -func (k Keeper) getValidatorSlashingPeriodForHeight(ctx sdk.Context, address sdk.ConsAddress, height int64) (slashingPeriod ValidatorSlashingPeriod) { - store := ctx.KVStore(k.storeKey) - // Get the most recent slashing period at or before the infraction height - start := GetValidatorSlashingPeriodPrefix(address) - end := sdk.PrefixEndBytes(GetValidatorSlashingPeriodKey(address, height)) - iterator := store.ReverseIterator(start, end) - if !iterator.Valid() { - panic(fmt.Sprintf("expected to find slashing period for validator %s before height %d, but none was found", address, height)) - } - slashingPeriod = k.unmarshalSlashingPeriodKeyValue(iterator.Key(), iterator.Value()) - return -} - -// Iterate over all slashing periods in the store, calling on each -// decode slashing period a provided handler function -// Stop if the provided handler function returns true -func (k Keeper) IterateValidatorSlashingPeriods(ctx sdk.Context, handler func(slashingPeriod ValidatorSlashingPeriod) (stop bool)) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorSlashingPeriodKey) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - slashingPeriod := k.unmarshalSlashingPeriodKeyValue(iter.Key(), iter.Value()) - if handler(slashingPeriod) { - break - } - } -} - -// Delete all slashing periods in the store. -func (k Keeper) DeleteValidatorSlashingPeriods(ctx sdk.Context) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorSlashingPeriodKey) - for ; iter.Valid(); iter.Next() { - store.Delete(iter.Key()) - } - iter.Close() -} - -// Stored by validator Tendermint address (not operator address) -// This function sets a validator slashing period for a particular validator, -// start height, end height, and current slashed-so-far total, or updates -// an existing slashing period for the same validator and start height. -func (k Keeper) SetValidatorSlashingPeriod(ctx sdk.Context, slashingPeriod ValidatorSlashingPeriod) { - slashingPeriodValue := ValidatorSlashingPeriodValue{ - EndHeight: slashingPeriod.EndHeight, - SlashedSoFar: slashingPeriod.SlashedSoFar, - } - store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshalBinaryLengthPrefixed(slashingPeriodValue) - store.Set(GetValidatorSlashingPeriodKey(slashingPeriod.ValidatorAddr, slashingPeriod.StartHeight), bz) -} - -// Unmarshal key/value into a ValidatorSlashingPeriod -func (k Keeper) unmarshalSlashingPeriodKeyValue(key []byte, value []byte) ValidatorSlashingPeriod { - var slashingPeriodValue ValidatorSlashingPeriodValue - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &slashingPeriodValue) - address := sdk.ConsAddress(key[1 : 1+sdk.AddrLen]) - startHeight := int64(binary.BigEndian.Uint64(key[1+sdk.AddrLen:1+sdk.AddrLen+8]) - uint64(stake.ValidatorUpdateDelay)) - return ValidatorSlashingPeriod{ - ValidatorAddr: address, - StartHeight: startHeight, - EndHeight: slashingPeriodValue.EndHeight, - SlashedSoFar: slashingPeriodValue.SlashedSoFar, - } -} - -// Construct a new `ValidatorSlashingPeriod` struct -func NewValidatorSlashingPeriod(startHeight int64, endHeight int64, slashedSoFar sdk.Dec) ValidatorSlashingPeriod { - return ValidatorSlashingPeriod{ - StartHeight: startHeight, - EndHeight: endHeight, - SlashedSoFar: slashedSoFar, - } -} - -// Slashing period for a validator -type ValidatorSlashingPeriod struct { - ValidatorAddr sdk.ConsAddress `json:"validator_addr"` // validator which this slashing period is for - StartHeight int64 `json:"start_height"` // starting height of the slashing period - EndHeight int64 `json:"end_height"` // ending height of the slashing period, or sentinel value of 0 for in-progress - SlashedSoFar sdk.Dec `json:"slashed_so_far"` // fraction of validator stake slashed so far in this slashing period -} - -// Value part of slashing period (validator address & start height are stored in the key) -type ValidatorSlashingPeriodValue struct { - EndHeight int64 `json:"end_height"` - SlashedSoFar sdk.Dec `json:"slashed_so_far"` -} - -// Return human readable slashing period -func (p ValidatorSlashingPeriod) HumanReadableString() string { - return fmt.Sprintf("Start height: %d, end height: %d, slashed so far: %v", - p.StartHeight, p.EndHeight, p.SlashedSoFar) -} diff --git a/x/slashing/slashing_period_test.go b/x/slashing/slashing_period_test.go deleted file mode 100644 index 522dcdf787e3..000000000000 --- a/x/slashing/slashing_period_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package slashing - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestGetSetValidatorSlashingPeriod(t *testing.T) { - ctx, _, _, _, keeper := createTestInput(t, DefaultParams()) - addr := sdk.ConsAddress(addrs[0]) - height := int64(5) - require.Panics(t, func() { keeper.getValidatorSlashingPeriodForHeight(ctx, addr, height) }) - newPeriod := ValidatorSlashingPeriod{ - ValidatorAddr: addr, - StartHeight: height, - EndHeight: height + 10, - SlashedSoFar: sdk.ZeroDec(), - } - keeper.SetValidatorSlashingPeriod(ctx, newPeriod) - - // Get at start height - retrieved := keeper.getValidatorSlashingPeriodForHeight(ctx, addr, height) - require.Equal(t, newPeriod, retrieved) - - // Get after start height (works) - retrieved = keeper.getValidatorSlashingPeriodForHeight(ctx, addr, int64(6)) - require.Equal(t, newPeriod, retrieved) - - // Get before start height (panic) - require.Panics(t, func() { keeper.getValidatorSlashingPeriodForHeight(ctx, addr, int64(0)) }) - - // Get after end height (panic) - newPeriod.EndHeight = int64(4) - keeper.SetValidatorSlashingPeriod(ctx, newPeriod) - require.Panics(t, func() { keeper.capBySlashingPeriod(ctx, addr, sdk.ZeroDec(), height) }) - - // Back to old end height - newPeriod.EndHeight = height + 10 - keeper.SetValidatorSlashingPeriod(ctx, newPeriod) - - // Set a new, later period - anotherPeriod := ValidatorSlashingPeriod{ - ValidatorAddr: addr, - StartHeight: height + 1, - EndHeight: height + 11, - SlashedSoFar: sdk.ZeroDec(), - } - keeper.SetValidatorSlashingPeriod(ctx, anotherPeriod) - - // Old period retrieved for prior height - retrieved = keeper.getValidatorSlashingPeriodForHeight(ctx, addr, height) - require.Equal(t, newPeriod, retrieved) - - // New period retrieved at new height - retrieved = keeper.getValidatorSlashingPeriodForHeight(ctx, addr, height+1) - require.Equal(t, anotherPeriod, retrieved) -} - -func TestValidatorSlashingPeriodCap(t *testing.T) { - ctx, _, _, _, keeper := createTestInput(t, DefaultParams()) - addr := sdk.ConsAddress(addrs[0]) - height := int64(5) - newPeriod := ValidatorSlashingPeriod{ - ValidatorAddr: addr, - StartHeight: height, - EndHeight: height + 10, - SlashedSoFar: sdk.ZeroDec(), - } - keeper.SetValidatorSlashingPeriod(ctx, newPeriod) - half := sdk.NewDec(1).Quo(sdk.NewDec(2)) - - // First slash should be full - fractionA := keeper.capBySlashingPeriod(ctx, addr, half, height) - require.True(t, fractionA.Equal(half)) - - // Second slash should be capped - fractionB := keeper.capBySlashingPeriod(ctx, addr, half, height) - require.True(t, fractionB.Equal(sdk.ZeroDec())) - - // Third slash should be capped to difference - fractionC := keeper.capBySlashingPeriod(ctx, addr, sdk.OneDec(), height) - require.True(t, fractionC.Equal(half)) -} diff --git a/x/slashing/test_common.go b/x/slashing/test_common.go index a0203bf5ab1e..803ce2124107 100644 --- a/x/slashing/test_common.go +++ b/x/slashing/test_common.go @@ -20,8 +20,8 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/stake" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) // TODO remove dependencies on staking (should only refer to validator set type from sdk) @@ -45,23 +45,23 @@ func createTestCodec() *codec.Codec { sdk.RegisterCodec(cdc) auth.RegisterCodec(cdc) bank.RegisterCodec(cdc) - stake.RegisterCodec(cdc) + staking.RegisterCodec(cdc) codec.RegisterCrypto(cdc) return cdc } -func createTestInput(t *testing.T, defaults Params) (sdk.Context, bank.Keeper, stake.Keeper, params.Subspace, Keeper) { +func createTestInput(t *testing.T, defaults Params) (sdk.Context, bank.Keeper, staking.Keeper, params.Subspace, Keeper) { keyAcc := sdk.NewKVStoreKey(auth.StoreKey) - keyStake := sdk.NewKVStoreKey(stake.StoreKey) - tkeyStake := sdk.NewTransientStoreKey(stake.TStoreKey) + keyStaking := sdk.NewKVStoreKey(staking.StoreKey) + tkeyStaking := sdk.NewTransientStoreKey(staking.TStoreKey) keySlashing := sdk.NewKVStoreKey(StoreKey) keyParams := sdk.NewKVStoreKey(params.StoreKey) tkeyParams := sdk.NewTransientStoreKey(params.TStoreKey) db := dbm.NewMemDB() ms := store.NewCommitMultiStore(db) ms.MountStoreWithDB(keyAcc, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(tkeyStake, sdk.StoreTypeTransient, nil) - ms.MountStoreWithDB(keyStake, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(tkeyStaking, sdk.StoreTypeTransient, nil) + ms.MountStoreWithDB(keyStaking, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keySlashing, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) @@ -73,12 +73,12 @@ func createTestInput(t *testing.T, defaults Params) (sdk.Context, bank.Keeper, s accountKeeper := auth.NewAccountKeeper(cdc, keyAcc, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) ck := bank.NewBaseKeeper(accountKeeper) - sk := stake.NewKeeper(cdc, keyStake, tkeyStake, ck, paramsKeeper.Subspace(stake.DefaultParamspace), stake.DefaultCodespace) - genesis := stake.DefaultGenesisState() + sk := staking.NewKeeper(cdc, keyStaking, tkeyStaking, ck, paramsKeeper.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) + genesis := staking.DefaultGenesisState() genesis.Pool.LooseTokens = sdk.NewInt(initCoins.MulRaw(int64(len(addrs))).Int64()) - _, err = stake.InitGenesis(ctx, sk, genesis) + _, err = staking.InitGenesis(ctx, sk, genesis) require.Nil(t, err) for _, addr := range addrs { @@ -92,7 +92,7 @@ func createTestInput(t *testing.T, defaults Params) (sdk.Context, bank.Keeper, s sk.SetHooks(keeper.Hooks()) require.NotPanics(t, func() { - InitGenesis(ctx, keeper, GenesisState{defaults, nil, nil, nil}, genesis) + InitGenesis(ctx, keeper, GenesisState{defaults, nil, nil}, genesis) }) return ctx, ck, sk, paramstore, keeper @@ -113,22 +113,22 @@ func testAddr(addr string) sdk.AccAddress { return res } -func NewTestMsgCreateValidator(address sdk.ValAddress, pubKey crypto.PubKey, amt sdk.Int) stake.MsgCreateValidator { - commission := stake.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) - return stake.MsgCreateValidator{ - Description: stake.Description{}, +func NewTestMsgCreateValidator(address sdk.ValAddress, pubKey crypto.PubKey, amt sdk.Int) staking.MsgCreateValidator { + commission := staking.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) + return staking.MsgCreateValidator{ + Description: staking.Description{}, Commission: commission, DelegatorAddr: sdk.AccAddress(address), ValidatorAddr: address, PubKey: pubKey, - Delegation: sdk.NewCoin(stakeTypes.DefaultBondDenom, amt), + Delegation: sdk.NewCoin(stakingTypes.DefaultBondDenom, amt), } } -func newTestMsgDelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, delAmount sdk.Int) stake.MsgDelegate { - return stake.MsgDelegate{ +func newTestMsgDelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, delAmount sdk.Int) staking.MsgDelegate { + return staking.MsgDelegate{ DelegatorAddr: delAddr, ValidatorAddr: valAddr, - Delegation: sdk.NewCoin(stakeTypes.DefaultBondDenom, delAmount), + Delegation: sdk.NewCoin(stakingTypes.DefaultBondDenom, delAmount), } } diff --git a/x/slashing/tick_test.go b/x/slashing/tick_test.go index 0afb6f5cd614..9ee6d03c0403 100644 --- a/x/slashing/tick_test.go +++ b/x/slashing/tick_test.go @@ -9,7 +9,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" ) func TestBeginBlocker(t *testing.T) { @@ -17,9 +17,9 @@ func TestBeginBlocker(t *testing.T) { addr, pk, amt := addrs[2], pks[2], sdk.NewInt(100) // bond the validator - got := stake.NewHandler(sk)(ctx, NewTestMsgCreateValidator(addr, pk, amt)) + got := staking.NewHandler(sk)(ctx, NewTestMsgCreateValidator(addr, pk, amt)) require.True(t, got.IsOK()) - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) require.Equal( t, ck.GetCoins(ctx, sdk.AccAddress(addr)), sdk.Coins{sdk.NewCoin(sk.GetParams(ctx).BondDenom, initCoins.Sub(amt))}, @@ -80,7 +80,7 @@ func TestBeginBlocker(t *testing.T) { } // end block - stake.EndBlocker(ctx, sk) + staking.EndBlocker(ctx, sk) // validator should be jailed validator, found := sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(pk)) diff --git a/x/stake/keeper/hooks.go b/x/stake/keeper/hooks.go deleted file mode 100644 index 4ae158786eec..000000000000 --- a/x/stake/keeper/hooks.go +++ /dev/null @@ -1,61 +0,0 @@ -//nolint -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Expose the hooks if present -func (k Keeper) OnValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { - if k.hooks != nil { - k.hooks.OnValidatorCreated(ctx, valAddr) - } -} - -func (k Keeper) OnValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { - if k.hooks != nil { - k.hooks.OnValidatorModified(ctx, valAddr) - } -} - -func (k Keeper) OnValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - if k.hooks != nil { - k.hooks.OnValidatorRemoved(ctx, consAddr, valAddr) - } -} - -func (k Keeper) OnValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - if k.hooks != nil { - k.hooks.OnValidatorBonded(ctx, consAddr, valAddr) - } -} - -func (k Keeper) OnValidatorPowerDidChange(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - if k.hooks != nil { - k.hooks.OnValidatorPowerDidChange(ctx, consAddr, valAddr) - } -} - -func (k Keeper) OnValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { - if k.hooks != nil { - k.hooks.OnValidatorBeginUnbonding(ctx, consAddr, valAddr) - } -} - -func (k Keeper) OnDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - if k.hooks != nil { - k.hooks.OnDelegationCreated(ctx, delAddr, valAddr) - } -} - -func (k Keeper) OnDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - if k.hooks != nil { - k.hooks.OnDelegationSharesModified(ctx, delAddr, valAddr) - } -} - -func (k Keeper) OnDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - if k.hooks != nil { - k.hooks.OnDelegationRemoved(ctx, delAddr, valAddr) - } -} diff --git a/x/stake/types/keys.go b/x/stake/types/keys.go deleted file mode 100644 index 28d099a023c9..000000000000 --- a/x/stake/types/keys.go +++ /dev/null @@ -1,15 +0,0 @@ -package types - -const ( - // StoreKey is the string store representation - StoreKey = "stake" - - // TStoreKey is the string transient store representation - TStoreKey = "transient_stake" - - // QuerierRoute is the querier route for the stake module - QuerierRoute = "stake" - - // RouterKey is the msg router key for the stake module - RouterKey = "stake" -) diff --git a/x/stake/app_test.go b/x/staking/app_test.go similarity index 88% rename from x/stake/app_test.go rename to x/staking/app_test.go index 1be37c1e3509..80f416d716f3 100644 --- a/x/stake/app_test.go +++ b/x/staking/app_test.go @@ -1,4 +1,4 @@ -package stake +package staking import ( "testing" @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/mock" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) // getMockApp returns an initialized mock application for this module. @@ -19,21 +19,21 @@ func getMockApp(t *testing.T) (*mock.App, Keeper) { RegisterCodec(mApp.Cdc) - keyStake := sdk.NewKVStoreKey(StoreKey) - tkeyStake := sdk.NewTransientStoreKey(TStoreKey) + keyStaking := sdk.NewKVStoreKey(StoreKey) + tkeyStaking := sdk.NewTransientStoreKey(TStoreKey) bankKeeper := bank.NewBaseKeeper(mApp.AccountKeeper) - keeper := NewKeeper(mApp.Cdc, keyStake, tkeyStake, bankKeeper, mApp.ParamsKeeper.Subspace(DefaultParamspace), DefaultCodespace) + keeper := NewKeeper(mApp.Cdc, keyStaking, tkeyStaking, bankKeeper, mApp.ParamsKeeper.Subspace(DefaultParamspace), DefaultCodespace) mApp.Router().AddRoute(RouterKey, NewHandler(keeper)) mApp.SetEndBlocker(getEndBlocker(keeper)) mApp.SetInitChainer(getInitChainer(mApp, keeper)) - require.NoError(t, mApp.CompleteSetup(keyStake, tkeyStake)) + require.NoError(t, mApp.CompleteSetup(keyStaking, tkeyStaking)) return mApp, keeper } -// getEndBlocker returns a stake endblocker. +// getEndBlocker returns a staking endblocker. func getEndBlocker(keeper Keeper) sdk.EndBlocker { return func(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { validatorUpdates, tags := EndBlocker(ctx, keeper) @@ -51,10 +51,10 @@ func getInitChainer(mapp *mock.App, keeper Keeper) sdk.InitChainer { return func(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { mapp.InitChainer(ctx, req) - stakeGenesis := DefaultGenesisState() - stakeGenesis.Pool.LooseTokens = sdk.NewInt(100000) + stakingGenesis := DefaultGenesisState() + stakingGenesis.Pool.LooseTokens = sdk.NewInt(100000) - validators, err := InitGenesis(ctx, keeper, stakeGenesis) + validators, err := InitGenesis(ctx, keeper, stakingGenesis) if err != nil { panic(err) } @@ -94,11 +94,11 @@ func checkDelegation( require.False(t, found) } -func TestStakeMsgs(t *testing.T) { +func TestStakingMsgs(t *testing.T) { mApp, keeper := getMockApp(t) - genCoin := sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 42) - bondCoin := sdk.NewInt64Coin(stakeTypes.DefaultBondDenom, 10) + genCoin := sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 42) + bondCoin := sdk.NewInt64Coin(stakingTypes.DefaultBondDenom, 10) acc1 := &auth.BaseAccount{ Address: addr1, diff --git a/x/stake/client/cli/flags.go b/x/staking/client/cli/flags.go similarity index 98% rename from x/stake/client/cli/flags.go rename to x/staking/client/cli/flags.go index a29bdf3762cc..6e1c4e51d73e 100644 --- a/x/stake/client/cli/flags.go +++ b/x/staking/client/cli/flags.go @@ -3,7 +3,7 @@ package cli import ( flag "github.com/spf13/pflag" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // nolint diff --git a/x/stake/client/cli/query.go b/x/staking/client/cli/query.go similarity index 90% rename from x/stake/client/cli/query.go rename to x/staking/client/cli/query.go index 40598fcf8000..e1aac2466e4f 100644 --- a/x/stake/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -10,8 +10,8 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // GetCmdQueryValidator implements the validator query command. @@ -26,7 +26,7 @@ func GetCmdQueryValidator(storeName string, cdc *codec.Codec) *cobra.Command { return err } - key := stake.GetValidatorKey(addr) + key := staking.GetValidatorKey(addr) cliCtx := context.NewCLIContext().WithCodec(cdc) res, err := cliCtx.QueryStore(key, storeName) @@ -36,7 +36,7 @@ func GetCmdQueryValidator(storeName string, cdc *codec.Codec) *cobra.Command { return fmt.Errorf("No validator found with address %s", args[0]) } - validator := types.MustUnmarshalValidator(cdc, addr, res) + validator := types.MustUnmarshalValidator(cdc, res) switch viper.Get(cli.OutputFlag) { case "text": @@ -70,7 +70,7 @@ func GetCmdQueryValidators(storeName string, cdc *codec.Codec) *cobra.Command { Use: "validators", Short: "Query for all validators", RunE: func(cmd *cobra.Command, args []string) error { - key := stake.ValidatorsKey + key := staking.ValidatorsKey cliCtx := context.NewCLIContext().WithCodec(cdc) resKVs, err := cliCtx.QuerySubspace(key, storeName) @@ -79,10 +79,9 @@ func GetCmdQueryValidators(storeName string, cdc *codec.Codec) *cobra.Command { } // parse out the validators - var validators []stake.Validator + var validators []staking.Validator for _, kv := range resKVs { - addr := kv.Key[1:] - validator := types.MustUnmarshalValidator(cdc, addr, kv.Value) + validator := types.MustUnmarshalValidator(cdc, kv.Value) validators = append(validators, validator) } @@ -127,7 +126,7 @@ func GetCmdQueryValidatorUnbondingDelegations(storeKey string, cdc *codec.Codec) } cliCtx := context.NewCLIContext().WithCodec(cdc) - params := stake.NewQueryValidatorParams(valAddr) + params := staking.NewQueryValidatorParams(valAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -162,7 +161,7 @@ func GetCmdQueryValidatorRedelegations(storeKey string, cdc *codec.Codec) *cobra } cliCtx := context.NewCLIContext().WithCodec(cdc) - params := stake.NewQueryValidatorParams(valAddr) + params := staking.NewQueryValidatorParams(valAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -200,7 +199,7 @@ func GetCmdQueryDelegation(storeName string, cdc *codec.Codec) *cobra.Command { return err } - key := stake.GetDelegationKey(delAddr, valAddr) + key := staking.GetDelegationKey(delAddr, valAddr) cliCtx := context.NewCLIContext().WithCodec(cdc) res, err := cliCtx.QueryStore(key, storeName) @@ -209,8 +208,7 @@ func GetCmdQueryDelegation(storeName string, cdc *codec.Codec) *cobra.Command { } // parse out the delegation - - delegation, err := types.UnmarshalDelegation(cdc, key, res) + delegation, err := types.UnmarshalDelegation(cdc, res) if err != nil { return err } @@ -256,7 +254,7 @@ func GetCmdQueryDelegations(storeName string, cdc *codec.Codec) *cobra.Command { return err } - key := stake.GetDelegationsKey(delegatorAddr) + key := staking.GetDelegationsKey(delegatorAddr) cliCtx := context.NewCLIContext().WithCodec(cdc) resKVs, err := cliCtx.QuerySubspace(key, storeName) @@ -265,9 +263,9 @@ func GetCmdQueryDelegations(storeName string, cdc *codec.Codec) *cobra.Command { } // parse out the validators - var delegations []stake.Delegation + var delegations []staking.Delegation for _, kv := range resKVs { - delegation := types.MustUnmarshalDelegation(cdc, kv.Key, kv.Value) + delegation := types.MustUnmarshalDelegation(cdc, kv.Value) delegations = append(delegations, delegation) } @@ -299,7 +297,7 @@ func GetCmdQueryValidatorDelegations(storeKey string, cdc *codec.Codec) *cobra.C return err } - params := stake.NewQueryValidatorParams(validatorAddr) + params := staking.NewQueryValidatorParams(validatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -338,7 +336,7 @@ func GetCmdQueryUnbondingDelegation(storeName string, cdc *codec.Codec) *cobra.C return err } - key := stake.GetUBDKey(delAddr, valAddr) + key := staking.GetUBDKey(delAddr, valAddr) cliCtx := context.NewCLIContext().WithCodec(cdc) res, err := cliCtx.QueryStore(key, storeName) @@ -347,7 +345,7 @@ func GetCmdQueryUnbondingDelegation(storeName string, cdc *codec.Codec) *cobra.C } // parse out the unbonding delegation - ubd := types.MustUnmarshalUBD(cdc, key, res) + ubd := types.MustUnmarshalUBD(cdc, res) switch viper.Get(cli.OutputFlag) { case "text": @@ -390,7 +388,7 @@ func GetCmdQueryUnbondingDelegations(storeName string, cdc *codec.Codec) *cobra. return err } - key := stake.GetUBDsKey(delegatorAddr) + key := staking.GetUBDsKey(delegatorAddr) cliCtx := context.NewCLIContext().WithCodec(cdc) resKVs, err := cliCtx.QuerySubspace(key, storeName) @@ -399,9 +397,9 @@ func GetCmdQueryUnbondingDelegations(storeName string, cdc *codec.Codec) *cobra. } // parse out the unbonding delegations - var ubds []stake.UnbondingDelegation + var ubds []staking.UnbondingDelegation for _, kv := range resKVs { - ubd := types.MustUnmarshalUBD(cdc, kv.Key, kv.Value) + ubd := types.MustUnmarshalUBD(cdc, kv.Value) ubds = append(ubds, ubd) } @@ -442,7 +440,7 @@ func GetCmdQueryRedelegation(storeName string, cdc *codec.Codec) *cobra.Command return err } - key := stake.GetREDKey(delAddr, valSrcAddr, valDstAddr) + key := staking.GetREDKey(delAddr, valSrcAddr, valDstAddr) cliCtx := context.NewCLIContext().WithCodec(cdc) res, err := cliCtx.QueryStore(key, storeName) @@ -451,7 +449,7 @@ func GetCmdQueryRedelegation(storeName string, cdc *codec.Codec) *cobra.Command } // parse out the unbonding delegation - red := types.MustUnmarshalRED(cdc, key, res) + red := types.MustUnmarshalRED(cdc, res) switch viper.Get(cli.OutputFlag) { case "text": @@ -494,7 +492,7 @@ func GetCmdQueryRedelegations(storeName string, cdc *codec.Codec) *cobra.Command return err } - key := stake.GetREDsKey(delegatorAddr) + key := staking.GetREDsKey(delegatorAddr) cliCtx := context.NewCLIContext().WithCodec(cdc) resKVs, err := cliCtx.QuerySubspace(key, storeName) @@ -503,9 +501,9 @@ func GetCmdQueryRedelegations(storeName string, cdc *codec.Codec) *cobra.Command } // parse out the validators - var reds []stake.Redelegation + var reds []staking.Redelegation for _, kv := range resKVs { - red := types.MustUnmarshalRED(cdc, kv.Key, kv.Value) + red := types.MustUnmarshalRED(cdc, kv.Value) reds = append(reds, red) } @@ -531,7 +529,7 @@ func GetCmdQueryPool(storeName string, cdc *codec.Codec) *cobra.Command { Short: "Query the current staking pool values", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - key := stake.PoolKey + key := staking.PoolKey cliCtx := context.NewCLIContext().WithCodec(cdc) res, err := cliCtx.QueryStore(key, storeName) @@ -571,12 +569,12 @@ func GetCmdQueryParams(storeName string, cdc *codec.Codec) *cobra.Command { Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - bz, err := cliCtx.QueryWithData("custom/stake/"+stake.QueryParameters, nil) + bz, err := cliCtx.QueryWithData("custom/staking/"+staking.QueryParameters, nil) if err != nil { return err } - var params stake.Params + var params staking.Params err = cdc.UnmarshalJSON(bz, ¶ms) if err != nil { return err diff --git a/x/stake/client/cli/tx.go b/x/staking/client/cli/tx.go similarity index 94% rename from x/stake/client/cli/tx.go rename to x/staking/client/cli/tx.go index adcff3799b4b..6788a2db65a0 100644 --- a/x/stake/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -12,7 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -76,7 +76,7 @@ func GetCmdEditValidator(cdc *codec.Codec) *cobra.Command { return err } - description := stake.Description{ + description := staking.Description{ Moniker: viper.GetString(FlagMoniker), Identity: viper.GetString(FlagIdentity), Website: viper.GetString(FlagWebsite), @@ -95,7 +95,7 @@ func GetCmdEditValidator(cdc *codec.Codec) *cobra.Command { newRate = &rate } - msg := stake.NewMsgEditValidator(sdk.ValAddress(valAddr), description, newRate) + msg := staking.NewMsgEditValidator(sdk.ValAddress(valAddr), description, newRate) if cliCtx.GenerateOnly { return utils.PrintUnsignedStdTx(os.Stdout, txBldr, cliCtx, []sdk.Msg{msg}, false) @@ -138,7 +138,7 @@ func GetCmdDelegate(cdc *codec.Codec) *cobra.Command { return err } - msg := stake.NewMsgDelegate(delAddr, valAddr, amount) + msg := staking.NewMsgDelegate(delAddr, valAddr, amount) if cliCtx.GenerateOnly { return utils.PrintUnsignedStdTx(os.Stdout, txBldr, cliCtx, []sdk.Msg{msg}, false) @@ -193,7 +193,7 @@ func GetCmdRedelegate(storeName string, cdc *codec.Codec) *cobra.Command { return err } - msg := stake.NewMsgBeginRedelegate(delAddr, valSrcAddr, valDstAddr, sharesAmount) + msg := staking.NewMsgBeginRedelegate(delAddr, valSrcAddr, valDstAddr, sharesAmount) if cliCtx.GenerateOnly { return utils.PrintUnsignedStdTx(os.Stdout, txBldr, cliCtx, []sdk.Msg{msg}, false) @@ -241,7 +241,7 @@ func GetCmdUnbond(storeName string, cdc *codec.Codec) *cobra.Command { return err } - msg := stake.NewMsgBeginUnbonding(delAddr, valAddr, sharesAmount) + msg := staking.NewMsgBeginUnbonding(delAddr, valAddr, sharesAmount) if cliCtx.GenerateOnly { return utils.PrintUnsignedStdTx(os.Stdout, txBldr, cliCtx, []sdk.Msg{msg}, false) @@ -276,7 +276,7 @@ func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr authtxb.TxBuilder return txBldr, nil, err } - description := stake.NewDescription( + description := staking.NewDescription( viper.GetString(FlagMoniker), viper.GetString(FlagIdentity), viper.GetString(FlagWebsite), @@ -301,11 +301,11 @@ func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr authtxb.TxBuilder return txBldr, nil, err } - msg = stake.NewMsgCreateValidatorOnBehalfOf( + msg = staking.NewMsgCreateValidatorOnBehalfOf( delAddr, sdk.ValAddress(valAddr), pk, amount, description, commissionMsg, ) } else { - msg = stake.NewMsgCreateValidator( + msg = staking.NewMsgCreateValidator( sdk.ValAddress(valAddr), pk, amount, description, commissionMsg, ) } diff --git a/x/stake/client/cli/utils.go b/x/staking/client/cli/utils.go similarity index 92% rename from x/stake/client/cli/utils.go rename to x/staking/client/cli/utils.go index 848e1725d05e..43eb10e4b0ab 100644 --- a/x/stake/client/cli/utils.go +++ b/x/staking/client/cli/utils.go @@ -6,8 +6,8 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) func getShares( @@ -42,7 +42,7 @@ func getShares( } // make a query to get the existing delegation shares - key := stake.GetDelegationKey(delAddr, valAddr) + key := staking.GetDelegationKey(delAddr, valAddr) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -52,7 +52,7 @@ func getShares( return sharesAmount, errors.Errorf("cannot find delegation to determine percent Error: %v", err) } - delegation, err := types.UnmarshalDelegation(cdc, key, resQuery) + delegation, err := types.UnmarshalDelegation(cdc, resQuery) if err != nil { return sdk.ZeroDec(), err } diff --git a/x/stake/client/module_client.go b/x/staking/client/module_client.go similarity index 84% rename from x/stake/client/module_client.go rename to x/staking/client/module_client.go index 03a7c25e2a65..ae2c8e7e80e3 100644 --- a/x/stake/client/module_client.go +++ b/x/staking/client/module_client.go @@ -5,7 +5,7 @@ import ( amino "github.com/tendermint/go-amino" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/x/stake/client/cli" + "github.com/cosmos/cosmos-sdk/x/staking/client/cli" ) // ModuleClient exports all client functionality from this module @@ -20,11 +20,11 @@ func NewModuleClient(storeKey string, cdc *amino.Codec) ModuleClient { // GetQueryCmd returns the cli query commands for this module func (mc ModuleClient) GetQueryCmd() *cobra.Command { - stakeQueryCmd := &cobra.Command{ - Use: "stake", + stakingQueryCmd := &cobra.Command{ + Use: "staking", Short: "Querying commands for the staking module", } - stakeQueryCmd.AddCommand(client.GetCommands( + stakingQueryCmd.AddCommand(client.GetCommands( cli.GetCmdQueryDelegation(mc.storeKey, mc.cdc), cli.GetCmdQueryDelegations(mc.storeKey, mc.cdc), cli.GetCmdQueryUnbondingDelegation(mc.storeKey, mc.cdc), @@ -39,18 +39,18 @@ func (mc ModuleClient) GetQueryCmd() *cobra.Command { cli.GetCmdQueryParams(mc.storeKey, mc.cdc), cli.GetCmdQueryPool(mc.storeKey, mc.cdc))...) - return stakeQueryCmd + return stakingQueryCmd } // GetTxCmd returns the transaction commands for this module func (mc ModuleClient) GetTxCmd() *cobra.Command { - stakeTxCmd := &cobra.Command{ - Use: "stake", + stakingTxCmd := &cobra.Command{ + Use: "staking", Short: "Staking transaction subcommands", } - stakeTxCmd.AddCommand(client.PostCommands( + stakingTxCmd.AddCommand(client.PostCommands( cli.GetCmdCreateValidator(mc.cdc), cli.GetCmdEditValidator(mc.cdc), cli.GetCmdDelegate(mc.cdc), @@ -58,5 +58,5 @@ func (mc ModuleClient) GetTxCmd() *cobra.Command { cli.GetCmdUnbond(mc.storeKey, mc.cdc), )...) - return stakeTxCmd + return stakingTxCmd } diff --git a/x/stake/client/rest/query.go b/x/staking/client/rest/query.go similarity index 79% rename from x/stake/client/rest/query.go rename to x/staking/client/rest/query.go index b46a24344eec..aa9f52b52bed 100644 --- a/x/stake/client/rest/query.go +++ b/x/staking/client/rest/query.go @@ -9,8 +9,8 @@ import ( "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/cosmos/cosmos-sdk/x/stake/tags" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/tags" "github.com/gorilla/mux" ) @@ -19,85 +19,85 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Co // Get all delegations from a delegator r.HandleFunc( - "/stake/delegators/{delegatorAddr}/delegations", + "/staking/delegators/{delegatorAddr}/delegations", delegatorDelegationsHandlerFn(cliCtx, cdc), ).Methods("GET") // Get all unbonding delegations from a delegator r.HandleFunc( - "/stake/delegators/{delegatorAddr}/unbonding_delegations", + "/staking/delegators/{delegatorAddr}/unbonding_delegations", delegatorUnbondingDelegationsHandlerFn(cliCtx, cdc), ).Methods("GET") // Get all staking txs (i.e msgs) from a delegator r.HandleFunc( - "/stake/delegators/{delegatorAddr}/txs", + "/staking/delegators/{delegatorAddr}/txs", delegatorTxsHandlerFn(cliCtx, cdc), ).Methods("GET") // Query all validators that a delegator is bonded to r.HandleFunc( - "/stake/delegators/{delegatorAddr}/validators", + "/staking/delegators/{delegatorAddr}/validators", delegatorValidatorsHandlerFn(cliCtx, cdc), ).Methods("GET") // Query a validator that a delegator is bonded to r.HandleFunc( - "/stake/delegators/{delegatorAddr}/validators/{validatorAddr}", + "/staking/delegators/{delegatorAddr}/validators/{validatorAddr}", delegatorValidatorHandlerFn(cliCtx, cdc), ).Methods("GET") // Query a delegation between a delegator and a validator r.HandleFunc( - "/stake/delegators/{delegatorAddr}/delegations/{validatorAddr}", + "/staking/delegators/{delegatorAddr}/delegations/{validatorAddr}", delegationHandlerFn(cliCtx, cdc), ).Methods("GET") // Query all unbonding delegations between a delegator and a validator r.HandleFunc( - "/stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}", + "/staking/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}", unbondingDelegationHandlerFn(cliCtx, cdc), ).Methods("GET") // Query redelegations (filters in query params) r.HandleFunc( - "/stake/redelegations", + "/staking/redelegations", redelegationsHandlerFn(cliCtx, cdc), ).Methods("GET") // Get all validators r.HandleFunc( - "/stake/validators", + "/staking/validators", validatorsHandlerFn(cliCtx, cdc), ).Methods("GET") // Get a single validator info r.HandleFunc( - "/stake/validators/{validatorAddr}", + "/staking/validators/{validatorAddr}", validatorHandlerFn(cliCtx, cdc), ).Methods("GET") // Get all delegations to a validator r.HandleFunc( - "/stake/validators/{validatorAddr}/delegations", + "/staking/validators/{validatorAddr}/delegations", validatorDelegationsHandlerFn(cliCtx, cdc), ).Methods("GET") // Get all unbonding delegations from a validator r.HandleFunc( - "/stake/validators/{validatorAddr}/unbonding_delegations", + "/staking/validators/{validatorAddr}/unbonding_delegations", validatorUnbondingDelegationsHandlerFn(cliCtx, cdc), ).Methods("GET") // Get the current state of the staking pool r.HandleFunc( - "/stake/pool", + "/staking/pool", poolHandlerFn(cliCtx, cdc), ).Methods("GET") // Get the current staking parameter values r.HandleFunc( - "/stake/parameters", + "/staking/parameters", paramsHandlerFn(cliCtx, cdc), ).Methods("GET") @@ -105,12 +105,12 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Co // HTTP request handler to query a delegator delegations func delegatorDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryDelegator(cliCtx, cdc, "custom/stake/delegatorDelegations") + return queryDelegator(cliCtx, cdc, "custom/staking/delegatorDelegations") } // HTTP request handler to query a delegator unbonding delegations func delegatorUnbondingDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryDelegator(cliCtx, cdc, "custom/stake/delegatorUnbondingDelegations") + return queryDelegator(cliCtx, cdc, "custom/staking/delegatorUnbondingDelegations") } // HTTP request handler to query all staking txs (msgs) from a delegator @@ -149,18 +149,18 @@ func delegatorTxsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Han switch { case isBondTx: - actions = append(actions, stake.MsgDelegate{}.Type()) + actions = append(actions, staking.MsgDelegate{}.Type()) case isUnbondTx: - actions = append(actions, stake.MsgBeginUnbonding{}.Type()) + actions = append(actions, staking.MsgBeginUnbonding{}.Type()) actions = append(actions, string(tags.ActionCompleteUnbonding)) case isRedTx: - actions = append(actions, stake.MsgBeginRedelegate{}.Type()) + actions = append(actions, staking.MsgBeginRedelegate{}.Type()) actions = append(actions, string(tags.ActionCompleteRedelegation)) case noQuery: - actions = append(actions, stake.MsgDelegate{}.Type()) - actions = append(actions, stake.MsgBeginUnbonding{}.Type()) + actions = append(actions, staking.MsgDelegate{}.Type()) + actions = append(actions, staking.MsgBeginUnbonding{}.Type()) actions = append(actions, string(tags.ActionCompleteUnbonding)) - actions = append(actions, stake.MsgBeginRedelegate{}.Type()) + actions = append(actions, staking.MsgBeginRedelegate{}.Type()) actions = append(actions, string(tags.ActionCompleteRedelegation)) default: w.WriteHeader(http.StatusNoContent) @@ -186,13 +186,13 @@ func delegatorTxsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Han // HTTP request handler to query an unbonding-delegation func unbondingDelegationHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryBonds(cliCtx, cdc, "custom/stake/unbondingDelegation") + return queryBonds(cliCtx, cdc, "custom/staking/unbondingDelegation") } // HTTP request handler to query redelegations func redelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var params stake.QueryRedelegationParams + var params staking.QueryRedelegationParams bechDelegatorAddr := r.URL.Query().Get("delegator") bechSrcValidatorAddr := r.URL.Query().Get("validator_from") @@ -231,7 +231,7 @@ func redelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Ha return } - res, err := cliCtx.QueryWithData("custom/stake/redelegations", bz) + res, err := cliCtx.QueryWithData("custom/staking/redelegations", bz) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -242,23 +242,23 @@ func redelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Ha // HTTP request handler to query a delegation func delegationHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryBonds(cliCtx, cdc, "custom/stake/delegation") + return queryBonds(cliCtx, cdc, "custom/staking/delegation") } // HTTP request handler to query all delegator bonded validators func delegatorValidatorsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryDelegator(cliCtx, cdc, "custom/stake/delegatorValidators") + return queryDelegator(cliCtx, cdc, "custom/staking/delegatorValidators") } // HTTP request handler to get information from a currently bonded validator func delegatorValidatorHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryBonds(cliCtx, cdc, "custom/stake/delegatorValidator") + return queryBonds(cliCtx, cdc, "custom/staking/delegatorValidator") } // HTTP request handler to query list of validators func validatorsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - res, err := cliCtx.QueryWithData("custom/stake/validators", nil) + res, err := cliCtx.QueryWithData("custom/staking/validators", nil) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -269,23 +269,23 @@ func validatorsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Handl // HTTP request handler to query the validator information from a given validator address func validatorHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryValidator(cliCtx, cdc, "custom/stake/validator") + return queryValidator(cliCtx, cdc, "custom/staking/validator") } // HTTP request handler to query all unbonding delegations from a validator func validatorDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryValidator(cliCtx, cdc, "custom/stake/validatorDelegations") + return queryValidator(cliCtx, cdc, "custom/staking/validatorDelegations") } // HTTP request handler to query all unbonding delegations from a validator func validatorUnbondingDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryValidator(cliCtx, cdc, "custom/stake/validatorUnbondingDelegations") + return queryValidator(cliCtx, cdc, "custom/staking/validatorUnbondingDelegations") } // HTTP request handler to query the pool information func poolHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - res, err := cliCtx.QueryWithData("custom/stake/pool", nil) + res, err := cliCtx.QueryWithData("custom/staking/pool", nil) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -297,7 +297,7 @@ func poolHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc // HTTP request handler to query the staking params values func paramsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - res, err := cliCtx.QueryWithData("custom/stake/parameters", nil) + res, err := cliCtx.QueryWithData("custom/staking/parameters", nil) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return diff --git a/x/stake/client/rest/rest.go b/x/staking/client/rest/rest.go similarity index 100% rename from x/stake/client/rest/rest.go rename to x/staking/client/rest/rest.go diff --git a/x/stake/client/rest/tx.go b/x/staking/client/rest/tx.go similarity index 89% rename from x/stake/client/rest/tx.go rename to x/staking/client/rest/tx.go index 7fde46acbd2e..26e7c9ea210c 100644 --- a/x/stake/client/rest/tx.go +++ b/x/staking/client/rest/tx.go @@ -9,22 +9,22 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/staking" "github.com/gorilla/mux" ) func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, kb keys.Keybase) { r.HandleFunc( - "/stake/delegators/{delegatorAddr}/delegations", + "/staking/delegators/{delegatorAddr}/delegations", postDelegationsHandlerFn(cdc, kb, cliCtx), ).Methods("POST") r.HandleFunc( - "/stake/delegators/{delegatorAddr}/unbonding_delegations", + "/staking/delegators/{delegatorAddr}/unbonding_delegations", postUnbondingDelegationsHandlerFn(cdc, kb, cliCtx), ).Methods("POST") r.HandleFunc( - "/stake/delegators/{delegatorAddr}/redelegations", + "/staking/delegators/{delegatorAddr}/redelegations", postRedelegationsHandlerFn(cdc, kb, cliCtx), ).Methods("POST") } @@ -79,7 +79,7 @@ func postDelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context. return } - msg := stake.NewMsgDelegate(req.DelegatorAddr, req.ValidatorAddr, req.Delegation) + msg := staking.NewMsgDelegate(req.DelegatorAddr, req.ValidatorAddr, req.Delegation) err = msg.ValidateBasic() if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) @@ -116,7 +116,7 @@ func postRedelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx contex return } - msg := stake.NewMsgBeginRedelegate(req.DelegatorAddr, req.ValidatorSrcAddr, req.ValidatorDstAddr, req.SharesAmount) + msg := staking.NewMsgBeginRedelegate(req.DelegatorAddr, req.ValidatorSrcAddr, req.ValidatorDstAddr, req.SharesAmount) err = msg.ValidateBasic() if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) @@ -153,7 +153,7 @@ func postUnbondingDelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx return } - msg := stake.NewMsgBeginUnbonding(req.DelegatorAddr, req.ValidatorAddr, req.SharesAmount) + msg := staking.NewMsgBeginUnbonding(req.DelegatorAddr, req.ValidatorAddr, req.SharesAmount) err = msg.ValidateBasic() if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) diff --git a/x/stake/client/rest/utils.go b/x/staking/client/rest/utils.go similarity index 93% rename from x/stake/client/rest/utils.go rename to x/staking/client/rest/utils.go index f499e323d239..2a95776e3dc0 100644 --- a/x/stake/client/rest/utils.go +++ b/x/staking/client/rest/utils.go @@ -11,8 +11,8 @@ import ( "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/cosmos/cosmos-sdk/x/stake/tags" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/tags" rpcclient "github.com/tendermint/tendermint/rpc/client" ) @@ -73,7 +73,7 @@ func queryRedelegations(cliCtx context.CLIContext, cdc *codec.Codec, endpoint st return } - params := stake.QueryRedelegationParams{ + params := staking.QueryRedelegationParams{ DelegatorAddr: delegatorAddr, SrcValidatorAddr: srcValidatorAddr, DstValidatorAddr: dstValidatorAddr, @@ -107,7 +107,7 @@ func queryBonds(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string) ht return } - params := stake.NewQueryBondsParams(delegatorAddr, validatorAddr) + params := staking.NewQueryBondsParams(delegatorAddr, validatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -135,7 +135,7 @@ func queryDelegator(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string return } - params := stake.NewQueryDelegatorParams(delegatorAddr) + params := staking.NewQueryDelegatorParams(delegatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -163,7 +163,7 @@ func queryValidator(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string return } - params := stake.NewQueryValidatorParams(validatorAddr) + params := staking.NewQueryValidatorParams(validatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { diff --git a/x/stake/genesis.go b/x/staking/genesis.go similarity index 96% rename from x/stake/genesis.go rename to x/staking/genesis.go index 744226c2c5d6..62ee49efd449 100644 --- a/x/stake/genesis.go +++ b/x/staking/genesis.go @@ -1,4 +1,4 @@ -package stake +package staking import ( "fmt" @@ -8,7 +8,7 @@ import ( tmtypes "github.com/tendermint/tendermint/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // InitGenesis sets the pool and parameters for the provided keeper. For each @@ -33,7 +33,7 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) (res [ // Manually set indices for the first time keeper.SetValidatorByConsAddr(ctx, validator) keeper.SetValidatorByPowerIndex(ctx, validator) - keeper.OnValidatorCreated(ctx, validator.OperatorAddr) + keeper.AfterValidatorCreated(ctx, validator.OperatorAddr) // Set timeslice if necessary if validator.Status == sdk.Unbonding { @@ -42,8 +42,8 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) (res [ } for _, delegation := range data.Bonds { + keeper.BeforeDelegationCreated(ctx, delegation.DelegatorAddr, delegation.ValidatorAddr) keeper.SetDelegation(ctx, delegation) - keeper.OnDelegationCreated(ctx, delegation.DelegatorAddr, delegation.ValidatorAddr) } sort.SliceStable(data.UnbondingDelegations[:], func(i, j int) bool { diff --git a/x/stake/genesis_test.go b/x/staking/genesis_test.go similarity index 97% rename from x/stake/genesis_test.go rename to x/staking/genesis_test.go index f7c874b708c5..ac9174651729 100644 --- a/x/stake/genesis_test.go +++ b/x/staking/genesis_test.go @@ -1,4 +1,4 @@ -package stake +package staking import ( "fmt" @@ -12,8 +12,8 @@ import ( abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" - keep "github.com/cosmos/cosmos-sdk/x/stake/keeper" - "github.com/cosmos/cosmos-sdk/x/stake/types" + keep "github.com/cosmos/cosmos-sdk/x/staking/keeper" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) func TestInitGenesis(t *testing.T) { diff --git a/x/stake/handler.go b/x/staking/handler.go similarity index 96% rename from x/stake/handler.go rename to x/staking/handler.go index 408ca52a338e..a4c856f6f4c0 100644 --- a/x/stake/handler.go +++ b/x/staking/handler.go @@ -1,4 +1,4 @@ -package stake +package staking import ( "bytes" @@ -9,9 +9,9 @@ import ( tmtypes "github.com/tendermint/tendermint/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/keeper" - "github.com/cosmos/cosmos-sdk/x/stake/tags" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/keeper" + "github.com/cosmos/cosmos-sdk/x/staking/tags" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) func NewHandler(k keeper.Keeper) sdk.Handler { @@ -128,7 +128,7 @@ func handleMsgCreateValidator(ctx sdk.Context, msg types.MsgCreateValidator, k k k.SetValidatorByConsAddr(ctx, validator) k.SetNewValidatorByPowerIndex(ctx, validator) - k.OnValidatorCreated(ctx, validator.OperatorAddr) + k.AfterValidatorCreated(ctx, validator.OperatorAddr) // move coins from the msg.Address account to a (self-delegation) delegator account // the validator account and global shares are updated within here @@ -168,8 +168,9 @@ func handleMsgEditValidator(ctx sdk.Context, msg types.MsgEditValidator, k keepe if err != nil { return err.Result() } + + k.BeforeValidatorModified(ctx, msg.ValidatorAddr) validator.Commission = commission - k.OnValidatorModified(ctx, msg.ValidatorAddr) } k.SetValidator(ctx, validator) diff --git a/x/stake/handler_test.go b/x/staking/handler_test.go similarity index 99% rename from x/stake/handler_test.go rename to x/staking/handler_test.go index eb6e5f8fb70c..96f804fb4abc 100644 --- a/x/stake/handler_test.go +++ b/x/staking/handler_test.go @@ -1,4 +1,4 @@ -package stake +package staking import ( "testing" @@ -12,8 +12,8 @@ import ( tmtypes "github.com/tendermint/tendermint/types" sdk "github.com/cosmos/cosmos-sdk/types" - keep "github.com/cosmos/cosmos-sdk/x/stake/keeper" - "github.com/cosmos/cosmos-sdk/x/stake/types" + keep "github.com/cosmos/cosmos-sdk/x/staking/keeper" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) //______________________________________________________________________ diff --git a/x/stake/keeper/_store.md b/x/staking/keeper/_store.md similarity index 99% rename from x/stake/keeper/_store.md rename to x/staking/keeper/_store.md index d569389417c3..f6430c312b90 100644 --- a/x/stake/keeper/_store.md +++ b/x/staking/keeper/_store.md @@ -1,7 +1,7 @@ # Stores This document provided a bit more insight as to the purpose of several related -prefixed areas of the staking store which are accessed in `x/stake/keeper.go`. +prefixed areas of the staking store which are accessed in `x/staking/keeper.go`. # IAVL Store diff --git a/x/stake/keeper/delegation.go b/x/staking/keeper/delegation.go similarity index 95% rename from x/stake/keeper/delegation.go rename to x/staking/keeper/delegation.go index 926d5274af3b..63bd2cfb05ba 100644 --- a/x/stake/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -5,7 +5,7 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // return a specific delegation @@ -20,7 +20,7 @@ func (k Keeper) GetDelegation(ctx sdk.Context, return delegation, false } - delegation = types.MustUnmarshalDelegation(k.cdc, key, value) + delegation = types.MustUnmarshalDelegation(k.cdc, value) return delegation, true } @@ -31,7 +31,7 @@ func (k Keeper) GetAllDelegations(ctx sdk.Context) (delegations []types.Delegati defer iterator.Close() for ; iterator.Valid(); iterator.Next() { - delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Key(), iterator.Value()) + delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value()) delegations = append(delegations, delegation) } return delegations @@ -44,7 +44,7 @@ func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { - delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Key(), iterator.Value()) + delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value()) if delegation.GetValidatorAddr().Equals(valAddr) { delegations = append(delegations, delegation) } @@ -65,7 +65,7 @@ func (k Keeper) GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddres i := 0 for ; iterator.Valid() && i < int(maxRetrieve); iterator.Next() { - delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Key(), iterator.Value()) + delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value()) delegations[i] = delegation i++ } @@ -81,7 +81,7 @@ func (k Keeper) SetDelegation(ctx sdk.Context, delegation types.Delegation) { // remove a delegation from store func (k Keeper) RemoveDelegation(ctx sdk.Context, delegation types.Delegation) { - k.OnDelegationRemoved(ctx, delegation.DelegatorAddr, delegation.ValidatorAddr) + k.BeforeDelegationRemoved(ctx, delegation.DelegatorAddr, delegation.ValidatorAddr) store := ctx.KVStore(k.storeKey) store.Delete(GetDelegationKey(delegation.DelegatorAddr, delegation.ValidatorAddr)) } @@ -101,7 +101,7 @@ func (k Keeper) GetUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddres i := 0 for ; iterator.Valid() && i < int(maxRetrieve); iterator.Next() { - unbondingDelegation := types.MustUnmarshalUBD(k.cdc, iterator.Key(), iterator.Value()) + unbondingDelegation := types.MustUnmarshalUBD(k.cdc, iterator.Value()) unbondingDelegations[i] = unbondingDelegation i++ } @@ -119,7 +119,7 @@ func (k Keeper) GetUnbondingDelegation(ctx sdk.Context, return ubd, false } - ubd = types.MustUnmarshalUBD(k.cdc, key, value) + ubd = types.MustUnmarshalUBD(k.cdc, value) return ubd, true } @@ -132,7 +132,7 @@ func (k Keeper) GetUnbondingDelegationsFromValidator(ctx sdk.Context, valAddr sd for ; iterator.Valid(); iterator.Next() { key := GetUBDKeyFromValIndexKey(iterator.Key()) value := store.Get(key) - ubd := types.MustUnmarshalUBD(k.cdc, key, value) + ubd := types.MustUnmarshalUBD(k.cdc, value) ubds = append(ubds, ubd) } return ubds @@ -145,7 +145,7 @@ func (k Keeper) IterateUnbondingDelegations(ctx sdk.Context, fn func(index int64 defer iterator.Close() for i := int64(0); iterator.Valid(); iterator.Next() { - ubd := types.MustUnmarshalUBD(k.cdc, iterator.Key(), iterator.Value()) + ubd := types.MustUnmarshalUBD(k.cdc, iterator.Value()) if stop := fn(i, ubd); stop { break } @@ -235,7 +235,7 @@ func (k Keeper) GetRedelegations(ctx sdk.Context, delegator sdk.AccAddress, i := 0 for ; iterator.Valid() && i < int(maxRetrieve); iterator.Next() { - redelegation := types.MustUnmarshalRED(k.cdc, iterator.Key(), iterator.Value()) + redelegation := types.MustUnmarshalRED(k.cdc, iterator.Value()) redelegations[i] = redelegation i++ } @@ -253,7 +253,7 @@ func (k Keeper) GetRedelegation(ctx sdk.Context, return red, false } - red = types.MustUnmarshalRED(k.cdc, key, value) + red = types.MustUnmarshalRED(k.cdc, value) return red, true } @@ -266,7 +266,7 @@ func (k Keeper) GetRedelegationsFromValidator(ctx sdk.Context, valAddr sdk.ValAd for ; iterator.Valid(); iterator.Next() { key := GetREDKeyFromValSrcIndexKey(iterator.Key()) value := store.Get(key) - red := types.MustUnmarshalRED(k.cdc, key, value) + red := types.MustUnmarshalRED(k.cdc, value) reds = append(reds, red) } return reds @@ -305,7 +305,7 @@ func (k Keeper) IterateRedelegations(ctx sdk.Context, fn func(index int64, red t defer iterator.Close() for i := int64(0); iterator.Valid(); iterator.Next() { - red := types.MustUnmarshalRED(k.cdc, iterator.Key(), iterator.Value()) + red := types.MustUnmarshalRED(k.cdc, iterator.Value()) if stop := fn(i, red); stop { break } @@ -398,9 +398,9 @@ func (k Keeper) Delegate(ctx sdk.Context, delAddr sdk.AccAddress, bondAmt sdk.Co // call the appropriate hook if present if found { - k.OnDelegationSharesModified(ctx, delAddr, validator.OperatorAddr) + k.BeforeDelegationSharesModified(ctx, delAddr, validator.OperatorAddr) } else { - k.OnDelegationCreated(ctx, delAddr, validator.OperatorAddr) + k.BeforeDelegationCreated(ctx, delAddr, validator.OperatorAddr) } if subtractAccount { @@ -430,7 +430,7 @@ func (k Keeper) unbond(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValA return amount, types.ErrNoDelegatorForAddress(k.Codespace()) } - k.OnDelegationSharesModified(ctx, delAddr, valAddr) + k.BeforeDelegationSharesModified(ctx, delAddr, valAddr) // retrieve the amount to remove if delegation.Shares.LT(shares) { diff --git a/x/stake/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go similarity index 99% rename from x/stake/keeper/delegation_test.go rename to x/staking/keeper/delegation_test.go index 37545ab22722..7a00b3ee47ba 100644 --- a/x/stake/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -6,7 +6,7 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/x/staking/keeper/hooks.go b/x/staking/keeper/hooks.go new file mode 100644 index 000000000000..29c1966d7d79 --- /dev/null +++ b/x/staking/keeper/hooks.go @@ -0,0 +1,61 @@ +//nolint +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// Expose the hooks if present +func (k Keeper) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { + if k.hooks != nil { + k.hooks.AfterValidatorCreated(ctx, valAddr) + } +} + +func (k Keeper) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { + if k.hooks != nil { + k.hooks.BeforeValidatorModified(ctx, valAddr) + } +} + +func (k Keeper) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + if k.hooks != nil { + k.hooks.AfterValidatorRemoved(ctx, consAddr, valAddr) + } +} + +func (k Keeper) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + if k.hooks != nil { + k.hooks.AfterValidatorBonded(ctx, consAddr, valAddr) + } +} + +func (k Keeper) AfterValidatorPowerDidChange(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + if k.hooks != nil { + k.hooks.AfterValidatorPowerDidChange(ctx, consAddr, valAddr) + } +} + +func (k Keeper) AfterValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + if k.hooks != nil { + k.hooks.AfterValidatorBeginUnbonding(ctx, consAddr, valAddr) + } +} + +func (k Keeper) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + if k.hooks != nil { + k.hooks.BeforeDelegationCreated(ctx, delAddr, valAddr) + } +} + +func (k Keeper) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + if k.hooks != nil { + k.hooks.BeforeDelegationSharesModified(ctx, delAddr, valAddr) + } +} + +func (k Keeper) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + if k.hooks != nil { + k.hooks.BeforeDelegationRemoved(ctx, delAddr, valAddr) + } +} diff --git a/x/stake/keeper/keeper.go b/x/staking/keeper/keeper.go similarity index 98% rename from x/stake/keeper/keeper.go rename to x/staking/keeper/keeper.go index 93b75958d176..ea3527d5d633 100644 --- a/x/stake/keeper/keeper.go +++ b/x/staking/keeper/keeper.go @@ -8,12 +8,12 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) const aminoCacheSize = 500 -// keeper of the stake store +// keeper of the staking store type Keeper struct { storeKey sdk.StoreKey storeTKey sdk.StoreKey diff --git a/x/stake/keeper/keeper_test.go b/x/staking/keeper/keeper_test.go similarity index 95% rename from x/stake/keeper/keeper_test.go rename to x/staking/keeper/keeper_test.go index be45fc20c191..89ffe13d19ee 100644 --- a/x/stake/keeper/keeper_test.go +++ b/x/staking/keeper/keeper_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) func TestParams(t *testing.T) { diff --git a/x/stake/keeper/key.go b/x/staking/keeper/key.go similarity index 97% rename from x/stake/keeper/key.go rename to x/staking/keeper/key.go index 8c45f98813fb..6dbb053cf688 100644 --- a/x/stake/keeper/key.go +++ b/x/staking/keeper/key.go @@ -5,7 +5,7 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // TODO remove some of these prefixes once have working multistore @@ -14,7 +14,7 @@ import ( var ( // Keys for store prefixes // TODO DEPRECATED: delete in next release and reorder keys - // ParamKey = []byte{0x00} // key for parameters relating to staking + // ParamKey = []byte{0x00} // key for parameters relating to stake PoolKey = []byte{0x01} // key for the staking pools // Last* values are const during a block. @@ -40,7 +40,7 @@ var ( const maxDigitsForAccount = 12 // ~220,000,000 atoms created at launch // gets the key for the validator with address -// VALUE: stake/types.Validator +// VALUE: staking/types.Validator func GetValidatorKey(operatorAddr sdk.ValAddress) []byte { return append(ValidatorsKey, operatorAddr.Bytes()...) } @@ -120,7 +120,7 @@ func GetValidatorQueueTimeKey(timestamp time.Time) []byte { //______________________________________________________________________________ // gets the key for delegator bond with validator -// VALUE: stake/types.Delegation +// VALUE: staking/types.Delegation func GetDelegationKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { return append(GetDelegationsKey(delAddr), valAddr.Bytes()...) } @@ -133,7 +133,7 @@ func GetDelegationsKey(delAddr sdk.AccAddress) []byte { //______________________________________________________________________________ // gets the key for an unbonding delegation by delegator and validator addr -// VALUE: stake/types.UnbondingDelegation +// VALUE: staking/types.UnbondingDelegation func GetUBDKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte { return append( GetUBDsKey(delAddr.Bytes()), @@ -178,7 +178,7 @@ func GetUnbondingDelegationTimeKey(timestamp time.Time) []byte { //________________________________________________________________________________ // gets the key for a redelegation -// VALUE: stake/types.RedelegationKey +// VALUE: staking/types.RedelegationKey func GetREDKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) []byte { key := make([]byte, 1+sdk.AddrLen*3) diff --git a/x/stake/keeper/key_test.go b/x/staking/keeper/key_test.go similarity index 98% rename from x/stake/keeper/key_test.go rename to x/staking/keeper/key_test.go index 0645fd85bb97..9f80062ac482 100644 --- a/x/stake/keeper/key_test.go +++ b/x/staking/keeper/key_test.go @@ -9,7 +9,7 @@ import ( "github.com/tendermint/tendermint/crypto/ed25519" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( diff --git a/x/stake/keeper/params.go b/x/staking/keeper/params.go similarity index 90% rename from x/stake/keeper/params.go rename to x/staking/keeper/params.go index b62a7688fbb8..2d3fdf296e10 100644 --- a/x/stake/keeper/params.go +++ b/x/staking/keeper/params.go @@ -5,15 +5,15 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // Default parameter namespace const ( - DefaultParamspace = "stake" + DefaultParamspace = "staking" ) -// ParamTable for stake module +// ParamTable for staking module func ParamTypeTable() params.TypeTable { return params.NewTypeTable().RegisterParamSet(&types.Params{}) } diff --git a/x/stake/keeper/query_utils.go b/x/staking/keeper/query_utils.go similarity index 90% rename from x/stake/keeper/query_utils.go rename to x/staking/keeper/query_utils.go index 699ae8ccff98..872059f1108a 100644 --- a/x/stake/keeper/query_utils.go +++ b/x/staking/keeper/query_utils.go @@ -2,7 +2,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // Return all validators that a delegator is bonded to. If maxRetrieve is supplied, the respective amount will be returned. @@ -17,8 +17,7 @@ func (k Keeper) GetDelegatorValidators(ctx sdk.Context, delegatorAddr sdk.AccAdd i := 0 for ; iterator.Valid() && i < int(maxRetrieve); iterator.Next() { - addr := iterator.Key() - delegation := types.MustUnmarshalDelegation(k.cdc, addr, iterator.Value()) + delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value()) validator, found := k.GetValidator(ctx, delegation.ValidatorAddr) if !found { @@ -59,7 +58,7 @@ func (k Keeper) GetAllDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAdd i := 0 for ; iterator.Valid(); iterator.Next() { - delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Key(), iterator.Value()) + delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value()) delegations = append(delegations, delegation) i++ } @@ -77,7 +76,7 @@ func (k Keeper) GetAllUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAdd i := 0 for ; iterator.Valid(); iterator.Next() { - unbondingDelegation := types.MustUnmarshalUBD(k.cdc, iterator.Key(), iterator.Value()) + unbondingDelegation := types.MustUnmarshalUBD(k.cdc, iterator.Value()) unbondingDelegations = append(unbondingDelegations, unbondingDelegation) i++ } @@ -95,7 +94,7 @@ func (k Keeper) GetAllRedelegations(ctx sdk.Context, delegator sdk.AccAddress, s dstValFilter := !(dstValAddress.Empty() || dstValAddress == nil) for ; iterator.Valid(); iterator.Next() { - redelegation := types.MustUnmarshalRED(k.cdc, iterator.Key(), iterator.Value()) + redelegation := types.MustUnmarshalRED(k.cdc, iterator.Value()) if srcValFilter && !(srcValAddress.Equals(redelegation.ValidatorSrcAddr)) { continue } diff --git a/x/stake/keeper/sdk_types.go b/x/staking/keeper/sdk_types.go similarity index 94% rename from x/stake/keeper/sdk_types.go rename to x/staking/keeper/sdk_types.go index dcef5c6d656e..265ee4c79843 100644 --- a/x/stake/keeper/sdk_types.go +++ b/x/staking/keeper/sdk_types.go @@ -4,7 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // Implements ValidatorSet @@ -16,8 +16,7 @@ func (k Keeper) IterateValidators(ctx sdk.Context, fn func(index int64, validato iterator := sdk.KVStorePrefixIterator(store, ValidatorsKey) i := int64(0) for ; iterator.Valid(); iterator.Next() { - addr := iterator.Key()[1:] - validator := types.MustUnmarshalValidator(k.cdc, addr, iterator.Value()) + validator := types.MustUnmarshalValidator(k.cdc, iterator.Value()) stop := fn(i, validator) // XXX is this safe will the validator unexposed fields be able to get written to? if stop { break @@ -136,7 +135,7 @@ func (k Keeper) IterateDelegations(ctx sdk.Context, delAddr sdk.AccAddress, delegatorPrefixKey := GetDelegationsKey(delAddr) iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) //smallest to largest for i := int64(0); iterator.Valid(); iterator.Next() { - del := types.MustUnmarshalDelegation(k.cdc, iterator.Key(), iterator.Value()) + del := types.MustUnmarshalDelegation(k.cdc, iterator.Value()) stop := fn(i, del) if stop { break diff --git a/x/stake/keeper/slash.go b/x/staking/keeper/slash.go similarity index 97% rename from x/stake/keeper/slash.go rename to x/staking/keeper/slash.go index 6d22c82fc986..afe58742c0fa 100644 --- a/x/stake/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -4,7 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/x/stake/types" + types "github.com/cosmos/cosmos-sdk/x/staking/types" ) // Slash a validator for an infraction committed at a known height @@ -22,7 +22,7 @@ import ( // Infraction committed at the current height or at a past height, // not at a height in the future func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeight int64, power int64, slashFactor sdk.Dec) { - logger := ctx.Logger().With("module", "x/stake") + logger := ctx.Logger().With("module", "x/staking") if slashFactor.LT(sdk.ZeroDec()) { panic(fmt.Errorf("attempted to slash with a negative slash factor: %v", slashFactor)) @@ -53,7 +53,7 @@ func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeigh } operatorAddress := validator.GetOperator() - k.OnValidatorModified(ctx, operatorAddress) + k.BeforeValidatorModified(ctx, operatorAddress) // Track remaining slash amount for the validator // This will decrease when we slash unbondings and @@ -123,7 +123,7 @@ func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeigh func (k Keeper) Jail(ctx sdk.Context, consAddr sdk.ConsAddress) { validator := k.mustGetValidatorByConsAddr(ctx, consAddr) k.jailValidator(ctx, validator) - logger := ctx.Logger().With("module", "x/stake") + logger := ctx.Logger().With("module", "x/staking") logger.Info(fmt.Sprintf("validator %s jailed", consAddr)) // TODO Return event(s), blocked on https://github.com/tendermint/tendermint/pull/1803 return @@ -133,7 +133,7 @@ func (k Keeper) Jail(ctx sdk.Context, consAddr sdk.ConsAddress) { func (k Keeper) Unjail(ctx sdk.Context, consAddr sdk.ConsAddress) { validator := k.mustGetValidatorByConsAddr(ctx, consAddr) k.unjailValidator(ctx, validator) - logger := ctx.Logger().With("module", "x/stake") + logger := ctx.Logger().With("module", "x/staking") logger.Info(fmt.Sprintf("validator %s unjailed", consAddr)) // TODO Return event(s), blocked on https://github.com/tendermint/tendermint/pull/1803 return diff --git a/x/stake/keeper/slash_test.go b/x/staking/keeper/slash_test.go similarity index 99% rename from x/stake/keeper/slash_test.go rename to x/staking/keeper/slash_test.go index 294bf2fe6c7d..a39b5b0a4b12 100644 --- a/x/stake/keeper/slash_test.go +++ b/x/staking/keeper/slash_test.go @@ -9,7 +9,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // TODO integrate with test_common.go helper (CreateTestInput) @@ -82,7 +82,7 @@ func TestSlashUnbondingDelegation(t *testing.T) { } keeper.SetUnbondingDelegation(ctx, ubd) - // unbonding started prior to the infraction height, stake didn't contribute + // unbonding started prior to the infraction height, stakw didn't contribute slashAmount := keeper.slashUnbondingDelegation(ctx, ubd, 1, fraction) require.Equal(t, int64(0), slashAmount.Int64()) diff --git a/x/stake/keeper/test_common.go b/x/staking/keeper/test_common.go similarity index 89% rename from x/stake/keeper/test_common.go rename to x/staking/keeper/test_common.go index 10d856f05b7b..04323b2d590c 100644 --- a/x/stake/keeper/test_common.go +++ b/x/staking/keeper/test_common.go @@ -22,7 +22,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // dummy addresses used for testing @@ -60,15 +60,15 @@ func MakeTestCodec() *codec.Codec { // Register Msgs cdc.RegisterInterface((*sdk.Msg)(nil), nil) - cdc.RegisterConcrete(bank.MsgSend{}, "test/stake/Send", nil) - cdc.RegisterConcrete(types.MsgCreateValidator{}, "test/stake/CreateValidator", nil) - cdc.RegisterConcrete(types.MsgEditValidator{}, "test/stake/EditValidator", nil) - cdc.RegisterConcrete(types.MsgBeginUnbonding{}, "test/stake/BeginUnbonding", nil) - cdc.RegisterConcrete(types.MsgBeginRedelegate{}, "test/stake/BeginRedelegate", nil) + cdc.RegisterConcrete(bank.MsgSend{}, "test/staking/Send", nil) + cdc.RegisterConcrete(types.MsgCreateValidator{}, "test/staking/CreateValidator", nil) + cdc.RegisterConcrete(types.MsgEditValidator{}, "test/staking/EditValidator", nil) + cdc.RegisterConcrete(types.MsgBeginUnbonding{}, "test/staking/BeginUnbonding", nil) + cdc.RegisterConcrete(types.MsgBeginRedelegate{}, "test/staking/BeginRedelegate", nil) // Register AppAccount cdc.RegisterInterface((*auth.Account)(nil), nil) - cdc.RegisterConcrete(&auth.BaseAccount{}, "test/stake/Account", nil) + cdc.RegisterConcrete(&auth.BaseAccount{}, "test/staking/Account", nil) codec.RegisterCrypto(cdc) return cdc @@ -77,16 +77,16 @@ func MakeTestCodec() *codec.Codec { // hogpodge of all sorts of input required for testing func CreateTestInput(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context, auth.AccountKeeper, Keeper) { - keyStake := sdk.NewKVStoreKey(types.StoreKey) - tkeyStake := sdk.NewTransientStoreKey(types.TStoreKey) + keyStaking := sdk.NewKVStoreKey(types.StoreKey) + tkeyStaking := sdk.NewTransientStoreKey(types.TStoreKey) keyAcc := sdk.NewKVStoreKey(auth.StoreKey) keyParams := sdk.NewKVStoreKey(params.StoreKey) tkeyParams := sdk.NewTransientStoreKey(params.TStoreKey) db := dbm.NewMemDB() ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(tkeyStake, sdk.StoreTypeTransient, nil) - ms.MountStoreWithDB(keyStake, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(tkeyStaking, sdk.StoreTypeTransient, nil) + ms.MountStoreWithDB(keyStaking, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keyAcc, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) @@ -108,7 +108,7 @@ func CreateTestInput(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context ck := bank.NewBaseKeeper(accountKeeper) - keeper := NewKeeper(cdc, keyStake, tkeyStake, ck, pk.Subspace(DefaultParamspace), types.DefaultCodespace) + keeper := NewKeeper(cdc, keyStaking, tkeyStaking, ck, pk.Subspace(DefaultParamspace), types.DefaultCodespace) keeper.SetPool(ctx, types.InitialPool()) keeper.SetParams(ctx, types.DefaultParams()) diff --git a/x/stake/keeper/val_state_change.go b/x/staking/keeper/val_state_change.go similarity index 96% rename from x/stake/keeper/val_state_change.go rename to x/staking/keeper/val_state_change.go index 85d38c943756..84d13d655cbd 100644 --- a/x/stake/keeper/val_state_change.go +++ b/x/staking/keeper/val_state_change.go @@ -8,7 +8,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // Apply and return accumulated updates to the bonded validator set. Also, @@ -80,7 +80,7 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab // Assert that the validator had updated its ValidatorDistInfo.FeePoolWithdrawalHeight. // This hook is extremely useful, otherwise lazy accum bugs will be difficult to solve. if k.hooks != nil { - k.hooks.OnValidatorPowerDidChange(ctx, validator.ConsAddress(), valAddr) + k.hooks.AfterValidatorPowerDidChange(ctx, validator.ConsAddress(), valAddr) } // set validator power on lookup index. @@ -196,7 +196,7 @@ func (k Keeper) bondValidator(ctx sdk.Context, validator types.Validator) types. // call the bond hook if present if k.hooks != nil { - k.hooks.OnValidatorBonded(ctx, validator.ConsAddress(), validator.OperatorAddr) + k.hooks.AfterValidatorBonded(ctx, validator.ConsAddress(), validator.OperatorAddr) } return validator @@ -231,7 +231,7 @@ func (k Keeper) beginUnbondingValidator(ctx sdk.Context, validator types.Validat // call the unbond hook if present if k.hooks != nil { - k.hooks.OnValidatorBeginUnbonding(ctx, validator.ConsAddress(), validator.OperatorAddr) + k.hooks.AfterValidatorBeginUnbonding(ctx, validator.ConsAddress(), validator.OperatorAddr) } return validator diff --git a/x/stake/keeper/validator.go b/x/staking/keeper/validator.go similarity index 96% rename from x/stake/keeper/validator.go rename to x/staking/keeper/validator.go index c69a7e63cdd7..56467d531691 100644 --- a/x/stake/keeper/validator.go +++ b/x/staking/keeper/validator.go @@ -6,7 +6,7 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // Cache the amino decoding of validators, as it can be the case that repeated slashing calls @@ -36,7 +36,7 @@ func (k Keeper) GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator ty } // amino bytes weren't found in cache, so amino unmarshal and add it to the cache - validator = types.MustUnmarshalValidator(k.cdc, addr, value) + validator = types.MustUnmarshalValidator(k.cdc, value) cachedVal := cachedValidator{validator, strValue} k.validatorCache[strValue] = cachedValidator{validator, strValue} k.validatorCacheList.PushBack(cachedVal) @@ -47,7 +47,7 @@ func (k Keeper) GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator ty delete(k.validatorCache, valToRemove.marshalled) } - validator = types.MustUnmarshalValidator(k.cdc, addr, value) + validator = types.MustUnmarshalValidator(k.cdc, value) return validator, true } @@ -202,7 +202,7 @@ func (k Keeper) RemoveValidator(ctx sdk.Context, address sdk.ValAddress) { // call hook if present if k.hooks != nil { - k.hooks.OnValidatorRemoved(ctx, validator.ConsAddress(), validator.OperatorAddr) + k.hooks.AfterValidatorRemoved(ctx, validator.ConsAddress(), validator.OperatorAddr) } } @@ -217,8 +217,7 @@ func (k Keeper) GetAllValidators(ctx sdk.Context) (validators []types.Validator) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { - addr := iterator.Key()[1:] - validator := types.MustUnmarshalValidator(k.cdc, addr, iterator.Value()) + validator := types.MustUnmarshalValidator(k.cdc, iterator.Value()) validators = append(validators, validator) } return validators @@ -234,8 +233,7 @@ func (k Keeper) GetValidators(ctx sdk.Context, maxRetrieve uint16) (validators [ i := 0 for ; iterator.Valid() && i < int(maxRetrieve); iterator.Next() { - addr := iterator.Key()[1:] - validator := types.MustUnmarshalValidator(k.cdc, addr, iterator.Value()) + validator := types.MustUnmarshalValidator(k.cdc, iterator.Value()) validators[i] = validator i++ } diff --git a/x/stake/keeper/validator_test.go b/x/staking/keeper/validator_test.go similarity index 99% rename from x/stake/keeper/validator_test.go rename to x/staking/keeper/validator_test.go index 8d23a80f97a1..69b0782225c7 100644 --- a/x/stake/keeper/validator_test.go +++ b/x/staking/keeper/validator_test.go @@ -8,7 +8,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/x/stake/querier/querier.go b/x/staking/querier/querier.go similarity index 92% rename from x/stake/querier/querier.go rename to x/staking/querier/querier.go index 14ca42d67624..4d8ad619cd3b 100644 --- a/x/stake/querier/querier.go +++ b/x/staking/querier/querier.go @@ -5,8 +5,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - keep "github.com/cosmos/cosmos-sdk/x/stake/keeper" - "github.com/cosmos/cosmos-sdk/x/stake/types" + keep "github.com/cosmos/cosmos-sdk/x/staking/keeper" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // query endpoints supported by the staking Querier @@ -58,16 +58,16 @@ func NewQuerier(k keep.Keeper, cdc *codec.Codec) sdk.Querier { case QueryParameters: return queryParameters(ctx, cdc, k) default: - return nil, sdk.ErrUnknownRequest("unknown stake query endpoint") + return nil, sdk.ErrUnknownRequest("unknown staking query endpoint") } } } // defines the params for the following queries: -// - 'custom/stake/delegatorDelegations' -// - 'custom/stake/delegatorUnbondingDelegations' -// - 'custom/stake/delegatorRedelegations' -// - 'custom/stake/delegatorValidators' +// - 'custom/staking/delegatorDelegations' +// - 'custom/staking/delegatorUnbondingDelegations' +// - 'custom/staking/delegatorRedelegations' +// - 'custom/staking/delegatorValidators' type QueryDelegatorParams struct { DelegatorAddr sdk.AccAddress } @@ -79,10 +79,10 @@ func NewQueryDelegatorParams(delegatorAddr sdk.AccAddress) QueryDelegatorParams } // defines the params for the following queries: -// - 'custom/stake/validator' -// - 'custom/stake/validatorDelegations' -// - 'custom/stake/validatorUnbondingDelegations' -// - 'custom/stake/validatorRedelegations' +// - 'custom/staking/validator' +// - 'custom/staking/validatorDelegations' +// - 'custom/staking/validatorUnbondingDelegations' +// - 'custom/staking/validatorRedelegations' type QueryValidatorParams struct { ValidatorAddr sdk.ValAddress } @@ -94,9 +94,9 @@ func NewQueryValidatorParams(validatorAddr sdk.ValAddress) QueryValidatorParams } // defines the params for the following queries: -// - 'custom/stake/delegation' -// - 'custom/stake/unbondingDelegation' -// - 'custom/stake/delegatorValidator' +// - 'custom/staking/delegation' +// - 'custom/staking/unbondingDelegation' +// - 'custom/staking/delegatorValidator' type QueryBondsParams struct { DelegatorAddr sdk.AccAddress ValidatorAddr sdk.ValAddress @@ -110,7 +110,7 @@ func NewQueryBondsParams(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddr } // defines the params for the following queries: -// - 'custom/stake/redelegation' +// - 'custom/staking/redelegation' type QueryRedelegationParams struct { DelegatorAddr sdk.AccAddress SrcValidatorAddr sdk.ValAddress @@ -126,8 +126,8 @@ func NewQueryRedelegationParams(delegatorAddr sdk.AccAddress, srcValidatorAddr s } func queryValidators(ctx sdk.Context, cdc *codec.Codec, k keep.Keeper) (res []byte, err sdk.Error) { - stakeParams := k.GetParams(ctx) - validators := k.GetValidators(ctx, stakeParams.MaxValidators) + stakingParams := k.GetParams(ctx) + validators := k.GetValidators(ctx, stakingParams.MaxValidators) res, errRes := codec.MarshalJSONIndent(cdc, validators) if err != nil { @@ -227,14 +227,14 @@ func queryDelegatorUnbondingDelegations(ctx sdk.Context, cdc *codec.Codec, req a func queryDelegatorValidators(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { var params QueryDelegatorParams - stakeParams := k.GetParams(ctx) + stakingParams := k.GetParams(ctx) errRes := cdc.UnmarshalJSON(req.Data, ¶ms) if errRes != nil { return []byte{}, sdk.ErrUnknownAddress("") } - validators := k.GetDelegatorValidators(ctx, params.DelegatorAddr, stakeParams.MaxValidators) + validators := k.GetDelegatorValidators(ctx, params.DelegatorAddr, stakingParams.MaxValidators) res, errRes = codec.MarshalJSONIndent(cdc, validators) if errRes != nil { diff --git a/x/stake/querier/querier_test.go b/x/staking/querier/querier_test.go similarity index 94% rename from x/stake/querier/querier_test.go rename to x/staking/querier/querier_test.go index 5541cb81c6eb..ab9f243809b8 100644 --- a/x/stake/querier/querier_test.go +++ b/x/staking/querier/querier_test.go @@ -8,8 +8,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - keep "github.com/cosmos/cosmos-sdk/x/stake/keeper" - "github.com/cosmos/cosmos-sdk/x/stake/types" + keep "github.com/cosmos/cosmos-sdk/x/staking/keeper" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( @@ -57,7 +57,7 @@ func TestNewQuerier(t *testing.T) { bz, errRes := cdc.MarshalJSON(queryValParams) require.Nil(t, errRes) - query.Path = "/custom/stake/validator" + query.Path = "/custom/staking/validator" query.Data = bz _, err = querier(ctx, []string{"validator"}, query) @@ -73,7 +73,7 @@ func TestNewQuerier(t *testing.T) { bz, errRes = cdc.MarshalJSON(queryDelParams) require.Nil(t, errRes) - query.Path = "/custom/stake/validator" + query.Path = "/custom/staking/validator" query.Data = bz _, err = querier(ctx, []string{"delegatorDelegations"}, query) @@ -150,7 +150,7 @@ func TestQueryValidators(t *testing.T) { require.Nil(t, errRes) query := abci.RequestQuery{ - Path: "/custom/stake/validator", + Path: "/custom/staking/validator", Data: bz, } res, err = queryValidator(ctx, cdc, query, keeper) @@ -188,7 +188,7 @@ func TestQueryDelegation(t *testing.T) { require.Nil(t, errRes) query := abci.RequestQuery{ - Path: "/custom/stake/delegatorValidators", + Path: "/custom/staking/delegatorValidators", Data: bz, } @@ -216,7 +216,7 @@ func TestQueryDelegation(t *testing.T) { require.Nil(t, errRes) query = abci.RequestQuery{ - Path: "/custom/stake/delegatorValidator", + Path: "/custom/staking/delegatorValidator", Data: bz, } @@ -238,7 +238,7 @@ func TestQueryDelegation(t *testing.T) { // Query delegation query = abci.RequestQuery{ - Path: "/custom/stake/delegation", + Path: "/custom/staking/delegation", Data: bz, } @@ -257,7 +257,7 @@ func TestQueryDelegation(t *testing.T) { // Query Delegator Delegations query = abci.RequestQuery{ - Path: "/custom/stake/delegatorDelegations", + Path: "/custom/staking/delegatorDelegations", Data: bz, } @@ -282,7 +282,7 @@ func TestQueryDelegation(t *testing.T) { require.Nil(t, errRes) query = abci.RequestQuery{ - Path: "custom/stake/validatorDelegations", + Path: "custom/staking/validatorDelegations", Data: bz, } @@ -303,7 +303,7 @@ func TestQueryDelegation(t *testing.T) { require.Nil(t, errRes) query = abci.RequestQuery{ - Path: "/custom/stake/unbondingDelegation", + Path: "/custom/staking/unbondingDelegation", Data: bz, } @@ -328,7 +328,7 @@ func TestQueryDelegation(t *testing.T) { // Query Delegator Delegations query = abci.RequestQuery{ - Path: "/custom/stake/delegatorUnbondingDelegations", + Path: "/custom/staking/delegatorUnbondingDelegations", Data: bz, } @@ -354,7 +354,7 @@ func TestQueryDelegation(t *testing.T) { require.Nil(t, errRes) query = abci.RequestQuery{ - Path: "/custom/stake/redelegations", + Path: "/custom/staking/redelegations", Data: bz, } @@ -393,7 +393,7 @@ func TestQueryRedelegations(t *testing.T) { require.Nil(t, errRes) query := abci.RequestQuery{ - Path: "/custom/stake/redelegations", + Path: "/custom/staking/redelegations", Data: bz, } @@ -412,7 +412,7 @@ func TestQueryRedelegations(t *testing.T) { require.Nil(t, errRes) query = abci.RequestQuery{ - Path: "/custom/stake/redelegations", + Path: "/custom/staking/redelegations", Data: bz, } diff --git a/x/stake/simulation/invariants.go b/x/staking/simulation/invariants.go similarity index 82% rename from x/stake/simulation/invariants.go rename to x/staking/simulation/invariants.go index 52775d268cc6..1bba6ccb23d1 100644 --- a/x/stake/simulation/invariants.go +++ b/x/staking/simulation/invariants.go @@ -9,14 +9,14 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/mock/simulation" - "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/cosmos/cosmos-sdk/x/stake/keeper" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/keeper" + stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) -// AllInvariants runs all invariants of the stake module. +// AllInvariants runs all invariants of the staking module. // Currently: total supply, positive power -func AllInvariants(ck bank.Keeper, k stake.Keeper, +func AllInvariants(ck bank.Keeper, k staking.Keeper, f auth.FeeCollectionKeeper, d distribution.Keeper, am auth.AccountKeeper) simulation.Invariant { @@ -47,7 +47,7 @@ func AllInvariants(ck bank.Keeper, k stake.Keeper, // SupplyInvariants checks that the total supply reflects all held loose tokens, bonded tokens, and unbonding delegations // nolint: unparam -func SupplyInvariants(ck bank.Keeper, k stake.Keeper, +func SupplyInvariants(ck bank.Keeper, k staking.Keeper, f auth.FeeCollectionKeeper, d distribution.Keeper, am auth.AccountKeeper) simulation.Invariant { return func(ctx sdk.Context) error { pool := k.GetPool(ctx) @@ -55,10 +55,10 @@ func SupplyInvariants(ck bank.Keeper, k stake.Keeper, loose := sdk.ZeroDec() bonded := sdk.ZeroDec() am.IterateAccounts(ctx, func(acc auth.Account) bool { - loose = loose.Add(sdk.NewDecFromInt(acc.GetCoins().AmountOf(stakeTypes.DefaultBondDenom))) + loose = loose.Add(sdk.NewDecFromInt(acc.GetCoins().AmountOf(stakingTypes.DefaultBondDenom))) return false }) - k.IterateUnbondingDelegations(ctx, func(_ int64, ubd stake.UnbondingDelegation) bool { + k.IterateUnbondingDelegations(ctx, func(_ int64, ubd staking.UnbondingDelegation) bool { loose = loose.Add(sdk.NewDecFromInt(ubd.Balance.Amount)) return false }) @@ -75,19 +75,19 @@ func SupplyInvariants(ck bank.Keeper, k stake.Keeper, feePool := d.GetFeePool(ctx) // add outstanding fees - loose = loose.Add(sdk.NewDecFromInt(f.GetCollectedFees(ctx).AmountOf(stakeTypes.DefaultBondDenom))) + loose = loose.Add(sdk.NewDecFromInt(f.GetCollectedFees(ctx).AmountOf(stakingTypes.DefaultBondDenom))) // add community pool - loose = loose.Add(feePool.CommunityPool.AmountOf(stakeTypes.DefaultBondDenom)) + loose = loose.Add(feePool.CommunityPool.AmountOf(stakingTypes.DefaultBondDenom)) // add validator distribution pool - loose = loose.Add(feePool.ValPool.AmountOf(stakeTypes.DefaultBondDenom)) + loose = loose.Add(feePool.ValPool.AmountOf(stakingTypes.DefaultBondDenom)) // add validator distribution commission and yet-to-be-withdrawn-by-delegators d.IterateValidatorDistInfos(ctx, func(_ int64, distInfo distribution.ValidatorDistInfo) (stop bool) { - loose = loose.Add(distInfo.DelPool.AmountOf(stakeTypes.DefaultBondDenom)) - loose = loose.Add(distInfo.ValCommission.AmountOf(stakeTypes.DefaultBondDenom)) + loose = loose.Add(distInfo.DelPool.AmountOf(stakingTypes.DefaultBondDenom)) + loose = loose.Add(distInfo.ValCommission.AmountOf(stakingTypes.DefaultBondDenom)) return false }, ) @@ -112,7 +112,7 @@ func SupplyInvariants(ck bank.Keeper, k stake.Keeper, } // NonNegativePowerInvariant checks that all stored validators have >= 0 power. -func NonNegativePowerInvariant(k stake.Keeper) simulation.Invariant { +func NonNegativePowerInvariant(k staking.Keeper) simulation.Invariant { return func(ctx sdk.Context) error { iterator := k.ValidatorsPowerStoreIterator(ctx) @@ -139,7 +139,7 @@ func NonNegativePowerInvariant(k stake.Keeper) simulation.Invariant { } // PositiveDelegationInvariant checks that all stored delegations have > 0 shares. -func PositiveDelegationInvariant(k stake.Keeper) simulation.Invariant { +func PositiveDelegationInvariant(k staking.Keeper) simulation.Invariant { return func(ctx sdk.Context) error { delegations := k.GetAllDelegations(ctx) for _, delegation := range delegations { @@ -158,7 +158,7 @@ func PositiveDelegationInvariant(k stake.Keeper) simulation.Invariant { // DelegatorSharesInvariant checks whether all the delegator shares which persist // in the delegator object add up to the correct total delegator shares // amount stored in each validator -func DelegatorSharesInvariant(k stake.Keeper) simulation.Invariant { +func DelegatorSharesInvariant(k staking.Keeper) simulation.Invariant { return func(ctx sdk.Context) error { validators := k.GetAllValidators(ctx) for _, validator := range validators { diff --git a/x/stake/simulation/msgs.go b/x/staking/simulation/msgs.go similarity index 82% rename from x/stake/simulation/msgs.go rename to x/staking/simulation/msgs.go index 9fa469d6ca5e..473681cc0707 100644 --- a/x/stake/simulation/msgs.go +++ b/x/staking/simulation/msgs.go @@ -8,24 +8,24 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/mock/simulation" - "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/cosmos/cosmos-sdk/x/stake/keeper" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/keeper" ) // SimulateMsgCreateValidator -func SimulateMsgCreateValidator(m auth.AccountKeeper, k stake.Keeper) simulation.Operation { - handler := stake.NewHandler(k) +func SimulateMsgCreateValidator(m auth.AccountKeeper, k staking.Keeper) simulation.Operation { + handler := staking.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) ( action string, fOp []simulation.FutureOperation, err error) { denom := k.GetParams(ctx).BondDenom - description := stake.Description{ + description := staking.Description{ Moniker: simulation.RandStringOfLength(r, 10), } maxCommission := sdk.NewDecWithPrec(r.Int63n(1000), 3) - commission := stake.NewCommissionMsg( + commission := staking.NewCommissionMsg( simulation.RandomDecAmount(r, maxCommission), maxCommission, simulation.RandomDecAmount(r, maxCommission), @@ -42,7 +42,7 @@ func SimulateMsgCreateValidator(m auth.AccountKeeper, k stake.Keeper) simulation return "no-operation", nil, nil } - msg := stake.MsgCreateValidator{ + msg := staking.MsgCreateValidator{ Description: description, Commission: commission, ValidatorAddr: address, @@ -61,7 +61,7 @@ func SimulateMsgCreateValidator(m auth.AccountKeeper, k stake.Keeper) simulation write() } - event(fmt.Sprintf("stake/MsgCreateValidator/%v", result.IsOK())) + event(fmt.Sprintf("staking/MsgCreateValidator/%v", result.IsOK())) // require.True(t, result.IsOK(), "expected OK result but instead got %v", result) action = fmt.Sprintf("TestMsgCreateValidator: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) @@ -70,13 +70,13 @@ func SimulateMsgCreateValidator(m auth.AccountKeeper, k stake.Keeper) simulation } // SimulateMsgEditValidator -func SimulateMsgEditValidator(k stake.Keeper) simulation.Operation { - handler := stake.NewHandler(k) +func SimulateMsgEditValidator(k staking.Keeper) simulation.Operation { + handler := staking.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) ( action string, fOp []simulation.FutureOperation, err error) { - description := stake.Description{ + description := staking.Description{ Moniker: simulation.RandStringOfLength(r, 10), Identity: simulation.RandStringOfLength(r, 10), Website: simulation.RandStringOfLength(r, 10), @@ -87,7 +87,7 @@ func SimulateMsgEditValidator(k stake.Keeper) simulation.Operation { address := val.GetOperator() newCommissionRate := simulation.RandomDecAmount(r, val.Commission.MaxRate) - msg := stake.MsgEditValidator{ + msg := staking.MsgEditValidator{ Description: description, ValidatorAddr: address, CommissionRate: &newCommissionRate, @@ -102,15 +102,15 @@ func SimulateMsgEditValidator(k stake.Keeper) simulation.Operation { if result.IsOK() { write() } - event(fmt.Sprintf("stake/MsgEditValidator/%v", result.IsOK())) + event(fmt.Sprintf("staking/MsgEditValidator/%v", result.IsOK())) action = fmt.Sprintf("TestMsgEditValidator: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) return action, nil, nil } } // SimulateMsgDelegate -func SimulateMsgDelegate(m auth.AccountKeeper, k stake.Keeper) simulation.Operation { - handler := stake.NewHandler(k) +func SimulateMsgDelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Operation { + handler := staking.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) ( action string, fOp []simulation.FutureOperation, err error) { @@ -127,7 +127,7 @@ func SimulateMsgDelegate(m auth.AccountKeeper, k stake.Keeper) simulation.Operat if amount.Equal(sdk.ZeroInt()) { return "no-operation", nil, nil } - msg := stake.MsgDelegate{ + msg := staking.MsgDelegate{ DelegatorAddr: delegatorAddress, ValidatorAddr: validatorAddress, Delegation: sdk.NewCoin(denom, amount), @@ -140,15 +140,15 @@ func SimulateMsgDelegate(m auth.AccountKeeper, k stake.Keeper) simulation.Operat if result.IsOK() { write() } - event(fmt.Sprintf("stake/MsgDelegate/%v", result.IsOK())) + event(fmt.Sprintf("staking/MsgDelegate/%v", result.IsOK())) action = fmt.Sprintf("TestMsgDelegate: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) return action, nil, nil } } // SimulateMsgBeginUnbonding -func SimulateMsgBeginUnbonding(m auth.AccountKeeper, k stake.Keeper) simulation.Operation { - handler := stake.NewHandler(k) +func SimulateMsgBeginUnbonding(m auth.AccountKeeper, k staking.Keeper) simulation.Operation { + handler := staking.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) ( action string, fOp []simulation.FutureOperation, err error) { @@ -165,7 +165,7 @@ func SimulateMsgBeginUnbonding(m auth.AccountKeeper, k stake.Keeper) simulation. if numShares.Equal(sdk.ZeroDec()) { return "no-operation", nil, nil } - msg := stake.MsgBeginUnbonding{ + msg := staking.MsgBeginUnbonding{ DelegatorAddr: delegatorAddress, ValidatorAddr: delegation.ValidatorAddr, SharesAmount: numShares, @@ -179,15 +179,15 @@ func SimulateMsgBeginUnbonding(m auth.AccountKeeper, k stake.Keeper) simulation. if result.IsOK() { write() } - event(fmt.Sprintf("stake/MsgBeginUnbonding/%v", result.IsOK())) + event(fmt.Sprintf("staking/MsgBeginUnbonding/%v", result.IsOK())) action = fmt.Sprintf("TestMsgBeginUnbonding: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) return action, nil, nil } } // SimulateMsgBeginRedelegate -func SimulateMsgBeginRedelegate(m auth.AccountKeeper, k stake.Keeper) simulation.Operation { - handler := stake.NewHandler(k) +func SimulateMsgBeginRedelegate(m auth.AccountKeeper, k staking.Keeper) simulation.Operation { + handler := staking.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) ( action string, fOp []simulation.FutureOperation, err error) { @@ -207,7 +207,7 @@ func SimulateMsgBeginRedelegate(m auth.AccountKeeper, k stake.Keeper) simulation if amount.Equal(sdk.ZeroInt()) { return "no-operation", nil, nil } - msg := stake.MsgBeginRedelegate{ + msg := staking.MsgBeginRedelegate{ DelegatorAddr: delegatorAddress, ValidatorSrcAddr: srcValidatorAddress, ValidatorDstAddr: destValidatorAddress, @@ -221,7 +221,7 @@ func SimulateMsgBeginRedelegate(m auth.AccountKeeper, k stake.Keeper) simulation if result.IsOK() { write() } - event(fmt.Sprintf("stake/MsgBeginRedelegate/%v", result.IsOK())) + event(fmt.Sprintf("staking/MsgBeginRedelegate/%v", result.IsOK())) action = fmt.Sprintf("TestMsgBeginRedelegate: %s", msg.GetSignBytes()) return action, nil, nil } diff --git a/x/stake/stake.go b/x/staking/staking.go similarity index 96% rename from x/stake/stake.go rename to x/staking/staking.go index 4043c10ce016..67fa3bb2e62c 100644 --- a/x/stake/stake.go +++ b/x/staking/staking.go @@ -1,11 +1,11 @@ // nolint -package stake +package staking import ( - "github.com/cosmos/cosmos-sdk/x/stake/keeper" - "github.com/cosmos/cosmos-sdk/x/stake/querier" - "github.com/cosmos/cosmos-sdk/x/stake/tags" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/keeper" + "github.com/cosmos/cosmos-sdk/x/staking/querier" + "github.com/cosmos/cosmos-sdk/x/staking/tags" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) type ( @@ -108,7 +108,7 @@ const ( const ( StoreKey = types.StoreKey TStoreKey = types.TStoreKey - QuerierRoute = types.QuerierRoute + QuerierRoute = types.QuerierRoute RouterKey = types.RouterKey DefaultCodespace = types.DefaultCodespace CodeInvalidValidator = types.CodeInvalidValidator diff --git a/x/stake/tags/tags.go b/x/staking/tags/tags.go similarity index 100% rename from x/stake/tags/tags.go rename to x/staking/tags/tags.go diff --git a/x/stake/test_common.go b/x/staking/test_common.go similarity index 96% rename from x/stake/test_common.go rename to x/staking/test_common.go index c9389d6eb9e3..e4bc3a22e329 100644 --- a/x/stake/test_common.go +++ b/x/staking/test_common.go @@ -1,4 +1,4 @@ -package stake +package staking import ( "github.com/tendermint/tendermint/crypto" @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( diff --git a/x/stake/types/codec.go b/x/staking/types/codec.go similarity index 100% rename from x/stake/types/codec.go rename to x/staking/types/codec.go diff --git a/x/stake/types/commission.go b/x/staking/types/commission.go similarity index 100% rename from x/stake/types/commission.go rename to x/staking/types/commission.go diff --git a/x/stake/types/delegation.go b/x/staking/types/delegation.go similarity index 59% rename from x/stake/types/delegation.go rename to x/staking/types/delegation.go index 0d49b1db58ad..46fb74e1dc2e 100644 --- a/x/stake/types/delegation.go +++ b/x/staking/types/delegation.go @@ -35,50 +35,24 @@ type Delegation struct { Shares sdk.Dec `json:"shares"` } -type delegationValue struct { - Shares sdk.Dec -} - -// return the delegation without fields contained within the key for the store +// return the delegation func MustMarshalDelegation(cdc *codec.Codec, delegation Delegation) []byte { - val := delegationValue{ - delegation.Shares, - } - return cdc.MustMarshalBinaryLengthPrefixed(val) + return cdc.MustMarshalBinaryLengthPrefixed(delegation) } -// return the delegation without fields contained within the key for the store -func MustUnmarshalDelegation(cdc *codec.Codec, key, value []byte) Delegation { - delegation, err := UnmarshalDelegation(cdc, key, value) +// return the delegation +func MustUnmarshalDelegation(cdc *codec.Codec, value []byte) Delegation { + delegation, err := UnmarshalDelegation(cdc, value) if err != nil { panic(err) } return delegation } -// return the delegation without fields contained within the key for the store -func UnmarshalDelegation(cdc *codec.Codec, key, value []byte) (delegation Delegation, err error) { - var storeValue delegationValue - err = cdc.UnmarshalBinaryLengthPrefixed(value, &storeValue) - if err != nil { - err = fmt.Errorf("%v: %v", ErrNoDelegation(DefaultCodespace).Data(), err) - return - } - - addrs := key[1:] // remove prefix bytes - if len(addrs) != 2*sdk.AddrLen { - err = fmt.Errorf("%v", ErrBadDelegationAddr(DefaultCodespace).Data()) - return - } - - delAddr := sdk.AccAddress(addrs[:sdk.AddrLen]) - valAddr := sdk.ValAddress(addrs[sdk.AddrLen:]) - - return Delegation{ - DelegatorAddr: delAddr, - ValidatorAddr: valAddr, - Shares: storeValue.Shares, - }, nil +// return the delegation +func UnmarshalDelegation(cdc *codec.Codec, value []byte) (delegation Delegation, err error) { + err = cdc.UnmarshalBinaryLengthPrefixed(value, &delegation) + return delegation, err } // nolint @@ -118,57 +92,24 @@ type UnbondingDelegation struct { Balance sdk.Coin `json:"balance"` // atoms to receive at completion } -type ubdValue struct { - CreationHeight int64 - MinTime time.Time - InitialBalance sdk.Coin - Balance sdk.Coin -} - -// return the unbonding delegation without fields contained within the key for the store +// return the unbonding delegation func MustMarshalUBD(cdc *codec.Codec, ubd UnbondingDelegation) []byte { - val := ubdValue{ - ubd.CreationHeight, - ubd.MinTime, - ubd.InitialBalance, - ubd.Balance, - } - return cdc.MustMarshalBinaryLengthPrefixed(val) + return cdc.MustMarshalBinaryLengthPrefixed(ubd) } -// unmarshal a unbonding delegation from a store key and value -func MustUnmarshalUBD(cdc *codec.Codec, key, value []byte) UnbondingDelegation { - ubd, err := UnmarshalUBD(cdc, key, value) +// unmarshal a unbonding delegation from a store value +func MustUnmarshalUBD(cdc *codec.Codec, value []byte) UnbondingDelegation { + ubd, err := UnmarshalUBD(cdc, value) if err != nil { panic(err) } return ubd } -// unmarshal a unbonding delegation from a store key and value -func UnmarshalUBD(cdc *codec.Codec, key, value []byte) (ubd UnbondingDelegation, err error) { - var storeValue ubdValue - err = cdc.UnmarshalBinaryLengthPrefixed(value, &storeValue) - if err != nil { - return - } - - addrs := key[1:] // remove prefix bytes - if len(addrs) != 2*sdk.AddrLen { - err = fmt.Errorf("%v", ErrBadDelegationAddr(DefaultCodespace).Data()) - return - } - delAddr := sdk.AccAddress(addrs[:sdk.AddrLen]) - valAddr := sdk.ValAddress(addrs[sdk.AddrLen:]) - - return UnbondingDelegation{ - DelegatorAddr: delAddr, - ValidatorAddr: valAddr, - CreationHeight: storeValue.CreationHeight, - MinTime: storeValue.MinTime, - InitialBalance: storeValue.InitialBalance, - Balance: storeValue.Balance, - }, nil +// unmarshal a unbonding delegation from a store value +func UnmarshalUBD(cdc *codec.Codec, value []byte) (ubd UnbondingDelegation, err error) { + err = cdc.UnmarshalBinaryLengthPrefixed(value, &ubd) + return ubd, err } // nolint @@ -206,65 +147,24 @@ type Redelegation struct { SharesDst sdk.Dec `json:"shares_dst"` // amount of destination shares redelegating } -type redValue struct { - CreationHeight int64 - MinTime time.Time - InitialBalance sdk.Coin - Balance sdk.Coin - SharesSrc sdk.Dec - SharesDst sdk.Dec -} - -// return the redelegation without fields contained within the key for the store +// return the redelegation func MustMarshalRED(cdc *codec.Codec, red Redelegation) []byte { - val := redValue{ - red.CreationHeight, - red.MinTime, - red.InitialBalance, - red.Balance, - red.SharesSrc, - red.SharesDst, - } - return cdc.MustMarshalBinaryLengthPrefixed(val) + return cdc.MustMarshalBinaryLengthPrefixed(red) } -// unmarshal a redelegation from a store key and value -func MustUnmarshalRED(cdc *codec.Codec, key, value []byte) Redelegation { - red, err := UnmarshalRED(cdc, key, value) +// unmarshal a redelegation from a store value +func MustUnmarshalRED(cdc *codec.Codec, value []byte) Redelegation { + red, err := UnmarshalRED(cdc, value) if err != nil { panic(err) } return red } -// unmarshal a redelegation from a store key and value -func UnmarshalRED(cdc *codec.Codec, key, value []byte) (red Redelegation, err error) { - var storeValue redValue - err = cdc.UnmarshalBinaryLengthPrefixed(value, &storeValue) - if err != nil { - return - } - - addrs := key[1:] // remove prefix bytes - if len(addrs) != 3*sdk.AddrLen { - err = fmt.Errorf("%v", ErrBadRedelegationAddr(DefaultCodespace).Data()) - return - } - delAddr := sdk.AccAddress(addrs[:sdk.AddrLen]) - valSrcAddr := sdk.ValAddress(addrs[sdk.AddrLen : 2*sdk.AddrLen]) - valDstAddr := sdk.ValAddress(addrs[2*sdk.AddrLen:]) - - return Redelegation{ - DelegatorAddr: delAddr, - ValidatorSrcAddr: valSrcAddr, - ValidatorDstAddr: valDstAddr, - CreationHeight: storeValue.CreationHeight, - MinTime: storeValue.MinTime, - InitialBalance: storeValue.InitialBalance, - Balance: storeValue.Balance, - SharesSrc: storeValue.SharesSrc, - SharesDst: storeValue.SharesDst, - }, nil +// unmarshal a redelegation from a store value +func UnmarshalRED(cdc *codec.Codec, value []byte) (red Redelegation, err error) { + err = cdc.UnmarshalBinaryLengthPrefixed(value, &red) + return red, err } // nolint diff --git a/x/stake/types/delegation_test.go b/x/staking/types/delegation_test.go similarity index 100% rename from x/stake/types/delegation_test.go rename to x/staking/types/delegation_test.go diff --git a/x/stake/types/errors.go b/x/staking/types/errors.go similarity index 99% rename from x/stake/types/errors.go rename to x/staking/types/errors.go index c3e52f5e448b..1ba5f4ca2520 100644 --- a/x/stake/types/errors.go +++ b/x/staking/types/errors.go @@ -12,7 +12,7 @@ import ( type CodeType = sdk.CodeType const ( - DefaultCodespace sdk.CodespaceType = "stake" + DefaultCodespace sdk.CodespaceType = "staking" CodeInvalidValidator CodeType = 101 CodeInvalidDelegation CodeType = 102 diff --git a/x/stake/types/genesis.go b/x/staking/types/genesis.go similarity index 100% rename from x/stake/types/genesis.go rename to x/staking/types/genesis.go diff --git a/x/staking/types/keys.go b/x/staking/types/keys.go new file mode 100644 index 000000000000..aa1b92d46def --- /dev/null +++ b/x/staking/types/keys.go @@ -0,0 +1,15 @@ +package types + +const ( + // StoreKey is the string store representation + StoreKey = "staking" + + // TStoreKey is the string transient store representation + TStoreKey = "transient_staking" + + // QuerierRoute is the querier route for the staking module + QuerierRoute = "staking" + + // RouterKey is the msg router key for the staking module + RouterKey = "staking" +) diff --git a/x/stake/types/msg.go b/x/staking/types/msg.go similarity index 100% rename from x/stake/types/msg.go rename to x/staking/types/msg.go diff --git a/x/stake/types/msg_test.go b/x/staking/types/msg_test.go similarity index 100% rename from x/stake/types/msg_test.go rename to x/staking/types/msg_test.go diff --git a/x/stake/types/params.go b/x/staking/types/params.go similarity index 100% rename from x/stake/types/params.go rename to x/staking/types/params.go diff --git a/x/stake/types/params_test.go b/x/staking/types/params_test.go similarity index 100% rename from x/stake/types/params_test.go rename to x/staking/types/params_test.go diff --git a/x/stake/types/pool.go b/x/staking/types/pool.go similarity index 100% rename from x/stake/types/pool.go rename to x/staking/types/pool.go diff --git a/x/stake/types/pool_test.go b/x/staking/types/pool_test.go similarity index 100% rename from x/stake/types/pool_test.go rename to x/staking/types/pool_test.go diff --git a/x/stake/types/test_utils.go b/x/staking/types/test_utils.go similarity index 100% rename from x/stake/types/test_utils.go rename to x/staking/types/test_utils.go diff --git a/x/stake/types/validator.go b/x/staking/types/validator.go similarity index 87% rename from x/stake/types/validator.go rename to x/staking/types/validator.go index 065e4d42bd8f..eddce185ea07 100644 --- a/x/stake/types/validator.go +++ b/x/staking/types/validator.go @@ -55,71 +55,24 @@ func NewValidator(operator sdk.ValAddress, pubKey crypto.PubKey, description Des } } -// what's kept in the store value -type validatorValue struct { - ConsPubKey crypto.PubKey - Jailed bool - Status sdk.BondStatus - Tokens sdk.Int - DelegatorShares sdk.Dec - Description Description - BondHeight int64 - UnbondingHeight int64 - UnbondingMinTime time.Time - Commission Commission -} - -// return the redelegation without fields contained within the key for the store +// return the redelegation func MustMarshalValidator(cdc *codec.Codec, validator Validator) []byte { - val := validatorValue{ - ConsPubKey: validator.ConsPubKey, - Jailed: validator.Jailed, - Status: validator.Status, - Tokens: validator.Tokens, - DelegatorShares: validator.DelegatorShares, - Description: validator.Description, - BondHeight: validator.BondHeight, - UnbondingHeight: validator.UnbondingHeight, - UnbondingMinTime: validator.UnbondingMinTime, - Commission: validator.Commission, - } - return cdc.MustMarshalBinaryLengthPrefixed(val) + return cdc.MustMarshalBinaryLengthPrefixed(validator) } -// unmarshal a redelegation from a store key and value -func MustUnmarshalValidator(cdc *codec.Codec, operatorAddr, value []byte) Validator { - validator, err := UnmarshalValidator(cdc, operatorAddr, value) +// unmarshal a redelegation from a store value +func MustUnmarshalValidator(cdc *codec.Codec, value []byte) Validator { + validator, err := UnmarshalValidator(cdc, value) if err != nil { panic(err) } return validator } -// unmarshal a redelegation from a store key and value -func UnmarshalValidator(cdc *codec.Codec, operatorAddr, value []byte) (validator Validator, err error) { - if len(operatorAddr) != sdk.AddrLen { - err = fmt.Errorf("%v", ErrBadValidatorAddr(DefaultCodespace).Data()) - return - } - var storeValue validatorValue - err = cdc.UnmarshalBinaryLengthPrefixed(value, &storeValue) - if err != nil { - return - } - - return Validator{ - OperatorAddr: operatorAddr, - ConsPubKey: storeValue.ConsPubKey, - Jailed: storeValue.Jailed, - Tokens: storeValue.Tokens, - Status: storeValue.Status, - DelegatorShares: storeValue.DelegatorShares, - Description: storeValue.Description, - BondHeight: storeValue.BondHeight, - UnbondingHeight: storeValue.UnbondingHeight, - UnbondingMinTime: storeValue.UnbondingMinTime, - Commission: storeValue.Commission, - }, nil +// unmarshal a redelegation from a store value +func UnmarshalValidator(cdc *codec.Codec, value []byte) (validator Validator, err error) { + err = cdc.UnmarshalBinaryLengthPrefixed(value, &validator) + return validator, err } // HumanReadableString returns a human readable string representation of a diff --git a/x/stake/types/validator_test.go b/x/staking/types/validator_test.go similarity index 100% rename from x/stake/types/validator_test.go rename to x/staking/types/validator_test.go