From bc51fa93b678a66f4cc98b6db3ed0ae908fba77c Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sat, 8 Dec 2018 07:18:04 -0800 Subject: [PATCH 01/21] Fix updateValidatorDistInfoFromPool (#3046) Fixes regression introduced by #2984. Continuiation of #3033 , which didn't fix the simulation issues. (candidate) Complete solution for #3019, 9002 halt bug. From #2984, it isn't sufficient to take the fee pool rewards of a validator. Since we don't track delegator accums (as we do with validator accums), and because onValidatorModified >updateValidatorDistInfoFromPool is also being called upon delegation updates (or at least I believe this is the reason), it is necessary to also withdraw self delegation. TODO: I don't think self-delegation should be required to be modified here... consider using a delegation hook to do the self-delegation withdraw part instead, e.g. splitting the updateValidatorDistInfoFromPool function into two. It might not result in cleaner code, however. Think hard. --- Makefile | 2 + cmd/gaia/cmd/gaiakeyutil/main.go | 51 +++++++++++++++++++++++++ types/decimal.go | 5 +++ x/distribution/keeper/hooks.go | 2 +- x/distribution/keeper/validator.go | 19 ++++++--- x/distribution/keeper/validator_test.go | 22 +++++++---- x/distribution/simulation/invariants.go | 5 ++- 7 files changed, 91 insertions(+), 15 deletions(-) create mode 100644 cmd/gaia/cmd/gaiakeyutil/main.go diff --git a/Makefile b/Makefile index e1c69b103..7d5a0790c 100644 --- a/Makefile +++ b/Makefile @@ -53,6 +53,7 @@ else go build $(BUILD_FLAGS) -o build/gaiad ./cmd/gaia/cmd/gaiad go build $(BUILD_FLAGS) -o build/gaiacli ./cmd/gaia/cmd/gaiacli go build $(BUILD_FLAGS) -o build/gaiareplay ./cmd/gaia/cmd/gaiareplay + go build $(BUILD_FLAGS) -o build/gaiakeyutil ./cmd/gaia/cmd/gaiakeyutil endif build-linux: @@ -85,6 +86,7 @@ install: check-ledger update_gaia_lite_docs go install $(BUILD_FLAGS) ./cmd/gaia/cmd/gaiad go install $(BUILD_FLAGS) ./cmd/gaia/cmd/gaiacli go install $(BUILD_FLAGS) ./cmd/gaia/cmd/gaiareplay + go install $(BUILD_FLAGS) ./cmd/gaia/cmd/gaiakeyutil install_examples: go install $(BUILD_FLAGS) ./docs/examples/basecoin/cmd/basecoind diff --git a/cmd/gaia/cmd/gaiakeyutil/main.go b/cmd/gaia/cmd/gaiakeyutil/main.go new file mode 100644 index 000000000..53320e823 --- /dev/null +++ b/cmd/gaia/cmd/gaiakeyutil/main.go @@ -0,0 +1,51 @@ +package main + +import ( + "encoding/hex" + "fmt" + "os" + + "github.com/tendermint/tendermint/libs/bech32" +) + +var bech32Prefixes = []string{"cosmos", "cosmospub", "cosmosvaloper", "cosmosvaloperpub", "cosmosvalcons", "cosmosvalconspub"} + +func main() { + if len(os.Args) < 2 { + fmt.Println("Must specify an input string") + } + arg := os.Args[1] + runFromBech32(arg) + runFromHex(arg) +} + +// Print info from bech32. +func runFromBech32(bech32str string) { + hrp, bz, err := bech32.DecodeAndConvert(bech32str) + if err != nil { + fmt.Println("Not a valid bech32 string") + return + } + fmt.Println("Bech32 parse:") + fmt.Printf("Human readible part: %v\nBytes (hex): %X\n", + hrp, + bz, + ) +} + +func runFromHex(hexaddr string) { + bz, err := hex.DecodeString(hexaddr) + if err != nil { + fmt.Println("Not a valid hex string") + return + } + fmt.Println("Hex parse:") + fmt.Println("Bech32 formats:") + for _, prefix := range bech32Prefixes { + bech32Addr, err := bech32.ConvertAndEncode(prefix, bz) + if err != nil { + panic(err) + } + fmt.Println(" - " + bech32Addr) + } +} diff --git a/types/decimal.go b/types/decimal.go index b4bd44fb2..5e0f8d267 100644 --- a/types/decimal.go +++ b/types/decimal.go @@ -400,6 +400,11 @@ func (d Dec) TruncateInt() Int { return NewIntFromBigInt(chopPrecisionAndTruncateNonMutative(d.Int)) } +// TruncateDec truncates the decimals from the number and returns a Dec +func (d Dec) TruncateDec() Dec { + return NewDecFromBigInt(chopPrecisionAndTruncateNonMutative(d.Int)) +} + //___________________________________________________________________________________ // reuse nil values diff --git a/x/distribution/keeper/hooks.go b/x/distribution/keeper/hooks.go index 260ee2e77..e9d31b8a2 100644 --- a/x/distribution/keeper/hooks.go +++ b/x/distribution/keeper/hooks.go @@ -32,7 +32,7 @@ func (k Keeper) onValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { // (dist info), but without actually withdrawing the rewards. This does not // need to happen during the genesis block. if ctx.BlockHeight() > 0 { - if err := k.updateValidatorDistInfoFromPool(ctx, valAddr); err != nil { + if err := k.takeValidatorFeePoolRewards(ctx, valAddr); err != nil { panic(err) } } diff --git a/x/distribution/keeper/validator.go b/x/distribution/keeper/validator.go index 951ba280a..4ce0834a7 100644 --- a/x/distribution/keeper/validator.go +++ b/x/distribution/keeper/validator.go @@ -91,27 +91,36 @@ func (k Keeper) GetValidatorAccum(ctx sdk.Context, operatorAddr sdk.ValAddress) return accum, nil } -// updateValidatorDistInfoFromPool updates the validator's distribution info +// takeValidatorFeePoolRewards updates the validator's distribution info // from the global fee pool without withdrawing any rewards. This will be called // from a onValidatorModified hook. -func (k Keeper) updateValidatorDistInfoFromPool(ctx sdk.Context, operatorAddr sdk.ValAddress) sdk.Error { +func (k Keeper) takeValidatorFeePoolRewards(ctx sdk.Context, operatorAddr sdk.ValAddress) sdk.Error { if !k.HasValidatorDistInfo(ctx, operatorAddr) { return types.ErrNoValidatorDistInfo(k.codespace) } + accAddr := sdk.AccAddress(operatorAddr.Bytes()) + // withdraw reward for self-delegation + if k.HasDelegationDistInfo(ctx, accAddr, operatorAddr) { + fp, vi, di, withdraw := + k.withdrawDelegationReward(ctx, accAddr, operatorAddr) + k.SetFeePool(ctx, fp) + k.SetValidatorDistInfo(ctx, vi) + k.SetDelegationDistInfo(ctx, di) + k.WithdrawToDelegator(ctx, fp, accAddr, withdraw) + } + + // withdrawal validator commission rewards valInfo := k.GetValidatorDistInfo(ctx, operatorAddr) wc := k.GetWithdrawContext(ctx, operatorAddr) valInfo, feePool := valInfo.TakeFeePoolRewards(wc) - k.SetFeePool(ctx, feePool) k.SetValidatorDistInfo(ctx, valInfo) - return nil } // withdrawal all the validator rewards including the commission func (k Keeper) WithdrawValidatorRewardsAll(ctx sdk.Context, operatorAddr sdk.ValAddress) sdk.Error { - if !k.HasValidatorDistInfo(ctx, operatorAddr) { return types.ErrNoValidatorDistInfo(k.codespace) } diff --git a/x/distribution/keeper/validator_test.go b/x/distribution/keeper/validator_test.go index 62638a4d2..fc9331959 100644 --- a/x/distribution/keeper/validator_test.go +++ b/x/distribution/keeper/validator_test.go @@ -13,7 +13,7 @@ func TestWithdrawValidatorRewardsAllNoDelegator(t *testing.T) { stakeHandler := stake.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom - //first make a validator + // first make a validator msgCreateValidator := stake.NewTestMsgCreateValidator(valOpAddr1, valConsPk1, 10) got := stakeHandler(ctx, msgCreateValidator) require.True(t, got.IsOK(), "expected msg to be ok, got %v", got) @@ -107,17 +107,20 @@ func TestWithdrawValidatorRewardsAllMultipleValidator(t *testing.T) { stakeHandler := stake.NewHandler(sk) denom := sk.GetParams(ctx).BondDenom - //make some validators with different commissions + // Make some validators with different commissions. + // Bond 10 of 100 with 0.1 commission. msgCreateValidator := stake.NewTestMsgCreateValidatorWithCommission( valOpAddr1, valConsPk1, 10, sdk.NewDecWithPrec(1, 1)) got := stakeHandler(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( valOpAddr2, valConsPk2, 50, sdk.NewDecWithPrec(2, 1)) got = stakeHandler(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( valOpAddr3, valConsPk3, 40, sdk.NewDecWithPrec(3, 1)) got = stakeHandler(ctx, msgCreateValidator) @@ -125,22 +128,27 @@ func TestWithdrawValidatorRewardsAllMultipleValidator(t *testing.T) { _ = sk.ApplyAndReturnValidatorSetUpdates(ctx) - // allocate 100 denom of fees + // Allocate 1000 denom of fees. feeInputs := sdk.NewInt(1000) fck.SetCollectedFees(sdk.Coins{sdk.NewCoin(denom, feeInputs)}) require.Equal(t, feeInputs, fck.GetCollectedFees(ctx).AmountOf(denom)) + // Collect proposer reward for 100% of votes. keeper.AllocateTokens(ctx, sdk.OneDec(), valConsAddr1) - // withdraw validator reward + // Withdraw validator reward. ctx = ctx.WithBlockHeight(1) keeper.WithdrawValidatorRewardsAll(ctx, valOpAddr1) amt := accMapper.GetAccount(ctx, valAccAddr1).GetCoins().AmountOf(denom) feesInNonProposer := sdk.NewDecFromInt(feeInputs).Mul(sdk.NewDecWithPrec(95, 2)) feesInProposer := sdk.NewDecFromInt(feeInputs).Mul(sdk.NewDecWithPrec(5, 2)) - expRes := sdk.NewDec(90). // orig tokens (100 - 10) - Add(feesInNonProposer.Quo(sdk.NewDec(10))). // validator 1 has 1/10 total power - Add(feesInProposer). + // NOTE: the non-proposer rewards (95) and proposer rewards (50) add up to + // 145. During computation, this is further split into 130.5 and 14.5, + // which is the non-commission and commission respectively, but the + // commission is for self so the result is just 145. + expRes := sdk.NewDec(90). // orig tokens (100) - bonded (10) + Add(feesInNonProposer.Quo(sdk.NewDec(10))). // validator 1 has 1/10 total power (non-proposer rewards = 95) + Add(feesInProposer). // (proposer rewards = 50) TruncateInt() require.True(sdk.IntEq(t, expRes, amt)) } diff --git a/x/distribution/simulation/invariants.go b/x/distribution/simulation/invariants.go index bf808905a..2f954d6e1 100644 --- a/x/distribution/simulation/invariants.go +++ b/x/distribution/simulation/invariants.go @@ -101,9 +101,10 @@ func DelAccumInvariants(k distr.Keeper, sk distr.StakeKeeper) simulation.Invaria delegation := sk.Delegation(ctx, ddi.DelegatorAddr, ddi.ValOperatorAddr) accum := ddi.GetDelAccum(height, delegation.GetShares()) if accum.IsPositive() { - logDelAccums += fmt.Sprintf("\n\t\tdel: %v, accum: %v", + logDelAccums += fmt.Sprintf("\n\t\tdel: %v, accum: %v, power: %v", ddi.DelegatorAddr.String(), - accum.String()) + accum.String(), + delegation.GetShares()) } } return false From e02e55116c90ab17af7263e867e271decbd9e107 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sat, 8 Dec 2018 07:31:27 -0800 Subject: [PATCH 02/21] multi_seed sim should run 400, or at least 100 --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 7d5a0790c..5564f8ec7 100644 --- a/Makefile +++ b/Makefile @@ -186,7 +186,7 @@ test_sim_gaia_simulation_after_import: test_sim_gaia_multi_seed: @echo "Running multi-seed Gaia simulation. This may take awhile!" - @bash scripts/multisim.sh 50 TestFullGaiaSimulation + @bash scripts/multisim.sh 400 TestFullGaiaSimulation SIM_NUM_BLOCKS ?= 500 SIM_BLOCK_SIZE ?= 200 From 663e954b806b5e8cc4206dd23d6770e7af4cfc2b Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sat, 8 Dec 2018 07:44:18 -0800 Subject: [PATCH 03/21] Default SimulationPeriod is 1 --- cmd/gaia/app/sim_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/gaia/app/sim_test.go b/cmd/gaia/app/sim_test.go index 52ac2ed1a..bf03f9a10 100644 --- a/cmd/gaia/app/sim_test.go +++ b/cmd/gaia/app/sim_test.go @@ -50,7 +50,7 @@ func init() { flag.BoolVar(&enabled, "SimulationEnabled", false, "Enable the simulation") flag.BoolVar(&verbose, "SimulationVerbose", false, "Verbose log output") flag.BoolVar(&commit, "SimulationCommit", false, "Have the simulation commit") - flag.IntVar(&period, "SimulationPeriod", 100, "Run slow invariants only once every period assertions") + flag.IntVar(&period, "SimulationPeriod", 1, "Run slow invariants only once every period assertions") } func appStateFn(r *rand.Rand, accs []simulation.Account) json.RawMessage { From 40a30b738f22dd318ea955b9c1945fd3db374339 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Mon, 10 Dec 2018 02:48:19 -0800 Subject: [PATCH 04/21] Update gas costs to more reasonable numbers for GoS (#3052) --- PENDING.md | 1 + scripts/multisim.sh | 2 +- store/gaskvstore.go | 2 +- store/gaskvstore_test.go | 14 +++++++------- types/gas.go | 16 +++++++--------- x/auth/ante.go | 10 +++++----- x/auth/ante_test.go | 15 ++++++++------- x/auth/stdtx_test.go | 2 +- x/bank/keeper.go | 14 -------------- 9 files changed, 31 insertions(+), 45 deletions(-) diff --git a/PENDING.md b/PENDING.md index 73567c237..202205111 100644 --- a/PENDING.md +++ b/PENDING.md @@ -14,6 +14,7 @@ BREAKING CHANGES - [#128](https://github.com/tendermint/devops/issues/128) Updated CircleCI job to trigger website build on every push to master/develop. - [\#2994](https://github.com/cosmos/cosmos-sdk/pull/2994) Change wrong-password error message. - \#3009 Added missing Gaia genesis verification + - [gas] \#3052 Updated gas costs to more reasonable numbers * SDK - [auth] \#2952 Signatures are no longer serialized on chain with the account number and sequence number diff --git a/scripts/multisim.sh b/scripts/multisim.sh index 028b6563f..b8d30772a 100755 --- a/scripts/multisim.sh +++ b/scripts/multisim.sh @@ -22,7 +22,7 @@ sim() { file="$tmpdir/gaia-simulation-seed-$seed-date-$(date -u +"%Y-%m-%dT%H:%M:%S+00:00").stdout" echo "Writing stdout to $file..." go test ./cmd/gaia/app -run $testname -SimulationEnabled=true -SimulationNumBlocks=$blocks \ - -SimulationVerbose=true -SimulationCommit=true -SimulationSeed=$seed -v -timeout 24h > $file + -SimulationVerbose=true -SimulationCommit=true -SimulationSeed=$seed -SimulationPeriod=5 -v -timeout 24h > $file } i=0 diff --git a/store/gaskvstore.go b/store/gaskvstore.go index 2ce6415e6..1100f8433 100644 --- a/store/gaskvstore.go +++ b/store/gaskvstore.go @@ -179,6 +179,6 @@ func (gi *gasIterator) Close() { func (gi *gasIterator) consumeSeekGas() { value := gi.Value() - gi.gasMeter.ConsumeGas(gi.gasConfig.ValueCostPerByte*sdk.Gas(len(value)), sdk.GasValuePerByteDesc) + gi.gasMeter.ConsumeGas(gi.gasConfig.ReadCostPerByte*sdk.Gas(len(value)), sdk.GasValuePerByteDesc) gi.gasMeter.ConsumeGas(gi.gasConfig.IterNextCostFlat, sdk.GasIterNextCostFlatDesc) } diff --git a/store/gaskvstore_test.go b/store/gaskvstore_test.go index f059df7f8..2426cf334 100644 --- a/store/gaskvstore_test.go +++ b/store/gaskvstore_test.go @@ -12,26 +12,26 @@ import ( ) func newGasKVStore() KVStore { - meter := sdk.NewGasMeter(1000) + meter := sdk.NewGasMeter(10000) mem := dbStoreAdapter{dbm.NewMemDB()} return NewGasKVStore(meter, sdk.KVGasConfig(), mem) } func TestGasKVStoreBasic(t *testing.T) { mem := dbStoreAdapter{dbm.NewMemDB()} - meter := sdk.NewGasMeter(1000) + meter := sdk.NewGasMeter(10000) st := NewGasKVStore(meter, sdk.KVGasConfig(), mem) require.Empty(t, st.Get(keyFmt(1)), "Expected `key1` to be empty") st.Set(keyFmt(1), valFmt(1)) require.Equal(t, valFmt(1), st.Get(keyFmt(1))) st.Delete(keyFmt(1)) require.Empty(t, st.Get(keyFmt(1)), "Expected `key1` to be empty") - require.Equal(t, meter.GasConsumed(), sdk.Gas(193)) + require.Equal(t, meter.GasConsumed(), sdk.Gas(6429)) } func TestGasKVStoreIterator(t *testing.T) { mem := dbStoreAdapter{dbm.NewMemDB()} - meter := sdk.NewGasMeter(1000) + meter := sdk.NewGasMeter(10000) st := NewGasKVStore(meter, sdk.KVGasConfig(), mem) require.Empty(t, st.Get(keyFmt(1)), "Expected `key1` to be empty") require.Empty(t, st.Get(keyFmt(2)), "Expected `key2` to be empty") @@ -50,7 +50,7 @@ func TestGasKVStoreIterator(t *testing.T) { iterator.Next() require.False(t, iterator.Valid()) require.Panics(t, iterator.Next) - require.Equal(t, meter.GasConsumed(), sdk.Gas(384)) + require.Equal(t, meter.GasConsumed(), sdk.Gas(6987)) } func TestGasKVStoreOutOfGasSet(t *testing.T) { @@ -62,7 +62,7 @@ func TestGasKVStoreOutOfGasSet(t *testing.T) { func TestGasKVStoreOutOfGasIterator(t *testing.T) { mem := dbStoreAdapter{dbm.NewMemDB()} - meter := sdk.NewGasMeter(200) + meter := sdk.NewGasMeter(20000) st := NewGasKVStore(meter, sdk.KVGasConfig(), mem) st.Set(keyFmt(1), valFmt(1)) iterator := st.Iterator(nil, nil) @@ -71,7 +71,7 @@ func TestGasKVStoreOutOfGasIterator(t *testing.T) { } func testGasKVStoreWrap(t *testing.T, store KVStore) { - meter := sdk.NewGasMeter(10000) + meter := sdk.NewGasMeter(100000) store = store.Gas(meter, sdk.GasConfig{HasCost: 10}) require.Equal(t, uint64(0), meter.GasConsumed()) diff --git a/types/gas.go b/types/gas.go index 100b00430..2daecdeb1 100644 --- a/types/gas.go +++ b/types/gas.go @@ -140,21 +140,19 @@ type GasConfig struct { ReadCostPerByte Gas WriteCostFlat Gas WriteCostPerByte Gas - ValueCostPerByte Gas IterNextCostFlat Gas } // KVGasConfig returns a default gas config for KVStores. func KVGasConfig() GasConfig { return GasConfig{ - HasCost: 10, - DeleteCost: 10, - ReadCostFlat: 10, - ReadCostPerByte: 1, - WriteCostFlat: 10, - WriteCostPerByte: 10, - ValueCostPerByte: 1, - IterNextCostFlat: 15, + HasCost: 1000, + DeleteCost: 1000, + ReadCostFlat: 1000, + ReadCostPerByte: 3, + WriteCostFlat: 2000, + WriteCostPerByte: 30, + IterNextCostFlat: 30, } } diff --git a/x/auth/ante.go b/x/auth/ante.go index 7c3195572..3c8a0f9aa 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -12,13 +12,13 @@ import ( ) const ( - memoCostPerByte sdk.Gas = 1 - ed25519VerifyCost = 59 - secp256k1VerifyCost = 100 - maxMemoCharacters = 100 + memoCostPerByte sdk.Gas = 3 + ed25519VerifyCost = 590 + secp256k1VerifyCost = 1000 + maxMemoCharacters = 256 // how much gas = 1 atom - gasPerUnitCost = 1000 + gasPerUnitCost = 10000 // max total number of sigs per tx txSigLimit = 7 diff --git a/x/auth/ante_test.go b/x/auth/ante_test.go index 88a63094a..20fec8896 100644 --- a/x/auth/ante_test.go +++ b/x/auth/ante_test.go @@ -2,6 +2,7 @@ package auth import ( "fmt" + "strings" "testing" codec "github.com/cosmos/cosmos-sdk/codec" @@ -20,7 +21,7 @@ func newTestMsg(addrs ...sdk.AccAddress) *sdk.TestMsg { } func newStdFee() StdFee { - return NewStdFee(5000, + return NewStdFee(50000, sdk.NewInt64Coin("atom", 150), ) } @@ -437,13 +438,13 @@ func TestAnteHandlerMemoGas(t *testing.T) { checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeOutOfGas) // memo too large - fee = NewStdFee(2001, sdk.NewInt64Coin("atom", 0)) - tx = newTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, "abcininasidniandsinasindiansdiansdinaisndiasndiadninsdabcininasidniandsinasindiansdiansdinaisndiasndiadninsdabcininasidniandsinasindiansdiansdinaisndiasndiadninsd") + fee = NewStdFee(9000, sdk.NewInt64Coin("atom", 0)) + tx = newTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("01234567890", 500)) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeMemoTooLarge) // tx with memo has enough gas - fee = NewStdFee(1100, sdk.NewInt64Coin("atom", 0)) - tx = newTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, "abcininasidniandsinasindiansdiansdinaisndiasndiadninsd") + fee = NewStdFee(9000, sdk.NewInt64Coin("atom", 0)) + tx = newTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("0123456789", 10)) checkValidTx(t, anteHandler, ctx, tx, false) } @@ -706,8 +707,8 @@ func TestAdjustFeesByGas(t *testing.T) { args args want sdk.Coins }{ - {"nil coins", args{sdk.Coins{}, 10000}, sdk.Coins{}}, - {"nil coins", args{sdk.Coins{sdk.NewInt64Coin("A", 10), sdk.NewInt64Coin("B", 0)}, 10000}, sdk.Coins{sdk.NewInt64Coin("A", 20), sdk.NewInt64Coin("B", 10)}}, + {"nil coins", args{sdk.Coins{}, 100000}, sdk.Coins{}}, + {"nil coins", args{sdk.Coins{sdk.NewInt64Coin("A", 10), sdk.NewInt64Coin("B", 0)}, 100000}, sdk.Coins{sdk.NewInt64Coin("A", 20), sdk.NewInt64Coin("B", 10)}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/auth/stdtx_test.go b/x/auth/stdtx_test.go index ee6556101..1f2fefaca 100644 --- a/x/auth/stdtx_test.go +++ b/x/auth/stdtx_test.go @@ -47,7 +47,7 @@ func TestStdSignBytes(t *testing.T) { }{ { args{"1234", 3, 6, defaultFee, []sdk.Msg{sdk.NewTestMsg(addr)}, "memo"}, - fmt.Sprintf("{\"account_number\":\"3\",\"chain_id\":\"1234\",\"fee\":{\"amount\":[{\"amount\":\"150\",\"denom\":\"atom\"}],\"gas\":\"5000\"},\"memo\":\"memo\",\"msgs\":[[\"%s\"]],\"sequence\":\"6\"}", addr), + fmt.Sprintf("{\"account_number\":\"3\",\"chain_id\":\"1234\",\"fee\":{\"amount\":[{\"amount\":\"150\",\"denom\":\"atom\"}],\"gas\":\"50000\"},\"memo\":\"memo\",\"msgs\":[[\"%s\"]],\"sequence\":\"6\"}", addr), }, } for i, tc := range tests { diff --git a/x/bank/keeper.go b/x/bank/keeper.go index 579c0a2a9..706f445eb 100644 --- a/x/bank/keeper.go +++ b/x/bank/keeper.go @@ -7,14 +7,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" ) -const ( - costGetCoins sdk.Gas = 10 - costHasCoins sdk.Gas = 10 - costSetCoins sdk.Gas = 100 - costSubtractCoins sdk.Gas = 10 - costAddCoins sdk.Gas = 10 -) - //----------------------------------------------------------------------------- // Keeper @@ -150,7 +142,6 @@ func (keeper BaseViewKeeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt //----------------------------------------------------------------------------- func getCoins(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress) sdk.Coins { - ctx.GasMeter().ConsumeGas(costGetCoins, "getCoins") acc := am.GetAccount(ctx, addr) if acc == nil { return sdk.Coins{} @@ -159,7 +150,6 @@ func getCoins(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress) sdk.C } func setCoins(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress, amt sdk.Coins) sdk.Error { - ctx.GasMeter().ConsumeGas(costSetCoins, "setCoins") acc := am.GetAccount(ctx, addr) if acc == nil { acc = am.NewAccountWithAddress(ctx, addr) @@ -175,14 +165,11 @@ func setCoins(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress, amt s // HasCoins returns whether or not an account has at least amt coins. func hasCoins(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress, amt sdk.Coins) bool { - ctx.GasMeter().ConsumeGas(costHasCoins, "hasCoins") return getCoins(ctx, am, addr).IsAllGTE(amt) } // SubtractCoins subtracts amt from the coins at the addr. func subtractCoins(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) { - ctx.GasMeter().ConsumeGas(costSubtractCoins, "subtractCoins") - oldCoins := getCoins(ctx, am, addr) newCoins, hasNeg := oldCoins.SafeMinus(amt) if hasNeg { @@ -196,7 +183,6 @@ func subtractCoins(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress, // AddCoins adds amt to the coins at the addr. func addCoins(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) { - ctx.GasMeter().ConsumeGas(costAddCoins, "addCoins") oldCoins := getCoins(ctx, am, addr) newCoins := oldCoins.Plus(amt) if !newCoins.IsNotNegative() { From 133134ca520b6fd437f587ec682c63db9ba431af Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Mon, 10 Dec 2018 02:49:37 -0800 Subject: [PATCH 05/21] Use address instead of bond height / intratxcounter for deduplication (#3055) --- PENDING.md | 1 + cmd/gaia/app/export.go | 1 - x/slashing/keeper_test.go | 4 +- x/stake/genesis.go | 18 +--- x/stake/genesis_test.go | 2 - x/stake/handler.go | 3 - x/stake/keeper/delegation.go | 2 +- x/stake/keeper/delegation_test.go | 48 +++++----- x/stake/keeper/keeper.go | 21 ----- x/stake/keeper/key.go | 42 +++++++-- x/stake/keeper/key_test.go | 8 +- x/stake/keeper/slash_test.go | 3 +- x/stake/keeper/test_common.go | 40 ++++++-- x/stake/keeper/validator.go | 5 - x/stake/keeper/validator_test.go | 125 ++++++++++++------------- x/stake/querier/querier_test.go | 1 - x/stake/stake.go | 1 - x/stake/types/genesis.go | 1 - x/stake/types/validator.go | 146 ++++++++++++++---------------- 19 files changed, 228 insertions(+), 244 deletions(-) diff --git a/PENDING.md b/PENDING.md index 202205111..af6171e94 100644 --- a/PENDING.md +++ b/PENDING.md @@ -18,6 +18,7 @@ BREAKING CHANGES * SDK - [auth] \#2952 Signatures are no longer serialized on chain with the account number and sequence number + - [stake] \#3055 Use address instead of bond height / intratxcounter for deduplication * Tendermint diff --git a/cmd/gaia/app/export.go b/cmd/gaia/app/export.go index 346830f90..a2aa42087 100644 --- a/cmd/gaia/app/export.go +++ b/cmd/gaia/app/export.go @@ -123,7 +123,6 @@ func (app *GaiaApp) prepForZeroHeightGenesis(ctx sdk.Context) { panic("expected validator, not found") } validator.BondHeight = 0 - validator.BondIntraTxCounter = counter validator.UnbondingHeight = 0 app.stakeKeeper.SetValidator(ctx, validator) counter++ diff --git a/x/slashing/keeper_test.go b/x/slashing/keeper_test.go index 6dc9ab800..dd32ea3f8 100644 --- a/x/slashing/keeper_test.go +++ b/x/slashing/keeper_test.go @@ -419,13 +419,13 @@ func TestValidatorDippingInAndOut(t *testing.T) { ctx = ctx.WithBlockHeight(height) // validator added back in - got = sh(ctx, newTestMsgDelegate(sdk.AccAddress(addrs[2]), addrs[0], sdk.NewInt(2))) + got = sh(ctx, newTestMsgDelegate(sdk.AccAddress(addrs[2]), addrs[0], sdk.NewInt(3))) require.True(t, got.IsOK()) validatorUpdates, _ = stake.EndBlocker(ctx, sk) require.Equal(t, 2, len(validatorUpdates)) validator, _ = sk.GetValidator(ctx, addr) require.Equal(t, sdk.Bonded, validator.Status) - newAmt = int64(102) + newAmt = int64(103) // validator misses a block keeper.handleValidatorSignature(ctx, val.Address(), newAmt, false) diff --git a/x/stake/genesis.go b/x/stake/genesis.go index 0a5e3e25f..d4039003e 100644 --- a/x/stake/genesis.go +++ b/x/stake/genesis.go @@ -11,11 +11,10 @@ import ( "github.com/cosmos/cosmos-sdk/x/stake/types" ) -// InitGenesis sets the pool and parameters for the provided keeper and -// initializes the IntraTxCounter. For each validator in data, it sets that -// validator in the keeper along with manually setting the indexes. In -// addition, it also sets any delegations found in data. Finally, it updates -// the bonded validators. +// InitGenesis sets the pool and parameters for the provided keeper. For each +// validator in data, it sets that validator in the keeper along with manually +// setting the indexes. In addition, it also sets any delegations found in +// data. Finally, it updates the bonded validators. // Returns final validator set after applying all declaration and delegations func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) (res []abci.ValidatorUpdate, err error) { @@ -26,14 +25,9 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) (res [ keeper.SetPool(ctx, data.Pool) keeper.SetParams(ctx, data.Params) - keeper.SetIntraTxCounter(ctx, data.IntraTxCounter) keeper.SetLastTotalPower(ctx, data.LastTotalPower) - for i, validator := range data.Validators { - // set the intra-tx counter to the order the validators are presented, if necessary - if !data.Exported { - validator.BondIntraTxCounter = int16(i) - } + for _, validator := range data.Validators { keeper.SetValidator(ctx, validator) // Manually set indices for the first time @@ -93,7 +87,6 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) (res [ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { pool := keeper.GetPool(ctx) params := keeper.GetParams(ctx) - intraTxCounter := keeper.GetIntraTxCounter(ctx) lastTotalPower := keeper.GetLastTotalPower(ctx) validators := keeper.GetAllValidators(ctx) bonds := keeper.GetAllDelegations(ctx) @@ -116,7 +109,6 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { return types.GenesisState{ Pool: pool, Params: params, - IntraTxCounter: intraTxCounter, LastTotalPower: lastTotalPower, LastValidatorPowers: lastValidatorPowers, Validators: validators, diff --git a/x/stake/genesis_test.go b/x/stake/genesis_test.go index 3f7295a7a..dfe5b7d1b 100644 --- a/x/stake/genesis_test.go +++ b/x/stake/genesis_test.go @@ -53,12 +53,10 @@ func TestInitGenesis(t *testing.T) { resVal, found := keeper.GetValidator(ctx, sdk.ValAddress(keep.Addrs[0])) require.True(t, found) require.Equal(t, sdk.Bonded, resVal.Status) - require.Equal(t, int16(0), resVal.BondIntraTxCounter) resVal, found = keeper.GetValidator(ctx, sdk.ValAddress(keep.Addrs[1])) require.True(t, found) require.Equal(t, sdk.Bonded, resVal.Status) - require.Equal(t, int16(1), resVal.BondIntraTxCounter) abcivals := make([]abci.ValidatorUpdate, len(vals)) for i, val := range validators { diff --git a/x/stake/handler.go b/x/stake/handler.go index 811fe7114..f8792da78 100644 --- a/x/stake/handler.go +++ b/x/stake/handler.go @@ -35,9 +35,6 @@ func NewHandler(k keeper.Keeper) sdk.Handler { // Called every block, update validator set func EndBlocker(ctx sdk.Context, k keeper.Keeper) (validatorUpdates []abci.ValidatorUpdate, endBlockerTags sdk.Tags) { - // Reset the intra-transaction counter. - k.SetIntraTxCounter(ctx, 0) - // Calculate validator set changes. // // NOTE: ApplyAndReturnValidatorSetUpdates has to come before diff --git a/x/stake/keeper/delegation.go b/x/stake/keeper/delegation.go index 811b15629..2567f3dfb 100644 --- a/x/stake/keeper/delegation.go +++ b/x/stake/keeper/delegation.go @@ -572,7 +572,7 @@ func (k Keeper) CompleteUnbonding(ctx sdk.Context, delAddr sdk.AccAddress, valAd return nil } -// complete unbonding an unbonding record +// begin unbonding / redelegation; create a redelegation record func (k Keeper) BeginRedelegation(ctx sdk.Context, delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress, sharesAmount sdk.Dec) (types.Redelegation, sdk.Error) { diff --git a/x/stake/keeper/delegation_test.go b/x/stake/keeper/delegation_test.go index 043f19193..584db1ef6 100644 --- a/x/stake/keeper/delegation_test.go +++ b/x/stake/keeper/delegation_test.go @@ -26,9 +26,9 @@ func TestDelegation(t *testing.T) { } keeper.SetPool(ctx, pool) - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) - validators[1] = TestingUpdateValidator(keeper, ctx, validators[1]) - validators[2] = TestingUpdateValidator(keeper, ctx, validators[2]) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], true) + validators[1] = TestingUpdateValidator(keeper, ctx, validators[1], true) + validators[2] = TestingUpdateValidator(keeper, ctx, validators[2], true) // first add a validators[0] to delegate too @@ -188,7 +188,7 @@ func TestUnbondDelegation(t *testing.T) { validator, pool, issuedShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) require.Equal(t, int64(10), pool.BondedTokens.RoundInt64()) @@ -230,7 +230,7 @@ func TestUndelegateSelfDelegation(t *testing.T) { validator, pool, issuedShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) selfDelegation := types.Delegation{ DelegatorAddr: sdk.AccAddress(addrVals[0].Bytes()), @@ -244,7 +244,7 @@ func TestUndelegateSelfDelegation(t *testing.T) { validator, pool, issuedShares = validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) delegation := types.Delegation{ DelegatorAddr: addrDels[0], @@ -278,7 +278,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) { validator, pool, issuedShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) selfDelegation := types.Delegation{ DelegatorAddr: sdk.AccAddress(addrVals[0].Bytes()), @@ -292,7 +292,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) { validator, pool, issuedShares = validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) delegation := types.Delegation{ DelegatorAddr: addrDels[0], @@ -354,7 +354,7 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) { validator, pool, issuedShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) selfDelegation := types.Delegation{ @@ -369,7 +369,7 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) { validator, pool, issuedShares = validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) delegation := types.Delegation{ DelegatorAddr: addrDels[0], @@ -433,7 +433,7 @@ func TestUnbondingAllDelegationFromValidator(t *testing.T) { validator, pool, issuedShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) selfDelegation := types.Delegation{ @@ -448,7 +448,7 @@ func TestUnbondingAllDelegationFromValidator(t *testing.T) { validator, pool, issuedShares = validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) delegation := types.Delegation{ DelegatorAddr: addrDels[0], @@ -595,7 +595,7 @@ func TestRedelegateToSameValidator(t *testing.T) { validator, pool, issuedShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) selfDelegation := types.Delegation{ @@ -621,7 +621,7 @@ func TestRedelegateSelfDelegation(t *testing.T) { validator, pool, issuedShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) selfDelegation := types.Delegation{ @@ -637,14 +637,14 @@ func TestRedelegateSelfDelegation(t *testing.T) { require.Equal(t, int64(10), issuedShares.RoundInt64()) pool.BondedTokens = pool.BondedTokens.Add(sdk.NewDec(10)) keeper.SetPool(ctx, pool) - validator2 = TestingUpdateValidator(keeper, ctx, validator2) + validator2 = TestingUpdateValidator(keeper, ctx, validator2, true) require.Equal(t, sdk.Bonded, validator2.Status) // create a second delegation to this validator validator, pool, issuedShares = validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) delegation := types.Delegation{ DelegatorAddr: addrDels[0], @@ -673,12 +673,11 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { //create a validator with a self-delegation validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - validator.BondIntraTxCounter = 1 validator, pool, issuedShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) selfDelegation := types.Delegation{ @@ -693,7 +692,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { validator, pool, issuedShares = validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) delegation := types.Delegation{ DelegatorAddr: addrDels[0], @@ -704,11 +703,10 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { // create a second validator validator2 := types.NewValidator(addrVals[1], PKs[1], types.Description{}) - validator2.BondIntraTxCounter = 2 validator2, pool, issuedShares = validator2.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator2 = TestingUpdateValidator(keeper, ctx, validator2) + validator2 = TestingUpdateValidator(keeper, ctx, validator2, true) header := ctx.BlockHeader() blockHeight := int64(10) @@ -762,7 +760,7 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) { validator, pool, issuedShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) selfDelegation := types.Delegation{ @@ -775,10 +773,9 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) { // create a second delegation to this validator keeper.DeleteValidatorByPowerIndex(ctx, validator) validator, pool, issuedShares = validator.AddTokensFromDel(pool, sdk.NewInt(10)) - validator.BondIntraTxCounter = 1 require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) pool = keeper.GetPool(ctx) delegation := types.Delegation{ DelegatorAddr: addrDels[0], @@ -789,11 +786,10 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) { // create a second validator validator2 := types.NewValidator(addrVals[1], PKs[1], types.Description{}) - validator2.BondIntraTxCounter = 2 validator2, pool, issuedShares = validator2.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) - validator2 = TestingUpdateValidator(keeper, ctx, validator2) + validator2 = TestingUpdateValidator(keeper, ctx, validator2, true) require.Equal(t, sdk.Bonded, validator2.Status) ctx = ctx.WithBlockHeight(10) diff --git a/x/stake/keeper/keeper.go b/x/stake/keeper/keeper.go index b6c973f98..a66daa1a5 100644 --- a/x/stake/keeper/keeper.go +++ b/x/stake/keeper/keeper.go @@ -132,24 +132,3 @@ func (k Keeper) DeleteLastValidatorPower(ctx sdk.Context, operator sdk.ValAddres store := ctx.KVStore(k.storeKey) store.Delete(GetLastValidatorPowerKey(operator)) } - -//__________________________________________________________________________ - -// get the current in-block validator operation counter -func (k Keeper) GetIntraTxCounter(ctx sdk.Context) int16 { - store := ctx.KVStore(k.storeKey) - b := store.Get(IntraTxCounterKey) - if b == nil { - return 0 - } - var counter int16 - k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &counter) - return counter -} - -// set the current in-block validator operation counter -func (k Keeper) SetIntraTxCounter(ctx sdk.Context, counter int16) { - store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshalBinaryLengthPrefixed(counter) - store.Set(IntraTxCounterKey, bz) -} diff --git a/x/stake/keeper/key.go b/x/stake/keeper/key.go index 34fa1a5b2..ce1429052 100644 --- a/x/stake/keeper/key.go +++ b/x/stake/keeper/key.go @@ -15,8 +15,7 @@ var ( // Keys for store prefixes // TODO DEPRECATED: delete in next release and reorder keys // ParamKey = []byte{0x00} // key for parameters relating to staking - PoolKey = []byte{0x01} // key for the staking pools - IntraTxCounterKey = []byte{0x02} // key for intra-block tx index + PoolKey = []byte{0x01} // key for the staking pools // Last* values are const during a block. LastValidatorPowerKey = []byte{0x11} // prefix for each key to a validator index, for bonded validators @@ -84,22 +83,34 @@ func getValidatorPowerRank(validator types.Validator) []byte { binary.BigEndian.PutUint64(tendermintPowerBytes[:], uint64(tendermintPower)) powerBytes := tendermintPowerBytes - powerBytesLen := len(powerBytes) + powerBytesLen := len(powerBytes) // 8 - // key is of format prefix || powerbytes || heightBytes || counterBytes - key := make([]byte, 1+powerBytesLen+8+2) + // key is of format prefix || powerbytes || addrBytes + key := make([]byte, 1+powerBytesLen+sdk.AddrLen) key[0] = ValidatorsByPowerIndexKey[0] copy(key[1:powerBytesLen+1], powerBytes) - - // include heightBytes height is inverted (older validators first) - binary.BigEndian.PutUint64(key[powerBytesLen+1:powerBytesLen+9], ^uint64(validator.BondHeight)) - // include counterBytes, counter is inverted (first txns have priority) - binary.BigEndian.PutUint16(key[powerBytesLen+9:powerBytesLen+11], ^uint16(validator.BondIntraTxCounter)) + operAddrInvr := cp(validator.OperatorAddr) + for i, b := range operAddrInvr { + operAddrInvr[i] = ^b + } + copy(key[powerBytesLen+1:], operAddrInvr) return key } +func parseValidatorPowerRankKey(key []byte) (operAddr []byte) { + powerBytesLen := 8 + if len(key) != 1+powerBytesLen+sdk.AddrLen { + panic("Invalid validator power rank key length") + } + operAddr = cp(key[powerBytesLen+1:]) + for i, b := range operAddr { + operAddr[i] = ^b + } + return operAddr +} + // gets the prefix for all unbonding delegations from a delegator func GetValidatorQueueTimeKey(timestamp time.Time) []byte { bz := sdk.FormatTimeBytes(timestamp) @@ -262,3 +273,14 @@ func GetREDsByDelToValDstIndexKey(delAddr sdk.AccAddress, valDstAddr sdk.ValAddr GetREDsToValDstIndexKey(valDstAddr), delAddr.Bytes()...) } + +//------------------------------------------------- + +func cp(bz []byte) (ret []byte) { + if bz == nil { + return nil + } + ret = make([]byte, len(bz)) + copy(ret, bz) + return ret +} diff --git a/x/stake/keeper/key_test.go b/x/stake/keeper/key_test.go index 385f313c1..0658e4b24 100644 --- a/x/stake/keeper/key_test.go +++ b/x/stake/keeper/key_test.go @@ -35,10 +35,10 @@ func TestGetValidatorPowerRank(t *testing.T) { validator types.Validator wantHex string }{ - {val1, "230000000000000000ffffffffffffffffffff"}, - {val2, "230000000000000001ffffffffffffffffffff"}, - {val3, "23000000000000000affffffffffffffffffff"}, - {val4, "230000010000000000ffffffffffffffffffff"}, + {val1, "2300000000000000009c288ede7df62742fc3b7d0962045a8cef0f79f6"}, + {val2, "2300000000000000019c288ede7df62742fc3b7d0962045a8cef0f79f6"}, + {val3, "23000000000000000a9c288ede7df62742fc3b7d0962045a8cef0f79f6"}, + {val4, "2300000100000000009c288ede7df62742fc3b7d0962045a8cef0f79f6"}, } for i, tt := range tests { got := hex.EncodeToString(getValidatorPowerRank(tt.validator)) diff --git a/x/stake/keeper/slash_test.go b/x/stake/keeper/slash_test.go index 9c23576c3..9f89dd210 100644 --- a/x/stake/keeper/slash_test.go +++ b/x/stake/keeper/slash_test.go @@ -26,10 +26,9 @@ func setupHelper(t *testing.T, amt int64) (sdk.Context, Keeper, types.Params) { for i := 0; i < numVals; i++ { validator := types.NewValidator(addrVals[i], PKs[i], types.Description{}) validator, pool, _ = validator.AddTokensFromDel(pool, sdk.NewInt(amt)) - validator.BondIntraTxCounter = int16(i) pool.BondedTokens = pool.BondedTokens.Add(sdk.NewDec(amt)) keeper.SetPool(ctx, pool) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) keeper.SetValidatorByConsAddr(ctx, validator) } pool = keeper.GetPool(ctx) diff --git a/x/stake/keeper/test_common.go b/x/stake/keeper/test_common.go index 244a8107f..f52b41c44 100644 --- a/x/stake/keeper/test_common.go +++ b/x/stake/keeper/test_common.go @@ -201,15 +201,41 @@ func ValidatorByPowerIndexExists(ctx sdk.Context, keeper Keeper, power []byte) b } // update validator for testing -func TestingUpdateValidator(keeper Keeper, ctx sdk.Context, validator types.Validator) types.Validator { +func TestingUpdateValidator(keeper Keeper, ctx sdk.Context, validator types.Validator, apply bool) types.Validator { keeper.SetValidator(ctx, validator) - keeper.SetValidatorByPowerIndex(ctx, validator) - keeper.ApplyAndReturnValidatorSetUpdates(ctx) - validator, found := keeper.GetValidator(ctx, validator.OperatorAddr) - if !found { - panic("validator expected but not found") + { // Remove any existing power key for validator. + store := ctx.KVStore(keeper.storeKey) + iterator := sdk.KVStorePrefixIterator(store, ValidatorsByPowerIndexKey) + deleted := false + for ; iterator.Valid(); iterator.Next() { + valAddr := parseValidatorPowerRankKey(iterator.Key()) + if bytes.Equal(valAddr, validator.OperatorAddr) { + if deleted { + panic("found duplicate power index key") + } else { + deleted = true + } + store.Delete(iterator.Key()) + } + } + } + keeper.SetValidatorByPowerIndex(ctx, validator) + if apply { + keeper.ApplyAndReturnValidatorSetUpdates(ctx) + validator, found := keeper.GetValidator(ctx, validator.OperatorAddr) + if !found { + panic("validator expected but not found") + } + return validator + } else { + cachectx, _ := ctx.CacheContext() + keeper.ApplyAndReturnValidatorSetUpdates(cachectx) + validator, found := keeper.GetValidator(cachectx, validator.OperatorAddr) + if !found { + panic("validator expected but not found") + } + return validator } - return validator } func validatorByPowerIndexExists(k Keeper, ctx sdk.Context, power []byte) bool { diff --git a/x/stake/keeper/validator.go b/x/stake/keeper/validator.go index 2d71ec513..8ec062605 100644 --- a/x/stake/keeper/validator.go +++ b/x/stake/keeper/validator.go @@ -129,11 +129,6 @@ func (k Keeper) AddValidatorTokensAndShares(ctx sdk.Context, validator types.Val k.DeleteValidatorByPowerIndex(ctx, validator) pool := k.GetPool(ctx) validator, pool, addedShares = validator.AddTokensFromDel(pool, tokensToAdd) - // increment the intra-tx counter - // in case of a conflict, the validator which least recently changed power takes precedence - counter := k.GetIntraTxCounter(ctx) - validator.BondIntraTxCounter = counter - k.SetIntraTxCounter(ctx, counter+1) k.SetValidator(ctx, validator) k.SetPool(ctx, pool) k.SetValidatorByPowerIndex(ctx, validator) diff --git a/x/stake/keeper/validator_test.go b/x/stake/keeper/validator_test.go index ed89f0edf..71b0edcd1 100644 --- a/x/stake/keeper/validator_test.go +++ b/x/stake/keeper/validator_test.go @@ -84,7 +84,7 @@ func TestUpdateValidatorByPowerIndex(t *testing.T) { require.Equal(t, sdk.Unbonded, validator.Status) require.Equal(t, int64(100), validator.Tokens.RoundInt64()) keeper.SetPool(ctx, pool) - TestingUpdateValidator(keeper, ctx, validator) + TestingUpdateValidator(keeper, ctx, validator, true) validator, found := keeper.GetValidator(ctx, addrVals[0]) require.True(t, found) require.Equal(t, int64(100), validator.Tokens.RoundInt64(), "\nvalidator %v\npool %v", validator, pool) @@ -97,8 +97,8 @@ func TestUpdateValidatorByPowerIndex(t *testing.T) { keeper.DeleteValidatorByPowerIndex(ctx, validator) validator, pool, burned := validator.RemoveDelShares(pool, delSharesCreated.Quo(sdk.NewDec(2))) require.Equal(t, int64(50), burned.RoundInt64()) - keeper.SetPool(ctx, pool) // update the pool - TestingUpdateValidator(keeper, ctx, validator) // update the validator, possibly kicking it out + keeper.SetPool(ctx, pool) // update the pool + TestingUpdateValidator(keeper, ctx, validator, true) // update the validator, possibly kicking it out require.False(t, validatorByPowerIndexExists(keeper, ctx, power)) pool = keeper.GetPool(ctx) @@ -131,11 +131,10 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { moniker := fmt.Sprintf("val#%d", int64(i)) val := types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{Moniker: moniker}) val.BondHeight = int64(i) - val.BondIntraTxCounter = int16(i) val, pool, _ = val.AddTokensFromDel(pool, sdk.NewInt(int64((i+1)*10))) keeper.SetPool(ctx, pool) - val = TestingUpdateValidator(keeper, ctx, val) + val = TestingUpdateValidator(keeper, ctx, val, true) validators[i] = val } @@ -146,7 +145,7 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { keeper.DeleteValidatorByPowerIndex(ctx, nextCliffVal) nextCliffVal, pool, _ = nextCliffVal.RemoveDelShares(pool, sdk.NewDec(21)) keeper.SetPool(ctx, pool) - nextCliffVal = TestingUpdateValidator(keeper, ctx, nextCliffVal) + nextCliffVal = TestingUpdateValidator(keeper, ctx, nextCliffVal, true) expectedValStatus := map[int]sdk.BondStatus{ 9: sdk.Bonded, 8: sdk.Bonded, 7: sdk.Bonded, 5: sdk.Bonded, 4: sdk.Bonded, @@ -178,7 +177,7 @@ func TestSlashToZeroPowerRemoved(t *testing.T) { require.Equal(t, int64(100), validator.Tokens.RoundInt64()) keeper.SetPool(ctx, pool) keeper.SetValidatorByConsAddr(ctx, validator) - validator = TestingUpdateValidator(keeper, ctx, validator) + validator = TestingUpdateValidator(keeper, ctx, validator, true) require.Equal(t, int64(100), validator.Tokens.RoundInt64(), "\nvalidator %v\npool %v", validator, pool) // slash the validator by 100% @@ -223,7 +222,7 @@ func TestValidatorBasics(t *testing.T) { assert.True(sdk.DecEq(t, sdk.ZeroDec(), pool.BondedTokens)) // set and retrieve a record - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], true) keeper.SetValidatorByConsAddr(ctx, validators[0]) resVal, found := keeper.GetValidator(ctx, addrVals[0]) require.True(t, found) @@ -250,7 +249,7 @@ func TestValidatorBasics(t *testing.T) { validators[0].Status = sdk.Bonded validators[0].Tokens = sdk.NewDec(10) validators[0].DelegatorShares = sdk.NewDec(10) - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], true) resVal, found = keeper.GetValidator(ctx, addrVals[0]) require.True(t, found) assert.True(ValEq(t, validators[0], resVal)) @@ -260,8 +259,8 @@ func TestValidatorBasics(t *testing.T) { assert.True(ValEq(t, validators[0], resVals[0])) // add other validators - validators[1] = TestingUpdateValidator(keeper, ctx, validators[1]) - validators[2] = TestingUpdateValidator(keeper, ctx, validators[2]) + validators[1] = TestingUpdateValidator(keeper, ctx, validators[1], true) + validators[2] = TestingUpdateValidator(keeper, ctx, validators[2], true) resVal, found = keeper.GetValidator(ctx, addrVals[1]) require.True(t, found) assert.True(ValEq(t, validators[1], resVal)) @@ -296,7 +295,7 @@ func GetValidatorSortingUnmixed(t *testing.T) { validators[i].Status = sdk.Bonded validators[i].Tokens = sdk.NewDec(amt) validators[i].DelegatorShares = sdk.NewDec(amt) - TestingUpdateValidator(keeper, ctx, validators[i]) + TestingUpdateValidator(keeper, ctx, validators[i], true) } // first make sure everything made it in to the gotValidator group @@ -315,14 +314,14 @@ func GetValidatorSortingUnmixed(t *testing.T) { // test a basic increase in voting power validators[3].Tokens = sdk.NewDec(500) - TestingUpdateValidator(keeper, ctx, validators[3]) + TestingUpdateValidator(keeper, ctx, validators[3], true) resValidators = keeper.GetBondedValidatorsByPower(ctx) require.Equal(t, len(resValidators), n) assert.True(ValEq(t, validators[3], resValidators[0])) // test a decrease in voting power validators[3].Tokens = sdk.NewDec(300) - TestingUpdateValidator(keeper, ctx, validators[3]) + TestingUpdateValidator(keeper, ctx, validators[3], true) resValidators = keeper.GetBondedValidatorsByPower(ctx) require.Equal(t, len(resValidators), n) assert.True(ValEq(t, validators[3], resValidators[0])) @@ -331,7 +330,7 @@ func GetValidatorSortingUnmixed(t *testing.T) { // test equal voting power, different age validators[3].Tokens = sdk.NewDec(200) ctx = ctx.WithBlockHeight(10) - TestingUpdateValidator(keeper, ctx, validators[3]) + TestingUpdateValidator(keeper, ctx, validators[3], true) resValidators = keeper.GetBondedValidatorsByPower(ctx) require.Equal(t, len(resValidators), n) assert.True(ValEq(t, validators[3], resValidators[0])) @@ -341,7 +340,7 @@ func GetValidatorSortingUnmixed(t *testing.T) { // no change in voting power - no change in sort ctx = ctx.WithBlockHeight(20) - TestingUpdateValidator(keeper, ctx, validators[4]) + TestingUpdateValidator(keeper, ctx, validators[4], true) resValidators = keeper.GetBondedValidatorsByPower(ctx) require.Equal(t, len(resValidators), n) assert.True(ValEq(t, validators[3], resValidators[0])) @@ -350,11 +349,11 @@ func GetValidatorSortingUnmixed(t *testing.T) { // change in voting power of both validators, both still in v-set, no age change validators[3].Tokens = sdk.NewDec(300) validators[4].Tokens = sdk.NewDec(300) - TestingUpdateValidator(keeper, ctx, validators[3]) + TestingUpdateValidator(keeper, ctx, validators[3], true) resValidators = keeper.GetBondedValidatorsByPower(ctx) require.Equal(t, len(resValidators), n) ctx = ctx.WithBlockHeight(30) - TestingUpdateValidator(keeper, ctx, validators[4]) + TestingUpdateValidator(keeper, ctx, validators[4], true) resValidators = keeper.GetBondedValidatorsByPower(ctx) require.Equal(t, len(resValidators), n, "%v", resValidators) assert.True(ValEq(t, validators[3], resValidators[0])) @@ -392,7 +391,7 @@ func GetValidatorSortingMixed(t *testing.T) { validators[4].Tokens = sdk.NewDec(amts[4]) for i := range amts { - TestingUpdateValidator(keeper, ctx, validators[i]) + TestingUpdateValidator(keeper, ctx, validators[i], true) } val0, found := keeper.GetValidator(ctx, sdk.ValAddress(Addrs[0])) require.True(t, found) @@ -444,9 +443,8 @@ func TestGetValidatorsEdgeCases(t *testing.T) { moniker := fmt.Sprintf("val#%d", int64(i)) validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{Moniker: moniker}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) - validators[i].BondIntraTxCounter = int16(i) keeper.SetPool(ctx, pool) - validators[i] = TestingUpdateValidator(keeper, ctx, validators[i]) + validators[i] = TestingUpdateValidator(keeper, ctx, validators[i], true) } for i := range amts { @@ -462,7 +460,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { keeper.DeleteValidatorByPowerIndex(ctx, validators[0]) validators[0], pool, _ = validators[0].AddTokensFromDel(pool, sdk.NewInt(500)) keeper.SetPool(ctx, pool) - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], true) resValidators = keeper.GetBondedValidatorsByPower(ctx) require.Equal(t, nMax, uint16(len(resValidators))) assert.True(ValEq(t, validators[0], resValidators[0])) @@ -480,7 +478,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { keeper.DeleteValidatorByPowerIndex(ctx, validators[3]) validators[3], pool, _ = validators[3].AddTokensFromDel(pool, sdk.NewInt(1)) keeper.SetPool(ctx, pool) - validators[3] = TestingUpdateValidator(keeper, ctx, validators[3]) + validators[3] = TestingUpdateValidator(keeper, ctx, validators[3], true) resValidators = keeper.GetBondedValidatorsByPower(ctx) require.Equal(t, nMax, uint16(len(resValidators))) assert.True(ValEq(t, validators[0], resValidators[0])) @@ -490,7 +488,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { keeper.DeleteValidatorByPowerIndex(ctx, validators[3]) validators[3], pool, _ = validators[3].RemoveDelShares(pool, sdk.NewDec(201)) keeper.SetPool(ctx, pool) - validators[3] = TestingUpdateValidator(keeper, ctx, validators[3]) + validators[3] = TestingUpdateValidator(keeper, ctx, validators[3], true) resValidators = keeper.GetBondedValidatorsByPower(ctx) require.Equal(t, nMax, uint16(len(resValidators))) assert.True(ValEq(t, validators[0], resValidators[0])) @@ -500,7 +498,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { keeper.DeleteValidatorByPowerIndex(ctx, validators[3]) validators[3], pool, _ = validators[3].AddTokensFromDel(pool, sdk.NewInt(200)) keeper.SetPool(ctx, pool) - validators[3] = TestingUpdateValidator(keeper, ctx, validators[3]) + validators[3] = TestingUpdateValidator(keeper, ctx, validators[3], true) resValidators = keeper.GetBondedValidatorsByPower(ctx) require.Equal(t, nMax, uint16(len(resValidators))) assert.True(ValEq(t, validators[0], resValidators[0])) @@ -524,22 +522,19 @@ func TestValidatorBondHeight(t *testing.T) { validators[0] = types.NewValidator(sdk.ValAddress(Addrs[0]), PKs[0], types.Description{}) validators[1] = types.NewValidator(sdk.ValAddress(Addrs[1]), PKs[1], types.Description{}) validators[2] = types.NewValidator(sdk.ValAddress(Addrs[2]), PKs[2], types.Description{}) - validators[0].BondIntraTxCounter = 0 - validators[1].BondIntraTxCounter = 1 - validators[2].BondIntraTxCounter = 2 validators[0], pool, _ = validators[0].AddTokensFromDel(pool, sdk.NewInt(200)) validators[1], pool, _ = validators[1].AddTokensFromDel(pool, sdk.NewInt(100)) validators[2], pool, _ = validators[2].AddTokensFromDel(pool, sdk.NewInt(100)) keeper.SetPool(ctx, pool) - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], true) //////////////////////////////////////// // If two validators both increase to the same voting power in the same block, // the one with the first transaction should become bonded - validators[1] = TestingUpdateValidator(keeper, ctx, validators[1]) - validators[2] = TestingUpdateValidator(keeper, ctx, validators[2]) + validators[1] = TestingUpdateValidator(keeper, ctx, validators[1], true) + validators[2] = TestingUpdateValidator(keeper, ctx, validators[2], true) pool = keeper.GetPool(ctx) @@ -553,10 +548,10 @@ func TestValidatorBondHeight(t *testing.T) { validators[1], pool, _ = validators[1].AddTokensFromDel(pool, sdk.NewInt(50)) validators[2], pool, _ = validators[2].AddTokensFromDel(pool, sdk.NewInt(50)) keeper.SetPool(ctx, pool) - validators[2] = TestingUpdateValidator(keeper, ctx, validators[2]) + validators[2] = TestingUpdateValidator(keeper, ctx, validators[2], true) resValidators = keeper.GetBondedValidatorsByPower(ctx) require.Equal(t, params.MaxValidators, uint16(len(resValidators))) - validators[1] = TestingUpdateValidator(keeper, ctx, validators[1]) + validators[1] = TestingUpdateValidator(keeper, ctx, validators[1], true) assert.True(ValEq(t, validators[0], resValidators[0])) assert.True(ValEq(t, validators[2], resValidators[1])) } @@ -575,9 +570,8 @@ func TestFullValidatorSetPowerChange(t *testing.T) { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) - validators[i].BondIntraTxCounter = int16(i) keeper.SetPool(ctx, pool) - TestingUpdateValidator(keeper, ctx, validators[i]) + TestingUpdateValidator(keeper, ctx, validators[i], true) } for i := range amts { var found bool @@ -598,7 +592,7 @@ func TestFullValidatorSetPowerChange(t *testing.T) { pool := keeper.GetPool(ctx) validators[0], pool, _ = validators[0].AddTokensFromDel(pool, sdk.NewInt(600)) keeper.SetPool(ctx, pool) - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], true) resValidators = keeper.GetBondedValidatorsByPower(ctx) assert.Equal(t, max, len(resValidators)) assert.True(ValEq(t, validators[0], resValidators[0])) @@ -648,14 +642,14 @@ func TestApplyAndReturnValidatorSetUpdatesIdentical(t *testing.T) { validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) - validators[1] = TestingUpdateValidator(keeper, ctx, validators[1]) - require.Equal(t, 0, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], false) + validators[1] = TestingUpdateValidator(keeper, ctx, validators[1], false) + require.Equal(t, 2, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) // test identical, // tendermintUpdate set: {} -> {} - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) - validators[1] = TestingUpdateValidator(keeper, ctx, validators[1]) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], false) + validators[1] = TestingUpdateValidator(keeper, ctx, validators[1], false) require.Equal(t, 0, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) } @@ -670,15 +664,15 @@ func TestApplyAndReturnValidatorSetUpdatesSingleValueChange(t *testing.T) { validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) - validators[1] = TestingUpdateValidator(keeper, ctx, validators[1]) - require.Equal(t, 0, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], false) + validators[1] = TestingUpdateValidator(keeper, ctx, validators[1], false) + require.Equal(t, 2, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) // test single value change // tendermintUpdate set: {} -> {c1'} validators[0].Status = sdk.Bonded validators[0].Tokens = sdk.NewDec(600) - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], false) updates := keeper.ApplyAndReturnValidatorSetUpdates(ctx) @@ -697,9 +691,9 @@ func TestApplyAndReturnValidatorSetUpdatesMultipleValueChange(t *testing.T) { validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) - validators[1] = TestingUpdateValidator(keeper, ctx, validators[1]) - require.Equal(t, 0, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], false) + validators[1] = TestingUpdateValidator(keeper, ctx, validators[1], false) + require.Equal(t, 2, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) // test multiple value change // tendermintUpdate set: {c1, c3} -> {c1', c3'} @@ -707,13 +701,13 @@ func TestApplyAndReturnValidatorSetUpdatesMultipleValueChange(t *testing.T) { validators[0], pool, _ = validators[0].AddTokensFromDel(pool, sdk.NewInt(190)) validators[1], pool, _ = validators[1].AddTokensFromDel(pool, sdk.NewInt(80)) keeper.SetPool(ctx, pool) - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) - validators[1] = TestingUpdateValidator(keeper, ctx, validators[1]) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], false) + validators[1] = TestingUpdateValidator(keeper, ctx, validators[1], false) updates := keeper.ApplyAndReturnValidatorSetUpdates(ctx) require.Equal(t, 2, len(updates)) - require.Equal(t, validators[0].ABCIValidatorUpdate(), updates[1]) - require.Equal(t, validators[1].ABCIValidatorUpdate(), updates[0]) + require.Equal(t, validators[0].ABCIValidatorUpdate(), updates[0]) + require.Equal(t, validators[1].ABCIValidatorUpdate(), updates[1]) } func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) { @@ -727,9 +721,9 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) { validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) - validators[1] = TestingUpdateValidator(keeper, ctx, validators[1]) - require.Equal(t, 0, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], false) + validators[1] = TestingUpdateValidator(keeper, ctx, validators[1], false) + require.Equal(t, 2, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) // test validtor added at the beginning // tendermintUpdate set: {} -> {c0} @@ -773,13 +767,13 @@ func TestApplyAndReturnValidatorSetUpdatesWithCliffValidator(t *testing.T) { validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) - validators[1] = TestingUpdateValidator(keeper, ctx, validators[1]) - require.Equal(t, 0, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], false) + validators[1] = TestingUpdateValidator(keeper, ctx, validators[1], false) + require.Equal(t, 2, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) // test validator added at the end but not inserted in the valset // tendermintUpdate set: {} -> {} - TestingUpdateValidator(keeper, ctx, validators[2]) + TestingUpdateValidator(keeper, ctx, validators[2], false) updates := keeper.ApplyAndReturnValidatorSetUpdates(ctx) require.Equal(t, 0, len(updates)) @@ -808,12 +802,11 @@ func TestApplyAndReturnValidatorSetUpdatesPowerDecrease(t *testing.T) { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) - validators[i].BondIntraTxCounter = int16(i) keeper.SetPool(ctx, pool) } - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) - validators[1] = TestingUpdateValidator(keeper, ctx, validators[1]) - require.Equal(t, 0, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], false) + validators[1] = TestingUpdateValidator(keeper, ctx, validators[1], false) + require.Equal(t, 2, len(keeper.ApplyAndReturnValidatorSetUpdates(ctx))) // check initial power require.Equal(t, sdk.NewDec(100).RoundInt64(), validators[0].GetPower().RoundInt64()) @@ -825,8 +818,8 @@ func TestApplyAndReturnValidatorSetUpdatesPowerDecrease(t *testing.T) { validators[0], pool, _ = validators[0].RemoveDelShares(pool, sdk.NewDec(20)) validators[1], pool, _ = validators[1].RemoveDelShares(pool, sdk.NewDec(30)) keeper.SetPool(ctx, pool) - validators[0] = TestingUpdateValidator(keeper, ctx, validators[0]) - validators[1] = TestingUpdateValidator(keeper, ctx, validators[1]) + validators[0] = TestingUpdateValidator(keeper, ctx, validators[0], false) + validators[1] = TestingUpdateValidator(keeper, ctx, validators[1], false) // power has changed require.Equal(t, sdk.NewDec(80).RoundInt64(), validators[0].GetPower().RoundInt64()) @@ -856,7 +849,6 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { valAddr := sdk.ValAddress(valPubKey.Address().Bytes()) validators[i] = types.NewValidator(valAddr, valPubKey, types.Description{}) - validators[i].BondIntraTxCounter = int16(i) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) @@ -942,7 +934,6 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { validators[i] = types.NewValidator(valAddr, valPubKey, types.Description{Moniker: moniker}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) - validators[i].BondIntraTxCounter = int16(i) keeper.SetPool(ctx, pool) keeper.SetValidator(ctx, validators[i]) keeper.SetValidatorByPowerIndex(ctx, validators[i]) diff --git a/x/stake/querier/querier_test.go b/x/stake/querier/querier_test.go index d6ea3639e..c13a37897 100644 --- a/x/stake/querier/querier_test.go +++ b/x/stake/querier/querier_test.go @@ -27,7 +27,6 @@ func TestNewQuerier(t *testing.T) { for i, amt := range amts { validators[i] = types.NewValidator(sdk.ValAddress(keep.Addrs[i]), keep.PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) - validators[i].BondIntraTxCounter = int16(i) keeper.SetValidator(ctx, validators[i]) keeper.SetValidatorByPowerIndex(ctx, validators[i]) } diff --git a/x/stake/stake.go b/x/stake/stake.go index 2e5b8feb7..f5a029a72 100644 --- a/x/stake/stake.go +++ b/x/stake/stake.go @@ -38,7 +38,6 @@ var ( GetDelegationKey = keeper.GetDelegationKey GetDelegationsKey = keeper.GetDelegationsKey PoolKey = keeper.PoolKey - IntraTxCounterKey = keeper.IntraTxCounterKey LastValidatorPowerKey = keeper.LastValidatorPowerKey LastTotalPowerKey = keeper.LastTotalPowerKey ValidatorsKey = keeper.ValidatorsKey diff --git a/x/stake/types/genesis.go b/x/stake/types/genesis.go index 1085e8f97..12c732781 100644 --- a/x/stake/types/genesis.go +++ b/x/stake/types/genesis.go @@ -8,7 +8,6 @@ import ( type GenesisState struct { Pool Pool `json:"pool"` Params Params `json:"params"` - IntraTxCounter int16 `json:"intra_tx_counter"` LastTotalPower sdk.Int `json:"last_total_power"` LastValidatorPowers []LastValidatorPower `json:"last_validator_powers"` Validators []Validator `json:"validators"` diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index 90558dd96..517671c3a 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -29,9 +29,8 @@ type Validator struct { Tokens sdk.Dec `json:"tokens"` // delegated tokens (incl. self-delegation) DelegatorShares sdk.Dec `json:"delegator_shares"` // total shares issued to a validator's delegators - Description Description `json:"description"` // description terms for the validator - BondHeight int64 `json:"bond_height"` // earliest height as a bonded validator - BondIntraTxCounter int16 `json:"bond_intra_tx_counter"` // block-local tx index of validator change + Description Description `json:"description"` // description terms for the validator + BondHeight int64 `json:"bond_height"` // earliest height as a bonded validator UnbondingHeight int64 `json:"unbonding_height"` // if unbonding, height at which this validator has begun unbonding UnbondingMinTime time.Time `json:"unbonding_time"` // if unbonding, min time for the validator to complete unbonding @@ -42,50 +41,47 @@ type Validator struct { // NewValidator - initialize a new validator func NewValidator(operator sdk.ValAddress, pubKey crypto.PubKey, description Description) Validator { return Validator{ - OperatorAddr: operator, - ConsPubKey: pubKey, - Jailed: false, - Status: sdk.Unbonded, - Tokens: sdk.ZeroDec(), - DelegatorShares: sdk.ZeroDec(), - Description: description, - BondHeight: int64(0), - BondIntraTxCounter: int16(0), - UnbondingHeight: int64(0), - UnbondingMinTime: time.Unix(0, 0).UTC(), - Commission: NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), + OperatorAddr: operator, + ConsPubKey: pubKey, + Jailed: false, + Status: sdk.Unbonded, + Tokens: sdk.ZeroDec(), + DelegatorShares: sdk.ZeroDec(), + Description: description, + BondHeight: int64(0), + UnbondingHeight: int64(0), + UnbondingMinTime: time.Unix(0, 0).UTC(), + Commission: NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), } } // what's kept in the store value type validatorValue struct { - ConsPubKey crypto.PubKey - Jailed bool - Status sdk.BondStatus - Tokens sdk.Dec - DelegatorShares sdk.Dec - Description Description - BondHeight int64 - BondIntraTxCounter int16 - UnbondingHeight int64 - UnbondingMinTime time.Time - Commission Commission + ConsPubKey crypto.PubKey + Jailed bool + Status sdk.BondStatus + Tokens sdk.Dec + 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 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, - BondIntraTxCounter: validator.BondIntraTxCounter, - UnbondingHeight: validator.UnbondingHeight, - UnbondingMinTime: validator.UnbondingMinTime, - Commission: validator.Commission, + 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) } @@ -112,18 +108,17 @@ func UnmarshalValidator(cdc *codec.Codec, operatorAddr, value []byte) (validator } 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, - BondIntraTxCounter: storeValue.BondIntraTxCounter, - UnbondingHeight: storeValue.UnbondingHeight, - UnbondingMinTime: storeValue.UnbondingMinTime, - Commission: storeValue.Commission, + 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 } @@ -164,9 +159,8 @@ type bechValidator struct { Tokens sdk.Dec `json:"tokens"` // delegated tokens (incl. self-delegation) DelegatorShares sdk.Dec `json:"delegator_shares"` // total shares issued to a validator's delegators - Description Description `json:"description"` // description terms for the validator - BondHeight int64 `json:"bond_height"` // earliest height as a bonded validator - BondIntraTxCounter int16 `json:"bond_intra_tx_counter"` // block-local tx index of validator change + Description Description `json:"description"` // description terms for the validator + BondHeight int64 `json:"bond_height"` // earliest height as a bonded validator UnbondingHeight int64 `json:"unbonding_height"` // if unbonding, height at which this validator has begun unbonding UnbondingMinTime time.Time `json:"unbonding_time"` // if unbonding, min time for the validator to complete unbonding @@ -182,18 +176,17 @@ func (v Validator) MarshalJSON() ([]byte, error) { } return codec.Cdc.MarshalJSON(bechValidator{ - OperatorAddr: v.OperatorAddr, - ConsPubKey: bechConsPubKey, - Jailed: v.Jailed, - Status: v.Status, - Tokens: v.Tokens, - DelegatorShares: v.DelegatorShares, - Description: v.Description, - BondHeight: v.BondHeight, - BondIntraTxCounter: v.BondIntraTxCounter, - UnbondingHeight: v.UnbondingHeight, - UnbondingMinTime: v.UnbondingMinTime, - Commission: v.Commission, + OperatorAddr: v.OperatorAddr, + ConsPubKey: bechConsPubKey, + Jailed: v.Jailed, + Status: v.Status, + Tokens: v.Tokens, + DelegatorShares: v.DelegatorShares, + Description: v.Description, + BondHeight: v.BondHeight, + UnbondingHeight: v.UnbondingHeight, + UnbondingMinTime: v.UnbondingMinTime, + Commission: v.Commission, }) } @@ -208,25 +201,24 @@ func (v *Validator) UnmarshalJSON(data []byte) error { return err } *v = Validator{ - OperatorAddr: bv.OperatorAddr, - ConsPubKey: consPubKey, - Jailed: bv.Jailed, - Tokens: bv.Tokens, - Status: bv.Status, - DelegatorShares: bv.DelegatorShares, - Description: bv.Description, - BondHeight: bv.BondHeight, - BondIntraTxCounter: bv.BondIntraTxCounter, - UnbondingHeight: bv.UnbondingHeight, - UnbondingMinTime: bv.UnbondingMinTime, - Commission: bv.Commission, + OperatorAddr: bv.OperatorAddr, + ConsPubKey: consPubKey, + Jailed: bv.Jailed, + Tokens: bv.Tokens, + Status: bv.Status, + DelegatorShares: bv.DelegatorShares, + Description: bv.Description, + BondHeight: bv.BondHeight, + UnbondingHeight: bv.UnbondingHeight, + UnbondingMinTime: bv.UnbondingMinTime, + Commission: bv.Commission, } return nil } //___________________________________________________________________ -// only the vitals - does not check bond height of IntraTxCounter +// only the vitals func (v Validator) Equal(v2 Validator) bool { return v.ConsPubKey.Equals(v2.ConsPubKey) && bytes.Equal(v.OperatorAddr, v2.OperatorAddr) && From 945803d586b83d65547cd16f4cd5994eac2957ea Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Mon, 10 Dec 2018 18:50:20 +0800 Subject: [PATCH 06/21] Governance Quorum (#3053) --- PENDING.md | 1 + cmd/gaia/cmd/gaiareplay/main.go | 2 +- docs/spec/governance/overview.md | 4 ---- docs/spec/governance/state.md | 1 + x/gov/genesis.go | 1 + x/gov/params.go | 1 + x/gov/tally.go | 10 +++++++++- x/gov/tally_test.go | 26 ++++++++++++++++++++++++++ 8 files changed, 40 insertions(+), 6 deletions(-) diff --git a/PENDING.md b/PENDING.md index af6171e94..95ecba5b5 100644 --- a/PENDING.md +++ b/PENDING.md @@ -31,6 +31,7 @@ FEATURES - [\#2961](https://github.com/cosmos/cosmos-sdk/issues/2961) Add --force flag to gaiacli keys delete command to skip passphrase check and force key deletion unconditionally. * Gaia + - [gov] Added minimum quorum needed for vote to pass * SDK diff --git a/cmd/gaia/cmd/gaiareplay/main.go b/cmd/gaia/cmd/gaiareplay/main.go index 4f52889e2..cd58640e4 100644 --- a/cmd/gaia/cmd/gaiareplay/main.go +++ b/cmd/gaia/cmd/gaiareplay/main.go @@ -131,7 +131,7 @@ func run(rootDir string) { _ = proxyApp.Stop() }() - var state tmsm.State = tmsm.LoadState(tmDB) + state := tmsm.LoadState(tmDB) if state.LastBlockHeight == 0 { // Send InitChain msg fmt.Println("Sending InitChain msg") diff --git a/docs/spec/governance/overview.md b/docs/spec/governance/overview.md index a79b95190..e2efe5544 100644 --- a/docs/spec/governance/overview.md +++ b/docs/spec/governance/overview.md @@ -111,10 +111,6 @@ option that casts a `NoWithVeto` vote.* Quorum is defined as the minimum percentage of voting power that needs to be casted on a proposal for the result to be valid. -In the initial version of the governance module, there will be no quorum -enforced by the protocol. Participation is ensured via the combination of -inheritance and validator's punishment for non-voting. - ### Threshold Threshold is defined as the minimum proportion of `Yes` votes (excluding diff --git a/docs/spec/governance/state.md b/docs/spec/governance/state.md index 6c2799fd0..abe2dc41b 100644 --- a/docs/spec/governance/state.md +++ b/docs/spec/governance/state.md @@ -24,6 +24,7 @@ type VotingParams struct { ```go type TallyParams struct { + Quorum sdk.Dec // Minimum percentage of stake that needs to vote for a proposal to be considered valid Threshold sdk.Dec // Minimum proportion of Yes votes for proposal to pass. Initial value: 0.5 Veto sdk.Dec // Minimum proportion of Veto votes to Total votes ratio for proposal to be vetoed. Initial value: 1/3 GovernancePenalty sdk.Dec // Penalty if validator does not vote diff --git a/x/gov/genesis.go b/x/gov/genesis.go index 341a4253b..8498e3b5a 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -51,6 +51,7 @@ func DefaultGenesisState() GenesisState { VotingPeriod: time.Duration(172800) * time.Second, }, TallyParams: TallyParams{ + Quorum: sdk.NewDecWithPrec(334, 3), Threshold: sdk.NewDecWithPrec(5, 1), Veto: sdk.NewDecWithPrec(334, 3), GovernancePenalty: sdk.NewDecWithPrec(1, 2), diff --git a/x/gov/params.go b/x/gov/params.go index b9e1efa87..01da184d5 100644 --- a/x/gov/params.go +++ b/x/gov/params.go @@ -14,6 +14,7 @@ type DepositParams struct { // 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 Threshold sdk.Dec `json:"threshold"` // Minimum propotion of Yes votes for proposal to pass. Initial value: 0.5 Veto sdk.Dec `json:"veto"` // Minimum value of Veto votes to Total votes ratio for proposal to be vetoed. Initial value: 1/3 GovernancePenalty sdk.Dec `json:"governance_penalty"` // Penalty if validator does not vote diff --git a/x/gov/tally.go b/x/gov/tally.go index d66237762..199370e93 100644 --- a/x/gov/tally.go +++ b/x/gov/tally.go @@ -93,7 +93,15 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tall NoWithVeto: results[OptionNoWithVeto], } - // If no one votes, proposal fails + // If there is no staked coins, the proposal fails + if keeper.vs.TotalPower(ctx).Equal(sdk.ZeroDec()) { + return false, tallyResults + } + // If there is not enough quorum of votes, the proposal fails + if totalVotingPower.Quo(keeper.vs.TotalPower(ctx)).LT(tallyParams.Quorum) { + return false, tallyResults + } + // If no one votes (everyone abstains), proposal fails if totalVotingPower.Sub(results[OptionAbstain]).Equal(sdk.ZeroDec()) { return false, tallyResults } diff --git a/x/gov/tally_test.go b/x/gov/tally_test.go index b2f6aaf32..86564ed42 100644 --- a/x/gov/tally_test.go +++ b/x/gov/tally_test.go @@ -59,6 +59,32 @@ func TestTallyNoOneVotes(t *testing.T) { require.True(t, tallyResults.Equals(EmptyTallyResult())) } +func TestTallyNoQuorum(t *testing.T) { + mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) + mapp.BeginBlock(abci.RequestBeginBlock{}) + ctx := mapp.BaseApp.NewContext(false, abci.Header{}) + stakeHandler := stake.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) + + proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) + proposalID := proposal.GetProposalID() + proposal.SetStatus(StatusVotingPeriod) + keeper.SetProposal(ctx, proposal) + + err := keeper.AddVote(ctx, proposalID, addrs[0], OptionYes) + require.Nil(t, err) + + passes, _ := tally(ctx, keeper, keeper.GetProposal(ctx, proposalID)) + require.False(t, passes) +} + func TestTallyOnlyValidatorsAllYes(t *testing.T) { mapp, keeper, sk, addrs, _, _ := getMockApp(t, 10) mapp.BeginBlock(abci.RequestBeginBlock{}) From ac0a7c0a1d95206c3677e6d632035ddcd3dfdad6 Mon Sep 17 00:00:00 2001 From: Alessio Treglia Date: Mon, 10 Dec 2018 14:26:34 +0000 Subject: [PATCH 07/21] Move generate_only and simulate to POST body in REST txs Closes: #3056 --- client/lcd/lcd_test.go | 28 ++++++++++++++++------------ client/utils/rest.go | 30 +++++++----------------------- x/stake/client/rest/tx.go | 6 +++--- 3 files changed, 26 insertions(+), 38 deletions(-) diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 04453111a..34f8edbc9 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -279,29 +279,29 @@ func TestCoinSend(t *testing.T) { require.Equal(t, int64(1), mycoins.Amount.Int64()) // test failure with too little gas - res, body, _ = doSendWithGas(t, port, seed, name, password, addr, "100", 0, "") + res, body, _ = doSendWithGas(t, port, seed, name, password, addr, "100", 0, false, false) require.Equal(t, http.StatusInternalServerError, res.StatusCode, body) // test failure with negative gas - res, body, _ = doSendWithGas(t, port, seed, name, password, addr, "-200", 0, "") + res, body, _ = doSendWithGas(t, port, seed, name, password, addr, "-200", 0, false, false) require.Equal(t, http.StatusBadRequest, res.StatusCode, body) // test failure with 0 gas - res, body, _ = doSendWithGas(t, port, seed, name, password, addr, "0", 0, "") + res, body, _ = doSendWithGas(t, port, seed, name, password, addr, "0", 0, false, false) require.Equal(t, http.StatusInternalServerError, res.StatusCode, body) // test failure with wrong adjustment - res, body, _ = doSendWithGas(t, port, seed, name, password, addr, "simulate", 0.1, "") + res, body, _ = doSendWithGas(t, port, seed, name, password, addr, "simulate", 0.1, false, false) require.Equal(t, http.StatusInternalServerError, res.StatusCode, body) // run simulation and test success with estimated gas - res, body, _ = doSendWithGas(t, port, seed, name, password, addr, "", 0, "?simulate=true") + res, body, _ = doSendWithGas(t, port, seed, name, password, addr, "", 0, true, false) require.Equal(t, http.StatusOK, res.StatusCode, body) var responseBody struct { GasEstimate int64 `json:"gas_estimate"` } require.Nil(t, json.Unmarshal([]byte(body), &responseBody)) - res, body, _ = doSendWithGas(t, port, seed, name, password, addr, fmt.Sprintf("%v", responseBody.GasEstimate), 0, "") + res, body, _ = doSendWithGas(t, port, seed, name, password, addr, fmt.Sprintf("%v", responseBody.GasEstimate), 0, false, false) require.Equal(t, http.StatusOK, res.StatusCode, body) } @@ -342,7 +342,7 @@ func TestCoinSendGenerateSignAndBroadcast(t *testing.T) { acc := getAccount(t, port, addr) // generate TX - res, body, _ := doSendWithGas(t, port, seed, name, password, addr, "simulate", 0, "?generate_only=true") + res, body, _ := doSendWithGas(t, port, seed, name, password, addr, "simulate", 0, false, true) require.Equal(t, http.StatusOK, res.StatusCode, body) var msg auth.StdTx require.Nil(t, cdc.UnmarshalJSON([]byte(body), &msg)) @@ -897,7 +897,9 @@ func getAccount(t *testing.T, port string, addr sdk.AccAddress) auth.Account { return acc } -func doSendWithGas(t *testing.T, port, seed, name, password string, addr sdk.AccAddress, gas string, gasAdjustment float64, queryStr string) (res *http.Response, body string, receiveAddr sdk.AccAddress) { +func doSendWithGas(t *testing.T, port, seed, name, password string, addr sdk.AccAddress, gas string, + gasAdjustment float64, simulate, generateOnly bool) ( + res *http.Response, body string, receiveAddr sdk.AccAddress) { // create receive address kb := client.MockKeyBase() @@ -935,11 +937,13 @@ func doSendWithGas(t *testing.T, port, seed, name, password string, addr sdk.Acc "password": "%s", "chain_id": "%s", "account_number":"%d", - "sequence":"%d" + "sequence": "%d", + "simulate": %v, + "generate_only": %v } - }`, coinbz, gasStr, gasAdjustmentStr, name, password, chainID, accnum, sequence)) + }`, coinbz, gasStr, gasAdjustmentStr, name, password, chainID, accnum, sequence, simulate, generateOnly)) - res, body = Request(t, port, "POST", fmt.Sprintf("/bank/accounts/%s/transfers%v", receiveAddr, queryStr), jsonStr) + res, body = Request(t, port, "POST", fmt.Sprintf("/bank/accounts/%s/transfers", receiveAddr), jsonStr) return } @@ -958,7 +962,7 @@ func doRecoverKey(t *testing.T, port, recoverName, recoverPassword, seed string) } func doSend(t *testing.T, port, seed, name, password string, addr sdk.AccAddress) (receiveAddr sdk.AccAddress, resultTx ctypes.ResultBroadcastTxCommit) { - res, body, receiveAddr := doSendWithGas(t, port, seed, name, password, addr, "", 0, "") + res, body, receiveAddr := doSendWithGas(t, port, seed, name, password, addr, "", 0, false, false) require.Equal(t, http.StatusOK, res.StatusCode, body) err := cdc.UnmarshalJSON([]byte(body), &resultTx) diff --git a/client/utils/rest.go b/client/utils/rest.go index c0a8c3c77..36ff05af8 100644 --- a/client/utils/rest.go +++ b/client/utils/rest.go @@ -4,7 +4,6 @@ import ( "fmt" "io/ioutil" "net/http" - "net/url" "strconv" "strings" @@ -17,11 +16,6 @@ import ( authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" ) -const ( - queryArgDryRun = "simulate" - queryArgGenerateOnly = "generate_only" -) - //---------------------------------------- // Basic HTTP utilities @@ -39,18 +33,6 @@ func WriteSimulationResponse(w http.ResponseWriter, gas uint64) { w.Write([]byte(fmt.Sprintf(`{"gas_estimate":%v}`, gas))) } -// HasDryRunArg returns true if the request's URL query contains the dry run -// argument and its value is set to "true". -func HasDryRunArg(r *http.Request) bool { - return urlQueryHasArg(r.URL, queryArgDryRun) -} - -// HasGenerateOnlyArg returns whether a URL's query "generate-only" parameter -// is set to "true". -func HasGenerateOnlyArg(r *http.Request) bool { - return urlQueryHasArg(r.URL, queryArgGenerateOnly) -} - // ParseInt64OrReturnBadRequest converts s to a int64 value. func ParseInt64OrReturnBadRequest(w http.ResponseWriter, s string) (n int64, ok bool) { var err error @@ -113,8 +95,6 @@ func WriteGenerateStdTxResponse(w http.ResponseWriter, txBldr authtxb.TxBuilder, return } -func urlQueryHasArg(url *url.URL, arg string) bool { return url.Query().Get(arg) == "true" } - //---------------------------------------- // Building / Sending utilities @@ -128,6 +108,8 @@ type BaseReq struct { Sequence uint64 `json:"sequence"` Gas string `json:"gas"` GasAdjustment string `json:"gas_adjustment"` + GenerateOnly bool `json:"generate_only"` + Simulate bool `json:"simulate"` } // Sanitize performs basic sanitization on a BaseReq object. @@ -140,6 +122,8 @@ func (br BaseReq) Sanitize() BaseReq { GasAdjustment: strings.TrimSpace(br.GasAdjustment), AccountNumber: br.AccountNumber, Sequence: br.Sequence, + GenerateOnly: br.GenerateOnly, + Simulate: br.Simulate, } } @@ -223,14 +207,14 @@ func CompleteAndBroadcastTxREST(w http.ResponseWriter, r *http.Request, cliCtx c Sequence: baseReq.Sequence, } - if HasDryRunArg(r) || txBldr.SimulateGas { + if baseReq.Simulate || txBldr.SimulateGas { newBldr, err := EnrichCtxWithGas(txBldr, cliCtx, baseReq.Name, msgs) if err != nil { WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - if HasDryRunArg(r) { + if baseReq.Simulate { WriteSimulationResponse(w, newBldr.Gas) return } @@ -238,7 +222,7 @@ func CompleteAndBroadcastTxREST(w http.ResponseWriter, r *http.Request, cliCtx c txBldr = newBldr } - if HasGenerateOnlyArg(r) { + if baseReq.GenerateOnly { WriteGenerateStdTxResponse(w, txBldr, msgs) return } diff --git a/x/stake/client/rest/tx.go b/x/stake/client/rest/tx.go index 437d40e77..5deb5b53c 100644 --- a/x/stake/client/rest/tx.go +++ b/x/stake/client/rest/tx.go @@ -219,14 +219,14 @@ func delegationsRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx conte baseReq.Sequence++ - if utils.HasDryRunArg(r) || txBldr.SimulateGas { + if baseReq.Simulate || txBldr.SimulateGas { newBldr, err := utils.EnrichCtxWithGas(txBldr, cliCtx, baseReq.Name, []sdk.Msg{msg}) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - if utils.HasDryRunArg(r) { + if baseReq.Simulate { utils.WriteSimulationResponse(w, newBldr.Gas) return } @@ -234,7 +234,7 @@ func delegationsRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx conte txBldr = newBldr } - if utils.HasGenerateOnlyArg(r) { + if baseReq.GenerateOnly { utils.WriteGenerateStdTxResponse(w, txBldr, []sdk.Msg{msg}) return } From 24a1670cf04898d077c4f00d745ef6cc25d5f1d1 Mon Sep 17 00:00:00 2001 From: Alessio Treglia Date: Mon, 10 Dec 2018 14:27:25 +0000 Subject: [PATCH 08/21] Run make format --- baseapp/helpers.go | 3 ++- baseapp/options.go | 3 ++- baseapp/query_test.go | 3 ++- client/config.go | 3 ++- client/context/context.go | 7 ++++--- client/context/errors.go | 3 ++- client/context/query.go | 3 ++- client/keys.go | 3 ++- client/keys/delete.go | 3 ++- client/keys/mnemonic.go | 3 ++- client/keys/root.go | 3 ++- client/keys/show.go | 8 +++++--- client/keys/update.go | 8 +++++--- client/keys/utils.go | 9 +++++---- client/keys/utils_test.go | 6 ++++-- client/lcd/root.go | 13 +++++++------ client/lcd/test_helpers.go | 6 ++++-- client/rpc/block.go | 3 ++- client/rpc/root.go | 3 ++- client/rpc/status.go | 5 +++-- client/rpc/validators.go | 5 +++-- client/tx/broadcast.go | 3 ++- client/tx/query.go | 3 ++- client/utils/utils.go | 5 +++-- client/utils/utils_test.go | 5 +++-- cmd/cosmos-sdk-cli/cmd/init.go | 3 ++- cmd/gaia/app/app.go | 9 +++++---- cmd/gaia/app/app_test.go | 7 ++++--- cmd/gaia/app/benchmarks/txsize_test.go | 3 ++- cmd/gaia/app/export.go | 5 +++-- cmd/gaia/app/genesis.go | 3 ++- cmd/gaia/app/genesis_test.go | 7 ++++--- cmd/gaia/app/invariants.go | 3 ++- cmd/gaia/cmd/gaiadebug/main.go | 7 ++++--- cmd/gaia/init/collect.go | 11 ++++++----- cmd/gaia/init/genesis_accts.go | 9 +++++---- cmd/gaia/init/genesis_accts_test.go | 3 ++- cmd/gaia/init/gentx.go | 9 +++++---- cmd/gaia/init/init.go | 9 +++++---- cmd/gaia/init/init_test.go | 10 ++++++---- cmd/gaia/init/testnet.go | 3 ++- cmd/gaia/init/utils.go | 5 +++-- crypto/keys/codec.go | 3 ++- crypto/keys/keybase.go | 3 ++- crypto/keys/keybase_test.go | 3 ++- crypto/keys/mintkey/mintkey.go | 3 ++- crypto/keys/types.go | 3 ++- docs/_attic/sdk/core/examples/app2_test.go | 3 ++- docs/examples/basecoin/app/app.go | 11 ++++++----- docs/examples/basecoin/app/app_test.go | 9 +++++---- docs/examples/basecoin/cli_test/cli_test.go | 3 ++- docs/examples/basecoin/cmd/basecli/main.go | 5 +++-- docs/examples/basecoin/cmd/basecoind/main.go | 9 +++++---- docs/examples/democoin/app/app_test.go | 11 ++++++----- docs/examples/democoin/cli_test/cli_test.go | 3 ++- docs/examples/democoin/cmd/democoind/main.go | 3 ++- docs/examples/democoin/mock/validator.go | 3 ++- docs/examples/democoin/x/cool/app_test.go | 7 ++++--- docs/examples/democoin/x/pow/mine.go | 3 ++- server/config/config_test.go | 3 ++- server/export.go | 6 ++++-- server/init.go | 7 +++++-- server/mock/app.go | 3 ++- server/mock/app_test.go | 3 ++- server/test_helpers.go | 3 ++- server/tm_cmds.go | 8 +++++--- server/util.go | 9 +++++---- server/util_test.go | 3 ++- store/dbstoreadapter.go | 3 ++- store/list_test.go | 3 ++- store/multistoreproof_test.go | 3 ++- store/transientstore.go | 3 ++- types/context_test.go | 3 ++- types/decimal_test.go | 3 ++- types/errors.go | 3 ++- x/auth/account.go | 3 ++- x/auth/ante.go | 3 ++- x/auth/ante_test.go | 5 +++-- x/auth/client/cli/sign.go | 7 ++++--- x/auth/client/txbuilder/txbuilder_test.go | 3 ++- x/auth/keeper.go | 3 ++- x/auth/keeper_bench_test.go | 5 +++-- x/auth/keeper_test.go | 7 ++++--- x/auth/stdtx.go | 5 +++-- x/auth/stdtx_test.go | 3 ++- x/bank/client/cli/broadcast.go | 5 +++-- x/bank/client/cli/sendtx.go | 3 ++- x/bank/simulation/msgs.go | 3 ++- x/distribution/client/module_client.go | 5 +++-- x/distribution/keeper/allocation_test.go | 5 +++-- x/distribution/keeper/delegation_test.go | 3 ++- x/distribution/keeper/keeper_test.go | 3 ++- x/distribution/keeper/validator_test.go | 3 ++- x/distribution/types/dec_coin_test.go | 3 ++- x/distribution/types/delegator_info_test.go | 3 ++- x/distribution/types/fee_pool_test.go | 3 ++- x/distribution/types/test_common.go | 3 ++- x/distribution/types/total_accum_test.go | 3 ++- x/distribution/types/validator_info_test.go | 3 ++- x/gov/client/cli/query.go | 5 +++-- x/gov/client/cli/tx.go | 6 ++++-- x/gov/client/cli/tx_test.go | 5 +++-- x/gov/client/module_client.go | 5 +++-- x/gov/client/rest/rest.go | 3 ++- x/gov/depositsvotes.go | 3 ++- x/gov/endblocker_test.go | 3 ++- x/gov/querier.go | 3 ++- x/gov/querier_test.go | 5 +++-- x/gov/tally_test.go | 3 ++- x/mock/app.go | 9 +++++---- x/mock/app_test.go | 5 +++-- x/mock/simulation/invariants.go | 3 ++- x/mock/test_utils.go | 5 +++-- x/slashing/client/cli/tx.go | 3 ++- x/slashing/client/module_client.go | 5 +++-- x/slashing/client/rest/query.go | 3 ++- x/slashing/keeper.go | 3 ++- x/slashing/keeper_test.go | 5 +++-- x/slashing/tick.go | 3 ++- x/stake/client/cli/utils.go | 3 ++- x/stake/client/module_client.go | 5 +++-- x/stake/client/rest/query.go | 3 ++- x/stake/client/rest/utils.go | 3 ++- x/stake/genesis_test.go | 5 +++-- x/stake/keeper/key_test.go | 5 +++-- x/stake/keeper/slash_test.go | 3 ++- x/stake/keeper/validator_test.go | 3 ++- x/stake/querier/querier.go | 3 ++- x/stake/querier/querier_test.go | 5 +++-- x/stake/types/delegation_test.go | 3 ++- x/stake/types/msg.go | 3 ++- x/stake/types/msg_test.go | 3 ++- x/stake/types/pool_test.go | 3 ++- x/stake/types/test_utils.go | 3 ++- 134 files changed, 375 insertions(+), 231 deletions(-) diff --git a/baseapp/helpers.go b/baseapp/helpers.go index f3f1448bc..b6a0a3612 100644 --- a/baseapp/helpers.go +++ b/baseapp/helpers.go @@ -1,10 +1,11 @@ package baseapp import ( - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/abci/server" abci "github.com/tendermint/tendermint/abci/types" cmn "github.com/tendermint/tendermint/libs/common" + + sdk "github.com/cosmos/cosmos-sdk/types" ) // nolint - Mostly for testing diff --git a/baseapp/options.go b/baseapp/options.go index 8d86933a0..6e4104e50 100644 --- a/baseapp/options.go +++ b/baseapp/options.go @@ -4,9 +4,10 @@ package baseapp import ( "fmt" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" - dbm "github.com/tendermint/tendermint/libs/db" ) // File for storing in-package BaseApp optional functions, diff --git a/baseapp/query_test.go b/baseapp/query_test.go index d9d4001eb..fed7ae477 100644 --- a/baseapp/query_test.go +++ b/baseapp/query_test.go @@ -4,9 +4,10 @@ import ( "fmt" "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" + + sdk "github.com/cosmos/cosmos-sdk/types" ) // Test that we can only query from the latest committed state. diff --git a/client/config.go b/client/config.go index 51d6da700..ab72ee78d 100644 --- a/client/config.go +++ b/client/config.go @@ -7,9 +7,10 @@ import ( "path" "strconv" - "github.com/cosmos/cosmos-sdk/cmd/gaia/app" "github.com/tendermint/tendermint/libs/cli" + "github.com/cosmos/cosmos-sdk/cmd/gaia/app" + "github.com/pelletier/go-toml" "github.com/spf13/cobra" "github.com/spf13/viper" diff --git a/client/context/context.go b/client/context/context.go index 4b4407368..df30374de 100644 --- a/client/context/context.go +++ b/client/context/context.go @@ -13,14 +13,15 @@ import ( "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client/keys" - cskeys "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/libs/log" tmlite "github.com/tendermint/tendermint/lite" tmliteProxy "github.com/tendermint/tendermint/lite/proxy" rpcclient "github.com/tendermint/tendermint/rpc/client" + + "github.com/cosmos/cosmos-sdk/client/keys" + cskeys "github.com/cosmos/cosmos-sdk/crypto/keys" + "github.com/cosmos/cosmos-sdk/types" ) const ctxAccStoreName = "acc" diff --git a/client/context/errors.go b/client/context/errors.go index de96aaa18..f28454ca0 100644 --- a/client/context/errors.go +++ b/client/context/errors.go @@ -1,8 +1,9 @@ package context import ( - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/pkg/errors" + + sdk "github.com/cosmos/cosmos-sdk/types" ) // ErrInvalidAccount returns a standardized error reflecting that a given diff --git a/client/context/query.go b/client/context/query.go index 486bd5186..0eff95d30 100644 --- a/client/context/query.go +++ b/client/context/query.go @@ -10,7 +10,6 @@ import ( "strings" - "github.com/cosmos/cosmos-sdk/store" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto/merkle" cmn "github.com/tendermint/tendermint/libs/common" @@ -18,6 +17,8 @@ import ( tmliteProxy "github.com/tendermint/tendermint/lite/proxy" rpcclient "github.com/tendermint/tendermint/rpc/client" tmtypes "github.com/tendermint/tendermint/types" + + "github.com/cosmos/cosmos-sdk/store" ) // GetNode returns an RPC client. If the context's client is not defined, an diff --git a/client/keys.go b/client/keys.go index a39b074b9..1fc594a2a 100644 --- a/client/keys.go +++ b/client/keys.go @@ -1,8 +1,9 @@ package client import ( - "github.com/cosmos/cosmos-sdk/crypto/keys" dbm "github.com/tendermint/tendermint/libs/db" + + "github.com/cosmos/cosmos-sdk/crypto/keys" ) // GetKeyBase initializes a keybase based on the given db. diff --git a/client/keys/delete.go b/client/keys/delete.go index e3fac4b7f..5f3ff4f09 100644 --- a/client/keys/delete.go +++ b/client/keys/delete.go @@ -10,10 +10,11 @@ import ( "github.com/spf13/viper" + "github.com/gorilla/mux" + "github.com/cosmos/cosmos-sdk/client" keys "github.com/cosmos/cosmos-sdk/crypto/keys" keyerror "github.com/cosmos/cosmos-sdk/crypto/keys/keyerror" - "github.com/gorilla/mux" "github.com/spf13/cobra" ) diff --git a/client/keys/mnemonic.go b/client/keys/mnemonic.go index 33270a087..32a6856bb 100644 --- a/client/keys/mnemonic.go +++ b/client/keys/mnemonic.go @@ -4,9 +4,10 @@ import ( "crypto/sha256" "fmt" - "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" + bip39 "github.com/bartekn/go-bip39" ) diff --git a/client/keys/root.go b/client/keys/root.go index bca6f50e8..f747d84a0 100644 --- a/client/keys/root.go +++ b/client/keys/root.go @@ -1,9 +1,10 @@ package keys import ( - "github.com/cosmos/cosmos-sdk/client" "github.com/gorilla/mux" "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" ) // Commands registers a sub-tree of commands to interact with diff --git a/client/keys/show.go b/client/keys/show.go index d539eb3b7..9583dd07a 100644 --- a/client/keys/show.go +++ b/client/keys/show.go @@ -4,17 +4,19 @@ import ( "fmt" "net/http" - "github.com/cosmos/cosmos-sdk/crypto/keys" "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/crypto/keys/keyerror" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/crypto/keys" + "github.com/gorilla/mux" "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/tendermint/tendermint/crypto/multisig" "github.com/tendermint/tendermint/libs/cli" + + "github.com/cosmos/cosmos-sdk/crypto/keys/keyerror" + sdk "github.com/cosmos/cosmos-sdk/types" ) const ( diff --git a/client/keys/update.go b/client/keys/update.go index 2489bce12..e72da240c 100644 --- a/client/keys/update.go +++ b/client/keys/update.go @@ -5,12 +5,14 @@ import ( "fmt" "net/http" - "github.com/cosmos/cosmos-sdk/client" - keys "github.com/cosmos/cosmos-sdk/crypto/keys" "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/crypto/keys/keyerror" + "github.com/cosmos/cosmos-sdk/client" + keys "github.com/cosmos/cosmos-sdk/crypto/keys" + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/crypto/keys/keyerror" ) func updateKeyCommand() *cobra.Command { diff --git a/client/keys/utils.go b/client/keys/utils.go index 0ac4a9c90..78899f5f8 100644 --- a/client/keys/utils.go +++ b/client/keys/utils.go @@ -5,14 +5,15 @@ import ( "net/http" "path/filepath" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/spf13/viper" "github.com/syndtr/goleveldb/leveldb/opt" "github.com/tendermint/tendermint/libs/cli" dbm "github.com/tendermint/tendermint/libs/db" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys" + sdk "github.com/cosmos/cosmos-sdk/types" ) // KeyDBName is the directory under root where we store the keys diff --git a/client/keys/utils_test.go b/client/keys/utils_test.go index 6b65bb55a..5f3dd4560 100644 --- a/client/keys/utils_test.go +++ b/client/keys/utils_test.go @@ -1,11 +1,13 @@ package keys import ( - "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/stretchr/testify/require" "io/ioutil" "os" "testing" + + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/crypto/keys" ) func TestGetKeyBaseLocks(t *testing.T) { diff --git a/client/lcd/root.go b/client/lcd/root.go index 00dab053e..ad7ba2ff0 100644 --- a/client/lcd/root.go +++ b/client/lcd/root.go @@ -7,12 +7,6 @@ import ( "net/http" "os" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/codec" - keybase "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/cosmos/cosmos-sdk/server" "github.com/gorilla/mux" "github.com/rakyll/statik/fs" "github.com/spf13/cobra" @@ -20,6 +14,13 @@ import ( "github.com/tendermint/tendermint/libs/log" rpcserver "github.com/tendermint/tendermint/rpc/lib/server" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/codec" + keybase "github.com/cosmos/cosmos-sdk/crypto/keys" + "github.com/cosmos/cosmos-sdk/server" + // Import statik for light client stuff _ "github.com/cosmos/cosmos-sdk/client/lcd/statik" ) diff --git a/client/lcd/test_helpers.go b/client/lcd/test_helpers.go index 921dc96dd..87f57f385 100644 --- a/client/lcd/test_helpers.go +++ b/client/lcd/test_helpers.go @@ -14,9 +14,10 @@ import ( "strings" "testing" - stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" "github.com/tendermint/tendermint/crypto/secp256k1" + stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/rpc" @@ -33,7 +34,6 @@ import ( "github.com/spf13/viper" "github.com/stretchr/testify/require" - txbuilder "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" abci "github.com/tendermint/tendermint/abci/types" tmcfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto" @@ -48,6 +48,8 @@ import ( tmrpc "github.com/tendermint/tendermint/rpc/lib/server" tmtypes "github.com/tendermint/tendermint/types" + txbuilder "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + authRest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" bankRest "github.com/cosmos/cosmos-sdk/x/bank/client/rest" govRest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" diff --git a/client/rpc/block.go b/client/rpc/block.go index b2db545db..ee77fb5c1 100644 --- a/client/rpc/block.go +++ b/client/rpc/block.go @@ -8,11 +8,12 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/client/utils" "github.com/gorilla/mux" "github.com/spf13/cobra" "github.com/spf13/viper" tmliteProxy "github.com/tendermint/tendermint/lite/proxy" + + "github.com/cosmos/cosmos-sdk/client/utils" ) //BlockCommand returns the verified block data for a given heights diff --git a/client/rpc/root.go b/client/rpc/root.go index 7bdcd8cd8..c8a98bc44 100644 --- a/client/rpc/root.go +++ b/client/rpc/root.go @@ -5,9 +5,10 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" - "github.com/spf13/viper" ) const ( diff --git a/client/rpc/status.go b/client/rpc/status.go index 0f81fc9c6..86bb1ef31 100644 --- a/client/rpc/status.go +++ b/client/rpc/status.go @@ -7,11 +7,12 @@ import ( "github.com/spf13/cobra" + "github.com/spf13/viper" + ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" - "github.com/spf13/viper" - ctypes "github.com/tendermint/tendermint/rpc/core/types" ) // StatusCommand returns the status of the network diff --git a/client/rpc/validators.go b/client/rpc/validators.go index 6ec7ba615..9d401f69c 100644 --- a/client/rpc/validators.go +++ b/client/rpc/validators.go @@ -9,12 +9,13 @@ import ( "github.com/gorilla/mux" "github.com/spf13/cobra" + "github.com/spf13/viper" + tmtypes "github.com/tendermint/tendermint/types" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/spf13/viper" - tmtypes "github.com/tendermint/tendermint/types" ) // TODO these next two functions feel kinda hacky based on their placement diff --git a/client/tx/broadcast.go b/client/tx/broadcast.go index 8346e1538..4080b68ec 100644 --- a/client/tx/broadcast.go +++ b/client/tx/broadcast.go @@ -3,10 +3,11 @@ package tx import ( "net/http" + "io/ioutil" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" - "io/ioutil" ) const ( diff --git a/client/tx/query.go b/client/tx/query.go index 3bbbf9a13..945701224 100644 --- a/client/tx/query.go +++ b/client/tx/query.go @@ -12,13 +12,14 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/spf13/viper" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "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/auth" - "github.com/spf13/viper" ) // QueryTxCmd implements the default command for a tx query. diff --git a/client/utils/utils.go b/client/utils/utils.go index 2d506e462..08a538eec 100644 --- a/client/utils/utils.go +++ b/client/utils/utils.go @@ -6,13 +6,14 @@ import ( "io" "os" + "github.com/tendermint/go-amino" + "github.com/tendermint/tendermint/libs/common" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/keys" 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/tendermint/go-amino" - "github.com/tendermint/tendermint/libs/common" ) // CompleteAndBroadcastTxCli implements a utility function that facilitates diff --git a/client/utils/utils_test.go b/client/utils/utils_test.go index b22a50806..23c665239 100644 --- a/client/utils/utils_test.go +++ b/client/utils/utils_test.go @@ -4,10 +4,11 @@ import ( "errors" "testing" - "github.com/cosmos/cosmos-sdk/cmd/gaia/app" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/cmd/gaia/app" + sdk "github.com/cosmos/cosmos-sdk/types" ) func TestParseQueryResponse(t *testing.T) { diff --git a/cmd/cosmos-sdk-cli/cmd/init.go b/cmd/cosmos-sdk-cli/cmd/init.go index fcf30b972..f8cf88b88 100644 --- a/cmd/cosmos-sdk-cli/cmd/init.go +++ b/cmd/cosmos-sdk-cli/cmd/init.go @@ -9,9 +9,10 @@ import ( "path/filepath" - "github.com/cosmos/cosmos-sdk/version" "github.com/spf13/cobra" tmversion "github.com/tendermint/tendermint/version" + + "github.com/cosmos/cosmos-sdk/version" ) var remoteBasecoinPath = "github.com/cosmos/cosmos-sdk/docs/examples/basecoin" diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 270fe52ec..d97d25f0a 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -6,6 +6,11 @@ import ( "os" "sort" + abci "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" + bam "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -17,10 +22,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/stake" - abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" ) const ( diff --git a/cmd/gaia/app/app_test.go b/cmd/gaia/app/app_test.go index e356d6d6d..238f22966 100644 --- a/cmd/gaia/app/app_test.go +++ b/cmd/gaia/app/app_test.go @@ -4,6 +4,10 @@ import ( "os" "testing" + "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/auth" distr "github.com/cosmos/cosmos-sdk/x/distribution" @@ -11,9 +15,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" abci "github.com/tendermint/tendermint/abci/types" ) diff --git a/cmd/gaia/app/benchmarks/txsize_test.go b/cmd/gaia/app/benchmarks/txsize_test.go index a401c16ca..d9862f22c 100644 --- a/cmd/gaia/app/benchmarks/txsize_test.go +++ b/cmd/gaia/app/benchmarks/txsize_test.go @@ -3,11 +3,12 @@ package app import ( "fmt" + "github.com/tendermint/tendermint/crypto/secp256k1" + "github.com/cosmos/cosmos-sdk/cmd/gaia/app" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/tendermint/tendermint/crypto/secp256k1" ) // This will fail half the time with the second output being 173 diff --git a/cmd/gaia/app/export.go b/cmd/gaia/app/export.go index a2aa42087..2b51c444b 100644 --- a/cmd/gaia/app/export.go +++ b/cmd/gaia/app/export.go @@ -4,6 +4,9 @@ import ( "encoding/json" "fmt" + abci "github.com/tendermint/tendermint/abci/types" + tmtypes "github.com/tendermint/tendermint/types" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" @@ -12,8 +15,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/slashing" stake "github.com/cosmos/cosmos-sdk/x/stake" - abci "github.com/tendermint/tendermint/abci/types" - tmtypes "github.com/tendermint/tendermint/types" ) // export the state of gaia for a genesis file diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index ee3ecfcd6..9c92f60ba 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -10,6 +10,8 @@ import ( "sort" "strings" + tmtypes "github.com/tendermint/tendermint/types" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" @@ -19,7 +21,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/stake" stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" - tmtypes "github.com/tendermint/tendermint/types" ) var ( diff --git a/cmd/gaia/app/genesis_test.go b/cmd/gaia/app/genesis_test.go index 1b1c19646..425962fa3 100644 --- a/cmd/gaia/app/genesis_test.go +++ b/cmd/gaia/app/genesis_test.go @@ -7,13 +7,14 @@ import ( "github.com/tendermint/tendermint/crypto/secp256k1" tmtypes "github.com/tendermint/tendermint/types" + "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/crypto/ed25519" + 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/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/ed25519" ) var ( diff --git a/cmd/gaia/app/invariants.go b/cmd/gaia/app/invariants.go index 4a60a41ae..4582457fc 100644 --- a/cmd/gaia/app/invariants.go +++ b/cmd/gaia/app/invariants.go @@ -4,12 +4,13 @@ import ( "fmt" "time" + abci "github.com/tendermint/tendermint/abci/types" + sdk "github.com/cosmos/cosmos-sdk/types" 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" - abci "github.com/tendermint/tendermint/abci/types" ) func (app *GaiaApp) runtimeInvariants() []simulation.Invariant { diff --git a/cmd/gaia/cmd/gaiadebug/main.go b/cmd/gaia/cmd/gaiadebug/main.go index 5117d0aa1..59e324966 100644 --- a/cmd/gaia/cmd/gaiadebug/main.go +++ b/cmd/gaia/cmd/gaiadebug/main.go @@ -10,12 +10,13 @@ import ( "strconv" "strings" - gaia "github.com/cosmos/cosmos-sdk/cmd/gaia/app" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" "github.com/spf13/cobra" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" + + gaia "github.com/cosmos/cosmos-sdk/cmd/gaia/app" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" ) func init() { diff --git a/cmd/gaia/init/collect.go b/cmd/gaia/init/collect.go index cdfc1688c..da97e4626 100644 --- a/cmd/gaia/init/collect.go +++ b/cmd/gaia/init/collect.go @@ -4,17 +4,18 @@ import ( "encoding/json" "path/filepath" - "github.com/cosmos/cosmos-sdk/client" - "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/x/auth" "github.com/spf13/cobra" "github.com/spf13/viper" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/types" + + "github.com/cosmos/cosmos-sdk/client" + "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/x/auth" ) type initConfig struct { diff --git a/cmd/gaia/init/genesis_accts.go b/cmd/gaia/init/genesis_accts.go index 04c1f6283..4f5043877 100644 --- a/cmd/gaia/init/genesis_accts.go +++ b/cmd/gaia/init/genesis_accts.go @@ -4,15 +4,16 @@ import ( "encoding/json" "fmt" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/tendermint/tendermint/libs/cli" + "github.com/tendermint/tendermint/libs/common" + "github.com/cosmos/cosmos-sdk/cmd/gaia/app" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/spf13/cobra" - "github.com/spf13/viper" - "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/libs/common" ) // AddGenesisAccountCmd returns add-genesis-account cobra Command diff --git a/cmd/gaia/init/genesis_accts_test.go b/cmd/gaia/init/genesis_accts_test.go index 49634a90c..42a36b263 100644 --- a/cmd/gaia/init/genesis_accts_test.go +++ b/cmd/gaia/init/genesis_accts_test.go @@ -1,9 +1,10 @@ package init import ( + "testing" + "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto/secp256k1" - "testing" "github.com/cosmos/cosmos-sdk/cmd/gaia/app" "github.com/cosmos/cosmos-sdk/codec" diff --git a/cmd/gaia/init/gentx.go b/cmd/gaia/init/gentx.go index 0a4eb8034..c8a7c05d2 100644 --- a/cmd/gaia/init/gentx.go +++ b/cmd/gaia/init/gentx.go @@ -11,6 +11,11 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" + cfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tendermint/crypto" + tmcli "github.com/tendermint/tendermint/libs/cli" + "github.com/tendermint/tendermint/libs/common" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/keys" @@ -23,10 +28,6 @@ import ( 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" - cfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/crypto" - tmcli "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/libs/common" ) const ( diff --git a/cmd/gaia/init/init.go b/cmd/gaia/init/init.go index 19179233a..7690d5336 100644 --- a/cmd/gaia/init/init.go +++ b/cmd/gaia/init/init.go @@ -6,15 +6,16 @@ import ( "os" "path/filepath" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/cmd/gaia/app" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/server" "github.com/spf13/cobra" "github.com/spf13/viper" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/cmd/gaia/app" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/server" ) const ( diff --git a/cmd/gaia/init/init_test.go b/cmd/gaia/init/init_test.go index 1eeba66ae..faf324e6c 100644 --- a/cmd/gaia/init/init_test.go +++ b/cmd/gaia/init/init_test.go @@ -8,17 +8,19 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/cmd/gaia/app" "github.com/tendermint/tendermint/libs/cli" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/server/mock" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/cmd/gaia/app" + "github.com/stretchr/testify/require" abciServer "github.com/tendermint/tendermint/abci/server" tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" "github.com/tendermint/tendermint/libs/log" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/server/mock" + "github.com/spf13/viper" ) diff --git a/cmd/gaia/init/testnet.go b/cmd/gaia/init/testnet.go index 73a7cea14..cfa3e6396 100644 --- a/cmd/gaia/init/testnet.go +++ b/cmd/gaia/init/testnet.go @@ -16,7 +16,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/stake" stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" - "github.com/cosmos/cosmos-sdk/server" "github.com/spf13/cobra" "github.com/spf13/viper" cfg "github.com/tendermint/tendermint/config" @@ -24,6 +23,8 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/types" tmtime "github.com/tendermint/tendermint/types/time" + + "github.com/cosmos/cosmos-sdk/server" ) var ( diff --git a/cmd/gaia/init/utils.go b/cmd/gaia/init/utils.go index 58edc9b2a..14c625d7f 100644 --- a/cmd/gaia/init/utils.go +++ b/cmd/gaia/init/utils.go @@ -6,8 +6,6 @@ import ( "io/ioutil" "time" - "github.com/cosmos/cosmos-sdk/cmd/gaia/app" - "github.com/cosmos/cosmos-sdk/codec" amino "github.com/tendermint/go-amino" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto" @@ -15,6 +13,9 @@ import ( "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/privval" "github.com/tendermint/tendermint/types" + + "github.com/cosmos/cosmos-sdk/cmd/gaia/app" + "github.com/cosmos/cosmos-sdk/codec" ) // ExportGenesisFile creates and writes the genesis configuration to disk. An diff --git a/crypto/keys/codec.go b/crypto/keys/codec.go index 80a13539a..f6c1a013d 100644 --- a/crypto/keys/codec.go +++ b/crypto/keys/codec.go @@ -1,9 +1,10 @@ package keys import ( - ccrypto "github.com/cosmos/cosmos-sdk/crypto" amino "github.com/tendermint/go-amino" "github.com/tendermint/tendermint/crypto/encoding/amino" + + ccrypto "github.com/cosmos/cosmos-sdk/crypto" ) var cdc = amino.NewCodec() diff --git a/crypto/keys/keybase.go b/crypto/keys/keybase.go index 982a4e726..e202cd6d8 100644 --- a/crypto/keys/keybase.go +++ b/crypto/keys/keybase.go @@ -15,11 +15,12 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys/mintkey" "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/keyerror" tmcrypto "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/encoding/amino" "github.com/tendermint/tendermint/crypto/secp256k1" dbm "github.com/tendermint/tendermint/libs/db" + + "github.com/cosmos/cosmos-sdk/crypto/keys/keyerror" ) var _ Keybase = dbKeybase{} diff --git a/crypto/keys/keybase_test.go b/crypto/keys/keybase_test.go index 3c7f98060..bc7783b67 100644 --- a/crypto/keys/keybase_test.go +++ b/crypto/keys/keybase_test.go @@ -13,8 +13,9 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/cosmos/cosmos-sdk/types" dbm "github.com/tendermint/tendermint/libs/db" + + "github.com/cosmos/cosmos-sdk/types" ) func init() { diff --git a/crypto/keys/mintkey/mintkey.go b/crypto/keys/mintkey/mintkey.go index 35cb9ccab..3b06415e2 100644 --- a/crypto/keys/mintkey/mintkey.go +++ b/crypto/keys/mintkey/mintkey.go @@ -11,8 +11,9 @@ import ( "github.com/tendermint/tendermint/crypto/encoding/amino" "github.com/tendermint/tendermint/crypto/xsalsa20symmetric" - "github.com/cosmos/cosmos-sdk/crypto/keys/keyerror" cmn "github.com/tendermint/tendermint/libs/common" + + "github.com/cosmos/cosmos-sdk/crypto/keys/keyerror" ) const ( diff --git a/crypto/keys/types.go b/crypto/keys/types.go index b4b328516..14d050961 100644 --- a/crypto/keys/types.go +++ b/crypto/keys/types.go @@ -1,9 +1,10 @@ package keys import ( - ccrypto "github.com/cosmos/cosmos-sdk/crypto" "github.com/tendermint/tendermint/crypto" + ccrypto "github.com/cosmos/cosmos-sdk/crypto" + "github.com/cosmos/cosmos-sdk/crypto/keys/hd" "github.com/cosmos/cosmos-sdk/types" ) diff --git a/docs/_attic/sdk/core/examples/app2_test.go b/docs/_attic/sdk/core/examples/app2_test.go index b7c94bbcf..0712e7add 100644 --- a/docs/_attic/sdk/core/examples/app2_test.go +++ b/docs/_attic/sdk/core/examples/app2_test.go @@ -3,9 +3,10 @@ package app import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/crypto/ed25519" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" ) diff --git a/docs/examples/basecoin/app/app.go b/docs/examples/basecoin/app/app.go index f534c9128..a469e0b2a 100644 --- a/docs/examples/basecoin/app/app.go +++ b/docs/examples/basecoin/app/app.go @@ -4,6 +4,12 @@ import ( "encoding/json" "os" + abci "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" + tmtypes "github.com/tendermint/tendermint/types" + bam "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/docs/examples/basecoin/types" @@ -11,11 +17,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/ibc" - abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" ) const ( diff --git a/docs/examples/basecoin/app/app_test.go b/docs/examples/basecoin/app/app_test.go index 64bc6a86e..4dae71194 100644 --- a/docs/examples/basecoin/app/app_test.go +++ b/docs/examples/basecoin/app/app_test.go @@ -4,15 +4,16 @@ import ( "os" "testing" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/docs/examples/basecoin/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto/ed25519" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/docs/examples/basecoin/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" ) func setGenesis(baseApp *BasecoinApp, accounts ...*types.AppAccount) (types.GenesisState, error) { diff --git a/docs/examples/basecoin/cli_test/cli_test.go b/docs/examples/basecoin/cli_test/cli_test.go index 635b54c3c..7e6a648df 100644 --- a/docs/examples/basecoin/cli_test/cli_test.go +++ b/docs/examples/basecoin/cli_test/cli_test.go @@ -6,10 +6,11 @@ import ( "os" "testing" + "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/cmd/gaia/app" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/tests" - "github.com/stretchr/testify/require" ) var ( diff --git a/docs/examples/basecoin/cmd/basecli/main.go b/docs/examples/basecoin/cmd/basecli/main.go index 6e274123e..fe681a3ad 100644 --- a/docs/examples/basecoin/cmd/basecli/main.go +++ b/docs/examples/basecoin/cmd/basecli/main.go @@ -9,6 +9,9 @@ import ( "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/docs/examples/basecoin/app" + "github.com/spf13/cobra" + "github.com/tendermint/tendermint/libs/cli" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" @@ -20,8 +23,6 @@ import ( slashing "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" stake "github.com/cosmos/cosmos-sdk/x/stake/client/rest" - "github.com/spf13/cobra" - "github.com/tendermint/tendermint/libs/cli" ) const ( diff --git a/docs/examples/basecoin/cmd/basecoind/main.go b/docs/examples/basecoin/cmd/basecoind/main.go index 383a843b2..9cb246671 100644 --- a/docs/examples/basecoin/cmd/basecoind/main.go +++ b/docs/examples/basecoin/cmd/basecoind/main.go @@ -11,10 +11,6 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" gaiaInit "github.com/cosmos/cosmos-sdk/cmd/gaia/init" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/docs/examples/basecoin/app" - "github.com/cosmos/cosmos-sdk/server" "github.com/spf13/cobra" "github.com/spf13/viper" abci "github.com/tendermint/tendermint/abci/types" @@ -23,6 +19,11 @@ import ( dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" tmtypes "github.com/tendermint/tendermint/types" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/docs/examples/basecoin/app" + "github.com/cosmos/cosmos-sdk/server" ) const ( diff --git a/docs/examples/democoin/app/app_test.go b/docs/examples/democoin/app/app_test.go index 93cef936c..200103466 100644 --- a/docs/examples/democoin/app/app_test.go +++ b/docs/examples/democoin/app/app_test.go @@ -4,16 +4,17 @@ import ( "os" "testing" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/docs/examples/democoin/types" - "github.com/cosmos/cosmos-sdk/docs/examples/democoin/x/cool" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto/ed25519" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/docs/examples/democoin/types" + "github.com/cosmos/cosmos-sdk/docs/examples/democoin/x/cool" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" ) func setGenesis(bapp *DemocoinApp, trend string, accs ...auth.BaseAccount) error { diff --git a/docs/examples/democoin/cli_test/cli_test.go b/docs/examples/democoin/cli_test/cli_test.go index 9a3cba0df..1aa9d94ac 100644 --- a/docs/examples/democoin/cli_test/cli_test.go +++ b/docs/examples/democoin/cli_test/cli_test.go @@ -8,9 +8,10 @@ import ( "github.com/cosmos/cosmos-sdk/cmd/gaia/app" + "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/tests" - "github.com/stretchr/testify/require" ) var ( diff --git a/docs/examples/democoin/cmd/democoind/main.go b/docs/examples/democoin/cmd/democoind/main.go index 8f52340f4..f0553ee5d 100644 --- a/docs/examples/democoin/cmd/democoind/main.go +++ b/docs/examples/democoin/cmd/democoind/main.go @@ -6,11 +6,12 @@ import ( "io" "os" - "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/viper" "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/p2p" + "github.com/cosmos/cosmos-sdk/client" + "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" diff --git a/docs/examples/democoin/mock/validator.go b/docs/examples/democoin/mock/validator.go index 1d10c48b2..ee8e497cb 100644 --- a/docs/examples/democoin/mock/validator.go +++ b/docs/examples/democoin/mock/validator.go @@ -3,8 +3,9 @@ package mock import ( "bytes" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/crypto" + + sdk "github.com/cosmos/cosmos-sdk/types" ) // Validator implements sdk.Validator diff --git a/docs/examples/democoin/x/cool/app_test.go b/docs/examples/democoin/x/cool/app_test.go index 3725f7b9b..7e9e29f24 100644 --- a/docs/examples/democoin/x/cool/app_test.go +++ b/docs/examples/democoin/x/cool/app_test.go @@ -3,13 +3,14 @@ package cool import ( "testing" + "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/crypto/ed25519" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" bank "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/mock" - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto/ed25519" ) var ( diff --git a/docs/examples/democoin/x/pow/mine.go b/docs/examples/democoin/x/pow/mine.go index bf1c64cd4..3c24c1264 100644 --- a/docs/examples/democoin/x/pow/mine.go +++ b/docs/examples/democoin/x/pow/mine.go @@ -5,8 +5,9 @@ import ( "math" "strconv" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/crypto" + + sdk "github.com/cosmos/cosmos-sdk/types" ) // generate the mine message diff --git a/server/config/config_test.go b/server/config/config_test.go index e4d552ad2..d68d84415 100644 --- a/server/config/config_test.go +++ b/server/config/config_test.go @@ -3,8 +3,9 @@ package config import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" ) func TestDefaultConfig(t *testing.T) { diff --git a/server/export.go b/server/export.go index 7b5ba4a69..aa30597da 100644 --- a/server/export.go +++ b/server/export.go @@ -7,10 +7,12 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/codec" - tmtypes "github.com/tendermint/tendermint/types" "io/ioutil" "path" + + tmtypes "github.com/tendermint/tendermint/types" + + "github.com/cosmos/cosmos-sdk/codec" ) const ( diff --git a/server/init.go b/server/init.go index e1655c27e..dd9e7b890 100644 --- a/server/init.go +++ b/server/init.go @@ -4,15 +4,18 @@ import ( "encoding/json" "errors" "fmt" - "github.com/cosmos/cosmos-sdk/crypto/keys" + "github.com/tendermint/tendermint/crypto" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/types" + "github.com/cosmos/cosmos-sdk/crypto/keys" + + tmtypes "github.com/tendermint/tendermint/types" + clkeys "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - tmtypes "github.com/tendermint/tendermint/types" ) // SimpleGenTx is a simple genesis tx diff --git a/server/mock/app.go b/server/mock/app.go index 9e5af4498..2b0b8ed5e 100644 --- a/server/mock/app.go +++ b/server/mock/app.go @@ -3,9 +3,10 @@ package mock import ( "encoding/json" "fmt" - "github.com/tendermint/tendermint/types" "path/filepath" + "github.com/tendermint/tendermint/types" + abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" diff --git a/server/mock/app_test.go b/server/mock/app_test.go index a5f2a078b..707c22c85 100644 --- a/server/mock/app_test.go +++ b/server/mock/app_test.go @@ -1,9 +1,10 @@ package mock import ( - "github.com/tendermint/tendermint/types" "testing" + "github.com/tendermint/tendermint/types" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" diff --git a/server/test_helpers.go b/server/test_helpers.go index 4347bad6c..148f63a48 100644 --- a/server/test_helpers.go +++ b/server/test_helpers.go @@ -2,12 +2,13 @@ package server import ( "fmt" - "github.com/cosmos/cosmos-sdk/client" "io/ioutil" "net" "os" "testing" + "github.com/cosmos/cosmos-sdk/client" + "github.com/spf13/viper" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/libs/cli" diff --git a/server/tm_cmds.go b/server/tm_cmds.go index 5aeacf92f..33994b0cb 100644 --- a/server/tm_cmds.go +++ b/server/tm_cmds.go @@ -3,15 +3,17 @@ package server import ( "fmt" - "github.com/cosmos/cosmos-sdk/codec" "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/codec" + tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" "github.com/tendermint/tendermint/p2p" pvm "github.com/tendermint/tendermint/privval" + + "github.com/cosmos/cosmos-sdk/client" + sdk "github.com/cosmos/cosmos-sdk/types" ) // ShowNodeIDCmd - ported from Tendermint, dump node ID to stdout diff --git a/server/util.go b/server/util.go index 3d4a9d0b6..5c07d1b46 100644 --- a/server/util.go +++ b/server/util.go @@ -13,15 +13,16 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/server/config" - "github.com/cosmos/cosmos-sdk/version" tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/libs/cli" tmflags "github.com/tendermint/tendermint/libs/cli/flags" "github.com/tendermint/tendermint/libs/log" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/server/config" + "github.com/cosmos/cosmos-sdk/version" ) // server context diff --git a/server/util_test.go b/server/util_test.go index 2c16759c9..fb4e73259 100644 --- a/server/util_test.go +++ b/server/util_test.go @@ -4,8 +4,9 @@ import ( "encoding/json" "testing" - "github.com/cosmos/cosmos-sdk/codec" "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/codec" ) func TestInsertKeyJSON(t *testing.T) { diff --git a/store/dbstoreadapter.go b/store/dbstoreadapter.go index 8f4a1583c..76e673de5 100644 --- a/store/dbstoreadapter.go +++ b/store/dbstoreadapter.go @@ -3,8 +3,9 @@ package store import ( "io" - sdk "github.com/cosmos/cosmos-sdk/types" dbm "github.com/tendermint/tendermint/libs/db" + + sdk "github.com/cosmos/cosmos-sdk/types" ) // Wrapper type for dbm.Db with implementation of KVStore diff --git a/store/list_test.go b/store/list_test.go index 396e2d1a1..6767457cd 100644 --- a/store/list_test.go +++ b/store/list_test.go @@ -4,8 +4,9 @@ import ( "math/rand" "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" ) func TestList(t *testing.T) { diff --git a/store/multistoreproof_test.go b/store/multistoreproof_test.go index db3b65cad..0f80657b8 100644 --- a/store/multistoreproof_test.go +++ b/store/multistoreproof_test.go @@ -3,10 +3,11 @@ package store import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tendermint/libs/db" + + sdk "github.com/cosmos/cosmos-sdk/types" ) func TestVerifyIAVLStoreQueryProof(t *testing.T) { diff --git a/store/transientstore.go b/store/transientstore.go index a3ce89631..63b154c01 100644 --- a/store/transientstore.go +++ b/store/transientstore.go @@ -1,8 +1,9 @@ package store import ( - sdk "github.com/cosmos/cosmos-sdk/types" dbm "github.com/tendermint/tendermint/libs/db" + + sdk "github.com/cosmos/cosmos-sdk/types" ) var _ KVStore = (*transientStore)(nil) diff --git a/types/context_test.go b/types/context_test.go index 0ab6c8dfc..3ccea2a8a 100644 --- a/types/context_test.go +++ b/types/context_test.go @@ -8,9 +8,10 @@ import ( dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/store" "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" ) type MockLogger struct { diff --git a/types/decimal_test.go b/types/decimal_test.go index b35894771..fa6442f3a 100644 --- a/types/decimal_test.go +++ b/types/decimal_test.go @@ -6,8 +6,9 @@ import ( "github.com/stretchr/testify/assert" - "github.com/cosmos/cosmos-sdk/codec" "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/codec" ) // create a decimal from a decimal string (ex. "1234.5678") diff --git a/types/errors.go b/types/errors.go index 46436531e..f659f2954 100644 --- a/types/errors.go +++ b/types/errors.go @@ -4,9 +4,10 @@ import ( "fmt" "strings" - "github.com/cosmos/cosmos-sdk/codec" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/cosmos/cosmos-sdk/codec" + abci "github.com/tendermint/tendermint/abci/types" ) diff --git a/x/auth/account.go b/x/auth/account.go index 0fa601acc..f647601ca 100644 --- a/x/auth/account.go +++ b/x/auth/account.go @@ -3,9 +3,10 @@ package auth import ( "errors" + "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/tendermint/tendermint/crypto" ) // Account is an interface used to store coins at a given address within state. diff --git a/x/auth/ante.go b/x/auth/ante.go index 3c8a0f9aa..91789dd22 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -5,10 +5,11 @@ import ( "encoding/hex" "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/crypto/secp256k1" + + sdk "github.com/cosmos/cosmos-sdk/types" ) const ( diff --git a/x/auth/ante_test.go b/x/auth/ante_test.go index 20fec8896..9d76107fe 100644 --- a/x/auth/ante_test.go +++ b/x/auth/ante_test.go @@ -5,8 +5,6 @@ import ( "strings" "testing" - codec "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" @@ -14,6 +12,9 @@ import ( "github.com/tendermint/tendermint/crypto/multisig" "github.com/tendermint/tendermint/crypto/secp256k1" "github.com/tendermint/tendermint/libs/log" + + codec "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" ) func newTestMsg(addrs ...sdk.AccAddress) *sdk.TestMsg { diff --git a/x/auth/client/cli/sign.go b/x/auth/client/cli/sign.go index 39d9b6694..842299df8 100644 --- a/x/auth/client/cli/sign.go +++ b/x/auth/client/cli/sign.go @@ -6,15 +6,16 @@ import ( "io/ioutil" "os" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/tendermint/go-amino" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" 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/spf13/cobra" - "github.com/spf13/viper" - "github.com/tendermint/go-amino" ) const ( diff --git a/x/auth/client/txbuilder/txbuilder_test.go b/x/auth/client/txbuilder/txbuilder_test.go index 4ff472fef..7b0a281d6 100644 --- a/x/auth/client/txbuilder/txbuilder_test.go +++ b/x/auth/client/txbuilder/txbuilder_test.go @@ -6,11 +6,12 @@ import ( "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/crypto/ed25519" + "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" - "github.com/tendermint/tendermint/crypto/ed25519" ) var ( diff --git a/x/auth/keeper.go b/x/auth/keeper.go index 18e82c206..bf8b92da6 100644 --- a/x/auth/keeper.go +++ b/x/auth/keeper.go @@ -1,9 +1,10 @@ package auth import ( + "github.com/tendermint/tendermint/crypto" + codec "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/tendermint/tendermint/crypto" ) var ( diff --git a/x/auth/keeper_bench_test.go b/x/auth/keeper_bench_test.go index 5ca414048..413cd6afd 100644 --- a/x/auth/keeper_bench_test.go +++ b/x/auth/keeper_bench_test.go @@ -3,10 +3,11 @@ package auth import ( "testing" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" ) func BenchmarkAccountMapperGetAccountFound(b *testing.B) { diff --git a/x/auth/keeper_test.go b/x/auth/keeper_test.go index b0ba2e74b..ad05c0f8e 100644 --- a/x/auth/keeper_test.go +++ b/x/auth/keeper_test.go @@ -3,13 +3,14 @@ package auth import ( "testing" - codec "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" + + codec "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdk "github.com/cosmos/cosmos-sdk/types" ) func setupMultiStore() (sdk.MultiStore, *sdk.KVStoreKey, *sdk.KVStoreKey) { diff --git a/x/auth/stdtx.go b/x/auth/stdtx.go index 59edf7c13..053b405c9 100644 --- a/x/auth/stdtx.go +++ b/x/auth/stdtx.go @@ -4,10 +4,11 @@ import ( "encoding/json" "fmt" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/multisig" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" ) var _ sdk.Tx = (*StdTx)(nil) diff --git a/x/auth/stdtx_test.go b/x/auth/stdtx_test.go index 1f2fefaca..da1fac179 100644 --- a/x/auth/stdtx_test.go +++ b/x/auth/stdtx_test.go @@ -5,12 +5,13 @@ import ( "strings" "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/libs/log" + + sdk "github.com/cosmos/cosmos-sdk/types" ) var ( diff --git a/x/bank/client/cli/broadcast.go b/x/bank/client/cli/broadcast.go index 126668364..1bcd811cd 100644 --- a/x/bank/client/cli/broadcast.go +++ b/x/bank/client/cli/broadcast.go @@ -4,11 +4,12 @@ import ( "io/ioutil" "os" + "github.com/spf13/cobra" + amino "github.com/tendermint/go-amino" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" ) // GetSignCommand returns the sign command diff --git a/x/bank/client/cli/sendtx.go b/x/bank/client/cli/sendtx.go index 1a7c444af..e61d6eb56 100644 --- a/x/bank/client/cli/sendtx.go +++ b/x/bank/client/cli/sendtx.go @@ -1,6 +1,8 @@ package cli import ( + "os" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" @@ -8,7 +10,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" bankClient "github.com/cosmos/cosmos-sdk/x/bank/client" - "os" "github.com/pkg/errors" "github.com/spf13/cobra" diff --git a/x/bank/simulation/msgs.go b/x/bank/simulation/msgs.go index 78b1f1945..96df52f56 100644 --- a/x/bank/simulation/msgs.go +++ b/x/bank/simulation/msgs.go @@ -6,13 +6,14 @@ import ( "math/big" "math/rand" + "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/baseapp" 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/mock/simulation" - "github.com/tendermint/tendermint/crypto" ) // SingleInputSendTx tests and runs a single msg send w/ auth, with one input and one output, where both diff --git a/x/distribution/client/module_client.go b/x/distribution/client/module_client.go index ba725e1f8..69734b08d 100644 --- a/x/distribution/client/module_client.go +++ b/x/distribution/client/module_client.go @@ -1,10 +1,11 @@ package client import ( - "github.com/cosmos/cosmos-sdk/client" - distCmds "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" "github.com/spf13/cobra" amino "github.com/tendermint/go-amino" + + "github.com/cosmos/cosmos-sdk/client" + distCmds "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" ) // ModuleClient exports all client functionality from this module diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index 7d05e82b1..35ad25e66 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -3,10 +3,11 @@ package keeper import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/stake" ) func TestAllocateTokensBasic(t *testing.T) { diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index 455ad14e8..67606cc84 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -3,9 +3,10 @@ package keeper import ( "testing" + "github.com/stretchr/testify/require" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/stretchr/testify/require" ) func TestWithdrawDelegationRewardBasic(t *testing.T) { diff --git a/x/distribution/keeper/keeper_test.go b/x/distribution/keeper/keeper_test.go index f8eb0925d..a8c378424 100644 --- a/x/distribution/keeper/keeper_test.go +++ b/x/distribution/keeper/keeper_test.go @@ -3,9 +3,10 @@ package keeper import ( "testing" + "github.com/stretchr/testify/require" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/stretchr/testify/require" ) func TestSetGetPreviousProposerConsAddr(t *testing.T) { diff --git a/x/distribution/keeper/validator_test.go b/x/distribution/keeper/validator_test.go index fc9331959..58079241c 100644 --- a/x/distribution/keeper/validator_test.go +++ b/x/distribution/keeper/validator_test.go @@ -3,9 +3,10 @@ package keeper import ( "testing" + "github.com/stretchr/testify/require" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/stretchr/testify/require" ) func TestWithdrawValidatorRewardsAllNoDelegator(t *testing.T) { diff --git a/x/distribution/types/dec_coin_test.go b/x/distribution/types/dec_coin_test.go index 5a326fa17..9b942f07c 100644 --- a/x/distribution/types/dec_coin_test.go +++ b/x/distribution/types/dec_coin_test.go @@ -3,9 +3,10 @@ package types import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" ) func TestPlusDecCoin(t *testing.T) { diff --git a/x/distribution/types/delegator_info_test.go b/x/distribution/types/delegator_info_test.go index e15ad2930..5619fb4d1 100644 --- a/x/distribution/types/delegator_info_test.go +++ b/x/distribution/types/delegator_info_test.go @@ -3,8 +3,9 @@ package types import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" + + sdk "github.com/cosmos/cosmos-sdk/types" ) func TestWithdrawRewards(t *testing.T) { diff --git a/x/distribution/types/fee_pool_test.go b/x/distribution/types/fee_pool_test.go index 73bda52fa..ceb908d7f 100644 --- a/x/distribution/types/fee_pool_test.go +++ b/x/distribution/types/fee_pool_test.go @@ -3,8 +3,9 @@ package types import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" ) func TestUpdateTotalValAccum(t *testing.T) { diff --git a/x/distribution/types/test_common.go b/x/distribution/types/test_common.go index b77efd46c..480244ac3 100644 --- a/x/distribution/types/test_common.go +++ b/x/distribution/types/test_common.go @@ -1,9 +1,10 @@ package types import ( - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" + + sdk "github.com/cosmos/cosmos-sdk/types" ) var ( diff --git a/x/distribution/types/total_accum_test.go b/x/distribution/types/total_accum_test.go index 81f80a154..3984612ad 100644 --- a/x/distribution/types/total_accum_test.go +++ b/x/distribution/types/total_accum_test.go @@ -3,8 +3,9 @@ package types import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" ) func TestTotalAccumUpdateForNewHeight(t *testing.T) { diff --git a/x/distribution/types/validator_info_test.go b/x/distribution/types/validator_info_test.go index 24c3eaee4..119eb6343 100644 --- a/x/distribution/types/validator_info_test.go +++ b/x/distribution/types/validator_info_test.go @@ -3,9 +3,10 @@ package types import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" ) func TestTakeFeePoolRewards(t *testing.T) { diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index 4f0c86fea..06dabfcdd 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -5,13 +5,14 @@ import ( "strconv" "strings" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "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/gov" govClientUtils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" - "github.com/spf13/cobra" - "github.com/spf13/viper" ) // GetCmdQueryProposal implements the query proposal command. diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index 58ce91352..74c311ef4 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -5,21 +5,23 @@ import ( "os" "strconv" + "github.com/pkg/errors" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "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/gov" - "github.com/pkg/errors" "encoding/json" "io/ioutil" "strings" - govClientUtils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" "github.com/spf13/cobra" "github.com/spf13/viper" + + govClientUtils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" ) const ( diff --git a/x/gov/client/cli/tx_test.go b/x/gov/client/cli/tx_test.go index e3aed05ff..73df8c290 100644 --- a/x/gov/client/cli/tx_test.go +++ b/x/gov/client/cli/tx_test.go @@ -1,10 +1,11 @@ package cli import ( - "github.com/spf13/viper" - "github.com/stretchr/testify/require" "io/ioutil" "testing" + + "github.com/spf13/viper" + "github.com/stretchr/testify/require" ) func TestParseSubmitProposalFlags(t *testing.T) { diff --git a/x/gov/client/module_client.go b/x/gov/client/module_client.go index 456ddfbe7..1f67c9c07 100644 --- a/x/gov/client/module_client.go +++ b/x/gov/client/module_client.go @@ -1,10 +1,11 @@ package client import ( - "github.com/cosmos/cosmos-sdk/client" - govCli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" "github.com/spf13/cobra" amino "github.com/tendermint/go-amino" + + "github.com/cosmos/cosmos-sdk/client" + govCli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" ) // ModuleClient exports all client functionality from this module diff --git a/x/gov/client/rest/rest.go b/x/gov/client/rest/rest.go index 72abdb214..53deffbbe 100644 --- a/x/gov/client/rest/rest.go +++ b/x/gov/client/rest/rest.go @@ -10,9 +10,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov" - govClientUtils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" "github.com/gorilla/mux" "github.com/pkg/errors" + + govClientUtils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" ) // REST Variable names diff --git a/x/gov/depositsvotes.go b/x/gov/depositsvotes.go index 8e22f245d..3e2ac5673 100644 --- a/x/gov/depositsvotes.go +++ b/x/gov/depositsvotes.go @@ -4,8 +4,9 @@ import ( "encoding/json" "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/pkg/errors" + + sdk "github.com/cosmos/cosmos-sdk/types" ) // Vote diff --git a/x/gov/endblocker_test.go b/x/gov/endblocker_test.go index 47e903758..622d0968f 100644 --- a/x/gov/endblocker_test.go +++ b/x/gov/endblocker_test.go @@ -6,9 +6,10 @@ import ( "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" + sdk "github.com/cosmos/cosmos-sdk/types" stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" - abci "github.com/tendermint/tendermint/abci/types" ) func TestTickExpiredDepositPeriod(t *testing.T) { diff --git a/x/gov/querier.go b/x/gov/querier.go index cde85bf94..8b985929e 100644 --- a/x/gov/querier.go +++ b/x/gov/querier.go @@ -3,9 +3,10 @@ package gov import ( "fmt" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" ) // query endpoints supported by the governance Querier diff --git a/x/gov/querier_test.go b/x/gov/querier_test.go index 9ee71323e..01b611e19 100644 --- a/x/gov/querier_test.go +++ b/x/gov/querier_test.go @@ -4,10 +4,11 @@ import ( "strings" "testing" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" ) func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier) (DepositParams, VotingParams, TallyParams) { diff --git a/x/gov/tally_test.go b/x/gov/tally_test.go index 86564ed42..fc5cac910 100644 --- a/x/gov/tally_test.go +++ b/x/gov/tally_test.go @@ -5,11 +5,12 @@ import ( "github.com/stretchr/testify/require" - sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/stake" stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" ) diff --git a/x/mock/app.go b/x/mock/app.go index 9251a95c0..066ac93dc 100644 --- a/x/mock/app.go +++ b/x/mock/app.go @@ -7,16 +7,17 @@ import ( "os" "sort" - bam "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/crypto/secp256k1" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" + + bam "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" ) const chainID = "" diff --git a/x/mock/app_test.go b/x/mock/app_test.go index 1af0e4a03..098126d89 100644 --- a/x/mock/app_test.go +++ b/x/mock/app_test.go @@ -3,10 +3,11 @@ package mock import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" ) const msgRoute = "testMsg" diff --git a/x/mock/simulation/invariants.go b/x/mock/simulation/invariants.go index a3ae5f3c3..d30b67be9 100644 --- a/x/mock/simulation/invariants.go +++ b/x/mock/simulation/invariants.go @@ -4,9 +4,10 @@ import ( "fmt" "testing" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" ) // An Invariant is a function which tests a particular invariant. diff --git a/x/mock/test_utils.go b/x/mock/test_utils.go index 4d5fe05f3..9c24967ab 100644 --- a/x/mock/test_utils.go +++ b/x/mock/test_utils.go @@ -5,11 +5,12 @@ import ( "math/rand" "testing" - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" + + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" ) // BigInterval is a representation of the interval [lo, hi), where diff --git a/x/slashing/client/cli/tx.go b/x/slashing/client/cli/tx.go index 513710ce4..2e97414bd 100644 --- a/x/slashing/client/cli/tx.go +++ b/x/slashing/client/cli/tx.go @@ -1,13 +1,14 @@ package cli import ( + "os" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "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/slashing" - "os" "github.com/spf13/cobra" ) diff --git a/x/slashing/client/module_client.go b/x/slashing/client/module_client.go index 82efb5afe..2d7c6b6eb 100644 --- a/x/slashing/client/module_client.go +++ b/x/slashing/client/module_client.go @@ -1,10 +1,11 @@ package client import ( - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" "github.com/spf13/cobra" amino "github.com/tendermint/go-amino" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" ) // ModuleClient exports all client functionality from this module diff --git a/x/slashing/client/rest/query.go b/x/slashing/client/rest/query.go index e55b6b9be..a95c01acf 100644 --- a/x/slashing/client/rest/query.go +++ b/x/slashing/client/rest/query.go @@ -3,12 +3,13 @@ package rest import ( "net/http" + "github.com/gorilla/mux" + "github.com/cosmos/cosmos-sdk/client/context" "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/slashing" - "github.com/gorilla/mux" ) func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { diff --git a/x/slashing/keeper.go b/x/slashing/keeper.go index 61d366172..5137b1198 100644 --- a/x/slashing/keeper.go +++ b/x/slashing/keeper.go @@ -4,11 +4,12 @@ import ( "fmt" "time" + "github.com/tendermint/tendermint/crypto" + "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" - "github.com/tendermint/tendermint/crypto" ) // Keeper of the slashing store diff --git a/x/slashing/keeper_test.go b/x/slashing/keeper_test.go index dd32ea3f8..fdf409c23 100644 --- a/x/slashing/keeper_test.go +++ b/x/slashing/keeper_test.go @@ -4,10 +4,11 @@ import ( "testing" "time" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/stake" ) // Have to change these parameters for tests diff --git a/x/slashing/tick.go b/x/slashing/tick.go index 03bd094af..41af4b9ae 100644 --- a/x/slashing/tick.go +++ b/x/slashing/tick.go @@ -4,9 +4,10 @@ import ( "encoding/binary" "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" tmtypes "github.com/tendermint/tendermint/types" + + sdk "github.com/cosmos/cosmos-sdk/types" ) // slashing begin block functionality diff --git a/x/stake/client/cli/utils.go b/x/stake/client/cli/utils.go index 502cb11ec..848e1725d 100644 --- a/x/stake/client/cli/utils.go +++ b/x/stake/client/cli/utils.go @@ -1,12 +1,13 @@ package cli import ( + "github.com/pkg/errors" + "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/pkg/errors" ) func getShares( diff --git a/x/stake/client/module_client.go b/x/stake/client/module_client.go index 5a08668dc..03a7c25e2 100644 --- a/x/stake/client/module_client.go +++ b/x/stake/client/module_client.go @@ -1,10 +1,11 @@ package client import ( - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/x/stake/client/cli" "github.com/spf13/cobra" amino "github.com/tendermint/go-amino" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/x/stake/client/cli" ) // ModuleClient exports all client functionality from this module diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 5788346f2..085d7e4e2 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -1,10 +1,11 @@ package rest import ( - "github.com/cosmos/cosmos-sdk/x/stake" "net/http" "strings" + "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/client/utils" diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 7f6edc193..d9ae457cf 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -4,6 +4,8 @@ import ( "fmt" "net/http" + "github.com/gorilla/mux" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/client/utils" @@ -11,7 +13,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/stake" "github.com/cosmos/cosmos-sdk/x/stake/tags" - "github.com/gorilla/mux" rpcclient "github.com/tendermint/tendermint/rpc/client" ) diff --git a/x/stake/genesis_test.go b/x/stake/genesis_test.go index dfe5b7d1b..f747ca7a7 100644 --- a/x/stake/genesis_test.go +++ b/x/stake/genesis_test.go @@ -8,11 +8,12 @@ import ( "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + 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" - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" ) func TestInitGenesis(t *testing.T) { diff --git a/x/stake/keeper/key_test.go b/x/stake/keeper/key_test.go index 0658e4b24..f994c3920 100644 --- a/x/stake/keeper/key_test.go +++ b/x/stake/keeper/key_test.go @@ -5,10 +5,11 @@ import ( "math/big" "testing" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake/types" "github.com/stretchr/testify/assert" "github.com/tendermint/tendermint/crypto/ed25519" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/stake/types" ) var ( diff --git a/x/stake/keeper/slash_test.go b/x/stake/keeper/slash_test.go index 9f89dd210..94418a962 100644 --- a/x/stake/keeper/slash_test.go +++ b/x/stake/keeper/slash_test.go @@ -6,9 +6,10 @@ import ( "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/stake/types" - abci "github.com/tendermint/tendermint/abci/types" ) // TODO integrate with test_common.go helper (CreateTestInput) diff --git a/x/stake/keeper/validator_test.go b/x/stake/keeper/validator_test.go index 71b0edcd1..e328537a5 100644 --- a/x/stake/keeper/validator_test.go +++ b/x/stake/keeper/validator_test.go @@ -5,9 +5,10 @@ import ( "testing" "time" + abci "github.com/tendermint/tendermint/abci/types" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/stake/types" - abci "github.com/tendermint/tendermint/abci/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/x/stake/querier/querier.go b/x/stake/querier/querier.go index 13ff97ef3..70627f0b1 100644 --- a/x/stake/querier/querier.go +++ b/x/stake/querier/querier.go @@ -1,11 +1,12 @@ package querier import ( + abci "github.com/tendermint/tendermint/abci/types" + "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" - abci "github.com/tendermint/tendermint/abci/types" ) // query endpoints supported by the staking Querier diff --git a/x/stake/querier/querier_test.go b/x/stake/querier/querier_test.go index c13a37897..525f3691a 100644 --- a/x/stake/querier/querier_test.go +++ b/x/stake/querier/querier_test.go @@ -3,12 +3,13 @@ package querier import ( "testing" + "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" + "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" - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" ) var ( diff --git a/x/stake/types/delegation_test.go b/x/stake/types/delegation_test.go index e75212257..ee7d81bf5 100644 --- a/x/stake/types/delegation_test.go +++ b/x/stake/types/delegation_test.go @@ -4,8 +4,9 @@ import ( "testing" "time" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" ) func TestDelegationEqual(t *testing.T) { diff --git a/x/stake/types/msg.go b/x/stake/types/msg.go index 63d0afb5f..a6692a7f3 100644 --- a/x/stake/types/msg.go +++ b/x/stake/types/msg.go @@ -3,8 +3,9 @@ package types import ( "bytes" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/crypto" + + sdk "github.com/cosmos/cosmos-sdk/types" ) // name to identify transaction routes diff --git a/x/stake/types/msg_test.go b/x/stake/types/msg_test.go index 4b4055fca..e5cb8a9f0 100644 --- a/x/stake/types/msg_test.go +++ b/x/stake/types/msg_test.go @@ -5,8 +5,9 @@ import ( "github.com/stretchr/testify/require" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/crypto" + + sdk "github.com/cosmos/cosmos-sdk/types" ) var ( diff --git a/x/stake/types/pool_test.go b/x/stake/types/pool_test.go index 4541edd3d..f877df0b1 100644 --- a/x/stake/types/pool_test.go +++ b/x/stake/types/pool_test.go @@ -3,8 +3,9 @@ package types import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" ) func TestPoolEqual(t *testing.T) { diff --git a/x/stake/types/test_utils.go b/x/stake/types/test_utils.go index b9d77ce9f..548cd316a 100644 --- a/x/stake/types/test_utils.go +++ b/x/stake/types/test_utils.go @@ -1,9 +1,10 @@ package types import ( - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" + + sdk "github.com/cosmos/cosmos-sdk/types" ) var ( From 2e05d4e3d731188018a14c5cdfb60c55ce82ea79 Mon Sep 17 00:00:00 2001 From: Alessio Treglia Date: Mon, 10 Dec 2018 14:36:20 +0000 Subject: [PATCH 09/21] drop extra else block, outdent its block, and make linter happy --- x/stake/keeper/test_common.go | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/x/stake/keeper/test_common.go b/x/stake/keeper/test_common.go index f52b41c44..c3ca811cd 100644 --- a/x/stake/keeper/test_common.go +++ b/x/stake/keeper/test_common.go @@ -227,15 +227,14 @@ func TestingUpdateValidator(keeper Keeper, ctx sdk.Context, validator types.Vali panic("validator expected but not found") } return validator - } else { - cachectx, _ := ctx.CacheContext() - keeper.ApplyAndReturnValidatorSetUpdates(cachectx) - validator, found := keeper.GetValidator(cachectx, validator.OperatorAddr) - if !found { - panic("validator expected but not found") - } - return validator } + cachectx, _ := ctx.CacheContext() + keeper.ApplyAndReturnValidatorSetUpdates(cachectx) + validator, found := keeper.GetValidator(cachectx, validator.OperatorAddr) + if !found { + panic("validator expected but not found") + } + return validator } func validatorByPowerIndexExists(k Keeper, ctx sdk.Context, power []byte) bool { From b4528d2a5d864394f09638647be6facf0a7e285d Mon Sep 17 00:00:00 2001 From: Alessio Treglia Date: Mon, 10 Dec 2018 14:39:25 +0000 Subject: [PATCH 10/21] Update PENDING.md --- PENDING.md | 1 + 1 file changed, 1 insertion(+) diff --git a/PENDING.md b/PENDING.md index 95ecba5b5..0bf61e800 100644 --- a/PENDING.md +++ b/PENDING.md @@ -3,6 +3,7 @@ BREAKING CHANGES * Gaia REST API (`gaiacli advanced rest-server`) + * [\#3056](https://github.com/cosmos/cosmos-sdk/pull/3056) `generate_only` and `simulate` have moved from query arguments to POST requests body. * Gaia CLI (`gaiacli`) * [cli] [\#2595](https://github.com/cosmos/cosmos-sdk/issues/2595) Remove `keys new` in favor of `keys add` incorporating existing functionality with addition of key recovery functionality. From 7d55bd1a3653c42655f13f80847c5525c6642b85 Mon Sep 17 00:00:00 2001 From: Christopher Goes Date: Mon, 10 Dec 2018 16:13:26 +0100 Subject: [PATCH 11/21] Merge PR #3063: Fix linter --- x/stake/keeper/test_common.go | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/x/stake/keeper/test_common.go b/x/stake/keeper/test_common.go index f52b41c44..c3ca811cd 100644 --- a/x/stake/keeper/test_common.go +++ b/x/stake/keeper/test_common.go @@ -227,15 +227,14 @@ func TestingUpdateValidator(keeper Keeper, ctx sdk.Context, validator types.Vali panic("validator expected but not found") } return validator - } else { - cachectx, _ := ctx.CacheContext() - keeper.ApplyAndReturnValidatorSetUpdates(cachectx) - validator, found := keeper.GetValidator(cachectx, validator.OperatorAddr) - if !found { - panic("validator expected but not found") - } - return validator } + cachectx, _ := ctx.CacheContext() + keeper.ApplyAndReturnValidatorSetUpdates(cachectx) + validator, found := keeper.GetValidator(cachectx, validator.OperatorAddr) + if !found { + panic("validator expected but not found") + } + return validator } func validatorByPowerIndexExists(k Keeper, ctx sdk.Context, power []byte) bool { From da7f459d44b048a1ee1a3ada107a573be8622cc7 Mon Sep 17 00:00:00 2001 From: dongsamb Date: Tue, 11 Dec 2018 00:29:10 +0900 Subject: [PATCH 12/21] Merge PR #3050: Add generate-only option to withdraw-rewards --- x/distribution/client/cli/tx.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index ee82498e8..0a51b2e8e 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -3,6 +3,7 @@ package cli import ( "fmt" + "os" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -88,6 +89,10 @@ func GetCmdWithdrawRewards(cdc *codec.Codec) *cobra.Command { msg = types.NewMsgWithdrawDelegatorRewardsAll(delAddr) } + if cliCtx.GenerateOnly { + return utils.PrintUnsignedStdTx(os.Stdout, txBldr, cliCtx, []sdk.Msg{msg}, false) + } + // build and sign the transaction, then broadcast to Tendermint return utils.CompleteAndBroadcastTxCli(txBldr, cliCtx, []sdk.Msg{msg}) }, From 4f34cb7c1e917224f28c12ff052e98dd9d311084 Mon Sep 17 00:00:00 2001 From: Alessio Treglia Date: Mon, 10 Dec 2018 16:00:38 +0000 Subject: [PATCH 13/21] Update LCD swagger docs --- client/lcd/swagger-ui/swagger.yaml | 66 +++--------------------------- 1 file changed, 6 insertions(+), 60 deletions(-) diff --git a/client/lcd/swagger-ui/swagger.yaml b/client/lcd/swagger-ui/swagger.yaml index 82e7c3429..0ecbe505f 100644 --- a/client/lcd/swagger-ui/swagger.yaml +++ b/client/lcd/swagger-ui/swagger.yaml @@ -376,16 +376,6 @@ paths: produces: - application/json parameters: - - in: query - name: simulate - description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it - required: false - type: boolean - - in: query - name: generate_only - description: if true, build an unsigned transaction and write it back - required: false - type: boolean - in: path name: address description: Account address in bech32 format @@ -638,16 +628,6 @@ paths: post: summary: Submit delegation parameters: - - in: query - name: simulate - description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it - required: false - type: boolean - - in: query - name: generate_only - description: if true, build an unsigned transaction and write it back - required: false - type: boolean - in: body name: delegation description: The password of the account to remove from the KMS @@ -1123,16 +1103,6 @@ paths: tags: - ICS23 parameters: - - in: query - name: simulate - description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it - required: false - type: boolean - - in: query - name: generate_only - description: if true, build an unsigned transaction and write it back - required: false - type: boolean - type: string description: Bech32 validator address name: validatorAddr @@ -1169,16 +1139,6 @@ paths: tags: - ICS22 parameters: - - in: query - name: simulate - description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it - required: false - type: boolean - - in: query - name: generate_only - description: if true, build an unsigned transaction and write it back - required: false - type: boolean - description: valid value of `"proposal_type"` can be `"text"`, `"parameter_change"`, `"software_upgrade"` name: post_proposal_body in: body @@ -1257,16 +1217,6 @@ paths: tags: - ICS22 parameters: - - in: query - name: simulate - description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it - required: false - type: boolean - - in: query - name: generate_only - description: if true, build an unsigned transaction and write it back - required: false - type: boolean - type: string description: proposal id name: proposalId @@ -1355,16 +1305,6 @@ paths: tags: - ICS22 parameters: - - in: query - name: simulate - description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it - required: false - type: boolean - - in: query - name: generate_only - description: if true, build an unsigned transaction and write it back - required: false - type: boolean - type: string description: proposal id name: proposalId @@ -1888,6 +1828,12 @@ definitions: gas_adjustment: type: string example: "1.2" + generate_only: + type: boolean + example: false + simulate: + type: boolean + example: true TendermintValidator: type: object properties: From 2ce41760e2c9cff38ed2fa191c949996aa2f2d9a Mon Sep 17 00:00:00 2001 From: Alexander Bezobchuk Date: Mon, 10 Dec 2018 14:24:57 -0500 Subject: [PATCH 14/21] Merge PR #3070: Check for gas overflow in tx validation * Check for gas overflow in tx validation * Use bitshifting over math.Pow --- PENDING.md | 5 +++-- x/auth/stdtx.go | 9 ++++++++- x/auth/stdtx_test.go | 9 +++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/PENDING.md b/PENDING.md index 95ecba5b5..932b3554a 100644 --- a/PENDING.md +++ b/PENDING.md @@ -48,10 +48,11 @@ IMPROVEMENTS * Gaia * SDK - - \#1277 Complete bank module specification - - \#2963 Complete auth module specification + * \#1277 Complete bank module specification + * \#2963 Complete auth module specification * \#2914 No longer withdraw validator rewards on bond/unbond, but rather move the rewards to the respective validator's pools. + * \#3068 check for uint64 gas overflow during `Std#ValidateBasic`. * Tendermint diff --git a/x/auth/stdtx.go b/x/auth/stdtx.go index 59edf7c13..f648d7e77 100644 --- a/x/auth/stdtx.go +++ b/x/auth/stdtx.go @@ -10,7 +10,11 @@ import ( "github.com/tendermint/tendermint/crypto/multisig" ) -var _ sdk.Tx = (*StdTx)(nil) +var ( + _ sdk.Tx = (*StdTx)(nil) + + maxGasWanted = uint64((1 << 63) - 1) +) // StdTx is a standard way to wrap a Msg with Fee and Signatures. // NOTE: the first signature is the fee payer (Signatures must not be nil). @@ -38,6 +42,9 @@ func (tx StdTx) GetMsgs() []sdk.Msg { return tx.Msgs } func (tx StdTx) ValidateBasic() sdk.Error { stdSigs := tx.GetSignatures() + if tx.Fee.Gas > maxGasWanted { + return sdk.ErrInternal(fmt.Sprintf("invalid gas supplied; %d > %d", tx.Fee.Gas, maxGasWanted)) + } if !tx.Fee.Amount.IsNotNegative() { return sdk.ErrInsufficientFee(fmt.Sprintf("invalid fee %s amount provided", tx.Fee.Amount)) } diff --git a/x/auth/stdtx_test.go b/x/auth/stdtx_test.go index 1f2fefaca..735944420 100644 --- a/x/auth/stdtx_test.go +++ b/x/auth/stdtx_test.go @@ -120,6 +120,15 @@ func TestTxValidateBasic(t *testing.T) { require.Error(t, err) require.Equal(t, sdk.CodeTooManySignatures, err.Result().Code) + // require to fail with invalid gas supplied + badFee = newStdFee() + badFee.Gas = 9223372036854775808 + tx = newTestTx(ctx, nil, nil, nil, nil, badFee) + + err = tx.ValidateBasic() + require.Error(t, err) + require.Equal(t, sdk.CodeInternal, err.Result().Code) + // require to pass when above criteria are matched privs, accNums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{0, 0} tx = newTestTx(ctx, msgs, privs, accNums, seqs, fee) From 243576143e3c72e6c6d60699323a341f549b5ad7 Mon Sep 17 00:00:00 2001 From: Christopher Goes Date: Mon, 10 Dec 2018 21:39:29 +0100 Subject: [PATCH 15/21] Merge PR #3072: Catch overflows in gas wanted * Check for overflow * Only expect block gas meter on DeliverTx * ErrGasOverflow in tx.ValidateBasic() * Update unit test --- PENDING.md | 1 + baseapp/baseapp.go | 8 ++++++++ types/errors.go | 4 ++++ x/auth/stdtx.go | 2 +- x/auth/stdtx_test.go | 2 +- 5 files changed, 15 insertions(+), 2 deletions(-) diff --git a/PENDING.md b/PENDING.md index 932b3554a..3f5c8e967 100644 --- a/PENDING.md +++ b/PENDING.md @@ -69,5 +69,6 @@ BUG FIXES * SDK * \#2967 Change ordering of `mint.BeginBlocker` and `distr.BeginBlocker`, recalculate inflation each block + * \#3071 Catch overflow on block gas meter * Tendermint diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index eeeea53da..c3042b588 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -701,6 +701,11 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk return } + var startingGas uint64 + if mode == runTxModeDeliver { + startingGas = ctx.BlockGasMeter().GasConsumed() + } + defer func() { if r := recover(); r != nil { switch rType := r.(type) { @@ -726,6 +731,9 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk if mode == runTxModeDeliver { ctx.BlockGasMeter().ConsumeGas( ctx.GasMeter().GasConsumedToLimit(), "block gas meter") + if ctx.BlockGasMeter().GasConsumed() < startingGas { + panic(sdk.ErrorGasOverflow{"tx gas summation"}) + } } }() diff --git a/types/errors.go b/types/errors.go index 46436531e..9e4d880df 100644 --- a/types/errors.go +++ b/types/errors.go @@ -43,6 +43,7 @@ const ( CodeMemoTooLarge CodeType = 13 CodeInsufficientFee CodeType = 14 CodeTooManySignatures CodeType = 15 + CodeGasOverflow CodeType = 16 // CodespaceRoot is a codespace for error codes in this file only. // Notice that 0 is an "unset" codespace, which can be overridden with @@ -143,6 +144,9 @@ func ErrInsufficientFee(msg string) Error { func ErrTooManySignatures(msg string) Error { return newErrorWithRootCodespace(CodeTooManySignatures, msg) } +func ErrGasOverflow(msg string) Error { + return newErrorWithRootCodespace(CodeGasOverflow, msg) +} //---------------------------------------- // Error & sdkError diff --git a/x/auth/stdtx.go b/x/auth/stdtx.go index f648d7e77..d1895a194 100644 --- a/x/auth/stdtx.go +++ b/x/auth/stdtx.go @@ -43,7 +43,7 @@ func (tx StdTx) ValidateBasic() sdk.Error { stdSigs := tx.GetSignatures() if tx.Fee.Gas > maxGasWanted { - return sdk.ErrInternal(fmt.Sprintf("invalid gas supplied; %d > %d", tx.Fee.Gas, maxGasWanted)) + return sdk.ErrGasOverflow(fmt.Sprintf("invalid gas supplied; %d > %d", tx.Fee.Gas, maxGasWanted)) } if !tx.Fee.Amount.IsNotNegative() { return sdk.ErrInsufficientFee(fmt.Sprintf("invalid fee %s amount provided", tx.Fee.Amount)) diff --git a/x/auth/stdtx_test.go b/x/auth/stdtx_test.go index 735944420..1ad9ef6e2 100644 --- a/x/auth/stdtx_test.go +++ b/x/auth/stdtx_test.go @@ -127,7 +127,7 @@ func TestTxValidateBasic(t *testing.T) { err = tx.ValidateBasic() require.Error(t, err) - require.Equal(t, sdk.CodeInternal, err.Result().Code) + require.Equal(t, sdk.CodeGasOverflow, err.Result().Code) // require to pass when above criteria are matched privs, accNums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{0, 0} From c7646d2caf49d607d90570081dd72cb27d1dcba4 Mon Sep 17 00:00:00 2001 From: Christopher Goes Date: Mon, 10 Dec 2018 22:48:01 +0100 Subject: [PATCH 16/21] Release v0.28.0 back to develop (#3043) * PENDING.md => CHANGELOG.md --- CHANGELOG.md | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++ PENDING.md | 22 --------------------- 2 files changed, 55 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7894748a4..2ff20a938 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,60 @@ # Changelog +## 0.28.0 + +BREAKING CHANGES + +* Gaia CLI (`gaiacli`) + * [cli] [\#2595](https://github.com/cosmos/cosmos-sdk/issues/2595) Remove `keys new` in favor of `keys add` incorporating existing functionality with addition of key recovery functionality. + * [cli] [\#2987](https://github.com/cosmos/cosmos-sdk/pull/2987) Add shorthand `-a` to `gaiacli keys show` and update docs + * [cli] [\#2971](https://github.com/cosmos/cosmos-sdk/pull/2971) Additional verification when running `gaiad gentx` + * [cli] [\#2734](https://github.com/cosmos/cosmos-sdk/issues/2734) Rewrite `gaiacli config`. It is now a non-interactive config utility. + +* Gaia + * [#128](https://github.com/tendermint/devops/issues/128) Updated CircleCI job to trigger website build on every push to master/develop. + * [\#2994](https://github.com/cosmos/cosmos-sdk/pull/2994) Change wrong-password error message. + * [\#3009](https://github.com/cosmos/cosmos-sdk/issues/3009) Added missing Gaia genesis verification + * [#128](https://github.com/tendermint/devops/issues/128) Updated CircleCI job to trigger website build on every push to master/develop. + * [\#2994](https://github.com/cosmos/cosmos-sdk/pull/2994) Change wrong-password error message. + * [\#3009](https://github.com/cosmos/cosmos-sdk/issues/3009) Added missing Gaia genesis verification + * [gas] [\#3052](https://github.com/cosmos/cosmos-sdk/issues/3052) Updated gas costs to more reasonable numbers + +* SDK + * [auth] [\#2952](https://github.com/cosmos/cosmos-sdk/issues/2952) Signatures are no longer serialized on chain with the account number and sequence number + * [auth] [\#2952](https://github.com/cosmos/cosmos-sdk/issues/2952) Signatures are no longer serialized on chain with the account number and sequence number + * [stake] [\#3055](https://github.com/cosmos/cosmos-sdk/issues/3055) Use address instead of bond height / intratxcounter for deduplication + +FEATURES + +* Gaia CLI (`gaiacli`) + * [\#2961](https://github.com/cosmos/cosmos-sdk/issues/2961) Add --force flag to gaiacli keys delete command to skip passphrase check and force key deletion unconditionally. + +IMPROVEMENTS + +* Gaia CLI (`gaiacli`) + * [\#2991](https://github.com/cosmos/cosmos-sdk/issues/2991) Fully validate transaction signatures during `gaiacli tx sign --validate-signatures` + +* SDK + * [\#1277](https://github.com/cosmos/cosmos-sdk/issues/1277) Complete bank module specification + * [\#2963](https://github.com/cosmos/cosmos-sdk/issues/2963) Complete auth module specification + * [\#2914](https://github.com/cosmos/cosmos-sdk/issues/2914) No longer withdraw validator rewards on bond/unbond, but rather move + the rewards to the respective validator's pools. + + +BUG FIXES + +* Gaia CLI (`gaiacli`) + * [\#2921](https://github.com/cosmos/cosmos-sdk/issues/2921) Fix `keys delete` inability to delete offline and ledger keys. + +* Gaia + * [\#3003](https://github.com/cosmos/cosmos-sdk/issues/3003) CollectStdTxs() must validate DelegatorAddr against genesis accounts. + +* SDK + * [\#2967](https://github.com/cosmos/cosmos-sdk/issues/2967) Change ordering of `mint.BeginBlocker` and `distr.BeginBlocker`, recalculate inflation each block + * [\#3068](https://github.com/cosmos/cosmos-sdk/issues/3068) check for uint64 gas overflow during `Std#ValidateBasic`. + * [\#3071](https://github.com/cosmos/cosmos-sdk/issues/3071) Catch overflow on block gas meter + + ## 0.27.0 BREAKING CHANGES diff --git a/PENDING.md b/PENDING.md index 3f5c8e967..4d87301f0 100644 --- a/PENDING.md +++ b/PENDING.md @@ -5,20 +5,10 @@ BREAKING CHANGES * Gaia REST API (`gaiacli advanced rest-server`) * Gaia CLI (`gaiacli`) - * [cli] [\#2595](https://github.com/cosmos/cosmos-sdk/issues/2595) Remove `keys new` in favor of `keys add` incorporating existing functionality with addition of key recovery functionality. - * [cli] [\#2987](https://github.com/cosmos/cosmos-sdk/pull/2987) Add shorthand `-a` to `gaiacli keys show` and update docs - * [cli] [\#2971](https://github.com/cosmos/cosmos-sdk/pull/2971) Additional verification when running `gaiad gentx` - * [cli] [\#2734](https://github.com/cosmos/cosmos-sdk/issues/2734) Rewrite `gaiacli config`. It is now a non-interactive config utility. * Gaia - - [#128](https://github.com/tendermint/devops/issues/128) Updated CircleCI job to trigger website build on every push to master/develop. - - [\#2994](https://github.com/cosmos/cosmos-sdk/pull/2994) Change wrong-password error message. - - \#3009 Added missing Gaia genesis verification - - [gas] \#3052 Updated gas costs to more reasonable numbers * SDK - - [auth] \#2952 Signatures are no longer serialized on chain with the account number and sequence number - - [stake] \#3055 Use address instead of bond height / intratxcounter for deduplication * Tendermint @@ -28,10 +18,8 @@ FEATURES * Gaia REST API (`gaiacli advanced rest-server`) * Gaia CLI (`gaiacli`) - - [\#2961](https://github.com/cosmos/cosmos-sdk/issues/2961) Add --force flag to gaiacli keys delete command to skip passphrase check and force key deletion unconditionally. * Gaia - - [gov] Added minimum quorum needed for vote to pass * SDK @@ -43,16 +31,10 @@ IMPROVEMENTS * Gaia REST API (`gaiacli advanced rest-server`) * Gaia CLI (`gaiacli`) - * \#2991 Fully validate transaction signatures during `gaiacli tx sign --validate-signatures` * Gaia * SDK - * \#1277 Complete bank module specification - * \#2963 Complete auth module specification - * \#2914 No longer withdraw validator rewards on bond/unbond, but rather move - the rewards to the respective validator's pools. - * \#3068 check for uint64 gas overflow during `Std#ValidateBasic`. * Tendermint @@ -62,13 +44,9 @@ BUG FIXES * Gaia REST API (`gaiacli advanced rest-server`) * Gaia CLI (`gaiacli`) - * [\#2921](https://github.com/cosmos/cosmos-sdk/issues/2921) Fix `keys delete` inability to delete offline and ledger keys. * Gaia - * [\#3003](https://github.com/cosmos/cosmos-sdk/issues/3003) CollectStdTxs() must validate DelegatorAddr against genesis accounts. * SDK - * \#2967 Change ordering of `mint.BeginBlocker` and `distr.BeginBlocker`, recalculate inflation each block - * \#3071 Catch overflow on block gas meter * Tendermint From affa1fb3f310f58e1d429f0555a0b0b5d085d9e8 Mon Sep 17 00:00:00 2001 From: Alessio Treglia Date: Thu, 6 Dec 2018 11:03:58 +0000 Subject: [PATCH 17/21] Reintroduce collect-gentxs's --gentx-dir flag It went lost in last genesis workflow refactoring. Also address structs initializations as per #2835. --- client/flags.go | 1 + cmd/gaia/cli_test/cli_test.go | 31 ++++++++++++++++++++++ cmd/gaia/init/collect.go | 48 ++++++++++++++++++++++++++--------- cmd/gaia/init/gentx.go | 11 +++++--- cmd/gaia/init/init.go | 8 ++---- cmd/gaia/init/testnet.go | 8 +----- x/stake/client/cli/flags.go | 2 -- 7 files changed, 79 insertions(+), 30 deletions(-) diff --git a/client/flags.go b/client/flags.go index 6a3ccff06..cf7be359e 100644 --- a/client/flags.go +++ b/client/flags.go @@ -43,6 +43,7 @@ const ( FlagSSLHosts = "ssl-hosts" FlagSSLCertFile = "ssl-certfile" FlagSSLKeyFile = "ssl-keyfile" + FlagOutputDocument = "output-document" // inspired by wget -O ) // LineBreak can be included in a command list to provide a blank line diff --git a/cmd/gaia/cli_test/cli_test.go b/cmd/gaia/cli_test/cli_test.go index f7d3b2d83..845edc757 100644 --- a/cmd/gaia/cli_test/cli_test.go +++ b/cmd/gaia/cli_test/cli_test.go @@ -645,6 +645,37 @@ trust_node = true cleanupDirs(gaiadHome, gaiacliHome) } +func TestGaiadCollectGentxs(t *testing.T) { + t.Parallel() + // 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)) + + // 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) +} + //___________________________________________________________________________________ // helper methods diff --git a/cmd/gaia/init/collect.go b/cmd/gaia/init/collect.go index da97e4626..e630d494c 100644 --- a/cmd/gaia/init/collect.go +++ b/cmd/gaia/init/collect.go @@ -18,6 +18,10 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" ) +const ( + flagGenTxDir = "gentx-dir" +) + type initConfig struct { ChainID string GenTxsDir string @@ -35,7 +39,6 @@ func CollectGenTxsCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { config := ctx.Config config.SetRoot(viper.GetString(cli.HomeFlag)) name := viper.GetString(client.FlagName) - nodeID, valPubKey, err := InitializeNodeValidatorFiles(config) if err != nil { return err @@ -46,19 +49,13 @@ func CollectGenTxsCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { return err } - toPrint := printInfo{ - Moniker: config.Moniker, - ChainID: genDoc.ChainID, - NodeID: nodeID, + genTxsDir := viper.GetString(flagGenTxDir) + if genTxsDir == "" { + genTxsDir = filepath.Join(config.RootDir, "config", "gentx") } - initCfg := initConfig{ - ChainID: genDoc.ChainID, - GenTxsDir: filepath.Join(config.RootDir, "config", "gentx"), - Name: name, - NodeID: nodeID, - ValPubKey: valPubKey, - } + toPrint := newPrintInfo(config.Moniker, genDoc.ChainID, nodeID, genTxsDir, json.RawMessage("")) + initCfg := newInitConfig(genDoc.ChainID, genTxsDir, name, nodeID, valPubKey) appMessage, err := genAppStateFromConfig(cdc, config, initCfg, genDoc) if err != nil { @@ -73,6 +70,9 @@ func CollectGenTxsCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { } cmd.Flags().String(cli.HomeFlag, app.DefaultNodeHome, "node's home directory") + cmd.Flags().String(flagGenTxDir, "", + "override default \"gentx\" directory from which collect and execute "+ + "genesis transactions; default [--home]/config/gentx/") return cmd } @@ -117,3 +117,27 @@ func genAppStateFromConfig( err = ExportGenesisFile(genFile, initCfg.ChainID, nil, appState) return } + +func newInitConfig(chainID, genTxsDir, name, nodeID string, + valPubKey crypto.PubKey) initConfig { + + return initConfig{ + ChainID: chainID, + GenTxsDir: genTxsDir, + Name: name, + NodeID: nodeID, + ValPubKey: valPubKey, + } +} + +func newPrintInfo(moniker, chainID, nodeID, genTxsDir string, + appMessage json.RawMessage) printInfo { + + return printInfo{ + Moniker: moniker, + ChainID: chainID, + NodeID: nodeID, + GenTxsDir: genTxsDir, + AppMessage: appMessage, + } +} diff --git a/cmd/gaia/init/gentx.go b/cmd/gaia/init/gentx.go index c8a7c05d2..9f985762a 100644 --- a/cmd/gaia/init/gentx.go +++ b/cmd/gaia/init/gentx.go @@ -137,9 +137,12 @@ following delegation and commission default parameters: } // Fetch output file name - outputDocument, err := makeOutputFilepath(config.RootDir, nodeID) - if err != nil { - return err + outputDocument := viper.GetString(client.FlagOutputDocument) + if outputDocument == "" { + outputDocument, err = makeOutputFilepath(config.RootDir, nodeID) + if err != nil { + return err + } } if err := writeSignedGenTx(cdc, outputDocument, signedTx); err != nil { @@ -154,6 +157,8 @@ following delegation and commission default parameters: cmd.Flags().String(tmcli.HomeFlag, app.DefaultNodeHome, "node's home directory") cmd.Flags().String(flagClientHome, app.DefaultCLIHome, "client's home directory") cmd.Flags().String(client.FlagName, "", "name of private key with which to sign the gentx") + cmd.Flags().String(client.FlagOutputDocument, "", + "write the genesis transaction JSON document to the given file instead of the default location") cmd.Flags().AddFlagSet(cli.FsCommissionCreate) cmd.Flags().AddFlagSet(cli.FsAmount) cmd.Flags().AddFlagSet(cli.FsPk) diff --git a/cmd/gaia/init/init.go b/cmd/gaia/init/init.go index 7690d5336..922cfbafa 100644 --- a/cmd/gaia/init/init.go +++ b/cmd/gaia/init/init.go @@ -28,6 +28,7 @@ type printInfo struct { Moniker string `json:"moniker"` ChainID string `json:"chain_id"` NodeID string `json:"node_id"` + GenTxsDir string `json:"gentxs_dir"` AppMessage json.RawMessage `json:"app_message"` } @@ -77,12 +78,7 @@ func InitCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { return err } - toPrint := printInfo{ - ChainID: chainID, - Moniker: config.Moniker, - NodeID: nodeID, - AppMessage: appState, - } + toPrint := newPrintInfo(config.Moniker, chainID, nodeID, "", appState) cfg.WriteConfigFile(filepath.Join(config.RootDir, "config", "config.toml"), config) diff --git a/cmd/gaia/init/testnet.go b/cmd/gaia/init/testnet.go index cfa3e6396..10b0b8265 100644 --- a/cmd/gaia/init/testnet.go +++ b/cmd/gaia/init/testnet.go @@ -279,13 +279,7 @@ func collectGenFiles( config.SetRoot(nodeDir) nodeID, valPubKey := nodeIDs[i], valPubKeys[i] - initCfg := initConfig{ - ChainID: chainID, - GenTxsDir: gentxsDir, - Name: moniker, - NodeID: nodeID, - ValPubKey: valPubKey, - } + initCfg := newInitConfig(chainID, gentxsDir, moniker, nodeID, valPubKey) genDoc, err := loadGenesisDoc(cdc, config.GenesisFile()) if err != nil { diff --git a/x/stake/client/cli/flags.go b/x/stake/client/cli/flags.go index d571bef9e..97a62ebd9 100644 --- a/x/stake/client/cli/flags.go +++ b/x/stake/client/cli/flags.go @@ -29,8 +29,6 @@ const ( FlagGenesisFormat = "genesis-format" FlagNodeID = "node-id" FlagIP = "ip" - - FlagOutputDocument = "output-document" // inspired by wget -O ) // common flagsets to add to various functions From 46bb2d0deaf007b5d6b2cf2d069fbd7bc930cf31 Mon Sep 17 00:00:00 2001 From: Alessio Treglia Date: Fri, 7 Dec 2018 13:45:40 +0000 Subject: [PATCH 18/21] Update PENDING.md --- PENDING.md | 1 + 1 file changed, 1 insertion(+) diff --git a/PENDING.md b/PENDING.md index 3c56e9234..1fd33035b 100644 --- a/PENDING.md +++ b/PENDING.md @@ -34,6 +34,7 @@ IMPROVEMENTS * Gaia CLI (`gaiacli`) * Gaia + * [\#3021](https://github.com/cosmos/cosmos-sdk/pull/3021) Add `--gentx-dir` to `gaiad collect-gentxs` to specify a directory from which collect and load gentxs. * SDK From a051491b564ed21ace7c7c80de3511d42d758a43 Mon Sep 17 00:00:00 2001 From: Alessio Treglia Date: Tue, 11 Dec 2018 12:54:45 +0000 Subject: [PATCH 19/21] Update PENDING.md --- PENDING.md | 1 + 1 file changed, 1 insertion(+) diff --git a/PENDING.md b/PENDING.md index 1fd33035b..1acf348e2 100644 --- a/PENDING.md +++ b/PENDING.md @@ -35,6 +35,7 @@ IMPROVEMENTS * Gaia * [\#3021](https://github.com/cosmos/cosmos-sdk/pull/3021) Add `--gentx-dir` to `gaiad collect-gentxs` to specify a directory from which collect and load gentxs. + Add `--output-document` to `gaiad init` to allow one to redirect output to file. * SDK From 4ecbf0dd5f3dd5e1b73bbe84f9463bd34a1540ba Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Tue, 11 Dec 2018 15:02:26 +0100 Subject: [PATCH 20/21] Merge PR #2997: Split POST delegations endpoint --- PENDING.md | 3 +- client/context/context.go | 16 +- client/lcd/lcd_test.go | 59 +-- client/lcd/swagger-ui/swagger.yaml | 605 ++++++++++++++++------------- client/utils/rest.go | 24 +- client/utils/utils.go | 4 +- x/bank/client/rest/sendtx.go | 5 +- x/gov/client/rest/rest.go | 15 +- x/ibc/client/rest/transfer.go | 5 +- x/slashing/client/rest/tx.go | 5 +- x/stake/client/rest/tx.go | 303 +++++---------- 11 files changed, 509 insertions(+), 535 deletions(-) diff --git a/PENDING.md b/PENDING.md index 3c56e9234..cc72812a0 100644 --- a/PENDING.md +++ b/PENDING.md @@ -3,7 +3,8 @@ BREAKING CHANGES * Gaia REST API (`gaiacli advanced rest-server`) - * [\#3056](https://github.com/cosmos/cosmos-sdk/pull/3056) `generate_only` and `simulate` have moved from query arguments to POST requests body. + * [gaia-lite] [\#2191](https://github.com/cosmos/cosmos-sdk/issues/2191) Split `POST /stake/delegators/{delegatorAddr}/delegations` into `POST /stake/delegators/{delegatorAddr}/delegations`, `POST /stake/delegators/{delegatorAddr}/unbonding_delegations` and `POST /stake/delegators/{delegatorAddr}/redelegations` + * [gaia-lite] [\#3056](https://github.com/cosmos/cosmos-sdk/pull/3056) `generate_only` and `simulate` have moved from query arguments to POST requests body. * Gaia CLI (`gaiacli`) diff --git a/client/context/context.go b/client/context/context.go index df30374de..9fac7c27a 100644 --- a/client/context/context.go +++ b/client/context/context.go @@ -47,7 +47,7 @@ type CLIContext struct { JSON bool PrintResponse bool Verifier tmlite.Verifier - DryRun bool + Simulate bool GenerateOnly bool fromAddress types.AccAddress fromName string @@ -85,7 +85,7 @@ func NewCLIContext() CLIContext { JSON: viper.GetBool(client.FlagJson), PrintResponse: viper.GetBool(client.FlagPrintResponse), Verifier: verifier, - DryRun: viper.GetBool(client.FlagDryRun), + Simulate: viper.GetBool(client.FlagDryRun), GenerateOnly: viper.GetBool(client.FlagGenerateOnly), fromAddress: fromAddress, fromName: fromName, @@ -244,3 +244,15 @@ func (ctx CLIContext) WithVerifier(verifier tmlite.Verifier) CLIContext { ctx.Verifier = verifier return ctx } + +// WithGenerateOnly returns a copy of the context with updated GenerateOnly value +func (ctx CLIContext) WithGenerateOnly(generateOnly bool) CLIContext { + ctx.GenerateOnly = generateOnly + return ctx +} + +// WithSimulation returns a copy of the context with updated Simulate value +func (ctx CLIContext) WithSimulation(simulate bool) CLIContext { + ctx.Simulate = simulate + return ctx +} diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 34f8edbc9..bc64c2321 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -342,7 +342,7 @@ func TestCoinSendGenerateSignAndBroadcast(t *testing.T) { acc := getAccount(t, port, addr) // generate TX - res, body, _ := doSendWithGas(t, port, seed, name, password, addr, "simulate", 0, false, true) + res, body, _ := doSendWithGas(t, port, seed, name, "", addr, "simulate", 0, false, true) require.Equal(t, http.StatusOK, res.StatusCode, body) var msg auth.StdTx require.Nil(t, cdc.UnmarshalJSON([]byte(body), &msg)) @@ -1176,15 +1176,9 @@ func doDelegate(t *testing.T, port, seed, name, password string, chainID := viper.GetString(client.FlagChainID) jsonStr := []byte(fmt.Sprintf(`{ - "delegations": [ - { - "delegator_addr": "%s", - "validator_addr": "%s", - "delegation": { "denom": "%s", "amount": "%d" } - } - ], - "begin_unbondings": [], - "begin_redelegates": [], + "delegator_addr": "%s", + "validator_addr": "%s", + "delegation": { "denom": "%s", "amount": "%d" }, "base_req": { "name": "%s", "password": "%s", @@ -1197,11 +1191,10 @@ func doDelegate(t *testing.T, port, seed, name, password string, res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delAddr), jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) - var results []ctypes.ResultBroadcastTxCommit - err := cdc.UnmarshalJSON([]byte(body), &results) + err := cdc.UnmarshalJSON([]byte(body), &resultTx) require.Nil(t, err) - return results[0] + return } func doBeginUnbonding(t *testing.T, port, seed, name, password string, @@ -1213,15 +1206,9 @@ func doBeginUnbonding(t *testing.T, port, seed, name, password string, chainID := viper.GetString(client.FlagChainID) jsonStr := []byte(fmt.Sprintf(`{ - "delegations": [], - "begin_unbondings": [ - { - "delegator_addr": "%s", - "validator_addr": "%s", - "shares": "%d" - } - ], - "begin_redelegates": [], + "delegator_addr": "%s", + "validator_addr": "%s", + "shares": "%d", "base_req": { "name": "%s", "password": "%s", @@ -1231,14 +1218,13 @@ func doBeginUnbonding(t *testing.T, port, seed, name, password string, } }`, delAddr, valAddr, amount, name, password, chainID, accnum, sequence)) - res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delAddr), jsonStr) + res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/unbonding_delegations", delAddr), jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) - var results []ctypes.ResultBroadcastTxCommit - err := cdc.UnmarshalJSON([]byte(body), &results) + err := cdc.UnmarshalJSON([]byte(body), &resultTx) require.Nil(t, err) - return results[0] + return } func doBeginRedelegation(t *testing.T, port, seed, name, password string, @@ -1251,16 +1237,10 @@ func doBeginRedelegation(t *testing.T, port, seed, name, password string, chainID := viper.GetString(client.FlagChainID) jsonStr := []byte(fmt.Sprintf(`{ - "delegations": [], - "begin_unbondings": [], - "begin_redelegates": [ - { - "delegator_addr": "%s", - "validator_src_addr": "%s", - "validator_dst_addr": "%s", - "shares": "%d" - } - ], + "delegator_addr": "%s", + "validator_src_addr": "%s", + "validator_dst_addr": "%s", + "shares": "%d", "base_req": { "name": "%s", "password": "%s", @@ -1270,14 +1250,13 @@ func doBeginRedelegation(t *testing.T, port, seed, name, password string, } }`, delAddr, valSrcAddr, valDstAddr, amount, name, password, chainID, accnum, sequence)) - res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delAddr), jsonStr) + res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/redelegations", delAddr), jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) - var results []ctypes.ResultBroadcastTxCommit - err := cdc.UnmarshalJSON([]byte(body), &results) + err := cdc.UnmarshalJSON([]byte(body), &resultTx) require.Nil(t, err) - return results[0] + return } func getValidators(t *testing.T, port string) []stake.Validator { diff --git a/client/lcd/swagger-ui/swagger.yaml b/client/lcd/swagger-ui/swagger.yaml index 0ecbe505f..a76bdddd6 100644 --- a/client/lcd/swagger-ui/swagger.yaml +++ b/client/lcd/swagger-ui/swagger.yaml @@ -625,71 +625,6 @@ paths: description: Bech32 AccAddress of Delegator required: true type: string - post: - summary: Submit delegation - parameters: - - in: body - name: delegation - description: The password of the account to remove from the KMS - schema: - type: object - properties: - base_req: - "$ref": "#/definitions/BaseReq" - delegations: - type: array - items: - type: object - properties: - delegator_addr: - $ref: "#/definitions/Address" - validator_addr: - $ref: "#/definitions/ValidatorAddress" - delegation: - $ref: "#/definitions/Coin" - begin_unbondings: - type: array - items: - type: object - properties: - delegator_addr: - $ref: "#/definitions/Address" - validator_addr: - $ref: "#/definitions/ValidatorAddress" - shares: - type: string - example: "100" - begin_redelegates: - type: array - items: - type: object - properties: - delegator_addr: - $ref: "#/definitions/Address" - validator_src_addr: - $ref: "#/definitions/ValidatorAddress" - validator_dst_addr: - $ref: "#/definitions/ValidatorAddress" - shares: - type: string - example: "100" - tags: - - ICS21 - consumes: - - application/json - produces: - - application/json - responses: - 200: - description: OK - schema: - $ref: "#/definitions/BroadcastTxCommitResult" - 400: - description: Invalid delegator address or delegation body - 401: - description: Key password is wrong - 500: - description: Internal Server Error get: summary: Get all delegations from a delegator tags: @@ -702,12 +637,72 @@ paths: schema: type: array items: - type: object - "$ref": "#/definitions/Delegation" + $ref: "#/definitions/Delegation" 400: description: Invalid delegator address 500: description: Internal Server Error + post: + summary: Submit delegation + parameters: + - in: body + name: delegation + description: The password of the account to remove from the KMS + schema: + type: object + properties: + base_req: + $ref: "#/definitions/BaseReq" + delegator_addr: + $ref: "#/definitions/Address" + validator_addr: + $ref: "#/definitions/ValidatorAddress" + delegation: + $ref: "#/definitions/Coin" + tags: + - ICS21 + consumes: + - application/json + produces: + - application/json + responses: + 200: + description: OK + schema: + $ref: "#/definitions/BroadcastTxCommitResult" + 400: + description: Invalid delegator address or delegation request body + 401: + description: Key password is wrong + 500: + description: Internal Server Error + /stake/delegators/{delegatorAddr}/delegations/{validatorAddr}: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + - in: path + name: validatorAddr + description: Bech32 OperatorAddress of validator + required: true + type: string + get: + summary: Query the current delegation between a delegator and a validator + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + $ref: "#/definitions/Delegation" + 400: + description: Invalid delegator address or validator address + 500: + description: Internal Server Error /stake/delegators/{delegatorAddr}/unbonding_delegations: parameters: - in: path @@ -727,12 +722,85 @@ paths: schema: type: array items: - type: object - "$ref": "#/definitions/UnbondingDelegation" + $ref: "#/definitions/UnbondingDelegation" 400: description: Invalid delegator address 500: description: Internal Server Error + post: + summary: Submit an unbonding delegation + parameters: + - in: query + name: simulate + description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it + required: false + type: boolean + - in: query + name: generate_only + description: if true, build an unsigned transaction and write it back + required: false + type: boolean + - in: body + name: delegation + description: The password of the account to remove from the KMS + schema: + type: object + properties: + base_req: + $ref: "#/definitions/BaseReq" + delegator_addr: + $ref: "#/definitions/Address" + validator_addr: + $ref: "#/definitions/ValidatorAddress" + shares: + type: string + example: "100" + tags: + - ICS21 + consumes: + - application/json + produces: + - application/json + responses: + 200: + description: OK + schema: + $ref: "#/definitions/BroadcastTxCommitResult" + 400: + description: Invalid delegator address or unbonding delegation request body + 401: + description: Key password is wrong + 500: + description: Internal Server Error + /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + - in: path + name: validatorAddr + description: Bech32 OperatorAddress of validator + required: true + type: string + get: + summary: Query all unbonding delegations between a delegator and a validator + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + type: array + items: + $ref: "#/definitions/UnbondingDelegation" + 400: + description: Invalid delegator address or validator address + 500: + description: Internal Server Error /stake/delegators/{delegatorAddr}/redelegations: parameters: - in: path @@ -752,12 +820,58 @@ paths: schema: type: array items: - type: object - "$ref": "#/definitions/Redelegation" + $ref: "#/definitions/Redelegation" 400: description: Invalid delegator address 500: description: Internal Server Error + post: + summary: Submit a redelegation + parameters: + - in: query + name: simulate + description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it + required: false + type: boolean + - in: query + name: generate_only + description: if true, build an unsigned transaction and write it back + required: false + type: boolean + - in: body + name: delegation + description: The password of the account to remove from the KMS + schema: + type: object + properties: + base_req: + $ref: "#/definitions/BaseReq" + delegator_addr: + $ref: "#/definitions/Address" + validator_src_addr: + $ref: "#/definitions/ValidatorAddress" + validator_dst_addr: + $ref: "#/definitions/ValidatorAddress" + shares: + type: string + example: "100" + tags: + - ICS21 + consumes: + - application/json + produces: + - application/json + responses: + 200: + description: OK + schema: + $ref: "#/definitions/BroadcastTxCommitResult" + 400: + description: Invalid delegator address or redelegation request body + 401: + description: Key password is wrong + 500: + description: Internal Server Error /stake/delegators/{delegatorAddr}/validators: parameters: - in: path @@ -835,63 +949,6 @@ paths: description: Invalid delegator address 500: description: Internal Server Error - /stake/delegators/{delegatorAddr}/delegations/{validatorAddr}: - parameters: - - in: path - name: delegatorAddr - description: Bech32 AccAddress of Delegator - required: true - type: string - - in: path - name: validatorAddr - description: Bech32 OperatorAddress of validator - required: true - type: string - get: - summary: Query the current delegation between a delegator and a validator - tags: - - ICS21 - produces: - - application/json - responses: - 200: - description: OK - schema: - $ref: "#/definitions/Delegation" - 400: - description: Invalid delegator address or validator address - 500: - description: Internal Server Error - /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}: - parameters: - - in: path - name: delegatorAddr - description: Bech32 AccAddress of Delegator - required: true - type: string - - in: path - name: validatorAddr - description: Bech32 OperatorAddress of validator - required: true - type: string - get: - summary: Query all unbonding delegations between a delegator and a validator - tags: - - ICS21 - produces: - - application/json - responses: - 200: - description: OK - schema: - type: array - items: - type: object - "$ref": "#/definitions/UnbondingDelegation" - 400: - description: Invalid delegator address or validator address - 500: - description: Internal Server Error /stake/validators: get: summary: Get all validator candidates @@ -1116,7 +1173,7 @@ paths: type: object properties: base_req: - "$ref": "#/definitions/BaseReq" + $ref: "#/definitions/BaseReq" responses: 200: description: OK @@ -1147,7 +1204,7 @@ paths: type: object properties: base_req: - "$ref": "#/definitions/BaseReq" + $ref: "#/definitions/BaseReq" title: type: string description: @@ -1156,7 +1213,7 @@ paths: type: string example: "text" proposer: - "$ref": "#/definitions/Address" + $ref: "#/definitions/Address" initial_deposit: type: array items: @@ -1165,7 +1222,7 @@ paths: 200: description: OK schema: - "$ref": "#/definitions/BroadcastTxCommitResult" + $ref: "#/definitions/BroadcastTxCommitResult" 400: description: Invalid proposal body 401: @@ -1201,12 +1258,57 @@ paths: schema: type: array items: - "$ref": "#/definitions/TextProposal" + $ref: "#/definitions/TextProposal" 400: description: Invalid query parameters 500: description: Internal Server Error + /gov/proposals/{proposalId}: + get: + summary: Query a proposal + description: Query a proposal by id + produces: + - application/json + tags: + - ICS22 + parameters: + - type: string + name: proposalId + required: true + in: path + responses: + 200: + description: OK + schema: + $ref: "#/definitions/TextProposal" + 400: + description: Invalid proposal id + 500: + description: Internal Server Error /gov/proposals/{proposalId}/deposits: + get: + summary: Query deposits + description: Query deposits by proposalId + produces: + - application/json + tags: + - ICS22 + parameters: + - type: string + name: proposalId + required: true + in: path + responses: + 200: + description: OK + schema: + type: array + items: + $ref: "#/definitions/Deposit" + 400: + description: Invalid proposal id + 500: + description: Internal Server Error post: summary: Deposit tokens to a proposal description: Send transaction to deposit tokens to a proposal @@ -1230,9 +1332,9 @@ paths: type: object properties: base_req: - "$ref": "#/definitions/BaseReq" + $ref: "#/definitions/BaseReq" depositor: - "$ref": "#/definitions/Address" + $ref: "#/definitions/Address" amount: type: array items: @@ -1241,146 +1343,13 @@ paths: 200: description: OK schema: - "$ref": "#/definitions/BroadcastTxCommitResult" + $ref: "#/definitions/BroadcastTxCommitResult" 400: description: Invalid proposal id or deposit body 401: description: Key password is wrong 500: description: Internal Server Error - get: - summary: Query deposits - description: Query deposits by proposalId - produces: - - application/json - tags: - - ICS22 - parameters: - - type: string - name: proposalId - required: true - in: path - responses: - 200: - description: OK - schema: - type: array - items: - "$ref": "#/definitions/Deposit" - 400: - description: Invalid proposal id - 500: - description: Internal Server Error - /gov/proposals/{proposalId}/tally: - get: - summary: Get a proposal's tally result at the current time - description: Gets a proposal's tally result at the current time. If the proposal is pending deposits (i.e status 'DepositPeriod') it returns an empty tally result. - produces: - - application/json - tags: - - ICS22 - parameters: - - type: string - description: proposal id - name: proposalId - required: true - in: path - responses: - 200: - description: OK - schema: - $ref: "#/definitions/TallyResult" - 400: - description: Invalid proposal id - 500: - description: Internal Server Error - /gov/proposals/{proposalId}/votes: - post: - summary: Vote a proposal - description: Send transaction to vote a proposal - consumes: - - application/json - produces: - - application/json - tags: - - ICS22 - parameters: - - type: string - description: proposal id - name: proposalId - required: true - in: path - - description: valid value of `"option"` field can be `"yes"`, `"no"`, `"no_with_veto"` and `"abstain"` - name: post_vote_body - in: body - required: true - schema: - type: object - properties: - base_req: - "$ref": "#/definitions/BaseReq" - voter: - "$ref": "#/definitions/Address" - option: - type: string - example: "yes" - responses: - 200: - description: OK - schema: - "$ref": "#/definitions/BroadcastTxCommitResult" - 400: - description: Invalid proposal id or vote body - 401: - description: Key password is wrong - 500: - description: Internal Server Error - get: - summary: Query voters - description: Query voters information by proposalId - produces: - - application/json - tags: - - ICS22 - parameters: - - type: string - description: proposal id - name: proposalId - required: true - in: path - responses: - 200: - description: OK - schema: - type: array - items: - "$ref": "#/definitions/Vote" - 400: - description: Invalid proposal id - 500: - description: Internal Server Error - /gov/proposals/{proposalId}: - get: - summary: Query a proposal - description: Query a proposal by id - produces: - - application/json - tags: - - ICS22 - parameters: - - type: string - name: proposalId - required: true - in: path - responses: - 200: - description: OK - schema: - "$ref": "#/definitions/TextProposal" - 400: - description: Invalid proposal id - 500: - description: Internal Server Error /gov/proposals/{proposalId}/deposits/{depositor}: get: summary: Query deposit @@ -1411,6 +1380,71 @@ paths: description: Found no deposit 500: description: Internal Server Error + /gov/proposals/{proposalId}/votes: + get: + summary: Query voters + description: Query voters information by proposalId + produces: + - application/json + tags: + - ICS22 + parameters: + - type: string + description: proposal id + name: proposalId + required: true + in: path + responses: + 200: + description: OK + schema: + type: array + items: + $ref: "#/definitions/Vote" + 400: + description: Invalid proposal id + 500: + description: Internal Server Error + post: + summary: Vote a proposal + description: Send transaction to vote a proposal + consumes: + - application/json + produces: + - application/json + tags: + - ICS22 + parameters: + - type: string + description: proposal id + name: proposalId + required: true + in: path + - description: valid value of `"option"` field can be `"yes"`, `"no"`, `"no_with_veto"` and `"abstain"` + name: post_vote_body + in: body + required: true + schema: + type: object + properties: + base_req: + $ref: "#/definitions/BaseReq" + voter: + $ref: "#/definitions/Address" + option: + type: string + example: "yes" + responses: + 200: + description: OK + schema: + $ref: "#/definitions/BroadcastTxCommitResult" + 400: + description: Invalid proposal id or vote body + 401: + description: Key password is wrong + 500: + description: Internal Server Error /gov/proposals/{proposalId}/votes/{voter}: get: summary: Query vote @@ -1441,6 +1475,29 @@ paths: description: Found no vote 500: description: Internal Server Error + /gov/proposals/{proposalId}/tally: + get: + summary: Get a proposal's tally result at the current time + description: Gets a proposal's tally result at the current time. If the proposal is pending deposits (i.e status 'DepositPeriod') it returns an empty tally result. + produces: + - application/json + tags: + - ICS22 + parameters: + - type: string + description: proposal id + name: proposalId + required: true + in: path + responses: + 200: + description: OK + schema: + $ref: "#/definitions/TallyResult" + 400: + description: Invalid proposal id + 500: + description: Internal Server Error /gov/parameters/deposit: get: summary: Query governance deposit parameters @@ -1538,7 +1595,7 @@ definitions: tags: type: array items: - "$ref": "#/definitions/KVPair" + $ref: "#/definitions/KVPair" example: code: 0 data: data @@ -1567,7 +1624,7 @@ definitions: tags: type: array items: - "$ref": "#/definitions/KVPair" + $ref: "#/definitions/KVPair" example: code: 5 data: data @@ -1868,7 +1925,7 @@ definitions: total_deposit: type: array items: - "$ref": "#/definitions/Coin" + $ref: "#/definitions/Coin" voting_start_time: type: string Deposit: @@ -1877,11 +1934,11 @@ definitions: amount: type: array items: - "$ref": "#/definitions/Coin" + $ref: "#/definitions/Coin" proposal_id: type: integer depositor: - "$ref": "#/definitions/Address" + $ref: "#/definitions/Address" TallyResult: type: object properties: diff --git a/client/utils/rest.go b/client/utils/rest.go index 36ff05af8..5917455ee 100644 --- a/client/utils/rest.go +++ b/client/utils/rest.go @@ -159,21 +159,21 @@ func ReadRESTReq(w http.ResponseWriter, r *http.Request, cdc *codec.Codec, req i // ValidateBasic performs basic validation of a BaseReq. If custom validation // logic is needed, the implementing request handler should perform those // checks manually. -func (br BaseReq) ValidateBasic(w http.ResponseWriter) bool { - switch { - case len(br.Name) == 0: +func (br BaseReq) ValidateBasic(w http.ResponseWriter, cliCtx context.CLIContext) bool { + if !cliCtx.GenerateOnly && !cliCtx.Simulate { + switch { + case len(br.Password) == 0: + WriteErrorResponse(w, http.StatusUnauthorized, "password required but not specified") + return false + case len(br.ChainID) == 0: + WriteErrorResponse(w, http.StatusUnauthorized, "chain-id required but not specified") + return false + } + } + if len(br.Name) == 0 { WriteErrorResponse(w, http.StatusUnauthorized, "name required but not specified") return false - - case len(br.Password) == 0: - WriteErrorResponse(w, http.StatusUnauthorized, "password required but not specified") - return false - - case len(br.ChainID) == 0: - WriteErrorResponse(w, http.StatusUnauthorized, "chainID required but not specified") - return false } - return true } diff --git a/client/utils/utils.go b/client/utils/utils.go index 08a538eec..6fde3ce6b 100644 --- a/client/utils/utils.go +++ b/client/utils/utils.go @@ -34,14 +34,14 @@ func CompleteAndBroadcastTxCli(txBldr authtxb.TxBuilder, cliCtx context.CLIConte return err } - if txBldr.SimulateGas || cliCtx.DryRun { + if txBldr.SimulateGas || cliCtx.Simulate { txBldr, err = EnrichCtxWithGas(txBldr, cliCtx, name, msgs) if err != nil { return err } fmt.Fprintf(os.Stderr, "estimated gas = %v\n", txBldr.Gas) } - if cliCtx.DryRun { + if cliCtx.Simulate { return nil } diff --git a/x/bank/client/rest/sendtx.go b/x/bank/client/rest/sendtx.go index 7bb2640fd..27cbc043c 100644 --- a/x/bank/client/rest/sendtx.go +++ b/x/bank/client/rest/sendtx.go @@ -49,8 +49,11 @@ func SendRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIC return } + cliCtx = cliCtx.WithGenerateOnly(req.BaseReq.GenerateOnly) + cliCtx = cliCtx.WithSimulation(req.BaseReq.Simulate) + baseReq := req.BaseReq.Sanitize() - if !baseReq.ValidateBasic(w) { + if !baseReq.ValidateBasic(w, cliCtx) { return } diff --git a/x/gov/client/rest/rest.go b/x/gov/client/rest/rest.go index 53deffbbe..821da0cc7 100644 --- a/x/gov/client/rest/rest.go +++ b/x/gov/client/rest/rest.go @@ -78,8 +78,11 @@ func postProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Han return } + cliCtx = cliCtx.WithGenerateOnly(req.BaseReq.GenerateOnly) + cliCtx = cliCtx.WithSimulation(req.BaseReq.Simulate) + baseReq := req.BaseReq.Sanitize() - if !baseReq.ValidateBasic(w) { + if !baseReq.ValidateBasic(w, cliCtx) { return } @@ -123,8 +126,11 @@ func depositHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerF return } + cliCtx = cliCtx.WithGenerateOnly(req.BaseReq.GenerateOnly) + cliCtx = cliCtx.WithSimulation(req.BaseReq.Simulate) + baseReq := req.BaseReq.Sanitize() - if !baseReq.ValidateBasic(w) { + if !baseReq.ValidateBasic(w, cliCtx) { return } @@ -162,8 +168,11 @@ func voteHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc return } + cliCtx = cliCtx.WithGenerateOnly(req.BaseReq.GenerateOnly) + cliCtx = cliCtx.WithSimulation(req.BaseReq.Simulate) + baseReq := req.BaseReq.Sanitize() - if !baseReq.ValidateBasic(w) { + if !baseReq.ValidateBasic(w, cliCtx) { return } diff --git a/x/ibc/client/rest/transfer.go b/x/ibc/client/rest/transfer.go index 19c921971..704b663e6 100644 --- a/x/ibc/client/rest/transfer.go +++ b/x/ibc/client/rest/transfer.go @@ -43,8 +43,11 @@ func TransferRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context. return } + cliCtx = cliCtx.WithGenerateOnly(req.BaseReq.GenerateOnly) + cliCtx = cliCtx.WithSimulation(req.BaseReq.Simulate) + baseReq := req.BaseReq.Sanitize() - if !baseReq.ValidateBasic(w) { + if !baseReq.ValidateBasic(w, cliCtx) { return } diff --git a/x/slashing/client/rest/tx.go b/x/slashing/client/rest/tx.go index 5f33a1210..ec28f48ed 100644 --- a/x/slashing/client/rest/tx.go +++ b/x/slashing/client/rest/tx.go @@ -38,8 +38,11 @@ func unjailRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CL return } + cliCtx = cliCtx.WithGenerateOnly(req.BaseReq.GenerateOnly) + cliCtx = cliCtx.WithSimulation(req.BaseReq.Simulate) + baseReq := req.BaseReq.Sanitize() - if !baseReq.ValidateBasic(w) { + if !baseReq.ValidateBasic(w, cliCtx) { return } diff --git a/x/stake/client/rest/tx.go b/x/stake/client/rest/tx.go index 5deb5b53c..bb2bc0e7f 100644 --- a/x/stake/client/rest/tx.go +++ b/x/stake/client/rest/tx.go @@ -2,81 +2,72 @@ package rest import ( "bytes" - "io/ioutil" "net/http" - "github.com/cosmos/cosmos-sdk/client" "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/crypto/keys" 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/gorilla/mux" - - ctypes "github.com/tendermint/tendermint/rpc/core/types" ) func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, kb keys.Keybase) { r.HandleFunc( "/stake/delegators/{delegatorAddr}/delegations", - delegationsRequestHandlerFn(cdc, kb, cliCtx), + postDelegationsHandlerFn(cdc, kb, cliCtx), + ).Methods("POST") + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/unbonding_delegations", + postUnbondingDelegationsHandlerFn(cdc, kb, cliCtx), + ).Methods("POST") + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/redelegations", + postRedelegationsHandlerFn(cdc, kb, cliCtx), ).Methods("POST") } type ( msgDelegationsInput struct { - DelegatorAddr string `json:"delegator_addr"` // in bech32 - ValidatorAddr string `json:"validator_addr"` // in bech32 - Delegation sdk.Coin `json:"delegation"` + BaseReq utils.BaseReq `json:"base_req"` + DelegatorAddr sdk.AccAddress `json:"delegator_addr"` // in bech32 + ValidatorAddr sdk.ValAddress `json:"validator_addr"` // in bech32 + Delegation sdk.Coin `json:"delegation"` } msgBeginRedelegateInput struct { - DelegatorAddr string `json:"delegator_addr"` // in bech32 - ValidatorSrcAddr string `json:"validator_src_addr"` // in bech32 - ValidatorDstAddr string `json:"validator_dst_addr"` // in bech32 - SharesAmount string `json:"shares"` + BaseReq utils.BaseReq `json:"base_req"` + DelegatorAddr sdk.AccAddress `json:"delegator_addr"` // in bech32 + ValidatorSrcAddr sdk.ValAddress `json:"validator_src_addr"` // in bech32 + ValidatorDstAddr sdk.ValAddress `json:"validator_dst_addr"` // in bech32 + SharesAmount sdk.Dec `json:"shares"` } msgBeginUnbondingInput struct { - DelegatorAddr string `json:"delegator_addr"` // in bech32 - ValidatorAddr string `json:"validator_addr"` // in bech32 - SharesAmount string `json:"shares"` - } - - // the request body for edit delegations - EditDelegationsReq struct { - BaseReq utils.BaseReq `json:"base_req"` - Delegations []msgDelegationsInput `json:"delegations"` - BeginUnbondings []msgBeginUnbondingInput `json:"begin_unbondings"` - BeginRedelegates []msgBeginRedelegateInput `json:"begin_redelegates"` + BaseReq utils.BaseReq `json:"base_req"` + DelegatorAddr sdk.AccAddress `json:"delegator_addr"` // in bech32 + ValidatorAddr sdk.ValAddress `json:"validator_addr"` // in bech32 + SharesAmount sdk.Dec `json:"shares"` } ) -// TODO: Split this up into several smaller functions, and remove the above nolint -// TODO: use sdk.ValAddress instead of sdk.AccAddress for validators in messages -// TODO: Seriously consider how to refactor...do we need to make it multiple txs? -// If not, we can just use CompleteAndBroadcastTxREST. -func delegationsRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { +func postDelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req EditDelegationsReq + var req msgDelegationsInput - body, err := ioutil.ReadAll(r.Body) + err := utils.ReadRESTReq(w, r, cdc, &req) if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - err = cdc.UnmarshalJSON(body, &req) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } + cliCtx = cliCtx.WithGenerateOnly(req.BaseReq.GenerateOnly) + cliCtx = cliCtx.WithSimulation(req.BaseReq.Simulate) baseReq := req.BaseReq.Sanitize() - if !baseReq.ValidateBasic(w) { + if !baseReq.ValidateBasic(w, cliCtx) { return } @@ -86,182 +77,98 @@ func delegationsRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx conte return } - // build messages - messages := make([]sdk.Msg, len(req.Delegations)+ - len(req.BeginRedelegates)+ - len(req.BeginUnbondings)) - - i := 0 - for _, msg := range req.Delegations { - delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - if !bytes.Equal(info.GetPubKey().Address(), delAddr) { - utils.WriteErrorResponse(w, http.StatusUnauthorized, "Must use own delegator address") - return - } - - messages[i] = stake.MsgDelegate{ - DelegatorAddr: delAddr, - ValidatorAddr: valAddr, - Delegation: msg.Delegation, - } - - i++ + if !bytes.Equal(info.GetPubKey().Address(), req.DelegatorAddr) { + utils.WriteErrorResponse(w, http.StatusUnauthorized, "Must use own delegator address") + return } - for _, msg := range req.BeginRedelegates { - delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - if !bytes.Equal(info.GetPubKey().Address(), delAddr) { - utils.WriteErrorResponse(w, http.StatusUnauthorized, "Must use own delegator address") - return - } - - valSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - valDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - shares, err := sdk.NewDecFromStr(msg.SharesAmount) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - messages[i] = stake.MsgBeginRedelegate{ - DelegatorAddr: delAddr, - ValidatorSrcAddr: valSrcAddr, - ValidatorDstAddr: valDstAddr, - SharesAmount: shares, - } - - i++ - } - - for _, msg := range req.BeginUnbondings { - delAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - if !bytes.Equal(info.GetPubKey().Address(), delAddr) { - utils.WriteErrorResponse(w, http.StatusUnauthorized, "Must use own delegator address") - return - } - - valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - shares, err := sdk.NewDecFromStr(msg.SharesAmount) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - messages[i] = stake.MsgBeginUnbonding{ - DelegatorAddr: delAddr, - ValidatorAddr: valAddr, - SharesAmount: shares, - } - - i++ - } - - simulateGas, gas, err := client.ReadGasFlag(baseReq.Gas) + msg := stake.NewMsgDelegate(req.DelegatorAddr, req.ValidatorAddr, req.Delegation) + err = msg.ValidateBasic() if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - adjustment, ok := utils.ParseFloat64OrReturnBadRequest(w, baseReq.GasAdjustment, client.DefaultGasAdjustment) - if !ok { + utils.CompleteAndBroadcastTxREST(w, r, cliCtx, baseReq, []sdk.Msg{msg}, cdc) + } +} + +func postRedelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req msgBeginRedelegateInput + + err := utils.ReadRESTReq(w, r, cdc, &req) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - txBldr := authtxb.TxBuilder{ - Codec: cdc, - Gas: gas, - GasAdjustment: adjustment, - SimulateGas: simulateGas, - ChainID: baseReq.ChainID, + cliCtx = cliCtx.WithGenerateOnly(req.BaseReq.GenerateOnly) + cliCtx = cliCtx.WithSimulation(req.BaseReq.Simulate) + + baseReq := req.BaseReq.Sanitize() + if !baseReq.ValidateBasic(w, cliCtx) { + return } - // sign messages - signedTxs := make([][]byte, len(messages[:])) - for i, msg := range messages { - // increment sequence for each message - txBldr = txBldr.WithAccountNumber(baseReq.AccountNumber) - txBldr = txBldr.WithSequence(baseReq.Sequence) - - baseReq.Sequence++ - - if baseReq.Simulate || txBldr.SimulateGas { - newBldr, err := utils.EnrichCtxWithGas(txBldr, cliCtx, baseReq.Name, []sdk.Msg{msg}) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - if baseReq.Simulate { - utils.WriteSimulationResponse(w, newBldr.Gas) - return - } - - txBldr = newBldr - } - - if baseReq.GenerateOnly { - utils.WriteGenerateStdTxResponse(w, txBldr, []sdk.Msg{msg}) - return - } - - txBytes, err := txBldr.BuildAndSign(baseReq.Name, baseReq.Password, []sdk.Msg{msg}) - if err != nil { - utils.WriteErrorResponse(w, http.StatusUnauthorized, err.Error()) - return - } - - signedTxs[i] = txBytes + info, err := kb.Get(baseReq.Name) + if err != nil { + utils.WriteErrorResponse(w, http.StatusUnauthorized, err.Error()) + return } - // send - // XXX the operation might not be atomic if a tx fails - // should we have a sdk.MultiMsg type to make sending atomic? - results := make([]*ctypes.ResultBroadcastTxCommit, len(signedTxs[:])) - for i, txBytes := range signedTxs { - res, err := cliCtx.BroadcastTx(txBytes) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - results[i] = res + if !bytes.Equal(info.GetPubKey().Address(), req.DelegatorAddr) { + utils.WriteErrorResponse(w, http.StatusUnauthorized, "Must use own delegator address") + return } - utils.PostProcessResponse(w, cdc, results, cliCtx.Indent) + msg := stake.NewMsgBeginRedelegate(req.DelegatorAddr, req.ValidatorSrcAddr, req.ValidatorDstAddr, req.SharesAmount) + err = msg.ValidateBasic() + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + utils.CompleteAndBroadcastTxREST(w, r, cliCtx, baseReq, []sdk.Msg{msg}, cdc) + } +} + +func postUnbondingDelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req msgBeginUnbondingInput + + err := utils.ReadRESTReq(w, r, cdc, &req) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + cliCtx = cliCtx.WithGenerateOnly(req.BaseReq.GenerateOnly) + cliCtx = cliCtx.WithSimulation(req.BaseReq.Simulate) + + baseReq := req.BaseReq.Sanitize() + if !baseReq.ValidateBasic(w, cliCtx) { + return + } + + info, err := kb.Get(baseReq.Name) + if err != nil { + utils.WriteErrorResponse(w, http.StatusUnauthorized, err.Error()) + return + } + + if !bytes.Equal(info.GetPubKey().Address(), req.DelegatorAddr) { + utils.WriteErrorResponse(w, http.StatusUnauthorized, "Must use own delegator address") + return + } + + msg := stake.NewMsgBeginUnbonding(req.DelegatorAddr, req.ValidatorAddr, req.SharesAmount) + err = msg.ValidateBasic() + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + utils.CompleteAndBroadcastTxREST(w, r, cliCtx, baseReq, []sdk.Msg{msg}, cdc) } } From e54e0465e294a0e729edbc0529af05d8f836358f Mon Sep 17 00:00:00 2001 From: Christopher Goes Date: Tue, 11 Dec 2018 15:49:19 +0100 Subject: [PATCH 21/21] Merge PR #3080: Run fewer blocks on CI multi-seed simulation --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index c194aa84f..d866bd637 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -178,7 +178,7 @@ jobs: name: Test multi-seed Gaia simulation command: | export PATH="$GOBIN:$PATH" - make test_sim_gaia_multi_seed + scripts/multisim.sh 25 TestFullGaiaSimulation test_cover: <<: *defaults