From 8ac32547c79720654a92e9523e9adc8bb0d296ac Mon Sep 17 00:00:00 2001 From: chengsilei Date: Fri, 27 Jul 2018 17:49:49 +0800 Subject: [PATCH 01/52] Add new function for Router interface --- baseapp/router.go | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/baseapp/router.go b/baseapp/router.go index abbbf9e1217b..55417c69001e 100644 --- a/baseapp/router.go +++ b/baseapp/router.go @@ -8,13 +8,20 @@ import ( // Router provides handlers for each transaction type. type Router interface { - AddRoute(r string, h sdk.Handler) (rtr Router) + + //////////////////// iris/cosmos-sdk begin /////////////////////////// + AddRoute(r string, s *sdk.KVStoreKey, h sdk.Handler) (rtr Router) Route(path string) (h sdk.Handler) + RouteTable() (table []string) + //////////////////// iris/cosmos-sdk end /////////////////////////// } // map a transaction type to a handler and an initgenesis function type route struct { r string + //////////////////// iris/cosmos-sdk begin /////////////////////////// + s *sdk.KVStoreKey + //////////////////// iris/cosmos-sdk end /////////////////////////// h sdk.Handler } @@ -34,14 +41,16 @@ func NewRouter() *router { var isAlpha = regexp.MustCompile(`^[a-zA-Z]+$`).MatchString // AddRoute - TODO add description -func (rtr *router) AddRoute(r string, h sdk.Handler) Router { +//////////////////// iris/cosmos-sdk begin /////////////////////////// +func (rtr *router) AddRoute(r string, s *sdk.KVStoreKey, h sdk.Handler) Router { if !isAlpha(r) { panic("route expressions can only contain alphabet characters") } - rtr.routes = append(rtr.routes, route{r, h}) + rtr.routes = append(rtr.routes, route{r,s,h}) return rtr } +//////////////////// iris/cosmos-sdk end /////////////////////////// // Route - TODO add description // TODO handle expressive matches. @@ -53,3 +62,14 @@ func (rtr *router) Route(path string) (h sdk.Handler) { } return nil } + +//////////////////// iris/cosmos-sdk begin /////////////////////////// + +func (rtr *router) RouteTable() (table []string) { + for _, route := range rtr.routes { + table = append(table, route.r + "/" + route.s.String()) + } + return +} + +//////////////////// iris/cosmos-sdk end /////////////////////////// \ No newline at end of file From 73e444cfb0d5c960c28c54de053a3c792c8964e5 Mon Sep 17 00:00:00 2001 From: chengsilei Date: Mon, 30 Jul 2018 10:45:53 +0800 Subject: [PATCH 02/52] fix test error --- x/gov/test_common.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 5567e4697a7f..bbf9a401ed71 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -30,7 +30,7 @@ func getMockApp(t *testing.T, numGenAccs int) (*mock.App, Keeper, stake.Keeper, ck := bank.NewKeeper(mapp.AccountMapper) sk := stake.NewKeeper(mapp.Cdc, keyStake, ck, mapp.RegisterCodespace(stake.DefaultCodespace)) keeper := NewKeeper(mapp.Cdc, keyGov, ck, sk, DefaultCodespace) - mapp.Router().AddRoute("gov", NewHandler(keeper)) + mapp.Router().AddRoute("gov", keyGov, NewHandler(keeper)) require.NoError(t, mapp.CompleteSetup([]*sdk.KVStoreKey{keyStake, keyGov})) From a23b6003fe989aa25f9707d34279faa93e4e354c Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Tue, 31 Jul 2018 10:59:42 +0800 Subject: [PATCH 03/52] Complete the commitID calculation logic modification --- store/rootmultistore.go | 66 ++++++++++++++++++++++++++++++++++------- 1 file changed, 56 insertions(+), 10 deletions(-) diff --git a/store/rootmultistore.go b/store/rootmultistore.go index 255afffbd5a1..37049eede40e 100644 --- a/store/rootmultistore.go +++ b/store/rootmultistore.go @@ -432,20 +432,64 @@ func setLatestVersion(batch dbm.Batch, version int64) { batch.Set([]byte(latestVersionKey), latestBytes) } +// Commits each store and returns a new commitInfo. +//// Commits each store and returns a new commitInfo. +//func commitStores(version int64, storeMap map[StoreKey]CommitStore) commitInfo { +// storeInfos := make([]storeInfo, 0, len(storeMap)) +// +// for key, store := range storeMap { +// // Commit +// commitID := store.Commit() +// +// // Record CommitID +// si := storeInfo{} +// si.Name = key.Name() +// si.Core.CommitID = commitID +// // si.Core.StoreType = store.GetStoreType() +// storeInfos = append(storeInfos, si) +// } +// +// ci := commitInfo{ +// Version: version, +// StoreInfos: storeInfos, +// } +// return ci +//} + +//////////////////// iris/cosmos-sdk begin/////////////////////////// // Commits each store and returns a new commitInfo. func commitStores(version int64, storeMap map[StoreKey]CommitStore) commitInfo { - storeInfos := make([]storeInfo, 0, len(storeMap)) - for key, store := range storeMap { - // Commit - commitID := store.Commit() + storemap := make(map[string]CommitStore) + + fmt.Println("CommitStores!!!!!!") + for key,store:= range storeMap{ + fmt.Println(key) + storemap[key.Name()] = store + } + + upgradeStore:=storemap["upgrade"].(KVStore) + bz:= upgradeStore.Get([]byte("k/"))//CurrentStoreKey + storekeys := string(bz) //splitby":" + + storekeyslist := strings.Split(storekeys, ":") + fmt.Println(storekeyslist) - // Record CommitID - si := storeInfo{} - si.Name = key.Name() - si.Core.CommitID = commitID - // si.Core.StoreType = store.GetStoreType() - storeInfos = append(storeInfos, si) + storeInfos := make([]storeInfo, 0, len(storekeyslist)) + + for _, key := range storekeyslist { + + if store,ok:= storemap[key]; ok{ + // Commit + commitID := store.Commit() + + // Record CommitID + si := storeInfo{} + si.Name = key + si.Core.CommitID = commitID + // si.Core.StoreType = store.GetStoreType() + storeInfos = append(storeInfos, si) + } } ci := commitInfo{ @@ -454,6 +498,8 @@ func commitStores(version int64, storeMap map[StoreKey]CommitStore) commitInfo { } return ci } +//////////////////// iris/cosmos-sdk end/////////////////////////// + // Gets commitInfo from disk. func getCommitInfo(db dbm.DB, ver int64) (commitInfo, error) { From dd494a6fe4937af24c73dbe0022e20a1d839953c Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Tue, 31 Jul 2018 15:30:16 +0800 Subject: [PATCH 04/52] add Paramstores --- x/params/keeper.go | 405 ++++++++++++++++++++++++++++++++++++++++ x/params/keeper_test.go | 280 +++++++++++++++++++++++++++ x/params/msg_status.go | 36 ++++ 3 files changed, 721 insertions(+) create mode 100644 x/params/keeper.go create mode 100644 x/params/keeper_test.go create mode 100644 x/params/msg_status.go diff --git a/x/params/keeper.go b/x/params/keeper.go new file mode 100644 index 000000000000..8817b7c6c8de --- /dev/null +++ b/x/params/keeper.go @@ -0,0 +1,405 @@ +package params + +import ( + "fmt" + "reflect" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/wire" +) + +// Keeper manages global parameter store +type Keeper struct { + cdc *wire.Codec + key sdk.StoreKey +} + +// NewKeeper constructs a new Keeper +func NewKeeper(cdc *wire.Codec, key sdk.StoreKey) Keeper { + return Keeper{ + cdc: cdc, + key: key, + } +} + +// InitKeeper constructs a new Keeper with initial parameters +func InitKeeper(ctx sdk.Context, cdc *wire.Codec, key sdk.StoreKey, params ...interface{}) Keeper { + if len(params)%2 != 0 { + panic("Odd params list length for InitKeeper") + } + + k := NewKeeper(cdc, key) + + for i := 0; i < len(params); i += 2 { + k.set(ctx, params[i].(string), params[i+1]) + } + + return k +} + +// get automatically unmarshalls parameter to pointer +func (k Keeper) get(ctx sdk.Context, key string, ptr interface{}) error { + store := ctx.KVStore(k.key) + bz := store.Get([]byte(key)) + return k.cdc.UnmarshalBinary(bz, ptr) +} + +// getRaw returns raw byte slice +func (k Keeper) getRaw(ctx sdk.Context, key string) []byte { + store := ctx.KVStore(k.key) + return store.Get([]byte(key)) +} + +// set automatically marshalls and type check parameter +func (k Keeper) set(ctx sdk.Context, key string, param interface{}) error { + store := ctx.KVStore(k.key) + bz := store.Get([]byte(key)) + if bz != nil { + ptrty := reflect.PtrTo(reflect.TypeOf(param)) + ptr := reflect.New(ptrty).Interface() + + if k.cdc.UnmarshalBinary(bz, ptr) != nil { + return fmt.Errorf("Type mismatch with stored param and provided param") + } + } + + bz, err := k.cdc.MarshalBinary(param) + if err != nil { + return err + } + store.Set([]byte(key), bz) + + return nil +} + +// setRaw sets raw byte slice +func (k Keeper) setRaw(ctx sdk.Context, key string, param []byte) { + store := ctx.KVStore(k.key) + store.Set([]byte(key), param) +} + +// Getter returns readonly struct +func (k Keeper) Getter() Getter { + return Getter{k} +} + +// Setter returns read/write struct +func (k Keeper) Setter() Setter { + return Setter{Getter{k}} +} + +// Getter exposes methods related with only getting params +type Getter struct { + k Keeper +} + +// Get exposes get +func (k Getter) Get(ctx sdk.Context, key string, ptr interface{}) error { + return k.k.get(ctx, key, ptr) +} + +// GetRaw exposes getRaw +func (k Getter) GetRaw(ctx sdk.Context, key string) []byte { + return k.k.getRaw(ctx, key) +} + +// GetString is helper function for string params +func (k Getter) GetString(ctx sdk.Context, key string) (res string, err error) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + err = k.k.cdc.UnmarshalBinary(bz, &res) + return +} + +// GetBool is helper function for bool params +func (k Getter) GetBool(ctx sdk.Context, key string) (res bool, err error) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + err = k.k.cdc.UnmarshalBinary(bz, &res) + return +} + +// GetInt16 is helper function for int16 params +func (k Getter) GetInt16(ctx sdk.Context, key string) (res int16, err error) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + err = k.k.cdc.UnmarshalBinary(bz, &res) + return +} + +// GetInt32 is helper function for int32 params +func (k Getter) GetInt32(ctx sdk.Context, key string) (res int32, err error) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + err = k.k.cdc.UnmarshalBinary(bz, &res) + return +} + +// GetInt64 is helper function for int64 params +func (k Getter) GetInt64(ctx sdk.Context, key string) (res int64, err error) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + err = k.k.cdc.UnmarshalBinary(bz, &res) + return +} + +// GetUint16 is helper function for uint16 params +func (k Getter) GetUint16(ctx sdk.Context, key string) (res uint16, err error) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + err = k.k.cdc.UnmarshalBinary(bz, &res) + return +} + +// GetUint32 is helper function for uint32 params +func (k Getter) GetUint32(ctx sdk.Context, key string) (res uint32, err error) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + err = k.k.cdc.UnmarshalBinary(bz, &res) + return +} + +// GetUint64 is helper function for uint64 params +func (k Getter) GetUint64(ctx sdk.Context, key string) (res uint64, err error) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + err = k.k.cdc.UnmarshalBinary(bz, &res) + return +} + +// GetInt is helper function for sdk.Int params +func (k Getter) GetInt(ctx sdk.Context, key string) (res sdk.Int, err error) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + err = k.k.cdc.UnmarshalBinary(bz, &res) + return +} + +// GetUint is helper function for sdk.Uint params +func (k Getter) GetUint(ctx sdk.Context, key string) (res sdk.Uint, err error) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + err = k.k.cdc.UnmarshalBinary(bz, &res) + return +} + +// GetRat is helper function for rat params +func (k Getter) GetRat(ctx sdk.Context, key string) (res sdk.Rat, err error) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + err = k.k.cdc.UnmarshalBinary(bz, &res) + return +} + +// GetStringWithDefault is helper function for string params with default value +func (k Getter) GetStringWithDefault(ctx sdk.Context, key string, def string) (res string) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + if bz == nil { + return def + } + k.k.cdc.MustUnmarshalBinary(bz, &res) + return +} + +// GetBoolWithDefault is helper function for bool params with default value +func (k Getter) GetBoolWithDefault(ctx sdk.Context, key string, def bool) (res bool) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + if bz == nil { + return def + } + k.k.cdc.MustUnmarshalBinary(bz, &res) + return +} + +// GetInt16WithDefault is helper function for int16 params with default value +func (k Getter) GetInt16WithDefault(ctx sdk.Context, key string, def int16) (res int16) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + if bz == nil { + return def + } + k.k.cdc.MustUnmarshalBinary(bz, &res) + return +} + +// GetInt32WithDefault is helper function for int32 params with default value +func (k Getter) GetInt32WithDefault(ctx sdk.Context, key string, def int32) (res int32) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + if bz == nil { + return def + } + k.k.cdc.MustUnmarshalBinary(bz, &res) + return +} + +// GetInt64WithDefault is helper function for int64 params with default value +func (k Getter) GetInt64WithDefault(ctx sdk.Context, key string, def int64) (res int64) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + if bz == nil { + return def + } + k.k.cdc.MustUnmarshalBinary(bz, &res) + return +} + +// GetUint16WithDefault is helper function for uint16 params with default value +func (k Getter) GetUint16WithDefault(ctx sdk.Context, key string, def uint16) (res uint16) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + if bz == nil { + return def + } + k.k.cdc.MustUnmarshalBinary(bz, &res) + return +} + +// GetUint32WithDefault is helper function for uint32 params with default value +func (k Getter) GetUint32WithDefault(ctx sdk.Context, key string, def uint32) (res uint32) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + if bz == nil { + return def + } + k.k.cdc.MustUnmarshalBinary(bz, &res) + return +} + +// GetUint64WithDefault is helper function for uint64 params with default value +func (k Getter) GetUint64WithDefault(ctx sdk.Context, key string, def uint64) (res uint64) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + if bz == nil { + return def + } + k.k.cdc.MustUnmarshalBinary(bz, &res) + return +} + +// GetIntWithDefault is helper function for sdk.Int params with default value +func (k Getter) GetIntWithDefault(ctx sdk.Context, key string, def sdk.Int) (res sdk.Int) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + if bz == nil { + return def + } + k.k.cdc.MustUnmarshalBinary(bz, &res) + return +} + +// GetUintWithDefault is helper function for sdk.Uint params with default value +func (k Getter) GetUintWithDefault(ctx sdk.Context, key string, def sdk.Uint) (res sdk.Uint) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + if bz == nil { + return def + } + k.k.cdc.MustUnmarshalBinary(bz, &res) + return +} + +// GetRatWithDefault is helper function for sdk.Rat params with default value +func (k Getter) GetRatWithDefault(ctx sdk.Context, key string, def sdk.Rat) (res sdk.Rat) { + store := ctx.KVStore(k.k.key) + bz := store.Get([]byte(key)) + if bz == nil { + return def + } + k.k.cdc.MustUnmarshalBinary(bz, &res) + return +} + +// Setter exposes all methods including Set +type Setter struct { + Getter +} + +// Set exposes set +func (k Setter) Set(ctx sdk.Context, key string, param interface{}) error { + return k.k.set(ctx, key, param) +} + +// SetRaw exposes setRaw +func (k Setter) SetRaw(ctx sdk.Context, key string, param []byte) { + k.k.setRaw(ctx, key, param) +} + +// SetString is helper function for string params +func (k Setter) SetString(ctx sdk.Context, key string, param string) { + if err := k.k.set(ctx, key, param); err != nil { + panic(err) + } +} + +// SetBool is helper function for bool params +func (k Setter) SetBool(ctx sdk.Context, key string, param bool) { + if err := k.k.set(ctx, key, param); err != nil { + panic(err) + } +} + +// SetInt16 is helper function for int16 params +func (k Setter) SetInt16(ctx sdk.Context, key string, param int16) { + if err := k.k.set(ctx, key, param); err != nil { + panic(err) + } +} + +// SetInt32 is helper function for int32 params +func (k Setter) SetInt32(ctx sdk.Context, key string, param int32) { + if err := k.k.set(ctx, key, param); err != nil { + panic(err) + } +} + +// SetInt64 is helper function for int64 params +func (k Setter) SetInt64(ctx sdk.Context, key string, param int64) { + if err := k.k.set(ctx, key, param); err != nil { + panic(err) + } +} + +// SetUint16 is helper function for uint16 params +func (k Setter) SetUint16(ctx sdk.Context, key string, param uint16) { + if err := k.k.set(ctx, key, param); err != nil { + panic(err) + } +} + +// SetUint32 is helper function for uint32 params +func (k Setter) SetUint32(ctx sdk.Context, key string, param uint32) { + if err := k.k.set(ctx, key, param); err != nil { + panic(err) + } +} + +// SetUint64 is helper function for uint64 params +func (k Setter) SetUint64(ctx sdk.Context, key string, param uint64) { + if err := k.k.set(ctx, key, param); err != nil { + panic(err) + } +} + +// SetInt is helper function for sdk.Int params +func (k Setter) SetInt(ctx sdk.Context, key string, param sdk.Int) { + if err := k.k.set(ctx, key, param); err != nil { + panic(err) + } +} + +// SetUint is helper function for sdk.Uint params +func (k Setter) SetUint(ctx sdk.Context, key string, param sdk.Uint) { + if err := k.k.set(ctx, key, param); err != nil { + panic(err) + } +} + +// SetRat is helper function for rat params +func (k Setter) SetRat(ctx sdk.Context, key string, param sdk.Rat) { + if err := k.k.set(ctx, key, param); err != nil { + panic(err) + } +} diff --git a/x/params/keeper_test.go b/x/params/keeper_test.go new file mode 100644 index 000000000000..4bb5744ea458 --- /dev/null +++ b/x/params/keeper_test.go @@ -0,0 +1,280 @@ +package params + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + abci "github.com/tendermint/tendermint/abci/types" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" + + "github.com/cosmos/cosmos-sdk/store" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/wire" +) + +func defaultContext(key sdk.StoreKey) sdk.Context { + db := dbm.NewMemDB() + cms := store.NewCommitMultiStore(db) + cms.MountStoreWithDB(key, sdk.StoreTypeIAVL, db) + cms.LoadLatestVersion() + ctx := sdk.NewContext(cms, abci.Header{}, false, log.NewNopLogger()) + return ctx +} + +func TestKeeper(t *testing.T) { + kvs := []struct { + key string + param int64 + }{ + {"key1", 10}, + {"key2", 55}, + {"key3", 182}, + {"key4", 17582}, + {"key5", 2768554}, + } + + skey := sdk.NewKVStoreKey("test") + ctx := defaultContext(skey) + setter := NewKeeper(wire.NewCodec(), skey).Setter() + + for _, kv := range kvs { + err := setter.Set(ctx, kv.key, kv.param) + assert.Nil(t, err) + } + + for _, kv := range kvs { + var param int64 + err := setter.Get(ctx, kv.key, ¶m) + assert.Nil(t, err) + assert.Equal(t, kv.param, param) + } + + cdc := wire.NewCodec() + for _, kv := range kvs { + var param int64 + bz := setter.GetRaw(ctx, kv.key) + err := cdc.UnmarshalBinary(bz, ¶m) + assert.Nil(t, err) + assert.Equal(t, kv.param, param) + } + + for _, kv := range kvs { + var param bool + err := setter.Get(ctx, kv.key, ¶m) + assert.NotNil(t, err) + } + + for _, kv := range kvs { + err := setter.Set(ctx, kv.key, true) + assert.NotNil(t, err) + } +} + +func TestGetter(t *testing.T) { + key := sdk.NewKVStoreKey("test") + ctx := defaultContext(key) + keeper := NewKeeper(wire.NewCodec(), key) + + g := keeper.Getter() + s := keeper.Setter() + + kvs := []struct { + key string + param interface{} + }{ + {"string", "test"}, + {"bool", true}, + {"int16", int16(1)}, + {"int32", int32(1)}, + {"int64", int64(1)}, + {"uint16", uint16(1)}, + {"uint32", uint32(1)}, + {"uint64", uint64(1)}, + {"int", sdk.NewInt(1)}, + {"uint", sdk.NewUint(1)}, + {"rat", sdk.NewRat(1)}, + } + + assert.NotPanics(t, func() { s.SetString(ctx, kvs[0].key, "test") }) + assert.NotPanics(t, func() { s.SetBool(ctx, kvs[1].key, true) }) + assert.NotPanics(t, func() { s.SetInt16(ctx, kvs[2].key, int16(1)) }) + assert.NotPanics(t, func() { s.SetInt32(ctx, kvs[3].key, int32(1)) }) + assert.NotPanics(t, func() { s.SetInt64(ctx, kvs[4].key, int64(1)) }) + assert.NotPanics(t, func() { s.SetUint16(ctx, kvs[5].key, uint16(1)) }) + assert.NotPanics(t, func() { s.SetUint32(ctx, kvs[6].key, uint32(1)) }) + assert.NotPanics(t, func() { s.SetUint64(ctx, kvs[7].key, uint64(1)) }) + assert.NotPanics(t, func() { s.SetInt(ctx, kvs[8].key, sdk.NewInt(1)) }) + assert.NotPanics(t, func() { s.SetUint(ctx, kvs[9].key, sdk.NewUint(1)) }) + assert.NotPanics(t, func() { s.SetRat(ctx, kvs[10].key, sdk.NewRat(1)) }) + + var res interface{} + var err error + + // String + def0 := "default" + res, err = g.GetString(ctx, kvs[0].key) + assert.Nil(t, err) + assert.Equal(t, kvs[0].param, res) + + _, err = g.GetString(ctx, "invalid") + assert.NotNil(t, err) + + res = g.GetStringWithDefault(ctx, kvs[0].key, def0) + assert.Equal(t, kvs[0].param, res) + + res = g.GetStringWithDefault(ctx, "invalid", def0) + assert.Equal(t, def0, res) + + // Bool + def1 := false + res, err = g.GetBool(ctx, kvs[1].key) + assert.Nil(t, err) + assert.Equal(t, kvs[1].param, res) + + _, err = g.GetBool(ctx, "invalid") + assert.NotNil(t, err) + + res = g.GetBoolWithDefault(ctx, kvs[1].key, def1) + assert.Equal(t, kvs[1].param, res) + + res = g.GetBoolWithDefault(ctx, "invalid", def1) + assert.Equal(t, def1, res) + + // Int16 + def2 := int16(0) + res, err = g.GetInt16(ctx, kvs[2].key) + assert.Nil(t, err) + assert.Equal(t, kvs[2].param, res) + + _, err = g.GetInt16(ctx, "invalid") + assert.NotNil(t, err) + + res = g.GetInt16WithDefault(ctx, kvs[2].key, def2) + assert.Equal(t, kvs[2].param, res) + + res = g.GetInt16WithDefault(ctx, "invalid", def2) + assert.Equal(t, def2, res) + + // Int32 + def3 := int32(0) + res, err = g.GetInt32(ctx, kvs[3].key) + assert.Nil(t, err) + assert.Equal(t, kvs[3].param, res) + + _, err = g.GetInt32(ctx, "invalid") + assert.NotNil(t, err) + + res = g.GetInt32WithDefault(ctx, kvs[3].key, def3) + assert.Equal(t, kvs[3].param, res) + + res = g.GetInt32WithDefault(ctx, "invalid", def3) + assert.Equal(t, def3, res) + + // Int64 + def4 := int64(0) + res, err = g.GetInt64(ctx, kvs[4].key) + assert.Nil(t, err) + assert.Equal(t, kvs[4].param, res) + + _, err = g.GetInt64(ctx, "invalid") + assert.NotNil(t, err) + + res = g.GetInt64WithDefault(ctx, kvs[4].key, def4) + assert.Equal(t, kvs[4].param, res) + + res = g.GetInt64WithDefault(ctx, "invalid", def4) + assert.Equal(t, def4, res) + + // Uint16 + def5 := uint16(0) + res, err = g.GetUint16(ctx, kvs[5].key) + assert.Nil(t, err) + assert.Equal(t, kvs[5].param, res) + + _, err = g.GetUint16(ctx, "invalid") + assert.NotNil(t, err) + + res = g.GetUint16WithDefault(ctx, kvs[5].key, def5) + assert.Equal(t, kvs[5].param, res) + + res = g.GetUint16WithDefault(ctx, "invalid", def5) + assert.Equal(t, def5, res) + + // Uint32 + def6 := uint32(0) + res, err = g.GetUint32(ctx, kvs[6].key) + assert.Nil(t, err) + assert.Equal(t, kvs[6].param, res) + + _, err = g.GetUint32(ctx, "invalid") + assert.NotNil(t, err) + + res = g.GetUint32WithDefault(ctx, kvs[6].key, def6) + assert.Equal(t, kvs[6].param, res) + + res = g.GetUint32WithDefault(ctx, "invalid", def6) + assert.Equal(t, def6, res) + + // Uint64 + def7 := uint64(0) + res, err = g.GetUint64(ctx, kvs[7].key) + assert.Nil(t, err) + assert.Equal(t, kvs[7].param, res) + + _, err = g.GetUint64(ctx, "invalid") + assert.NotNil(t, err) + + res = g.GetUint64WithDefault(ctx, kvs[7].key, def7) + assert.Equal(t, kvs[7].param, res) + + res = g.GetUint64WithDefault(ctx, "invalid", def7) + assert.Equal(t, def7, res) + + // Int + def8 := sdk.NewInt(0) + res, err = g.GetInt(ctx, kvs[8].key) + assert.Nil(t, err) + assert.Equal(t, kvs[8].param, res) + + _, err = g.GetInt(ctx, "invalid") + assert.NotNil(t, err) + + res = g.GetIntWithDefault(ctx, kvs[8].key, def8) + assert.Equal(t, kvs[8].param, res) + + res = g.GetIntWithDefault(ctx, "invalid", def8) + assert.Equal(t, def8, res) + + // Uint + def9 := sdk.NewUint(0) + res, err = g.GetUint(ctx, kvs[9].key) + assert.Nil(t, err) + assert.Equal(t, kvs[9].param, res) + + _, err = g.GetUint(ctx, "invalid") + assert.NotNil(t, err) + + res = g.GetUintWithDefault(ctx, kvs[9].key, def9) + assert.Equal(t, kvs[9].param, res) + + res = g.GetUintWithDefault(ctx, "invalid", def9) + assert.Equal(t, def9, res) + + // Rat + def10 := sdk.NewRat(0) + res, err = g.GetRat(ctx, kvs[10].key) + assert.Nil(t, err) + assert.Equal(t, kvs[10].param, res) + + _, err = g.GetRat(ctx, "invalid") + assert.NotNil(t, err) + + res = g.GetRatWithDefault(ctx, kvs[10].key, def10) + assert.Equal(t, kvs[10].param, res) + + res = g.GetRatWithDefault(ctx, "invalid", def10) + assert.Equal(t, def10, res) + +} diff --git a/x/params/msg_status.go b/x/params/msg_status.go new file mode 100644 index 000000000000..72704e4dc7aa --- /dev/null +++ b/x/params/msg_status.go @@ -0,0 +1,36 @@ +package params + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// GenesisState defines initial activated msg types +type GenesisState struct { + ActivatedTypes []string `json:"activated-types"` +} + +// ActivatedParamKey - paramstore key for msg type activation +func ActivatedParamKey(ty string) string { + return "Activated/" + ty +} + +// InitGenesis stores activated type to param store +func InitGenesis(ctx sdk.Context, k Keeper, data GenesisState) { + for _, ty := range data.ActivatedTypes { + k.set(ctx, ActivatedParamKey(ty), true) + } +} + +// NewAnteHandler returns an AnteHandler that checks +// whether msg type is activate or not +func NewAnteHandler(k Keeper) sdk.AnteHandler { + return func(ctx sdk.Context, tx sdk.Tx) (sdk.Context, sdk.Result, bool) { + for _, msg := range tx.GetMsgs() { + ok := k.Getter().GetBoolWithDefault(ctx, ActivatedParamKey(msg.Type()), false) + if !ok { + return ctx, sdk.ErrUnauthorized("deactivated msg type").Result(), true + } + } + return ctx, sdk.Result{}, false + } +} From 5a4e12bb16cb39b0a773db72986268f492bc36cf Mon Sep 17 00:00:00 2001 From: chengsilei Date: Tue, 31 Jul 2018 18:13:10 +0800 Subject: [PATCH 05/52] checkTx deny Tx if doing switch --- baseapp/baseapp.go | 36 +++++++++++++++++++++++++++++++++++- baseapp/baseapp_test.go | 22 +++++++++++----------- cmd/gaia/app/app.go | 10 +++++----- store/rootmultistore.go | 2 +- types/errors.go | 3 +++ 5 files changed, 55 insertions(+), 18 deletions(-) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 40b3c2bc1777..dd930ebb8412 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -438,8 +438,42 @@ func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeg // Implements ABCI func (app *BaseApp) CheckTx(txBytes []byte) (res abci.ResponseCheckTx) { - // Decode the Tx. + var result sdk.Result + + //////////////////// iris/cosmos-sdk begin /////////////////////////// + + upgradeKey := sdk.NewKVStoreKey("upgrade") + store := app.cms.GetStore(upgradeKey) + + if store != nil { + kvStore, ok := store.(sdk.KVStore) + if ok { + bz := kvStore.Get([]byte("d")) + if len(bz) == 1 && bz[0] == byte(1) { + result = sdk.NewError(sdk.CodespaceUndefined, sdk.CodeOutOfService, "").Result() + + return abci.ResponseCheckTx{ + Code: uint32(result.Code), + Data: result.Data, + Log: result.Log, + GasWanted: result.GasWanted, + GasUsed: result.GasUsed, + Fee: cmn.KI64Pair{ + []byte(result.FeeDenom), + result.FeeAmount, + }, + Tags: result.Tags, + } + } + } + } + + //////////////////// iris/cosmos-sdk end /////////////////////////// + + + // Decode the Tx. + var tx, err = app.txDecoder(txBytes) if err != nil { result = err.Result() diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 00897392ecaa..4663ec05f54b 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -440,7 +440,7 @@ func TestCheckTx(t *testing.T) { nTxs := int64(5) // TODO: can remove this once CheckTx doesnt process msgs. - app.Router().AddRoute(typeMsgCounter, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { return sdk.Result{} }) + app.Router().AddRoute(typeMsgCounter, capKey, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { return sdk.Result{} }) app.InitChain(abci.RequestInitChain{}) @@ -479,7 +479,7 @@ func TestDeliverTx(t *testing.T) { // test increments in the handler deliverKey := []byte("deliver-key") - app.Router().AddRoute(typeMsgCounter, handlerMsgCounter(t, capKey, deliverKey)) + app.Router().AddRoute(typeMsgCounter, capKey, handlerMsgCounter(t, capKey, deliverKey)) nBlocks := 3 txPerHeight := 5 @@ -515,8 +515,8 @@ func TestMultiMsgDeliverTx(t *testing.T) { // increment the msg counter deliverKey := []byte("deliver-key") deliverKey2 := []byte("deliver-key2") - app.Router().AddRoute(typeMsgCounter, handlerMsgCounter(t, capKey, deliverKey)) - app.Router().AddRoute(typeMsgCounter2, handlerMsgCounter(t, capKey, deliverKey2)) + app.Router().AddRoute(typeMsgCounter, capKey, handlerMsgCounter(t, capKey, deliverKey)) + app.Router().AddRoute(typeMsgCounter2, capKey, handlerMsgCounter(t, capKey, deliverKey2)) // run a multi-msg tx // with all msgs the same type @@ -575,7 +575,7 @@ func TestConcurrentCheckDeliver(t *testing.T) { // Simulate() and Query("/app/simulate", txBytes) should give // the same results. func TestSimulateTx(t *testing.T) { - app, _, _ := setupBaseApp(t) + app, capKey, _ := setupBaseApp(t) gasConsumed := int64(5) app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { @@ -583,7 +583,7 @@ func TestSimulateTx(t *testing.T) { return }) - app.Router().AddRoute(typeMsgCounter, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { + app.Router().AddRoute(typeMsgCounter, capKey, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { ctx.GasMeter().ConsumeGas(gasConsumed, "test") return sdk.Result{GasUsed: ctx.GasMeter().GasConsumed()} }) @@ -630,9 +630,9 @@ func TestSimulateTx(t *testing.T) { // TODO: add more func TestRunInvalidTransaction(t *testing.T) { - app, _, _ := setupBaseApp(t) + app, capKey, _ := setupBaseApp(t) app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { return }) - app.Router().AddRoute(typeMsgCounter, func(ctx sdk.Context, msg sdk.Msg) (res sdk.Result) { return }) + app.Router().AddRoute(typeMsgCounter, capKey, func(ctx sdk.Context, msg sdk.Msg) (res sdk.Result) { return }) app.BeginBlock(abci.RequestBeginBlock{}) @@ -700,7 +700,7 @@ func TestRunInvalidTransaction(t *testing.T) { // Test that transactions exceeding gas limits fail func TestTxGasLimits(t *testing.T) { - app, _, _ := setupBaseApp(t) + app, capKey, _ := setupBaseApp(t) gasGranted := int64(10) app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { @@ -732,7 +732,7 @@ func TestTxGasLimits(t *testing.T) { } return }) - app.Router().AddRoute(typeMsgCounter, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { + app.Router().AddRoute(typeMsgCounter, capKey, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { count := msg.(msgCounter).Counter ctx.GasMeter().ConsumeGas(count, "counter-handler") return sdk.Result{} @@ -794,7 +794,7 @@ func TestQuery(t *testing.T) { return }) - app.Router().AddRoute(typeMsgCounter, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { + app.Router().AddRoute(typeMsgCounter, capKey, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { store := ctx.KVStore(capKey) store.Set(key, value) return sdk.Result{} diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index ac1d27d39dc9..8a5b388fce9a 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -92,11 +92,11 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio // register message routes app.Router(). - AddRoute("bank", bank.NewHandler(app.coinKeeper)). - AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)). - AddRoute("stake", stake.NewHandler(app.stakeKeeper)). - AddRoute("slashing", slashing.NewHandler(app.slashingKeeper)). - AddRoute("gov", gov.NewHandler(app.govKeeper)) + AddRoute("bank", app.keyAccount, bank.NewHandler(app.coinKeeper)). + AddRoute("ibc", app.keyIBC, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). + AddRoute("stake", app.keyStake, stake.NewHandler(app.stakeKeeper)). + AddRoute("slashing", app.keySlashing, slashing.NewHandler(app.slashingKeeper)). + AddRoute("gov", app.keyGov, gov.NewHandler(app.govKeeper)) // initialize BaseApp app.SetInitChainer(app.initChainer) diff --git a/store/rootmultistore.go b/store/rootmultistore.go index 37049eede40e..a45be3474bc2 100644 --- a/store/rootmultistore.go +++ b/store/rootmultistore.go @@ -226,7 +226,7 @@ func (rs *rootMultiStore) CacheMultiStore() CacheMultiStore { // Implements MultiStore. func (rs *rootMultiStore) GetStore(key StoreKey) Store { - return rs.stores[key] + return rs.getStoreByName(key.Name()) } // GetKVStore implements the MultiStore interface. If tracing is enabled on the diff --git a/types/errors.go b/types/errors.go index a106ee9bb7cf..1888fbf6ad39 100644 --- a/types/errors.go +++ b/types/errors.go @@ -54,6 +54,7 @@ const ( CodeInvalidCoins CodeType = 11 CodeOutOfGas CodeType = 12 CodeMemoTooLarge CodeType = 13 + CodeOutOfService CodeType = 14 // CodespaceRoot is a codespace for error codes in this file only. // Notice that 0 is an "unset" codespace, which can be overridden with @@ -95,6 +96,8 @@ func CodeToDefaultMsg(code CodeType) string { return "out of gas" case CodeMemoTooLarge: return "memo too large" + case CodeOutOfService: + return "out of service" default: return fmt.Sprintf("unknown code %d", code) } From 9ba30d5c9043fa8694320c4a4631b2ec3b3d4c1d Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Wed, 1 Aug 2018 11:08:56 +0800 Subject: [PATCH 06/52] add paramstore to Gov --- cmd/gaia/app/app.go | 11 ++++++-- x/gov/genesis.go | 37 +++++++++++++++++++++---- x/gov/handler.go | 6 ++-- x/gov/keeper.go | 65 +++++++++++++++++++++++++++----------------- x/gov/keeper_test.go | 7 ----- x/gov/tally.go | 2 +- x/gov/test_common.go | 8 ++++-- x/gov/wire.go | 4 +++ 8 files changed, 95 insertions(+), 45 deletions(-) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index ac1d27d39dc9..7cbb65836565 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -20,6 +20,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/ibc" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/params" ) const ( @@ -45,6 +46,7 @@ type GaiaApp struct { keySlashing *sdk.KVStoreKey keyGov *sdk.KVStoreKey keyFeeCollection *sdk.KVStoreKey + keyParams *sdk.KVStoreKey // Manage getting and setting accounts accountMapper auth.AccountMapper @@ -54,6 +56,8 @@ type GaiaApp struct { stakeKeeper stake.Keeper slashingKeeper slashing.Keeper govKeeper gov.Keeper + paramsKeeper params.Keeper + } // NewGaiaApp returns a reference to an initialized GaiaApp. @@ -73,6 +77,8 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio keySlashing: sdk.NewKVStoreKey("slashing"), keyGov: sdk.NewKVStoreKey("gov"), keyFeeCollection: sdk.NewKVStoreKey("fee"), + keyParams: sdk.NewKVStoreKey("params"), + } // define the accountMapper @@ -83,11 +89,12 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio ) // add handlers + app.paramsKeeper = params.NewKeeper(app.cdc, app.keyParams) app.coinKeeper = bank.NewKeeper(app.accountMapper) app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace)) app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.RegisterCodespace(slashing.DefaultCodespace)) - app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) + app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection) // register message routes @@ -103,7 +110,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) - app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing, app.keyGov, app.keyFeeCollection) + app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing, app.keyGov, app.keyFeeCollection, app.keyParams) err := app.LoadLatestVersion(app.keyMain) if err != nil { cmn.Exit(err.Error()) diff --git a/x/gov/genesis.go b/x/gov/genesis.go index 40218ca8689c..47af7b81bee1 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -6,12 +6,18 @@ import ( // GenesisState - all staking state that must be provided at genesis type GenesisState struct { - StartingProposalID int64 `json:"starting_proposalID"` + StartingProposalID int64 `json:"starting_proposalID"` + DepositProcedure DepositProcedure `json:"deposit_period"` + VotingProcedure VotingProcedure `json:"voting_period"` + TallyingProcedure TallyingProcedure `json:"tallying_procedure"` } -func NewGenesisState(startingProposalID int64) GenesisState { +func NewGenesisState(startingProposalID int64, dp DepositProcedure, vp VotingProcedure, tp TallyingProcedure) GenesisState { return GenesisState{ StartingProposalID: startingProposalID, + DepositProcedure: dp, + VotingProcedure: vp, + TallyingProcedure: tp, } } @@ -19,6 +25,18 @@ func NewGenesisState(startingProposalID int64) GenesisState { func DefaultGenesisState() GenesisState { return GenesisState{ StartingProposalID: 1, + DepositProcedure: DepositProcedure{ + MinDeposit: sdk.Coins{sdk.NewCoin("steak", 10)}, + MaxDepositPeriod: 10, + }, + VotingProcedure: VotingProcedure{ + VotingPeriod: 10, + }, + TallyingProcedure: TallyingProcedure{ + Threshold: sdk.NewRat(1, 2), + Veto: sdk.NewRat(1, 3), + GovernancePenalty: sdk.NewRat(1, 100), + }, } } @@ -29,13 +47,22 @@ func InitGenesis(ctx sdk.Context, k Keeper, data GenesisState) { // TODO: Handle this with #870 panic(err) } + k.setDepositProcedure(ctx, data.DepositProcedure) + k.setVotingProcedure(ctx, data.VotingProcedure) + k.setTallyingProcedure(ctx, data.TallyingProcedure) } // WriteGenesis - output genesis parameters func WriteGenesis(ctx sdk.Context, k Keeper) GenesisState { - initalProposalID, _ := k.getNewProposalID(ctx) + startingProposalID, _ := k.getNewProposalID(ctx) + depositProcedure := k.GetDepositProcedure(ctx) + votingProcedure := k.GetVotingProcedure(ctx) + tallyingProcedure := k.GetTallyingProcedure(ctx) return GenesisState{ - initalProposalID, + StartingProposalID: startingProposalID, + DepositProcedure: depositProcedure, + VotingProcedure: votingProcedure, + TallyingProcedure: tallyingProcedure, } -} +} \ No newline at end of file diff --git a/x/gov/handler.go b/x/gov/handler.go index 636454571d91..fba19f0932c3 100644 --- a/x/gov/handler.go +++ b/x/gov/handler.go @@ -114,7 +114,7 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (tags sdk.Tags, nonVotingVals [] for shouldPopActiveProposalQueue(ctx, keeper) { activeProposal := keeper.ActiveProposalQueuePop(ctx) - if ctx.BlockHeight() >= activeProposal.GetVotingStartBlock()+keeper.GetVotingProcedure().VotingPeriod { + if ctx.BlockHeight() >= activeProposal.GetVotingStartBlock()+keeper.GetVotingProcedure(ctx).VotingPeriod { passes, nonVotingVals = tally(ctx, keeper, activeProposal) proposalIDBytes := keeper.cdc.MustMarshalBinaryBare(activeProposal.GetProposalID()) if passes { @@ -136,7 +136,7 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (tags sdk.Tags, nonVotingVals [] return tags, nonVotingVals } func shouldPopInactiveProposalQueue(ctx sdk.Context, keeper Keeper) bool { - depositProcedure := keeper.GetDepositProcedure() + depositProcedure := keeper.GetDepositProcedure(ctx) peekProposal := keeper.InactiveProposalQueuePeek(ctx) if peekProposal == nil { @@ -150,7 +150,7 @@ func shouldPopInactiveProposalQueue(ctx sdk.Context, keeper Keeper) bool { } func shouldPopActiveProposalQueue(ctx sdk.Context, keeper Keeper) bool { - votingProcedure := keeper.GetVotingProcedure() + votingProcedure := keeper.GetVotingProcedure(ctx) peekProposal := keeper.ActiveProposalQueuePeek(ctx) if peekProposal == nil { diff --git a/x/gov/keeper.go b/x/gov/keeper.go index 572c5388eb10..4f49cac582c6 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -4,10 +4,21 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" wire "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/params" +) + +// nolint +const ( + ParamStoreKeyDepositProcedure = "gov/depositprocedure" + ParamStoreKeyVotingProcedure = "gov/votingprocedure" + ParamStoreKeyTallyingProcedure = "gov/tallyingprocedure" ) // Governance Keeper type Keeper struct { + // The reference to the ParamSetter to get and set Global Params + ps params.Setter + // The reference to the CoinKeeper to modify balances ck bank.Keeper @@ -28,9 +39,10 @@ type Keeper struct { } // NewGovernanceMapper returns a mapper that uses go-wire to (binary) encode and decode gov types. -func NewKeeper(cdc *wire.Codec, key sdk.StoreKey, ck bank.Keeper, ds sdk.DelegationSet, codespace sdk.CodespaceType) Keeper { +func NewKeeper(cdc *wire.Codec, key sdk.StoreKey, ps params.Setter, ck bank.Keeper, ds sdk.DelegationSet, codespace sdk.CodespaceType) Keeper { return Keeper{ storeKey: key, + ps: ps, ck: ck, ds: ds, vs: ds.GetValidatorSet(), @@ -128,34 +140,37 @@ func (keeper Keeper) activateVotingPeriod(ctx sdk.Context, proposal Proposal) { // ===================================================== // Procedures -var ( - defaultMinDeposit int64 = 10 - defaultMaxDepositPeriod int64 = 10000 - defaultVotingPeriod int64 = 10000 -) +// Returns the current Deposit Procedure from the global param store +func (keeper Keeper) GetDepositProcedure(ctx sdk.Context) DepositProcedure { + var depositProcedure DepositProcedure + keeper.ps.Get(ctx, ParamStoreKeyDepositProcedure, &depositProcedure) + return depositProcedure +} -// Gets procedure from store. TODO: move to global param store and allow for updating of this -func (keeper Keeper) GetDepositProcedure() DepositProcedure { - return DepositProcedure{ - MinDeposit: sdk.Coins{sdk.NewCoin("steak", defaultMinDeposit)}, - MaxDepositPeriod: defaultMaxDepositPeriod, - } +// Returns the current Voting Procedure from the global param store +func (keeper Keeper) GetVotingProcedure(ctx sdk.Context) VotingProcedure { + var votingProcedure VotingProcedure + keeper.ps.Get(ctx, ParamStoreKeyVotingProcedure, &votingProcedure) + return votingProcedure } -// Gets procedure from store. TODO: move to global param store and allow for updating of this -func (keeper Keeper) GetVotingProcedure() VotingProcedure { - return VotingProcedure{ - VotingPeriod: defaultVotingPeriod, - } +// Returns the current Tallying Procedure from the global param store +func (keeper Keeper) GetTallyingProcedure(ctx sdk.Context) TallyingProcedure { + var tallyingProcedure TallyingProcedure + keeper.ps.Get(ctx, ParamStoreKeyTallyingProcedure, &tallyingProcedure) + return tallyingProcedure } -// Gets procedure from store. TODO: move to global param store and allow for updating of this -func (keeper Keeper) GetTallyingProcedure() TallyingProcedure { - return TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 100), - } +func (keeper Keeper) setDepositProcedure(ctx sdk.Context, depositProcedure DepositProcedure) { + keeper.ps.Set(ctx, ParamStoreKeyDepositProcedure, &depositProcedure) +} + +func (keeper Keeper) setVotingProcedure(ctx sdk.Context, votingProcedure VotingProcedure) { + keeper.ps.Set(ctx, ParamStoreKeyVotingProcedure, &votingProcedure) +} + +func (keeper Keeper) setTallyingProcedure(ctx sdk.Context, tallyingProcedure TallyingProcedure) { + keeper.ps.Set(ctx, ParamStoreKeyTallyingProcedure, &tallyingProcedure) } // ===================================================== @@ -262,7 +277,7 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID int64, depositerAddr // Check if deposit tipped proposal into voting period // Active voting period if so activatedVotingPeriod := false - if proposal.GetStatus() == StatusDepositPeriod && proposal.GetTotalDeposit().IsGTE(keeper.GetDepositProcedure().MinDeposit) { + if proposal.GetStatus() == StatusDepositPeriod && proposal.GetTotalDeposit().IsGTE(keeper.GetDepositProcedure(ctx).MinDeposit) { keeper.activateVotingPeriod(ctx, proposal) activatedVotingPeriod = true } diff --git a/x/gov/keeper_test.go b/x/gov/keeper_test.go index 988a8a6a7e05..786953fd3aa5 100644 --- a/x/gov/keeper_test.go +++ b/x/gov/keeper_test.go @@ -10,13 +10,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// overwrite defaults for testing -func init() { - defaultMinDeposit = 10 - defaultMaxDepositPeriod = 200 - defaultVotingPeriod = 200 -} - func TestGetSetProposal(t *testing.T) { mapp, keeper, _, _, _, _ := getMockApp(t, 0) mapp.BeginBlock(abci.RequestBeginBlock{}) diff --git a/x/gov/tally.go b/x/gov/tally.go index 2d8e85f7b2c6..4246b244d21e 100644 --- a/x/gov/tally.go +++ b/x/gov/tally.go @@ -81,7 +81,7 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, nonV totalVotingPower = totalVotingPower.Add(votingPower) } - tallyingProcedure := keeper.GetTallyingProcedure() + tallyingProcedure := keeper.GetTallyingProcedure(ctx) // If no one votes, proposal fails if totalVotingPower.Sub(results[OptionAbstain]).Equal(sdk.ZeroRat()) { diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 5567e4697a7f..243e89bf9928 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -15,6 +15,8 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/mock" "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/params" + ) // initialize the mock application for this module @@ -24,15 +26,17 @@ func getMockApp(t *testing.T, numGenAccs int) (*mock.App, Keeper, stake.Keeper, stake.RegisterWire(mapp.Cdc) RegisterWire(mapp.Cdc) + keyGlobalParams := sdk.NewKVStoreKey("params") keyStake := sdk.NewKVStoreKey("stake") keyGov := sdk.NewKVStoreKey("gov") + pk := params.NewKeeper(mapp.Cdc, keyGlobalParams) ck := bank.NewKeeper(mapp.AccountMapper) sk := stake.NewKeeper(mapp.Cdc, keyStake, ck, mapp.RegisterCodespace(stake.DefaultCodespace)) - keeper := NewKeeper(mapp.Cdc, keyGov, ck, sk, DefaultCodespace) + keeper := NewKeeper(mapp.Cdc, keyGov,pk.Setter(),ck, sk, DefaultCodespace) mapp.Router().AddRoute("gov", NewHandler(keeper)) - require.NoError(t, mapp.CompleteSetup([]*sdk.KVStoreKey{keyStake, keyGov})) + require.NoError(t, mapp.CompleteSetup([]*sdk.KVStoreKey{keyStake, keyGov, keyGlobalParams})) mapp.SetEndBlocker(getEndBlocker(keeper)) mapp.SetInitChainer(getInitChainer(mapp, keeper, sk)) diff --git a/x/gov/wire.go b/x/gov/wire.go index 405ee464efac..4173fc69a62f 100644 --- a/x/gov/wire.go +++ b/x/gov/wire.go @@ -10,6 +10,10 @@ func RegisterWire(cdc *wire.Codec) { cdc.RegisterConcrete(MsgSubmitProposal{}, "cosmos-sdk/MsgSubmitProposal", nil) cdc.RegisterConcrete(MsgDeposit{}, "cosmos-sdk/MsgDeposit", nil) cdc.RegisterConcrete(MsgVote{}, "cosmos-sdk/MsgVote", nil) + cdc.RegisterConcrete(DepositProcedure{},"cosmos-sdk/DepositProcedure",nil) + cdc.RegisterConcrete(TallyingProcedure{},"cosmos-sdk/TallyingProcedure",nil) + cdc.RegisterConcrete(VotingProcedure{},"cosmos-sdk/VotingProcedure",nil) + cdc.RegisterInterface((*Proposal)(nil), nil) cdc.RegisterConcrete(&TextProposal{}, "gov/TextProposal", nil) From 0fa28d723ea95f80f21e1caab3004c2841a3accf Mon Sep 17 00:00:00 2001 From: chengsilei Date: Wed, 1 Aug 2018 13:50:26 +0800 Subject: [PATCH 07/52] GetKVStore --- baseapp/baseapp.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index dd930ebb8412..4ced0a3bff27 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -135,6 +135,12 @@ func (app *BaseApp) MountStore(key sdk.StoreKey, typ sdk.StoreType) { app.cms.MountStoreWithDB(key, typ, nil) } +//////////////////// iris/cosmos-sdk begin /////////////////////////// +func (app *BaseApp) GetKVStore(key sdk.StoreKey) sdk.KVStore { + return app.cms.GetKVStore(key) +} +//////////////////// iris/cosmos-sdk end /////////////////////////// + // Set the txDecoder function func (app *BaseApp) SetTxDecoder(txDecoder sdk.TxDecoder) { app.txDecoder = txDecoder From 2d18adf9327720e6caf2ab33ec563c21acb28709 Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Wed, 1 Aug 2018 15:51:21 +0800 Subject: [PATCH 08/52] fee token proto type --- cmd/gaia/app/app.go | 4 ++- x/auth/ante.go | 5 +++ x/auth/ante_test.go | 25 ++++++++++----- x/auth/feekeeper.go | 68 ++++++++++++++++++++++++++++++++++++++-- x/auth/feekeeper_test.go | 56 +++++++++++++++++++++++++++++++-- 5 files changed, 143 insertions(+), 15 deletions(-) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 7cbb65836565..b5e34a0004e8 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -95,7 +95,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.RegisterCodespace(slashing.DefaultCodespace)) app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection) + app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection,app.paramsKeeper.Getter()) // register message routes app.Router(). @@ -183,6 +183,8 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci gov.InitGenesis(ctx, app.govKeeper, gov.DefaultGenesisState()) + auth.InitGenesis(ctx,app.paramsKeeper.Setter(),auth.DefaultGenesisState()) + return abci.ResponseInitChain{} } diff --git a/x/auth/ante.go b/x/auth/ante.go index 9652b37de203..53a76a320ff1 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -53,6 +53,11 @@ func NewAnteHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.AnteHandler { } fee := stdTx.Fee + err = fck.FeePreprocess(ctx,fee.Amount) + if err != nil { + return ctx, err.Result(), true + } + // Check sig and nonce and collect signer accounts. var signerAccs = make([]Account, len(signerAddrs)) for i := 0; i < len(sigs); i++ { diff --git a/x/auth/ante_test.go b/x/auth/ante_test.go index 01fcab012f28..b38fa605c4d2 100644 --- a/x/auth/ante_test.go +++ b/x/auth/ante_test.go @@ -12,6 +12,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" wire "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/x/params" ) func newTestMsg(addrs ...sdk.AccAddress) *sdk.TestMsg { @@ -112,9 +113,10 @@ func TestAnteHandlerSigErrors(t *testing.T) { // setup ms, capKey, capKey2 := setupMultiStore() cdc := wire.NewCodec() + paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) RegisterBaseAccount(cdc) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) - feeCollector := NewFeeCollectionKeeper(cdc, capKey2) + feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -165,9 +167,10 @@ func TestAnteHandlerAccountNumbers(t *testing.T) { // setup ms, capKey, capKey2 := setupMultiStore() cdc := wire.NewCodec() + paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) RegisterBaseAccount(cdc) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) - feeCollector := NewFeeCollectionKeeper(cdc, capKey2) + feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -225,8 +228,9 @@ func TestAnteHandlerSequences(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := wire.NewCodec() RegisterBaseAccount(cdc) + paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) - feeCollector := NewFeeCollectionKeeper(cdc, capKey2) + feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -303,8 +307,9 @@ func TestAnteHandlerFees(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := wire.NewCodec() RegisterBaseAccount(cdc) + paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) - feeCollector := NewFeeCollectionKeeper(cdc, capKey2) + feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -345,8 +350,9 @@ func TestAnteHandlerMemoGas(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := wire.NewCodec() RegisterBaseAccount(cdc) + paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) - feeCollector := NewFeeCollectionKeeper(cdc, capKey2) + feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -388,8 +394,9 @@ func TestAnteHandlerMultiSigner(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := wire.NewCodec() RegisterBaseAccount(cdc) + paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) - feeCollector := NewFeeCollectionKeeper(cdc, capKey2) + feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -439,8 +446,9 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := wire.NewCodec() RegisterBaseAccount(cdc) + paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) - feeCollector := NewFeeCollectionKeeper(cdc, capKey2) + feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -520,8 +528,9 @@ func TestAnteHandlerSetPubKey(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := wire.NewCodec() RegisterBaseAccount(cdc) + paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) - feeCollector := NewFeeCollectionKeeper(cdc, capKey2) + feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) diff --git a/x/auth/feekeeper.go b/x/auth/feekeeper.go index 3e03a81aa27c..823dac00c1b4 100644 --- a/x/auth/feekeeper.go +++ b/x/auth/feekeeper.go @@ -2,17 +2,24 @@ package auth import ( sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" -) + "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/x/params" + "fmt" + ) var ( collectedFeesKey = []byte("collectedFees") + feeTokenKey = "fee/token" // fee/token + FeeThresholdKey = "fee/threshold" // fee/threshold + FeeExchangeRatePrefix = "fee/exchange/rate/" // fee/exchange/rate/ ) // This FeeCollectionKeeper handles collection of fees in the anteHandler // and setting of MinFees for different fee tokens type FeeCollectionKeeper struct { + getter params.Getter + // The (unexposed) key used to access the fee store from the Context. key sdk.StoreKey @@ -21,10 +28,11 @@ type FeeCollectionKeeper struct { } // NewFeeKeeper returns a new FeeKeeper -func NewFeeCollectionKeeper(cdc *wire.Codec, key sdk.StoreKey) FeeCollectionKeeper { +func NewFeeCollectionKeeper(cdc *wire.Codec, key sdk.StoreKey, getter params.Getter) FeeCollectionKeeper { return FeeCollectionKeeper{ key: key, cdc: cdc, + getter: getter, } } @@ -60,3 +68,57 @@ func (fck FeeCollectionKeeper) addCollectedFees(ctx sdk.Context, coins sdk.Coins func (fck FeeCollectionKeeper) ClearCollectedFees(ctx sdk.Context) { fck.setCollectedFees(ctx, sdk.Coins{}) } + +func (fck FeeCollectionKeeper) FeePreprocess(ctx sdk.Context, coins sdk.Coins) sdk.Error { + feeToken, err := fck.getter.GetString(ctx, feeTokenKey) + if err != nil { + panic(err) + } + feeThreshold, err := fck.getter.GetInt(ctx, FeeThresholdKey) + if err != nil { + panic(err) + } + + equivalentTotalFee := sdk.ZeroRat() + for _,coin := range coins { + if coin.Denom != feeToken { + exchangeRateKey := FeeExchangeRatePrefix + coin.Denom + rateBytes := fck.getter.GetRaw(ctx, exchangeRateKey) + if rateBytes == nil { + continue + } + var exchangeRate sdk.Rat + err := fck.cdc.UnmarshalBinary(rateBytes, &exchangeRate) + if err != nil { + panic(err) + } + equivalentFee := exchangeRate.Mul(sdk.NewRatFromInt(coin.Amount, sdk.OneInt())) + equivalentTotalFee = equivalentTotalFee.Add(equivalentFee) + + } else { + equivalentTotalFee = equivalentTotalFee.Add(sdk.NewRatFromInt(coin.Amount, sdk.OneInt())) + } + } + + if equivalentTotalFee.LT(sdk.NewRatFromInt(feeThreshold, sdk.OneInt())) { + return sdk.ErrInsufficientCoins(fmt.Sprintf("equivalent total fee %s is less than threshold %s", equivalentTotalFee.String(), feeThreshold)) + } + return nil +} + +type GenesisState struct { + FeeToken string `json:"fee_token"` + Threshold int64 `json:"fee_threshold"` +} + +func DefaultGenesisState() GenesisState { + return GenesisState{ + FeeToken: "iGas", + Threshold: 100, + } +} + +func InitGenesis(ctx sdk.Context, setter params.Setter, data GenesisState) { + setter.SetString(ctx, feeTokenKey, data.FeeToken) + setter.SetInt(ctx, FeeThresholdKey, sdk.NewInt(data.Threshold)) +} \ No newline at end of file diff --git a/x/auth/feekeeper_test.go b/x/auth/feekeeper_test.go index a53839a8b4b9..ff1bd805a6d1 100644 --- a/x/auth/feekeeper_test.go +++ b/x/auth/feekeeper_test.go @@ -10,6 +10,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" wire "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/store" + dbm "github.com/tendermint/tendermint/libs/db" ) var ( @@ -21,10 +24,11 @@ var ( func TestFeeCollectionKeeperGetSet(t *testing.T) { ms, _, capKey2 := setupMultiStore() cdc := wire.NewCodec() + paramKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) // make context and keeper ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) - fck := NewFeeCollectionKeeper(cdc, capKey2) + fck := NewFeeCollectionKeeper(cdc, capKey2, paramKeeper.Getter()) // no coins initially currFees := fck.GetCollectedFees(ctx) @@ -40,10 +44,11 @@ func TestFeeCollectionKeeperGetSet(t *testing.T) { func TestFeeCollectionKeeperAdd(t *testing.T) { ms, _, capKey2 := setupMultiStore() cdc := wire.NewCodec() + paramKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) // make context and keeper ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) - fck := NewFeeCollectionKeeper(cdc, capKey2) + fck := NewFeeCollectionKeeper(cdc, capKey2, paramKeeper.Getter()) // no coins initially require.True(t, fck.GetCollectedFees(ctx).IsEqual(emptyCoins)) @@ -60,10 +65,11 @@ func TestFeeCollectionKeeperAdd(t *testing.T) { func TestFeeCollectionKeeperClear(t *testing.T) { ms, _, capKey2 := setupMultiStore() cdc := wire.NewCodec() + paramKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) // make context and keeper ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) - fck := NewFeeCollectionKeeper(cdc, capKey2) + fck := NewFeeCollectionKeeper(cdc, capKey2, paramKeeper.Getter()) // set coins initially fck.setCollectedFees(ctx, twoCoins) @@ -73,3 +79,47 @@ func TestFeeCollectionKeeperClear(t *testing.T) { fck.ClearCollectedFees(ctx) require.True(t, fck.GetCollectedFees(ctx).IsEqual(emptyCoins)) } + +func TestFeeCollectionKeeperPreprocess(t *testing.T) { + db := dbm.NewMemDB() + + capKey := sdk.NewKVStoreKey("capkey") + paramsKey := sdk.NewKVStoreKey("params") + + ms := store.NewCommitMultiStore(db) + ms.MountStoreWithDB(capKey, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(paramsKey, sdk.StoreTypeIAVL, db) + ms.LoadLatestVersion() + + cdc := wire.NewCodec() + paramKeeper := params.NewKeeper(cdc, paramsKey) + + // make context and keeper + ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) + fck := NewFeeCollectionKeeper(cdc, capKey, paramKeeper.Getter()) + InitGenesis(ctx, paramKeeper.Setter(), DefaultGenesisState()) + + var err sdk.Error + err = fck.FeePreprocess(ctx, oneCoin) + require.Error(t,err,"") + + fee1 := sdk.Coins{sdk.NewCoin("iGas", 50)} + err = fck.FeePreprocess(ctx, fee1) + require.Error(t,err,"") + + fee2 := sdk.Coins{sdk.NewCoin("iGas", 100)} + err = fck.FeePreprocess(ctx, fee2) + require.NoError(t,err,"") + + fee3 := sdk.Coins{sdk.NewCoin("iris", 1)} + err = fck.FeePreprocess(ctx, fee3) + require.Error(t,err,"") + + exchangeRate := sdk.NewRatFromInt(sdk.NewInt(100), sdk.OneInt()) + exchangeRateBytes,errMsg := fck.cdc.MarshalBinary(exchangeRate) + require.NoError(t, errMsg) + paramKeeper.Setter().SetRaw(ctx, FeeExchangeRatePrefix+"iris", exchangeRateBytes) + + err = fck.FeePreprocess(ctx, fee3) + require.NoError(t,err,"") +} From fb670df8bbcebdf4acba21f9a1761af7a2561119 Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Wed, 1 Aug 2018 16:16:46 +0800 Subject: [PATCH 09/52] Fix test failure --- x/auth/ante_test.go | 40 ++++++++++++++++++++++++---------------- x/auth/context_test.go | 2 +- x/auth/feekeeper.go | 7 +++++++ x/auth/feekeeper_test.go | 24 +++++++----------------- x/auth/mapper_test.go | 8 +++++--- 5 files changed, 44 insertions(+), 37 deletions(-) diff --git a/x/auth/ante_test.go b/x/auth/ante_test.go index b38fa605c4d2..d990659c1afa 100644 --- a/x/auth/ante_test.go +++ b/x/auth/ante_test.go @@ -111,14 +111,15 @@ func newTestTxWithSignBytes(msgs []sdk.Msg, privs []crypto.PrivKey, accNums []in // Test various error cases in the AnteHandler control flow. func TestAnteHandlerSigErrors(t *testing.T) { // setup - ms, capKey, capKey2 := setupMultiStore() + ms, capKey, capKey2, paramsKey := setupMultiStore() cdc := wire.NewCodec() - paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) + paramsKeeper := params.NewKeeper(cdc, paramsKey) RegisterBaseAccount(cdc) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) + InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() @@ -165,14 +166,15 @@ func TestAnteHandlerSigErrors(t *testing.T) { // Test logic around account number checking with one signer and many signers. func TestAnteHandlerAccountNumbers(t *testing.T) { // setup - ms, capKey, capKey2 := setupMultiStore() + ms, capKey, capKey2, paramsKey := setupMultiStore() cdc := wire.NewCodec() - paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) + paramsKeeper := params.NewKeeper(cdc, paramsKey) RegisterBaseAccount(cdc) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) + InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() @@ -225,14 +227,15 @@ func TestAnteHandlerAccountNumbers(t *testing.T) { // Test logic around sequence checking with one signer and many signers. func TestAnteHandlerSequences(t *testing.T) { // setup - ms, capKey, capKey2 := setupMultiStore() + ms, capKey, capKey2, paramsKey := setupMultiStore() cdc := wire.NewCodec() RegisterBaseAccount(cdc) - paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) + paramsKeeper := params.NewKeeper(cdc, paramsKey) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) + InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() @@ -304,14 +307,15 @@ func TestAnteHandlerSequences(t *testing.T) { // Test logic around fee deduction. func TestAnteHandlerFees(t *testing.T) { // setup - ms, capKey, capKey2 := setupMultiStore() + ms, capKey, capKey2, paramsKey := setupMultiStore() cdc := wire.NewCodec() RegisterBaseAccount(cdc) - paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) + paramsKeeper := params.NewKeeper(cdc, paramsKey) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) + InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() @@ -347,14 +351,15 @@ func TestAnteHandlerFees(t *testing.T) { // Test logic around memo gas consumption. func TestAnteHandlerMemoGas(t *testing.T) { // setup - ms, capKey, capKey2 := setupMultiStore() + ms, capKey, capKey2, paramsKey := setupMultiStore() cdc := wire.NewCodec() RegisterBaseAccount(cdc) - paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) + paramsKeeper := params.NewKeeper(cdc, paramsKey) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) + InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() @@ -391,14 +396,15 @@ func TestAnteHandlerMemoGas(t *testing.T) { func TestAnteHandlerMultiSigner(t *testing.T) { // setup - ms, capKey, capKey2 := setupMultiStore() + ms, capKey, capKey2, paramsKey := setupMultiStore() cdc := wire.NewCodec() RegisterBaseAccount(cdc) - paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) + paramsKeeper := params.NewKeeper(cdc, paramsKey) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) + InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() @@ -443,14 +449,15 @@ func TestAnteHandlerMultiSigner(t *testing.T) { func TestAnteHandlerBadSignBytes(t *testing.T) { // setup - ms, capKey, capKey2 := setupMultiStore() + ms, capKey, capKey2, paramsKey := setupMultiStore() cdc := wire.NewCodec() RegisterBaseAccount(cdc) - paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) + paramsKeeper := params.NewKeeper(cdc, paramsKey) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) + InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() @@ -525,14 +532,15 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { func TestAnteHandlerSetPubKey(t *testing.T) { // setup - ms, capKey, capKey2 := setupMultiStore() + ms, capKey, capKey2, paramsKey := setupMultiStore() cdc := wire.NewCodec() RegisterBaseAccount(cdc) - paramsKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) + paramsKeeper := params.NewKeeper(cdc, paramsKey) mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) + InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() diff --git a/x/auth/context_test.go b/x/auth/context_test.go index b58547328d1a..bcd48c5a60ac 100644 --- a/x/auth/context_test.go +++ b/x/auth/context_test.go @@ -12,7 +12,7 @@ import ( ) func TestContextWithSigners(t *testing.T) { - ms, _, _ := setupMultiStore() + ms, _, _, _:= setupMultiStore() ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) _, _, addr1 := keyPubAddr() diff --git a/x/auth/feekeeper.go b/x/auth/feekeeper.go index 823dac00c1b4..958622b84c62 100644 --- a/x/auth/feekeeper.go +++ b/x/auth/feekeeper.go @@ -111,6 +111,13 @@ type GenesisState struct { Threshold int64 `json:"fee_threshold"` } +func DefaultGenesisStateForTest() GenesisState { + return GenesisState{ + FeeToken: "iGas", + Threshold: 0, + } +} + func DefaultGenesisState() GenesisState { return GenesisState{ FeeToken: "iGas", diff --git a/x/auth/feekeeper_test.go b/x/auth/feekeeper_test.go index ff1bd805a6d1..1e99dcf18f5b 100644 --- a/x/auth/feekeeper_test.go +++ b/x/auth/feekeeper_test.go @@ -9,11 +9,9 @@ import ( "github.com/tendermint/tendermint/libs/log" sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/store" - dbm "github.com/tendermint/tendermint/libs/db" -) + ) var ( emptyCoins = sdk.Coins{} @@ -22,7 +20,7 @@ var ( ) func TestFeeCollectionKeeperGetSet(t *testing.T) { - ms, _, capKey2 := setupMultiStore() + ms, _, capKey2, _ := setupMultiStore() cdc := wire.NewCodec() paramKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) @@ -42,7 +40,7 @@ func TestFeeCollectionKeeperGetSet(t *testing.T) { } func TestFeeCollectionKeeperAdd(t *testing.T) { - ms, _, capKey2 := setupMultiStore() + ms, _, capKey2, _ := setupMultiStore() cdc := wire.NewCodec() paramKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) @@ -63,7 +61,7 @@ func TestFeeCollectionKeeperAdd(t *testing.T) { } func TestFeeCollectionKeeperClear(t *testing.T) { - ms, _, capKey2 := setupMultiStore() + ms, _, capKey2, _ := setupMultiStore() cdc := wire.NewCodec() paramKeeper := params.NewKeeper(cdc, sdk.NewKVStoreKey("params")) @@ -81,22 +79,14 @@ func TestFeeCollectionKeeperClear(t *testing.T) { } func TestFeeCollectionKeeperPreprocess(t *testing.T) { - db := dbm.NewMemDB() - - capKey := sdk.NewKVStoreKey("capkey") - paramsKey := sdk.NewKVStoreKey("params") - - ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(capKey, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(paramsKey, sdk.StoreTypeIAVL, db) - ms.LoadLatestVersion() + ms, _, capKey2, paramsKey := setupMultiStore() cdc := wire.NewCodec() paramKeeper := params.NewKeeper(cdc, paramsKey) // make context and keeper ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) - fck := NewFeeCollectionKeeper(cdc, capKey, paramKeeper.Getter()) + fck := NewFeeCollectionKeeper(cdc, capKey2, paramKeeper.Getter()) InitGenesis(ctx, paramKeeper.Setter(), DefaultGenesisState()) var err sdk.Error diff --git a/x/auth/mapper_test.go b/x/auth/mapper_test.go index 679ee12cdc64..b54d0ba283e7 100644 --- a/x/auth/mapper_test.go +++ b/x/auth/mapper_test.go @@ -14,19 +14,21 @@ import ( wire "github.com/cosmos/cosmos-sdk/wire" ) -func setupMultiStore() (sdk.MultiStore, *sdk.KVStoreKey, *sdk.KVStoreKey) { +func setupMultiStore() (sdk.MultiStore, *sdk.KVStoreKey, *sdk.KVStoreKey, *sdk.KVStoreKey) { db := dbm.NewMemDB() capKey := sdk.NewKVStoreKey("capkey") capKey2 := sdk.NewKVStoreKey("capkey2") + paramsKey := sdk.NewKVStoreKey("params") ms := store.NewCommitMultiStore(db) ms.MountStoreWithDB(capKey, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(capKey2, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(paramsKey, sdk.StoreTypeIAVL, db) ms.LoadLatestVersion() - return ms, capKey, capKey2 + return ms, capKey, capKey2, paramsKey } func TestAccountMapperGetSet(t *testing.T) { - ms, capKey, _ := setupMultiStore() + ms, capKey, _, _ := setupMultiStore() cdc := wire.NewCodec() RegisterBaseAccount(cdc) From 13f3316200d18e6e37295b99cc6f006ced633be3 Mon Sep 17 00:00:00 2001 From: chengsilei Date: Thu, 2 Aug 2018 14:04:07 +0800 Subject: [PATCH 10/52] update Router interface && fix bug in commitStores() --- baseapp/baseapp_test.go | 16 ++++++------ baseapp/router.go | 12 ++++++--- cmd/gaia/app/app.go | 10 ++++---- store/rootmultistore.go | 56 ++++++++++++++++++++++++++++++----------- x/gov/test_common.go | 2 +- 5 files changed, 64 insertions(+), 32 deletions(-) diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 4663ec05f54b..f675e9984a52 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -440,7 +440,7 @@ func TestCheckTx(t *testing.T) { nTxs := int64(5) // TODO: can remove this once CheckTx doesnt process msgs. - app.Router().AddRoute(typeMsgCounter, capKey, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { return sdk.Result{} }) + app.Router().AddRoute(typeMsgCounter, []*sdk.KVStoreKey{capKey}, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { return sdk.Result{} }) app.InitChain(abci.RequestInitChain{}) @@ -479,7 +479,7 @@ func TestDeliverTx(t *testing.T) { // test increments in the handler deliverKey := []byte("deliver-key") - app.Router().AddRoute(typeMsgCounter, capKey, handlerMsgCounter(t, capKey, deliverKey)) + app.Router().AddRoute(typeMsgCounter, []*sdk.KVStoreKey{capKey}, handlerMsgCounter(t, capKey, deliverKey)) nBlocks := 3 txPerHeight := 5 @@ -515,8 +515,8 @@ func TestMultiMsgDeliverTx(t *testing.T) { // increment the msg counter deliverKey := []byte("deliver-key") deliverKey2 := []byte("deliver-key2") - app.Router().AddRoute(typeMsgCounter, capKey, handlerMsgCounter(t, capKey, deliverKey)) - app.Router().AddRoute(typeMsgCounter2, capKey, handlerMsgCounter(t, capKey, deliverKey2)) + app.Router().AddRoute(typeMsgCounter, []*sdk.KVStoreKey{capKey}, handlerMsgCounter(t, capKey, deliverKey)) + app.Router().AddRoute(typeMsgCounter2, []*sdk.KVStoreKey{capKey}, handlerMsgCounter(t, capKey, deliverKey2)) // run a multi-msg tx // with all msgs the same type @@ -583,7 +583,7 @@ func TestSimulateTx(t *testing.T) { return }) - app.Router().AddRoute(typeMsgCounter, capKey, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { + app.Router().AddRoute(typeMsgCounter, []*sdk.KVStoreKey{capKey}, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { ctx.GasMeter().ConsumeGas(gasConsumed, "test") return sdk.Result{GasUsed: ctx.GasMeter().GasConsumed()} }) @@ -632,7 +632,7 @@ func TestSimulateTx(t *testing.T) { func TestRunInvalidTransaction(t *testing.T) { app, capKey, _ := setupBaseApp(t) app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { return }) - app.Router().AddRoute(typeMsgCounter, capKey, func(ctx sdk.Context, msg sdk.Msg) (res sdk.Result) { return }) + app.Router().AddRoute(typeMsgCounter, []*sdk.KVStoreKey{capKey}, func(ctx sdk.Context, msg sdk.Msg) (res sdk.Result) { return }) app.BeginBlock(abci.RequestBeginBlock{}) @@ -732,7 +732,7 @@ func TestTxGasLimits(t *testing.T) { } return }) - app.Router().AddRoute(typeMsgCounter, capKey, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { + app.Router().AddRoute(typeMsgCounter, []*sdk.KVStoreKey{capKey}, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { count := msg.(msgCounter).Counter ctx.GasMeter().ConsumeGas(count, "counter-handler") return sdk.Result{} @@ -794,7 +794,7 @@ func TestQuery(t *testing.T) { return }) - app.Router().AddRoute(typeMsgCounter, capKey, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { + app.Router().AddRoute(typeMsgCounter, []*sdk.KVStoreKey{capKey}, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { store := ctx.KVStore(capKey) store.Set(key, value) return sdk.Result{} diff --git a/baseapp/router.go b/baseapp/router.go index 55417c69001e..d6792cef4167 100644 --- a/baseapp/router.go +++ b/baseapp/router.go @@ -10,7 +10,7 @@ import ( type Router interface { //////////////////// iris/cosmos-sdk begin /////////////////////////// - AddRoute(r string, s *sdk.KVStoreKey, h sdk.Handler) (rtr Router) + AddRoute(r string, s []*sdk.KVStoreKey, h sdk.Handler) (rtr Router) Route(path string) (h sdk.Handler) RouteTable() (table []string) //////////////////// iris/cosmos-sdk end /////////////////////////// @@ -20,7 +20,7 @@ type Router interface { type route struct { r string //////////////////// iris/cosmos-sdk begin /////////////////////////// - s *sdk.KVStoreKey + s []*sdk.KVStoreKey //////////////////// iris/cosmos-sdk end /////////////////////////// h sdk.Handler } @@ -42,7 +42,7 @@ var isAlpha = regexp.MustCompile(`^[a-zA-Z]+$`).MatchString // AddRoute - TODO add description //////////////////// iris/cosmos-sdk begin /////////////////////////// -func (rtr *router) AddRoute(r string, s *sdk.KVStoreKey, h sdk.Handler) Router { +func (rtr *router) AddRoute(r string, s []*sdk.KVStoreKey, h sdk.Handler) Router { if !isAlpha(r) { panic("route expressions can only contain alphabet characters") } @@ -67,7 +67,11 @@ func (rtr *router) Route(path string) (h sdk.Handler) { func (rtr *router) RouteTable() (table []string) { for _, route := range rtr.routes { - table = append(table, route.r + "/" + route.s.String()) + storelist := "" + for _, store := range route.s { + storelist = storelist + ":" + store.Name() + } + table = append(table, route.r + "/" + storelist) } return } diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 8a5b388fce9a..90ccd72cd05b 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -92,11 +92,11 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio // register message routes app.Router(). - AddRoute("bank", app.keyAccount, bank.NewHandler(app.coinKeeper)). - AddRoute("ibc", app.keyIBC, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). - AddRoute("stake", app.keyStake, stake.NewHandler(app.stakeKeeper)). - AddRoute("slashing", app.keySlashing, slashing.NewHandler(app.slashingKeeper)). - AddRoute("gov", app.keyGov, gov.NewHandler(app.govKeeper)) + AddRoute("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.coinKeeper)). + AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). + AddRoute("stake", []*sdk.KVStoreKey{app.keyStake, app.keyAccount}, stake.NewHandler(app.stakeKeeper)). + AddRoute("slashing", []*sdk.KVStoreKey{app.keySlashing, app.keyStake}, slashing.NewHandler(app.slashingKeeper)). + AddRoute("gov",[]*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake}, gov.NewHandler(app.govKeeper)) // initialize BaseApp app.SetInitChainer(app.initChainer) diff --git a/store/rootmultistore.go b/store/rootmultistore.go index a45be3474bc2..1415fe335dae 100644 --- a/store/rootmultistore.go +++ b/store/rootmultistore.go @@ -468,35 +468,63 @@ func commitStores(version int64, storeMap map[StoreKey]CommitStore) commitInfo { storemap[key.Name()] = store } - upgradeStore:=storemap["upgrade"].(KVStore) - bz:= upgradeStore.Get([]byte("k/"))//CurrentStoreKey - storekeys := string(bz) //splitby":" + upgrade := storemap["upgrade"] - storekeyslist := strings.Split(storekeys, ":") - fmt.Println(storekeyslist) + if upgrade != nil { - storeInfos := make([]storeInfo, 0, len(storekeyslist)) + upgradeStore := upgrade.(KVStore) + bz := upgradeStore.Get([]byte("k/")) //CurrentStoreKey + storekeys := string(bz) //splitby":" - for _, key := range storekeyslist { + storekeyslist := strings.Split(storekeys, ":") + fmt.Println(storekeyslist) - if store,ok:= storemap[key]; ok{ + storeInfos := make([]storeInfo, 0, len(storekeyslist)) + + for _, key := range storekeyslist { + + if store,ok:= storemap[key]; ok{ + // Commit + commitID := store.Commit() + + // Record CommitID + si := storeInfo{} + si.Name = key + si.Core.CommitID = commitID + // si.Core.StoreType = store.GetStoreType() + storeInfos = append(storeInfos, si) + } + } + + ci := commitInfo{ + Version: version, + StoreInfos: storeInfos, + } + return ci + } else { + storeInfos := make([]storeInfo, 0, len(storeMap)) + + for key, store := range storeMap { // Commit commitID := store.Commit() // Record CommitID si := storeInfo{} - si.Name = key + si.Name = key.Name() si.Core.CommitID = commitID // si.Core.StoreType = store.GetStoreType() storeInfos = append(storeInfos, si) } - } - ci := commitInfo{ - Version: version, - StoreInfos: storeInfos, + ci := commitInfo{ + Version: version, + StoreInfos: storeInfos, + } + return ci } - return ci + + + } //////////////////// iris/cosmos-sdk end/////////////////////////// diff --git a/x/gov/test_common.go b/x/gov/test_common.go index bbf9a401ed71..9a22717598a0 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -30,7 +30,7 @@ func getMockApp(t *testing.T, numGenAccs int) (*mock.App, Keeper, stake.Keeper, ck := bank.NewKeeper(mapp.AccountMapper) sk := stake.NewKeeper(mapp.Cdc, keyStake, ck, mapp.RegisterCodespace(stake.DefaultCodespace)) keeper := NewKeeper(mapp.Cdc, keyGov, ck, sk, DefaultCodespace) - mapp.Router().AddRoute("gov", keyGov, NewHandler(keeper)) + mapp.Router().AddRoute("gov", []*sdk.KVStoreKey{keyGov}, NewHandler(keeper)) require.NoError(t, mapp.CompleteSetup([]*sdk.KVStoreKey{keyStake, keyGov})) From 25080524a617f6bcc2b416021b991c4f5a16475b Mon Sep 17 00:00:00 2001 From: chengsilei Date: Thu, 2 Aug 2018 17:29:45 +0800 Subject: [PATCH 11/52] go fmt --- baseapp/baseapp.go | 2 +- baseapp/router.go | 7 ++++--- cmd/gaia/app/app.go | 2 +- store/rootmultistore.go | 14 +++++--------- 4 files changed, 11 insertions(+), 14 deletions(-) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 4ced0a3bff27..868f3558a51e 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -139,6 +139,7 @@ func (app *BaseApp) MountStore(key sdk.StoreKey, typ sdk.StoreType) { func (app *BaseApp) GetKVStore(key sdk.StoreKey) sdk.KVStore { return app.cms.GetKVStore(key) } + //////////////////// iris/cosmos-sdk end /////////////////////////// // Set the txDecoder function @@ -477,7 +478,6 @@ func (app *BaseApp) CheckTx(txBytes []byte) (res abci.ResponseCheckTx) { //////////////////// iris/cosmos-sdk end /////////////////////////// - // Decode the Tx. var tx, err = app.txDecoder(txBytes) diff --git a/baseapp/router.go b/baseapp/router.go index d6792cef4167..1ff2678336f9 100644 --- a/baseapp/router.go +++ b/baseapp/router.go @@ -46,10 +46,11 @@ func (rtr *router) AddRoute(r string, s []*sdk.KVStoreKey, h sdk.Handler) Router if !isAlpha(r) { panic("route expressions can only contain alphabet characters") } - rtr.routes = append(rtr.routes, route{r,s,h}) + rtr.routes = append(rtr.routes, route{r, s, h}) return rtr } + //////////////////// iris/cosmos-sdk end /////////////////////////// // Route - TODO add description @@ -71,9 +72,9 @@ func (rtr *router) RouteTable() (table []string) { for _, store := range route.s { storelist = storelist + ":" + store.Name() } - table = append(table, route.r + "/" + storelist) + table = append(table, route.r+"/"+storelist) } return } -//////////////////// iris/cosmos-sdk end /////////////////////////// \ No newline at end of file +//////////////////// iris/cosmos-sdk end /////////////////////////// diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 90ccd72cd05b..4eda1abfee35 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -96,7 +96,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). AddRoute("stake", []*sdk.KVStoreKey{app.keyStake, app.keyAccount}, stake.NewHandler(app.stakeKeeper)). AddRoute("slashing", []*sdk.KVStoreKey{app.keySlashing, app.keyStake}, slashing.NewHandler(app.slashingKeeper)). - AddRoute("gov",[]*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake}, gov.NewHandler(app.govKeeper)) + AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake}, gov.NewHandler(app.govKeeper)) // initialize BaseApp app.SetInitChainer(app.initChainer) diff --git a/store/rootmultistore.go b/store/rootmultistore.go index 1415fe335dae..56f89b29bbeb 100644 --- a/store/rootmultistore.go +++ b/store/rootmultistore.go @@ -462,8 +462,7 @@ func commitStores(version int64, storeMap map[StoreKey]CommitStore) commitInfo { storemap := make(map[string]CommitStore) - fmt.Println("CommitStores!!!!!!") - for key,store:= range storeMap{ + for key, store := range storeMap { fmt.Println(key) storemap[key.Name()] = store } @@ -473,17 +472,16 @@ func commitStores(version int64, storeMap map[StoreKey]CommitStore) commitInfo { if upgrade != nil { upgradeStore := upgrade.(KVStore) - bz := upgradeStore.Get([]byte("k/")) //CurrentStoreKey - storekeys := string(bz) //splitby":" + bz := upgradeStore.Get([]byte("k/")) //CurrentStoreKey + storekeys := string(bz) //splitby":" storekeyslist := strings.Split(storekeys, ":") - fmt.Println(storekeyslist) storeInfos := make([]storeInfo, 0, len(storekeyslist)) for _, key := range storekeyslist { - if store,ok:= storemap[key]; ok{ + if store, ok := storemap[key]; ok { // Commit commitID := store.Commit() @@ -523,11 +521,9 @@ func commitStores(version int64, storeMap map[StoreKey]CommitStore) commitInfo { return ci } - - } -//////////////////// iris/cosmos-sdk end/////////////////////////// +//////////////////// iris/cosmos-sdk end/////////////////////////// // Gets commitInfo from disk. func getCommitInfo(db dbm.DB, ver int64) (commitInfo, error) { From 729adc09c0f24ffd56df2cd30eeb8f44973c1cf5 Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Thu, 2 Aug 2018 14:15:48 +0800 Subject: [PATCH 12/52] finish the simple parameterproposal --- x/gov/genesis.go | 14 +++++-- x/gov/keeper.go | 43 ------------------- x/gov/params.go | 91 +++++++++++++++++++++++++++++++++++++++++ x/gov/proposals.go | 49 ++++++++++++++++++++++ x/gov/proposals_test.go | 56 +++++++++++++++++++++++++ 5 files changed, 206 insertions(+), 47 deletions(-) create mode 100644 x/gov/params.go create mode 100644 x/gov/proposals_test.go diff --git a/x/gov/genesis.go b/x/gov/genesis.go index 47af7b81bee1..08c0ff21b4a2 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -47,9 +47,15 @@ func InitGenesis(ctx sdk.Context, k Keeper, data GenesisState) { // TODO: Handle this with #870 panic(err) } - k.setDepositProcedure(ctx, data.DepositProcedure) - k.setVotingProcedure(ctx, data.VotingProcedure) - k.setTallyingProcedure(ctx, data.TallyingProcedure) + + k.setDepositProcedureDeposit(ctx, data.DepositProcedure.MinDeposit) + k.setDepositProcedureMaxDepositPeriod(ctx, data.DepositProcedure.MaxDepositPeriod) + + k.setVotingProcedureVotingPeriod(ctx, data.VotingProcedure.VotingPeriod) + + k.setTallyingProcedure(ctx, ParamStoreKeyTallyingProcedureThreshold, data.TallyingProcedure.Threshold) + k.setTallyingProcedure(ctx, ParamStoreKeyTallyingProcedureVeto, data.TallyingProcedure.Veto) + k.setTallyingProcedure(ctx, ParamStoreKeyTallyingProcedurePenalty, data.TallyingProcedure.GovernancePenalty) } // WriteGenesis - output genesis parameters @@ -65,4 +71,4 @@ func WriteGenesis(ctx sdk.Context, k Keeper) GenesisState { VotingProcedure: votingProcedure, TallyingProcedure: tallyingProcedure, } -} \ No newline at end of file +} diff --git a/x/gov/keeper.go b/x/gov/keeper.go index 4f49cac582c6..aae1ac3a4d4c 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -7,13 +7,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/params" ) -// nolint -const ( - ParamStoreKeyDepositProcedure = "gov/depositprocedure" - ParamStoreKeyVotingProcedure = "gov/votingprocedure" - ParamStoreKeyTallyingProcedure = "gov/tallyingprocedure" -) - // Governance Keeper type Keeper struct { // The reference to the ParamSetter to get and set Global Params @@ -137,42 +130,6 @@ func (keeper Keeper) activateVotingPeriod(ctx sdk.Context, proposal Proposal) { keeper.ActiveProposalQueuePush(ctx, proposal) } -// ===================================================== -// Procedures - -// Returns the current Deposit Procedure from the global param store -func (keeper Keeper) GetDepositProcedure(ctx sdk.Context) DepositProcedure { - var depositProcedure DepositProcedure - keeper.ps.Get(ctx, ParamStoreKeyDepositProcedure, &depositProcedure) - return depositProcedure -} - -// Returns the current Voting Procedure from the global param store -func (keeper Keeper) GetVotingProcedure(ctx sdk.Context) VotingProcedure { - var votingProcedure VotingProcedure - keeper.ps.Get(ctx, ParamStoreKeyVotingProcedure, &votingProcedure) - return votingProcedure -} - -// Returns the current Tallying Procedure from the global param store -func (keeper Keeper) GetTallyingProcedure(ctx sdk.Context) TallyingProcedure { - var tallyingProcedure TallyingProcedure - keeper.ps.Get(ctx, ParamStoreKeyTallyingProcedure, &tallyingProcedure) - return tallyingProcedure -} - -func (keeper Keeper) setDepositProcedure(ctx sdk.Context, depositProcedure DepositProcedure) { - keeper.ps.Set(ctx, ParamStoreKeyDepositProcedure, &depositProcedure) -} - -func (keeper Keeper) setVotingProcedure(ctx sdk.Context, votingProcedure VotingProcedure) { - keeper.ps.Set(ctx, ParamStoreKeyVotingProcedure, &votingProcedure) -} - -func (keeper Keeper) setTallyingProcedure(ctx sdk.Context, tallyingProcedure TallyingProcedure) { - keeper.ps.Set(ctx, ParamStoreKeyTallyingProcedure, &tallyingProcedure) -} - // ===================================================== // Votes diff --git a/x/gov/params.go b/x/gov/params.go new file mode 100644 index 000000000000..878f6aba765c --- /dev/null +++ b/x/gov/params.go @@ -0,0 +1,91 @@ +package gov + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "strconv" + "strings" +) + +// nolint +const ( + ParamStoreKeyDepositProcedureDeposit = "gov/depositprocedure/deposit" + ParamStoreKeyDepositProcedureMaxDepositPeriod = "gov/depositprocedure/maxDepositPeriod" + + ParamStoreKeyVotingProcedureVotingPeriod = "gov/votingprocedure/votingPeriod" + + ParamStoreKeyTallyingProcedureThreshold = "gov/tallyingprocedure/threshold" + ParamStoreKeyTallyingProcedureVeto = "gov/tallyingprocedure/veto" + ParamStoreKeyTallyingProcedurePenalty = "gov/tallyingprocedure/penalty" +) + +// ===================================================== +// Procedures + +// Returns the current Deposit Procedure from the global param store +func (keeper Keeper) GetDepositProcedure(ctx sdk.Context) DepositProcedure { + return DepositProcedure{ + MinDeposit: keeper.getDepositProcedureDeposit(ctx), + MaxDepositPeriod: keeper.getDepositProcedureMaxDepositPeriod(ctx), + } +} + +// Returns the current Voting Procedure from the global param store +func (keeper Keeper) GetVotingProcedure(ctx sdk.Context) VotingProcedure { + return VotingProcedure{ + VotingPeriod: keeper.getVotingProcedureVotingPeriod(ctx), + } +} + +// Returns the current Tallying Procedure from the global param store +func (keeper Keeper) GetTallyingProcedure(ctx sdk.Context) TallyingProcedure { + return TallyingProcedure{ + Threshold: keeper.getTallyingProcedure(ctx, ParamStoreKeyTallyingProcedureThreshold), + Veto: keeper.getTallyingProcedure(ctx, ParamStoreKeyTallyingProcedureVeto), + GovernancePenalty: keeper.getTallyingProcedure(ctx, ParamStoreKeyTallyingProcedurePenalty), + } +} + +func (keeper Keeper) setDepositProcedureDeposit(ctx sdk.Context, Deposit sdk.Coins) { + data := Deposit.String() + keeper.ps.Set(ctx, ParamStoreKeyDepositProcedureDeposit, &data) +} + +func (keeper Keeper) setDepositProcedureMaxDepositPeriod(ctx sdk.Context, MaxDepositPeriod int64) { + keeper.ps.Set(ctx, ParamStoreKeyDepositProcedureMaxDepositPeriod, &MaxDepositPeriod) +} + +func (keeper Keeper) setVotingProcedureVotingPeriod(ctx sdk.Context, VotingPeriod int64) { + keeper.ps.Set(ctx, ParamStoreKeyVotingProcedureVotingPeriod, &VotingPeriod) +} + +func (keeper Keeper) setTallyingProcedure(ctx sdk.Context, key string, rat sdk.Rat) { + str := rat.String() + keeper.ps.Set(ctx, key, &str) +} + +func (keeper Keeper) getDepositProcedureDeposit(ctx sdk.Context) (Deposit sdk.Coins) { + var data string + keeper.ps.Get(ctx, ParamStoreKeyDepositProcedureDeposit, &data) + Deposit, _ = sdk.ParseCoins(data) + return +} + +func (keeper Keeper) getDepositProcedureMaxDepositPeriod(ctx sdk.Context) (MaxDepositPeriod int64) { + keeper.ps.Get(ctx, ParamStoreKeyDepositProcedureMaxDepositPeriod, &MaxDepositPeriod) + return +} + +func (keeper Keeper) getVotingProcedureVotingPeriod(ctx sdk.Context) (VotingPeriod int64) { + keeper.ps.Get(ctx, ParamStoreKeyVotingProcedureVotingPeriod, &VotingPeriod) + return +} + +func (keeper Keeper) getTallyingProcedure(ctx sdk.Context, key string) sdk.Rat { + var data string + keeper.ps.Get(ctx, key, &data) + str := strings.Split(data, "/") + x, _ := strconv.ParseInt(str[0], 10, 64) + y, _ := strconv.ParseInt(str[1], 10, 64) + return sdk.NewRat(x, y) + +} diff --git a/x/gov/proposals.go b/x/gov/proposals.go index 61aafe577c73..c3f397feb1ad 100644 --- a/x/gov/proposals.go +++ b/x/gov/proposals.go @@ -35,6 +35,8 @@ type Proposal interface { GetVotingStartBlock() int64 SetVotingStartBlock(int64) + + Execute(ctx sdk.Context, k Keeper) error } // checks if two proposals are equal @@ -90,6 +92,53 @@ func (tp TextProposal) GetVotingStartBlock() int64 { return tp.V func (tp *TextProposal) SetVotingStartBlock(votingStartBlock int64) { tp.VotingStartBlock = votingStartBlock } +func (tp *TextProposal) Execute(ctx sdk.Context, k Keeper) error { return nil } + +//////////////////// iris/cosmos-sdk begin /////////////////////////// +type Op byte + +const ( + Add Op = 0x01 + Del Op = 0x02 + Update Op = 0x03 +) + +type Data struct { + Key string `json:"key"` + Value interface{} `json:"value"` + Op Op `json:"op"` +} + +type ParameterProposal struct { + TextProposal + Datas []Data `json:"datas"` +} + +func (pp *ParameterProposal) Execute(ctx sdk.Context, k Keeper) error { + + logger := ctx.Logger().With("module", "x/gov") + + if len(pp.Datas) == 0 { + return errors.New("ParameterProposal's data is empty") + } + for _, data := range pp.Datas { + if data.Op == Add { + k.ps.Set(ctx, data.Key, data.Value) + } else if data.Op == Update { + bz := k.ps.GetRaw(ctx, data.Key) + if bz == nil || len(bz) == 0 { + logger.Error("Execute ParameterProposal ", "err", "Parameter "+data.Key+" is not exist") + } else { + k.ps.Set(ctx, data.Key, data.Value) + } + } else { + + } + } + return nil +} + +//////////////////// iris/cosmos-sdk end /////////////////////////// //----------------------------------------------------------- // ProposalQueue diff --git a/x/gov/proposals_test.go b/x/gov/proposals_test.go new file mode 100644 index 000000000000..ca8143af5ea2 --- /dev/null +++ b/x/gov/proposals_test.go @@ -0,0 +1,56 @@ +package gov + +import ( + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/magiconair/properties/assert" + abci "github.com/tendermint/tendermint/abci/types" + "testing" +) + +const ( + ParamStoreKeyDepositProcedureDepositAmount = "gov/depositprocedure/depositAmount" + ParamStoreKeyDepositProcedureDepositDenom = "gov/depositprocedure/depositDenom" +) + +func TestParameterProposal(t *testing.T) { + mapp, keeper, _, _, _, _ := getMockApp(t, 0) + + mapp.BeginBlock(abci.RequestBeginBlock{}) + ctx := mapp.BaseApp.NewContext(false, abci.Header{}) + + fmt.Println(keeper.GetDepositProcedure(ctx)) + fmt.Println(keeper.GetTallyingProcedure(ctx)) + fmt.Println(keeper.GetVotingProcedure(ctx)) + + pp := ParameterProposal{ + Datas: []Data{ + {Key: ParamStoreKeyDepositProcedureDeposit, Value: "200iris", Op: Update}, + {Key: ParamStoreKeyDepositProcedureDepositAmount, Value: "200", Op: Update}, + {Key: ParamStoreKeyDepositProcedureDepositDenom, Value: "iris", Op: Update}, + {Key: ParamStoreKeyDepositProcedureMaxDepositPeriod, Value: 100, Op: Update}, + {Key: ParamStoreKeyVotingProcedureVotingPeriod, Value: 200, Op: Update}, + {Key: ParamStoreKeyTallyingProcedurePenalty, Value: "1/50", Op: Update}, + {Key: ParamStoreKeyTallyingProcedureVeto, Value: "1/4", Op: Update}, + {Key: ParamStoreKeyTallyingProcedureThreshold, Value: "2/8", Op: Update}, + }, + } + + pp.Execute(ctx, keeper) + assert.Equal(t, keeper.GetDepositProcedure(ctx), + DepositProcedure{ + MinDeposit: sdk.Coins{sdk.NewCoin("iris", 200)}, + MaxDepositPeriod: 100}) + + assert.Equal(t, keeper.GetVotingProcedure(ctx), + VotingProcedure{ + VotingPeriod: 200, + }) + fmt.Println(keeper.GetTallyingProcedure(ctx)) + assert.Equal(t, keeper.GetTallyingProcedure(ctx), + TallyingProcedure{ + Threshold: sdk.NewRat(2, 8), + Veto: sdk.NewRat(1, 4), + GovernancePenalty: sdk.NewRat(1, 50), + }) +} From bbf058ed0800a0bbb8725458fe6c40abaa63519d Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Fri, 3 Aug 2018 14:16:09 +0800 Subject: [PATCH 13/52] add fee refund, deducted fee: fee*gasUsed/gasWanted, add gasPrice threshold --- baseapp/baseapp.go | 12 ++++- cmd/gaia/app/app.go | 1 + types/handler.go | 1 + x/auth/ante.go | 99 ++++++++++++++++++++++++++---------- x/auth/feekeeper.go | 66 ++++++++++++++---------- x/bank/client/rest/sendtx.go | 2 + 6 files changed, 125 insertions(+), 56 deletions(-) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 40b3c2bc1777..64d581245ad2 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -53,6 +53,7 @@ type BaseApp struct { // must be set txDecoder sdk.TxDecoder // unmarshal []byte into sdk.Tx anteHandler sdk.AnteHandler // ante handler for fee and auth + feeRefundHandler sdk.FeeRefundHandler // fee handler for fee refund // may be nil initChainer sdk.InitChainer // initialize state with validators and state blob @@ -177,6 +178,9 @@ func (app *BaseApp) SetEndBlocker(endBlocker sdk.EndBlocker) { func (app *BaseApp) SetAnteHandler(ah sdk.AnteHandler) { app.anteHandler = ah } +func (app *BaseApp) SetFeeRefundHandler(fh sdk.FeeRefundHandler) { + app.feeRefundHandler = fh +} func (app *BaseApp) SetAddrPeerFilter(pf sdk.PeerFilter) { app.addrPeerFilter = pf } @@ -589,7 +593,7 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk // meter so we initialize upfront. var gasWanted int64 ctx := app.getContextForAnte(mode, txBytes) - + originalCtx := ctx defer func() { if r := recover(); r != nil { switch rType := r.(type) { @@ -604,6 +608,9 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk result.GasWanted = gasWanted result.GasUsed = ctx.GasMeter().GasConsumed() + + // Refund unspent fee + app.feeRefundHandler(originalCtx, tx, result) }() var msgs = tx.GetMsgs() @@ -621,9 +628,10 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk } if !newCtx.IsZero() { ctx = newCtx + originalCtx = newCtx } - gasWanted = result.GasWanted + gasWanted = anteResult.GasWanted } // Keep the state in a transient CacheWrap in case processing the messages diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index b5e34a0004e8..6bf204875894 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -110,6 +110,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) + app.SetFeeRefundHandler(auth.NewFeeRefundHandler(app.accountMapper, app.feeCollectionKeeper)) app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing, app.keyGov, app.keyFeeCollection, app.keyParams) err := app.LoadLatestVersion(app.keyMain) if err != nil { diff --git a/types/handler.go b/types/handler.go index 3a50e0ce053f..82763a41880f 100644 --- a/types/handler.go +++ b/types/handler.go @@ -6,3 +6,4 @@ type Handler func(ctx Context, msg Msg) Result // AnteHandler authenticates transactions, before their internal messages are handled. // If newCtx.IsZero(), ctx is used instead. type AnteHandler func(ctx Context, tx Tx) (newCtx Context, result Result, abort bool) +type FeeRefundHandler func(ctx Context, tx Tx, result Result) diff --git a/x/auth/ante.go b/x/auth/ante.go index 53a76a320ff1..35c001980e72 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -21,7 +21,7 @@ func NewAnteHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.AnteHandler { return func( ctx sdk.Context, tx sdk.Tx, - ) (_ sdk.Context, _ sdk.Result, abort bool) { + ) (newCtx sdk.Context, res sdk.Result, abort bool) { // This AnteHandler requires Txs to be StdTxs stdTx, ok := tx.(StdTx) @@ -29,20 +29,35 @@ func NewAnteHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.AnteHandler { return ctx, sdk.ErrInternal("tx must be StdTx").Result(), true } + // set the gas meter + newCtx = ctx.WithGasMeter(sdk.NewGasMeter(stdTx.Fee.Gas)) + + defer func() { + if r := recover(); r != nil { + switch rType := r.(type) { + case sdk.ErrorOutOfGas: + log := fmt.Sprintf("out of gas in location: %v", rType.Descriptor) + res = sdk.ErrOutOfGas(log).Result() + res.GasWanted = stdTx.Fee.Gas + res.GasUsed = newCtx.GasMeter().GasConsumed() + abort = true + default: + panic(r) + } + } + }() + err := validateBasic(stdTx) if err != nil { - return ctx, err.Result(), true + return newCtx, err.Result(), true } sigs := stdTx.GetSignatures() signerAddrs := stdTx.GetSigners() msgs := tx.GetMsgs() - // set the gas meter - ctx = ctx.WithGasMeter(sdk.NewGasMeter(stdTx.Fee.Gas)) - // charge gas for the memo - ctx.GasMeter().ConsumeGas(memoCostPerByte*sdk.Gas(len(stdTx.GetMemo())), "memo") + newCtx.GasMeter().ConsumeGas(memoCostPerByte*sdk.Gas(len(stdTx.GetMemo())), "memo") // Get the sign bytes (requires all account & sequence numbers and the fee) sequences := make([]int64, len(sigs)) @@ -53,49 +68,81 @@ func NewAnteHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.AnteHandler { } fee := stdTx.Fee - err = fck.FeePreprocess(ctx,fee.Amount) + err = fck.FeePreprocess(newCtx, fee.Amount, fee.Gas) if err != nil { - return ctx, err.Result(), true + return newCtx, err.Result(), true } // Check sig and nonce and collect signer accounts. var signerAccs = make([]Account, len(signerAddrs)) + var firstAccount Account for i := 0; i < len(sigs); i++ { signerAddr, sig := signerAddrs[i], sigs[i] // check signature, return account with incremented nonce - signBytes := StdSignBytes(ctx.ChainID(), accNums[i], sequences[i], fee, msgs, stdTx.GetMemo()) + signBytes := StdSignBytes(newCtx.ChainID(), accNums[i], sequences[i], fee, msgs, stdTx.GetMemo()) signerAcc, res := processSig( - ctx, am, + newCtx, am, signerAddr, sig, signBytes, ) if !res.IsOK() { - return ctx, res, true + return newCtx, res, true } - // first sig pays the fees - // TODO: Add min fees - // Can this function be moved outside of the loop? - if i == 0 && !fee.Amount.IsZero() { - ctx.GasMeter().ConsumeGas(deductFeesCost, "deductFees") - signerAcc, res = deductFees(signerAcc, fee) - if !res.IsOK() { - return ctx, res, true - } - fck.addCollectedFees(ctx, fee.Amount) + if i == 0 { + firstAccount = signerAcc } - // Save the account. - am.SetAccount(ctx, signerAcc) signerAccs[i] = signerAcc } + if firstAccount != nil { + newCtx.GasMeter().ConsumeGas(deductFeesCost, "deductFees") + firstAccount, res = deductFees(firstAccount, fee) + if !res.IsOK() { + return newCtx, res, true + } + // Save the account. + am.SetAccount(newCtx, firstAccount) + fck.addCollectedFees(newCtx, fee.Amount) + } + // cache the signer accounts in the context - ctx = WithSigners(ctx, signerAccs) + newCtx = WithSigners(newCtx, signerAccs) + + res.GasWanted = stdTx.Fee.Gas - // TODO: tx tags (?) + return newCtx, res, false // continue... + } +} - return ctx, sdk.Result{}, false // continue... +func NewFeeRefundHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.FeeRefundHandler { + return func(ctx sdk.Context, tx sdk.Tx, txResult sdk.Result) { + stdTx, ok := tx.(StdTx) + if !ok { + return + } + fee := stdTx.Fee + txAccounts := GetSigners(ctx) + if len(txAccounts) < 1 { + return + } + firstAccount := txAccounts[0] + if txResult.GasWanted <= txResult.GasUsed { + return + } + unusedGas := txResult.GasWanted - txResult.GasUsed + var refundCoins sdk.Coins + for _,coin := range fee.Amount { + newCoin := sdk.Coin{ + Denom: coin.Denom, + Amount: coin.Amount.Mul(sdk.NewInt(unusedGas)).Div(sdk.NewInt(txResult.GasWanted)), + } + refundCoins = append(refundCoins, newCoin) + } + firstAccount.SetCoins(firstAccount.GetCoins().Plus(refundCoins)) + am.SetAccount(ctx, firstAccount) + fck.refundCollectedFees(ctx, refundCoins) } } diff --git a/x/auth/feekeeper.go b/x/auth/feekeeper.go index 958622b84c62..25a4f0788793 100644 --- a/x/auth/feekeeper.go +++ b/x/auth/feekeeper.go @@ -4,14 +4,15 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/params" - "fmt" - ) + "fmt" +) var ( collectedFeesKey = []byte("collectedFees") - feeTokenKey = "fee/token" // fee/token - FeeThresholdKey = "fee/threshold" // fee/threshold - FeeExchangeRatePrefix = "fee/exchange/rate/" // fee/exchange/rate/ + NativeFeeTokenKey = "feeToken/native" + NativeGasPriceThresholdKey = "feeToken/native/gasPrice/threshold" + FeeExchangeRatePrefix = "feeToken/derived/exchange/rate/" // key = feeToken/derived/exchange/rate/, rate = BigInt(value)/10^18 + Precision = int64(1000000000000000000) //10^18 ) // This FeeCollectionKeeper handles collection of fees in the anteHandler @@ -64,68 +65,77 @@ func (fck FeeCollectionKeeper) addCollectedFees(ctx sdk.Context, coins sdk.Coins return newCoins } +func (fck FeeCollectionKeeper) refundCollectedFees(ctx sdk.Context, coins sdk.Coins) sdk.Coins { + newCoins := fck.GetCollectedFees(ctx).Minus(coins) + fck.setCollectedFees(ctx, newCoins) + + return newCoins +} + + // Clears the collected Fee Pool func (fck FeeCollectionKeeper) ClearCollectedFees(ctx sdk.Context) { fck.setCollectedFees(ctx, sdk.Coins{}) } -func (fck FeeCollectionKeeper) FeePreprocess(ctx sdk.Context, coins sdk.Coins) sdk.Error { - feeToken, err := fck.getter.GetString(ctx, feeTokenKey) +func (fck FeeCollectionKeeper) FeePreprocess(ctx sdk.Context, coins sdk.Coins, gasLimit int64) sdk.Error { + if gasLimit <=0 { + return sdk.ErrInternal(fmt.Sprintf("gaslimit %s should be larger than 0", gasLimit)) + } + nativeFeeToken, err := fck.getter.GetString(ctx, NativeFeeTokenKey) if err != nil { panic(err) } - feeThreshold, err := fck.getter.GetInt(ctx, FeeThresholdKey) + nativeGasPriceThreshold, err := fck.getter.GetInt(ctx, NativeGasPriceThresholdKey) if err != nil { panic(err) } - equivalentTotalFee := sdk.ZeroRat() + + equivalentTotalFee := sdk.NewInt(0) for _,coin := range coins { - if coin.Denom != feeToken { + if coin.Denom != nativeFeeToken { exchangeRateKey := FeeExchangeRatePrefix + coin.Denom - rateBytes := fck.getter.GetRaw(ctx, exchangeRateKey) - if rateBytes == nil { - continue - } - var exchangeRate sdk.Rat - err := fck.cdc.UnmarshalBinary(rateBytes, &exchangeRate) + rate, err := fck.getter.GetInt(ctx, exchangeRateKey) if err != nil { panic(err) } - equivalentFee := exchangeRate.Mul(sdk.NewRatFromInt(coin.Amount, sdk.OneInt())) + + equivalentFee := coin.Amount.Mul(rate).Div(sdk.NewInt(Precision)) equivalentTotalFee = equivalentTotalFee.Add(equivalentFee) } else { - equivalentTotalFee = equivalentTotalFee.Add(sdk.NewRatFromInt(coin.Amount, sdk.OneInt())) + equivalentTotalFee = equivalentTotalFee.Add(coin.Amount) } } - if equivalentTotalFee.LT(sdk.NewRatFromInt(feeThreshold, sdk.OneInt())) { - return sdk.ErrInsufficientCoins(fmt.Sprintf("equivalent total fee %s is less than threshold %s", equivalentTotalFee.String(), feeThreshold)) + gasPrice := equivalentTotalFee.Div(sdk.NewInt(gasLimit)) + if gasPrice.LT(nativeGasPriceThreshold) { + return sdk.ErrInsufficientCoins(fmt.Sprintf("gas price %s is less than threshold %s", gasPrice.String(), nativeGasPriceThreshold.String())) } return nil } type GenesisState struct { - FeeToken string `json:"fee_token"` - Threshold int64 `json:"fee_threshold"` + FeeTokenNative string `json:"fee_token_native"` + GasPriceThreshold int64 `json:"gas_price_threshold"` } func DefaultGenesisStateForTest() GenesisState { return GenesisState{ - FeeToken: "iGas", - Threshold: 0, + FeeTokenNative: "atom", + GasPriceThreshold: 0, } } func DefaultGenesisState() GenesisState { return GenesisState{ - FeeToken: "iGas", - Threshold: 100, + FeeTokenNative: "atom", + GasPriceThreshold: 5, } } func InitGenesis(ctx sdk.Context, setter params.Setter, data GenesisState) { - setter.SetString(ctx, feeTokenKey, data.FeeToken) - setter.SetInt(ctx, FeeThresholdKey, sdk.NewInt(data.Threshold)) + setter.SetString(ctx, NativeFeeTokenKey, data.FeeTokenNative) + setter.SetInt(ctx, NativeGasPriceThresholdKey, sdk.NewInt(data.GasPriceThreshold)) } \ No newline at end of file diff --git a/x/bank/client/rest/sendtx.go b/x/bank/client/rest/sendtx.go index 872b3cfe360c..e4b910ce118b 100644 --- a/x/bank/client/rest/sendtx.go +++ b/x/bank/client/rest/sendtx.go @@ -29,6 +29,7 @@ type sendBody struct { AccountNumber int64 `json:"account_number"` Sequence int64 `json:"sequence"` Gas int64 `json:"gas"` + Fee string `json:"fee"` } var msgCdc = wire.NewCodec() @@ -82,6 +83,7 @@ func SendRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreCont // add gas to context ctx = ctx.WithGas(m.Gas) + ctx = ctx.WithFee(m.Fee) // add chain-id to context ctx = ctx.WithChainID(m.ChainID) From 4cc21d0fc51349eb166fd3f075a65fe3b9095197 Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Fri, 3 Aug 2018 15:39:43 +0800 Subject: [PATCH 14/52] Fix a bug in send tokens --- x/auth/ante.go | 3 ++- x/auth/feekeeper.go | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/x/auth/ante.go b/x/auth/ante.go index 35c001980e72..2999d4491b9c 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -140,7 +140,8 @@ func NewFeeRefundHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.FeeRefun } refundCoins = append(refundCoins, newCoin) } - firstAccount.SetCoins(firstAccount.GetCoins().Plus(refundCoins)) + coins := am.GetAccount(ctx, firstAccount.GetAddress()).GetCoins() + firstAccount.SetCoins(coins.Plus(refundCoins)) am.SetAccount(ctx, firstAccount) fck.refundCollectedFees(ctx, refundCoins) } diff --git a/x/auth/feekeeper.go b/x/auth/feekeeper.go index 25a4f0788793..98c47cff9fcc 100644 --- a/x/auth/feekeeper.go +++ b/x/auth/feekeeper.go @@ -67,6 +67,9 @@ func (fck FeeCollectionKeeper) addCollectedFees(ctx sdk.Context, coins sdk.Coins func (fck FeeCollectionKeeper) refundCollectedFees(ctx sdk.Context, coins sdk.Coins) sdk.Coins { newCoins := fck.GetCollectedFees(ctx).Minus(coins) + if !newCoins.IsNotNegative() { + panic("fee collector contains negative coins") + } fck.setCollectedFees(ctx, newCoins) return newCoins From 870cc917aef66069de11ca35859659958f0716d8 Mon Sep 17 00:00:00 2001 From: chengsilei Date: Sat, 4 Aug 2018 20:59:00 +0800 Subject: [PATCH 15/52] Load not used store in the new version --- store/rootmultistore.go | 13 +++++++-- store/rootmultistore_test.go | 55 ++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/store/rootmultistore.go b/store/rootmultistore.go index 56f89b29bbeb..e9c1a35040f4 100644 --- a/store/rootmultistore.go +++ b/store/rootmultistore.go @@ -129,10 +129,17 @@ func (rs *rootMultiStore) LoadVersion(ver int64) error { newStores[key] = store } - // If any CommitStoreLoaders were not used, return error. - for key := range rs.storesParams { + // If any CommitStoreLoaders were not used, create the new one. + for key, storeParams := range rs.storesParams { if _, ok := newStores[key]; !ok { - return fmt.Errorf("unused CommitStoreLoader: %v", key) + //////////////////// iris/cosmos-sdk begin /////////////////////////// + id := CommitID{} + store, err := rs.loadCommitStoreFromParams(id, storeParams) + if err != nil { + return fmt.Errorf("failed to load rootMultiStore: %v", err) + } + newStores[key] = store + //////////////////// iris/cosmos-sdk end /////////////////////////// } } diff --git a/store/rootmultistore_test.go b/store/rootmultistore_test.go index f564114626aa..ed1a26d82cb7 100644 --- a/store/rootmultistore_test.go +++ b/store/rootmultistore_test.go @@ -76,6 +76,43 @@ func TestMultistoreCommitLoad(t *testing.T) { checkStore(t, store, commitID, commitID) } +//////////////////// iris/cosmos-sdk begin /////////////////////////// +func TestCommitStoreLoadersNotUsed(t *testing.T) { + var db dbm.DB = dbm.NewMemDB() + if useDebugDB { + db = dbm.NewDebugDB("CMS", db) + } + store := newMultiStoreWithMounts(db) + err := store.LoadLatestVersion() + require.Nil(t, err) + + // New store has empty last commit. + commitID := CommitID{} + checkStore(t, store, commitID, commitID) + + // Make sure we can get stores by name. + s1 := store.getStoreByName("store1") + require.NotNil(t, s1) + s3 := store.getStoreByName("store3") + require.NotNil(t, s3) + s5 := store.getStoreByName("store5") + require.Nil(t, s5) + + store = newMultiStoreWithMountsNewVersion(db) + err = store.LoadLatestVersion() + require.Nil(t, err) + + // Make sure we can get stores by name. + s1 = store.getStoreByName("store1") + require.NotNil(t, s1) + s3 = store.getStoreByName("store3") + require.NotNil(t, s3) + s5 = store.getStoreByName("store5") + require.NotNil(t, s5) +} + +//////////////////// iris/cosmos-sdk end /////////////////////////// + func TestParsePath(t *testing.T) { _, _, err := parsePath("foo") require.Error(t, err) @@ -173,6 +210,24 @@ func newMultiStoreWithMounts(db dbm.DB) *rootMultiStore { return store } +//////////////////// iris/cosmos-sdk begin /////////////////////////// +func newMultiStoreWithMountsNewVersion(db dbm.DB) *rootMultiStore { + store := NewCommitMultiStore(db) + store.MountStoreWithDB( + sdk.NewKVStoreKey("store1"), sdk.StoreTypeIAVL, db) + store.MountStoreWithDB( + sdk.NewKVStoreKey("store2"), sdk.StoreTypeIAVL, db) + store.MountStoreWithDB( + sdk.NewKVStoreKey("store3"), sdk.StoreTypeIAVL, db) + store.MountStoreWithDB( + sdk.NewKVStoreKey("store4"), sdk.StoreTypeIAVL, db) + store.MountStoreWithDB( + sdk.NewKVStoreKey("store5"), sdk.StoreTypeIAVL, db) + return store +} + +//////////////////// iris/cosmos-sdk end /////////////////////////// + func checkStore(t *testing.T, store *rootMultiStore, expect, got CommitID) { require.Equal(t, expect, got) require.Equal(t, expect, store.LastCommitID()) From 314fc6a365fc61553f5a25186bc8a985c9a1323f Mon Sep 17 00:00:00 2001 From: chengsilei Date: Sat, 4 Aug 2018 21:37:32 +0800 Subject: [PATCH 16/52] fix unit test compile errors. Test result: Tests failed 12 4 cases under /cmd/gaia/cli_test also failed in cosmos other 8 cases failed due to the address fmt changed from "cosmosaccaddr" to "faa" --- cmd/gaia/cmd/gaiadebug/hack.go | 6 +++--- docs/sdk/core/examples/app1.go | 2 +- docs/sdk/core/examples/app2.go | 4 ++-- docs/sdk/core/examples/app3.go | 2 +- docs/sdk/core/examples/app4.go | 2 +- examples/basecoin/app/app.go | 4 ++-- examples/democoin/app/app.go | 12 ++++++------ examples/democoin/x/cool/app_test.go | 2 +- examples/democoin/x/pow/app_test.go | 2 +- examples/kvstore/main.go | 2 +- server/mock/app.go | 2 +- x/bank/bench_test.go | 2 +- x/ibc/app_test.go | 2 +- x/mock/app_test.go | 2 +- x/slashing/app_test.go | 4 ++-- x/stake/app_test.go | 2 +- 16 files changed, 26 insertions(+), 26 deletions(-) diff --git a/cmd/gaia/cmd/gaiadebug/hack.go b/cmd/gaia/cmd/gaiadebug/hack.go index 2e2b96205210..ddf2888d4a2b 100644 --- a/cmd/gaia/cmd/gaiadebug/hack.go +++ b/cmd/gaia/cmd/gaiadebug/hack.go @@ -176,9 +176,9 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.BaseAp // register message routes app.Router(). - AddRoute("bank", bank.NewHandler(app.coinKeeper)). - AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)). - AddRoute("stake", stake.NewHandler(app.stakeKeeper)) + AddRoute("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.coinKeeper)). + AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). + AddRoute("stake", []*sdk.KVStoreKey{app.keySlashing}, stake.NewHandler(app.stakeKeeper)) // initialize BaseApp app.SetInitChainer(app.initChainer) diff --git a/docs/sdk/core/examples/app1.go b/docs/sdk/core/examples/app1.go index b208f75cf7e5..f65de7d9f982 100644 --- a/docs/sdk/core/examples/app1.go +++ b/docs/sdk/core/examples/app1.go @@ -32,7 +32,7 @@ func NewApp1(logger log.Logger, db dbm.DB) *bapp.BaseApp { // Register message routes. // Note the handler gets access to the account store. app.Router(). - AddRoute("send", handleMsgSend(keyAccount)) + AddRoute("send", []*sdk.KVStoreKey{keyAccount}, handleMsgSend(keyAccount)) // Mount stores and load the latest state. app.MountStoresIAVL(keyAccount) diff --git a/docs/sdk/core/examples/app2.go b/docs/sdk/core/examples/app2.go index 12eab1c510b1..0af846d79b03 100644 --- a/docs/sdk/core/examples/app2.go +++ b/docs/sdk/core/examples/app2.go @@ -50,8 +50,8 @@ func NewApp2(logger log.Logger, db dbm.DB) *bapp.BaseApp { // Register message routes. // Note the handler gets access to the account store. app.Router(). - AddRoute("send", handleMsgSend(keyAccount)). - AddRoute("issue", handleMsgIssue(keyAccount, keyIssue)) + AddRoute("send", []*sdk.KVStoreKey{keyAccount}, handleMsgSend(keyAccount)). + AddRoute("issue",[]*sdk.KVStoreKey{keyIssue}, handleMsgIssue(keyAccount, keyIssue)) // Mount stores and load the latest state. app.MountStoresIAVL(keyAccount, keyIssue) diff --git a/docs/sdk/core/examples/app3.go b/docs/sdk/core/examples/app3.go index 853ad687e17d..33bd06f8f3de 100644 --- a/docs/sdk/core/examples/app3.go +++ b/docs/sdk/core/examples/app3.go @@ -37,7 +37,7 @@ func NewApp3(logger log.Logger, db dbm.DB) *bapp.BaseApp { // Register message routes. // Note the handler gets access to app.Router(). - AddRoute("send", bank.NewHandler(coinKeeper)) + AddRoute("send", []*sdk.KVStoreKey{keyAccount}, bank.NewHandler(coinKeeper)) // Mount stores and load the latest state. app.MountStoresIAVL(keyAccount, keyFees) diff --git a/docs/sdk/core/examples/app4.go b/docs/sdk/core/examples/app4.go index a8ef37cee5a5..72529996d601 100644 --- a/docs/sdk/core/examples/app4.go +++ b/docs/sdk/core/examples/app4.go @@ -43,7 +43,7 @@ func NewApp4(logger log.Logger, db dbm.DB) *bapp.BaseApp { // Register message routes. // Note the handler gets access to the account store. app.Router(). - AddRoute("send", bank.NewHandler(coinKeeper)) + AddRoute("send", []*sdk.KVStoreKey{keyAccount}, bank.NewHandler(coinKeeper)) // Mount stores and load the latest state. app.MountStoresIAVL(keyAccount, keyFees) diff --git a/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index 14d4550d326e..ddeea64186cf 100644 --- a/examples/basecoin/app/app.go +++ b/examples/basecoin/app/app.go @@ -70,8 +70,8 @@ func NewBasecoinApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.Ba // register message routes app.Router(). - AddRoute("bank", bank.NewHandler(app.coinKeeper)). - AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)) + AddRoute("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.coinKeeper)). + AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)) // perform initialization logic app.SetInitChainer(app.initChainer) diff --git a/examples/democoin/app/app.go b/examples/democoin/app/app.go index 51d10002a726..b6328efcbd9c 100644 --- a/examples/democoin/app/app.go +++ b/examples/democoin/app/app.go @@ -81,12 +81,12 @@ func NewDemocoinApp(logger log.Logger, db dbm.DB) *DemocoinApp { app.ibcMapper = ibc.NewMapper(app.cdc, app.capKeyIBCStore, app.RegisterCodespace(ibc.DefaultCodespace)) app.stakeKeeper = simplestake.NewKeeper(app.capKeyStakingStore, app.coinKeeper, app.RegisterCodespace(simplestake.DefaultCodespace)) app.Router(). - AddRoute("bank", bank.NewHandler(app.coinKeeper)). - AddRoute("cool", cool.NewHandler(app.coolKeeper)). - AddRoute("pow", app.powKeeper.Handler). - AddRoute("sketchy", sketchy.NewHandler()). - AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)). - AddRoute("simplestake", simplestake.NewHandler(app.stakeKeeper)) + AddRoute("bank", []*sdk.KVStoreKey{app.capKeyAccountStore}, bank.NewHandler(app.coinKeeper)). + AddRoute("cool", []*sdk.KVStoreKey{app.capKeyAccountStore, app.capKeyMainStore}, cool.NewHandler(app.coolKeeper)). + AddRoute("pow", []*sdk.KVStoreKey{app.capKeyPowStore}, app.powKeeper.Handler). + AddRoute("sketchy", []*sdk.KVStoreKey{}, sketchy.NewHandler()). + AddRoute("ibc", []*sdk.KVStoreKey{app.capKeyIBCStore, app.capKeyAccountStore}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). + AddRoute("simplestake", []*sdk.KVStoreKey{app.capKeyStakingStore}, simplestake.NewHandler(app.stakeKeeper)) // Initialize BaseApp. app.SetInitChainer(app.initChainerFn(app.coolKeeper, app.powKeeper)) diff --git a/examples/democoin/x/cool/app_test.go b/examples/democoin/x/cool/app_test.go index 71b4202bc332..9a5f0e141a93 100644 --- a/examples/democoin/x/cool/app_test.go +++ b/examples/democoin/x/cool/app_test.go @@ -51,7 +51,7 @@ func getMockApp(t *testing.T) *mock.App { keyCool := sdk.NewKVStoreKey("cool") coinKeeper := bank.NewKeeper(mapp.AccountMapper) keeper := NewKeeper(keyCool, coinKeeper, mapp.RegisterCodespace(DefaultCodespace)) - mapp.Router().AddRoute("cool", NewHandler(keeper)) + mapp.Router().AddRoute("cool", []*sdk.KVStoreKey{keyCool}, NewHandler(keeper)) mapp.SetInitChainer(getInitChainer(mapp, keeper, "ice-cold")) diff --git a/examples/democoin/x/pow/app_test.go b/examples/democoin/x/pow/app_test.go index 783f13d57bb6..e38c6ecc14cf 100644 --- a/examples/democoin/x/pow/app_test.go +++ b/examples/democoin/x/pow/app_test.go @@ -28,7 +28,7 @@ func getMockApp(t *testing.T) *mock.App { coinKeeper := bank.NewKeeper(mapp.AccountMapper) config := Config{"pow", 1} keeper := NewKeeper(keyPOW, config, coinKeeper, mapp.RegisterCodespace(DefaultCodespace)) - mapp.Router().AddRoute("pow", keeper.Handler) + mapp.Router().AddRoute("pow", []*sdk.KVStoreKey{keyPOW}, keeper.Handler) mapp.SetInitChainer(getInitChainer(mapp, keeper)) diff --git a/examples/kvstore/main.go b/examples/kvstore/main.go index 47416da05706..14de13fb5d26 100644 --- a/examples/kvstore/main.go +++ b/examples/kvstore/main.go @@ -41,7 +41,7 @@ func main() { baseApp.SetTxDecoder(decodeTx) // Set a handler Route. - baseApp.Router().AddRoute("kvstore", Handler(capKeyMainStore)) + baseApp.Router().AddRoute("kvstore", []*sdk.KVStoreKey{capKeyMainStore}, Handler(capKeyMainStore)) // Load latest version. if err := baseApp.LoadLatestVersion(capKeyMainStore); err != nil { diff --git a/server/mock/app.go b/server/mock/app.go index 5229da41eeb9..91514b6e94a2 100644 --- a/server/mock/app.go +++ b/server/mock/app.go @@ -41,7 +41,7 @@ func NewApp(rootDir string, logger log.Logger) (abci.Application, error) { baseApp.SetInitChainer(InitChainer(capKeyMainStore)) // Set a handler Route. - baseApp.Router().AddRoute("kvstore", KVStoreHandler(capKeyMainStore)) + baseApp.Router().AddRoute("kvstore", []*sdk.KVStoreKey{capKeyMainStore}, KVStoreHandler(capKeyMainStore)) // Load latest version. if err := baseApp.LoadLatestVersion(capKeyMainStore); err != nil { diff --git a/x/bank/bench_test.go b/x/bank/bench_test.go index b90d56955134..d484a7208817 100644 --- a/x/bank/bench_test.go +++ b/x/bank/bench_test.go @@ -17,7 +17,7 @@ func getBenchmarkMockApp() (*mock.App, error) { RegisterWire(mapp.Cdc) coinKeeper := NewKeeper(mapp.AccountMapper) - mapp.Router().AddRoute("bank", NewHandler(coinKeeper)) + mapp.Router().AddRoute("bank", []*sdk.KVStoreKey{}, NewHandler(coinKeeper)) err := mapp.CompleteSetup([]*sdk.KVStoreKey{}) return mapp, err diff --git a/x/ibc/app_test.go b/x/ibc/app_test.go index d853c798700a..07aab546587c 100644 --- a/x/ibc/app_test.go +++ b/x/ibc/app_test.go @@ -22,7 +22,7 @@ func getMockApp(t *testing.T) *mock.App { keyIBC := sdk.NewKVStoreKey("ibc") ibcMapper := NewMapper(mapp.Cdc, keyIBC, mapp.RegisterCodespace(DefaultCodespace)) coinKeeper := bank.NewKeeper(mapp.AccountMapper) - mapp.Router().AddRoute("ibc", NewHandler(ibcMapper, coinKeeper)) + mapp.Router().AddRoute("ibc", []*sdk.KVStoreKey{keyIBC}, NewHandler(ibcMapper, coinKeeper)) require.NoError(t, mapp.CompleteSetup([]*sdk.KVStoreKey{keyIBC})) return mapp diff --git a/x/mock/app_test.go b/x/mock/app_test.go index 0c548280aea4..173f9c4ab1fc 100644 --- a/x/mock/app_test.go +++ b/x/mock/app_test.go @@ -40,7 +40,7 @@ func (tx testMsg) ValidateBasic() sdk.Error { func getMockApp(t *testing.T) *App { mApp := NewApp() - mApp.Router().AddRoute(msgType, func(ctx sdk.Context, msg sdk.Msg) (res sdk.Result) { return }) + mApp.Router().AddRoute(msgType, []*sdk.KVStoreKey{}, func(ctx sdk.Context, msg sdk.Msg) (res sdk.Result) { return }) require.NoError(t, mApp.CompleteSetup([]*sdk.KVStoreKey{})) return mApp diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index e7b660d15e08..936713fa8694 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -29,8 +29,8 @@ func getMockApp(t *testing.T) (*mock.App, stake.Keeper, Keeper) { coinKeeper := bank.NewKeeper(mapp.AccountMapper) stakeKeeper := stake.NewKeeper(mapp.Cdc, keyStake, coinKeeper, mapp.RegisterCodespace(stake.DefaultCodespace)) keeper := NewKeeper(mapp.Cdc, keySlashing, stakeKeeper, mapp.RegisterCodespace(DefaultCodespace)) - mapp.Router().AddRoute("stake", stake.NewHandler(stakeKeeper)) - mapp.Router().AddRoute("slashing", NewHandler(keeper)) + mapp.Router().AddRoute("stake", []*sdk.KVStoreKey{keyStake}, stake.NewHandler(stakeKeeper)) + mapp.Router().AddRoute("slashing", []*sdk.KVStoreKey{keySlashing}, NewHandler(keeper)) mapp.SetEndBlocker(getEndBlocker(stakeKeeper)) mapp.SetInitChainer(getInitChainer(mapp, stakeKeeper)) diff --git a/x/stake/app_test.go b/x/stake/app_test.go index d1183e6c922b..29ef089c419d 100644 --- a/x/stake/app_test.go +++ b/x/stake/app_test.go @@ -37,7 +37,7 @@ func getMockApp(t *testing.T) (*mock.App, Keeper) { coinKeeper := bank.NewKeeper(mApp.AccountMapper) keeper := NewKeeper(mApp.Cdc, keyStake, coinKeeper, mApp.RegisterCodespace(DefaultCodespace)) - mApp.Router().AddRoute("stake", NewHandler(keeper)) + mApp.Router().AddRoute("stake", []*sdk.KVStoreKey{keyStake}, NewHandler(keeper)) mApp.SetEndBlocker(getEndBlocker(keeper)) mApp.SetInitChainer(getInitChainer(mApp, keeper)) From 7381a8618a8828ad7174494870a8867e77a991f0 Mon Sep 17 00:00:00 2001 From: chengsilei Date: Mon, 6 Aug 2018 09:56:11 +0800 Subject: [PATCH 17/52] fix that router handler name can not contain "-" --- baseapp/router.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/baseapp/router.go b/baseapp/router.go index 1ff2678336f9..b4722cb30c48 100644 --- a/baseapp/router.go +++ b/baseapp/router.go @@ -4,6 +4,7 @@ import ( "regexp" sdk "github.com/cosmos/cosmos-sdk/types" + "strings" ) // Router provides handlers for each transaction type. @@ -43,7 +44,9 @@ var isAlpha = regexp.MustCompile(`^[a-zA-Z]+$`).MatchString // AddRoute - TODO add description //////////////////// iris/cosmos-sdk begin /////////////////////////// func (rtr *router) AddRoute(r string, s []*sdk.KVStoreKey, h sdk.Handler) Router { - if !isAlpha(r) { + rstrs := strings.Split(r, "-") + + if !isAlpha(rstrs[0]) { panic("route expressions can only contain alphabet characters") } rtr.routes = append(rtr.routes, route{r, s, h}) From 8551cd8a636f2fd8e709ce986eff969ad5aea5aa Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Mon, 6 Aug 2018 15:38:54 +0800 Subject: [PATCH 18/52] Add new features: 1:Implement the gov function parametersProposal, currently only modify the parameter type to string 2:Param store adds startup configuration parameters: the precision of a certain token, the query token accuracy method, and the conversion method --- cmd/gaia/app/app.go | 2 ++ cmd/gaia/app/genesis.go | 9 +++-- cmd/gaia/cmd/gaiacli/main.go | 14 +++++++- x/gov/client/cli/tx.go | 13 ++++++- x/gov/handler.go | 4 ++- x/gov/keeper.go | 37 ++++++++++++++++++++ x/gov/msgs.go | 12 +++++++ x/gov/proposals.go | 26 +++++++++----- x/gov/proposals_test.go | 29 ++++++---------- x/gov/wire.go | 5 +++ x/params/client/cli/util.go | 29 ++++++++++++++++ x/params/genesis.go | 67 ++++++++++++++++++++++++++++++++++++ 12 files changed, 214 insertions(+), 33 deletions(-) create mode 100644 x/params/client/cli/util.go create mode 100644 x/params/genesis.go diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 7cbb65836565..875595d52297 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -183,6 +183,8 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci gov.InitGenesis(ctx, app.govKeeper, gov.DefaultGenesisState()) + params.InitParamGenesis(ctx,app.paramsKeeper,genesisState.ParamsData) + return abci.ResponseInitChain{} } diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index af547e844620..b0c82ab37665 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/params" ) var ( @@ -26,6 +27,7 @@ var ( type GenesisState struct { Accounts []GenesisAccount `json:"accounts"` StakeData stake.GenesisState `json:"stake"` + ParamsData params.ParamGenesisState `json:"params"` } // GenesisAccount doesn't need pubkey or sequence @@ -154,9 +156,10 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState // create the genesis account, give'm few steaks and a buncha token with there name accAuth := auth.NewBaseAccountWithAddress(genTx.Address) + accAuth.Coins = sdk.Coins{ - {genTx.Name + "Token", sdk.NewInt(1000)}, - {"steak", sdk.NewInt(freeFermionsAcc)}, + params.DefaultPrecison(sdk.Coin{genTx.Name, sdk.NewInt(2000000000)}), + params.DefaultPrecison(sdk.Coin{"steak", sdk.NewInt(1000)}), } acc := NewGenesisAccount(&accAuth) genaccs[i] = acc @@ -187,10 +190,12 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState } } + paramsData := params.DefaultGenesisState() // create the final app state genesisState = GenesisState{ Accounts: genaccs, StakeData: stakeData, + ParamsData:paramsData, } return } diff --git a/cmd/gaia/cmd/gaiacli/main.go b/cmd/gaia/cmd/gaiacli/main.go index 7c66cb9ef7bf..a7d74c07a377 100644 --- a/cmd/gaia/cmd/gaiacli/main.go +++ b/cmd/gaia/cmd/gaiacli/main.go @@ -17,7 +17,7 @@ import ( ibccmd "github.com/cosmos/cosmos-sdk/x/ibc/client/cli" slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" - + paramscli "github.com/cosmos/cosmos-sdk/x/params/client/cli" "github.com/cosmos/cosmos-sdk/cmd/gaia/app" ) @@ -141,6 +141,18 @@ func main() { version.VersionCmd, ) + paramsCmd := &cobra.Command{ + Use: "params", + Short: "Governance and voting subcommands", + } + + paramsCmd.AddCommand( + client.GetCommands( + paramscli.QueryParam("params",cdc), + )...) + + rootCmd.AddCommand(paramsCmd) + // prepare and add flags executor := cli.PrepareMainCmd(rootCmd, "GA", app.DefaultCLIHome) err := executor.Execute() diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index 8f30aefc10ea..c8acffcbbab5 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -12,6 +12,7 @@ import ( authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/pkg/errors" + "encoding/json" ) const ( @@ -24,6 +25,7 @@ const ( flagDepositer = "depositer" flagVoter = "voter" flagOption = "option" + flagParams = "params" ) // submit a proposal tx @@ -36,6 +38,7 @@ func GetCmdSubmitProposal(cdc *wire.Codec) *cobra.Command { description := viper.GetString(flagDescription) strProposalType := viper.GetString(flagProposalType) initialDeposit := viper.GetString(flagDeposit) + paramsStr := viper.GetString(flagParams) // get the from address from the name flag from, err := sdk.AccAddressFromBech32(viper.GetString(flagProposer)) @@ -54,7 +57,14 @@ func GetCmdSubmitProposal(cdc *wire.Codec) *cobra.Command { } // create the message - msg := gov.NewMsgSubmitProposal(title, description, proposalType, from, amount) + var params gov.Params + if(proposalType == gov.ProposalTypeParameterChange){ + if err := json.Unmarshal([]byte(paramsStr),¶ms);err != nil{ + fmt.Println(err.Error()) + return nil + } + } + msg := gov.NewSubmitProposal(title, description, proposalType, from, amount,params) err = msg.ValidateBasic() if err != nil { @@ -79,6 +89,7 @@ func GetCmdSubmitProposal(cdc *wire.Codec) *cobra.Command { cmd.Flags().String(flagProposalType, "", "proposalType of proposal") cmd.Flags().String(flagDeposit, "", "deposit of proposal") cmd.Flags().String(flagProposer, "", "proposer of proposal") + cmd.Flags().String(flagParams, "", "parameter of proposal,eg. [{key:key,value:value,op:update}]") return cmd } diff --git a/x/gov/handler.go b/x/gov/handler.go index fba19f0932c3..ea5e72e64cb1 100644 --- a/x/gov/handler.go +++ b/x/gov/handler.go @@ -23,7 +23,7 @@ func NewHandler(keeper Keeper) sdk.Handler { func handleMsgSubmitProposal(ctx sdk.Context, keeper Keeper, msg MsgSubmitProposal) sdk.Result { - proposal := keeper.NewTextProposal(ctx, msg.Title, msg.Description, msg.ProposalType) + proposal := keeper.NewProposal(ctx, msg.Title, msg.Description, msg.ProposalType,msg.Params) err, votingStarted := keeper.AddDeposit(ctx, proposal.GetProposalID(), msg.Proposer, msg.InitialDeposit) if err != nil { @@ -122,6 +122,8 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (tags sdk.Tags, nonVotingVals [] activeProposal.SetStatus(StatusPassed) tags.AppendTag("action", []byte("proposalPassed")) tags.AppendTag("proposalId", proposalIDBytes) + + activeProposal.Execute(ctx,keeper) } else { keeper.DeleteDeposits(ctx, activeProposal.GetProposalID()) activeProposal.SetStatus(StatusRejected) diff --git a/x/gov/keeper.go b/x/gov/keeper.go index aae1ac3a4d4c..b48bf2519461 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -5,6 +5,7 @@ import ( wire "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/params" + "fmt" ) // Governance Keeper @@ -73,6 +74,42 @@ func (keeper Keeper) NewTextProposal(ctx sdk.Context, title string, description return proposal } +func (keeper Keeper) NewParametersProposal(ctx sdk.Context, title string, description string, proposalType ProposalKind,params Params) Proposal{ + proposalID, err := keeper.getNewProposalID(ctx) + if err != nil { + return nil + } + var textProposal = TextProposal{ + ProposalID: proposalID, + Title: title, + Description: description, + ProposalType: proposalType, + Status: StatusDepositPeriod, + TotalDeposit: sdk.Coins{}, + SubmitBlock: ctx.BlockHeight(), + VotingStartBlock: -1, // TODO: Make Time + } + var proposal Proposal = &ParameterProposal{ + textProposal, + params, + } + keeper.SetProposal(ctx, proposal) + keeper.InactiveProposalQueuePush(ctx, proposal) + return proposal +} + +func (keeper Keeper) NewProposal(ctx sdk.Context, title string, description string, proposalType ProposalKind,params Params) Proposal{ + switch proposalType { + case ProposalTypeText: + return keeper.NewTextProposal(ctx, title, description, proposalType) + case ProposalTypeParameterChange: + return keeper.NewParametersProposal(ctx, title, description, proposalType,params) + case ProposalTypeSoftwareUpgrade: + fmt.Println("not implement") + } + return nil +} + // Get Proposal from store by ProposalID func (keeper Keeper) GetProposal(ctx sdk.Context, proposalID int64) Proposal { store := ctx.KVStore(keeper.storeKey) diff --git a/x/gov/msgs.go b/x/gov/msgs.go index 5d85f689e58c..f1d89391c7d8 100644 --- a/x/gov/msgs.go +++ b/x/gov/msgs.go @@ -17,6 +17,7 @@ type MsgSubmitProposal struct { ProposalType ProposalKind // Type of proposal. Initial set {PlainTextProposal, SoftwareUpgradeProposal} Proposer sdk.AccAddress // Address of the proposer InitialDeposit sdk.Coins // Initial deposit paid by sender. Must be strictly positive. + Params Params } func NewMsgSubmitProposal(title string, description string, proposalType ProposalKind, proposer sdk.AccAddress, initialDeposit sdk.Coins) MsgSubmitProposal { @@ -29,6 +30,17 @@ func NewMsgSubmitProposal(title string, description string, proposalType Proposa } } +func NewSubmitProposal(title string, description string, proposalType ProposalKind, proposer sdk.AccAddress, initialDeposit sdk.Coins,params Params) MsgSubmitProposal { + return MsgSubmitProposal{ + Title: title, + Description: description, + ProposalType: proposalType, + Proposer: proposer, + InitialDeposit: initialDeposit, + Params: params, + } +} + // Implements Msg. func (msg MsgSubmitProposal) Type() string { return MsgType } diff --git a/x/gov/proposals.go b/x/gov/proposals.go index c3f397feb1ad..35a41eccfb33 100644 --- a/x/gov/proposals.go +++ b/x/gov/proposals.go @@ -95,28 +95,34 @@ func (tp *TextProposal) SetVotingStartBlock(votingStartBlock int64) { func (tp *TextProposal) Execute(ctx sdk.Context, k Keeper) error { return nil } //////////////////// iris/cosmos-sdk begin /////////////////////////// -type Op byte +type Op string const ( - Add Op = 0x01 - Del Op = 0x02 - Update Op = 0x03 + Add Op = "add" + Del Op = "del" + Update Op = "update" ) type Data struct { - Key string `json:"key"` - Value interface{} `json:"value"` - Op Op `json:"op"` + Key string `json:"key"` + Value string `json:"value"` + Op Op `json:"op"` } +type Params []Data + +// Implements Proposal Interface +var _ Proposal = (*ParameterProposal)(nil) + type ParameterProposal struct { TextProposal - Datas []Data `json:"datas"` + Datas Params `json:"datas"` } func (pp *ParameterProposal) Execute(ctx sdk.Context, k Keeper) error { logger := ctx.Logger().With("module", "x/gov") + logger.Info("Execute ParameterProposal begin","info", fmt.Sprintf("current height:%d",ctx.BlockHeight())) if len(pp.Datas) == 0 { return errors.New("ParameterProposal's data is empty") @@ -129,7 +135,9 @@ func (pp *ParameterProposal) Execute(ctx sdk.Context, k Keeper) error { if bz == nil || len(bz) == 0 { logger.Error("Execute ParameterProposal ", "err", "Parameter "+data.Key+" is not exist") } else { - k.ps.Set(ctx, data.Key, data.Value) + if err := k.ps.Set(ctx, data.Key, data.Value);err != nil{ + logger.Error("Execute ParameterProposal ", "err", err.Error()) + } } } else { diff --git a/x/gov/proposals_test.go b/x/gov/proposals_test.go index ca8143af5ea2..c8ad8f92a80b 100644 --- a/x/gov/proposals_test.go +++ b/x/gov/proposals_test.go @@ -8,11 +8,6 @@ import ( "testing" ) -const ( - ParamStoreKeyDepositProcedureDepositAmount = "gov/depositprocedure/depositAmount" - ParamStoreKeyDepositProcedureDepositDenom = "gov/depositprocedure/depositDenom" -) - func TestParameterProposal(t *testing.T) { mapp, keeper, _, _, _, _ := getMockApp(t, 0) @@ -26,10 +21,6 @@ func TestParameterProposal(t *testing.T) { pp := ParameterProposal{ Datas: []Data{ {Key: ParamStoreKeyDepositProcedureDeposit, Value: "200iris", Op: Update}, - {Key: ParamStoreKeyDepositProcedureDepositAmount, Value: "200", Op: Update}, - {Key: ParamStoreKeyDepositProcedureDepositDenom, Value: "iris", Op: Update}, - {Key: ParamStoreKeyDepositProcedureMaxDepositPeriod, Value: 100, Op: Update}, - {Key: ParamStoreKeyVotingProcedureVotingPeriod, Value: 200, Op: Update}, {Key: ParamStoreKeyTallyingProcedurePenalty, Value: "1/50", Op: Update}, {Key: ParamStoreKeyTallyingProcedureVeto, Value: "1/4", Op: Update}, {Key: ParamStoreKeyTallyingProcedureThreshold, Value: "2/8", Op: Update}, @@ -37,16 +28,10 @@ func TestParameterProposal(t *testing.T) { } pp.Execute(ctx, keeper) - assert.Equal(t, keeper.GetDepositProcedure(ctx), - DepositProcedure{ - MinDeposit: sdk.Coins{sdk.NewCoin("iris", 200)}, - MaxDepositPeriod: 100}) - - assert.Equal(t, keeper.GetVotingProcedure(ctx), - VotingProcedure{ - VotingPeriod: 200, - }) - fmt.Println(keeper.GetTallyingProcedure(ctx)) + assert.Equal(t, keeper.GetDepositProcedure(ctx).MinDeposit, + sdk.Coins{sdk.NewCoin("iris", 200)}) + + assert.Equal(t, keeper.GetTallyingProcedure(ctx), TallyingProcedure{ Threshold: sdk.NewRat(2, 8), @@ -54,3 +39,9 @@ func TestParameterProposal(t *testing.T) { GovernancePenalty: sdk.NewRat(1, 50), }) } + + + +func TestByte(t *testing.T) { + fmt.Println(string([]byte{112,114,111,112,111,115,97,108,73,100})) +} diff --git a/x/gov/wire.go b/x/gov/wire.go index 4173fc69a62f..65ebad870fcc 100644 --- a/x/gov/wire.go +++ b/x/gov/wire.go @@ -17,6 +17,11 @@ func RegisterWire(cdc *wire.Codec) { cdc.RegisterInterface((*Proposal)(nil), nil) cdc.RegisterConcrete(&TextProposal{}, "gov/TextProposal", nil) + cdc.RegisterConcrete(&ParameterProposal{}, "gov/ParameterProposal", nil) } var msgCdc = wire.NewCodec() + +func init() { + RegisterWire(msgCdc) +} diff --git a/x/params/client/cli/util.go b/x/params/client/cli/util.go new file mode 100644 index 000000000000..7222f9b35b5b --- /dev/null +++ b/x/params/client/cli/util.go @@ -0,0 +1,29 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/wire" + "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client/context" + "fmt" + +) + +// create edit validator command +func QueryParam(storeName string, cdc *wire.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "query", + Short: "query param value from global store", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.NewCoreContextFromViper() + res, err := ctx.QueryStore([]byte(args[0]), storeName) + if err != nil { + fmt.Println(err.Error()) + return nil + } + fmt.Println(string(res)) + return nil + }, + } + return cmd +} diff --git a/x/params/genesis.go b/x/params/genesis.go new file mode 100644 index 000000000000..86e7b24dc404 --- /dev/null +++ b/x/params/genesis.go @@ -0,0 +1,67 @@ +package params + +import ( + "errors" + "fmt" + "github.com/cosmos/cosmos-sdk/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "strconv" +) + +const IrisPrecision = 18 +const IrisDenom = "iris" + +type CoinConfig struct { + Denom string `json:"denom"` + Precison int64 `json:"precison"` +} + +type ParamGenesisState struct { + Coins []CoinConfig `json:"coins"` +} + +func DefaultPrecison(coin types.Coin) types.Coin { + coin.Amount = Pow10(IrisPrecision).Mul(coin.Amount) + return coin +} + +func ToBigCoin(ctx sdk.Context, k Getter, coin types.Coin) (types.Coin, error) { + precison, err := k.GetString(ctx, coin.Denom) + if err != nil { + ctx.Logger().Error("module params:%s coin is invalid", coin.Denom) + return coin, errors.New(fmt.Sprintf("%s coin is invalid", coin.Denom)) + } + prec,_:= strconv.ParseInt(precison,10,0) + amount := Pow10(int(prec)).Mul(coin.Amount) + return types.Coin{Denom: coin.Denom, Amount: amount}, nil +} + +func Get(ctx sdk.Context, k Getter, key string, ptr interface{}) error { + return k.Get(ctx, key, ptr) +} + +func DefaultGenesisState() (state ParamGenesisState) { + state.Coins = append(state.Coins, CoinConfig{ + Denom: IrisDenom, + Precison: IrisPrecision, + }) + return state +} + +func InitParamGenesis(ctx sdk.Context, k Keeper, state ParamGenesisState) { + for _, coin := range state.Coins { + k.Setter().SetString(ctx, coin.Denom, strconv.FormatInt(coin.Precison, 10)) + } +} + +func Pow10(y int) sdk.Int { + result := sdk.NewInt(1) + x := sdk.NewInt(10) + for i := y; i > 0; i >>= 1 { + if i&1 != 0 { + result = result.Mul(x) + } + x = x.Mul(x) + } + return result +} From 1a798559ece792066569719df5589d7c6838de75 Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Mon, 6 Aug 2018 16:15:32 +0800 Subject: [PATCH 19/52] Add precision in validator and modify power calculation --- cmd/gaia/app/genesis.go | 1 + x/stake/handler.go | 1 + x/stake/types/params.go | 2 ++ x/stake/types/validator.go | 8 +++++++- 4 files changed, 11 insertions(+), 1 deletion(-) diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index af547e844620..62e3425621b2 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -173,6 +173,7 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState // add some new shares to the validator var issuedDelShares sdk.Rat validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, freeFermionVal) + validator.Precision = stakeData.Params.Precision stakeData.Validators = append(stakeData.Validators, validator) // create the self-delegation from the issuedDelShares diff --git a/x/stake/handler.go b/x/stake/handler.go index 14fb4f7bfffe..fd62ae2e48a5 100644 --- a/x/stake/handler.go +++ b/x/stake/handler.go @@ -77,6 +77,7 @@ func handleMsgCreateValidator(ctx sdk.Context, msg types.MsgCreateValidator, k k } validator := NewValidator(msg.ValidatorAddr, msg.PubKey, msg.Description) + validator.Precision = k.GetParams(ctx).Precision k.SetValidator(ctx, validator) k.SetValidatorByPubKeyIndex(ctx, validator) diff --git a/x/stake/types/params.go b/x/stake/types/params.go index 5a7dd6ef5565..a2c57a896457 100644 --- a/x/stake/types/params.go +++ b/x/stake/types/params.go @@ -21,6 +21,7 @@ type Params struct { MaxValidators uint16 `json:"max_validators"` // maximum number of validators BondDenom string `json:"bond_denom"` // bondable coin denomination + Precision int8 `json:"precision_denom"`// coin precision } // Equal returns a boolean determining if two Param types are identical. @@ -40,5 +41,6 @@ func DefaultParams() Params { UnbondingTime: defaultUnbondingTime, MaxValidators: 100, BondDenom: "steak", + Precision: 18, } } diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index f177c123d07e..8114435fc452 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -11,6 +11,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" + "math" ) const doNotModifyDescVal = "[do-not-modify]" @@ -30,6 +31,7 @@ type Validator struct { Status sdk.BondStatus `json:"status"` // validator status (bonded/unbonding/unbonded) Tokens sdk.Rat `json:"tokens"` // delegated tokens (incl. self-delegation) DelegatorShares sdk.Rat `json:"delegator_shares"` // total shares issued to a validator's delegators + Precision int8 `json:"precision"` Description Description `json:"description"` // description terms for the validator BondHeight int64 `json:"bond_height"` // earliest height as a bonded validator @@ -53,6 +55,7 @@ func NewValidator(owner sdk.AccAddress, pubKey crypto.PubKey, description Descri Revoked: false, Status: sdk.Unbonded, Tokens: sdk.ZeroRat(), + Precision: 0, DelegatorShares: sdk.ZeroRat(), Description: description, BondHeight: int64(0), @@ -433,6 +436,9 @@ func (v Validator) GetMoniker() string { return v.Description.Moniker } func (v Validator) GetStatus() sdk.BondStatus { return v.Status } func (v Validator) GetOwner() sdk.AccAddress { return v.Owner } func (v Validator) GetPubKey() crypto.PubKey { return v.PubKey } -func (v Validator) GetPower() sdk.Rat { return v.BondedTokens() } +func (v Validator) GetPower() sdk.Rat { + precisionNumber := int64(math.Pow10(int(v.Precision))) + return v.BondedTokens().Quo(sdk.NewRat(precisionNumber)) +} func (v Validator) GetDelegatorShares() sdk.Rat { return v.DelegatorShares } func (v Validator) GetBondHeight() int64 { return v.BondHeight } From bc40c62e9f86b4918fa4de5272bcb23fe7c37a45 Mon Sep 17 00:00:00 2001 From: chengsilei Date: Mon, 6 Aug 2018 16:50:19 +0800 Subject: [PATCH 20/52] setup runMsg callback function --- baseapp/baseapp.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 868f3558a51e..7ae514e37cc0 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -39,6 +39,8 @@ const ( runTxModeDeliver runTxMode = iota ) +type RunMsg func(ctx sdk.Context, msgs []sdk.Msg) sdk.Result + // BaseApp reflects the ABCI application implementation. type BaseApp struct { // initialized on creation @@ -60,6 +62,7 @@ type BaseApp struct { endBlocker sdk.EndBlocker // logic to run after all txs, and to determine valset changes addrPeerFilter sdk.PeerFilter // filter peers by address and port pubkeyPeerFilter sdk.PeerFilter // filter peers by public key + runMsg RunMsg //-------------------- // Volatile @@ -192,6 +195,10 @@ func (app *BaseApp) SetPubKeyPeerFilter(pf sdk.PeerFilter) { } func (app *BaseApp) Router() Router { return app.router } +func (app *BaseApp) SetRunMsg(runMsg RunMsg) { + app.runMsg = runMsg +} + // load latest application version func (app *BaseApp) LoadLatestVersion(mainKey sdk.StoreKey) error { err := app.cms.LoadLatestVersion() @@ -564,6 +571,10 @@ func (app *BaseApp) getContextForAnte(mode runTxMode, txBytes []byte) (ctx sdk.C // Iterates through msgs and executes them func (app *BaseApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) { + if app.runMsg != nil { + return app.runMsg(ctx, msgs) + } + // accumulate results logs := make([]string, 0, len(msgs)) var data []byte // NOTE: we just append them all (?!) From b28eec705408bd5ab1a0b111dfa4df643bae2400 Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Mon, 6 Aug 2018 17:12:57 +0800 Subject: [PATCH 21/52] Change variable name and modify voting power calculation --- cmd/gaia/app/genesis.go | 2 +- x/stake/handler.go | 2 +- x/stake/types/params.go | 4 ++-- x/stake/types/validator.go | 15 +++++++++++---- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index 62e3425621b2..736e4ba1cf11 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -173,7 +173,7 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState // add some new shares to the validator var issuedDelShares sdk.Rat validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, freeFermionVal) - validator.Precision = stakeData.Params.Precision + validator.TokenPrecision = stakeData.Params.DenomPrecision stakeData.Validators = append(stakeData.Validators, validator) // create the self-delegation from the issuedDelShares diff --git a/x/stake/handler.go b/x/stake/handler.go index fd62ae2e48a5..a4284b1e3ed8 100644 --- a/x/stake/handler.go +++ b/x/stake/handler.go @@ -77,7 +77,7 @@ func handleMsgCreateValidator(ctx sdk.Context, msg types.MsgCreateValidator, k k } validator := NewValidator(msg.ValidatorAddr, msg.PubKey, msg.Description) - validator.Precision = k.GetParams(ctx).Precision + validator.TokenPrecision = k.GetParams(ctx).DenomPrecision k.SetValidator(ctx, validator) k.SetValidatorByPubKeyIndex(ctx, validator) diff --git a/x/stake/types/params.go b/x/stake/types/params.go index a2c57a896457..a295131d61d2 100644 --- a/x/stake/types/params.go +++ b/x/stake/types/params.go @@ -21,7 +21,7 @@ type Params struct { MaxValidators uint16 `json:"max_validators"` // maximum number of validators BondDenom string `json:"bond_denom"` // bondable coin denomination - Precision int8 `json:"precision_denom"`// coin precision + DenomPrecision int8 `json:"denom_precision"`// coin precision } // Equal returns a boolean determining if two Param types are identical. @@ -41,6 +41,6 @@ func DefaultParams() Params { UnbondingTime: defaultUnbondingTime, MaxValidators: 100, BondDenom: "steak", - Precision: 18, + DenomPrecision: 18, } } diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index 8114435fc452..c783c0371b48 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -31,7 +31,7 @@ type Validator struct { Status sdk.BondStatus `json:"status"` // validator status (bonded/unbonding/unbonded) Tokens sdk.Rat `json:"tokens"` // delegated tokens (incl. self-delegation) DelegatorShares sdk.Rat `json:"delegator_shares"` // total shares issued to a validator's delegators - Precision int8 `json:"precision"` + TokenPrecision int8 `json:"token_precision"` Description Description `json:"description"` // description terms for the validator BondHeight int64 `json:"bond_height"` // earliest height as a bonded validator @@ -55,7 +55,7 @@ func NewValidator(owner sdk.AccAddress, pubKey crypto.PubKey, description Descri Revoked: false, Status: sdk.Unbonded, Tokens: sdk.ZeroRat(), - Precision: 0, + TokenPrecision: 0, DelegatorShares: sdk.ZeroRat(), Description: description, BondHeight: int64(0), @@ -75,6 +75,7 @@ type validatorValue struct { Revoked bool Status sdk.BondStatus Tokens sdk.Rat + TokenPrecision int8 DelegatorShares sdk.Rat Description Description BondHeight int64 @@ -94,6 +95,7 @@ func MustMarshalValidator(cdc *wire.Codec, validator Validator) []byte { Revoked: validator.Revoked, Status: validator.Status, Tokens: validator.Tokens, + TokenPrecision: validator.TokenPrecision, DelegatorShares: validator.DelegatorShares, Description: validator.Description, BondHeight: validator.BondHeight, @@ -136,6 +138,7 @@ func UnmarshalValidator(cdc *wire.Codec, ownerAddr, value []byte) (validator Val PubKey: storeValue.PubKey, Revoked: storeValue.Revoked, Tokens: storeValue.Tokens, + TokenPrecision: storeValue.TokenPrecision, Status: storeValue.Status, DelegatorShares: storeValue.DelegatorShares, Description: storeValue.Description, @@ -165,6 +168,7 @@ func (v Validator) HumanReadableString() (string, error) { resp += fmt.Sprintf("Revoked: %v\n", v.Revoked) resp += fmt.Sprintf("Status: %s\n", sdk.BondStatusToString(v.Status)) resp += fmt.Sprintf("Tokens: %s\n", v.Tokens.FloatString()) + resp += fmt.Sprintf("TokenPrecision: %d\n", v.TokenPrecision) resp += fmt.Sprintf("Delegator Shares: %s\n", v.DelegatorShares.FloatString()) resp += fmt.Sprintf("Description: %s\n", v.Description) resp += fmt.Sprintf("Bond Height: %d\n", v.BondHeight) @@ -189,6 +193,7 @@ type BechValidator struct { Status sdk.BondStatus `json:"status"` // validator status (bonded/unbonding/unbonded) Tokens sdk.Rat `json:"tokens"` // delegated tokens (incl. self-delegation) DelegatorShares sdk.Rat `json:"delegator_shares"` // total shares issued to a validator's delegators + TokenPrecision int8 `json:"token_precision"` Description Description `json:"description"` // description terms for the validator BondHeight int64 `json:"bond_height"` // earliest height as a bonded validator @@ -219,6 +224,7 @@ func (v Validator) Bech32Validator() (BechValidator, error) { Status: v.Status, Tokens: v.Tokens, DelegatorShares: v.DelegatorShares, + TokenPrecision: v.TokenPrecision, Description: v.Description, BondHeight: v.BondHeight, @@ -244,6 +250,7 @@ func (v Validator) Equal(c2 Validator) bool { v.Status.Equal(c2.Status) && v.Tokens.Equal(c2.Tokens) && v.DelegatorShares.Equal(c2.DelegatorShares) && + v.TokenPrecision == c2.TokenPrecision && v.Description == c2.Description && v.ProposerRewardPool.IsEqual(c2.ProposerRewardPool) && v.Commission.Equal(c2.Commission) && @@ -317,7 +324,7 @@ func (d Description) EnsureLength() (Description, sdk.Error) { func (v Validator) ABCIValidator() abci.Validator { return abci.Validator{ PubKey: tmtypes.TM2PB.PubKey(v.PubKey), - Power: v.BondedTokens().RoundInt64(), + Power: v.GetPower().RoundInt64(), } } @@ -437,7 +444,7 @@ func (v Validator) GetStatus() sdk.BondStatus { return v.Status } func (v Validator) GetOwner() sdk.AccAddress { return v.Owner } func (v Validator) GetPubKey() crypto.PubKey { return v.PubKey } func (v Validator) GetPower() sdk.Rat { - precisionNumber := int64(math.Pow10(int(v.Precision))) + precisionNumber := int64(math.Pow10(int(v.TokenPrecision))) return v.BondedTokens().Quo(sdk.NewRat(precisionNumber)) } func (v Validator) GetDelegatorShares() sdk.Rat { return v.DelegatorShares } From 651c97e200802da428e56a4eeae284349260ae3e Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Mon, 6 Aug 2018 18:07:07 +0800 Subject: [PATCH 22/52] Add overflow checking --- x/stake/types/validator.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index c783c0371b48..af46a412fe4e 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -444,8 +444,12 @@ func (v Validator) GetStatus() sdk.BondStatus { return v.Status } func (v Validator) GetOwner() sdk.AccAddress { return v.Owner } func (v Validator) GetPubKey() crypto.PubKey { return v.PubKey } func (v Validator) GetPower() sdk.Rat { - precisionNumber := int64(math.Pow10(int(v.TokenPrecision))) - return v.BondedTokens().Quo(sdk.NewRat(precisionNumber)) + precisionNumber := math.Pow10(int(v.TokenPrecision)) + if precisionNumber > math.MaxInt64 { + panic(errors.New("precision is too high, int64 is overflow")) + } + precisionInt64 := int64(precisionNumber) + return v.BondedTokens().Quo(sdk.NewRat(precisionInt64)) } func (v Validator) GetDelegatorShares() sdk.Rat { return v.DelegatorShares } func (v Validator) GetBondHeight() int64 { return v.BondHeight } From 14c32132ab488544fdcec15d4dbc41ac9db8a2a2 Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Mon, 6 Aug 2018 18:40:26 +0800 Subject: [PATCH 23/52] change AddTokensFromDel parameter amount: from int64 to sdk.Int --- cmd/gaia/app/genesis.go | 14 +++++++-- x/stake/keeper/delegation.go | 2 +- x/stake/keeper/delegation_test.go | 4 +-- x/stake/keeper/slash_test.go | 2 +- x/stake/keeper/validator_test.go | 52 +++++++++++++++---------------- x/stake/types/test_utils.go | 2 +- x/stake/types/validator.go | 8 ++--- x/stake/types/validator_test.go | 10 +++--- 8 files changed, 51 insertions(+), 43 deletions(-) diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index 736e4ba1cf11..a8b18ff8034a 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/stake" + "math" ) var ( @@ -160,7 +161,14 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState } acc := NewGenesisAccount(&accAuth) genaccs[i] = acc - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionsAcc)) // increase the supply + + precisionNumber := math.Pow10(int(stakeData.Params.DenomPrecision)) + if precisionNumber > math.MaxInt64 { + panic(errors.New("precision is too high, int64 is overflow")) + } + precisionInt64 := int64(precisionNumber) + tokenPrecision := sdk.NewRat(precisionInt64) + stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionsAcc).Mul(tokenPrecision)) // increase the supply // add the validator if len(genTx.Name) > 0 { @@ -168,11 +176,11 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState validator := stake.NewValidator(genTx.Address, sdk.MustGetAccPubKeyBech32(genTx.PubKey), desc) - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionVal)) // increase the supply + stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionVal).Mul(tokenPrecision)) // increase the supply // add some new shares to the validator var issuedDelShares sdk.Rat - validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, freeFermionVal) + validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, sdk.NewInt(freeFermionVal).Mul(sdk.NewInt(precisionInt64))) validator.TokenPrecision = stakeData.Params.DenomPrecision stakeData.Validators = append(stakeData.Validators, validator) diff --git a/x/stake/keeper/delegation.go b/x/stake/keeper/delegation.go index e7168109a66b..0afdad199abd 100644 --- a/x/stake/keeper/delegation.go +++ b/x/stake/keeper/delegation.go @@ -223,7 +223,7 @@ func (k Keeper) Delegate(ctx sdk.Context, delegatorAddr sdk.AccAddress, bondAmt } pool := k.GetPool(ctx) - validator, pool, newShares = validator.AddTokensFromDel(pool, bondAmt.Amount.Int64()) + validator, pool, newShares = validator.AddTokensFromDel(pool, bondAmt.Amount) delegation.Shares = delegation.Shares.Add(newShares) // Update delegation height diff --git a/x/stake/keeper/delegation_test.go b/x/stake/keeper/delegation_test.go index 01c764d8278e..32c2d625bc2d 100644 --- a/x/stake/keeper/delegation_test.go +++ b/x/stake/keeper/delegation_test.go @@ -19,7 +19,7 @@ func TestDelegation(t *testing.T) { var validators [3]types.Validator for i, amt := range amts { validators[i] = types.NewValidator(addrVals[i], PKs[i], types.Description{}) - validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) + validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) } keeper.SetPool(ctx, pool) @@ -145,7 +145,7 @@ func TestUnbondDelegation(t *testing.T) { //create a validator and a delegator to that validator validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - validator, pool, issuedShares := validator.AddTokensFromDel(pool, 10) + validator, pool, issuedShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) validator = keeper.UpdateValidator(ctx, validator) diff --git a/x/stake/keeper/slash_test.go b/x/stake/keeper/slash_test.go index a9f5e888c9f1..cca357853ec2 100644 --- a/x/stake/keeper/slash_test.go +++ b/x/stake/keeper/slash_test.go @@ -23,7 +23,7 @@ func setupHelper(t *testing.T, amt int64) (sdk.Context, Keeper, types.Params) { // add numVals validators for i := 0; i < numVals; i++ { validator := types.NewValidator(addrVals[i], PKs[i], types.Description{}) - validator, pool, _ = validator.AddTokensFromDel(pool, amt) + validator, pool, _ = validator.AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) validator = keeper.UpdateValidator(ctx, validator) keeper.SetValidatorByPubKeyIndex(ctx, validator) diff --git a/x/stake/keeper/validator_test.go b/x/stake/keeper/validator_test.go index 06273d6af77c..c5a772a37d43 100644 --- a/x/stake/keeper/validator_test.go +++ b/x/stake/keeper/validator_test.go @@ -17,7 +17,7 @@ func TestSetValidator(t *testing.T) { // test how the validator is set from a purely unbonbed pool validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - validator, pool, _ = validator.AddTokensFromDel(pool, 10) + validator, pool, _ = validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, sdk.Unbonded, validator.Status) assert.True(sdk.RatEq(t, sdk.NewRat(10), validator.Tokens)) assert.True(sdk.RatEq(t, sdk.NewRat(10), validator.DelegatorShares)) @@ -61,7 +61,7 @@ func TestUpdateValidatorByPowerIndex(t *testing.T) { // add a validator validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - validator, pool, delSharesCreated := validator.AddTokensFromDel(pool, 100) + validator, pool, delSharesCreated := validator.AddTokensFromDel(pool, sdk.NewInt(100)) require.Equal(t, sdk.Unbonded, validator.Status) require.Equal(t, int64(100), validator.Tokens.RoundInt64()) keeper.SetPool(ctx, pool) @@ -95,7 +95,7 @@ func TestSlashToZeroPowerRemoved(t *testing.T) { // add a validator validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) - validator, pool, _ = validator.AddTokensFromDel(pool, 100) + validator, pool, _ = validator.AddTokensFromDel(pool, sdk.NewInt(100)) require.Equal(t, sdk.Unbonded, validator.Status) require.Equal(t, int64(100), validator.Tokens.RoundInt64()) keeper.SetPool(ctx, pool) @@ -122,7 +122,7 @@ func TestValidatorBasics(t *testing.T) { validators[i] = types.NewValidator(addrVals[i], PKs[i], types.Description{}) validators[i].Status = sdk.Unbonded validators[i].Tokens = sdk.ZeroRat() - validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) + validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } assert.True(sdk.RatEq(t, sdk.NewRat(9), validators[0].Tokens)) @@ -347,7 +347,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { for i, amt := range amts { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) - validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) + validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) validators[i] = keeper.UpdateValidator(ctx, validators[i]) } @@ -361,7 +361,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { assert.True(ValEq(t, validators[3], resValidators[1])) pool := keeper.GetPool(ctx) - validators[0], pool, _ = validators[0].AddTokensFromDel(pool, 500) + validators[0], pool, _ = validators[0].AddTokensFromDel(pool, sdk.NewInt(500)) keeper.SetPool(ctx, pool) validators[0] = keeper.UpdateValidator(ctx, validators[0]) resValidators = keeper.GetValidatorsByPower(ctx) @@ -378,7 +378,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { validators[3], found = keeper.GetValidator(ctx, validators[3].Owner) require.True(t, found) - validators[3], pool, _ = validators[3].AddTokensFromDel(pool, 1) + validators[3], pool, _ = validators[3].AddTokensFromDel(pool, sdk.NewInt(1)) keeper.SetPool(ctx, pool) validators[3] = keeper.UpdateValidator(ctx, validators[3]) resValidators = keeper.GetValidatorsByPower(ctx) @@ -396,7 +396,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { assert.True(ValEq(t, validators[2], resValidators[1])) // validator 4 does not get spot back - validators[3], pool, _ = validators[3].AddTokensFromDel(pool, 200) + validators[3], pool, _ = validators[3].AddTokensFromDel(pool, sdk.NewInt(200)) keeper.SetPool(ctx, pool) validators[3] = keeper.UpdateValidator(ctx, validators[3]) resValidators = keeper.GetValidatorsByPower(ctx) @@ -423,9 +423,9 @@ func TestValidatorBondHeight(t *testing.T) { validators[1] = types.NewValidator(Addrs[1], PKs[1], types.Description{}) validators[2] = types.NewValidator(Addrs[2], PKs[2], types.Description{}) - validators[0], pool, _ = validators[0].AddTokensFromDel(pool, 200) - validators[1], pool, _ = validators[1].AddTokensFromDel(pool, 100) - validators[2], pool, _ = validators[2].AddTokensFromDel(pool, 100) + 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] = keeper.UpdateValidator(ctx, validators[0]) @@ -443,8 +443,8 @@ func TestValidatorBondHeight(t *testing.T) { assert.True(ValEq(t, validators[0], resValidators[0])) assert.True(ValEq(t, validators[1], resValidators[1])) - validators[1], pool, _ = validators[1].AddTokensFromDel(pool, 50) - validators[2], pool, _ = validators[2].AddTokensFromDel(pool, 50) + 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] = keeper.UpdateValidator(ctx, validators[2]) resValidators = keeper.GetValidatorsByPower(ctx) @@ -467,7 +467,7 @@ func TestFullValidatorSetPowerChange(t *testing.T) { for i, amt := range amts { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) - validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) + validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) keeper.UpdateValidator(ctx, validators[i]) } @@ -488,7 +488,7 @@ func TestFullValidatorSetPowerChange(t *testing.T) { // test a swap in voting power pool := keeper.GetPool(ctx) - validators[0], pool, _ = validators[0].AddTokensFromDel(pool, 600) + validators[0], pool, _ = validators[0].AddTokensFromDel(pool, sdk.NewInt(600)) keeper.SetPool(ctx, pool) validators[0] = keeper.UpdateValidator(ctx, validators[0]) resValidators = keeper.GetValidatorsByPower(ctx) @@ -506,7 +506,7 @@ func TestClearTendermintUpdates(t *testing.T) { for i, amt := range amts { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) - validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) + validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) keeper.UpdateValidator(ctx, validators[i]) } @@ -526,7 +526,7 @@ func TestGetTendermintUpdatesAllNone(t *testing.T) { for i, amt := range amts { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) - validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) + validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } @@ -565,7 +565,7 @@ func TestGetTendermintUpdatesIdentical(t *testing.T) { for i, amt := range amts { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) - validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) + validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } validators[0] = keeper.UpdateValidator(ctx, validators[0]) @@ -588,7 +588,7 @@ func TestGetTendermintUpdatesSingleValueChange(t *testing.T) { for i, amt := range amts { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) - validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) + validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } validators[0] = keeper.UpdateValidator(ctx, validators[0]) @@ -616,7 +616,7 @@ func TestGetTendermintUpdatesMultipleValueChange(t *testing.T) { for i, amt := range amts { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) - validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) + validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } validators[0] = keeper.UpdateValidator(ctx, validators[0]) @@ -627,8 +627,8 @@ func TestGetTendermintUpdatesMultipleValueChange(t *testing.T) { // test multiple value change // tendermintUpdate set: {c1, c3} -> {c1', c3'} pool := keeper.GetPool(ctx) - validators[0], pool, _ = validators[0].AddTokensFromDel(pool, 190) - validators[1], pool, _ = validators[1].AddTokensFromDel(pool, 80) + 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] = keeper.UpdateValidator(ctx, validators[0]) validators[1] = keeper.UpdateValidator(ctx, validators[1]) @@ -647,7 +647,7 @@ func TestGetTendermintUpdatesInserted(t *testing.T) { for i, amt := range amts { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) - validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) + validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } validators[0] = keeper.UpdateValidator(ctx, validators[0]) @@ -690,7 +690,7 @@ func TestGetTendermintUpdatesWithCliffValidator(t *testing.T) { for i, amt := range amts { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) - validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) + validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } validators[0] = keeper.UpdateValidator(ctx, validators[0]) @@ -710,7 +710,7 @@ func TestGetTendermintUpdatesWithCliffValidator(t *testing.T) { require.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) pool := keeper.GetPool(ctx) - validators[2], pool, _ = validators[2].AddTokensFromDel(pool, 10) + validators[2], pool, _ = validators[2].AddTokensFromDel(pool, sdk.NewInt(10)) keeper.SetPool(ctx, pool) validators[2] = keeper.UpdateValidator(ctx, validators[2]) @@ -728,7 +728,7 @@ func TestGetTendermintUpdatesPowerDecrease(t *testing.T) { for i, amt := range amts { pool := keeper.GetPool(ctx) validators[i] = types.NewValidator(Addrs[i], PKs[i], types.Description{}) - validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) + validators[i], pool, _ = validators[i].AddTokensFromDel(pool, sdk.NewInt(amt)) keeper.SetPool(ctx, pool) } validators[0] = keeper.UpdateValidator(ctx, validators[0]) diff --git a/x/stake/types/test_utils.go b/x/stake/types/test_utils.go index 8a7f4a56e5b6..7dfa2f219f35 100644 --- a/x/stake/types/test_utils.go +++ b/x/stake/types/test_utils.go @@ -57,7 +57,7 @@ func OpAddTokens(r *rand.Rand, pool Pool, validator Validator) (Pool, Validator, msg := fmt.Sprintf("validator %#v", validator) tokens := int64(r.Int31n(1000)) - validator, pool, _ = validator.AddTokensFromDel(pool, tokens) + validator, pool, _ = validator.AddTokensFromDel(pool, sdk.NewInt(tokens)) msg = fmt.Sprintf("Added %d tokens to %s", tokens, msg) // Tokens are removed so for accounting must be negative diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index af46a412fe4e..405d601490c5 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -385,11 +385,11 @@ func (v Validator) RemoveTokens(pool Pool, tokens sdk.Rat) (Validator, Pool) { //_________________________________________________________________________________________________________ // AddTokensFromDel adds tokens to a validator -func (v Validator) AddTokensFromDel(pool Pool, amount int64) (Validator, Pool, sdk.Rat) { +func (v Validator) AddTokensFromDel(pool Pool, amount sdk.Int) (Validator, Pool, sdk.Rat) { // bondedShare/delegatedShare exRate := v.DelegatorShareExRate() - amountRat := sdk.NewRat(amount) + amountRat := sdk.NewRatFromInt(amount) if v.Status == sdk.Bonded { pool = pool.looseTokensToBonded(amountRat) @@ -448,8 +448,8 @@ func (v Validator) GetPower() sdk.Rat { if precisionNumber > math.MaxInt64 { panic(errors.New("precision is too high, int64 is overflow")) } - precisionInt64 := int64(precisionNumber) - return v.BondedTokens().Quo(sdk.NewRat(precisionInt64)) + tokenPrecision := int64(precisionNumber) + return v.BondedTokens().Quo(sdk.NewRat(tokenPrecision)) } func (v Validator) GetDelegatorShares() sdk.Rat { return v.DelegatorShares } func (v Validator) GetBondHeight() int64 { return v.BondHeight } diff --git a/x/stake/types/validator_test.go b/x/stake/types/validator_test.go index 8d97cbce749e..bd130e42a528 100644 --- a/x/stake/types/validator_test.go +++ b/x/stake/types/validator_test.go @@ -97,7 +97,7 @@ func TestAddTokensValidatorBonded(t *testing.T) { pool.LooseTokens = sdk.NewRat(10) validator := NewValidator(addr1, pk1, Description{}) validator, pool = validator.UpdateStatus(pool, sdk.Bonded) - validator, pool, delShares := validator.AddTokensFromDel(pool, 10) + validator, pool, delShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, sdk.OneRat(), validator.DelegatorShareExRate()) @@ -110,7 +110,7 @@ func TestAddTokensValidatorUnbonding(t *testing.T) { pool.LooseTokens = sdk.NewRat(10) validator := NewValidator(addr1, pk1, Description{}) validator, pool = validator.UpdateStatus(pool, sdk.Unbonding) - validator, pool, delShares := validator.AddTokensFromDel(pool, 10) + validator, pool, delShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, sdk.OneRat(), validator.DelegatorShareExRate()) @@ -124,7 +124,7 @@ func TestAddTokensValidatorUnbonded(t *testing.T) { pool.LooseTokens = sdk.NewRat(10) validator := NewValidator(addr1, pk1, Description{}) validator, pool = validator.UpdateStatus(pool, sdk.Unbonded) - validator, pool, delShares := validator.AddTokensFromDel(pool, 10) + validator, pool, delShares := validator.AddTokensFromDel(pool, sdk.NewInt(10)) require.Equal(t, sdk.OneRat(), validator.DelegatorShareExRate()) @@ -189,7 +189,7 @@ func TestUpdateStatus(t *testing.T) { pool.LooseTokens = sdk.NewRat(100) validator := NewValidator(addr1, pk1, Description{}) - validator, pool, _ = validator.AddTokensFromDel(pool, 100) + validator, pool, _ = validator.AddTokensFromDel(pool, sdk.NewInt(100)) require.Equal(t, sdk.Unbonded, validator.Status) require.Equal(t, int64(100), validator.Tokens.RoundInt64()) require.Equal(t, int64(0), pool.BondedTokens.RoundInt64()) @@ -226,7 +226,7 @@ func TestPossibleOverflow(t *testing.T) { } tokens := int64(71) msg := fmt.Sprintf("validator %#v", validator) - newValidator, _, _ := validator.AddTokensFromDel(pool, tokens) + newValidator, _, _ := validator.AddTokensFromDel(pool, sdk.NewInt(tokens)) msg = fmt.Sprintf("Added %d tokens to %s", tokens, msg) require.False(t, newValidator.DelegatorShareExRate().LT(sdk.ZeroRat()), From c2e8f7a57e00b194060197f152d769f0b6b781e8 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Mon, 6 Aug 2018 18:53:23 +0800 Subject: [PATCH 24/52] modify cli_test(coin int64 --> Int) --- cmd/gaia/app/genesis.go | 10 ++++---- cmd/gaia/cli_test/cli_test.go | 44 +++++++++++++++++++---------------- types/coin.go | 7 +++--- x/bank/msgs_test.go | 2 +- x/params/genesis.go | 6 ++--- x/stake/types/validator.go | 18 ++++++++++++++ 6 files changed, 54 insertions(+), 33 deletions(-) diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index b0c82ab37665..11d64b23add2 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -158,12 +158,12 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState accAuth := auth.NewBaseAccountWithAddress(genTx.Address) accAuth.Coins = sdk.Coins{ - params.DefaultPrecison(sdk.Coin{genTx.Name, sdk.NewInt(2000000000)}), - params.DefaultPrecison(sdk.Coin{"steak", sdk.NewInt(1000)}), + sdk.Coin{genTx.Name, params.DefaultPrecison(2000000000)}, + sdk.Coin{"steak", params.DefaultPrecison(freeFermionsAcc)}, } acc := NewGenesisAccount(&accAuth) genaccs[i] = acc - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionsAcc)) // increase the supply + stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRatFromInt(params.DefaultPrecison(freeFermionsAcc))) // increase the supply // add the validator if len(genTx.Name) > 0 { @@ -171,11 +171,11 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState validator := stake.NewValidator(genTx.Address, sdk.MustGetAccPubKeyBech32(genTx.PubKey), desc) - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionVal)) // increase the supply + stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRatFromInt(params.DefaultPrecison(freeFermionVal))) // increase the supply // add some new shares to the validator var issuedDelShares sdk.Rat - validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, freeFermionVal) + validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromInt(stakeData.Pool, params.DefaultPrecison(freeFermionVal)) stakeData.Validators = append(stakeData.Validators, validator) // create the self-delegation from the issuedDelShares diff --git a/cmd/gaia/cli_test/cli_test.go b/cmd/gaia/cli_test/cli_test.go index fa2d459e2dae..f19c4561579b 100644 --- a/cmd/gaia/cli_test/cli_test.go +++ b/cmd/gaia/cli_test/cli_test.go @@ -20,6 +20,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/params" ) var ( @@ -55,35 +56,38 @@ func TestGaiaCLISend(t *testing.T) { barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --output=json --home=%s", gaiacliHome)) fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t,toBigInt(50) , fooAcc.GetCoins().AmountOf("steak")) - executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo", flags, barAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=%vsteak --to=%s --from=foo", flags,toBigInt(10), barAddr), pass) tests.WaitForNextNBlocksTM(2, port) barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(10), barAcc.GetCoins().AmountOf("steak")) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(40), fooAcc.GetCoins().AmountOf("steak")) // test autosequencing - executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo", flags, barAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=%vsteak --to=%s --from=foo", flags,toBigInt(10), barAddr), pass) tests.WaitForNextNBlocksTM(2, port) barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, int64(20), barAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(20), barAcc.GetCoins().AmountOf("steak")) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(30), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(30), fooAcc.GetCoins().AmountOf("steak")) // test memo - executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo --memo 'testmemo'", flags, barAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=%vsteak --to=%s --from=foo --memo 'testmemo'", flags,toBigInt(10), barAddr), pass) tests.WaitForNextNBlocksTM(2, port) barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, int64(30), barAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(30), barAcc.GetCoins().AmountOf("steak")) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(20), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(20), fooAcc.GetCoins().AmountOf("steak")) } +func toBigInt(amount int) sdk.Int{ + return params.Pow10(18).Mul(sdk.NewInt(int64(amount))) +} func TestGaiaCLICreateValidator(t *testing.T) { tests.ExecuteT(t, fmt.Sprintf("gaiad --home=%s unsafe_reset_all", gaiadHome)) executeWrite(t, fmt.Sprintf("gaiacli keys delete --home=%s foo", gaiacliHome), pass) @@ -107,27 +111,27 @@ func TestGaiaCLICreateValidator(t *testing.T) { barAddr, barPubKey := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --output=json --home=%s", gaiacliHome)) barCeshPubKey := sdk.MustBech32ifyValPub(barPubKey) - executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo", flags, barAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=%vsteak --to=%s --from=foo", flags,toBigInt(10), barAddr), pass) tests.WaitForNextNBlocksTM(2, port) barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(10), barAcc.GetCoins().AmountOf("steak")) fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(40), fooAcc.GetCoins().AmountOf("steak")) // create validator cvStr := fmt.Sprintf("gaiacli stake create-validator %v", flags) cvStr += fmt.Sprintf(" --from=%s", "bar") cvStr += fmt.Sprintf(" --address-validator=%s", barAddr) cvStr += fmt.Sprintf(" --pubkey=%s", barCeshPubKey) - cvStr += fmt.Sprintf(" --amount=%v", "2steak") + cvStr += fmt.Sprintf(" --amount=%vsteak", toBigInt(2)) cvStr += fmt.Sprintf(" --moniker=%v", "bar-vally") executeWrite(t, cvStr, pass) tests.WaitForNextNBlocksTM(2, port) barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, int64(8), barAcc.GetCoins().AmountOf("steak").Int64(), "%v", barAcc) + require.Equal(t, toBigInt(8), barAcc.GetCoins().AmountOf("steak"), "%v", barAcc) validator := executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %s --output=json %v", barAddr, flags)) require.Equal(t, validator.Owner, barAddr) @@ -174,23 +178,23 @@ func TestGaiaCLISubmitProposal(t *testing.T) { fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --output=json --home=%s", gaiacliHome)) fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(50), fooAcc.GetCoins().AmountOf("steak")) - executeWrite(t, fmt.Sprintf("gaiacli gov submit-proposal %v --proposer=%s --deposit=5steak --type=Text --title=Test --description=test --from=foo", flags, fooAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli gov submit-proposal %v --proposer=%s --deposit=%vsteak --type=Text --title=Test --description=test --from=foo", flags, fooAddr,toBigInt(5)), pass) tests.WaitForNextNBlocksTM(2, port) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(45), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(45), fooAcc.GetCoins().AmountOf("steak")) proposal1 := executeGetProposal(t, fmt.Sprintf("gaiacli gov query-proposal --proposalID=1 --output=json %v", flags)) require.Equal(t, int64(1), proposal1.GetProposalID()) require.Equal(t, gov.StatusDepositPeriod, proposal1.GetStatus()) - executeWrite(t, fmt.Sprintf("gaiacli gov deposit %v --depositer=%s --deposit=10steak --proposalID=1 --from=foo", flags, fooAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli gov deposit %v --depositer=%s --deposit=%vsteak --proposalID=1 --from=foo", flags, fooAddr,toBigInt(10)), pass) tests.WaitForNextNBlocksTM(2, port) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(35), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(35), fooAcc.GetCoins().AmountOf("steak")) proposal1 = executeGetProposal(t, fmt.Sprintf("gaiacli gov query-proposal --proposalID=1 --output=json %v", flags)) require.Equal(t, int64(1), proposal1.GetProposalID()) require.Equal(t, gov.StatusVotingPeriod, proposal1.GetStatus()) diff --git a/types/coin.go b/types/coin.go index eba645932146..ddcc813e1dfa 100644 --- a/types/coin.go +++ b/types/coin.go @@ -4,7 +4,6 @@ import ( "fmt" "regexp" "sort" - "strconv" "strings" ) @@ -292,12 +291,12 @@ func ParseCoin(coinStr string) (coin Coin, err error) { } denomStr, amountStr := matches[2], matches[1] - amount, err := strconv.Atoi(amountStr) - if err != nil { + amount, ok := NewIntFromString(amountStr) + if !ok { return } - return Coin{denomStr, NewInt(int64(amount))}, nil + return Coin{denomStr, amount}, nil } // ParseCoins will parse out a list of coins separated by commas. diff --git a/x/bank/msgs_test.go b/x/bank/msgs_test.go index b60cc65ad012..596e751b5e4b 100644 --- a/x/bank/msgs_test.go +++ b/x/bank/msgs_test.go @@ -257,7 +257,7 @@ func TestMsgIssueGetSignBytes(t *testing.T) { } res := msg.GetSignBytes() - expected := `{"banker":"cosmosaccaddr1d9h8qat5e4ehc5","outputs":[{"address":"cosmosaccaddr1d3hkzm3dveex7mfdvfsku6cwsauqd","coins":[{"amount":"10","denom":"atom"}]}]}` + expected := `{"banker":"faa1d9h8qat5umnd2g","outputs":[{"address":"faa1d3hkzm3dveex7mfdvfsku6crf5s7g","coins":[{"amount":"10","denom":"atom"}]}]}` require.Equal(t, expected, string(res)) } diff --git a/x/params/genesis.go b/x/params/genesis.go index 86e7b24dc404..715a560cb91e 100644 --- a/x/params/genesis.go +++ b/x/params/genesis.go @@ -20,9 +20,9 @@ type ParamGenesisState struct { Coins []CoinConfig `json:"coins"` } -func DefaultPrecison(coin types.Coin) types.Coin { - coin.Amount = Pow10(IrisPrecision).Mul(coin.Amount) - return coin + +func DefaultPrecison(amount int64) sdk.Int { + return Pow10(IrisPrecision).Mul(sdk.NewInt(amount)) } func ToBigCoin(ctx sdk.Context, k Getter, coin types.Coin) (types.Coin, error) { diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index f177c123d07e..2ac886276987 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -392,6 +392,24 @@ func (v Validator) AddTokensFromDel(pool Pool, amount int64) (Validator, Pool, s return v, pool, issuedShares } +// AddTokensFromDel adds tokens to a validator +func (v Validator) AddTokensFromInt(pool Pool, amount sdk.Int) (Validator, Pool, sdk.Rat) { + + // bondedShare/delegatedShare + exRate := v.DelegatorShareExRate() + amountRat := sdk.NewRatFromInt(amount) + + if v.Status == sdk.Bonded { + pool = pool.looseTokensToBonded(amountRat) + } + + v.Tokens = v.Tokens.Add(amountRat) + issuedShares := amountRat.Quo(exRate) + v.DelegatorShares = v.DelegatorShares.Add(issuedShares) + + return v, pool, issuedShares +} + // RemoveDelShares removes delegator shares from a validator. func (v Validator) RemoveDelShares(pool Pool, delShares sdk.Rat) (Validator, Pool, sdk.Rat) { issuedTokens := v.DelegatorShareExRate().Mul(delShares) From 704b8ef843242a714a0ec540b95eed5e248d6499 Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Mon, 6 Aug 2018 18:54:27 +0800 Subject: [PATCH 25/52] refactor code --- cmd/gaia/app/genesis.go | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index a8b18ff8034a..81432d7e1153 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -142,7 +142,12 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState // start with the default staking genesis state stakeData := stake.DefaultGenesisState() - + precisionNumber := math.Pow10(int(stakeData.Params.DenomPrecision)) + if precisionNumber > math.MaxInt64 { + panic(errors.New("precision is too high, int64 is overflow")) + } + precisionInt64 := int64(precisionNumber) + tokenPrecision := sdk.NewRat(precisionInt64) // get genesis flag account information genaccs := make([]GenesisAccount, len(appGenTxs)) for i, appGenTx := range appGenTxs { @@ -156,18 +161,11 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState // create the genesis account, give'm few steaks and a buncha token with there name accAuth := auth.NewBaseAccountWithAddress(genTx.Address) accAuth.Coins = sdk.Coins{ - {genTx.Name + "Token", sdk.NewInt(1000)}, - {"steak", sdk.NewInt(freeFermionsAcc)}, + {genTx.Name + "Token", sdk.NewInt(1000).Mul(sdk.NewInt(precisionInt64))}, + {"steak", sdk.NewInt(freeFermionsAcc).Mul(sdk.NewInt(precisionInt64))}, } acc := NewGenesisAccount(&accAuth) genaccs[i] = acc - - precisionNumber := math.Pow10(int(stakeData.Params.DenomPrecision)) - if precisionNumber > math.MaxInt64 { - panic(errors.New("precision is too high, int64 is overflow")) - } - precisionInt64 := int64(precisionNumber) - tokenPrecision := sdk.NewRat(precisionInt64) stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionsAcc).Mul(tokenPrecision)) // increase the supply // add the validator From 87b42f82a01f8841c16c7fceac84d4638e54134f Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Tue, 7 Aug 2018 10:43:08 +0800 Subject: [PATCH 26/52] modify cli_test --- cmd/gaia/app/genesis.go | 10 ++--- cmd/gaia/cli_test/cli_test.go | 71 ++++++++++++++++++++++------------- x/gov/proposals_test.go | 3 ++ 3 files changed, 52 insertions(+), 32 deletions(-) diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index 11d64b23add2..f75fe0b46a53 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -158,12 +158,12 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState accAuth := auth.NewBaseAccountWithAddress(genTx.Address) accAuth.Coins = sdk.Coins{ - sdk.Coin{genTx.Name, params.DefaultPrecison(2000000000)}, - sdk.Coin{"steak", params.DefaultPrecison(freeFermionsAcc)}, + {genTx.Name + "Token", sdk.NewInt(1000)}, + {"steak", sdk.NewInt(freeFermionsAcc)}, } acc := NewGenesisAccount(&accAuth) genaccs[i] = acc - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRatFromInt(params.DefaultPrecison(freeFermionsAcc))) // increase the supply + stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionsAcc)) // increase the supply // add the validator if len(genTx.Name) > 0 { @@ -171,11 +171,11 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState validator := stake.NewValidator(genTx.Address, sdk.MustGetAccPubKeyBech32(genTx.PubKey), desc) - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRatFromInt(params.DefaultPrecison(freeFermionVal))) // increase the supply + stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionVal)) // increase the supply // add some new shares to the validator var issuedDelShares sdk.Rat - validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromInt(stakeData.Pool, params.DefaultPrecison(freeFermionVal)) + validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, freeFermionVal) stakeData.Validators = append(stakeData.Validators, validator) // create the self-delegation from the issuedDelShares diff --git a/cmd/gaia/cli_test/cli_test.go b/cmd/gaia/cli_test/cli_test.go index f19c4561579b..037a8d8f5fb1 100644 --- a/cmd/gaia/cli_test/cli_test.go +++ b/cmd/gaia/cli_test/cli_test.go @@ -20,7 +20,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/cosmos/cosmos-sdk/x/params" ) var ( @@ -56,38 +55,35 @@ func TestGaiaCLISend(t *testing.T) { barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --output=json --home=%s", gaiacliHome)) fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t,toBigInt(50) , fooAcc.GetCoins().AmountOf("steak")) + require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf("steak").Int64()) - executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=%vsteak --to=%s --from=foo", flags,toBigInt(10), barAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo", flags, barAddr), pass) tests.WaitForNextNBlocksTM(2, port) barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, toBigInt(10), barAcc.GetCoins().AmountOf("steak")) + require.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak").Int64()) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, toBigInt(40), fooAcc.GetCoins().AmountOf("steak")) + require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak").Int64()) // test autosequencing - executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=%vsteak --to=%s --from=foo", flags,toBigInt(10), barAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo", flags, barAddr), pass) tests.WaitForNextNBlocksTM(2, port) barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, toBigInt(20), barAcc.GetCoins().AmountOf("steak")) + require.Equal(t, int64(20), barAcc.GetCoins().AmountOf("steak").Int64()) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, toBigInt(30), fooAcc.GetCoins().AmountOf("steak")) + require.Equal(t, int64(30), fooAcc.GetCoins().AmountOf("steak").Int64()) // test memo - executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=%vsteak --to=%s --from=foo --memo 'testmemo'", flags,toBigInt(10), barAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo --memo 'testmemo'", flags, barAddr), pass) tests.WaitForNextNBlocksTM(2, port) barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, toBigInt(30), barAcc.GetCoins().AmountOf("steak")) + require.Equal(t, int64(30), barAcc.GetCoins().AmountOf("steak").Int64()) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, toBigInt(20), fooAcc.GetCoins().AmountOf("steak")) + require.Equal(t, int64(20), fooAcc.GetCoins().AmountOf("steak").Int64()) } -func toBigInt(amount int) sdk.Int{ - return params.Pow10(18).Mul(sdk.NewInt(int64(amount))) -} func TestGaiaCLICreateValidator(t *testing.T) { tests.ExecuteT(t, fmt.Sprintf("gaiad --home=%s unsafe_reset_all", gaiadHome)) executeWrite(t, fmt.Sprintf("gaiacli keys delete --home=%s foo", gaiacliHome), pass) @@ -111,27 +107,27 @@ func TestGaiaCLICreateValidator(t *testing.T) { barAddr, barPubKey := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --output=json --home=%s", gaiacliHome)) barCeshPubKey := sdk.MustBech32ifyValPub(barPubKey) - executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=%vsteak --to=%s --from=foo", flags,toBigInt(10), barAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo", flags, barAddr), pass) tests.WaitForNextNBlocksTM(2, port) barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, toBigInt(10), barAcc.GetCoins().AmountOf("steak")) + require.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak").Int64()) fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, toBigInt(40), fooAcc.GetCoins().AmountOf("steak")) + require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak").Int64()) // create validator cvStr := fmt.Sprintf("gaiacli stake create-validator %v", flags) cvStr += fmt.Sprintf(" --from=%s", "bar") - cvStr += fmt.Sprintf(" --address-validator=%s", barAddr) cvStr += fmt.Sprintf(" --pubkey=%s", barCeshPubKey) - cvStr += fmt.Sprintf(" --amount=%vsteak", toBigInt(2)) + cvStr += fmt.Sprintf(" --amount=%v", "2steak") cvStr += fmt.Sprintf(" --moniker=%v", "bar-vally") + cvStr += fmt.Sprintf(" --address-validator=%s", barAddr) executeWrite(t, cvStr, pass) tests.WaitForNextNBlocksTM(2, port) barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, toBigInt(8), barAcc.GetCoins().AmountOf("steak"), "%v", barAcc) + require.Equal(t, int64(8), barAcc.GetCoins().AmountOf("steak").Int64(), "%v", barAcc) validator := executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %s --output=json %v", barAddr, flags)) require.Equal(t, validator.Owner, barAddr) @@ -178,31 +174,52 @@ func TestGaiaCLISubmitProposal(t *testing.T) { fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --output=json --home=%s", gaiacliHome)) fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, toBigInt(50), fooAcc.GetCoins().AmountOf("steak")) + require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf("steak").Int64()) - executeWrite(t, fmt.Sprintf("gaiacli gov submit-proposal %v --proposer=%s --deposit=%vsteak --type=Text --title=Test --description=test --from=foo", flags, fooAddr,toBigInt(5)), pass) + // unbond a single share + spStr := fmt.Sprintf("gaiacli gov submit-proposal %v", flags) + spStr += fmt.Sprintf(" --from=%s", "foo") + spStr += fmt.Sprintf(" --deposit=%s", "5steak") + spStr += fmt.Sprintf(" --type=%s", "Text") + spStr += fmt.Sprintf(" --title=%s", "Test") + spStr += fmt.Sprintf(" --description=%s", "test") + spStr += fmt.Sprintf(" --proposer=%s", fooAddr) + + executeWrite(t, spStr, pass) tests.WaitForNextNBlocksTM(2, port) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, toBigInt(45), fooAcc.GetCoins().AmountOf("steak")) + require.Equal(t, int64(45), fooAcc.GetCoins().AmountOf("steak").Int64()) proposal1 := executeGetProposal(t, fmt.Sprintf("gaiacli gov query-proposal --proposalID=1 --output=json %v", flags)) require.Equal(t, int64(1), proposal1.GetProposalID()) require.Equal(t, gov.StatusDepositPeriod, proposal1.GetStatus()) - executeWrite(t, fmt.Sprintf("gaiacli gov deposit %v --depositer=%s --deposit=%vsteak --proposalID=1 --from=foo", flags, fooAddr,toBigInt(10)), pass) + depositStr := fmt.Sprintf("gaiacli gov deposit %v", flags) + depositStr += fmt.Sprintf(" --from=%s", "foo") + depositStr += fmt.Sprintf(" --deposit=%s", "10steak") + depositStr += fmt.Sprintf(" --proposalID=%s", "1") + depositStr += fmt.Sprintf(" --depositer=%s", fooAddr) + + executeWrite(t, depositStr, pass) tests.WaitForNextNBlocksTM(2, port) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, toBigInt(35), fooAcc.GetCoins().AmountOf("steak")) + require.Equal(t, int64(35), fooAcc.GetCoins().AmountOf("steak").Int64()) proposal1 = executeGetProposal(t, fmt.Sprintf("gaiacli gov query-proposal --proposalID=1 --output=json %v", flags)) require.Equal(t, int64(1), proposal1.GetProposalID()) require.Equal(t, gov.StatusVotingPeriod, proposal1.GetStatus()) - executeWrite(t, fmt.Sprintf("gaiacli gov vote %v --proposalID=1 --voter=%s --option=Yes --from=foo", flags, fooAddr), pass) + voteStr := fmt.Sprintf("gaiacli gov vote %v", flags) + voteStr += fmt.Sprintf(" --from=%s", "foo") + voteStr += fmt.Sprintf(" --proposalID=%s", "1") + voteStr += fmt.Sprintf(" --option=%s", "Yes") + voteStr += fmt.Sprintf(" --voter=%s", fooAddr) + + executeWrite(t, voteStr, pass) tests.WaitForNextNBlocksTM(2, port) - vote := executeGetVote(t, fmt.Sprintf("gaiacli gov query-vote --proposalID=1 --voter=%s --output=json %v", fooAddr, flags)) + vote := executeGetVote(t, fmt.Sprintf("gaiacli gov query-vote --proposalID=1 --voter=%s --output=json %v", fooAddr, flags)) require.Equal(t, int64(1), vote.ProposalID) require.Equal(t, gov.OptionYes, vote.Option) diff --git a/x/gov/proposals_test.go b/x/gov/proposals_test.go index c8ad8f92a80b..b0777ec648b1 100644 --- a/x/gov/proposals_test.go +++ b/x/gov/proposals_test.go @@ -6,6 +6,7 @@ import ( "github.com/magiconair/properties/assert" abci "github.com/tendermint/tendermint/abci/types" "testing" + "github.com/cosmos/cosmos-sdk/x/params" ) func TestParameterProposal(t *testing.T) { @@ -44,4 +45,6 @@ func TestParameterProposal(t *testing.T) { func TestByte(t *testing.T) { fmt.Println(string([]byte{112,114,111,112,111,115,97,108,73,100})) + bInt :=sdk.NewRatFromInt(params.DefaultPrecison(100)) + fmt.Println(bInt) } From d7b6993cca6d62d3ce2fe9138cdd70d70fbdea35 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Tue, 7 Aug 2018 13:00:51 +0800 Subject: [PATCH 27/52] Merge branch 'irisnet/develop' of https://github.com/irisnet/cosmos-sdk into zhiqiang/irisnet/feature_gov # Conflicts: # x/gov/test_common.go --- x/gov/test_common.go | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 70b1ffc17f36..6bde627bd938 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -33,13 +33,9 @@ func getMockApp(t *testing.T, numGenAccs int) (*mock.App, Keeper, stake.Keeper, pk := params.NewKeeper(mapp.Cdc, keyGlobalParams) ck := bank.NewKeeper(mapp.AccountMapper) sk := stake.NewKeeper(mapp.Cdc, keyStake, ck, mapp.RegisterCodespace(stake.DefaultCodespace)) -<<<<<<< HEAD - keeper := NewKeeper(mapp.Cdc, keyGov,pk.Setter(),ck, sk, DefaultCodespace) - mapp.Router().AddRoute("gov", NewHandler(keeper)) -======= - keeper := NewKeeper(mapp.Cdc, keyGov, ck, sk, DefaultCodespace) - mapp.Router().AddRoute("gov", []*sdk.KVStoreKey{keyGov}, NewHandler(keeper)) ->>>>>>> b481cfdc58d1c4ad3c84078050c0ac1247a72b42 + + keeper := NewKeeper(mapp.Cdc, keyGov,pk.Setter(), ck, sk, DefaultCodespace) + mapp.Router().AddRoute("gov", []*sdk.KVStoreKey{keyGov, mapp.KeyAccount, keyStake}, NewHandler(keeper)) require.NoError(t, mapp.CompleteSetup([]*sdk.KVStoreKey{keyStake, keyGov, keyGlobalParams})) From 32411eb88f1cbc6038044b93fb373ea17ed8c317 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Tue, 7 Aug 2018 13:30:40 +0800 Subject: [PATCH 28/52] Merge branch 'irisnet/develop' of https://github.com/irisnet/cosmos-sdk into zhiqiang/irisnet/feature_gov --- examples/basecoin/app/app.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index 14d4550d326e..747cb9080b54 100644 --- a/examples/basecoin/app/app.go +++ b/examples/basecoin/app/app.go @@ -70,8 +70,8 @@ func NewBasecoinApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.Ba // register message routes app.Router(). - AddRoute("bank", bank.NewHandler(app.coinKeeper)). - AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)) + AddRoute("bank",[]*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.coinKeeper)). + AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC},ibc.NewHandler(app.ibcMapper, app.coinKeeper)) // perform initialization logic app.SetInitChainer(app.initChainer) From a2513508a72ef345102fd9d7a2a52829fbd8b135 Mon Sep 17 00:00:00 2001 From: chengsilei Date: Tue, 7 Aug 2018 14:16:59 +0800 Subject: [PATCH 29/52] fix bug in router --- baseapp/router.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/baseapp/router.go b/baseapp/router.go index b4722cb30c48..bea695334d59 100644 --- a/baseapp/router.go +++ b/baseapp/router.go @@ -73,7 +73,11 @@ func (rtr *router) RouteTable() (table []string) { for _, route := range rtr.routes { storelist := "" for _, store := range route.s { - storelist = storelist + ":" + store.Name() + if storelist == "" { + storelist = store.Name() + } else { + storelist = storelist + ":" + store.Name() + } } table = append(table, route.r+"/"+storelist) } From 5321ee93aa2a7716214de333a490f52a17ca3033 Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Tue, 7 Aug 2018 19:55:28 +0800 Subject: [PATCH 30/52] Merge from irisnet/develop and fix some bugs --- baseapp/baseapp.go | 53 ++++++++++++- baseapp/baseapp_test.go | 22 +++--- baseapp/router.go | 40 +++++++++- cmd/gaia/app/app.go | 12 +-- cmd/gaia/app/genesis.go | 5 ++ cmd/gaia/cli_test/cli_test.go | 72 ++++++++++------- cmd/gaia/cmd/gaiacli/main.go | 14 +++- cmd/gaia/cmd/gaiadebug/hack.go | 6 +- docs/sdk/core/examples/app1.go | 2 +- docs/sdk/core/examples/app2.go | 4 +- docs/sdk/core/examples/app3.go | 2 +- docs/sdk/core/examples/app4.go | 2 +- examples/basecoin/app/app.go | 4 +- examples/democoin/app/app.go | 12 +-- examples/democoin/x/cool/app_test.go | 2 +- examples/democoin/x/pow/app_test.go | 2 +- examples/kvstore/main.go | 2 +- server/mock/app.go | 2 +- store/rootmultistore.go | 113 ++++++++++++++++++++++----- store/rootmultistore_test.go | 55 +++++++++++++ types/coin.go | 7 +- types/errors.go | 3 + x/auth/ante.go | 2 + x/auth/ante_test.go | 27 ++++--- x/auth/feekeeper.go | 40 +++++----- x/auth/feekeeper_test.go | 23 +++--- x/bank/bench_test.go | 2 +- x/bank/msgs_test.go | 2 +- x/gov/client/cli/tx.go | 13 ++- x/gov/genesis.go | 26 +++++- x/gov/handler.go | 4 +- x/gov/keeper.go | 80 +++++++++---------- x/gov/msgs.go | 12 +++ x/gov/params.go | 91 +++++++++++++++++++++ x/gov/proposals.go | 57 ++++++++++++++ x/gov/proposals_test.go | 50 ++++++++++++ x/gov/test_common.go | 5 +- x/gov/wire.go | 5 ++ x/ibc/app_test.go | 2 +- x/mock/app_test.go | 2 +- x/params/client/cli/util.go | 29 +++++++ x/params/genesis.go | 67 ++++++++++++++++ x/slashing/app_test.go | 4 +- x/stake/app_test.go | 2 +- x/stake/types/validator.go | 18 +++++ 45 files changed, 806 insertions(+), 193 deletions(-) create mode 100644 x/gov/params.go create mode 100644 x/gov/proposals_test.go create mode 100644 x/params/client/cli/util.go create mode 100644 x/params/genesis.go diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 64d581245ad2..cccb4f8e7d56 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -39,6 +39,8 @@ const ( runTxModeDeliver runTxMode = iota ) +type RunMsg func(ctx sdk.Context, msgs []sdk.Msg) sdk.Result + // BaseApp reflects the ABCI application implementation. type BaseApp struct { // initialized on creation @@ -61,6 +63,7 @@ type BaseApp struct { endBlocker sdk.EndBlocker // logic to run after all txs, and to determine valset changes addrPeerFilter sdk.PeerFilter // filter peers by address and port pubkeyPeerFilter sdk.PeerFilter // filter peers by public key + runMsg RunMsg //-------------------- // Volatile @@ -136,6 +139,13 @@ func (app *BaseApp) MountStore(key sdk.StoreKey, typ sdk.StoreType) { app.cms.MountStoreWithDB(key, typ, nil) } +//////////////////// iris/cosmos-sdk begin /////////////////////////// +func (app *BaseApp) GetKVStore(key sdk.StoreKey) sdk.KVStore { + return app.cms.GetKVStore(key) +} + +//////////////////// iris/cosmos-sdk end /////////////////////////// + // Set the txDecoder function func (app *BaseApp) SetTxDecoder(txDecoder sdk.TxDecoder) { app.txDecoder = txDecoder @@ -189,6 +199,10 @@ func (app *BaseApp) SetPubKeyPeerFilter(pf sdk.PeerFilter) { } func (app *BaseApp) Router() Router { return app.router } +func (app *BaseApp) SetRunMsg(runMsg RunMsg) { + app.runMsg = runMsg +} + // load latest application version func (app *BaseApp) LoadLatestVersion(mainKey sdk.StoreKey) error { err := app.cms.LoadLatestVersion() @@ -442,8 +456,41 @@ func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeg // Implements ABCI func (app *BaseApp) CheckTx(txBytes []byte) (res abci.ResponseCheckTx) { - // Decode the Tx. + var result sdk.Result + + //////////////////// iris/cosmos-sdk begin /////////////////////////// + + upgradeKey := sdk.NewKVStoreKey("upgrade") + store := app.cms.GetStore(upgradeKey) + + if store != nil { + kvStore, ok := store.(sdk.KVStore) + if ok { + bz := kvStore.Get([]byte("d")) + if len(bz) == 1 && bz[0] == byte(1) { + result = sdk.NewError(sdk.CodespaceUndefined, sdk.CodeOutOfService, "").Result() + + return abci.ResponseCheckTx{ + Code: uint32(result.Code), + Data: result.Data, + Log: result.Log, + GasWanted: result.GasWanted, + GasUsed: result.GasUsed, + Fee: cmn.KI64Pair{ + []byte(result.FeeDenom), + result.FeeAmount, + }, + Tags: result.Tags, + } + } + } + } + + //////////////////// iris/cosmos-sdk end /////////////////////////// + + // Decode the Tx. + var tx, err = app.txDecoder(txBytes) if err != nil { result = err.Result() @@ -528,6 +575,10 @@ func (app *BaseApp) getContextForAnte(mode runTxMode, txBytes []byte) (ctx sdk.C // Iterates through msgs and executes them func (app *BaseApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) { + if app.runMsg != nil { + return app.runMsg(ctx, msgs) + } + // accumulate results logs := make([]string, 0, len(msgs)) var data []byte // NOTE: we just append them all (?!) diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 00897392ecaa..f675e9984a52 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -440,7 +440,7 @@ func TestCheckTx(t *testing.T) { nTxs := int64(5) // TODO: can remove this once CheckTx doesnt process msgs. - app.Router().AddRoute(typeMsgCounter, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { return sdk.Result{} }) + app.Router().AddRoute(typeMsgCounter, []*sdk.KVStoreKey{capKey}, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { return sdk.Result{} }) app.InitChain(abci.RequestInitChain{}) @@ -479,7 +479,7 @@ func TestDeliverTx(t *testing.T) { // test increments in the handler deliverKey := []byte("deliver-key") - app.Router().AddRoute(typeMsgCounter, handlerMsgCounter(t, capKey, deliverKey)) + app.Router().AddRoute(typeMsgCounter, []*sdk.KVStoreKey{capKey}, handlerMsgCounter(t, capKey, deliverKey)) nBlocks := 3 txPerHeight := 5 @@ -515,8 +515,8 @@ func TestMultiMsgDeliverTx(t *testing.T) { // increment the msg counter deliverKey := []byte("deliver-key") deliverKey2 := []byte("deliver-key2") - app.Router().AddRoute(typeMsgCounter, handlerMsgCounter(t, capKey, deliverKey)) - app.Router().AddRoute(typeMsgCounter2, handlerMsgCounter(t, capKey, deliverKey2)) + app.Router().AddRoute(typeMsgCounter, []*sdk.KVStoreKey{capKey}, handlerMsgCounter(t, capKey, deliverKey)) + app.Router().AddRoute(typeMsgCounter2, []*sdk.KVStoreKey{capKey}, handlerMsgCounter(t, capKey, deliverKey2)) // run a multi-msg tx // with all msgs the same type @@ -575,7 +575,7 @@ func TestConcurrentCheckDeliver(t *testing.T) { // Simulate() and Query("/app/simulate", txBytes) should give // the same results. func TestSimulateTx(t *testing.T) { - app, _, _ := setupBaseApp(t) + app, capKey, _ := setupBaseApp(t) gasConsumed := int64(5) app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { @@ -583,7 +583,7 @@ func TestSimulateTx(t *testing.T) { return }) - app.Router().AddRoute(typeMsgCounter, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { + app.Router().AddRoute(typeMsgCounter, []*sdk.KVStoreKey{capKey}, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { ctx.GasMeter().ConsumeGas(gasConsumed, "test") return sdk.Result{GasUsed: ctx.GasMeter().GasConsumed()} }) @@ -630,9 +630,9 @@ func TestSimulateTx(t *testing.T) { // TODO: add more func TestRunInvalidTransaction(t *testing.T) { - app, _, _ := setupBaseApp(t) + app, capKey, _ := setupBaseApp(t) app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { return }) - app.Router().AddRoute(typeMsgCounter, func(ctx sdk.Context, msg sdk.Msg) (res sdk.Result) { return }) + app.Router().AddRoute(typeMsgCounter, []*sdk.KVStoreKey{capKey}, func(ctx sdk.Context, msg sdk.Msg) (res sdk.Result) { return }) app.BeginBlock(abci.RequestBeginBlock{}) @@ -700,7 +700,7 @@ func TestRunInvalidTransaction(t *testing.T) { // Test that transactions exceeding gas limits fail func TestTxGasLimits(t *testing.T) { - app, _, _ := setupBaseApp(t) + app, capKey, _ := setupBaseApp(t) gasGranted := int64(10) app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { @@ -732,7 +732,7 @@ func TestTxGasLimits(t *testing.T) { } return }) - app.Router().AddRoute(typeMsgCounter, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { + app.Router().AddRoute(typeMsgCounter, []*sdk.KVStoreKey{capKey}, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { count := msg.(msgCounter).Counter ctx.GasMeter().ConsumeGas(count, "counter-handler") return sdk.Result{} @@ -794,7 +794,7 @@ func TestQuery(t *testing.T) { return }) - app.Router().AddRoute(typeMsgCounter, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { + app.Router().AddRoute(typeMsgCounter, []*sdk.KVStoreKey{capKey}, func(ctx sdk.Context, msg sdk.Msg) sdk.Result { store := ctx.KVStore(capKey) store.Set(key, value) return sdk.Result{} diff --git a/baseapp/router.go b/baseapp/router.go index abbbf9e1217b..bea695334d59 100644 --- a/baseapp/router.go +++ b/baseapp/router.go @@ -4,17 +4,25 @@ import ( "regexp" sdk "github.com/cosmos/cosmos-sdk/types" + "strings" ) // Router provides handlers for each transaction type. type Router interface { - AddRoute(r string, h sdk.Handler) (rtr Router) + + //////////////////// iris/cosmos-sdk begin /////////////////////////// + AddRoute(r string, s []*sdk.KVStoreKey, h sdk.Handler) (rtr Router) Route(path string) (h sdk.Handler) + RouteTable() (table []string) + //////////////////// iris/cosmos-sdk end /////////////////////////// } // map a transaction type to a handler and an initgenesis function type route struct { r string + //////////////////// iris/cosmos-sdk begin /////////////////////////// + s []*sdk.KVStoreKey + //////////////////// iris/cosmos-sdk end /////////////////////////// h sdk.Handler } @@ -34,15 +42,20 @@ func NewRouter() *router { var isAlpha = regexp.MustCompile(`^[a-zA-Z]+$`).MatchString // AddRoute - TODO add description -func (rtr *router) AddRoute(r string, h sdk.Handler) Router { - if !isAlpha(r) { +//////////////////// iris/cosmos-sdk begin /////////////////////////// +func (rtr *router) AddRoute(r string, s []*sdk.KVStoreKey, h sdk.Handler) Router { + rstrs := strings.Split(r, "-") + + if !isAlpha(rstrs[0]) { panic("route expressions can only contain alphabet characters") } - rtr.routes = append(rtr.routes, route{r, h}) + rtr.routes = append(rtr.routes, route{r, s, h}) return rtr } +//////////////////// iris/cosmos-sdk end /////////////////////////// + // Route - TODO add description // TODO handle expressive matches. func (rtr *router) Route(path string) (h sdk.Handler) { @@ -53,3 +66,22 @@ func (rtr *router) Route(path string) (h sdk.Handler) { } return nil } + +//////////////////// iris/cosmos-sdk begin /////////////////////////// + +func (rtr *router) RouteTable() (table []string) { + for _, route := range rtr.routes { + storelist := "" + for _, store := range route.s { + if storelist == "" { + storelist = store.Name() + } else { + storelist = storelist + ":" + store.Name() + } + } + table = append(table, route.r+"/"+storelist) + } + return +} + +//////////////////// iris/cosmos-sdk end /////////////////////////// diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 6bf204875894..439514ff09c2 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -99,11 +99,11 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio // register message routes app.Router(). - AddRoute("bank", bank.NewHandler(app.coinKeeper)). - AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)). - AddRoute("stake", stake.NewHandler(app.stakeKeeper)). - AddRoute("slashing", slashing.NewHandler(app.slashingKeeper)). - AddRoute("gov", gov.NewHandler(app.govKeeper)) + AddRoute("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.coinKeeper)). + AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). + AddRoute("stake", []*sdk.KVStoreKey{app.keyStake, app.keyAccount}, stake.NewHandler(app.stakeKeeper)). + AddRoute("slashing", []*sdk.KVStoreKey{app.keySlashing, app.keyStake}, slashing.NewHandler(app.slashingKeeper)). + AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake}, gov.NewHandler(app.govKeeper)) // initialize BaseApp app.SetInitChainer(app.initChainer) @@ -184,6 +184,8 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci gov.InitGenesis(ctx, app.govKeeper, gov.DefaultGenesisState()) + params.InitParamGenesis(ctx, app.paramsKeeper, genesisState.ParamsData) + auth.InitGenesis(ctx,app.paramsKeeper.Setter(),auth.DefaultGenesisState()) return abci.ResponseInitChain{} diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index 81432d7e1153..aeb3c324ae1d 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -15,6 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/stake" "math" + "github.com/cosmos/cosmos-sdk/x/params" ) var ( @@ -27,6 +28,7 @@ var ( type GenesisState struct { Accounts []GenesisAccount `json:"accounts"` StakeData stake.GenesisState `json:"stake"` + ParamsData params.ParamGenesisState `json:"params"` } // GenesisAccount doesn't need pubkey or sequence @@ -160,6 +162,7 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState // create the genesis account, give'm few steaks and a buncha token with there name accAuth := auth.NewBaseAccountWithAddress(genTx.Address) + accAuth.Coins = sdk.Coins{ {genTx.Name + "Token", sdk.NewInt(1000).Mul(sdk.NewInt(precisionInt64))}, {"steak", sdk.NewInt(freeFermionsAcc).Mul(sdk.NewInt(precisionInt64))}, @@ -194,10 +197,12 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState } } + paramsData := params.DefaultGenesisState() // create the final app state genesisState = GenesisState{ Accounts: genaccs, StakeData: stakeData, + ParamsData: paramsData, } return } diff --git a/cmd/gaia/cli_test/cli_test.go b/cmd/gaia/cli_test/cli_test.go index fa2d459e2dae..15899ad610d1 100644 --- a/cmd/gaia/cli_test/cli_test.go +++ b/cmd/gaia/cli_test/cli_test.go @@ -20,6 +20,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/params" ) var ( @@ -55,35 +56,41 @@ func TestGaiaCLISend(t *testing.T) { barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --output=json --home=%s", gaiacliHome)) fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t,toBigInt(50) , fooAcc.GetCoins().AmountOf("steak")) - executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo", flags, barAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=%vsteak --to=%s --from=foo --gas 10000 --fee 200000000000000steak", flags,toBigInt(10), barAddr), pass) tests.WaitForNextNBlocksTM(2, port) barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(10), barAcc.GetCoins().AmountOf("steak")) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.True(t, fooAcc.GetCoins().AmountOf("steak").LT(toBigInt(40))) + require.True(t, fooAcc.GetCoins().AmountOf("steak").GT(toBigInt(39))) // test autosequencing - executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo", flags, barAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=%vsteak --to=%s --from=foo --gas 10000 --fee 200000000000000steak", flags,toBigInt(10), barAddr), pass) tests.WaitForNextNBlocksTM(2, port) barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, int64(20), barAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(20), barAcc.GetCoins().AmountOf("steak")) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(30), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.True(t, fooAcc.GetCoins().AmountOf("steak").LT(toBigInt(30))) + require.True(t, fooAcc.GetCoins().AmountOf("steak").GT(toBigInt(29))) // test memo - executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo --memo 'testmemo'", flags, barAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=%vsteak --to=%s --from=foo --memo 'testmemo' --gas 10000 --fee 200000000000000steak", flags,toBigInt(10), barAddr), pass) tests.WaitForNextNBlocksTM(2, port) barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, int64(30), barAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(30), barAcc.GetCoins().AmountOf("steak")) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(20), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.True(t, fooAcc.GetCoins().AmountOf("steak").LT(toBigInt(20))) + require.True(t, fooAcc.GetCoins().AmountOf("steak").GT(toBigInt(19))) } +func toBigInt(amount int) sdk.Int{ + return params.Pow10(18).Mul(sdk.NewInt(int64(amount))) +} func TestGaiaCLICreateValidator(t *testing.T) { tests.ExecuteT(t, fmt.Sprintf("gaiad --home=%s unsafe_reset_all", gaiadHome)) executeWrite(t, fmt.Sprintf("gaiacli keys delete --home=%s foo", gaiacliHome), pass) @@ -107,38 +114,44 @@ func TestGaiaCLICreateValidator(t *testing.T) { barAddr, barPubKey := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show bar --output=json --home=%s", gaiacliHome)) barCeshPubKey := sdk.MustBech32ifyValPub(barPubKey) - executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%s --from=foo", flags, barAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=%vsteak --to=%s --from=foo --gas 10000 --fee 200000000000000steak", flags,toBigInt(10), barAddr), pass) tests.WaitForNextNBlocksTM(2, port) barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(10), barAcc.GetCoins().AmountOf("steak")) fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.True(t, fooAcc.GetCoins().AmountOf("steak").LT(toBigInt(40))) + require.True(t, fooAcc.GetCoins().AmountOf("steak").GT(toBigInt(39))) // create validator cvStr := fmt.Sprintf("gaiacli stake create-validator %v", flags) cvStr += fmt.Sprintf(" --from=%s", "bar") cvStr += fmt.Sprintf(" --address-validator=%s", barAddr) cvStr += fmt.Sprintf(" --pubkey=%s", barCeshPubKey) - cvStr += fmt.Sprintf(" --amount=%v", "2steak") + cvStr += fmt.Sprintf(" --amount=%vsteak", toBigInt(2)) cvStr += fmt.Sprintf(" --moniker=%v", "bar-vally") + cvStr += fmt.Sprintf(" --gas=%d", 100000) + cvStr += fmt.Sprintf(" --fee=%vsteak", 2000000000000000) executeWrite(t, cvStr, pass) tests.WaitForNextNBlocksTM(2, port) barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", barAddr, flags)) - require.Equal(t, int64(8), barAcc.GetCoins().AmountOf("steak").Int64(), "%v", barAcc) + require.True(t, barAcc.GetCoins().AmountOf("steak").LT(toBigInt(8)), "%v", barAcc) + require.True(t, barAcc.GetCoins().AmountOf("steak").GT(toBigInt(7)), "%v", barAcc) validator := executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %s --output=json %v", barAddr, flags)) require.Equal(t, validator.Owner, barAddr) - require.True(sdk.RatEq(t, sdk.NewRat(2), validator.Tokens)) + require.True(sdk.RatEq(t, sdk.NewRat(2).Mul(sdk.NewRatFromInt(sdk.NewInt(1000000000000000000))), validator.Tokens)) // unbond a single share unbondStr := fmt.Sprintf("gaiacli stake unbond begin %v", flags) unbondStr += fmt.Sprintf(" --from=%s", "bar") unbondStr += fmt.Sprintf(" --address-validator=%s", barAddr) unbondStr += fmt.Sprintf(" --address-delegator=%s", barAddr) - unbondStr += fmt.Sprintf(" --shares-amount=%v", "1") + unbondStr += fmt.Sprintf(" --shares-amount=%v", toBigInt(1).String()) + unbondStr += fmt.Sprintf(" --gas=%d", 100000) + unbondStr += fmt.Sprintf(" --fee=%vsteak", 2000000000000000) success := executeWrite(t, unbondStr, pass) require.True(t, success) @@ -149,7 +162,7 @@ func TestGaiaCLICreateValidator(t *testing.T) { require.Equal(t, int64(9), barAcc.GetCoins().AmountOf("steak").Int64(), "%v", barAcc) */ validator = executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %s --output=json %v", barAddr, flags)) - require.Equal(t, "1/1", validator.Tokens.String()) + require.Equal(t, "1000000000000000000/1", validator.Tokens.String()) } func TestGaiaCLISubmitProposal(t *testing.T) { @@ -174,28 +187,31 @@ func TestGaiaCLISubmitProposal(t *testing.T) { fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("gaiacli keys show foo --output=json --home=%s", gaiacliHome)) fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, toBigInt(50), fooAcc.GetCoins().AmountOf("steak")) - executeWrite(t, fmt.Sprintf("gaiacli gov submit-proposal %v --proposer=%s --deposit=5steak --type=Text --title=Test --description=test --from=foo", flags, fooAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli gov submit-proposal %v --proposer=%s --deposit=%vsteak --type=Text --title=Test --description=test --from=foo --gas 100000 --fee 2000000000000000steak", flags, fooAddr,toBigInt(5)), pass) tests.WaitForNextNBlocksTM(2, port) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(45), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.True(t, fooAcc.GetCoins().AmountOf("steak").LT(toBigInt(45))) + require.True(t, fooAcc.GetCoins().AmountOf("steak").GT(toBigInt(44))) + proposal1 := executeGetProposal(t, fmt.Sprintf("gaiacli gov query-proposal --proposalID=1 --output=json %v", flags)) require.Equal(t, int64(1), proposal1.GetProposalID()) require.Equal(t, gov.StatusDepositPeriod, proposal1.GetStatus()) - executeWrite(t, fmt.Sprintf("gaiacli gov deposit %v --depositer=%s --deposit=10steak --proposalID=1 --from=foo", flags, fooAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli gov deposit %v --depositer=%s --deposit=%vsteak --proposalID=1 --from=foo --gas 100000 --fee 2000000000000000steak", flags, fooAddr,toBigInt(10)), pass) tests.WaitForNextNBlocksTM(2, port) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %s %v", fooAddr, flags)) - require.Equal(t, int64(35), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.True(t, fooAcc.GetCoins().AmountOf("steak").LT(toBigInt(35))) + require.True(t, fooAcc.GetCoins().AmountOf("steak").GT(toBigInt(34))) proposal1 = executeGetProposal(t, fmt.Sprintf("gaiacli gov query-proposal --proposalID=1 --output=json %v", flags)) require.Equal(t, int64(1), proposal1.GetProposalID()) require.Equal(t, gov.StatusVotingPeriod, proposal1.GetStatus()) - executeWrite(t, fmt.Sprintf("gaiacli gov vote %v --proposalID=1 --voter=%s --option=Yes --from=foo", flags, fooAddr), pass) + executeWrite(t, fmt.Sprintf("gaiacli gov vote %v --proposalID=1 --voter=%s --option=Yes --from=foo --gas 100000 --fee 2000000000000000steak", flags, fooAddr), pass) tests.WaitForNextNBlocksTM(2, port) vote := executeGetVote(t, fmt.Sprintf("gaiacli gov query-vote --proposalID=1 --voter=%s --output=json %v", fooAddr, flags)) @@ -212,9 +228,9 @@ func TestGaiaCLISubmitProposal(t *testing.T) { // helper methods func getTestingHomeDirs() (string, string) { - tmpDir := os.TempDir() - gaiadHome := fmt.Sprintf("%s%s.test_gaiad", tmpDir, string(os.PathSeparator)) - gaiacliHome := fmt.Sprintf("%s%s.test_gaiacli", tmpDir, string(os.PathSeparator)) + //tmpDir := os.TempDir() + gaiadHome := fmt.Sprintf("%s%s.gaiad", "/home/lhy", string(os.PathSeparator)) + gaiacliHome := fmt.Sprintf("%s%s.gaiacli", "/home/lhy", string(os.PathSeparator)) return gaiadHome, gaiacliHome } @@ -318,4 +334,4 @@ func executeGetVotes(t *testing.T, cmdStr string) []gov.Vote { err := cdc.UnmarshalJSON([]byte(out), &votes) require.NoError(t, err, "out %v\n, err %v", out, err) return votes -} +} \ No newline at end of file diff --git a/cmd/gaia/cmd/gaiacli/main.go b/cmd/gaia/cmd/gaiacli/main.go index 7c66cb9ef7bf..a7d74c07a377 100644 --- a/cmd/gaia/cmd/gaiacli/main.go +++ b/cmd/gaia/cmd/gaiacli/main.go @@ -17,7 +17,7 @@ import ( ibccmd "github.com/cosmos/cosmos-sdk/x/ibc/client/cli" slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" - + paramscli "github.com/cosmos/cosmos-sdk/x/params/client/cli" "github.com/cosmos/cosmos-sdk/cmd/gaia/app" ) @@ -141,6 +141,18 @@ func main() { version.VersionCmd, ) + paramsCmd := &cobra.Command{ + Use: "params", + Short: "Governance and voting subcommands", + } + + paramsCmd.AddCommand( + client.GetCommands( + paramscli.QueryParam("params",cdc), + )...) + + rootCmd.AddCommand(paramsCmd) + // prepare and add flags executor := cli.PrepareMainCmd(rootCmd, "GA", app.DefaultCLIHome) err := executor.Execute() diff --git a/cmd/gaia/cmd/gaiadebug/hack.go b/cmd/gaia/cmd/gaiadebug/hack.go index 2e2b96205210..ddf2888d4a2b 100644 --- a/cmd/gaia/cmd/gaiadebug/hack.go +++ b/cmd/gaia/cmd/gaiadebug/hack.go @@ -176,9 +176,9 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.BaseAp // register message routes app.Router(). - AddRoute("bank", bank.NewHandler(app.coinKeeper)). - AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)). - AddRoute("stake", stake.NewHandler(app.stakeKeeper)) + AddRoute("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.coinKeeper)). + AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). + AddRoute("stake", []*sdk.KVStoreKey{app.keySlashing}, stake.NewHandler(app.stakeKeeper)) // initialize BaseApp app.SetInitChainer(app.initChainer) diff --git a/docs/sdk/core/examples/app1.go b/docs/sdk/core/examples/app1.go index b208f75cf7e5..f65de7d9f982 100644 --- a/docs/sdk/core/examples/app1.go +++ b/docs/sdk/core/examples/app1.go @@ -32,7 +32,7 @@ func NewApp1(logger log.Logger, db dbm.DB) *bapp.BaseApp { // Register message routes. // Note the handler gets access to the account store. app.Router(). - AddRoute("send", handleMsgSend(keyAccount)) + AddRoute("send", []*sdk.KVStoreKey{keyAccount}, handleMsgSend(keyAccount)) // Mount stores and load the latest state. app.MountStoresIAVL(keyAccount) diff --git a/docs/sdk/core/examples/app2.go b/docs/sdk/core/examples/app2.go index 12eab1c510b1..0af846d79b03 100644 --- a/docs/sdk/core/examples/app2.go +++ b/docs/sdk/core/examples/app2.go @@ -50,8 +50,8 @@ func NewApp2(logger log.Logger, db dbm.DB) *bapp.BaseApp { // Register message routes. // Note the handler gets access to the account store. app.Router(). - AddRoute("send", handleMsgSend(keyAccount)). - AddRoute("issue", handleMsgIssue(keyAccount, keyIssue)) + AddRoute("send", []*sdk.KVStoreKey{keyAccount}, handleMsgSend(keyAccount)). + AddRoute("issue",[]*sdk.KVStoreKey{keyIssue}, handleMsgIssue(keyAccount, keyIssue)) // Mount stores and load the latest state. app.MountStoresIAVL(keyAccount, keyIssue) diff --git a/docs/sdk/core/examples/app3.go b/docs/sdk/core/examples/app3.go index 853ad687e17d..33bd06f8f3de 100644 --- a/docs/sdk/core/examples/app3.go +++ b/docs/sdk/core/examples/app3.go @@ -37,7 +37,7 @@ func NewApp3(logger log.Logger, db dbm.DB) *bapp.BaseApp { // Register message routes. // Note the handler gets access to app.Router(). - AddRoute("send", bank.NewHandler(coinKeeper)) + AddRoute("send", []*sdk.KVStoreKey{keyAccount}, bank.NewHandler(coinKeeper)) // Mount stores and load the latest state. app.MountStoresIAVL(keyAccount, keyFees) diff --git a/docs/sdk/core/examples/app4.go b/docs/sdk/core/examples/app4.go index a8ef37cee5a5..72529996d601 100644 --- a/docs/sdk/core/examples/app4.go +++ b/docs/sdk/core/examples/app4.go @@ -43,7 +43,7 @@ func NewApp4(logger log.Logger, db dbm.DB) *bapp.BaseApp { // Register message routes. // Note the handler gets access to the account store. app.Router(). - AddRoute("send", bank.NewHandler(coinKeeper)) + AddRoute("send", []*sdk.KVStoreKey{keyAccount}, bank.NewHandler(coinKeeper)) // Mount stores and load the latest state. app.MountStoresIAVL(keyAccount, keyFees) diff --git a/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index 14d4550d326e..ddeea64186cf 100644 --- a/examples/basecoin/app/app.go +++ b/examples/basecoin/app/app.go @@ -70,8 +70,8 @@ func NewBasecoinApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.Ba // register message routes app.Router(). - AddRoute("bank", bank.NewHandler(app.coinKeeper)). - AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)) + AddRoute("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.coinKeeper)). + AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)) // perform initialization logic app.SetInitChainer(app.initChainer) diff --git a/examples/democoin/app/app.go b/examples/democoin/app/app.go index 51d10002a726..b6328efcbd9c 100644 --- a/examples/democoin/app/app.go +++ b/examples/democoin/app/app.go @@ -81,12 +81,12 @@ func NewDemocoinApp(logger log.Logger, db dbm.DB) *DemocoinApp { app.ibcMapper = ibc.NewMapper(app.cdc, app.capKeyIBCStore, app.RegisterCodespace(ibc.DefaultCodespace)) app.stakeKeeper = simplestake.NewKeeper(app.capKeyStakingStore, app.coinKeeper, app.RegisterCodespace(simplestake.DefaultCodespace)) app.Router(). - AddRoute("bank", bank.NewHandler(app.coinKeeper)). - AddRoute("cool", cool.NewHandler(app.coolKeeper)). - AddRoute("pow", app.powKeeper.Handler). - AddRoute("sketchy", sketchy.NewHandler()). - AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)). - AddRoute("simplestake", simplestake.NewHandler(app.stakeKeeper)) + AddRoute("bank", []*sdk.KVStoreKey{app.capKeyAccountStore}, bank.NewHandler(app.coinKeeper)). + AddRoute("cool", []*sdk.KVStoreKey{app.capKeyAccountStore, app.capKeyMainStore}, cool.NewHandler(app.coolKeeper)). + AddRoute("pow", []*sdk.KVStoreKey{app.capKeyPowStore}, app.powKeeper.Handler). + AddRoute("sketchy", []*sdk.KVStoreKey{}, sketchy.NewHandler()). + AddRoute("ibc", []*sdk.KVStoreKey{app.capKeyIBCStore, app.capKeyAccountStore}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). + AddRoute("simplestake", []*sdk.KVStoreKey{app.capKeyStakingStore}, simplestake.NewHandler(app.stakeKeeper)) // Initialize BaseApp. app.SetInitChainer(app.initChainerFn(app.coolKeeper, app.powKeeper)) diff --git a/examples/democoin/x/cool/app_test.go b/examples/democoin/x/cool/app_test.go index 71b4202bc332..9a5f0e141a93 100644 --- a/examples/democoin/x/cool/app_test.go +++ b/examples/democoin/x/cool/app_test.go @@ -51,7 +51,7 @@ func getMockApp(t *testing.T) *mock.App { keyCool := sdk.NewKVStoreKey("cool") coinKeeper := bank.NewKeeper(mapp.AccountMapper) keeper := NewKeeper(keyCool, coinKeeper, mapp.RegisterCodespace(DefaultCodespace)) - mapp.Router().AddRoute("cool", NewHandler(keeper)) + mapp.Router().AddRoute("cool", []*sdk.KVStoreKey{keyCool}, NewHandler(keeper)) mapp.SetInitChainer(getInitChainer(mapp, keeper, "ice-cold")) diff --git a/examples/democoin/x/pow/app_test.go b/examples/democoin/x/pow/app_test.go index 783f13d57bb6..e38c6ecc14cf 100644 --- a/examples/democoin/x/pow/app_test.go +++ b/examples/democoin/x/pow/app_test.go @@ -28,7 +28,7 @@ func getMockApp(t *testing.T) *mock.App { coinKeeper := bank.NewKeeper(mapp.AccountMapper) config := Config{"pow", 1} keeper := NewKeeper(keyPOW, config, coinKeeper, mapp.RegisterCodespace(DefaultCodespace)) - mapp.Router().AddRoute("pow", keeper.Handler) + mapp.Router().AddRoute("pow", []*sdk.KVStoreKey{keyPOW}, keeper.Handler) mapp.SetInitChainer(getInitChainer(mapp, keeper)) diff --git a/examples/kvstore/main.go b/examples/kvstore/main.go index 47416da05706..14de13fb5d26 100644 --- a/examples/kvstore/main.go +++ b/examples/kvstore/main.go @@ -41,7 +41,7 @@ func main() { baseApp.SetTxDecoder(decodeTx) // Set a handler Route. - baseApp.Router().AddRoute("kvstore", Handler(capKeyMainStore)) + baseApp.Router().AddRoute("kvstore", []*sdk.KVStoreKey{capKeyMainStore}, Handler(capKeyMainStore)) // Load latest version. if err := baseApp.LoadLatestVersion(capKeyMainStore); err != nil { diff --git a/server/mock/app.go b/server/mock/app.go index 5229da41eeb9..91514b6e94a2 100644 --- a/server/mock/app.go +++ b/server/mock/app.go @@ -41,7 +41,7 @@ func NewApp(rootDir string, logger log.Logger) (abci.Application, error) { baseApp.SetInitChainer(InitChainer(capKeyMainStore)) // Set a handler Route. - baseApp.Router().AddRoute("kvstore", KVStoreHandler(capKeyMainStore)) + baseApp.Router().AddRoute("kvstore", []*sdk.KVStoreKey{capKeyMainStore}, KVStoreHandler(capKeyMainStore)) // Load latest version. if err := baseApp.LoadLatestVersion(capKeyMainStore); err != nil { diff --git a/store/rootmultistore.go b/store/rootmultistore.go index 255afffbd5a1..e9c1a35040f4 100644 --- a/store/rootmultistore.go +++ b/store/rootmultistore.go @@ -129,10 +129,17 @@ func (rs *rootMultiStore) LoadVersion(ver int64) error { newStores[key] = store } - // If any CommitStoreLoaders were not used, return error. - for key := range rs.storesParams { + // If any CommitStoreLoaders were not used, create the new one. + for key, storeParams := range rs.storesParams { if _, ok := newStores[key]; !ok { - return fmt.Errorf("unused CommitStoreLoader: %v", key) + //////////////////// iris/cosmos-sdk begin /////////////////////////// + id := CommitID{} + store, err := rs.loadCommitStoreFromParams(id, storeParams) + if err != nil { + return fmt.Errorf("failed to load rootMultiStore: %v", err) + } + newStores[key] = store + //////////////////// iris/cosmos-sdk end /////////////////////////// } } @@ -226,7 +233,7 @@ func (rs *rootMultiStore) CacheMultiStore() CacheMultiStore { // Implements MultiStore. func (rs *rootMultiStore) GetStore(key StoreKey) Store { - return rs.stores[key] + return rs.getStoreByName(key.Name()) } // GetKVStore implements the MultiStore interface. If tracing is enabled on the @@ -432,29 +439,99 @@ func setLatestVersion(batch dbm.Batch, version int64) { batch.Set([]byte(latestVersionKey), latestBytes) } +// Commits each store and returns a new commitInfo. +//// Commits each store and returns a new commitInfo. +//func commitStores(version int64, storeMap map[StoreKey]CommitStore) commitInfo { +// storeInfos := make([]storeInfo, 0, len(storeMap)) +// +// for key, store := range storeMap { +// // Commit +// commitID := store.Commit() +// +// // Record CommitID +// si := storeInfo{} +// si.Name = key.Name() +// si.Core.CommitID = commitID +// // si.Core.StoreType = store.GetStoreType() +// storeInfos = append(storeInfos, si) +// } +// +// ci := commitInfo{ +// Version: version, +// StoreInfos: storeInfos, +// } +// return ci +//} + +//////////////////// iris/cosmos-sdk begin/////////////////////////// // Commits each store and returns a new commitInfo. func commitStores(version int64, storeMap map[StoreKey]CommitStore) commitInfo { - storeInfos := make([]storeInfo, 0, len(storeMap)) + + storemap := make(map[string]CommitStore) for key, store := range storeMap { - // Commit - commitID := store.Commit() - - // Record CommitID - si := storeInfo{} - si.Name = key.Name() - si.Core.CommitID = commitID - // si.Core.StoreType = store.GetStoreType() - storeInfos = append(storeInfos, si) + fmt.Println(key) + storemap[key.Name()] = store } - ci := commitInfo{ - Version: version, - StoreInfos: storeInfos, + upgrade := storemap["upgrade"] + + if upgrade != nil { + + upgradeStore := upgrade.(KVStore) + bz := upgradeStore.Get([]byte("k/")) //CurrentStoreKey + storekeys := string(bz) //splitby":" + + storekeyslist := strings.Split(storekeys, ":") + + storeInfos := make([]storeInfo, 0, len(storekeyslist)) + + for _, key := range storekeyslist { + + if store, ok := storemap[key]; ok { + // Commit + commitID := store.Commit() + + // Record CommitID + si := storeInfo{} + si.Name = key + si.Core.CommitID = commitID + // si.Core.StoreType = store.GetStoreType() + storeInfos = append(storeInfos, si) + } + } + + ci := commitInfo{ + Version: version, + StoreInfos: storeInfos, + } + return ci + } else { + storeInfos := make([]storeInfo, 0, len(storeMap)) + + for key, store := range storeMap { + // Commit + commitID := store.Commit() + + // Record CommitID + si := storeInfo{} + si.Name = key.Name() + si.Core.CommitID = commitID + // si.Core.StoreType = store.GetStoreType() + storeInfos = append(storeInfos, si) + } + + ci := commitInfo{ + Version: version, + StoreInfos: storeInfos, + } + return ci } - return ci + } +//////////////////// iris/cosmos-sdk end/////////////////////////// + // Gets commitInfo from disk. func getCommitInfo(db dbm.DB, ver int64) (commitInfo, error) { diff --git a/store/rootmultistore_test.go b/store/rootmultistore_test.go index f564114626aa..ed1a26d82cb7 100644 --- a/store/rootmultistore_test.go +++ b/store/rootmultistore_test.go @@ -76,6 +76,43 @@ func TestMultistoreCommitLoad(t *testing.T) { checkStore(t, store, commitID, commitID) } +//////////////////// iris/cosmos-sdk begin /////////////////////////// +func TestCommitStoreLoadersNotUsed(t *testing.T) { + var db dbm.DB = dbm.NewMemDB() + if useDebugDB { + db = dbm.NewDebugDB("CMS", db) + } + store := newMultiStoreWithMounts(db) + err := store.LoadLatestVersion() + require.Nil(t, err) + + // New store has empty last commit. + commitID := CommitID{} + checkStore(t, store, commitID, commitID) + + // Make sure we can get stores by name. + s1 := store.getStoreByName("store1") + require.NotNil(t, s1) + s3 := store.getStoreByName("store3") + require.NotNil(t, s3) + s5 := store.getStoreByName("store5") + require.Nil(t, s5) + + store = newMultiStoreWithMountsNewVersion(db) + err = store.LoadLatestVersion() + require.Nil(t, err) + + // Make sure we can get stores by name. + s1 = store.getStoreByName("store1") + require.NotNil(t, s1) + s3 = store.getStoreByName("store3") + require.NotNil(t, s3) + s5 = store.getStoreByName("store5") + require.NotNil(t, s5) +} + +//////////////////// iris/cosmos-sdk end /////////////////////////// + func TestParsePath(t *testing.T) { _, _, err := parsePath("foo") require.Error(t, err) @@ -173,6 +210,24 @@ func newMultiStoreWithMounts(db dbm.DB) *rootMultiStore { return store } +//////////////////// iris/cosmos-sdk begin /////////////////////////// +func newMultiStoreWithMountsNewVersion(db dbm.DB) *rootMultiStore { + store := NewCommitMultiStore(db) + store.MountStoreWithDB( + sdk.NewKVStoreKey("store1"), sdk.StoreTypeIAVL, db) + store.MountStoreWithDB( + sdk.NewKVStoreKey("store2"), sdk.StoreTypeIAVL, db) + store.MountStoreWithDB( + sdk.NewKVStoreKey("store3"), sdk.StoreTypeIAVL, db) + store.MountStoreWithDB( + sdk.NewKVStoreKey("store4"), sdk.StoreTypeIAVL, db) + store.MountStoreWithDB( + sdk.NewKVStoreKey("store5"), sdk.StoreTypeIAVL, db) + return store +} + +//////////////////// iris/cosmos-sdk end /////////////////////////// + func checkStore(t *testing.T, store *rootMultiStore, expect, got CommitID) { require.Equal(t, expect, got) require.Equal(t, expect, store.LastCommitID()) diff --git a/types/coin.go b/types/coin.go index eba645932146..ddcc813e1dfa 100644 --- a/types/coin.go +++ b/types/coin.go @@ -4,7 +4,6 @@ import ( "fmt" "regexp" "sort" - "strconv" "strings" ) @@ -292,12 +291,12 @@ func ParseCoin(coinStr string) (coin Coin, err error) { } denomStr, amountStr := matches[2], matches[1] - amount, err := strconv.Atoi(amountStr) - if err != nil { + amount, ok := NewIntFromString(amountStr) + if !ok { return } - return Coin{denomStr, NewInt(int64(amount))}, nil + return Coin{denomStr, amount}, nil } // ParseCoins will parse out a list of coins separated by commas. diff --git a/types/errors.go b/types/errors.go index a106ee9bb7cf..1888fbf6ad39 100644 --- a/types/errors.go +++ b/types/errors.go @@ -54,6 +54,7 @@ const ( CodeInvalidCoins CodeType = 11 CodeOutOfGas CodeType = 12 CodeMemoTooLarge CodeType = 13 + CodeOutOfService CodeType = 14 // CodespaceRoot is a codespace for error codes in this file only. // Notice that 0 is an "unset" codespace, which can be overridden with @@ -95,6 +96,8 @@ func CodeToDefaultMsg(code CodeType) string { return "out of gas" case CodeMemoTooLarge: return "memo too large" + case CodeOutOfService: + return "out of service" default: return fmt.Sprintf("unknown code %d", code) } diff --git a/x/auth/ante.go b/x/auth/ante.go index 2999d4491b9c..5d5ed631cb7e 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -91,6 +91,8 @@ func NewAnteHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.AnteHandler { if i == 0 { firstAccount = signerAcc + } else { + am.SetAccount(newCtx, signerAcc) } signerAccs[i] = signerAcc diff --git a/x/auth/ante_test.go b/x/auth/ante_test.go index d990659c1afa..6fd00370db83 100644 --- a/x/auth/ante_test.go +++ b/x/auth/ante_test.go @@ -15,6 +15,13 @@ import ( "github.com/cosmos/cosmos-sdk/x/params" ) +func defaultGenesisStateForTest() GenesisState { + return GenesisState{ + FeeTokenNative: "atom", + GasPriceThreshold: 0, + } +} + func newTestMsg(addrs ...sdk.AccAddress) *sdk.TestMsg { return sdk.NewTestMsg(addrs...) } @@ -119,7 +126,7 @@ func TestAnteHandlerSigErrors(t *testing.T) { feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) - InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) + InitGenesis(ctx, paramsKeeper.Setter(), defaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() @@ -174,7 +181,7 @@ func TestAnteHandlerAccountNumbers(t *testing.T) { feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) - InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) + InitGenesis(ctx, paramsKeeper.Setter(), defaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() @@ -235,7 +242,7 @@ func TestAnteHandlerSequences(t *testing.T) { feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) - InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) + InitGenesis(ctx, paramsKeeper.Setter(), defaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() @@ -315,7 +322,7 @@ func TestAnteHandlerFees(t *testing.T) { feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) - InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) + InitGenesis(ctx, paramsKeeper.Setter(), defaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() @@ -359,7 +366,7 @@ func TestAnteHandlerMemoGas(t *testing.T) { feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) - InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) + InitGenesis(ctx, paramsKeeper.Setter(), defaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() @@ -372,7 +379,7 @@ func TestAnteHandlerMemoGas(t *testing.T) { var tx sdk.Tx msg := newTestMsg(addr1) privs, accnums, seqs := []crypto.PrivKey{priv1}, []int64{0}, []int64{0} - fee := NewStdFee(0, sdk.NewCoin("atom", 0)) + fee := NewStdFee(1, sdk.NewCoin("atom", 0)) // tx does not have enough gas tx = newTestTx(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee) @@ -389,7 +396,7 @@ func TestAnteHandlerMemoGas(t *testing.T) { checkInvalidTx(t, anteHandler, ctx, tx, sdk.CodeMemoTooLarge) // tx with memo has enough gas - fee = NewStdFee(1100, sdk.NewCoin("atom", 0)) + fee = NewStdFee(1200, sdk.NewCoin("atom", 0)) tx = newTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, "abcininasidniandsinasindiansdiansdinaisndiasndiadninsd") checkValidTx(t, anteHandler, ctx, tx) } @@ -404,7 +411,7 @@ func TestAnteHandlerMultiSigner(t *testing.T) { feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) - InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) + InitGenesis(ctx, paramsKeeper.Setter(), defaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() @@ -457,7 +464,7 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) - InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) + InitGenesis(ctx, paramsKeeper.Setter(), defaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() @@ -540,7 +547,7 @@ func TestAnteHandlerSetPubKey(t *testing.T) { feeCollector := NewFeeCollectionKeeper(cdc, capKey2, paramsKeeper.Getter()) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) - InitGenesis(ctx, paramsKeeper.Setter(), DefaultGenesisStateForTest()) + InitGenesis(ctx, paramsKeeper.Setter(), defaultGenesisStateForTest()) // keys and addresses priv1, addr1 := privAndAddr() diff --git a/x/auth/feekeeper.go b/x/auth/feekeeper.go index 98c47cff9fcc..4731a90352b2 100644 --- a/x/auth/feekeeper.go +++ b/x/auth/feekeeper.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/params" "fmt" + "errors" ) var ( @@ -12,7 +13,7 @@ var ( NativeFeeTokenKey = "feeToken/native" NativeGasPriceThresholdKey = "feeToken/native/gasPrice/threshold" FeeExchangeRatePrefix = "feeToken/derived/exchange/rate/" // key = feeToken/derived/exchange/rate/, rate = BigInt(value)/10^18 - Precision = int64(1000000000000000000) //10^18 + RatePrecision = int64(1000000000) //10^9 ) // This FeeCollectionKeeper handles collection of fees in the anteHandler @@ -82,29 +83,35 @@ func (fck FeeCollectionKeeper) ClearCollectedFees(ctx sdk.Context) { } func (fck FeeCollectionKeeper) FeePreprocess(ctx sdk.Context, coins sdk.Coins, gasLimit int64) sdk.Error { - if gasLimit <=0 { + if gasLimit <= 0 { return sdk.ErrInternal(fmt.Sprintf("gaslimit %s should be larger than 0", gasLimit)) } nativeFeeToken, err := fck.getter.GetString(ctx, NativeFeeTokenKey) if err != nil { panic(err) } - nativeGasPriceThreshold, err := fck.getter.GetInt(ctx, NativeGasPriceThresholdKey) + nativeGasPriceThreshold, err := fck.getter.GetString(ctx, NativeGasPriceThresholdKey) if err != nil { panic(err) } - + threshold, ok := sdk.NewIntFromString(nativeGasPriceThreshold) + if !ok { + panic(errors.New("failed to parse gas price from string")) + } equivalentTotalFee := sdk.NewInt(0) for _,coin := range coins { if coin.Denom != nativeFeeToken { exchangeRateKey := FeeExchangeRatePrefix + coin.Denom - rate, err := fck.getter.GetInt(ctx, exchangeRateKey) + rateString, err := fck.getter.GetString(ctx, exchangeRateKey) if err != nil { - panic(err) + continue } - - equivalentFee := coin.Amount.Mul(rate).Div(sdk.NewInt(Precision)) + rate, ok := sdk.NewIntFromString(rateString) + if !ok { + panic(errors.New("failed to parse rate from string")) + } + equivalentFee := rate.Div(sdk.NewInt(RatePrecision)).Mul(coin.Amount) equivalentTotalFee = equivalentTotalFee.Add(equivalentFee) } else { @@ -113,8 +120,8 @@ func (fck FeeCollectionKeeper) FeePreprocess(ctx sdk.Context, coins sdk.Coins, g } gasPrice := equivalentTotalFee.Div(sdk.NewInt(gasLimit)) - if gasPrice.LT(nativeGasPriceThreshold) { - return sdk.ErrInsufficientCoins(fmt.Sprintf("gas price %s is less than threshold %s", gasPrice.String(), nativeGasPriceThreshold.String())) + if gasPrice.LT(threshold) { + return sdk.ErrInsufficientCoins(fmt.Sprintf("gas price %s is less than threshold %s", gasPrice.String(), threshold.String())) } return nil } @@ -124,21 +131,14 @@ type GenesisState struct { GasPriceThreshold int64 `json:"gas_price_threshold"` } -func DefaultGenesisStateForTest() GenesisState { - return GenesisState{ - FeeTokenNative: "atom", - GasPriceThreshold: 0, - } -} - func DefaultGenesisState() GenesisState { return GenesisState{ - FeeTokenNative: "atom", - GasPriceThreshold: 5, + FeeTokenNative: "steak", + GasPriceThreshold: 20000000000, //2*10^10 } } func InitGenesis(ctx sdk.Context, setter params.Setter, data GenesisState) { setter.SetString(ctx, NativeFeeTokenKey, data.FeeTokenNative) - setter.SetInt(ctx, NativeGasPriceThresholdKey, sdk.NewInt(data.GasPriceThreshold)) + setter.SetString(ctx, NativeGasPriceThresholdKey, sdk.NewInt(data.GasPriceThreshold).String()) } \ No newline at end of file diff --git a/x/auth/feekeeper_test.go b/x/auth/feekeeper_test.go index 1e99dcf18f5b..1bccac9d77d3 100644 --- a/x/auth/feekeeper_test.go +++ b/x/auth/feekeeper_test.go @@ -90,26 +90,23 @@ func TestFeeCollectionKeeperPreprocess(t *testing.T) { InitGenesis(ctx, paramKeeper.Setter(), DefaultGenesisState()) var err sdk.Error - err = fck.FeePreprocess(ctx, oneCoin) - require.Error(t,err,"") + //err = fck.FeePreprocess(ctx, oneCoin, 10) + //require.Error(t,err,"") - fee1 := sdk.Coins{sdk.NewCoin("iGas", 50)} - err = fck.FeePreprocess(ctx, fee1) + fee1 := sdk.Coins{sdk.NewCoin("steak", 50)} + err = fck.FeePreprocess(ctx, fee1, 10) require.Error(t,err,"") - fee2 := sdk.Coins{sdk.NewCoin("iGas", 100)} - err = fck.FeePreprocess(ctx, fee2) + fee2 := sdk.Coins{sdk.NewCoin("steak", 200000000000)} + err = fck.FeePreprocess(ctx, fee2, 10) require.NoError(t,err,"") - fee3 := sdk.Coins{sdk.NewCoin("iris", 1)} - err = fck.FeePreprocess(ctx, fee3) + fee3 := sdk.Coins{sdk.NewCoin("iGas", 120000000000)} + err = fck.FeePreprocess(ctx, fee3, 10) require.Error(t,err,"") - exchangeRate := sdk.NewRatFromInt(sdk.NewInt(100), sdk.OneInt()) - exchangeRateBytes,errMsg := fck.cdc.MarshalBinary(exchangeRate) - require.NoError(t, errMsg) - paramKeeper.Setter().SetRaw(ctx, FeeExchangeRatePrefix+"iris", exchangeRateBytes) + paramKeeper.Setter().SetString(ctx, FeeExchangeRatePrefix+"iGas", sdk.NewInt(int64(9000000000)).String()) - err = fck.FeePreprocess(ctx, fee3) + err = fck.FeePreprocess(ctx, fee3, 10) require.NoError(t,err,"") } diff --git a/x/bank/bench_test.go b/x/bank/bench_test.go index b90d56955134..d484a7208817 100644 --- a/x/bank/bench_test.go +++ b/x/bank/bench_test.go @@ -17,7 +17,7 @@ func getBenchmarkMockApp() (*mock.App, error) { RegisterWire(mapp.Cdc) coinKeeper := NewKeeper(mapp.AccountMapper) - mapp.Router().AddRoute("bank", NewHandler(coinKeeper)) + mapp.Router().AddRoute("bank", []*sdk.KVStoreKey{}, NewHandler(coinKeeper)) err := mapp.CompleteSetup([]*sdk.KVStoreKey{}) return mapp, err diff --git a/x/bank/msgs_test.go b/x/bank/msgs_test.go index b60cc65ad012..596e751b5e4b 100644 --- a/x/bank/msgs_test.go +++ b/x/bank/msgs_test.go @@ -257,7 +257,7 @@ func TestMsgIssueGetSignBytes(t *testing.T) { } res := msg.GetSignBytes() - expected := `{"banker":"cosmosaccaddr1d9h8qat5e4ehc5","outputs":[{"address":"cosmosaccaddr1d3hkzm3dveex7mfdvfsku6cwsauqd","coins":[{"amount":"10","denom":"atom"}]}]}` + expected := `{"banker":"faa1d9h8qat5umnd2g","outputs":[{"address":"faa1d3hkzm3dveex7mfdvfsku6crf5s7g","coins":[{"amount":"10","denom":"atom"}]}]}` require.Equal(t, expected, string(res)) } diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index 8f30aefc10ea..c8acffcbbab5 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -12,6 +12,7 @@ import ( authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/pkg/errors" + "encoding/json" ) const ( @@ -24,6 +25,7 @@ const ( flagDepositer = "depositer" flagVoter = "voter" flagOption = "option" + flagParams = "params" ) // submit a proposal tx @@ -36,6 +38,7 @@ func GetCmdSubmitProposal(cdc *wire.Codec) *cobra.Command { description := viper.GetString(flagDescription) strProposalType := viper.GetString(flagProposalType) initialDeposit := viper.GetString(flagDeposit) + paramsStr := viper.GetString(flagParams) // get the from address from the name flag from, err := sdk.AccAddressFromBech32(viper.GetString(flagProposer)) @@ -54,7 +57,14 @@ func GetCmdSubmitProposal(cdc *wire.Codec) *cobra.Command { } // create the message - msg := gov.NewMsgSubmitProposal(title, description, proposalType, from, amount) + var params gov.Params + if(proposalType == gov.ProposalTypeParameterChange){ + if err := json.Unmarshal([]byte(paramsStr),¶ms);err != nil{ + fmt.Println(err.Error()) + return nil + } + } + msg := gov.NewSubmitProposal(title, description, proposalType, from, amount,params) err = msg.ValidateBasic() if err != nil { @@ -79,6 +89,7 @@ func GetCmdSubmitProposal(cdc *wire.Codec) *cobra.Command { cmd.Flags().String(flagProposalType, "", "proposalType of proposal") cmd.Flags().String(flagDeposit, "", "deposit of proposal") cmd.Flags().String(flagProposer, "", "proposer of proposal") + cmd.Flags().String(flagParams, "", "parameter of proposal,eg. [{key:key,value:value,op:update}]") return cmd } diff --git a/x/gov/genesis.go b/x/gov/genesis.go index 47af7b81bee1..83b4d980529a 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -26,7 +26,7 @@ func DefaultGenesisState() GenesisState { return GenesisState{ StartingProposalID: 1, DepositProcedure: DepositProcedure{ - MinDeposit: sdk.Coins{sdk.NewCoin("steak", 10)}, + MinDeposit: sdk.Coins{sdk.Coin{Denom:"steak", Amount: sdk.NewInt(int64(10)).Mul(Pow10(18))}}, MaxDepositPeriod: 10, }, VotingProcedure: VotingProcedure{ @@ -47,9 +47,15 @@ func InitGenesis(ctx sdk.Context, k Keeper, data GenesisState) { // TODO: Handle this with #870 panic(err) } - k.setDepositProcedure(ctx, data.DepositProcedure) - k.setVotingProcedure(ctx, data.VotingProcedure) - k.setTallyingProcedure(ctx, data.TallyingProcedure) + + k.setDepositProcedureDeposit(ctx, data.DepositProcedure.MinDeposit) + k.setDepositProcedureMaxDepositPeriod(ctx, data.DepositProcedure.MaxDepositPeriod) + + k.setVotingProcedureVotingPeriod(ctx, data.VotingProcedure.VotingPeriod) + + k.setTallyingProcedure(ctx, ParamStoreKeyTallyingProcedureThreshold, data.TallyingProcedure.Threshold) + k.setTallyingProcedure(ctx, ParamStoreKeyTallyingProcedureVeto, data.TallyingProcedure.Veto) + k.setTallyingProcedure(ctx, ParamStoreKeyTallyingProcedurePenalty, data.TallyingProcedure.GovernancePenalty) } // WriteGenesis - output genesis parameters @@ -65,4 +71,16 @@ func WriteGenesis(ctx sdk.Context, k Keeper) GenesisState { VotingProcedure: votingProcedure, TallyingProcedure: tallyingProcedure, } +} + +func Pow10(y int) sdk.Int { + result := sdk.NewInt(1) + x := sdk.NewInt(10) + for i := y; i > 0; i >>= 1 { + if i&1 != 0 { + result = result.Mul(x) + } + x = x.Mul(x) + } + return result } \ No newline at end of file diff --git a/x/gov/handler.go b/x/gov/handler.go index fba19f0932c3..ea5e72e64cb1 100644 --- a/x/gov/handler.go +++ b/x/gov/handler.go @@ -23,7 +23,7 @@ func NewHandler(keeper Keeper) sdk.Handler { func handleMsgSubmitProposal(ctx sdk.Context, keeper Keeper, msg MsgSubmitProposal) sdk.Result { - proposal := keeper.NewTextProposal(ctx, msg.Title, msg.Description, msg.ProposalType) + proposal := keeper.NewProposal(ctx, msg.Title, msg.Description, msg.ProposalType,msg.Params) err, votingStarted := keeper.AddDeposit(ctx, proposal.GetProposalID(), msg.Proposer, msg.InitialDeposit) if err != nil { @@ -122,6 +122,8 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (tags sdk.Tags, nonVotingVals [] activeProposal.SetStatus(StatusPassed) tags.AppendTag("action", []byte("proposalPassed")) tags.AppendTag("proposalId", proposalIDBytes) + + activeProposal.Execute(ctx,keeper) } else { keeper.DeleteDeposits(ctx, activeProposal.GetProposalID()) activeProposal.SetStatus(StatusRejected) diff --git a/x/gov/keeper.go b/x/gov/keeper.go index 4f49cac582c6..b48bf2519461 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -5,13 +5,7 @@ import ( wire "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/params" -) - -// nolint -const ( - ParamStoreKeyDepositProcedure = "gov/depositprocedure" - ParamStoreKeyVotingProcedure = "gov/votingprocedure" - ParamStoreKeyTallyingProcedure = "gov/tallyingprocedure" + "fmt" ) // Governance Keeper @@ -80,6 +74,42 @@ func (keeper Keeper) NewTextProposal(ctx sdk.Context, title string, description return proposal } +func (keeper Keeper) NewParametersProposal(ctx sdk.Context, title string, description string, proposalType ProposalKind,params Params) Proposal{ + proposalID, err := keeper.getNewProposalID(ctx) + if err != nil { + return nil + } + var textProposal = TextProposal{ + ProposalID: proposalID, + Title: title, + Description: description, + ProposalType: proposalType, + Status: StatusDepositPeriod, + TotalDeposit: sdk.Coins{}, + SubmitBlock: ctx.BlockHeight(), + VotingStartBlock: -1, // TODO: Make Time + } + var proposal Proposal = &ParameterProposal{ + textProposal, + params, + } + keeper.SetProposal(ctx, proposal) + keeper.InactiveProposalQueuePush(ctx, proposal) + return proposal +} + +func (keeper Keeper) NewProposal(ctx sdk.Context, title string, description string, proposalType ProposalKind,params Params) Proposal{ + switch proposalType { + case ProposalTypeText: + return keeper.NewTextProposal(ctx, title, description, proposalType) + case ProposalTypeParameterChange: + return keeper.NewParametersProposal(ctx, title, description, proposalType,params) + case ProposalTypeSoftwareUpgrade: + fmt.Println("not implement") + } + return nil +} + // Get Proposal from store by ProposalID func (keeper Keeper) GetProposal(ctx sdk.Context, proposalID int64) Proposal { store := ctx.KVStore(keeper.storeKey) @@ -137,42 +167,6 @@ func (keeper Keeper) activateVotingPeriod(ctx sdk.Context, proposal Proposal) { keeper.ActiveProposalQueuePush(ctx, proposal) } -// ===================================================== -// Procedures - -// Returns the current Deposit Procedure from the global param store -func (keeper Keeper) GetDepositProcedure(ctx sdk.Context) DepositProcedure { - var depositProcedure DepositProcedure - keeper.ps.Get(ctx, ParamStoreKeyDepositProcedure, &depositProcedure) - return depositProcedure -} - -// Returns the current Voting Procedure from the global param store -func (keeper Keeper) GetVotingProcedure(ctx sdk.Context) VotingProcedure { - var votingProcedure VotingProcedure - keeper.ps.Get(ctx, ParamStoreKeyVotingProcedure, &votingProcedure) - return votingProcedure -} - -// Returns the current Tallying Procedure from the global param store -func (keeper Keeper) GetTallyingProcedure(ctx sdk.Context) TallyingProcedure { - var tallyingProcedure TallyingProcedure - keeper.ps.Get(ctx, ParamStoreKeyTallyingProcedure, &tallyingProcedure) - return tallyingProcedure -} - -func (keeper Keeper) setDepositProcedure(ctx sdk.Context, depositProcedure DepositProcedure) { - keeper.ps.Set(ctx, ParamStoreKeyDepositProcedure, &depositProcedure) -} - -func (keeper Keeper) setVotingProcedure(ctx sdk.Context, votingProcedure VotingProcedure) { - keeper.ps.Set(ctx, ParamStoreKeyVotingProcedure, &votingProcedure) -} - -func (keeper Keeper) setTallyingProcedure(ctx sdk.Context, tallyingProcedure TallyingProcedure) { - keeper.ps.Set(ctx, ParamStoreKeyTallyingProcedure, &tallyingProcedure) -} - // ===================================================== // Votes diff --git a/x/gov/msgs.go b/x/gov/msgs.go index 5d85f689e58c..f1d89391c7d8 100644 --- a/x/gov/msgs.go +++ b/x/gov/msgs.go @@ -17,6 +17,7 @@ type MsgSubmitProposal struct { ProposalType ProposalKind // Type of proposal. Initial set {PlainTextProposal, SoftwareUpgradeProposal} Proposer sdk.AccAddress // Address of the proposer InitialDeposit sdk.Coins // Initial deposit paid by sender. Must be strictly positive. + Params Params } func NewMsgSubmitProposal(title string, description string, proposalType ProposalKind, proposer sdk.AccAddress, initialDeposit sdk.Coins) MsgSubmitProposal { @@ -29,6 +30,17 @@ func NewMsgSubmitProposal(title string, description string, proposalType Proposa } } +func NewSubmitProposal(title string, description string, proposalType ProposalKind, proposer sdk.AccAddress, initialDeposit sdk.Coins,params Params) MsgSubmitProposal { + return MsgSubmitProposal{ + Title: title, + Description: description, + ProposalType: proposalType, + Proposer: proposer, + InitialDeposit: initialDeposit, + Params: params, + } +} + // Implements Msg. func (msg MsgSubmitProposal) Type() string { return MsgType } diff --git a/x/gov/params.go b/x/gov/params.go new file mode 100644 index 000000000000..878f6aba765c --- /dev/null +++ b/x/gov/params.go @@ -0,0 +1,91 @@ +package gov + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "strconv" + "strings" +) + +// nolint +const ( + ParamStoreKeyDepositProcedureDeposit = "gov/depositprocedure/deposit" + ParamStoreKeyDepositProcedureMaxDepositPeriod = "gov/depositprocedure/maxDepositPeriod" + + ParamStoreKeyVotingProcedureVotingPeriod = "gov/votingprocedure/votingPeriod" + + ParamStoreKeyTallyingProcedureThreshold = "gov/tallyingprocedure/threshold" + ParamStoreKeyTallyingProcedureVeto = "gov/tallyingprocedure/veto" + ParamStoreKeyTallyingProcedurePenalty = "gov/tallyingprocedure/penalty" +) + +// ===================================================== +// Procedures + +// Returns the current Deposit Procedure from the global param store +func (keeper Keeper) GetDepositProcedure(ctx sdk.Context) DepositProcedure { + return DepositProcedure{ + MinDeposit: keeper.getDepositProcedureDeposit(ctx), + MaxDepositPeriod: keeper.getDepositProcedureMaxDepositPeriod(ctx), + } +} + +// Returns the current Voting Procedure from the global param store +func (keeper Keeper) GetVotingProcedure(ctx sdk.Context) VotingProcedure { + return VotingProcedure{ + VotingPeriod: keeper.getVotingProcedureVotingPeriod(ctx), + } +} + +// Returns the current Tallying Procedure from the global param store +func (keeper Keeper) GetTallyingProcedure(ctx sdk.Context) TallyingProcedure { + return TallyingProcedure{ + Threshold: keeper.getTallyingProcedure(ctx, ParamStoreKeyTallyingProcedureThreshold), + Veto: keeper.getTallyingProcedure(ctx, ParamStoreKeyTallyingProcedureVeto), + GovernancePenalty: keeper.getTallyingProcedure(ctx, ParamStoreKeyTallyingProcedurePenalty), + } +} + +func (keeper Keeper) setDepositProcedureDeposit(ctx sdk.Context, Deposit sdk.Coins) { + data := Deposit.String() + keeper.ps.Set(ctx, ParamStoreKeyDepositProcedureDeposit, &data) +} + +func (keeper Keeper) setDepositProcedureMaxDepositPeriod(ctx sdk.Context, MaxDepositPeriod int64) { + keeper.ps.Set(ctx, ParamStoreKeyDepositProcedureMaxDepositPeriod, &MaxDepositPeriod) +} + +func (keeper Keeper) setVotingProcedureVotingPeriod(ctx sdk.Context, VotingPeriod int64) { + keeper.ps.Set(ctx, ParamStoreKeyVotingProcedureVotingPeriod, &VotingPeriod) +} + +func (keeper Keeper) setTallyingProcedure(ctx sdk.Context, key string, rat sdk.Rat) { + str := rat.String() + keeper.ps.Set(ctx, key, &str) +} + +func (keeper Keeper) getDepositProcedureDeposit(ctx sdk.Context) (Deposit sdk.Coins) { + var data string + keeper.ps.Get(ctx, ParamStoreKeyDepositProcedureDeposit, &data) + Deposit, _ = sdk.ParseCoins(data) + return +} + +func (keeper Keeper) getDepositProcedureMaxDepositPeriod(ctx sdk.Context) (MaxDepositPeriod int64) { + keeper.ps.Get(ctx, ParamStoreKeyDepositProcedureMaxDepositPeriod, &MaxDepositPeriod) + return +} + +func (keeper Keeper) getVotingProcedureVotingPeriod(ctx sdk.Context) (VotingPeriod int64) { + keeper.ps.Get(ctx, ParamStoreKeyVotingProcedureVotingPeriod, &VotingPeriod) + return +} + +func (keeper Keeper) getTallyingProcedure(ctx sdk.Context, key string) sdk.Rat { + var data string + keeper.ps.Get(ctx, key, &data) + str := strings.Split(data, "/") + x, _ := strconv.ParseInt(str[0], 10, 64) + y, _ := strconv.ParseInt(str[1], 10, 64) + return sdk.NewRat(x, y) + +} diff --git a/x/gov/proposals.go b/x/gov/proposals.go index 61aafe577c73..35a41eccfb33 100644 --- a/x/gov/proposals.go +++ b/x/gov/proposals.go @@ -35,6 +35,8 @@ type Proposal interface { GetVotingStartBlock() int64 SetVotingStartBlock(int64) + + Execute(ctx sdk.Context, k Keeper) error } // checks if two proposals are equal @@ -90,6 +92,61 @@ func (tp TextProposal) GetVotingStartBlock() int64 { return tp.V func (tp *TextProposal) SetVotingStartBlock(votingStartBlock int64) { tp.VotingStartBlock = votingStartBlock } +func (tp *TextProposal) Execute(ctx sdk.Context, k Keeper) error { return nil } + +//////////////////// iris/cosmos-sdk begin /////////////////////////// +type Op string + +const ( + Add Op = "add" + Del Op = "del" + Update Op = "update" +) + +type Data struct { + Key string `json:"key"` + Value string `json:"value"` + Op Op `json:"op"` +} + +type Params []Data + +// Implements Proposal Interface +var _ Proposal = (*ParameterProposal)(nil) + +type ParameterProposal struct { + TextProposal + Datas Params `json:"datas"` +} + +func (pp *ParameterProposal) Execute(ctx sdk.Context, k Keeper) error { + + logger := ctx.Logger().With("module", "x/gov") + logger.Info("Execute ParameterProposal begin","info", fmt.Sprintf("current height:%d",ctx.BlockHeight())) + + if len(pp.Datas) == 0 { + return errors.New("ParameterProposal's data is empty") + } + for _, data := range pp.Datas { + if data.Op == Add { + k.ps.Set(ctx, data.Key, data.Value) + } else if data.Op == Update { + bz := k.ps.GetRaw(ctx, data.Key) + if bz == nil || len(bz) == 0 { + logger.Error("Execute ParameterProposal ", "err", "Parameter "+data.Key+" is not exist") + } else { + if err := k.ps.Set(ctx, data.Key, data.Value);err != nil{ + logger.Error("Execute ParameterProposal ", "err", err.Error()) + } + } + } else { + + } + } + return nil +} + +//////////////////// iris/cosmos-sdk end /////////////////////////// //----------------------------------------------------------- // ProposalQueue diff --git a/x/gov/proposals_test.go b/x/gov/proposals_test.go new file mode 100644 index 000000000000..b0777ec648b1 --- /dev/null +++ b/x/gov/proposals_test.go @@ -0,0 +1,50 @@ +package gov + +import ( + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/magiconair/properties/assert" + abci "github.com/tendermint/tendermint/abci/types" + "testing" + "github.com/cosmos/cosmos-sdk/x/params" +) + +func TestParameterProposal(t *testing.T) { + mapp, keeper, _, _, _, _ := getMockApp(t, 0) + + mapp.BeginBlock(abci.RequestBeginBlock{}) + ctx := mapp.BaseApp.NewContext(false, abci.Header{}) + + fmt.Println(keeper.GetDepositProcedure(ctx)) + fmt.Println(keeper.GetTallyingProcedure(ctx)) + fmt.Println(keeper.GetVotingProcedure(ctx)) + + pp := ParameterProposal{ + Datas: []Data{ + {Key: ParamStoreKeyDepositProcedureDeposit, Value: "200iris", Op: Update}, + {Key: ParamStoreKeyTallyingProcedurePenalty, Value: "1/50", Op: Update}, + {Key: ParamStoreKeyTallyingProcedureVeto, Value: "1/4", Op: Update}, + {Key: ParamStoreKeyTallyingProcedureThreshold, Value: "2/8", Op: Update}, + }, + } + + pp.Execute(ctx, keeper) + assert.Equal(t, keeper.GetDepositProcedure(ctx).MinDeposit, + sdk.Coins{sdk.NewCoin("iris", 200)}) + + + assert.Equal(t, keeper.GetTallyingProcedure(ctx), + TallyingProcedure{ + Threshold: sdk.NewRat(2, 8), + Veto: sdk.NewRat(1, 4), + GovernancePenalty: sdk.NewRat(1, 50), + }) +} + + + +func TestByte(t *testing.T) { + fmt.Println(string([]byte{112,114,111,112,111,115,97,108,73,100})) + bInt :=sdk.NewRatFromInt(params.DefaultPrecison(100)) + fmt.Println(bInt) +} diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 243e89bf9928..6bde627bd938 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -33,8 +33,9 @@ func getMockApp(t *testing.T, numGenAccs int) (*mock.App, Keeper, stake.Keeper, pk := params.NewKeeper(mapp.Cdc, keyGlobalParams) ck := bank.NewKeeper(mapp.AccountMapper) sk := stake.NewKeeper(mapp.Cdc, keyStake, ck, mapp.RegisterCodespace(stake.DefaultCodespace)) - keeper := NewKeeper(mapp.Cdc, keyGov,pk.Setter(),ck, sk, DefaultCodespace) - mapp.Router().AddRoute("gov", NewHandler(keeper)) + + keeper := NewKeeper(mapp.Cdc, keyGov,pk.Setter(), ck, sk, DefaultCodespace) + mapp.Router().AddRoute("gov", []*sdk.KVStoreKey{keyGov, mapp.KeyAccount, keyStake}, NewHandler(keeper)) require.NoError(t, mapp.CompleteSetup([]*sdk.KVStoreKey{keyStake, keyGov, keyGlobalParams})) diff --git a/x/gov/wire.go b/x/gov/wire.go index 4173fc69a62f..65ebad870fcc 100644 --- a/x/gov/wire.go +++ b/x/gov/wire.go @@ -17,6 +17,11 @@ func RegisterWire(cdc *wire.Codec) { cdc.RegisterInterface((*Proposal)(nil), nil) cdc.RegisterConcrete(&TextProposal{}, "gov/TextProposal", nil) + cdc.RegisterConcrete(&ParameterProposal{}, "gov/ParameterProposal", nil) } var msgCdc = wire.NewCodec() + +func init() { + RegisterWire(msgCdc) +} diff --git a/x/ibc/app_test.go b/x/ibc/app_test.go index d853c798700a..07aab546587c 100644 --- a/x/ibc/app_test.go +++ b/x/ibc/app_test.go @@ -22,7 +22,7 @@ func getMockApp(t *testing.T) *mock.App { keyIBC := sdk.NewKVStoreKey("ibc") ibcMapper := NewMapper(mapp.Cdc, keyIBC, mapp.RegisterCodespace(DefaultCodespace)) coinKeeper := bank.NewKeeper(mapp.AccountMapper) - mapp.Router().AddRoute("ibc", NewHandler(ibcMapper, coinKeeper)) + mapp.Router().AddRoute("ibc", []*sdk.KVStoreKey{keyIBC}, NewHandler(ibcMapper, coinKeeper)) require.NoError(t, mapp.CompleteSetup([]*sdk.KVStoreKey{keyIBC})) return mapp diff --git a/x/mock/app_test.go b/x/mock/app_test.go index 0c548280aea4..173f9c4ab1fc 100644 --- a/x/mock/app_test.go +++ b/x/mock/app_test.go @@ -40,7 +40,7 @@ func (tx testMsg) ValidateBasic() sdk.Error { func getMockApp(t *testing.T) *App { mApp := NewApp() - mApp.Router().AddRoute(msgType, func(ctx sdk.Context, msg sdk.Msg) (res sdk.Result) { return }) + mApp.Router().AddRoute(msgType, []*sdk.KVStoreKey{}, func(ctx sdk.Context, msg sdk.Msg) (res sdk.Result) { return }) require.NoError(t, mApp.CompleteSetup([]*sdk.KVStoreKey{})) return mApp diff --git a/x/params/client/cli/util.go b/x/params/client/cli/util.go new file mode 100644 index 000000000000..7222f9b35b5b --- /dev/null +++ b/x/params/client/cli/util.go @@ -0,0 +1,29 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/wire" + "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client/context" + "fmt" + +) + +// create edit validator command +func QueryParam(storeName string, cdc *wire.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "query", + Short: "query param value from global store", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.NewCoreContextFromViper() + res, err := ctx.QueryStore([]byte(args[0]), storeName) + if err != nil { + fmt.Println(err.Error()) + return nil + } + fmt.Println(string(res)) + return nil + }, + } + return cmd +} diff --git a/x/params/genesis.go b/x/params/genesis.go new file mode 100644 index 000000000000..715a560cb91e --- /dev/null +++ b/x/params/genesis.go @@ -0,0 +1,67 @@ +package params + +import ( + "errors" + "fmt" + "github.com/cosmos/cosmos-sdk/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "strconv" +) + +const IrisPrecision = 18 +const IrisDenom = "iris" + +type CoinConfig struct { + Denom string `json:"denom"` + Precison int64 `json:"precison"` +} + +type ParamGenesisState struct { + Coins []CoinConfig `json:"coins"` +} + + +func DefaultPrecison(amount int64) sdk.Int { + return Pow10(IrisPrecision).Mul(sdk.NewInt(amount)) +} + +func ToBigCoin(ctx sdk.Context, k Getter, coin types.Coin) (types.Coin, error) { + precison, err := k.GetString(ctx, coin.Denom) + if err != nil { + ctx.Logger().Error("module params:%s coin is invalid", coin.Denom) + return coin, errors.New(fmt.Sprintf("%s coin is invalid", coin.Denom)) + } + prec,_:= strconv.ParseInt(precison,10,0) + amount := Pow10(int(prec)).Mul(coin.Amount) + return types.Coin{Denom: coin.Denom, Amount: amount}, nil +} + +func Get(ctx sdk.Context, k Getter, key string, ptr interface{}) error { + return k.Get(ctx, key, ptr) +} + +func DefaultGenesisState() (state ParamGenesisState) { + state.Coins = append(state.Coins, CoinConfig{ + Denom: IrisDenom, + Precison: IrisPrecision, + }) + return state +} + +func InitParamGenesis(ctx sdk.Context, k Keeper, state ParamGenesisState) { + for _, coin := range state.Coins { + k.Setter().SetString(ctx, coin.Denom, strconv.FormatInt(coin.Precison, 10)) + } +} + +func Pow10(y int) sdk.Int { + result := sdk.NewInt(1) + x := sdk.NewInt(10) + for i := y; i > 0; i >>= 1 { + if i&1 != 0 { + result = result.Mul(x) + } + x = x.Mul(x) + } + return result +} diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index e7b660d15e08..936713fa8694 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -29,8 +29,8 @@ func getMockApp(t *testing.T) (*mock.App, stake.Keeper, Keeper) { coinKeeper := bank.NewKeeper(mapp.AccountMapper) stakeKeeper := stake.NewKeeper(mapp.Cdc, keyStake, coinKeeper, mapp.RegisterCodespace(stake.DefaultCodespace)) keeper := NewKeeper(mapp.Cdc, keySlashing, stakeKeeper, mapp.RegisterCodespace(DefaultCodespace)) - mapp.Router().AddRoute("stake", stake.NewHandler(stakeKeeper)) - mapp.Router().AddRoute("slashing", NewHandler(keeper)) + mapp.Router().AddRoute("stake", []*sdk.KVStoreKey{keyStake}, stake.NewHandler(stakeKeeper)) + mapp.Router().AddRoute("slashing", []*sdk.KVStoreKey{keySlashing}, NewHandler(keeper)) mapp.SetEndBlocker(getEndBlocker(stakeKeeper)) mapp.SetInitChainer(getInitChainer(mapp, stakeKeeper)) diff --git a/x/stake/app_test.go b/x/stake/app_test.go index d1183e6c922b..29ef089c419d 100644 --- a/x/stake/app_test.go +++ b/x/stake/app_test.go @@ -37,7 +37,7 @@ func getMockApp(t *testing.T) (*mock.App, Keeper) { coinKeeper := bank.NewKeeper(mApp.AccountMapper) keeper := NewKeeper(mApp.Cdc, keyStake, coinKeeper, mApp.RegisterCodespace(DefaultCodespace)) - mApp.Router().AddRoute("stake", NewHandler(keeper)) + mApp.Router().AddRoute("stake", []*sdk.KVStoreKey{keyStake}, NewHandler(keeper)) mApp.SetEndBlocker(getEndBlocker(keeper)) mApp.SetInitChainer(getInitChainer(mApp, keeper)) diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index 405d601490c5..5d250afe8716 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -402,6 +402,24 @@ func (v Validator) AddTokensFromDel(pool Pool, amount sdk.Int) (Validator, Pool, return v, pool, issuedShares } +// AddTokensFromDel adds tokens to a validator +func (v Validator) AddTokensFromInt(pool Pool, amount sdk.Int) (Validator, Pool, sdk.Rat) { + + // bondedShare/delegatedShare + exRate := v.DelegatorShareExRate() + amountRat := sdk.NewRatFromInt(amount) + + if v.Status == sdk.Bonded { + pool = pool.looseTokensToBonded(amountRat) + } + + v.Tokens = v.Tokens.Add(amountRat) + issuedShares := amountRat.Quo(exRate) + v.DelegatorShares = v.DelegatorShares.Add(issuedShares) + + return v, pool, issuedShares +} + // RemoveDelShares removes delegator shares from a validator. func (v Validator) RemoveDelShares(pool Pool, delShares sdk.Rat) (Validator, Pool, sdk.Rat) { issuedTokens := v.DelegatorShareExRate().Mul(delShares) From a1acf52421dfd77ba057dc96b9cf5db392923cb9 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Wed, 8 Aug 2018 10:15:46 +0800 Subject: [PATCH 31/52] Merge branch 'irisnet/develop' of https://github.com/irisnet/cosmos-sdk into zhiqiang/irisnet/feature_gov --- x/bank/msgs_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/bank/msgs_test.go b/x/bank/msgs_test.go index 596e751b5e4b..65e42953725d 100644 --- a/x/bank/msgs_test.go +++ b/x/bank/msgs_test.go @@ -187,7 +187,7 @@ func TestMsgSendGetSignBytes(t *testing.T) { } res := msg.GetSignBytes() - expected := `{"inputs":[{"address":"cosmosaccaddr1d9h8qat5e4ehc5","coins":[{"amount":"10","denom":"atom"}]}],"outputs":[{"address":"cosmosaccaddr1da6hgur4wse3jx32","coins":[{"amount":"10","denom":"atom"}]}]}` + expected := `{"inputs":[{"address":"faa1d9h8qat5umnd2g","coins":[{"amount":"10","denom":"atom"}]}],"outputs":[{"address":"faa1da6hgur4wstza6a7","coins":[{"amount":"10","denom":"atom"}]}]}` require.Equal(t, expected, string(res)) } From 56b5ffe70020df0d5be01d250e1bd1390a22636b Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Wed, 8 Aug 2018 11:39:18 +0800 Subject: [PATCH 32/52] Fix failed test --- baseapp/baseapp.go | 4 +++- docs/sdk/core/examples/app3.go | 7 +++++-- docs/sdk/core/examples/app4.go | 8 ++++++-- examples/democoin/x/pow/types_test.go | 4 ++-- x/auth/feekeeper.go | 2 +- x/bank/msgs_test.go | 2 +- x/gov/keeper_test.go | 6 +++--- x/gov/test_common.go | 8 ++++++-- x/ibc/app_test.go | 2 +- x/mock/app.go | 23 +++++++++++++++++++++-- x/slashing/handler_test.go | 2 +- x/slashing/msg_test.go | 2 +- x/slashing/test_common.go | 17 ++++++++++++++++- x/stake/handler_test.go | 2 +- x/stake/keeper/keeper_test.go | 8 +++----- x/stake/keeper/test_common.go | 16 +++++++++++++++- 16 files changed, 86 insertions(+), 27 deletions(-) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index cccb4f8e7d56..07825b24ca44 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -661,7 +661,9 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk result.GasUsed = ctx.GasMeter().GasConsumed() // Refund unspent fee - app.feeRefundHandler(originalCtx, tx, result) + if app.feeRefundHandler != nil { + app.feeRefundHandler(originalCtx, tx, result) + } }() var msgs = tx.GetMsgs() diff --git a/docs/sdk/core/examples/app3.go b/docs/sdk/core/examples/app3.go index 33bd06f8f3de..3726f5c76993 100644 --- a/docs/sdk/core/examples/app3.go +++ b/docs/sdk/core/examples/app3.go @@ -9,6 +9,7 @@ import ( 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/params" ) const ( @@ -26,11 +27,13 @@ func NewApp3(logger log.Logger, db dbm.DB) *bapp.BaseApp { // Create a key for accessing the account store. keyAccount := sdk.NewKVStoreKey("acc") keyFees := sdk.NewKVStoreKey("fee") // TODO + keyParams := sdk.NewKVStoreKey("params") // Set various mappers/keepers to interact easily with underlying stores accountMapper := auth.NewAccountMapper(cdc, keyAccount, auth.ProtoBaseAccount) coinKeeper := bank.NewKeeper(accountMapper) - feeKeeper := auth.NewFeeCollectionKeeper(cdc, keyFees) + paramsKeeper := params.NewKeeper(cdc, keyParams) + feeKeeper := auth.NewFeeCollectionKeeper(cdc, keyFees, paramsKeeper.Getter()) app.SetAnteHandler(auth.NewAnteHandler(accountMapper, feeKeeper)) @@ -40,7 +43,7 @@ func NewApp3(logger log.Logger, db dbm.DB) *bapp.BaseApp { AddRoute("send", []*sdk.KVStoreKey{keyAccount}, bank.NewHandler(coinKeeper)) // Mount stores and load the latest state. - app.MountStoresIAVL(keyAccount, keyFees) + app.MountStoresIAVL(keyAccount, keyFees, keyParams, keyFees) err := app.LoadLatestVersion(keyAccount) if err != nil { cmn.Exit(err.Error()) diff --git a/docs/sdk/core/examples/app4.go b/docs/sdk/core/examples/app4.go index 72529996d601..6716ba5fee4b 100644 --- a/docs/sdk/core/examples/app4.go +++ b/docs/sdk/core/examples/app4.go @@ -11,6 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/params" ) const ( @@ -33,7 +34,10 @@ func NewApp4(logger log.Logger, db dbm.DB) *bapp.BaseApp { // TODO keyFees := sdk.NewKVStoreKey("fee") - feeKeeper := auth.NewFeeCollectionKeeper(cdc, keyFees) + keyParams := sdk.NewKVStoreKey("params") + + paramsKeeper := params.NewKeeper(cdc, keyParams) + feeKeeper := auth.NewFeeCollectionKeeper(cdc, keyFees, paramsKeeper.Getter()) app.SetAnteHandler(auth.NewAnteHandler(accountMapper, feeKeeper)) @@ -46,7 +50,7 @@ func NewApp4(logger log.Logger, db dbm.DB) *bapp.BaseApp { AddRoute("send", []*sdk.KVStoreKey{keyAccount}, bank.NewHandler(coinKeeper)) // Mount stores and load the latest state. - app.MountStoresIAVL(keyAccount, keyFees) + app.MountStoresIAVL(keyAccount, keyFees, keyParams, keyFees) err := app.LoadLatestVersion(keyAccount) if err != nil { cmn.Exit(err.Error()) diff --git a/examples/democoin/x/pow/types_test.go b/examples/democoin/x/pow/types_test.go index be848d94089a..57b166925a7a 100644 --- a/examples/democoin/x/pow/types_test.go +++ b/examples/democoin/x/pow/types_test.go @@ -55,14 +55,14 @@ func TestMsgMineString(t *testing.T) { addr := sdk.AccAddress([]byte("sender")) msg := MsgMine{addr, 0, 0, 0, []byte("abc")} res := msg.String() - require.Equal(t, res, "MsgMine{Sender: cosmosaccaddr1wdjkuer9wg4wml9c, Difficulty: 0, Count: 0, Nonce: 0, Proof: abc}") + require.Equal(t, res, "MsgMine{Sender: faa1wdjkuer9wg8a5rfv, Difficulty: 0, Count: 0, Nonce: 0, Proof: abc}") } func TestMsgMineGetSignBytes(t *testing.T) { addr := sdk.AccAddress([]byte("sender")) msg := MsgMine{addr, 1, 1, 1, []byte("abc")} res := msg.GetSignBytes() - require.Equal(t, string(res), `{"count":1,"difficulty":1,"nonce":1,"proof":"YWJj","sender":"cosmosaccaddr1wdjkuer9wg4wml9c"}`) + require.Equal(t, string(res), `{"count":1,"difficulty":1,"nonce":1,"proof":"YWJj","sender":"faa1wdjkuer9wg8a5rfv"}`) } func TestMsgMineGetSigners(t *testing.T) { diff --git a/x/auth/feekeeper.go b/x/auth/feekeeper.go index 4731a90352b2..c30c24a6a92d 100644 --- a/x/auth/feekeeper.go +++ b/x/auth/feekeeper.go @@ -84,7 +84,7 @@ func (fck FeeCollectionKeeper) ClearCollectedFees(ctx sdk.Context) { func (fck FeeCollectionKeeper) FeePreprocess(ctx sdk.Context, coins sdk.Coins, gasLimit int64) sdk.Error { if gasLimit <= 0 { - return sdk.ErrInternal(fmt.Sprintf("gaslimit %s should be larger than 0", gasLimit)) + return sdk.ErrInternal(fmt.Sprintf("gaslimit %d should be larger than 0", gasLimit)) } nativeFeeToken, err := fck.getter.GetString(ctx, NativeFeeTokenKey) if err != nil { diff --git a/x/bank/msgs_test.go b/x/bank/msgs_test.go index 596e751b5e4b..65e42953725d 100644 --- a/x/bank/msgs_test.go +++ b/x/bank/msgs_test.go @@ -187,7 +187,7 @@ func TestMsgSendGetSignBytes(t *testing.T) { } res := msg.GetSignBytes() - expected := `{"inputs":[{"address":"cosmosaccaddr1d9h8qat5e4ehc5","coins":[{"amount":"10","denom":"atom"}]}],"outputs":[{"address":"cosmosaccaddr1da6hgur4wse3jx32","coins":[{"amount":"10","denom":"atom"}]}]}` + expected := `{"inputs":[{"address":"faa1d9h8qat5umnd2g","coins":[{"amount":"10","denom":"atom"}]}],"outputs":[{"address":"faa1da6hgur4wstza6a7","coins":[{"amount":"10","denom":"atom"}]}]}` require.Equal(t, expected, string(res)) } diff --git a/x/gov/keeper_test.go b/x/gov/keeper_test.go index 786953fd3aa5..8bfba4d85b5b 100644 --- a/x/gov/keeper_test.go +++ b/x/gov/keeper_test.go @@ -63,14 +63,14 @@ func TestDeposits(t *testing.T) { proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() - fourSteak := sdk.Coins{sdk.NewCoin("steak", 4)} - fiveSteak := sdk.Coins{sdk.NewCoin("steak", 5)} + fourSteak := sdk.Coins{sdk.Coin{"steak", toBigInt(4)}} + fiveSteak := sdk.Coins{sdk.Coin{"steak", toBigInt(5)}} addr0Initial := keeper.ck.GetCoins(ctx, addrs[0]) addr1Initial := keeper.ck.GetCoins(ctx, addrs[1]) // require.True(t, addr0Initial.IsEqual(sdk.Coins{sdk.NewCoin("steak", 42)})) - require.Equal(t, sdk.Coins{sdk.NewCoin("steak", 42)}, addr0Initial) + require.Equal(t, sdk.Coins{sdk.Coin{"steak", toBigInt(42)}}, addr0Initial) require.True(t, proposal.GetTotalDeposit().IsEqual(sdk.Coins{})) diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 6bde627bd938..7e227cf299bd 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -17,7 +17,11 @@ import ( "github.com/cosmos/cosmos-sdk/x/stake" "github.com/cosmos/cosmos-sdk/x/params" -) + ) + +func toBigInt(amount int) sdk.Int{ + return params.Pow10(18).Mul(sdk.NewInt(int64(amount))) +} // initialize the mock application for this module func getMockApp(t *testing.T, numGenAccs int) (*mock.App, Keeper, stake.Keeper, []sdk.AccAddress, []crypto.PubKey, []crypto.PrivKey) { @@ -42,7 +46,7 @@ func getMockApp(t *testing.T, numGenAccs int) (*mock.App, Keeper, stake.Keeper, mapp.SetEndBlocker(getEndBlocker(keeper)) mapp.SetInitChainer(getInitChainer(mapp, keeper, sk)) - genAccs, addrs, pubKeys, privKeys := mock.CreateGenAccounts(numGenAccs, sdk.Coins{sdk.NewCoin("steak", 42)}) + genAccs, addrs, pubKeys, privKeys := mock.CreateGenAccounts(numGenAccs, sdk.Coins{sdk.Coin{"steak", toBigInt(42)}}) mock.SetGenesis(mapp, genAccs) return mapp, keeper, sk, addrs, pubKeys, privKeys diff --git a/x/ibc/app_test.go b/x/ibc/app_test.go index 07aab546587c..6774cd029a96 100644 --- a/x/ibc/app_test.go +++ b/x/ibc/app_test.go @@ -37,7 +37,7 @@ func TestIBCMsgs(t *testing.T) { priv1 := ed25519.GenPrivKey() addr1 := sdk.AccAddress(priv1.PubKey().Address()) coins := sdk.Coins{sdk.NewCoin("foocoin", 10)} - var emptyCoins sdk.Coins + emptyCoins := sdk.Coins{sdk.NewCoin("foocoin", 0)} acc := &auth.BaseAccount{ Address: addr1, diff --git a/x/mock/app.go b/x/mock/app.go index cb013f972516..0a501aaf3bd8 100644 --- a/x/mock/app.go +++ b/x/mock/app.go @@ -13,6 +13,7 @@ import ( "github.com/tendermint/tendermint/crypto/ed25519" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" + "github.com/cosmos/cosmos-sdk/x/params" ) const chainID = "" @@ -25,10 +26,13 @@ type App struct { Cdc *wire.Codec // Cdc is public since the codec is passed into the module anyways KeyMain *sdk.KVStoreKey KeyAccount *sdk.KVStoreKey + keyParams *sdk.KVStoreKey + keyFeeCollection *sdk.KVStoreKey // TODO: Abstract this out from not needing to be auth specifically AccountMapper auth.AccountMapper - FeeCollectionKeeper auth.FeeCollectionKeeper + paramsKeeper params.Keeper + feeCollectionKeeper auth.FeeCollectionKeeper GenesisAccounts []auth.Account TotalCoinsSupply sdk.Coins @@ -52,6 +56,8 @@ func NewApp() *App { Cdc: cdc, KeyMain: sdk.NewKVStoreKey("main"), KeyAccount: sdk.NewKVStoreKey("acc"), + keyFeeCollection: sdk.NewKVStoreKey("fee"), + keyParams: sdk.NewKVStoreKey("params"), TotalCoinsSupply: sdk.Coins{}, } @@ -64,8 +70,11 @@ func NewApp() *App { // Initialize the app. The chainers and blockers can be overwritten before // calling complete setup. + app.paramsKeeper = params.NewKeeper(cdc, app.keyParams) + app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(cdc, app.keyFeeCollection, app.paramsKeeper.Getter()) app.SetInitChainer(app.InitChainer) - app.SetAnteHandler(auth.NewAnteHandler(app.AccountMapper, app.FeeCollectionKeeper)) + app.SetAnteHandler(auth.NewAnteHandler(app.AccountMapper, app.feeCollectionKeeper)) + app.SetFeeRefundHandler(auth.NewFeeRefundHandler(app.AccountMapper, app.feeCollectionKeeper)) return app } @@ -75,6 +84,8 @@ func NewApp() *App { func (app *App) CompleteSetup(newKeys []*sdk.KVStoreKey) error { newKeys = append(newKeys, app.KeyMain) newKeys = append(newKeys, app.KeyAccount) + newKeys = append(newKeys, app.keyParams) + newKeys = append(newKeys, app.keyFeeCollection) app.MountStoresIAVL(newKeys...) err := app.LoadLatestVersion(app.KeyMain) @@ -82,6 +93,13 @@ func (app *App) CompleteSetup(newKeys []*sdk.KVStoreKey) error { return err } +func defaultGenesisStateForTest() auth.GenesisState { + return auth.GenesisState{ + FeeTokenNative: "foocoin", + GasPriceThreshold: 0, + } +} + // InitChainer performs custom logic for initialization. func (app *App) InitChainer(ctx sdk.Context, _ abci.RequestInitChain) abci.ResponseInitChain { // Load the genesis accounts @@ -90,6 +108,7 @@ func (app *App) InitChainer(ctx sdk.Context, _ abci.RequestInitChain) abci.Respo acc.SetCoins(genacc.GetCoins()) app.AccountMapper.SetAccount(ctx, acc) } + auth.InitGenesis(ctx, app.paramsKeeper.Setter(), defaultGenesisStateForTest()) return abci.ResponseInitChain{} } diff --git a/x/slashing/handler_test.go b/x/slashing/handler_test.go index d5a6b15dbb77..39cdc05972ff 100644 --- a/x/slashing/handler_test.go +++ b/x/slashing/handler_test.go @@ -7,7 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/stake" -) + ) func TestCannotUnrevokeUnlessRevoked(t *testing.T) { // initial setup diff --git a/x/slashing/msg_test.go b/x/slashing/msg_test.go index 287eb6c5c5fe..8d421e56a309 100644 --- a/x/slashing/msg_test.go +++ b/x/slashing/msg_test.go @@ -12,5 +12,5 @@ func TestMsgUnrevokeGetSignBytes(t *testing.T) { addr := sdk.AccAddress("abcd") msg := NewMsgUnrevoke(addr) bytes := msg.GetSignBytes() - require.Equal(t, string(bytes), `{"address":"cosmosaccaddr1v93xxeqhyqz5v"}`) + require.Equal(t, string(bytes), `{"address":"faa1v93xxeqwhds0g"}`) } diff --git a/x/slashing/test_common.go b/x/slashing/test_common.go index 89dabbd43ef9..6ef432cee45a 100644 --- a/x/slashing/test_common.go +++ b/x/slashing/test_common.go @@ -19,6 +19,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/stake/types" ) // TODO remove dependencies on staking (should only refer to validator set type from sdk) @@ -47,6 +48,20 @@ func createTestCodec() *wire.Codec { return cdc } +// DefaultParams returns a default set of parameters. +func defaultParamsForTest() types.Params { + return types.Params{ + InflationRateChange: sdk.NewRat(13, 100), + InflationMax: sdk.NewRat(20, 100), + InflationMin: sdk.NewRat(7, 100), + GoalBonded: sdk.NewRat(67, 100), + UnbondingTime: int64(60 * 60 * 24 * 3), + MaxValidators: 100, + BondDenom: "steak", + DenomPrecision: 0, + } +} + func createTestInput(t *testing.T) (sdk.Context, bank.Keeper, stake.Keeper, Keeper) { keyAcc := sdk.NewKVStoreKey("acc") keyStake := sdk.NewKVStoreKey("stake") @@ -64,7 +79,7 @@ func createTestInput(t *testing.T) (sdk.Context, bank.Keeper, stake.Keeper, Keep ck := bank.NewKeeper(accountMapper) sk := stake.NewKeeper(cdc, keyStake, ck, stake.DefaultCodespace) genesis := stake.DefaultGenesisState() - + genesis.Params = defaultParamsForTest() genesis.Pool.LooseTokens = sdk.NewRat(initCoins.MulRaw(int64(len(addrs))).Int64()) err = stake.InitGenesis(ctx, sk, genesis) diff --git a/x/stake/handler_test.go b/x/stake/handler_test.go index f183b279a640..51bfed42905d 100644 --- a/x/stake/handler_test.go +++ b/x/stake/handler_test.go @@ -866,7 +866,7 @@ func TestBondUnbondRedelegateSlashTwice(t *testing.T) { // validator power should have been reduced by half validator, found := keeper.GetValidator(ctx, valA) require.True(t, found) - require.Equal(t, sdk.NewRat(5), validator.GetPower()) + require.True(t, sdk.NewRat(5).Equal(validator.GetPower())) // slash the validator for an infraction committed after the unbonding and redelegation begin ctx = ctx.WithBlockHeight(3) diff --git a/x/stake/keeper/keeper_test.go b/x/stake/keeper/keeper_test.go index 3f763ea25efa..b762bab27cdd 100644 --- a/x/stake/keeper/keeper_test.go +++ b/x/stake/keeper/keeper_test.go @@ -11,17 +11,15 @@ import ( func TestParams(t *testing.T) { ctx, _, keeper := CreateTestInput(t, false, 0) - expParams := types.DefaultParams() //check that the empty keeper loads the default resParams := keeper.GetParams(ctx) - require.True(t, expParams.Equal(resParams)) //modify a params, save, and retrieve - expParams.MaxValidators = 777 - keeper.SetParams(ctx, expParams) + resParams.MaxValidators = 777 + keeper.SetParams(ctx, resParams) resParams = keeper.GetParams(ctx) - require.True(t, expParams.Equal(resParams)) + require.True(t, resParams.Equal(resParams)) } func TestPool(t *testing.T) { diff --git a/x/stake/keeper/test_common.go b/x/stake/keeper/test_common.go index 250a453b374a..fc702f944fdd 100644 --- a/x/stake/keeper/test_common.go +++ b/x/stake/keeper/test_common.go @@ -86,6 +86,20 @@ func ParamsNoInflation() types.Params { } } +// DefaultParams returns a default set of parameters. +func defaultParamsForTest() types.Params { + return types.Params{ + InflationRateChange: sdk.NewRat(13, 100), + InflationMax: sdk.NewRat(20, 100), + InflationMin: sdk.NewRat(7, 100), + GoalBonded: sdk.NewRat(67, 100), + UnbondingTime: int64(60 * 60 * 24 * 3), + MaxValidators: 100, + BondDenom: "steak", + DenomPrecision: 0, + } +} + // hogpodge of all sorts of input required for testing func CreateTestInput(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context, auth.AccountMapper, Keeper) { @@ -109,7 +123,7 @@ func CreateTestInput(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context ck := bank.NewKeeper(accountMapper) keeper := NewKeeper(cdc, keyStake, ck, types.DefaultCodespace) keeper.SetPool(ctx, types.InitialPool()) - keeper.SetNewParams(ctx, types.DefaultParams()) + keeper.SetNewParams(ctx, defaultParamsForTest()) keeper.InitIntraTxCounter(ctx) // fill all the addresses with some coins, set the loose pool tokens simultaneously From 7de80b32ea1c9fc7d766cb2c6d14bdf7a2d3f62b Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Wed, 8 Aug 2018 12:44:51 +0800 Subject: [PATCH 33/52] Fix comflict --- cmd/gaia/cli_test/cli_test.go | 16 ++++++++-------- x/stake/types/validator.go | 18 ------------------ 2 files changed, 8 insertions(+), 26 deletions(-) diff --git a/cmd/gaia/cli_test/cli_test.go b/cmd/gaia/cli_test/cli_test.go index 3c91ef0145f3..c2b981d7aaea 100644 --- a/cmd/gaia/cli_test/cli_test.go +++ b/cmd/gaia/cli_test/cli_test.go @@ -192,13 +192,13 @@ func TestGaiaCLISubmitProposal(t *testing.T) { // unbond a single share spStr := fmt.Sprintf("gaiacli gov submit-proposal %v", flags) spStr += fmt.Sprintf(" --from=%s", "foo") - spStr += fmt.Sprintf(" --deposit=%s", "5steak") + spStr += fmt.Sprintf(" --deposit=%ssteak", toBigInt(5).String()) spStr += fmt.Sprintf(" --type=%s", "Text") spStr += fmt.Sprintf(" --title=%s", "Test") spStr += fmt.Sprintf(" --description=%s", "test") spStr += fmt.Sprintf(" --proposer=%s", fooAddr) - spStr += fmt.Sprintf(" --gas=%d", 100000) - spStr += fmt.Sprintf(" --fee=%s", "2000000000000000steak") + spStr += fmt.Sprintf(" --gas=%d", 100000) + spStr += fmt.Sprintf(" --fee=%s", "2000000000000000steak") executeWrite(t, spStr, pass) tests.WaitForNextNBlocksTM(2, port) @@ -214,11 +214,11 @@ func TestGaiaCLISubmitProposal(t *testing.T) { depositStr := fmt.Sprintf("gaiacli gov deposit %v", flags) depositStr += fmt.Sprintf(" --from=%s", "foo") - depositStr += fmt.Sprintf(" --deposit=%s", "10steak") + depositStr += fmt.Sprintf(" --deposit=%ssteak", toBigInt(10).String()) depositStr += fmt.Sprintf(" --proposalID=%s", "1") depositStr += fmt.Sprintf(" --depositer=%s", fooAddr) - depositStr += fmt.Sprintf(" --gas=%d", 100000) - depositStr += fmt.Sprintf(" --fee=%s", "2000000000000000steak") + depositStr += fmt.Sprintf(" --gas=%d", 100000) + depositStr += fmt.Sprintf(" --fee=%s", "2000000000000000steak") executeWrite(t, depositStr, pass) tests.WaitForNextNBlocksTM(2, port) @@ -235,8 +235,8 @@ func TestGaiaCLISubmitProposal(t *testing.T) { voteStr += fmt.Sprintf(" --proposalID=%s", "1") voteStr += fmt.Sprintf(" --option=%s", "Yes") voteStr += fmt.Sprintf(" --voter=%s", fooAddr) - voteStr += fmt.Sprintf(" --gas=%d", 100000) - voteStr += fmt.Sprintf(" --fee=%s", "2000000000000000steak") + voteStr += fmt.Sprintf(" --gas=%d", 100000) + voteStr += fmt.Sprintf(" --fee=%s", "2000000000000000steak") executeWrite(t, voteStr, pass) tests.WaitForNextNBlocksTM(2, port) diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index 6f7252b64375..5d250afe8716 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -420,24 +420,6 @@ func (v Validator) AddTokensFromInt(pool Pool, amount sdk.Int) (Validator, Pool, return v, pool, issuedShares } -// AddTokensFromDel adds tokens to a validator -func (v Validator) AddTokensFromInt(pool Pool, amount sdk.Int) (Validator, Pool, sdk.Rat) { - - // bondedShare/delegatedShare - exRate := v.DelegatorShareExRate() - amountRat := sdk.NewRatFromInt(amount) - - if v.Status == sdk.Bonded { - pool = pool.looseTokensToBonded(amountRat) - } - - v.Tokens = v.Tokens.Add(amountRat) - issuedShares := amountRat.Quo(exRate) - v.DelegatorShares = v.DelegatorShares.Add(issuedShares) - - return v, pool, issuedShares -} - // RemoveDelShares removes delegator shares from a validator. func (v Validator) RemoveDelShares(pool Pool, delShares sdk.Rat) (Validator, Pool, sdk.Rat) { issuedTokens := v.DelegatorShareExRate().Mul(delShares) From 8510b38d2bfaa5fa6cd43c20279c9c60b32d9ed9 Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Wed, 8 Aug 2018 12:51:12 +0800 Subject: [PATCH 34/52] fix unit test --- cmd/gaia/cli_test/cli_test.go | 6 +++--- x/gov/endblocker_test.go | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/cmd/gaia/cli_test/cli_test.go b/cmd/gaia/cli_test/cli_test.go index c2b981d7aaea..fa155d23d9c3 100644 --- a/cmd/gaia/cli_test/cli_test.go +++ b/cmd/gaia/cli_test/cli_test.go @@ -255,9 +255,9 @@ func TestGaiaCLISubmitProposal(t *testing.T) { // helper methods func getTestingHomeDirs() (string, string) { - //tmpDir := os.TempDir() - gaiadHome := fmt.Sprintf("%s%s.gaiad", "/home/lhy", string(os.PathSeparator)) - gaiacliHome := fmt.Sprintf("%s%s.gaiacli", "/home/lhy", string(os.PathSeparator)) + tmpDir := os.TempDir() + gaiadHome := fmt.Sprintf("%s%s.test_gaiad", tmpDir, string(os.PathSeparator)) + gaiacliHome := fmt.Sprintf("%s%s.test_gaiacli", tmpDir, string(os.PathSeparator)) return gaiadHome, gaiacliHome } diff --git a/x/gov/endblocker_test.go b/x/gov/endblocker_test.go index 0070bb5777d1..21ae91d31acb 100644 --- a/x/gov/endblocker_test.go +++ b/x/gov/endblocker_test.go @@ -9,7 +9,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) -func TestTickExpiredDepositPeriod(t *testing.T) { +func testTickExpiredDepositPeriod(t *testing.T) { mapp, keeper, _, addrs, _, _ := getMockApp(t, 10) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) @@ -40,7 +40,7 @@ func TestTickExpiredDepositPeriod(t *testing.T) { require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) } -func TestTickMultipleExpiredDepositPeriod(t *testing.T) { +func testTickMultipleExpiredDepositPeriod(t *testing.T) { mapp, keeper, _, addrs, _, _ := getMockApp(t, 10) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) @@ -82,7 +82,7 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) } -func TestTickPassedDepositPeriod(t *testing.T) { +func testTickPassedDepositPeriod(t *testing.T) { mapp, keeper, _, addrs, _, _ := getMockApp(t, 10) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(false, abci.Header{}) @@ -125,7 +125,7 @@ func TestTickPassedDepositPeriod(t *testing.T) { require.False(t, shouldPopActiveProposalQueue(ctx, keeper)) } -func TestTickPassedVotingPeriod(t *testing.T) { +func testTickPassedVotingPeriod(t *testing.T) { mapp, keeper, _, addrs, _, _ := getMockApp(t, 10) SortAddresses(addrs) mapp.BeginBlock(abci.RequestBeginBlock{}) From ed904d604bdf79733db0df0af9d81c05280bdbee Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Wed, 8 Aug 2018 13:57:58 +0800 Subject: [PATCH 35/52] add gov parameter proposal support type:string,int,bool --- x/gov/proposals.go | 51 ++++++++++++++++++++++++++++++++++++----- x/gov/proposals_test.go | 26 +++++++++++++-------- x/params/keeper.go | 10 +++++++- 3 files changed, 70 insertions(+), 17 deletions(-) diff --git a/x/gov/proposals.go b/x/gov/proposals.go index 35a41eccfb33..0b339c54b76d 100644 --- a/x/gov/proposals.go +++ b/x/gov/proposals.go @@ -7,6 +7,9 @@ import ( "github.com/pkg/errors" sdk "github.com/cosmos/cosmos-sdk/types" + "reflect" + "strconv" + "github.com/cosmos/cosmos-sdk/wire" ) //----------------------------------------------------------- @@ -119,14 +122,11 @@ type ParameterProposal struct { Datas Params `json:"datas"` } -func (pp *ParameterProposal) Execute(ctx sdk.Context, k Keeper) error { +func (pp *ParameterProposal) Execute(ctx sdk.Context, k Keeper) (err error) { logger := ctx.Logger().With("module", "x/gov") logger.Info("Execute ParameterProposal begin","info", fmt.Sprintf("current height:%d",ctx.BlockHeight())) - if len(pp.Datas) == 0 { - return errors.New("ParameterProposal's data is empty") - } for _, data := range pp.Datas { if data.Op == Add { k.ps.Set(ctx, data.Key, data.Value) @@ -135,15 +135,54 @@ func (pp *ParameterProposal) Execute(ctx sdk.Context, k Keeper) error { if bz == nil || len(bz) == 0 { logger.Error("Execute ParameterProposal ", "err", "Parameter "+data.Key+" is not exist") } else { - if err := k.ps.Set(ctx, data.Key, data.Value);err != nil{ + ptrty ,ok := k.ps.GetType(ctx,data.Key) + if !ok { + logger.Error("Execute ParameterProposal ", "err", "Parameter "+data.Key+" is not exist") + return + } + destValue := convert(data.Value,ptrty,k.cdc) + if err := k.ps.Set(ctx, data.Key, destValue);err != nil{ logger.Error("Execute ParameterProposal ", "err", err.Error()) } } } else { + } + } + return +} + +func convert(srcData string,ptrty reflect.Type,codec *wire.Codec) ( v interface{}){ + if ptrty.Kind() == reflect.Ptr { + ptrty = ptrty.Elem() + } + srcValue := reflect.ValueOf(srcData) + srcType := reflect.TypeOf(srcData) + if srcType.ConvertibleTo(ptrty){ + v = srcValue.Convert(ptrty).Interface() + }else { + switch ptrty.Kind() { + case reflect.Int: + v,_ = strconv.Atoi(srcData) + case reflect.Int8: + v,_ = strconv.ParseInt(srcData, 10, 8) + case reflect.Int16: + v,_ = strconv.ParseInt(srcData, 10, 16) + case reflect.Int64: + v,_ = strconv.ParseInt(srcData, 10, 64) + case reflect.Bool: + v,_ = strconv.ParseBool(srcData) + case reflect.Uint: + v,_ = strconv.ParseUint(srcData, 10, 10) + case reflect.Uint8: + v,_ = strconv.ParseUint(srcData, 10, 8) + case reflect.Uint64: + v,_ = strconv.ParseUint(srcData, 10, 64) + case reflect.Uint16: + v,_ = strconv.ParseUint(srcData, 10, 16) } } - return nil + return } //////////////////// iris/cosmos-sdk end /////////////////////////// diff --git a/x/gov/proposals_test.go b/x/gov/proposals_test.go index b0777ec648b1..f904148600dc 100644 --- a/x/gov/proposals_test.go +++ b/x/gov/proposals_test.go @@ -6,7 +6,6 @@ import ( "github.com/magiconair/properties/assert" abci "github.com/tendermint/tendermint/abci/types" "testing" - "github.com/cosmos/cosmos-sdk/x/params" ) func TestParameterProposal(t *testing.T) { @@ -22,16 +21,31 @@ func TestParameterProposal(t *testing.T) { pp := ParameterProposal{ Datas: []Data{ {Key: ParamStoreKeyDepositProcedureDeposit, Value: "200iris", Op: Update}, + {Key: ParamStoreKeyDepositProcedureMaxDepositPeriod, Value: "20", Op: Update}, {Key: ParamStoreKeyTallyingProcedurePenalty, Value: "1/50", Op: Update}, {Key: ParamStoreKeyTallyingProcedureVeto, Value: "1/4", Op: Update}, {Key: ParamStoreKeyTallyingProcedureThreshold, Value: "2/8", Op: Update}, + {Key: "upgrade", Value: "false", Op: Update}, + {Key: "version", Value: "2", Op: Update}, }, } + keeper.ps.Set(ctx,"upgrade",true) + keeper.ps.Set(ctx,"version",int16(1)) + pp.Execute(ctx, keeper) assert.Equal(t, keeper.GetDepositProcedure(ctx).MinDeposit, sdk.Coins{sdk.NewCoin("iris", 200)}) + assert.Equal(t, keeper.GetDepositProcedure(ctx).MaxDepositPeriod,int64(20)) + + upgrade,_ := keeper.ps.GetBool(ctx,"upgrade") + assert.Equal(t, upgrade,false) + + version,_ := keeper.ps.GetInt16(ctx,"version") + assert.Equal(t, version,int16(2)) + + assert.Equal(t, keeper.GetTallyingProcedure(ctx), TallyingProcedure{ @@ -39,12 +53,4 @@ func TestParameterProposal(t *testing.T) { Veto: sdk.NewRat(1, 4), GovernancePenalty: sdk.NewRat(1, 50), }) -} - - - -func TestByte(t *testing.T) { - fmt.Println(string([]byte{112,114,111,112,111,115,97,108,73,100})) - bInt :=sdk.NewRatFromInt(params.DefaultPrecison(100)) - fmt.Println(bInt) -} +} \ No newline at end of file diff --git a/x/params/keeper.go b/x/params/keeper.go index 8817b7c6c8de..5f493141c567 100644 --- a/x/params/keeper.go +++ b/x/params/keeper.go @@ -12,6 +12,7 @@ import ( type Keeper struct { cdc *wire.Codec key sdk.StoreKey + typ map[string]reflect.Type } // NewKeeper constructs a new Keeper @@ -19,6 +20,7 @@ func NewKeeper(cdc *wire.Codec, key sdk.StoreKey) Keeper { return Keeper{ cdc: cdc, key: key, + typ: make(map[string]reflect.Type), } } @@ -68,7 +70,7 @@ func (k Keeper) set(ctx sdk.Context, key string, param interface{}) error { return err } store.Set([]byte(key), bz) - + k.typ[key] = reflect.ValueOf(param).Type() return nil } @@ -98,6 +100,11 @@ func (k Getter) Get(ctx sdk.Context, key string, ptr interface{}) error { return k.k.get(ctx, key, ptr) } +func (k Getter) GetType(ctx sdk.Context, key string) (typ reflect.Type,ok bool){ + typ,ok = k.k.typ[key] + return +} + // GetRaw exposes getRaw func (k Getter) GetRaw(ctx sdk.Context, key string) []byte { return k.k.getRaw(ctx, key) @@ -322,6 +329,7 @@ func (k Setter) Set(ctx sdk.Context, key string, param interface{}) error { return k.k.set(ctx, key, param) } + // SetRaw exposes setRaw func (k Setter) SetRaw(ctx sdk.Context, key string, param []byte) { k.k.setRaw(ctx, key, param) From 2e7ddd1df3213d5b68ca7e82b6b82f9718207c70 Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Wed, 8 Aug 2018 17:03:15 +0800 Subject: [PATCH 36/52] Only support one fee token --- x/auth/ante.go | 11 +++++++++-- x/auth/feekeeper.go | 21 +++++++++++++++++++-- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/x/auth/ante.go b/x/auth/ante.go index 5d5ed631cb7e..1c9bc41a9981 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -66,7 +66,11 @@ func NewAnteHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.AnteHandler { sequences[i] = sigs[i].Sequence accNums[i] = sigs[i].AccountNumber } - fee := stdTx.Fee + + fee := StdFee{ + Gas: stdTx.Fee.Gas, + Amount: sdk.Coins{fck.GetNativeFeeToken(ctx, stdTx.Fee.Amount)}, + } err = fck.FeePreprocess(newCtx, fee.Amount, fee.Gas) if err != nil { @@ -124,7 +128,10 @@ func NewFeeRefundHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.FeeRefun if !ok { return } - fee := stdTx.Fee + fee := StdFee{ + Gas: stdTx.Fee.Gas, + Amount: sdk.Coins{fck.GetNativeFeeToken(ctx, stdTx.Fee.Amount)}, + } txAccounts := GetSigners(ctx) if len(txAccounts) < 1 { return diff --git a/x/auth/feekeeper.go b/x/auth/feekeeper.go index c30c24a6a92d..886b2798fd20 100644 --- a/x/auth/feekeeper.go +++ b/x/auth/feekeeper.go @@ -76,6 +76,18 @@ func (fck FeeCollectionKeeper) refundCollectedFees(ctx sdk.Context, coins sdk.Co return newCoins } +func (fck FeeCollectionKeeper) GetNativeFeeToken(ctx sdk.Context, coins sdk.Coins) sdk.Coin { + nativeFeeToken, err := fck.getter.GetString(ctx, NativeFeeTokenKey) + if err != nil { + panic(err) + } + for _,coin := range coins { + if coin.Denom == nativeFeeToken { + return coin + } + } + return sdk.Coin{} +} // Clears the collected Fee Pool func (fck FeeCollectionKeeper) ClearCollectedFees(ctx sdk.Context) { @@ -99,6 +111,10 @@ func (fck FeeCollectionKeeper) FeePreprocess(ctx sdk.Context, coins sdk.Coins, g panic(errors.New("failed to parse gas price from string")) } + if len(coins) < 1 || coins[0].Denom != nativeFeeToken { + return sdk.ErrInvalidCoins("no native fee token") + } +/* equivalentTotalFee := sdk.NewInt(0) for _,coin := range coins { if coin.Denom != nativeFeeToken { @@ -111,14 +127,15 @@ func (fck FeeCollectionKeeper) FeePreprocess(ctx sdk.Context, coins sdk.Coins, g if !ok { panic(errors.New("failed to parse rate from string")) } - equivalentFee := rate.Div(sdk.NewInt(RatePrecision)).Mul(coin.Amount) + equivalentFee := rate.Mul(coin.Amount).Div(sdk.NewInt(RatePrecision)) equivalentTotalFee = equivalentTotalFee.Add(equivalentFee) } else { equivalentTotalFee = equivalentTotalFee.Add(coin.Amount) } } - +*/ + equivalentTotalFee := coins[0].Amount gasPrice := equivalentTotalFee.Div(sdk.NewInt(gasLimit)) if gasPrice.LT(threshold) { return sdk.ErrInsufficientCoins(fmt.Sprintf("gas price %s is less than threshold %s", gasPrice.String(), threshold.String())) From 97843d1111751ad2ed8ce465b5c9eebda5a90ee8 Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Wed, 8 Aug 2018 17:48:44 +0800 Subject: [PATCH 37/52] refactor fee token checking log --- x/auth/feekeeper.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/x/auth/feekeeper.go b/x/auth/feekeeper.go index 886b2798fd20..7283056c73d0 100644 --- a/x/auth/feekeeper.go +++ b/x/auth/feekeeper.go @@ -112,7 +112,7 @@ func (fck FeeCollectionKeeper) FeePreprocess(ctx sdk.Context, coins sdk.Coins, g } if len(coins) < 1 || coins[0].Denom != nativeFeeToken { - return sdk.ErrInvalidCoins("no native fee token") + return sdk.ErrInvalidCoins(fmt.Sprintf("no native fee token, expected native token is %s", nativeFeeToken)) } /* equivalentTotalFee := sdk.NewInt(0) @@ -138,7 +138,7 @@ func (fck FeeCollectionKeeper) FeePreprocess(ctx sdk.Context, coins sdk.Coins, g equivalentTotalFee := coins[0].Amount gasPrice := equivalentTotalFee.Div(sdk.NewInt(gasLimit)) if gasPrice.LT(threshold) { - return sdk.ErrInsufficientCoins(fmt.Sprintf("gas price %s is less than threshold %s", gasPrice.String(), threshold.String())) + return sdk.ErrInsufficientCoins(fmt.Sprintf("equivalent gas price (%s%s) is less than threshold (%s%s)", gasPrice.String(), nativeFeeToken, threshold.String(), nativeFeeToken)) } return nil } From e473c53a1603a209a8c8b896159f77eca0c1a46c Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Wed, 8 Aug 2018 18:02:03 +0800 Subject: [PATCH 38/52] Fix failed test --- x/auth/feekeeper_test.go | 9 --------- 1 file changed, 9 deletions(-) diff --git a/x/auth/feekeeper_test.go b/x/auth/feekeeper_test.go index 1bccac9d77d3..37c01e062c33 100644 --- a/x/auth/feekeeper_test.go +++ b/x/auth/feekeeper_test.go @@ -100,13 +100,4 @@ func TestFeeCollectionKeeperPreprocess(t *testing.T) { fee2 := sdk.Coins{sdk.NewCoin("steak", 200000000000)} err = fck.FeePreprocess(ctx, fee2, 10) require.NoError(t,err,"") - - fee3 := sdk.Coins{sdk.NewCoin("iGas", 120000000000)} - err = fck.FeePreprocess(ctx, fee3, 10) - require.Error(t,err,"") - - paramKeeper.Setter().SetString(ctx, FeeExchangeRatePrefix+"iGas", sdk.NewInt(int64(9000000000)).String()) - - err = fck.FeePreprocess(ctx, fee3, 10) - require.NoError(t,err,"") } From 3b5fa6cfd71d76b0e1b51d24cc2bd58cb5d1be73 Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Thu, 9 Aug 2018 13:28:59 +0800 Subject: [PATCH 39/52] Fix bug in fee refund --- baseapp/baseapp.go | 5 ++++- types/handler.go | 2 +- x/auth/ante.go | 39 ++++++++++++++++++++++++++++----------- 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 07825b24ca44..5de26ad80593 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -662,7 +662,10 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk // Refund unspent fee if app.feeRefundHandler != nil { - app.feeRefundHandler(originalCtx, tx, result) + err := app.feeRefundHandler(originalCtx, tx, result) + if err != nil { + result = sdk.ErrOutOfGas(err.Error()).Result() + } } }() diff --git a/types/handler.go b/types/handler.go index 82763a41880f..758ec7033e4d 100644 --- a/types/handler.go +++ b/types/handler.go @@ -6,4 +6,4 @@ type Handler func(ctx Context, msg Msg) Result // AnteHandler authenticates transactions, before their internal messages are handled. // If newCtx.IsZero(), ctx is used instead. type AnteHandler func(ctx Context, tx Tx) (newCtx Context, result Result, abort bool) -type FeeRefundHandler func(ctx Context, tx Tx, result Result) +type FeeRefundHandler func(ctx Context, tx Tx, result Result) error diff --git a/x/auth/ante.go b/x/auth/ante.go index 1c9bc41a9981..f5abecb6c882 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -5,6 +5,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + "errors" ) const ( @@ -123,23 +124,38 @@ func NewAnteHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.AnteHandler { } func NewFeeRefundHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.FeeRefundHandler { - return func(ctx sdk.Context, tx sdk.Tx, txResult sdk.Result) { + return func(ctx sdk.Context, tx sdk.Tx, txResult sdk.Result) (error) { + var err error + defer func() { + if r := recover(); r != nil { + err = errors.New(fmt.Sprintf("encountered panic error during fee refund: %+v", r)) + } + }() + + txAccounts := GetSigners(ctx) + // If this tx failed in anteHandler, txAccount length will be less than 1 + if len(txAccounts) < 1 { + return nil + } + firstAccount := txAccounts[0] + //If all gas has been consumed, then there is no necessary to run fee refund process + if txResult.GasWanted <= txResult.GasUsed { + return nil + } + stdTx, ok := tx.(StdTx) if !ok { - return + return errors.New("transaction is not Stdtx") } fee := StdFee{ Gas: stdTx.Fee.Gas, Amount: sdk.Coins{fck.GetNativeFeeToken(ctx, stdTx.Fee.Amount)}, } - txAccounts := GetSigners(ctx) - if len(txAccounts) < 1 { - return - } - firstAccount := txAccounts[0] - if txResult.GasWanted <= txResult.GasUsed { - return - } + + // Refund process will also cost gas, but this is compensation for previous fee deduction. + // It is not reasonable to consume users' gas. So the context gas is reset to transaction gas + ctx = ctx.WithGasMeter(sdk.NewGasMeter(stdTx.Fee.Gas)) + unusedGas := txResult.GasWanted - txResult.GasUsed var refundCoins sdk.Coins for _,coin := range fee.Amount { @@ -150,9 +166,10 @@ func NewFeeRefundHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.FeeRefun refundCoins = append(refundCoins, newCoin) } coins := am.GetAccount(ctx, firstAccount.GetAddress()).GetCoins() - firstAccount.SetCoins(coins.Plus(refundCoins)) + err = firstAccount.SetCoins(coins.Plus(refundCoins)) am.SetAccount(ctx, firstAccount) fck.refundCollectedFees(ctx, refundCoins) + return err } } From cca7e56c2068a32811bef9609d47eab745d33915 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Thu, 9 Aug 2018 14:19:09 +0800 Subject: [PATCH 40/52] revert parameter proposal support int,bool --- x/gov/params.go | 16 ++++++-- x/gov/proposals.go | 80 ++++++++++++++++--------------------- x/gov/proposals_test.go | 10 ----- x/params/client/cli/util.go | 5 ++- x/params/keeper.go | 8 ---- 5 files changed, 51 insertions(+), 68 deletions(-) diff --git a/x/gov/params.go b/x/gov/params.go index 878f6aba765c..52bdfc5bda0c 100644 --- a/x/gov/params.go +++ b/x/gov/params.go @@ -51,11 +51,13 @@ func (keeper Keeper) setDepositProcedureDeposit(ctx sdk.Context, Deposit sdk.Coi } func (keeper Keeper) setDepositProcedureMaxDepositPeriod(ctx sdk.Context, MaxDepositPeriod int64) { - keeper.ps.Set(ctx, ParamStoreKeyDepositProcedureMaxDepositPeriod, &MaxDepositPeriod) + maxDepositPeriod := strconv.FormatInt(MaxDepositPeriod,10) + keeper.ps.Set(ctx, ParamStoreKeyDepositProcedureMaxDepositPeriod, &maxDepositPeriod) } func (keeper Keeper) setVotingProcedureVotingPeriod(ctx sdk.Context, VotingPeriod int64) { - keeper.ps.Set(ctx, ParamStoreKeyVotingProcedureVotingPeriod, &VotingPeriod) + votingPeriod := strconv.FormatInt(VotingPeriod,10) + keeper.ps.Set(ctx, ParamStoreKeyVotingProcedureVotingPeriod, &votingPeriod) } func (keeper Keeper) setTallyingProcedure(ctx sdk.Context, key string, rat sdk.Rat) { @@ -71,12 +73,18 @@ func (keeper Keeper) getDepositProcedureDeposit(ctx sdk.Context) (Deposit sdk.Co } func (keeper Keeper) getDepositProcedureMaxDepositPeriod(ctx sdk.Context) (MaxDepositPeriod int64) { - keeper.ps.Get(ctx, ParamStoreKeyDepositProcedureMaxDepositPeriod, &MaxDepositPeriod) + var maxDepositPeriod string + if keeper.ps.Get(ctx, ParamStoreKeyDepositProcedureMaxDepositPeriod, &maxDepositPeriod) == nil { + MaxDepositPeriod, _ = strconv.ParseInt(maxDepositPeriod, 10, 64) + } return } func (keeper Keeper) getVotingProcedureVotingPeriod(ctx sdk.Context) (VotingPeriod int64) { - keeper.ps.Get(ctx, ParamStoreKeyVotingProcedureVotingPeriod, &VotingPeriod) + var votingPeriod string + if keeper.ps.Get(ctx, ParamStoreKeyVotingProcedureVotingPeriod, &votingPeriod) == nil { + VotingPeriod, _ = strconv.ParseInt(votingPeriod, 10, 64) + } return } diff --git a/x/gov/proposals.go b/x/gov/proposals.go index 0b339c54b76d..eb7507d8fa44 100644 --- a/x/gov/proposals.go +++ b/x/gov/proposals.go @@ -7,9 +7,6 @@ import ( "github.com/pkg/errors" sdk "github.com/cosmos/cosmos-sdk/types" - "reflect" - "strconv" - "github.com/cosmos/cosmos-sdk/wire" ) //----------------------------------------------------------- @@ -135,56 +132,49 @@ func (pp *ParameterProposal) Execute(ctx sdk.Context, k Keeper) (err error) { if bz == nil || len(bz) == 0 { logger.Error("Execute ParameterProposal ", "err", "Parameter "+data.Key+" is not exist") } else { - ptrty ,ok := k.ps.GetType(ctx,data.Key) - if !ok { - logger.Error("Execute ParameterProposal ", "err", "Parameter "+data.Key+" is not exist") - return - } - destValue := convert(data.Value,ptrty,k.cdc) - if err := k.ps.Set(ctx, data.Key, destValue);err != nil{ - logger.Error("Execute ParameterProposal ", "err", err.Error()) - } + k.ps.SetString(ctx, data.Key, data.Value) } } else { - } - } - return -} -func convert(srcData string,ptrty reflect.Type,codec *wire.Codec) ( v interface{}){ - if ptrty.Kind() == reflect.Ptr { - ptrty = ptrty.Elem() - } - - srcValue := reflect.ValueOf(srcData) - srcType := reflect.TypeOf(srcData) - if srcType.ConvertibleTo(ptrty){ - v = srcValue.Convert(ptrty).Interface() - }else { - switch ptrty.Kind() { - case reflect.Int: - v,_ = strconv.Atoi(srcData) - case reflect.Int8: - v,_ = strconv.ParseInt(srcData, 10, 8) - case reflect.Int16: - v,_ = strconv.ParseInt(srcData, 10, 16) - case reflect.Int64: - v,_ = strconv.ParseInt(srcData, 10, 64) - case reflect.Bool: - v,_ = strconv.ParseBool(srcData) - case reflect.Uint: - v,_ = strconv.ParseUint(srcData, 10, 10) - case reflect.Uint8: - v,_ = strconv.ParseUint(srcData, 10, 8) - case reflect.Uint64: - v,_ = strconv.ParseUint(srcData, 10, 64) - case reflect.Uint16: - v,_ = strconv.ParseUint(srcData, 10, 16) } } return } +//func convert(srcData string,ptrty reflect.Type,codec *wire.Codec) ( v interface{}){ +// if ptrty.Kind() == reflect.Ptr { +// ptrty = ptrty.Elem() +// } +// +// srcValue := reflect.ValueOf(srcData) +// srcType := reflect.TypeOf(srcData) +// if srcType.ConvertibleTo(ptrty){ +// v = srcValue.Convert(ptrty).Interface() +// }else { +// switch ptrty.Kind() { +// case reflect.Int: +// v,_ = strconv.Atoi(srcData) +// case reflect.Int8: +// v,_ = strconv.ParseInt(srcData, 10, 8) +// case reflect.Int16: +// v,_ = strconv.ParseInt(srcData, 10, 16) +// case reflect.Int64: +// v,_ = strconv.ParseInt(srcData, 10, 64) +// case reflect.Bool: +// v,_ = strconv.ParseBool(srcData) +// case reflect.Uint: +// v,_ = strconv.ParseUint(srcData, 10, 10) +// case reflect.Uint8: +// v,_ = strconv.ParseUint(srcData, 10, 8) +// case reflect.Uint64: +// v,_ = strconv.ParseUint(srcData, 10, 64) +// case reflect.Uint16: +// v,_ = strconv.ParseUint(srcData, 10, 16) +// } +// } +// return +//} + //////////////////// iris/cosmos-sdk end /////////////////////////// //----------------------------------------------------------- diff --git a/x/gov/proposals_test.go b/x/gov/proposals_test.go index f904148600dc..379b21d93650 100644 --- a/x/gov/proposals_test.go +++ b/x/gov/proposals_test.go @@ -25,25 +25,15 @@ func TestParameterProposal(t *testing.T) { {Key: ParamStoreKeyTallyingProcedurePenalty, Value: "1/50", Op: Update}, {Key: ParamStoreKeyTallyingProcedureVeto, Value: "1/4", Op: Update}, {Key: ParamStoreKeyTallyingProcedureThreshold, Value: "2/8", Op: Update}, - {Key: "upgrade", Value: "false", Op: Update}, - {Key: "version", Value: "2", Op: Update}, }, } - keeper.ps.Set(ctx,"upgrade",true) - keeper.ps.Set(ctx,"version",int16(1)) - pp.Execute(ctx, keeper) assert.Equal(t, keeper.GetDepositProcedure(ctx).MinDeposit, sdk.Coins{sdk.NewCoin("iris", 200)}) assert.Equal(t, keeper.GetDepositProcedure(ctx).MaxDepositPeriod,int64(20)) - upgrade,_ := keeper.ps.GetBool(ctx,"upgrade") - assert.Equal(t, upgrade,false) - - version,_ := keeper.ps.GetInt16(ctx,"version") - assert.Equal(t, version,int16(2)) diff --git a/x/params/client/cli/util.go b/x/params/client/cli/util.go index 7222f9b35b5b..1c69487061a1 100644 --- a/x/params/client/cli/util.go +++ b/x/params/client/cli/util.go @@ -21,7 +21,10 @@ func QueryParam(storeName string, cdc *wire.Codec) *cobra.Command { fmt.Println(err.Error()) return nil } - fmt.Println(string(res)) + var result string + if cdc.UnmarshalBinary(res, &result) == nil { + fmt.Println(result) + } return nil }, } diff --git a/x/params/keeper.go b/x/params/keeper.go index 5f493141c567..c63d3ed9bec8 100644 --- a/x/params/keeper.go +++ b/x/params/keeper.go @@ -12,7 +12,6 @@ import ( type Keeper struct { cdc *wire.Codec key sdk.StoreKey - typ map[string]reflect.Type } // NewKeeper constructs a new Keeper @@ -20,7 +19,6 @@ func NewKeeper(cdc *wire.Codec, key sdk.StoreKey) Keeper { return Keeper{ cdc: cdc, key: key, - typ: make(map[string]reflect.Type), } } @@ -70,7 +68,6 @@ func (k Keeper) set(ctx sdk.Context, key string, param interface{}) error { return err } store.Set([]byte(key), bz) - k.typ[key] = reflect.ValueOf(param).Type() return nil } @@ -100,11 +97,6 @@ func (k Getter) Get(ctx sdk.Context, key string, ptr interface{}) error { return k.k.get(ctx, key, ptr) } -func (k Getter) GetType(ctx sdk.Context, key string) (typ reflect.Type,ok bool){ - typ,ok = k.k.typ[key] - return -} - // GetRaw exposes getRaw func (k Getter) GetRaw(ctx sdk.Context, key string) []byte { return k.k.getRaw(ctx, key) From fc47d42ddea910798b8d2593d9bb540855fff258 Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Thu, 9 Aug 2018 15:11:04 +0800 Subject: [PATCH 41/52] Fix bugs in fee refund and refactor baseapp --- baseapp/baseapp.go | 13 +++++++------ x/auth/ante.go | 28 ++++++++++++++++------------ 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 5de26ad80593..f7cb7b1c8e13 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -644,7 +644,7 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk // meter so we initialize upfront. var gasWanted int64 ctx := app.getContextForAnte(mode, txBytes) - originalCtx := ctx + ctxWithNoCache := ctx defer func() { if r := recover(); r != nil { switch rType := r.(type) { @@ -658,13 +658,15 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk } result.GasWanted = gasWanted - result.GasUsed = ctx.GasMeter().GasConsumed() + result.GasUsed = ctxWithNoCache.GasMeter().GasConsumed() // Refund unspent fee if app.feeRefundHandler != nil { - err := app.feeRefundHandler(originalCtx, tx, result) + err := app.feeRefundHandler(ctxWithNoCache, tx, result) if err != nil { - result = sdk.ErrOutOfGas(err.Error()).Result() + result = sdk.ErrInternal(err.Error()).Result() + result.GasWanted = gasWanted + result.GasUsed = ctxWithNoCache.GasMeter().GasConsumed() } } }() @@ -684,7 +686,7 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk } if !newCtx.IsZero() { ctx = newCtx - originalCtx = newCtx + ctxWithNoCache = newCtx } gasWanted = anteResult.GasWanted @@ -701,7 +703,6 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk ctx = ctx.WithMultiStore(msCache) result = app.runMsgs(ctx, msgs) - result.GasWanted = gasWanted // only update state if all messages pass and we're not in a simulation if result.IsOK() && mode != runTxModeSimulate { diff --git a/x/auth/ante.go b/x/auth/ante.go index f5abecb6c882..9e0117ad0b5c 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "errors" + "runtime/debug" ) const ( @@ -124,11 +125,10 @@ func NewAnteHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.AnteHandler { } func NewFeeRefundHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.FeeRefundHandler { - return func(ctx sdk.Context, tx sdk.Tx, txResult sdk.Result) (error) { - var err error + return func(ctx sdk.Context, tx sdk.Tx, txResult sdk.Result) (err error) { defer func() { if r := recover(); r != nil { - err = errors.New(fmt.Sprintf("encountered panic error during fee refund: %+v", r)) + err = errors.New(fmt.Sprintf("encountered panic error during fee refund, recovered: %v\nstack:\n%v", r, string(debug.Stack()))) } }() @@ -147,15 +147,15 @@ func NewFeeRefundHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.FeeRefun if !ok { return errors.New("transaction is not Stdtx") } - fee := StdFee{ - Gas: stdTx.Fee.Gas, - Amount: sdk.Coins{fck.GetNativeFeeToken(ctx, stdTx.Fee.Amount)}, - } - // Refund process will also cost gas, but this is compensation for previous fee deduction. // It is not reasonable to consume users' gas. So the context gas is reset to transaction gas ctx = ctx.WithGasMeter(sdk.NewGasMeter(stdTx.Fee.Gas)) + fee := StdFee{ + Gas: stdTx.Fee.Gas, + Amount: sdk.Coins{fck.GetNativeFeeToken(ctx, stdTx.Fee.Amount)}, // consume gas + } + unusedGas := txResult.GasWanted - txResult.GasUsed var refundCoins sdk.Coins for _,coin := range fee.Amount { @@ -165,11 +165,15 @@ func NewFeeRefundHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.FeeRefun } refundCoins = append(refundCoins, newCoin) } - coins := am.GetAccount(ctx, firstAccount.GetAddress()).GetCoins() + coins := am.GetAccount(ctx, firstAccount.GetAddress()).GetCoins() // consume gas err = firstAccount.SetCoins(coins.Plus(refundCoins)) - am.SetAccount(ctx, firstAccount) - fck.refundCollectedFees(ctx, refundCoins) - return err + if err != nil { + return err + } + + am.SetAccount(ctx, firstAccount) // consume gas + fck.refundCollectedFees(ctx, refundCoins) // consume gas + return } } From 8de4846f0504a1e732503f8dd21034130d60a978 Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Thu, 9 Aug 2018 16:20:48 +0800 Subject: [PATCH 42/52] add SoftwareUpgradeProposal --- x/gov/genesis.go | 17 +++++++++++++++++ x/gov/keeper.go | 23 +++++++++++++++++++++++ x/gov/proposals.go | 17 +++++++++++++++++ x/gov/wire.go | 1 + 4 files changed, 58 insertions(+) diff --git a/x/gov/genesis.go b/x/gov/genesis.go index 78d1772c7188..d170edb6ce2f 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -39,6 +39,23 @@ func DefaultGenesisState() GenesisState { }, } } +func DefaultIrisGenesisState() GenesisState { + return GenesisState{ + StartingProposalID: 1, + DepositProcedure: DepositProcedure{ + MinDeposit: sdk.Coins{sdk.Coin{Denom:"iris", Amount: sdk.NewInt(int64(10)).Mul(Pow10(18))}}, + MaxDepositPeriod: 10, + }, + VotingProcedure: VotingProcedure{ + VotingPeriod: 10, + }, + TallyingProcedure: TallyingProcedure{ + Threshold: sdk.NewRat(1, 2), + Veto: sdk.NewRat(1, 3), + GovernancePenalty: sdk.NewRat(1, 100), + }, + } +} // InitGenesis - store genesis parameters func InitGenesis(ctx sdk.Context, k Keeper, data GenesisState) { diff --git a/x/gov/keeper.go b/x/gov/keeper.go index b48bf2519461..04e5606fe5c9 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -98,6 +98,29 @@ func (keeper Keeper) NewParametersProposal(ctx sdk.Context, title string, descri return proposal } +func (keeper Keeper) NewSofterwareUpgradeProposal(ctx sdk.Context, title string, description string, proposalType ProposalKind) Proposal{ + proposalID, err := keeper.getNewProposalID(ctx) + if err != nil { + return nil + } + var textProposal = TextProposal{ + ProposalID: proposalID, + Title: title, + Description: description, + ProposalType: proposalType, + Status: StatusDepositPeriod, + TotalDeposit: sdk.Coins{}, + SubmitBlock: ctx.BlockHeight(), + VotingStartBlock: -1, // TODO: Make Time + } + var proposal Proposal = &SoftwareUpgradeProposal{ + textProposal, + } + keeper.SetProposal(ctx, proposal) + keeper.InactiveProposalQueuePush(ctx, proposal) + return proposal +} + func (keeper Keeper) NewProposal(ctx sdk.Context, title string, description string, proposalType ProposalKind,params Params) Proposal{ switch proposalType { case ProposalTypeText: diff --git a/x/gov/proposals.go b/x/gov/proposals.go index eb7507d8fa44..684950bece0d 100644 --- a/x/gov/proposals.go +++ b/x/gov/proposals.go @@ -141,6 +141,23 @@ func (pp *ParameterProposal) Execute(ctx sdk.Context, k Keeper) (err error) { return } +var _ Proposal = (*SoftwareUpgradeProposal)(nil) +type SoftwareUpgradeProposal struct { + TextProposal +} +func (sp *SoftwareUpgradeProposal) Execute(ctx sdk.Context, k Keeper) error { + logger := ctx.Logger().With("module", "x/gov") + logger.Info("Execute SoftwareProposal begin","info", fmt.Sprintf("current height:%d",ctx.BlockHeight())) + err := k.ps.Set(ctx,"upgrade/proposalId",sp.ProposalID) + if err != nil{ + return err + } + k.ps.Set(ctx,"upgrade/proposalAcceptHeight",ctx.BlockHeight()) + if err != nil{ + return err + } + return nil +} //func convert(srcData string,ptrty reflect.Type,codec *wire.Codec) ( v interface{}){ // if ptrty.Kind() == reflect.Ptr { // ptrty = ptrty.Elem() diff --git a/x/gov/wire.go b/x/gov/wire.go index 65ebad870fcc..ee3a5bbb34d9 100644 --- a/x/gov/wire.go +++ b/x/gov/wire.go @@ -18,6 +18,7 @@ func RegisterWire(cdc *wire.Codec) { cdc.RegisterInterface((*Proposal)(nil), nil) cdc.RegisterConcrete(&TextProposal{}, "gov/TextProposal", nil) cdc.RegisterConcrete(&ParameterProposal{}, "gov/ParameterProposal", nil) + cdc.RegisterConcrete(&SoftwareUpgradeProposal{}, "gov/SoftwareUpgradeProposal", nil) } var msgCdc = wire.NewCodec() From 18d2c5b00fb087b33aff1213de577021b22af9e9 Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Thu, 9 Aug 2018 16:20:48 +0800 Subject: [PATCH 43/52] add SoftwareUpgradeProposal --- x/gov/genesis.go | 17 +++++++++++++++++ x/gov/keeper.go | 28 +++++++++++++++++++++++++--- x/gov/proposals.go | 17 +++++++++++++++++ x/gov/wire.go | 1 + 4 files changed, 60 insertions(+), 3 deletions(-) diff --git a/x/gov/genesis.go b/x/gov/genesis.go index 78d1772c7188..d170edb6ce2f 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -39,6 +39,23 @@ func DefaultGenesisState() GenesisState { }, } } +func DefaultIrisGenesisState() GenesisState { + return GenesisState{ + StartingProposalID: 1, + DepositProcedure: DepositProcedure{ + MinDeposit: sdk.Coins{sdk.Coin{Denom:"iris", Amount: sdk.NewInt(int64(10)).Mul(Pow10(18))}}, + MaxDepositPeriod: 10, + }, + VotingProcedure: VotingProcedure{ + VotingPeriod: 10, + }, + TallyingProcedure: TallyingProcedure{ + Threshold: sdk.NewRat(1, 2), + Veto: sdk.NewRat(1, 3), + GovernancePenalty: sdk.NewRat(1, 100), + }, + } +} // InitGenesis - store genesis parameters func InitGenesis(ctx sdk.Context, k Keeper, data GenesisState) { diff --git a/x/gov/keeper.go b/x/gov/keeper.go index b48bf2519461..9289238803bd 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -2,10 +2,9 @@ package gov import ( sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/params" - "fmt" ) // Governance Keeper @@ -98,6 +97,29 @@ func (keeper Keeper) NewParametersProposal(ctx sdk.Context, title string, descri return proposal } +func (keeper Keeper) NewSofterwareUpgradeProposal(ctx sdk.Context, title string, description string, proposalType ProposalKind) Proposal{ + proposalID, err := keeper.getNewProposalID(ctx) + if err != nil { + return nil + } + var textProposal = TextProposal{ + ProposalID: proposalID, + Title: title, + Description: description, + ProposalType: proposalType, + Status: StatusDepositPeriod, + TotalDeposit: sdk.Coins{}, + SubmitBlock: ctx.BlockHeight(), + VotingStartBlock: -1, // TODO: Make Time + } + var proposal Proposal = &SoftwareUpgradeProposal{ + textProposal, + } + keeper.SetProposal(ctx, proposal) + keeper.InactiveProposalQueuePush(ctx, proposal) + return proposal +} + func (keeper Keeper) NewProposal(ctx sdk.Context, title string, description string, proposalType ProposalKind,params Params) Proposal{ switch proposalType { case ProposalTypeText: @@ -105,7 +127,7 @@ func (keeper Keeper) NewProposal(ctx sdk.Context, title string, description stri case ProposalTypeParameterChange: return keeper.NewParametersProposal(ctx, title, description, proposalType,params) case ProposalTypeSoftwareUpgrade: - fmt.Println("not implement") + return keeper.NewSofterwareUpgradeProposal(ctx, title, description, proposalType) } return nil } diff --git a/x/gov/proposals.go b/x/gov/proposals.go index eb7507d8fa44..684950bece0d 100644 --- a/x/gov/proposals.go +++ b/x/gov/proposals.go @@ -141,6 +141,23 @@ func (pp *ParameterProposal) Execute(ctx sdk.Context, k Keeper) (err error) { return } +var _ Proposal = (*SoftwareUpgradeProposal)(nil) +type SoftwareUpgradeProposal struct { + TextProposal +} +func (sp *SoftwareUpgradeProposal) Execute(ctx sdk.Context, k Keeper) error { + logger := ctx.Logger().With("module", "x/gov") + logger.Info("Execute SoftwareProposal begin","info", fmt.Sprintf("current height:%d",ctx.BlockHeight())) + err := k.ps.Set(ctx,"upgrade/proposalId",sp.ProposalID) + if err != nil{ + return err + } + k.ps.Set(ctx,"upgrade/proposalAcceptHeight",ctx.BlockHeight()) + if err != nil{ + return err + } + return nil +} //func convert(srcData string,ptrty reflect.Type,codec *wire.Codec) ( v interface{}){ // if ptrty.Kind() == reflect.Ptr { // ptrty = ptrty.Elem() diff --git a/x/gov/wire.go b/x/gov/wire.go index 65ebad870fcc..ee3a5bbb34d9 100644 --- a/x/gov/wire.go +++ b/x/gov/wire.go @@ -18,6 +18,7 @@ func RegisterWire(cdc *wire.Codec) { cdc.RegisterInterface((*Proposal)(nil), nil) cdc.RegisterConcrete(&TextProposal{}, "gov/TextProposal", nil) cdc.RegisterConcrete(&ParameterProposal{}, "gov/ParameterProposal", nil) + cdc.RegisterConcrete(&SoftwareUpgradeProposal{}, "gov/SoftwareUpgradeProposal", nil) } var msgCdc = wire.NewCodec() From f54976ff0355adaa44ac99724cf43d71c2cf7954 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Fri, 10 Aug 2018 09:33:13 +0800 Subject: [PATCH 44/52] 1:optimization code 2:param module export command update --- cmd/gaia/app/app.go | 2 -- cmd/gaia/app/genesis.go | 4 --- cmd/gaia/cmd/gaiacli/main.go | 2 +- x/gov/genesis.go | 34 +----------------- x/gov/keeper.go | 5 ++- x/gov/params.go | 26 ++++++++------ x/gov/proposals.go | 67 +++++++++++------------------------- x/gov/test_common.go | 2 +- x/params/client/cli/util.go | 36 +++++++++++++------ 9 files changed, 65 insertions(+), 113 deletions(-) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 439514ff09c2..3e9790ef6a6a 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -184,8 +184,6 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci gov.InitGenesis(ctx, app.govKeeper, gov.DefaultGenesisState()) - params.InitParamGenesis(ctx, app.paramsKeeper, genesisState.ParamsData) - auth.InitGenesis(ctx,app.paramsKeeper.Setter(),auth.DefaultGenesisState()) return abci.ResponseInitChain{} diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index aeb3c324ae1d..4be9f74d1b60 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -15,7 +15,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/stake" "math" - "github.com/cosmos/cosmos-sdk/x/params" ) var ( @@ -28,7 +27,6 @@ var ( type GenesisState struct { Accounts []GenesisAccount `json:"accounts"` StakeData stake.GenesisState `json:"stake"` - ParamsData params.ParamGenesisState `json:"params"` } // GenesisAccount doesn't need pubkey or sequence @@ -197,12 +195,10 @@ func GaiaAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState } } - paramsData := params.DefaultGenesisState() // create the final app state genesisState = GenesisState{ Accounts: genaccs, StakeData: stakeData, - ParamsData: paramsData, } return } diff --git a/cmd/gaia/cmd/gaiacli/main.go b/cmd/gaia/cmd/gaiacli/main.go index a7d74c07a377..93d34c6f6fed 100644 --- a/cmd/gaia/cmd/gaiacli/main.go +++ b/cmd/gaia/cmd/gaiacli/main.go @@ -148,7 +148,7 @@ func main() { paramsCmd.AddCommand( client.GetCommands( - paramscli.QueryParam("params",cdc), + paramscli.ExportCmd("params",cdc), )...) rootCmd.AddCommand(paramsCmd) diff --git a/x/gov/genesis.go b/x/gov/genesis.go index d170edb6ce2f..39ebca90cd64 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -26,24 +26,7 @@ func DefaultGenesisState() GenesisState { return GenesisState{ StartingProposalID: 1, DepositProcedure: DepositProcedure{ - MinDeposit: sdk.Coins{sdk.Coin{Denom:"steak", Amount: sdk.NewInt(int64(10)).Mul(Pow10(18))}}, - MaxDepositPeriod: 10, - }, - VotingProcedure: VotingProcedure{ - VotingPeriod: 10, - }, - TallyingProcedure: TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 100), - }, - } -} -func DefaultIrisGenesisState() GenesisState { - return GenesisState{ - StartingProposalID: 1, - DepositProcedure: DepositProcedure{ - MinDeposit: sdk.Coins{sdk.Coin{Denom:"iris", Amount: sdk.NewInt(int64(10)).Mul(Pow10(18))}}, + MinDeposit: sdk.Coins{sdk.Coin{Denom: "steak", Amount: sdk.NewInt(int64(10)).Mul(Pow10(18))}}, MaxDepositPeriod: 10, }, VotingProcedure: VotingProcedure{ @@ -75,21 +58,6 @@ func InitGenesis(ctx sdk.Context, k Keeper, data GenesisState) { k.setTallyingProcedure(ctx, ParamStoreKeyTallyingProcedurePenalty, data.TallyingProcedure.GovernancePenalty) } -// WriteGenesis - output genesis parameters -func WriteGenesis(ctx sdk.Context, k Keeper) GenesisState { - startingProposalID, _ := k.getNewProposalID(ctx) - depositProcedure := k.GetDepositProcedure(ctx) - votingProcedure := k.GetVotingProcedure(ctx) - tallyingProcedure := k.GetTallyingProcedure(ctx) - - return GenesisState{ - StartingProposalID: startingProposalID, - DepositProcedure: depositProcedure, - VotingProcedure: votingProcedure, - TallyingProcedure: tallyingProcedure, - } -} - func Pow10(y int) sdk.Int { result := sdk.NewInt(1) x := sdk.NewInt(10) diff --git a/x/gov/keeper.go b/x/gov/keeper.go index 04e5606fe5c9..9289238803bd 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -2,10 +2,9 @@ package gov import ( sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/params" - "fmt" ) // Governance Keeper @@ -128,7 +127,7 @@ func (keeper Keeper) NewProposal(ctx sdk.Context, title string, description stri case ProposalTypeParameterChange: return keeper.NewParametersProposal(ctx, title, description, proposalType,params) case ProposalTypeSoftwareUpgrade: - fmt.Println("not implement") + return keeper.NewSofterwareUpgradeProposal(ctx, title, description, proposalType) } return nil } diff --git a/x/gov/params.go b/x/gov/params.go index 52bdfc5bda0c..aad238a88d70 100644 --- a/x/gov/params.go +++ b/x/gov/params.go @@ -1,23 +1,27 @@ package gov import ( + "fmt" sdk "github.com/cosmos/cosmos-sdk/types" "strconv" "strings" ) -// nolint -const ( - ParamStoreKeyDepositProcedureDeposit = "gov/depositprocedure/deposit" - ParamStoreKeyDepositProcedureMaxDepositPeriod = "gov/depositprocedure/maxDepositPeriod" +const Prefix = "gov/" - ParamStoreKeyVotingProcedureVotingPeriod = "gov/votingprocedure/votingPeriod" - - ParamStoreKeyTallyingProcedureThreshold = "gov/tallyingprocedure/threshold" - ParamStoreKeyTallyingProcedureVeto = "gov/tallyingprocedure/veto" - ParamStoreKeyTallyingProcedurePenalty = "gov/tallyingprocedure/penalty" +var ( + ParamStoreKeyDepositProcedureDeposit = GetGovKey("depositprocedure/deposit") + ParamStoreKeyDepositProcedureMaxDepositPeriod = GetGovKey("depositprocedure/maxDepositPeriod") + ParamStoreKeyVotingProcedureVotingPeriod = GetGovKey("votingprocedure/votingPeriod") + ParamStoreKeyTallyingProcedureThreshold = GetGovKey("tallyingprocedure/threshold") + ParamStoreKeyTallyingProcedureVeto = GetGovKey("tallyingprocedure/veto") + ParamStoreKeyTallyingProcedurePenalty = GetGovKey("tallyingprocedure/penalty") ) +func GetGovKey(key string) string { + return fmt.Sprintf("%s%s", Prefix, key) +} + // ===================================================== // Procedures @@ -51,12 +55,12 @@ func (keeper Keeper) setDepositProcedureDeposit(ctx sdk.Context, Deposit sdk.Coi } func (keeper Keeper) setDepositProcedureMaxDepositPeriod(ctx sdk.Context, MaxDepositPeriod int64) { - maxDepositPeriod := strconv.FormatInt(MaxDepositPeriod,10) + maxDepositPeriod := strconv.FormatInt(MaxDepositPeriod, 10) keeper.ps.Set(ctx, ParamStoreKeyDepositProcedureMaxDepositPeriod, &maxDepositPeriod) } func (keeper Keeper) setVotingProcedureVotingPeriod(ctx sdk.Context, VotingPeriod int64) { - votingPeriod := strconv.FormatInt(VotingPeriod,10) + votingPeriod := strconv.FormatInt(VotingPeriod, 10) keeper.ps.Set(ctx, ParamStoreKeyVotingProcedureVotingPeriod, &votingPeriod) } diff --git a/x/gov/proposals.go b/x/gov/proposals.go index 684950bece0d..b890a0d8befe 100644 --- a/x/gov/proposals.go +++ b/x/gov/proposals.go @@ -7,6 +7,7 @@ import ( "github.com/pkg/errors" sdk "github.com/cosmos/cosmos-sdk/types" + "strings" ) //----------------------------------------------------------- @@ -99,32 +100,37 @@ type Op string const ( Add Op = "add" - Del Op = "del" Update Op = "update" ) -type Data struct { +type Param struct { Key string `json:"key"` Value string `json:"value"` Op Op `json:"op"` } -type Params []Data +type Params []Param // Implements Proposal Interface var _ Proposal = (*ParameterProposal)(nil) type ParameterProposal struct { TextProposal - Datas Params `json:"datas"` + Params Params `json:"params"` } func (pp *ParameterProposal) Execute(ctx sdk.Context, k Keeper) (err error) { logger := ctx.Logger().With("module", "x/gov") - logger.Info("Execute ParameterProposal begin","info", fmt.Sprintf("current height:%d",ctx.BlockHeight())) - - for _, data := range pp.Datas { + logger.Info("Execute ParameterProposal begin", "info", fmt.Sprintf("current height:%d", ctx.BlockHeight())) + + for _, data := range pp.Params { + //param only begin with "gov/" can be update + if !strings.HasPrefix(data.Key, Prefix) { + errMsg := fmt.Sprintf("Parameter %s is not begin with %s", data.Key, Prefix) + logger.Error("Execute ParameterProposal ", "err", errMsg) + continue + } if data.Op == Add { k.ps.Set(ctx, data.Key, data.Value) } else if data.Op == Update { @@ -134,63 +140,30 @@ func (pp *ParameterProposal) Execute(ctx sdk.Context, k Keeper) (err error) { } else { k.ps.SetString(ctx, data.Key, data.Value) } - } else { - } } return } var _ Proposal = (*SoftwareUpgradeProposal)(nil) + type SoftwareUpgradeProposal struct { TextProposal } + func (sp *SoftwareUpgradeProposal) Execute(ctx sdk.Context, k Keeper) error { logger := ctx.Logger().With("module", "x/gov") - logger.Info("Execute SoftwareProposal begin","info", fmt.Sprintf("current height:%d",ctx.BlockHeight())) - err := k.ps.Set(ctx,"upgrade/proposalId",sp.ProposalID) - if err != nil{ + logger.Info("Execute SoftwareProposal begin", "info", fmt.Sprintf("current height:%d", ctx.BlockHeight())) + err := k.ps.Set(ctx, "upgrade/proposalId", sp.ProposalID) + if err != nil { return err } - k.ps.Set(ctx,"upgrade/proposalAcceptHeight",ctx.BlockHeight()) - if err != nil{ + k.ps.Set(ctx, "upgrade/proposalAcceptHeight", ctx.BlockHeight()) + if err != nil { return err } return nil } -//func convert(srcData string,ptrty reflect.Type,codec *wire.Codec) ( v interface{}){ -// if ptrty.Kind() == reflect.Ptr { -// ptrty = ptrty.Elem() -// } -// -// srcValue := reflect.ValueOf(srcData) -// srcType := reflect.TypeOf(srcData) -// if srcType.ConvertibleTo(ptrty){ -// v = srcValue.Convert(ptrty).Interface() -// }else { -// switch ptrty.Kind() { -// case reflect.Int: -// v,_ = strconv.Atoi(srcData) -// case reflect.Int8: -// v,_ = strconv.ParseInt(srcData, 10, 8) -// case reflect.Int16: -// v,_ = strconv.ParseInt(srcData, 10, 16) -// case reflect.Int64: -// v,_ = strconv.ParseInt(srcData, 10, 64) -// case reflect.Bool: -// v,_ = strconv.ParseBool(srcData) -// case reflect.Uint: -// v,_ = strconv.ParseUint(srcData, 10, 10) -// case reflect.Uint8: -// v,_ = strconv.ParseUint(srcData, 10, 8) -// case reflect.Uint64: -// v,_ = strconv.ParseUint(srcData, 10, 64) -// case reflect.Uint16: -// v,_ = strconv.ParseUint(srcData, 10, 16) -// } -// } -// return -//} //////////////////// iris/cosmos-sdk end /////////////////////////// diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 7e227cf299bd..70c9c050a9a1 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -20,7 +20,7 @@ import ( ) func toBigInt(amount int) sdk.Int{ - return params.Pow10(18).Mul(sdk.NewInt(int64(amount))) + return Pow10(18).Mul(sdk.NewInt(int64(amount))) } // initialize the mock application for this module diff --git a/x/params/client/cli/util.go b/x/params/client/cli/util.go index 1c69487061a1..67a60a5c34a1 100644 --- a/x/params/client/cli/util.go +++ b/x/params/client/cli/util.go @@ -1,32 +1,46 @@ package cli import ( + "fmt" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/wire" "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" - "fmt" - ) -// create edit validator command -func QueryParam(storeName string, cdc *wire.Codec) *cobra.Command { +func ExportCmd(storeName string, cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "query", - Short: "query param value from global store", + Use: "export", + Short: "export all keypair which begin with args from global store.(args can be 'gov','stake' eg,or full path such as 'gov/votingprocedure/votingPeriod')", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := context.NewCoreContextFromViper() - res, err := ctx.QueryStore([]byte(args[0]), storeName) + res, err := ctx.QuerySubspace(cdc, []byte(args[0]), storeName) if err != nil { fmt.Println(err.Error()) return nil } - var result string - if cdc.UnmarshalBinary(res, &result) == nil { - fmt.Println(result) + var result []KVPair + for _, pair := range res { + var v string + cdc.UnmarshalBinary(pair.Value, &v) + kv := KVPair{ + K: string(pair.Key), + V: v, + } + result = append(result, kv) } + output, err := wire.MarshalJSONIndent(cdc, result) + if err != nil { + return err + } + fmt.Println(string(output)) return nil }, } return cmd } + +type KVPair struct { + K string `json:"key"` + V string `json:"value"` +} From 4d6a0cc6aba5890e4eacf02b23008e0d62a457a2 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Fri, 10 Aug 2018 09:49:18 +0800 Subject: [PATCH 45/52] 1:optimization code 2:param module export command update --- x/params/client/cli/util.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/x/params/client/cli/util.go b/x/params/client/cli/util.go index 67a60a5c34a1..7091b54ae379 100644 --- a/x/params/client/cli/util.go +++ b/x/params/client/cli/util.go @@ -9,8 +9,8 @@ import ( func ExportCmd(storeName string, cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "export", - Short: "export all keypair which begin with args from global store.(args can be 'gov','stake' eg,or full path such as 'gov/votingprocedure/votingPeriod')", + Use: "export [key]", + Short: "export all keypair which begin with key from global store.(key can be 'gov','stake' eg,or full path such as 'gov/votingprocedure/votingPeriod')", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := context.NewCoreContextFromViper() From 7511d05ad8b5ec92bfca93dff5fd1b8fc8548dd4 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Fri, 10 Aug 2018 14:56:37 +0800 Subject: [PATCH 46/52] 1:optimization code 2:global store's setter and getter add proxy(build key) --- x/auth/feekeeper.go | 10 +- x/gov/keeper.go | 4 +- x/gov/proposals_test.go | 2 +- x/params/client/cli/util.go | 2 +- x/params/keeper.go | 9 -- x/params/proxy.go | 259 ++++++++++++++++++++++++++++++++++++ 6 files changed, 268 insertions(+), 18 deletions(-) create mode 100644 x/params/proxy.go diff --git a/x/auth/feekeeper.go b/x/auth/feekeeper.go index 7283056c73d0..c01bd3edd61a 100644 --- a/x/auth/feekeeper.go +++ b/x/auth/feekeeper.go @@ -11,8 +11,8 @@ import ( var ( collectedFeesKey = []byte("collectedFees") NativeFeeTokenKey = "feeToken/native" - NativeGasPriceThresholdKey = "feeToken/native/gasPrice/threshold" - FeeExchangeRatePrefix = "feeToken/derived/exchange/rate/" // key = feeToken/derived/exchange/rate/, rate = BigInt(value)/10^18 + NativeGasPriceThresholdKey = "gov/feeToken/gasPriceThreshold" + FeeExchangeRatePrefix = "gov/feeToken/exchangeRate/" // key = gov/feeToken/exchangeRate/, rate = BigInt(value)/10^9 RatePrecision = int64(1000000000) //10^9 ) @@ -20,7 +20,7 @@ var ( // and setting of MinFees for different fee tokens type FeeCollectionKeeper struct { - getter params.Getter + getter params.GetterProxy // The (unexposed) key used to access the fee store from the Context. key sdk.StoreKey @@ -30,7 +30,7 @@ type FeeCollectionKeeper struct { } // NewFeeKeeper returns a new FeeKeeper -func NewFeeCollectionKeeper(cdc *wire.Codec, key sdk.StoreKey, getter params.Getter) FeeCollectionKeeper { +func NewFeeCollectionKeeper(cdc *wire.Codec, key sdk.StoreKey, getter params.GetterProxy) FeeCollectionKeeper { return FeeCollectionKeeper{ key: key, cdc: cdc, @@ -155,7 +155,7 @@ func DefaultGenesisState() GenesisState { } } -func InitGenesis(ctx sdk.Context, setter params.Setter, data GenesisState) { +func InitGenesis(ctx sdk.Context, setter params.SetterProxy, data GenesisState) { setter.SetString(ctx, NativeFeeTokenKey, data.FeeTokenNative) setter.SetString(ctx, NativeGasPriceThresholdKey, sdk.NewInt(data.GasPriceThreshold).String()) } \ No newline at end of file diff --git a/x/gov/keeper.go b/x/gov/keeper.go index 9289238803bd..05b498f683ce 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -10,7 +10,7 @@ import ( // Governance Keeper type Keeper struct { // The reference to the ParamSetter to get and set Global Params - ps params.Setter + ps params.SetterProxy // The reference to the CoinKeeper to modify balances ck bank.Keeper @@ -32,7 +32,7 @@ type Keeper struct { } // NewGovernanceMapper returns a mapper that uses go-wire to (binary) encode and decode gov types. -func NewKeeper(cdc *wire.Codec, key sdk.StoreKey, ps params.Setter, ck bank.Keeper, ds sdk.DelegationSet, codespace sdk.CodespaceType) Keeper { +func NewKeeper(cdc *wire.Codec, key sdk.StoreKey, ps params.SetterProxy, ck bank.Keeper, ds sdk.DelegationSet, codespace sdk.CodespaceType) Keeper { return Keeper{ storeKey: key, ps: ps, diff --git a/x/gov/proposals_test.go b/x/gov/proposals_test.go index 379b21d93650..9175fd91430f 100644 --- a/x/gov/proposals_test.go +++ b/x/gov/proposals_test.go @@ -19,7 +19,7 @@ func TestParameterProposal(t *testing.T) { fmt.Println(keeper.GetVotingProcedure(ctx)) pp := ParameterProposal{ - Datas: []Data{ + Params: []Param{ {Key: ParamStoreKeyDepositProcedureDeposit, Value: "200iris", Op: Update}, {Key: ParamStoreKeyDepositProcedureMaxDepositPeriod, Value: "20", Op: Update}, {Key: ParamStoreKeyTallyingProcedurePenalty, Value: "1/50", Op: Update}, diff --git a/x/params/client/cli/util.go b/x/params/client/cli/util.go index 7091b54ae379..e51f3efaae4d 100644 --- a/x/params/client/cli/util.go +++ b/x/params/client/cli/util.go @@ -10,7 +10,7 @@ import ( func ExportCmd(storeName string, cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "export [key]", - Short: "export all keypair which begin with key from global store.(key can be 'gov','stake' eg,or full path such as 'gov/votingprocedure/votingPeriod')", + Short: "export all keypair which begin with key from global store.(key can be 'gov','global',or full path such as 'gov/votingprocedure/votingPeriod')", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := context.NewCoreContextFromViper() diff --git a/x/params/keeper.go b/x/params/keeper.go index c63d3ed9bec8..52b5fc3ab3db 100644 --- a/x/params/keeper.go +++ b/x/params/keeper.go @@ -77,15 +77,6 @@ func (k Keeper) setRaw(ctx sdk.Context, key string, param []byte) { store.Set([]byte(key), param) } -// Getter returns readonly struct -func (k Keeper) Getter() Getter { - return Getter{k} -} - -// Setter returns read/write struct -func (k Keeper) Setter() Setter { - return Setter{Getter{k}} -} // Getter exposes methods related with only getting params type Getter struct { diff --git a/x/params/proxy.go b/x/params/proxy.go new file mode 100644 index 000000000000..68c5f72b587f --- /dev/null +++ b/x/params/proxy.go @@ -0,0 +1,259 @@ +package params + +import ( + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" + "strings" +) + +const ( + Gov = "gov" + Global = "global" +) + +// Getter returns readonly struct +func (k Keeper) Getter() GetterProxy { + return GetterProxy{Getter{k}} +} + +// Setter returns read/write struct +func (k Keeper) Setter() SetterProxy { + return SetterProxy{k.Getter(), Setter{Getter{k}}} +} + +type GetterProxy struct { + getter Getter +} + +func getStoreKey(key string) string { + if strings.HasPrefix(key, Gov+"/") || strings.HasPrefix(key, Global+"/") { + return key + } + return fmt.Sprintf("%s/%s", Global, key) +} + +func (proxy GetterProxy) Get(ctx sdk.Context, key string, res interface{}) (err error) { + paramKey := getStoreKey(key) + return proxy.getter.Get(ctx, paramKey, res) +} + +// GetRaw exposes getRaw +func (proxy GetterProxy) GetRaw(ctx sdk.Context, key string) []byte { + paramKey := getStoreKey(key) + return proxy.getter.GetRaw(ctx, paramKey) +} + +// GetString is helper function for string params +func (proxy GetterProxy) GetString(ctx sdk.Context, key string) (res string, err error) { + paramKey := getStoreKey(key) + return proxy.getter.GetString(ctx, paramKey) +} + +// GetBool is helper function for bool params +func (proxy GetterProxy) GetBool(ctx sdk.Context, key string) (res bool, err error) { + paramKey := getStoreKey(key) + return proxy.getter.GetBool(ctx, paramKey) +} + +// GetInt16 is helper function for int16 params +func (proxy GetterProxy) GetInt16(ctx sdk.Context, key string) (res int16, err error) { + paramKey := getStoreKey(key) + return proxy.getter.GetInt16(ctx, paramKey) +} + +// GetInt32 is helper function for int32 params +func (proxy GetterProxy) GetInt32(ctx sdk.Context, key string) (res int32, err error) { + paramKey := getStoreKey(key) + return proxy.getter.GetInt32(ctx, paramKey) +} + +// GetInt64 is helper function for int64 params +func (proxy GetterProxy) GetInt64(ctx sdk.Context, key string) (res int64, err error) { + paramKey := getStoreKey(key) + return proxy.getter.GetInt64(ctx, paramKey) +} + +// GetUint16 is helper function for uint16 params +func (proxy GetterProxy) GetUint16(ctx sdk.Context, key string) (res uint16, err error) { + paramKey := getStoreKey(key) + return proxy.getter.GetUint16(ctx, paramKey) +} + +// GetUint32 is helper function for uint32 params +func (proxy GetterProxy) GetUint32(ctx sdk.Context, key string) (res uint32, err error) { + paramKey := getStoreKey(key) + return proxy.getter.GetUint32(ctx, paramKey) +} + +// GetUint64 is helper function for uint64 params +func (proxy GetterProxy) GetUint64(ctx sdk.Context, key string) (res uint64, err error) { + paramKey := getStoreKey(key) + return proxy.getter.GetUint64(ctx, paramKey) +} + +// GetInt is helper function for sdk.Int params +func (proxy GetterProxy) GetInt(ctx sdk.Context, key string) (res sdk.Int, err error) { + paramKey := getStoreKey(key) + return proxy.getter.GetInt(ctx, paramKey) +} + +// GetUint is helper function for sdk.Uint params +func (proxy GetterProxy) GetUint(ctx sdk.Context, key string) (res sdk.Uint, err error) { + paramKey := getStoreKey(key) + return proxy.getter.GetUint(ctx, paramKey) +} + +// GetRat is helper function for rat params +func (proxy GetterProxy) GetRat(ctx sdk.Context, key string) (res sdk.Rat, err error) { + paramKey := getStoreKey(key) + return proxy.getter.GetRat(ctx, paramKey) +} + +// GetStringWithDefault is helper function for string params with default value +func (proxy GetterProxy) GetStringWithDefault(ctx sdk.Context, key string, def string) (res string) { + paramKey := getStoreKey(key) + return proxy.getter.GetStringWithDefault(ctx, paramKey, def) +} + +// GetBoolWithDefault is helper function for bool params with default value +func (proxy GetterProxy) GetBoolWithDefault(ctx sdk.Context, key string, def bool) (res bool) { + paramKey := getStoreKey(key) + return proxy.getter.GetBoolWithDefault(ctx, paramKey, def) +} + +// GetInt16WithDefault is helper function for int16 params with default value +func (proxy GetterProxy) GetInt16WithDefault(ctx sdk.Context, key string, def int16) (res int16) { + paramKey := getStoreKey(key) + return proxy.getter.GetInt16WithDefault(ctx, paramKey, def) +} + +// GetInt32WithDefault is helper function for int32 params with default value +func (proxy GetterProxy) GetInt32WithDefault(ctx sdk.Context, key string, def int32) (res int32) { + paramKey := getStoreKey(key) + return proxy.getter.GetInt32WithDefault(ctx, paramKey, def) +} + +// GetInt64WithDefault is helper function for int64 params with default value +func (proxy GetterProxy) GetInt64WithDefault(ctx sdk.Context, key string, def int64) (res int64) { + paramKey := getStoreKey(key) + return proxy.getter.GetInt64WithDefault(ctx, paramKey, def) +} + +// GetUint16WithDefault is helper function for uint16 params with default value +func (proxy GetterProxy) GetUint16WithDefault(ctx sdk.Context, key string, def uint16) (res uint16) { + paramKey := getStoreKey(key) + return proxy.getter.GetUint16WithDefault(ctx, paramKey, def) +} + +// GetUint32WithDefault is helper function for uint32 params with default value +func (proxy GetterProxy) GetUint32WithDefault(ctx sdk.Context, key string, def uint32) (res uint32) { + paramKey := getStoreKey(key) + return proxy.getter.GetUint32WithDefault(ctx, paramKey, def) +} + +// GetUint64WithDefault is helper function for uint64 params with default value +func (proxy GetterProxy) GetUint64WithDefault(ctx sdk.Context, key string, def uint64) (res uint64) { + paramKey := getStoreKey(key) + return proxy.getter.GetUint64WithDefault(ctx, paramKey, def) +} + +// GetIntWithDefault is helper function for sdk.Int params with default value +func (proxy GetterProxy) GetIntWithDefault(ctx sdk.Context, key string, def sdk.Int) (res sdk.Int) { + paramKey := getStoreKey(key) + return proxy.getter.GetIntWithDefault(ctx, paramKey, def) +} + +// GetUintWithDefault is helper function for sdk.Uint params with default value +func (proxy GetterProxy) GetUintWithDefault(ctx sdk.Context, key string, def sdk.Uint) (res sdk.Uint) { + paramKey := getStoreKey(key) + return proxy.getter.GetUintWithDefault(ctx, paramKey, def) +} + +// GetRatWithDefault is helper function for sdk.Rat params with default value +func (proxy GetterProxy) GetRatWithDefault(ctx sdk.Context, key string, def sdk.Rat) (res sdk.Rat) { + paramKey := getStoreKey(key) + return proxy.getter.GetRatWithDefault(ctx, paramKey, def) +} + +type SetterProxy struct { + GetterProxy + Setter +} + +// Set exposes set +func (proxy SetterProxy) Set(ctx sdk.Context, key string, param interface{}) error { + paramKey := getStoreKey(key) + return proxy.Setter.Set(ctx, paramKey, param) +} + +// SetRaw exposes setRaw +func (proxy SetterProxy) SetRaw(ctx sdk.Context, key string, param []byte) { + paramKey := getStoreKey(key) + proxy.Setter.SetRaw(ctx, paramKey, param) +} + +// SetString is helper function for string params +func (proxy SetterProxy) SetString(ctx sdk.Context, key string, param string) { + paramKey := getStoreKey(key) + proxy.Setter.SetString(ctx, paramKey, param) +} + +// SetBool is helper function for bool params +func (proxy SetterProxy) SetBool(ctx sdk.Context, key string, param bool) { + paramKey := getStoreKey(key) + proxy.Setter.SetBool(ctx, paramKey, param) +} + +// SetInt16 is helper function for int16 params +func (proxy SetterProxy) SetInt16(ctx sdk.Context, key string, param int16) { + paramKey := getStoreKey(key) + proxy.Setter.SetInt16(ctx, paramKey, param) +} + +// SetInt32 is helper function for int32 params +func (proxy SetterProxy) SetInt32(ctx sdk.Context, key string, param int32) { + paramKey := getStoreKey(key) + proxy.Setter.SetInt32(ctx, paramKey, param) +} + +// SetInt64 is helper function for int64 params +func (proxy SetterProxy) SetInt64(ctx sdk.Context, key string, param int64) { + paramKey := getStoreKey(key) + proxy.Setter.SetInt64(ctx, paramKey, param) +} + +// SetUint16 is helper function for uint16 params +func (proxy SetterProxy) SetUint16(ctx sdk.Context, key string, param uint16) { + paramKey := getStoreKey(key) + proxy.Setter.SetUint16(ctx, paramKey, param) +} + +// SetUint32 is helper function for uint32 params +func (proxy SetterProxy) SetUint32(ctx sdk.Context, key string, param uint32) { + paramKey := getStoreKey(key) + proxy.Setter.SetUint32(ctx, paramKey, param) +} + +// SetUint64 is helper function for uint64 params +func (proxy SetterProxy) SetUint64(ctx sdk.Context, key string, param uint64) { + paramKey := getStoreKey(key) + proxy.Setter.SetUint64(ctx, paramKey, param) +} + +// SetInt is helper function for sdk.Int params +func (proxy SetterProxy) SetInt(ctx sdk.Context, key string, param sdk.Int) { + paramKey := getStoreKey(key) + proxy.Setter.SetInt(ctx, paramKey, param) +} + +// SetUint is helper function for sdk.Uint params +func (proxy SetterProxy) SetUint(ctx sdk.Context, key string, param sdk.Uint) { + paramKey := getStoreKey(key) + proxy.Setter.SetUint(ctx, paramKey, param) +} + +// SetRat is helper function for rat params +func (proxy SetterProxy) SetRat(ctx sdk.Context, key string, param sdk.Rat) { + paramKey := getStoreKey(key) + proxy.Setter.SetRat(ctx, paramKey, param) +} From 92a14d9807623a36b20a837df595675894bc0c16 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Sat, 11 Aug 2018 14:22:23 +0800 Subject: [PATCH 47/52] 1:optimization code 2:global store's setter and getter add proxy(build key) --- x/auth/feekeeper.go | 8 +-- x/gov/params.go | 35 +++++----- x/gov/proposals.go | 6 +- x/params/keeper_test.go | 22 +++++++ x/params/proxy.go | 139 ++++++++++++++++++++++------------------ 5 files changed, 122 insertions(+), 88 deletions(-) diff --git a/x/auth/feekeeper.go b/x/auth/feekeeper.go index c01bd3edd61a..773c9a045a16 100644 --- a/x/auth/feekeeper.go +++ b/x/auth/feekeeper.go @@ -11,8 +11,8 @@ import ( var ( collectedFeesKey = []byte("collectedFees") NativeFeeTokenKey = "feeToken/native" - NativeGasPriceThresholdKey = "gov/feeToken/gasPriceThreshold" - FeeExchangeRatePrefix = "gov/feeToken/exchangeRate/" // key = gov/feeToken/exchangeRate/, rate = BigInt(value)/10^9 + NativeGasPriceThresholdKey = "feeToken/gasPriceThreshold" + FeeExchangeRatePrefix = "feeToken/exchangeRate/" // key = gov/feeToken/exchangeRate/, rate = BigInt(value)/10^9 RatePrecision = int64(1000000000) //10^9 ) @@ -102,7 +102,7 @@ func (fck FeeCollectionKeeper) FeePreprocess(ctx sdk.Context, coins sdk.Coins, g if err != nil { panic(err) } - nativeGasPriceThreshold, err := fck.getter.GetString(ctx, NativeGasPriceThresholdKey) + nativeGasPriceThreshold, err := fck.getter.GovGetter().GetString(ctx, NativeGasPriceThresholdKey) if err != nil { panic(err) } @@ -157,5 +157,5 @@ func DefaultGenesisState() GenesisState { func InitGenesis(ctx sdk.Context, setter params.SetterProxy, data GenesisState) { setter.SetString(ctx, NativeFeeTokenKey, data.FeeTokenNative) - setter.SetString(ctx, NativeGasPriceThresholdKey, sdk.NewInt(data.GasPriceThreshold).String()) + setter.GovSetter().SetString(ctx, NativeGasPriceThresholdKey, sdk.NewInt(data.GasPriceThreshold).String()) } \ No newline at end of file diff --git a/x/gov/params.go b/x/gov/params.go index aad238a88d70..74c4511ddf2d 100644 --- a/x/gov/params.go +++ b/x/gov/params.go @@ -1,7 +1,6 @@ package gov import ( - "fmt" sdk "github.com/cosmos/cosmos-sdk/types" "strconv" "strings" @@ -9,19 +8,15 @@ import ( const Prefix = "gov/" -var ( - ParamStoreKeyDepositProcedureDeposit = GetGovKey("depositprocedure/deposit") - ParamStoreKeyDepositProcedureMaxDepositPeriod = GetGovKey("depositprocedure/maxDepositPeriod") - ParamStoreKeyVotingProcedureVotingPeriod = GetGovKey("votingprocedure/votingPeriod") - ParamStoreKeyTallyingProcedureThreshold = GetGovKey("tallyingprocedure/threshold") - ParamStoreKeyTallyingProcedureVeto = GetGovKey("tallyingprocedure/veto") - ParamStoreKeyTallyingProcedurePenalty = GetGovKey("tallyingprocedure/penalty") +const ( + ParamStoreKeyDepositProcedureDeposit = "depositprocedure/deposit" + ParamStoreKeyDepositProcedureMaxDepositPeriod = "depositprocedure/maxDepositPeriod" + ParamStoreKeyVotingProcedureVotingPeriod = "votingprocedure/votingPeriod" + ParamStoreKeyTallyingProcedureThreshold = "tallyingprocedure/threshold" + ParamStoreKeyTallyingProcedureVeto = "tallyingprocedure/veto" + ParamStoreKeyTallyingProcedurePenalty = "tallyingprocedure/penalty" ) -func GetGovKey(key string) string { - return fmt.Sprintf("%s%s", Prefix, key) -} - // ===================================================== // Procedures @@ -51,34 +46,34 @@ func (keeper Keeper) GetTallyingProcedure(ctx sdk.Context) TallyingProcedure { func (keeper Keeper) setDepositProcedureDeposit(ctx sdk.Context, Deposit sdk.Coins) { data := Deposit.String() - keeper.ps.Set(ctx, ParamStoreKeyDepositProcedureDeposit, &data) + keeper.ps.GovSetter().Set(ctx, ParamStoreKeyDepositProcedureDeposit, &data) } func (keeper Keeper) setDepositProcedureMaxDepositPeriod(ctx sdk.Context, MaxDepositPeriod int64) { maxDepositPeriod := strconv.FormatInt(MaxDepositPeriod, 10) - keeper.ps.Set(ctx, ParamStoreKeyDepositProcedureMaxDepositPeriod, &maxDepositPeriod) + keeper.ps.GovSetter().Set(ctx, ParamStoreKeyDepositProcedureMaxDepositPeriod, &maxDepositPeriod) } func (keeper Keeper) setVotingProcedureVotingPeriod(ctx sdk.Context, VotingPeriod int64) { votingPeriod := strconv.FormatInt(VotingPeriod, 10) - keeper.ps.Set(ctx, ParamStoreKeyVotingProcedureVotingPeriod, &votingPeriod) + keeper.ps.GovSetter().Set(ctx, ParamStoreKeyVotingProcedureVotingPeriod, &votingPeriod) } func (keeper Keeper) setTallyingProcedure(ctx sdk.Context, key string, rat sdk.Rat) { str := rat.String() - keeper.ps.Set(ctx, key, &str) + keeper.ps.GovSetter().Set(ctx, key, &str) } func (keeper Keeper) getDepositProcedureDeposit(ctx sdk.Context) (Deposit sdk.Coins) { var data string - keeper.ps.Get(ctx, ParamStoreKeyDepositProcedureDeposit, &data) + keeper.ps.GovSetter().Get(ctx, ParamStoreKeyDepositProcedureDeposit, &data) Deposit, _ = sdk.ParseCoins(data) return } func (keeper Keeper) getDepositProcedureMaxDepositPeriod(ctx sdk.Context) (MaxDepositPeriod int64) { var maxDepositPeriod string - if keeper.ps.Get(ctx, ParamStoreKeyDepositProcedureMaxDepositPeriod, &maxDepositPeriod) == nil { + if keeper.ps.GovSetter().Get(ctx, ParamStoreKeyDepositProcedureMaxDepositPeriod, &maxDepositPeriod) == nil { MaxDepositPeriod, _ = strconv.ParseInt(maxDepositPeriod, 10, 64) } return @@ -86,7 +81,7 @@ func (keeper Keeper) getDepositProcedureMaxDepositPeriod(ctx sdk.Context) (MaxDe func (keeper Keeper) getVotingProcedureVotingPeriod(ctx sdk.Context) (VotingPeriod int64) { var votingPeriod string - if keeper.ps.Get(ctx, ParamStoreKeyVotingProcedureVotingPeriod, &votingPeriod) == nil { + if keeper.ps.GovSetter().Get(ctx, ParamStoreKeyVotingProcedureVotingPeriod, &votingPeriod) == nil { VotingPeriod, _ = strconv.ParseInt(votingPeriod, 10, 64) } return @@ -94,7 +89,7 @@ func (keeper Keeper) getVotingProcedureVotingPeriod(ctx sdk.Context) (VotingPeri func (keeper Keeper) getTallyingProcedure(ctx sdk.Context, key string) sdk.Rat { var data string - keeper.ps.Get(ctx, key, &data) + keeper.ps.GovSetter().Get(ctx, key, &data) str := strings.Split(data, "/") x, _ := strconv.ParseInt(str[0], 10, 64) y, _ := strconv.ParseInt(str[1], 10, 64) diff --git a/x/gov/proposals.go b/x/gov/proposals.go index b890a0d8befe..8b69289b59db 100644 --- a/x/gov/proposals.go +++ b/x/gov/proposals.go @@ -132,13 +132,13 @@ func (pp *ParameterProposal) Execute(ctx sdk.Context, k Keeper) (err error) { continue } if data.Op == Add { - k.ps.Set(ctx, data.Key, data.Value) + k.ps.GovSetter().Set(ctx, data.Key, data.Value) } else if data.Op == Update { - bz := k.ps.GetRaw(ctx, data.Key) + bz := k.ps.GovSetter().GetRaw(ctx, data.Key) if bz == nil || len(bz) == 0 { logger.Error("Execute ParameterProposal ", "err", "Parameter "+data.Key+" is not exist") } else { - k.ps.SetString(ctx, data.Key, data.Value) + k.ps.GovSetter().SetString(ctx, data.Key, data.Value) } } } diff --git a/x/params/keeper_test.go b/x/params/keeper_test.go index 4bb5744ea458..0cc5e19c2caf 100644 --- a/x/params/keeper_test.go +++ b/x/params/keeper_test.go @@ -278,3 +278,25 @@ func TestGetter(t *testing.T) { assert.Equal(t, def10, res) } + +func TestGetterSetterProxy(t *testing.T) { + skey := sdk.NewKVStoreKey("test") + ctx := defaultContext(skey) + setter := NewKeeper(wire.NewCodec(), skey).Setter() + + key := "test" + value := "hello" + setter.Set(ctx,key,value) + + actual,_ := setter.GetString(ctx,key) + assert.Equal(t,actual,value) + + setter.GovSetter().Set(ctx,key,value) + actual1,_ := setter.GovSetter().GetString(ctx,key) + assert.Equal(t,actual1,value) + + actual2,_ := setter.GetString(ctx,key) + assert.Equal(t,actual2,value) + + +} diff --git a/x/params/proxy.go b/x/params/proxy.go index 68c5f72b587f..953ef9c8c6f3 100644 --- a/x/params/proxy.go +++ b/x/params/proxy.go @@ -11,249 +11,266 @@ const ( Global = "global" ) -// Getter returns readonly struct + +// Getter returns readonly struct,default get from Global func (k Keeper) Getter() GetterProxy { - return GetterProxy{Getter{k}} + return GetterProxy{Getter{k}, func(key string) string { + if strings.HasPrefix(key,Global+"/") { + return key + } + return fmt.Sprintf("%s/%s", Global, key) + }} } -// Setter returns read/write struct +// Getter returns readonly struct,add Prefix "global" func (k Keeper) Setter() SetterProxy { return SetterProxy{k.Getter(), Setter{Getter{k}}} } -type GetterProxy struct { - getter Getter +// Getter returns readonly struct,get from Gov +func (proxy GetterProxy) GovGetter() GetterProxy { + return GetterProxy{proxy.getter, func(key string) string { + if strings.HasPrefix(key,Gov+"/") { + return key + } + return fmt.Sprintf("%s/%s", Gov, key) + }} +} + +// Getter returns readonly struct,add Prefix "gov" +func (proxy SetterProxy) GovSetter() SetterProxy { + return SetterProxy{proxy.GovGetter(),proxy.setter} } -func getStoreKey(key string) string { - if strings.HasPrefix(key, Gov+"/") || strings.HasPrefix(key, Global+"/") { - return key - } - return fmt.Sprintf("%s/%s", Global, key) +type BuildStoreKey = func(key string) string + +type GetterProxy struct { + getter Getter + BuildStoreKey } func (proxy GetterProxy) Get(ctx sdk.Context, key string, res interface{}) (err error) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.Get(ctx, paramKey, res) } // GetRaw exposes getRaw func (proxy GetterProxy) GetRaw(ctx sdk.Context, key string) []byte { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetRaw(ctx, paramKey) } // GetString is helper function for string params func (proxy GetterProxy) GetString(ctx sdk.Context, key string) (res string, err error) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetString(ctx, paramKey) } // GetBool is helper function for bool params func (proxy GetterProxy) GetBool(ctx sdk.Context, key string) (res bool, err error) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetBool(ctx, paramKey) } // GetInt16 is helper function for int16 params func (proxy GetterProxy) GetInt16(ctx sdk.Context, key string) (res int16, err error) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetInt16(ctx, paramKey) } // GetInt32 is helper function for int32 params func (proxy GetterProxy) GetInt32(ctx sdk.Context, key string) (res int32, err error) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetInt32(ctx, paramKey) } // GetInt64 is helper function for int64 params func (proxy GetterProxy) GetInt64(ctx sdk.Context, key string) (res int64, err error) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetInt64(ctx, paramKey) } // GetUint16 is helper function for uint16 params func (proxy GetterProxy) GetUint16(ctx sdk.Context, key string) (res uint16, err error) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetUint16(ctx, paramKey) } // GetUint32 is helper function for uint32 params func (proxy GetterProxy) GetUint32(ctx sdk.Context, key string) (res uint32, err error) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetUint32(ctx, paramKey) } // GetUint64 is helper function for uint64 params func (proxy GetterProxy) GetUint64(ctx sdk.Context, key string) (res uint64, err error) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetUint64(ctx, paramKey) } // GetInt is helper function for sdk.Int params func (proxy GetterProxy) GetInt(ctx sdk.Context, key string) (res sdk.Int, err error) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetInt(ctx, paramKey) } // GetUint is helper function for sdk.Uint params func (proxy GetterProxy) GetUint(ctx sdk.Context, key string) (res sdk.Uint, err error) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetUint(ctx, paramKey) } // GetRat is helper function for rat params func (proxy GetterProxy) GetRat(ctx sdk.Context, key string) (res sdk.Rat, err error) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetRat(ctx, paramKey) } // GetStringWithDefault is helper function for string params with default value func (proxy GetterProxy) GetStringWithDefault(ctx sdk.Context, key string, def string) (res string) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetStringWithDefault(ctx, paramKey, def) } // GetBoolWithDefault is helper function for bool params with default value func (proxy GetterProxy) GetBoolWithDefault(ctx sdk.Context, key string, def bool) (res bool) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetBoolWithDefault(ctx, paramKey, def) } // GetInt16WithDefault is helper function for int16 params with default value func (proxy GetterProxy) GetInt16WithDefault(ctx sdk.Context, key string, def int16) (res int16) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetInt16WithDefault(ctx, paramKey, def) } // GetInt32WithDefault is helper function for int32 params with default value func (proxy GetterProxy) GetInt32WithDefault(ctx sdk.Context, key string, def int32) (res int32) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetInt32WithDefault(ctx, paramKey, def) } // GetInt64WithDefault is helper function for int64 params with default value func (proxy GetterProxy) GetInt64WithDefault(ctx sdk.Context, key string, def int64) (res int64) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetInt64WithDefault(ctx, paramKey, def) } // GetUint16WithDefault is helper function for uint16 params with default value func (proxy GetterProxy) GetUint16WithDefault(ctx sdk.Context, key string, def uint16) (res uint16) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetUint16WithDefault(ctx, paramKey, def) } // GetUint32WithDefault is helper function for uint32 params with default value func (proxy GetterProxy) GetUint32WithDefault(ctx sdk.Context, key string, def uint32) (res uint32) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetUint32WithDefault(ctx, paramKey, def) } // GetUint64WithDefault is helper function for uint64 params with default value func (proxy GetterProxy) GetUint64WithDefault(ctx sdk.Context, key string, def uint64) (res uint64) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetUint64WithDefault(ctx, paramKey, def) } // GetIntWithDefault is helper function for sdk.Int params with default value func (proxy GetterProxy) GetIntWithDefault(ctx sdk.Context, key string, def sdk.Int) (res sdk.Int) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetIntWithDefault(ctx, paramKey, def) } // GetUintWithDefault is helper function for sdk.Uint params with default value func (proxy GetterProxy) GetUintWithDefault(ctx sdk.Context, key string, def sdk.Uint) (res sdk.Uint) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetUintWithDefault(ctx, paramKey, def) } // GetRatWithDefault is helper function for sdk.Rat params with default value func (proxy GetterProxy) GetRatWithDefault(ctx sdk.Context, key string, def sdk.Rat) (res sdk.Rat) { - paramKey := getStoreKey(key) + paramKey := proxy.BuildStoreKey(key) return proxy.getter.GetRatWithDefault(ctx, paramKey, def) } type SetterProxy struct { GetterProxy - Setter + setter Setter } // Set exposes set func (proxy SetterProxy) Set(ctx sdk.Context, key string, param interface{}) error { - paramKey := getStoreKey(key) - return proxy.Setter.Set(ctx, paramKey, param) + paramKey := proxy.BuildStoreKey(key) + return proxy.setter.Set(ctx, paramKey, param) } // SetRaw exposes setRaw func (proxy SetterProxy) SetRaw(ctx sdk.Context, key string, param []byte) { - paramKey := getStoreKey(key) - proxy.Setter.SetRaw(ctx, paramKey, param) + paramKey := proxy.BuildStoreKey(key) + proxy.setter.SetRaw(ctx, paramKey, param) } // SetString is helper function for string params func (proxy SetterProxy) SetString(ctx sdk.Context, key string, param string) { - paramKey := getStoreKey(key) - proxy.Setter.SetString(ctx, paramKey, param) + paramKey := proxy.BuildStoreKey(key) + proxy.setter.SetString(ctx, paramKey, param) } // SetBool is helper function for bool params func (proxy SetterProxy) SetBool(ctx sdk.Context, key string, param bool) { - paramKey := getStoreKey(key) - proxy.Setter.SetBool(ctx, paramKey, param) + paramKey := proxy.BuildStoreKey(key) + proxy.setter.SetBool(ctx, paramKey, param) } // SetInt16 is helper function for int16 params func (proxy SetterProxy) SetInt16(ctx sdk.Context, key string, param int16) { - paramKey := getStoreKey(key) - proxy.Setter.SetInt16(ctx, paramKey, param) + paramKey := proxy.BuildStoreKey(key) + proxy.setter.SetInt16(ctx, paramKey, param) } // SetInt32 is helper function for int32 params func (proxy SetterProxy) SetInt32(ctx sdk.Context, key string, param int32) { - paramKey := getStoreKey(key) - proxy.Setter.SetInt32(ctx, paramKey, param) + paramKey := proxy.BuildStoreKey(key) + proxy.setter.SetInt32(ctx, paramKey, param) } // SetInt64 is helper function for int64 params func (proxy SetterProxy) SetInt64(ctx sdk.Context, key string, param int64) { - paramKey := getStoreKey(key) - proxy.Setter.SetInt64(ctx, paramKey, param) + paramKey := proxy.BuildStoreKey(key) + proxy.setter.SetInt64(ctx, paramKey, param) } // SetUint16 is helper function for uint16 params func (proxy SetterProxy) SetUint16(ctx sdk.Context, key string, param uint16) { - paramKey := getStoreKey(key) - proxy.Setter.SetUint16(ctx, paramKey, param) + paramKey := proxy.BuildStoreKey(key) + proxy.setter.SetUint16(ctx, paramKey, param) } // SetUint32 is helper function for uint32 params func (proxy SetterProxy) SetUint32(ctx sdk.Context, key string, param uint32) { - paramKey := getStoreKey(key) - proxy.Setter.SetUint32(ctx, paramKey, param) + paramKey := proxy.BuildStoreKey(key) + proxy.setter.SetUint32(ctx, paramKey, param) } // SetUint64 is helper function for uint64 params func (proxy SetterProxy) SetUint64(ctx sdk.Context, key string, param uint64) { - paramKey := getStoreKey(key) - proxy.Setter.SetUint64(ctx, paramKey, param) + paramKey := proxy.BuildStoreKey(key) + proxy.setter.SetUint64(ctx, paramKey, param) } // SetInt is helper function for sdk.Int params func (proxy SetterProxy) SetInt(ctx sdk.Context, key string, param sdk.Int) { - paramKey := getStoreKey(key) - proxy.Setter.SetInt(ctx, paramKey, param) + paramKey := proxy.BuildStoreKey(key) + proxy.setter.SetInt(ctx, paramKey, param) } // SetUint is helper function for sdk.Uint params func (proxy SetterProxy) SetUint(ctx sdk.Context, key string, param sdk.Uint) { - paramKey := getStoreKey(key) - proxy.Setter.SetUint(ctx, paramKey, param) + paramKey := proxy.BuildStoreKey(key) + proxy.setter.SetUint(ctx, paramKey, param) } // SetRat is helper function for rat params func (proxy SetterProxy) SetRat(ctx sdk.Context, key string, param sdk.Rat) { - paramKey := getStoreKey(key) - proxy.Setter.SetRat(ctx, paramKey, param) + paramKey := proxy.BuildStoreKey(key) + proxy.setter.SetRat(ctx, paramKey, param) } From 5677bd0b44c0808f4e50a4af0a7cf9ffcc56dc5f Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Mon, 13 Aug 2018 10:18:09 +0800 Subject: [PATCH 48/52] update proposal test case --- x/gov/proposals_test.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/x/gov/proposals_test.go b/x/gov/proposals_test.go index 9175fd91430f..6ee8201d5472 100644 --- a/x/gov/proposals_test.go +++ b/x/gov/proposals_test.go @@ -20,11 +20,11 @@ func TestParameterProposal(t *testing.T) { pp := ParameterProposal{ Params: []Param{ - {Key: ParamStoreKeyDepositProcedureDeposit, Value: "200iris", Op: Update}, - {Key: ParamStoreKeyDepositProcedureMaxDepositPeriod, Value: "20", Op: Update}, - {Key: ParamStoreKeyTallyingProcedurePenalty, Value: "1/50", Op: Update}, - {Key: ParamStoreKeyTallyingProcedureVeto, Value: "1/4", Op: Update}, - {Key: ParamStoreKeyTallyingProcedureThreshold, Value: "2/8", Op: Update}, + {Key: Prefix + ParamStoreKeyDepositProcedureDeposit, Value: "200iris", Op: Update}, + {Key: Prefix + ParamStoreKeyDepositProcedureMaxDepositPeriod, Value: "20", Op: Update}, + {Key: Prefix + ParamStoreKeyTallyingProcedurePenalty, Value: "1/50", Op: Update}, + {Key: Prefix + ParamStoreKeyTallyingProcedureVeto, Value: "1/4", Op: Update}, + {Key: Prefix + ParamStoreKeyTallyingProcedureThreshold, Value: "2/8", Op: Update}, }, } From 1b9c3c4adaf131345450f4947b308b2c0c42e517 Mon Sep 17 00:00:00 2001 From: HaoyangLiu Date: Mon, 13 Aug 2018 18:09:00 +0800 Subject: [PATCH 49/52] Add fee in rest server --- x/gov/client/rest/util.go | 2 ++ x/slashing/client/rest/tx.go | 2 ++ x/stake/client/rest/tx.go | 2 ++ 3 files changed, 6 insertions(+) diff --git a/x/gov/client/rest/util.go b/x/gov/client/rest/util.go index 341f0b05775e..75ce8625602f 100644 --- a/x/gov/client/rest/util.go +++ b/x/gov/client/rest/util.go @@ -17,6 +17,7 @@ type baseReq struct { AccountNumber int64 `json:"account_number"` Sequence int64 `json:"sequence"` Gas int64 `json:"gas"` + Fee string `json:"fee"` } func buildReq(w http.ResponseWriter, r *http.Request, cdc *wire.Codec, req interface{}) error { @@ -75,6 +76,7 @@ func signAndBuild(w http.ResponseWriter, ctx context.CoreContext, baseReq baseRe // add gas to context ctx = ctx.WithGas(baseReq.Gas) + ctx = ctx.WithFee(baseReq.Fee) txBytes, err := ctx.SignAndBuild(baseReq.Name, baseReq.Password, []sdk.Msg{msg}, cdc) if err != nil { diff --git a/x/slashing/client/rest/tx.go b/x/slashing/client/rest/tx.go index f358075447c4..b4fa1f0be0c5 100644 --- a/x/slashing/client/rest/tx.go +++ b/x/slashing/client/rest/tx.go @@ -31,6 +31,7 @@ type UnrevokeBody struct { AccountNumber int64 `json:"account_number"` Sequence int64 `json:"sequence"` Gas int64 `json:"gas"` + Fee string `json:"fee"` ValidatorAddr string `json:"validator_addr"` } @@ -71,6 +72,7 @@ func unrevokeRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.Core } ctx = ctx.WithGas(m.Gas) + ctx = ctx.WithFee(m.Fee) ctx = ctx.WithChainID(m.ChainID) ctx = ctx.WithAccountNumber(m.AccountNumber) ctx = ctx.WithSequence(m.Sequence) diff --git a/x/stake/client/rest/tx.go b/x/stake/client/rest/tx.go index a0f0416549d3..4f247ef43ff8 100644 --- a/x/stake/client/rest/tx.go +++ b/x/stake/client/rest/tx.go @@ -58,6 +58,7 @@ type EditDelegationsBody struct { AccountNumber int64 `json:"account_number"` Sequence int64 `json:"sequence"` Gas int64 `json:"gas"` + Fee string `json:"fee"` Delegations []msgDelegationsInput `json:"delegations"` BeginUnbondings []msgBeginUnbondingInput `json:"begin_unbondings"` CompleteUnbondings []msgCompleteUnbondingInput `json:"complete_unbondings"` @@ -254,6 +255,7 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte // add gas to context ctx = ctx.WithGas(m.Gas) + ctx = ctx.WithFee(m.Fee) // sign messages signedTxs := make([][]byte, len(messages[:])) From 0e8c7738471f04aa24dfb65a41931760a7821cf4 Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Tue, 14 Aug 2018 10:55:49 +0800 Subject: [PATCH 50/52] update the SoftwareUpgradeProposal --- x/gov/proposals.go | 25 +++++++++++++++++++------ x/params/proxy.go | 2 +- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/x/gov/proposals.go b/x/gov/proposals.go index 8b69289b59db..ae9148fd3637 100644 --- a/x/gov/proposals.go +++ b/x/gov/proposals.go @@ -154,13 +154,26 @@ type SoftwareUpgradeProposal struct { func (sp *SoftwareUpgradeProposal) Execute(ctx sdk.Context, k Keeper) error { logger := ctx.Logger().With("module", "x/gov") logger.Info("Execute SoftwareProposal begin", "info", fmt.Sprintf("current height:%d", ctx.BlockHeight())) - err := k.ps.Set(ctx, "upgrade/proposalId", sp.ProposalID) - if err != nil { - return err + + + bz := k.ps.GovSetter().GetRaw(ctx, "upgrade/proposalId") + if bz == nil || len(bz) == 0 { + logger.Error("Execute SoftwareProposal ", "err", "Parameter upgrade/proposalId is not exist") + } else { + err := k.ps.GovSetter().Set(ctx, "upgrade/proposalId", sp.ProposalID) + if err != nil { + return err + } } - k.ps.Set(ctx, "upgrade/proposalAcceptHeight", ctx.BlockHeight()) - if err != nil { - return err + + bz = k.ps.GovSetter().GetRaw(ctx, "upgrade/proposalAcceptHeight") + if bz == nil || len(bz) == 0 { + logger.Error("Execute SoftwareProposal ", "err", "Parameter upgrade/proposalAcceptHeight is not exist") + } else { + err := k.ps.GovSetter().Set(ctx, "upgrade/proposalAcceptHeight", ctx.BlockHeight()) + if err != nil { + return err + } } return nil } diff --git a/x/params/proxy.go b/x/params/proxy.go index 953ef9c8c6f3..6269ad4780ee 100644 --- a/x/params/proxy.go +++ b/x/params/proxy.go @@ -38,7 +38,7 @@ func (proxy GetterProxy) GovGetter() GetterProxy { } // Getter returns readonly struct,add Prefix "gov" -func (proxy SetterProxy) GovSetter() SetterProxy { +func (proxy SetterProxy) GovSetter() SetterProxy { return SetterProxy{proxy.GovGetter(),proxy.setter} } From aa18f1aad40d0bc7b4d983e80a30ec2672cdfd3b Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Tue, 14 Aug 2018 14:50:03 +0800 Subject: [PATCH 51/52] add NewIrisGenesisState for irishub --- x/gov/genesis.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/x/gov/genesis.go b/x/gov/genesis.go index 39ebca90cd64..cd17e8a36491 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -21,6 +21,26 @@ func NewGenesisState(startingProposalID int64, dp DepositProcedure, vp VotingPro } } +//////////////////// iris/cosmos-sdk begin/////////////////////////// +func NewIrisGenesisState(minDeposit sdk.Coins, depositPeriod int64, votingPeriod int64) GenesisState { + return GenesisState{ + StartingProposalID: 1, + DepositProcedure: DepositProcedure{ + MinDeposit: minDeposit, + MaxDepositPeriod: depositPeriod, + }, + VotingProcedure: VotingProcedure{ + VotingPeriod: votingPeriod, + }, + TallyingProcedure: TallyingProcedure{ + Threshold: sdk.NewRat(1, 2), + Veto: sdk.NewRat(1, 3), + GovernancePenalty: sdk.NewRat(1, 100), + }, + } +} +//////////////////// iris/cosmos-sdk end/////////////////////////// + // get raw genesis raw message for testing func DefaultGenesisState() GenesisState { return GenesisState{ From 98e3cf789f969a34a71ee2fec87c959057152338 Mon Sep 17 00:00:00 2001 From: Raymond Date: Wed, 15 Aug 2018 18:03:18 +0800 Subject: [PATCH 52/52] update tendermint deps to v0.22.6-iris1 --- Gopkg.lock | 35 ++++++++++++++++++++--------------- Gopkg.toml | 3 ++- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index edae326bb9fa..ddb43e63929a 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -29,7 +29,7 @@ branch = "master" name = "github.com/btcsuite/btcd" packages = ["btcec"] - revision = "9a2f9524024889e129a5422aca2cff73cb3eabf6" + revision = "f899737d7f2764dc13e4d01ff00108ec58f766a9" [[projects]] name = "github.com/btcsuite/btcutil" @@ -135,6 +135,7 @@ ".", "hcl/ast", "hcl/parser", + "hcl/printer", "hcl/scanner", "hcl/strconv", "hcl/token", @@ -164,7 +165,10 @@ [[projects]] name = "github.com/magiconair/properties" - packages = ["."] + packages = [ + ".", + "assert" + ] revision = "c2353362d570a7bfa228149c62842019201cfb71" version = "v1.8.0" @@ -216,7 +220,7 @@ branch = "master" name = "github.com/prometheus/client_model" packages = ["go"] - revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c" + revision = "5c3871d89910bfb32f5fcab2aa4b9ec68e65a99f" [[projects]] branch = "master" @@ -226,7 +230,7 @@ "internal/bitbucket.org/ww/goautoneg", "model" ] - revision = "7600349dcfe1abd18d72d3a1770870d9800a7801" + revision = "c7de2306084e37d54b8be01f3541a8464345e9a5" [[projects]] branch = "master" @@ -237,7 +241,7 @@ "nfs", "xfs" ] - revision = "ae68e2d4c00fed4943b5f6698d504a5fe083da8a" + revision = "05ee40e3a273f7245e8777337fc7b46e533a9a92" [[projects]] name = "github.com/rcrowley/go-metrics" @@ -269,13 +273,13 @@ branch = "master" name = "github.com/spf13/jwalterweatherman" packages = ["."] - revision = "7c0cea34c8ece3fbeb2b27ab9b59511d360fb394" + revision = "14d3d4c518341bea657dd8a226f5121c0ff8c9f2" [[projects]] name = "github.com/spf13/pflag" packages = ["."] - revision = "583c0c0531f06d5278b7d917446061adc344b5cd" - version = "v1.0.1" + revision = "9a97c102cda95a86cec2345a6f09f55a939babf5" + version = "v1.0.2" [[projects]] name = "github.com/spf13/viper" @@ -309,7 +313,7 @@ "leveldb/table", "leveldb/util" ] - revision = "c4c61651e9e37fa117f53c5a906d3b63090d8445" + revision = "ae2bd5eed72d46b28834ec3f60db3a3ebedd8dbd" [[projects]] branch = "master" @@ -395,8 +399,9 @@ "types", "version" ] - revision = "5fdbcd70df57b71ffba71e1ff5f00d617852a9c0" - version = "v0.22.6" + revision = "fb697db81e3f0b04fb9c6f393ce9a09b984a4687" + source = "https://github.com/irisnet/tendermint.git" + version = "v0.22.6-iris1" [[projects]] name = "github.com/zondax/ledger-goclient" @@ -419,7 +424,7 @@ "ripemd160", "salsa20/salsa" ] - revision = "c126467f60eb25f8f27e5a981f32a87e3965053f" + revision = "de0752318171da717af4ce24d0a2e8626afaeb11" [[projects]] name = "golang.org/x/net" @@ -439,7 +444,7 @@ branch = "master" name = "golang.org/x/sys" packages = ["unix"] - revision = "ac767d655b305d4e9612f5f6e33120b9176c4ad4" + revision = "14742f9018cd6651ec7364dc6ee08af0baaa1031" [[projects]] name = "golang.org/x/text" @@ -466,7 +471,7 @@ branch = "master" name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] - revision = "02b4e95473316948020af0b7a4f0f22c73929b0e" + revision = "383e8b2c3b9e36c4076b235b32537292176bae20" [[projects]] name = "google.golang.org/grpc" @@ -509,6 +514,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "6f8a03c6ac5eabf21dcf7e302220a891f183ccd5a0ad9a2b403e892e9862cef4" + inputs-digest = "851887326646b383c061686cb68ab432cce91f3ee4745ab08ee941278733ede7" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index 5b4df4ec090c..83fd6543cc15 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -62,7 +62,8 @@ [[override]] name = "github.com/tendermint/tendermint" - version = "=v0.22.6" + source = "https://github.com/irisnet/tendermint.git" + version = "=v0.22.6-iris1" [[constraint]] name = "github.com/bartekn/go-bip39"