From 2f75f66fd500dd77faa05dacb3bd0110d8903deb Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 27 Jul 2018 11:18:28 +0200 Subject: [PATCH 01/46] Updated some staking txs routes (bond, unbond, redelegate) --- x/stake/client/rest/query.go | 369 +++++++++++++++++++++++------------ x/stake/keeper/key.go | 8 + 2 files changed, 249 insertions(+), 128 deletions(-) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 9a4c3755ddcc..4106e0b152e3 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -3,6 +3,8 @@ package rest import ( "fmt" "net/http" + "reflect" + "strings" "github.com/gorilla/mux" @@ -16,37 +18,58 @@ import ( const storeName = "stake" +func contains(stringSlice []string, txType string) bool { + for _, word := range stringSlice { + if word == txType { + return true + } + } + return false +} + func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec) { - r.HandleFunc( - "/stake/{delegator}/delegation/{validator}", - delegationHandlerFn(ctx, cdc), - ).Methods("GET") + // GET /delegators/{addr}/txs // Get all staking txs from a delegator + + // GET /delegators/{addr}/txs/{id} // Get a specific staking tx from a delegator + // GET /delegators/{addr}/validators // Query all validators that a delegator is bonded to + // GET /delegators/{addr}/validators/{addr} // Query a validator info that a delegator is bonded to + // GET /delegators/{addr}/validators/{addr}/txs // Get all txs to a validator performed by a delegator + // GET /delegators/{addr}/validators/{addr}/txs?type=bond // Get all bonding txs to a validator performed by a delegator + // GET /delegators/{addr}/validators/{addr}/txs?type=unbond // Get all unbonding txs to a validator performed by a delegator + // GET /delegators/{addr}/validators/{addr}/txs?type=redelegate // Get all redelegation txs to a validator performed by a delegator r.HandleFunc( - "/stake/{delegator}/ubd/{validator}", - ubdHandlerFn(ctx, cdc), - ).Methods("GET") + "/delegators/{delegatorAddr}/validators/{validatorAddr}/txs", + stakingTxsHandlerFn(ctx, cdc), + ).Queries("type", "{type}").Methods("GET") + // GET /validators/ r.HandleFunc( - "/stake/{delegator}/red/{validator_src}/{validator_dst}", - redHandlerFn(ctx, cdc), + "/validators", + validatorsHandlerFn(ctx, cdc), ).Methods("GET") + // GET /validators/{addr} r.HandleFunc( - "/stake/validators", - validatorsHandlerFn(ctx, cdc), + "/validators/{addr}", + validatorHandlerFn(ctx, cdc), ).Methods("GET") + + // GET /validators/{addr}/delegators + // r.HandleFunc( + // "/validators/{addr}/delegators", + // validatorDelegatorsHandlerFn(ctx, cdc), + // ).Methods("GET") } -// http request handler to query a delegation -func delegationHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +func stakingTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // read parameters vars := mux.Vars(r) - bech32delegator := vars["delegator"] - bech32validator := vars["validator"] + bech32delegator := vars["delegatorAddr"] + bech32validator := vars["validatorAddr"] delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) if err != nil { @@ -62,85 +85,183 @@ func delegationHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF return } - key := stake.GetDelegationKey(delegatorAddr, validatorAddr) + var typesQuerySlice []string + var output []byte + typesQuery := r.URL.Query().Get("type") + typesQuerySlice = strings.Split(strings.TrimSpace(typesQuery), " ") - res, err := ctx.QueryStore(key, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) - return - } + noQuery := len(typesQuerySlice) == 0 - // the query will return empty if there is no data for this record - if len(res) == 0 { - w.WriteHeader(http.StatusNoContent) - return - } + // delegation + if noQuery || contains(typesQuerySlice, "bond") { + key := stake.GetDelegationKey(delegatorAddr, validatorAddr) - delegation, err := types.UnmarshalDelegation(cdc, key, res) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } + res, err := ctx.QueryStore(key, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + return + } - output, err := cdc.MarshalJSON(delegation) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return + // the query will return empty if there is no data for this record + if len(res) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + + delegation, err := types.UnmarshalDelegation(cdc, key, res) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + + outputBond, err := cdc.MarshalJSON(delegation) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + output = append(output, outputBond...) } + if noQuery || contains(typesQuerySlice, "unbond") { - w.Write(output) - } -} + key := stake.GetUBDKey(delegatorAddr, validatorAddr) -// http request handler to query an unbonding-delegation -func ubdHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { + res, err := ctx.QueryStore(key, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } - // read parameters - vars := mux.Vars(r) - bech32delegator := vars["delegator"] - bech32validator := vars["validator"] + // the query will return empty if there is no data for this record + if len(res) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } + ubd, err := types.UnmarshalUBD(cdc, key, res) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } - validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return + outputUnbond, err := cdc.MarshalJSON(ubd) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + output = append(output, outputUnbond...) } + if noQuery || contains(typesQuerySlice, "redelegate") { + // keyValidatorFrom := stake.GetREDsByDelFromValSrcIndexKey(delegatorAddr, validatorAddr) + keyValidatorTo := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) + + // All redelegations from source validator (i.e unbonding) + res, err := ctx.QueryStore(keyValidatorFrom, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) + return + } + + // the query will return empty if there is no data for this record + if len(res) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + + red, err := types.UnmarshalRED(cdc, keyValidatorFrom, res) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } + + outputFrom, err := cdc.MarshalJSON(red) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + // All redelegations to destination validator (i.e bonding) + res, err = ctx.QueryStore(keyValidatorTo, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) + return + } + + // the query will return empty if there is no data for this record + if len(res) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + + red, err = types.UnmarshalRED(cdc, keyValidatorTo, res) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } + + outputTo, err := cdc.MarshalJSON(red) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } - key := stake.GetUBDKey(delegatorAddr, validatorAddr) + // All redelegations From or To the given validator address + output := append(outputFrom, outputTo...) + } + w.Write(output) + } +} - res, err := ctx.QueryStore(key, storeName) +// TODO bech32 +// http request handler to query list of validators +func validatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("couldn't query validators. Error: %s", err.Error()))) return } - // the query will return empty if there is no data for this record - if len(res) == 0 { + // the query will return empty if there are no validators + if len(kvs) == 0 { w.WriteHeader(http.StatusNoContent) return } - ubd, err := types.UnmarshalUBD(cdc, key, res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return + // parse out the validators + validators := make([]types.BechValidator, len(kvs)) + for i, kv := range kvs { + + addr := kv.Key[1:] + validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return + } + + bech32Validator, err := validator.Bech32Validator() + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + validators[i] = bech32Validator } - output, err := cdc.MarshalJSON(ubd) + output, err := cdc.MarshalJSON(validators) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) @@ -151,78 +272,82 @@ func ubdHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { } } -// http request handler to query an redelegation -func redHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +// HTTP request handler to query the validator information from a given validator address +func validatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // read parameters vars := mux.Vars(r) - bech32delegator := vars["delegator"] - bech32validatorSrc := vars["validator_src"] - bech32validatorDst := vars["validator_dst"] - - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + bech32validatorAddr := vars["addr"] + valAddress, err := sdk.AccAddressFromBech32(bech32validatorAddr) if err != nil { w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) return } - validatorSrcAddr, err := sdk.AccAddressFromBech32(bech32validatorSrc) + kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) return } - validatorDstAddr, err := sdk.AccAddressFromBech32(bech32validatorDst) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) + // the query will return empty if there are no validators + if len(kvs) == 0 { + w.WriteHeader(http.StatusNoContent) return } - key := stake.GetREDKey(delegatorAddr, validatorSrcAddr, validatorDstAddr) + var output []byte - res, err := ctx.QueryStore(key, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) - return + // parse out the validators + for i, kv := range kvs { + addr := kv.Key[1:] + validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } + + ownerAddress := validator.GetOwner() + if reflect.DeepEqual(ownerAddress.Bytes(), valAddress.Bytes()) { + output, err = cdc.MarshalJSON(validator) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + break + } } - // the query will return empty if there is no data for this record - if len(res) == 0 { + if output == nil { w.WriteHeader(http.StatusNoContent) return } + w.Write(output) + } +} - red, err := types.UnmarshalRED(cdc, key, res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return - } +func validatorDelegatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { - output, err := cdc.MarshalJSON(red) + // read parameters + vars := mux.Vars(r) + bech32validatorAddr := vars["addr"] + valAddress, err := sdk.AccAddressFromBech32(bech32validatorAddr) if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) return } - w.Write(output) - } -} - -// TODO bech32 -// http request handler to query list of validators -func validatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query validators. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) return } @@ -232,10 +357,10 @@ func validatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF return } + var output []byte + // parse out the validators - validators := make([]types.BechValidator, len(kvs)) for i, kv := range kvs { - addr := kv.Key[1:] validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) if err != nil { @@ -244,22 +369,10 @@ func validatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF return } - bech32Validator, err := validator.Bech32Validator() - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return + ownerAddress := validator.GetOwner() + if reflect.DeepEqual(ownerAddress.Bytes(), valAddress.Bytes()) { + ctx.QuerySubspace(cdc, stake.DelegationKey, storeName) } - validators[i] = bech32Validator } - - output, err := cdc.MarshalJSON(validators) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - w.Write(output) } } diff --git a/x/stake/keeper/key.go b/x/stake/keeper/key.go index e373ede18a45..b6330b29eb25 100644 --- a/x/stake/keeper/key.go +++ b/x/stake/keeper/key.go @@ -230,3 +230,11 @@ func GetREDsByDelToValDstIndexKey(delegatorAddr, validatorDstAddr sdk.AccAddress GetREDsToValDstIndexKey(validatorDstAddr), delegatorAddr.Bytes()...) } + +// get the prefix keyspace for all redelegations redelegating from a source validator +// from a particular delegator +func GetREDsByDelFromValSrcIndexKey(delegatorAddr, validatorSrcAddr sdk.AccAddress) []byte { + return append( + GetREDsFromValSrcIndexKey(validatorSrcAddr), + delegatorAddr.Bytes()...) +} From 6f87e3f9ceaa5906bce9108b8f7b231748db9bda Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 27 Jul 2018 13:52:11 +0200 Subject: [PATCH 02/46] LCD utils for validators --- x/stake/client/rest/query.go | 272 ++++++++++++++++++++++------------- x/stake/client/rest/utils.go | 58 ++++++++ 2 files changed, 230 insertions(+), 100 deletions(-) create mode 100644 x/stake/client/rest/utils.go diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 4106e0b152e3..845e48eefad6 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -3,7 +3,6 @@ package rest import ( "fmt" "net/http" - "reflect" "strings" "github.com/gorilla/mux" @@ -18,27 +17,24 @@ import ( const storeName = "stake" -func contains(stringSlice []string, txType string) bool { - for _, word := range stringSlice { - if word == txType { - return true - } - } - return false -} - func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec) { // GET /delegators/{addr}/txs // Get all staking txs from a delegator - // GET /delegators/{addr}/txs/{id} // Get a specific staking tx from a delegator // GET /delegators/{addr}/validators // Query all validators that a delegator is bonded to + // GET /delegators/{addr}/validators/{addr} // Query a validator info that a delegator is bonded to + r.HandleFunc( + "/delegators/{delegatorAddr}/validators/{validatorAddr}", + delegatorValidatorHandlerFn(ctx, cdc), + ).Methods("GET") - // GET /delegators/{addr}/validators/{addr}/txs // Get all txs to a validator performed by a delegator - // GET /delegators/{addr}/validators/{addr}/txs?type=bond // Get all bonding txs to a validator performed by a delegator - // GET /delegators/{addr}/validators/{addr}/txs?type=unbond // Get all unbonding txs to a validator performed by a delegator - // GET /delegators/{addr}/validators/{addr}/txs?type=redelegate // Get all redelegation txs to a validator performed by a delegator + /* + GET /delegators/{addr}/validators/{addr}/txs // Get all txs to a validator performed by a delegator + GET /delegators/{addr}/validators/{addr}/txs?type=bond // Get all bonding txs to a validator performed by a delegator + GET /delegators/{addr}/validators/{addr}/txs?type=unbond // Get all unbonding txs to a validator performed by a delegator + GET /delegators/{addr}/validators/{addr}/txs?type=redelegate // Get all redelegation txs to a validator performed by a delegator + */ r.HandleFunc( "/delegators/{delegatorAddr}/validators/{validatorAddr}/txs", stakingTxsHandlerFn(ctx, cdc), @@ -63,6 +59,97 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec // ).Methods("GET") } +// HTTP request handler to query list of validators +func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + // read parameters + var isBonded bool + var output []byte + vars := mux.Vars(r) + bech32delegator := vars["delegatorAddr"] + bech32validator := vars["validatorAddr"] + + delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + + validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + + // Check if there if the delegator is bonded or redelegated to the validator + + keyDel := stake.GetDelegationKey(delegatorAddr, validatorAddr) + keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) + + res, err := ctx.QueryStore(keyDel, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + return + } + + if len(res) != 0 { + isBonded = true + } + + if !isBonded { + res, err = ctx.QueryStore(keyRed, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + return + } + + if len(res) != 0 { + isBonded = true + } + } + + if isBonded { + kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return + } + + // the query will return empty if there are no validators + if len(kvs) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + validator, err := getValidator(validatorAddr, kvs, cdc) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Couldn't get info from validator %s. Error: %s", validatorAddr.String(), err.Error()))) + return + } else if validator == nil && err == nil { + w.WriteHeader(http.StatusNoContent) + return + } + // success + output, err = cdc.MarshalJSON(validator) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + } else { + // delegator is not bonded to any delegator + w.WriteHeader(http.StatusNoContent) + return + } + w.Write(output) + } +} + func stakingTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { @@ -224,7 +311,7 @@ func stakingTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF } // TODO bech32 -// http request handler to query list of validators +// HTTP request handler to query list of validators func validatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) @@ -240,25 +327,11 @@ func validatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF return } - // parse out the validators - validators := make([]types.BechValidator, len(kvs)) - for i, kv := range kvs { - - addr := kv.Key[1:] - validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) - return - } - - bech32Validator, err := validator.Bech32Validator() - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - validators[i] = bech32Validator + validators, err := getValidators(kvs, cdc) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return } output, err := cdc.MarshalJSON(validators) @@ -276,6 +349,7 @@ func validatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF func validatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + var output []byte // read parameters vars := mux.Vars(r) bech32validatorAddr := vars["addr"] @@ -299,80 +373,78 @@ func validatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu return } - var output []byte - - // parse out the validators - for i, kv := range kvs { - addr := kv.Key[1:] - validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return - } - - ownerAddress := validator.GetOwner() - if reflect.DeepEqual(ownerAddress.Bytes(), valAddress.Bytes()) { - output, err = cdc.MarshalJSON(validator) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - break - } - } - - if output == nil { - w.WriteHeader(http.StatusNoContent) - return - } - w.Write(output) - } -} - -func validatorDelegatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - - // read parameters - vars := mux.Vars(r) - bech32validatorAddr := vars["addr"] - valAddress, err := sdk.AccAddressFromBech32(bech32validatorAddr) + validator, err := getValidator(valAddress, kvs, cdc) if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) return } - - kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + output, err = cdc.MarshalJSON(validator) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + w.Write([]byte(err.Error())) return } - - // the query will return empty if there are no validators - if len(kvs) == 0 { + if output == nil { w.WriteHeader(http.StatusNoContent) return } - - var output []byte - - // parse out the validators - for i, kv := range kvs { - addr := kv.Key[1:] - validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return - } - - ownerAddress := validator.GetOwner() - if reflect.DeepEqual(ownerAddress.Bytes(), valAddress.Bytes()) { - ctx.QuerySubspace(cdc, stake.DelegationKey, storeName) - } - } + w.Write(output) } } + +// +// func validatorDelegatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +// return func(w http.ResponseWriter, r *http.Request) { +// +// // read parameters +// vars := mux.Vars(r) +// bech32validatorAddr := vars["addr"] +// valAddress, err := sdk.AccAddressFromBech32(bech32validatorAddr) +// if err != nil { +// w.WriteHeader(http.StatusBadRequest) +// w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) +// return +// } +// +// kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) +// return +// } +// +// // the query will return empty if there are no validators +// if len(kvs) == 0 { +// w.WriteHeader(http.StatusNoContent) +// return +// } +// +// var output []byte +// +// validator, err := getValidator(valAddress, kvs, cdc) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) +// return +// } else if validator == nil && err == nil { +// +// } +// +// for i, kv := range kvs { +// addr := kv.Key[1:] +// validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) +// +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) +// return +// } +// +// ownerAddress := validator.GetOwner() +// if reflect.DeepEqual(ownerAddress.Bytes(), valAddress.Bytes()) { +// ctx.QuerySubspace(cdc, stake.DelegationKey, storeName) +// } +// } +// } +// } diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go new file mode 100644 index 000000000000..d9d7e6aeb53a --- /dev/null +++ b/x/stake/client/rest/utils.go @@ -0,0 +1,58 @@ +package rest + +import ( + "reflect" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/x/stake/types" +) + +// Contains checks if the a given query contains one of the tx types +func contains(stringSlice []string, txType string) bool { + for _, word := range stringSlice { + if word == txType { + return true + } + } + return false +} + +// get all Validators +func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechValidator, error) { + // parse out the validators + validators := make([]types.BechValidator, len(validatorKVs)) + for i, kv := range validatorKVs { + + addr := kv.Key[1:] + validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) + if err != nil { + return nil, err + } + + bech32Validator, err := validator.Bech32Validator() + if err != nil { + return nil, err + } + validators[i] = bech32Validator + } + return validators, nil +} + +// get Validator given an Account Address +func getValidator(address sdk.AccAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (sdk.Validator, error) { + // parse out the validators + for i, kv := range validatorKVs { + addr := kv.Key[1:] + validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) + if err != nil { + return nil, err + } + + ownerAddress := validator.GetOwner() + if reflect.DeepEqual(ownerAddress.Bytes(), address.Bytes()) { + return validator, nil + } + } + return nil, nil // validator Not Found +} From df3e021d737e90b5e07c756657b9c9accb414c81 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 30 Jul 2018 11:07:36 +0200 Subject: [PATCH 03/46] Updated DelegatorTxs route --- x/stake/client/rest/query.go | 302 ++++++++++++++++++++++++++--------- 1 file changed, 224 insertions(+), 78 deletions(-) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 845e48eefad6..18722e2886b5 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -19,44 +19,239 @@ const storeName = "stake" func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec) { - // GET /delegators/{addr}/txs // Get all staking txs from a delegator + // GET /stake/delegators/{addr}/txs // Get all staking txs from a delegator + r.HandleFunc( + "/stake/delegators/{addr}/txs", + delegatorTxsHandlerFn(ctx, cdc), + ).Queries("type", "{type}").Methods("GET") - // GET /delegators/{addr}/validators // Query all validators that a delegator is bonded to + // GET /stake/delegators/{addr}/validators // Query all validators that a delegator is bonded to + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/validators/{validatorAddr}", + delegatorValidatorHandlerFn(ctx, cdc), + ).Methods("GET") - // GET /delegators/{addr}/validators/{addr} // Query a validator info that a delegator is bonded to + // GET /stake/delegators/{addr}/validators/{addr} // Query a validator info that a delegator is bonded to r.HandleFunc( - "/delegators/{delegatorAddr}/validators/{validatorAddr}", + "/stake/delegators/{delegatorAddr}/validators/{validatorAddr}", delegatorValidatorHandlerFn(ctx, cdc), ).Methods("GET") /* - GET /delegators/{addr}/validators/{addr}/txs // Get all txs to a validator performed by a delegator - GET /delegators/{addr}/validators/{addr}/txs?type=bond // Get all bonding txs to a validator performed by a delegator - GET /delegators/{addr}/validators/{addr}/txs?type=unbond // Get all unbonding txs to a validator performed by a delegator - GET /delegators/{addr}/validators/{addr}/txs?type=redelegate // Get all redelegation txs to a validator performed by a delegator + GET /stake/delegators/{addr}/validators/{addr}/txs // Get all txs to a validator performed by a delegator + GET /stake/delegators/{addr}/validators/{addr}/txs?type=bond // Get all bonding txs to a validator performed by a delegator + GET /stake/delegators/{addr}/validators/{addr}/txs?type=unbond // Get all unbonding txs to a validator performed by a delegator + GET /stake/delegators/{addr}/validators/{addr}/txs?type=redelegate // Get all redelegation txs to a validator performed by a delegator */ r.HandleFunc( - "/delegators/{delegatorAddr}/validators/{validatorAddr}/txs", + "/stake/delegators/{delegatorAddr}/validators/{validatorAddr}/txs", stakingTxsHandlerFn(ctx, cdc), ).Queries("type", "{type}").Methods("GET") - // GET /validators/ + // GET /stake/validators/ r.HandleFunc( - "/validators", + "/stake/validators", validatorsHandlerFn(ctx, cdc), ).Methods("GET") - // GET /validators/{addr} + // GET /stake/validators/{addr} r.HandleFunc( - "/validators/{addr}", + "/stake/validators/{addr}", validatorHandlerFn(ctx, cdc), ).Methods("GET") - // GET /validators/{addr}/delegators - // r.HandleFunc( - // "/validators/{addr}/delegators", - // validatorDelegatorsHandlerFn(ctx, cdc), - // ).Methods("GET") + // GET /stake/validators/{addr}/delegators + // Don't think this is currently possible without changing keys +} + +func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var validatorAddr sdk.AccAddress + var output []byte // txs from a single validator + var typesQuerySlice []string + + // read parameters + vars := mux.Vars(r) + bech32delegator := vars["delegatorAddr"] + + delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + + // Get values from query + + typesQuery := r.URL.Query().Get("type") + typesQuerySlice = strings.Split(strings.TrimSpace(typesQuery), " ") + + noQuery := len(typesQuerySlice) == 0 + isBondTx := contains(typesQuerySlice, "bond") + isUnbondTx := contains(typesQuerySlice, "unbond") + isRedTx := contains(typesQuerySlice, "redelegate") + if !isBondTx || !isUnbondTx || !isRedTx { + w.WriteHeader(http.StatusNoContent) + return + } + + // Get all validators using key + kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query validators. Error: %s", err.Error()))) + return + } + + // the query will return empty if there are no validators + if len(kvs) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + + validators, err := getValidators(kvs, cdc) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return + } + + for i, validator := range validators { + // get all transactions from the delegator to val and append + output = nil + validatorAddr = validator.Owner + // delegation + if noQuery || isBondTx { + key := stake.GetDelegationKey(delegatorAddr, validatorAddr) + + res, err := ctx.QueryStore(key, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + return + } + + // the query will return empty if there is no data for this record + if len(res) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + + delegation, err := types.UnmarshalDelegation(cdc, key, res) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + + outputBond, err := cdc.MarshalJSON(delegation) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + output = append(output, outputBond...) + } + if noQuery || isUnbondTx { + + key := stake.GetUBDKey(delegatorAddr, validatorAddr) + + res, err := ctx.QueryStore(key, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } + + // the query will return empty if there is no data for this record + if len(res) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + + ubd, err := types.UnmarshalUBD(cdc, key, res) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } + + outputUnbond, err := cdc.MarshalJSON(ubd) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + output = append(output, outputUnbond...) + } + if noQuery || isRedTx { + // keyValidatorFrom := stake.GetREDsByDelFromValSrcIndexKey(delegatorAddr, validatorAddr) + keyValidatorTo := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) + + // All redelegations from source validator (i.e unbonding) + res, err := ctx.QueryStore(keyValidatorFrom, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) + return + } + + // the query will return empty if there is no data for this record + if len(res) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + + red, err := types.UnmarshalRED(cdc, keyValidatorFrom, res) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } + + outputFrom, err := cdc.MarshalJSON(red) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + // All redelegations to destination validator (i.e bonding) + res, err = ctx.QueryStore(keyValidatorTo, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) + return + } + + // the query will return empty if there is no data for this record + if len(res) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + + red, err = types.UnmarshalRED(cdc, keyValidatorTo, res) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } + + outputTo, err := cdc.MarshalJSON(red) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + // All redelegations From or To the given validator address + output = append(outputFrom, outputTo...) + } + w.Write(output) // write + } + + } } // HTTP request handler to query list of validators @@ -173,14 +368,21 @@ func stakingTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF } var typesQuerySlice []string - var output []byte + var output []byte // XXX not sure if this is append typesQuery := r.URL.Query().Get("type") typesQuerySlice = strings.Split(strings.TrimSpace(typesQuery), " ") noQuery := len(typesQuerySlice) == 0 + isBondTx := contains(typesQuerySlice, "bond") + isUnbondTx := contains(typesQuerySlice, "unbond") + isRedTx := contains(typesQuerySlice, "redelegate") + if !isBondTx || !isUnbondTx || !isRedTx { + w.WriteHeader(http.StatusNoContent) + return + } // delegation - if noQuery || contains(typesQuerySlice, "bond") { + if noQuery || isBondTx { key := stake.GetDelegationKey(delegatorAddr, validatorAddr) res, err := ctx.QueryStore(key, storeName) @@ -211,7 +413,7 @@ func stakingTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF } output = append(output, outputBond...) } - if noQuery || contains(typesQuerySlice, "unbond") { + if noQuery || isUnbondTx { key := stake.GetUBDKey(delegatorAddr, validatorAddr) @@ -243,7 +445,7 @@ func stakingTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF } output = append(output, outputUnbond...) } - if noQuery || contains(typesQuerySlice, "redelegate") { + if noQuery || isRedTx { // keyValidatorFrom := stake.GetREDsByDelFromValSrcIndexKey(delegatorAddr, validatorAddr) keyValidatorTo := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) @@ -392,59 +594,3 @@ func validatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu w.Write(output) } } - -// -// func validatorDelegatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { -// return func(w http.ResponseWriter, r *http.Request) { -// -// // read parameters -// vars := mux.Vars(r) -// bech32validatorAddr := vars["addr"] -// valAddress, err := sdk.AccAddressFromBech32(bech32validatorAddr) -// if err != nil { -// w.WriteHeader(http.StatusBadRequest) -// w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) -// return -// } -// -// kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) -// return -// } -// -// // the query will return empty if there are no validators -// if len(kvs) == 0 { -// w.WriteHeader(http.StatusNoContent) -// return -// } -// -// var output []byte -// -// validator, err := getValidator(valAddress, kvs, cdc) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) -// return -// } else if validator == nil && err == nil { -// -// } -// -// for i, kv := range kvs { -// addr := kv.Key[1:] -// validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) -// -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) -// return -// } -// -// ownerAddress := validator.GetOwner() -// if reflect.DeepEqual(ownerAddress.Bytes(), valAddress.Bytes()) { -// ctx.QuerySubspace(cdc, stake.DelegationKey, storeName) -// } -// } -// } -// } From 5f5b07d26250575b1b9506664e1ae32bf29916f5 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 30 Jul 2018 18:34:34 +0200 Subject: [PATCH 04/46] Updated endpoints --- x/stake/client/rest/query.go | 464 ++++++++++++++++++++--------------- 1 file changed, 262 insertions(+), 202 deletions(-) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 18722e2886b5..0d2666e2caef 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -19,7 +19,13 @@ const storeName = "stake" func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec) { - // GET /stake/delegators/{addr}/txs // Get all staking txs from a delegator + // GET /stake/delegators/{addr} // Get all delegations (delegation, undelegation and redelegation) from a delegator + r.HandleFunc( + "/stake/delegators/{addr}", + delegatorHandlerFn(ctx, cdc), + ).Methods("GET") + + // GET /stake/delegators/{addr}/txs // Get all staking txs (i.e msgs) from a delegator r.HandleFunc( "/stake/delegators/{addr}/txs", delegatorTxsHandlerFn(ctx, cdc), @@ -27,8 +33,8 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec // GET /stake/delegators/{addr}/validators // Query all validators that a delegator is bonded to r.HandleFunc( - "/stake/delegators/{delegatorAddr}/validators/{validatorAddr}", - delegatorValidatorHandlerFn(ctx, cdc), + "/stake/delegators/{delegatorAddr}/validators", + delegatorValidatorsHandlerFn(ctx, cdc), ).Methods("GET") // GET /stake/delegators/{addr}/validators/{addr} // Query a validator info that a delegator is bonded to @@ -37,6 +43,8 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec delegatorValidatorHandlerFn(ctx, cdc), ).Methods("GET") + // GET /stake/delegators/{addr}/validators/{addr} + /* GET /stake/delegators/{addr}/validators/{addr}/txs // Get all txs to a validator performed by a delegator GET /stake/delegators/{addr}/validators/{addr}/txs?type=bond // Get all bonding txs to a validator performed by a delegator @@ -64,7 +72,8 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec // Don't think this is currently possible without changing keys } -func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +// HTTP request handler to query a delegator delegations +func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var validatorAddr sdk.AccAddress @@ -91,10 +100,6 @@ func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Handle isBondTx := contains(typesQuerySlice, "bond") isUnbondTx := contains(typesQuerySlice, "unbond") isRedTx := contains(typesQuerySlice, "redelegate") - if !isBondTx || !isUnbondTx || !isRedTx { - w.WriteHeader(http.StatusNoContent) - return - } // Get all validators using key kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) @@ -133,25 +138,22 @@ func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Handle } // the query will return empty if there is no data for this record - if len(res) == 0 { - w.WriteHeader(http.StatusNoContent) - return + if len(res) != 0 { + delegation, err := types.UnmarshalDelegation(cdc, key, res) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + + outputBond, err := cdc.MarshalJSON(delegation) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + output = append(output, outputBond...) } - - delegation, err := types.UnmarshalDelegation(cdc, key, res) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - outputBond, err := cdc.MarshalJSON(delegation) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - output = append(output, outputBond...) } if noQuery || isUnbondTx { @@ -165,25 +167,23 @@ func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Handle } // the query will return empty if there is no data for this record - if len(res) == 0 { - w.WriteHeader(http.StatusNoContent) - return + if len(res) != 0 { + ubd, err := types.UnmarshalUBD(cdc, key, res) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } + + outputUnbond, err := cdc.MarshalJSON(ubd) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + output = append(output, outputUnbond...) } - - ubd, err := types.UnmarshalUBD(cdc, key, res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return - } - - outputUnbond, err := cdc.MarshalJSON(ubd) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - output = append(output, outputUnbond...) } if noQuery || isRedTx { // keyValidatorFrom := stake.GetREDsByDelFromValSrcIndexKey(delegatorAddr, validatorAddr) @@ -198,63 +198,253 @@ func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Handle } // the query will return empty if there is no data for this record - if len(res) == 0 { - w.WriteHeader(http.StatusNoContent) - return + if len(res) != 0 { + red, err := types.UnmarshalRED(cdc, keyValidatorFrom, res) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } + + outputFrom, err := cdc.MarshalJSON(red) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + output = append(output, outputFrom...) } - red, err := types.UnmarshalRED(cdc, keyValidatorFrom, res) + // All redelegations to destination validator (i.e bonding) + res, err = ctx.QueryStore(keyValidatorTo, storeName) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) return } - outputFrom, err := cdc.MarshalJSON(red) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return + // the query will return empty if there is no data for this record + if len(res) != 0 { + red, err := types.UnmarshalRED(cdc, keyValidatorTo, res) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } + + outputTo, err := cdc.MarshalJSON(red) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + output = append(output, outputTo...) } + } + if len(output) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + // success + w.Write(output) // write + } + } +} - // All redelegations to destination validator (i.e bonding) - res, err = ctx.QueryStore(keyValidatorTo, storeName) +// HTTP request handler to query all staking txs (msgs) from a delegator +func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var output []byte + var typesQuerySlice []string + vars := mux.Vars(r) + bech32delegator := vars["addr"] + + delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + + node, err := ctx.GetNode() + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Couldn't get current Node information. Error: %s", err.Error()))) + return + } + + // Get values from query + + typesQuery := r.URL.Query().Get("type") + typesQuerySlice = strings.Split(strings.TrimSpace(typesQuery), " ") + + query := sdk.TagDelegator + " " + delegatorAddr.String() + noQuery := len(typesQuerySlice) == 0 + isBondTx := contains(typesQuerySlice, "bond") + isUnbondTx := contains(typesQuerySlice, "unbond") + isRedTx := contains(typesQuerySlice, "redelegate") + if !isBondTx || !isUnbondTx || !isRedTx { + w.WriteHeader(http.StatusNoContent) + return + } + + // TODO double check this + if noQuery || isBondTx { + query = query + " ANY " + sdk.TagAction + query = query + " delegate" + } + if noQuery || isUnbondTx { + query = query + " AND " + sdk.TagAction + query = query + " begin-unbonding" + + query = query + " OR " + sdk.TagAction + query = query + " complete-unbonding" + } + if noQuery || isRedTx { + query = query + " AND " + sdk.TagAction + query = query + " begin-redelegation" + + query = query + " OR " + sdk.TagAction + query = query + " complete-redelegation" + } + + page := 0 + perPage := 100 + prove := false + res, err := node.TxSearch(query, prove, page, perPage) + if err != nil { + w.WriteHeader(http.StatusNoContent) + return + } + + info, err := formatTxResults(cdc, res.Txs) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query txs. Error: %s", err.Error()))) + return + } + // success + output, err = cdc.MarshalJSON(info) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + w.Write(output) // write + } +} + +// HTTP request handler to query all delegator bonded validators +func delegatorValidatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var isBonded bool + var validatorAddr sdk.AccAddress + var bondedValidators []sdk.Validator + var output []byte // validators + var typesQuerySlice []string + + // read parameters + vars := mux.Vars(r) + bech32delegator := vars["delegatorAddr"] + + delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + + // Get all validators using key + kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query validators. Error: %s", err.Error()))) + return + } + + // the query will return empty if there are no validators + if len(kvs) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + + validators, err := getValidators(kvs, cdc) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return + } + + for i, validator := range validators { + // get all transactions from the delegator to val and append + isBonded = false + validatorAddr = validator.Owner + + // Check if there if the delegator is bonded or redelegated to the validator + + keyDel := stake.GetDelegationKey(delegatorAddr, validatorAddr) + keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) + + res, err := ctx.QueryStore(keyDel, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + return + } + + if len(res) != 0 { + isBonded = true + } + + if !isBonded { + res, err = ctx.QueryStore(keyRed, storeName) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) return } - // the query will return empty if there is no data for this record - if len(res) == 0 { - w.WriteHeader(http.StatusNoContent) - return + if len(res) != 0 { + isBonded = true } + } - red, err = types.UnmarshalRED(cdc, keyValidatorTo, res) + if isBonded { + kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) return } - outputTo, err := cdc.MarshalJSON(red) + // the query will return empty if there are no validators + if len(kvs) == 0 { + continue + } + validator, err := getValidator(validatorAddr, kvs, cdc) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) + w.Write([]byte(fmt.Sprintf("Couldn't get info from validator %s. Error: %s", validatorAddr.String(), err.Error()))) return + } else if validator == nil && err == nil { + continue } - - // All redelegations From or To the given validator address - output = append(outputFrom, outputTo...) + bondedValidators = append(bondedValidators, validator) } - w.Write(output) // write } - + // success + output, err = cdc.MarshalJSON(bondedValidators) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + w.Write(output) // write } } -// HTTP request handler to query list of validators +// HTTP request handler to query a bonded validator func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // read parameters @@ -345,6 +535,7 @@ func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http. } } +// TODO Rename func stakingTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { @@ -376,138 +567,7 @@ func stakingTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF isBondTx := contains(typesQuerySlice, "bond") isUnbondTx := contains(typesQuerySlice, "unbond") isRedTx := contains(typesQuerySlice, "redelegate") - if !isBondTx || !isUnbondTx || !isRedTx { - w.WriteHeader(http.StatusNoContent) - return - } - - // delegation - if noQuery || isBondTx { - key := stake.GetDelegationKey(delegatorAddr, validatorAddr) - - res, err := ctx.QueryStore(key, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) - return - } - // the query will return empty if there is no data for this record - if len(res) == 0 { - w.WriteHeader(http.StatusNoContent) - return - } - - delegation, err := types.UnmarshalDelegation(cdc, key, res) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - outputBond, err := cdc.MarshalJSON(delegation) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - output = append(output, outputBond...) - } - if noQuery || isUnbondTx { - - key := stake.GetUBDKey(delegatorAddr, validatorAddr) - - res, err := ctx.QueryStore(key, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return - } - - // the query will return empty if there is no data for this record - if len(res) == 0 { - w.WriteHeader(http.StatusNoContent) - return - } - - ubd, err := types.UnmarshalUBD(cdc, key, res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return - } - - outputUnbond, err := cdc.MarshalJSON(ubd) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - output = append(output, outputUnbond...) - } - if noQuery || isRedTx { - // keyValidatorFrom := stake.GetREDsByDelFromValSrcIndexKey(delegatorAddr, validatorAddr) - keyValidatorTo := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) - - // All redelegations from source validator (i.e unbonding) - res, err := ctx.QueryStore(keyValidatorFrom, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) - return - } - - // the query will return empty if there is no data for this record - if len(res) == 0 { - w.WriteHeader(http.StatusNoContent) - return - } - - red, err := types.UnmarshalRED(cdc, keyValidatorFrom, res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return - } - - outputFrom, err := cdc.MarshalJSON(red) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - // All redelegations to destination validator (i.e bonding) - res, err = ctx.QueryStore(keyValidatorTo, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) - return - } - - // the query will return empty if there is no data for this record - if len(res) == 0 { - w.WriteHeader(http.StatusNoContent) - return - } - - red, err = types.UnmarshalRED(cdc, keyValidatorTo, res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return - } - - outputTo, err := cdc.MarshalJSON(red) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - // All redelegations From or To the given validator address - output := append(outputFrom, outputTo...) - } w.Write(output) } } From 0174084f635a04fa6875adcf2ef25f89a162a220 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 30 Jul 2018 18:45:23 +0200 Subject: [PATCH 05/46] Moved staking LCD tests to module --- Gopkg.lock | 197 +++-------------- client/lcd/lcd_test.go | 191 ----------------- x/stake/client/rest/lcd_test.go | 315 ++++++++++++++++++++++++++++ x/stake/client/rest/test_helpers.go | 287 +++++++++++++++++++++++++ x/stake/client/rest/utils.go | 49 +++++ 5 files changed, 677 insertions(+), 362 deletions(-) create mode 100644 x/stake/client/rest/lcd_test.go create mode 100644 x/stake/client/rest/test_helpers.go diff --git a/Gopkg.lock b/Gopkg.lock index e6f15683550e..86b75ba33652 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -2,76 +2,57 @@ [[projects]] - digest = "1:09a7f74eb6bb3c0f14d8926610c87f569c5cff68e978d30e9a3540aeb626fdf0" name = "github.com/bartekn/go-bip39" packages = ["."] - pruneopts = "UT" revision = "a05967ea095d81c8fe4833776774cfaff8e5036c" [[projects]] branch = "master" - digest = "1:d6afaeed1502aa28e80a4ed0981d570ad91b2579193404256ce672ed0a609e0d" name = "github.com/beorn7/perks" packages = ["quantile"] - pruneopts = "UT" revision = "3a771d992973f24aa725d07868b467d1ddfceafb" [[projects]] - digest = "1:1343a2963481a305ca4d051e84bc2abd16b601ee22ed324f8d605de1adb291b0" name = "github.com/bgentry/speakeasy" packages = ["."] - pruneopts = "UT" revision = "4aabc24848ce5fd31929f7d1e4ea74d3709c14cd" version = "v0.1.0" [[projects]] branch = "master" - digest = "1:70f6b224a59b2fa453debffa85c77f71063d8754b90c8c4fbad5794e2c382b0f" name = "github.com/brejski/hid" packages = ["."] - pruneopts = "UT" revision = "06112dcfcc50a7e0e4fd06e17f9791e788fdaafc" [[projects]] branch = "master" - digest = "1:2c00f064ba355903866cbfbf3f7f4c0fe64af6638cc7d1b8bdcf3181bc67f1d8" name = "github.com/btcsuite/btcd" packages = ["btcec"] - pruneopts = "UT" revision = "fdfc19097e7ac6b57035062056f5b7b4638b8898" [[projects]] - digest = "1:386de157f7d19259a7f9c81f26ce011223ce0f090353c1152ffdf730d7d10ac2" name = "github.com/btcsuite/btcutil" packages = ["bech32"] - pruneopts = "UT" revision = "d4cc87b860166d00d6b5b9e0d3b3d71d6088d4d4" [[projects]] - digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39" name = "github.com/davecgh/go-spew" packages = ["spew"] - pruneopts = "UT" revision = "346938d642f2ec3594ed81d874461961cd0faa76" version = "v1.1.0" [[projects]] - digest = "1:c7644c73a3d23741fdba8a99b1464e021a224b7e205be497271a8003a15ca41b" name = "github.com/ebuchman/fail-test" packages = ["."] - pruneopts = "UT" revision = "95f809107225be108efcf10a3509e4ea6ceef3c4" [[projects]] - digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd" name = "github.com/fsnotify/fsnotify" packages = ["."] - pruneopts = "UT" revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" version = "v1.4.7" [[projects]] - digest = "1:fdf5169073fb0ad6dc12a70c249145e30f4058647bea25f0abd48b6d9f228a11" name = "github.com/go-kit/kit" packages = [ "log", @@ -80,30 +61,24 @@ "metrics", "metrics/discard", "metrics/internal/lv", - "metrics/prometheus", + "metrics/prometheus" ] - pruneopts = "UT" revision = "4dc7be5d2d12881735283bcab7352178e190fc71" version = "v0.6.0" [[projects]] - digest = "1:31a18dae27a29aa074515e43a443abfd2ba6deb6d69309d8d7ce789c45f34659" name = "github.com/go-logfmt/logfmt" packages = ["."] - pruneopts = "UT" revision = "390ab7935ee28ec6b286364bba9b4dd6410cb3d5" version = "v0.3.0" [[projects]] - digest = "1:c4a2528ccbcabf90f9f3c464a5fc9e302d592861bbfd0b7135a7de8a943d0406" name = "github.com/go-stack/stack" packages = ["."] - pruneopts = "UT" revision = "259ab82a6cad3992b4e21ff5cac294ccb06474bc" version = "v1.7.0" [[projects]] - digest = "1:35621fe20f140f05a0c4ef662c26c0ab4ee50bca78aa30fe87d33120bd28165e" name = "github.com/gogo/protobuf" packages = [ "gogoproto", @@ -111,61 +86,49 @@ "proto", "protoc-gen-gogo/descriptor", "sortkeys", - "types", + "types" ] - pruneopts = "UT" revision = "636bf0302bc95575d69441b25a2603156ffdddf1" version = "v1.1.1" [[projects]] - digest = "1:17fe264ee908afc795734e8c4e63db2accabaf57326dbf21763a7d6b86096260" name = "github.com/golang/protobuf" packages = [ "proto", "ptypes", "ptypes/any", "ptypes/duration", - "ptypes/timestamp", + "ptypes/timestamp" ] - pruneopts = "UT" revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" version = "v1.1.0" [[projects]] branch = "master" - digest = "1:4a0c6bb4805508a6287675fac876be2ac1182539ca8a32468d8128882e9d5009" name = "github.com/golang/snappy" packages = ["."] - pruneopts = "UT" revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" [[projects]] - digest = "1:c79fb010be38a59d657c48c6ba1d003a8aa651fa56b579d959d74573b7dff8e1" name = "github.com/gorilla/context" packages = ["."] - pruneopts = "UT" revision = "08b5f424b9271eedf6f9f0ce86cb9396ed337a42" version = "v1.1.1" [[projects]] - digest = "1:e73f5b0152105f18bc131fba127d9949305c8693f8a762588a82a48f61756f5f" name = "github.com/gorilla/mux" packages = ["."] - pruneopts = "UT" revision = "e3702bed27f0d39777b0b37b664b6280e8ef8fbf" version = "v1.6.2" [[projects]] - digest = "1:43dd08a10854b2056e615d1b1d22ac94559d822e1f8b6fcc92c1a1057e85188e" name = "github.com/gorilla/websocket" packages = ["."] - pruneopts = "UT" revision = "ea4d1f681babbce9545c9c5f3d5194a789c89f5b" version = "v1.2.0" [[projects]] branch = "master" - digest = "1:12247a2e99a060cc692f6680e5272c8adf0b8f572e6bce0d7095e624c958a240" name = "github.com/hashicorp/hcl" packages = [ ".", @@ -176,206 +139,160 @@ "hcl/token", "json/parser", "json/scanner", - "json/token", + "json/token" ] - pruneopts = "UT" revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" [[projects]] - digest = "1:870d441fe217b8e689d7949fef6e43efbc787e50f200cb1e70dbca9204a1d6be" name = "github.com/inconshreveable/mousetrap" packages = ["."] - pruneopts = "UT" revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75" version = "v1.0" [[projects]] branch = "master" - digest = "1:39b27d1381a30421f9813967a5866fba35dc1d4df43a6eefe3b7a5444cb07214" name = "github.com/jmhodges/levigo" packages = ["."] - pruneopts = "UT" revision = "c42d9e0ca023e2198120196f842701bb4c55d7b9" [[projects]] branch = "master" - digest = "1:a64e323dc06b73892e5bb5d040ced475c4645d456038333883f58934abbf6f72" name = "github.com/kr/logfmt" packages = ["."] - pruneopts = "UT" revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0" [[projects]] - digest = "1:c568d7727aa262c32bdf8a3f7db83614f7af0ed661474b24588de635c20024c7" name = "github.com/magiconair/properties" packages = ["."] - pruneopts = "UT" revision = "c2353362d570a7bfa228149c62842019201cfb71" version = "v1.8.0" [[projects]] - digest = "1:d4d17353dbd05cb52a2a52b7fe1771883b682806f68db442b436294926bbfafb" name = "github.com/mattn/go-isatty" packages = ["."] - pruneopts = "UT" revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" version = "v0.0.3" [[projects]] - digest = "1:ff5ebae34cfbf047d505ee150de27e60570e8c394b3b8fdbb720ff6ac71985fc" name = "github.com/matttproud/golang_protobuf_extensions" packages = ["pbutil"] - pruneopts = "UT" revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" version = "v1.0.1" [[projects]] branch = "master" - digest = "1:e730597b38a4d56e2361e0b6236cb800e52c73cace2ff91396f4ff35792ddfa7" name = "github.com/mitchellh/mapstructure" packages = ["."] - pruneopts = "UT" revision = "bb74f1db0675b241733089d5a1faa5dd8b0ef57b" [[projects]] - digest = "1:95741de3af260a92cc5c7f3f3061e85273f5a81b5db20d4bd68da74bd521675e" name = "github.com/pelletier/go-toml" packages = ["."] - pruneopts = "UT" revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194" version = "v1.2.0" [[projects]] - digest = "1:40e195917a951a8bf867cd05de2a46aaf1806c50cf92eebf4c16f78cd196f747" name = "github.com/pkg/errors" packages = ["."] - pruneopts = "UT" revision = "645ef00459ed84a119197bfb8d8205042c6df63d" version = "v0.8.0" [[projects]] - digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" name = "github.com/pmezard/go-difflib" packages = ["difflib"] - pruneopts = "UT" revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" [[projects]] - digest = "1:c1a04665f9613e082e1209cf288bf64f4068dcd6c87a64bf1c4ff006ad422ba0" name = "github.com/prometheus/client_golang" packages = [ "prometheus", - "prometheus/promhttp", + "prometheus/promhttp" ] - pruneopts = "UT" revision = "ae27198cdd90bf12cd134ad79d1366a6cf49f632" [[projects]] branch = "master" - digest = "1:32d10bdfa8f09ecf13598324dba86ab891f11db3c538b6a34d1c3b5b99d7c36b" name = "github.com/prometheus/client_model" packages = ["go"] - pruneopts = "UT" revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c" [[projects]] branch = "master" - digest = "1:e469cd65badf7694aeb44874518606d93c1d59e7735d3754ad442782437d3cc3" name = "github.com/prometheus/common" packages = [ "expfmt", "internal/bitbucket.org/ww/goautoneg", - "model", + "model" ] - pruneopts = "UT" revision = "7600349dcfe1abd18d72d3a1770870d9800a7801" [[projects]] branch = "master" - digest = "1:20d9bb50dbee172242f9bcd6ec24a917dd7a5bb17421bf16a79c33111dea7db1" name = "github.com/prometheus/procfs" packages = [ ".", "internal/util", "nfs", - "xfs", + "xfs" ] - pruneopts = "UT" revision = "ae68e2d4c00fed4943b5f6698d504a5fe083da8a" [[projects]] - digest = "1:c4556a44e350b50a490544d9b06e9fba9c286c21d6c0e47f54f3a9214597298c" name = "github.com/rcrowley/go-metrics" packages = ["."] - pruneopts = "UT" revision = "e2704e165165ec55d062f5919b4b29494e9fa790" [[projects]] - digest = "1:bd1ae00087d17c5a748660b8e89e1043e1e5479d0fea743352cda2f8dd8c4f84" name = "github.com/spf13/afero" packages = [ ".", - "mem", + "mem" ] - pruneopts = "UT" revision = "787d034dfe70e44075ccc060d346146ef53270ad" version = "v1.1.1" [[projects]] - digest = "1:516e71bed754268937f57d4ecb190e01958452336fa73dbac880894164e91c1f" name = "github.com/spf13/cast" packages = ["."] - pruneopts = "UT" revision = "8965335b8c7107321228e3e3702cab9832751bac" version = "v1.2.0" [[projects]] - digest = "1:7ffc0983035bc7e297da3688d9fe19d60a420e9c38bef23f845c53788ed6a05e" name = "github.com/spf13/cobra" packages = ["."] - pruneopts = "UT" revision = "7b2c5ac9fc04fc5efafb60700713d4fa609b777b" version = "v0.0.1" [[projects]] branch = "master" - digest = "1:080e5f630945ad754f4b920e60b4d3095ba0237ebf88dc462eb28002932e3805" name = "github.com/spf13/jwalterweatherman" packages = ["."] - pruneopts = "UT" revision = "7c0cea34c8ece3fbeb2b27ab9b59511d360fb394" [[projects]] - digest = "1:9424f440bba8f7508b69414634aef3b2b3a877e522d8a4624692412805407bb7" name = "github.com/spf13/pflag" packages = ["."] - pruneopts = "UT" revision = "583c0c0531f06d5278b7d917446061adc344b5cd" version = "v1.0.1" [[projects]] - digest = "1:f8e1a678a2571e265f4bf91a3e5e32aa6b1474a55cb0ea849750cc177b664d96" name = "github.com/spf13/viper" packages = ["."] - pruneopts = "UT" revision = "25b30aa063fc18e48662b86996252eabdcf2f0c7" version = "v1.0.0" [[projects]] - digest = "1:7e8d267900c7fa7f35129a2a37596e38ed0f11ca746d6d9ba727980ee138f9f6" name = "github.com/stretchr/testify" packages = [ "assert", - "require", + "require" ] - pruneopts = "UT" revision = "12b6f73e6084dad08a7c6e575284b177ecafbc71" version = "v1.2.1" [[projects]] branch = "master" - digest = "1:b3cfb8d82b1601a846417c3f31c03a7961862cb2c98dcf0959c473843e6d9a2b" name = "github.com/syndtr/goleveldb" packages = [ "leveldb", @@ -389,41 +306,33 @@ "leveldb/opt", "leveldb/storage", "leveldb/table", - "leveldb/util", + "leveldb/util" ] - pruneopts = "UT" revision = "c4c61651e9e37fa117f53c5a906d3b63090d8445" [[projects]] branch = "master" - digest = "1:087aaa7920e5d0bf79586feb57ce01c35c830396ab4392798112e8aae8c47722" name = "github.com/tendermint/ed25519" packages = [ ".", "edwards25519", - "extra25519", + "extra25519" ] - pruneopts = "UT" revision = "d8387025d2b9d158cf4efb07e7ebf814bcce2057" [[projects]] - digest = "1:e9113641c839c21d8eaeb2c907c7276af1eddeed988df8322168c56b7e06e0e1" name = "github.com/tendermint/go-amino" packages = ["."] - pruneopts = "UT" revision = "2106ca61d91029c931fd54968c2bb02dc96b1412" version = "0.10.1" [[projects]] - digest = "1:d4a15d404afbf591e8be16fcda7f5ac87948d5c7531f9d909fd84cc730ab16e2" name = "github.com/tendermint/iavl" packages = ["."] - pruneopts = "UT" revision = "35f66e53d9b01e83b30de68b931f54b2477a94c9" version = "v0.9.2" [[projects]] - digest = "1:e10e95fd9f0a3a31686c9696f8995f6c04b0bc1b4ed0562a4f53cddc0b89d059" name = "github.com/tendermint/tendermint" packages = [ "abci/client", @@ -483,22 +392,27 @@ "state/txindex/kv", "state/txindex/null", "types", - "version", + "version" ] - pruneopts = "UT" revision = "5fdbcd70df57b71ffba71e1ff5f00d617852a9c0" version = "v0.22.6" [[projects]] - digest = "1:5bd938386bd1f61a581bf8cd6ff2b7b2f79c542929176db4ceb44965440dae07" + name = "github.com/tendermint/tmlibs" + packages = [ + "common", + "log" + ] + revision = "49596e0a1f48866603813df843c9409fc19805c6" + version = "v0.9.0" + +[[projects]] name = "github.com/zondax/ledger-goclient" packages = ["."] - pruneopts = "UT" revision = "39ba4728c137c75718a21f9b4b3280fa31b9139b" [[projects]] branch = "master" - digest = "1:65a21a9e051d54eb6a3f70c659a765f706a998d9287c302269f4ed8054b2a852" name = "golang.org/x/crypto" packages = [ "blowfish", @@ -511,13 +425,11 @@ "pbkdf2", "poly1305", "ripemd160", - "salsa20/salsa", + "salsa20/salsa" ] - pruneopts = "UT" revision = "a49355c7e3f8fe157a85be2f77e6e269a0f89602" [[projects]] - digest = "1:d36f55a999540d29b6ea3c2ea29d71c76b1d9853fdcd3e5c5cb4836f2ba118f1" name = "golang.org/x/net" packages = [ "context", @@ -527,21 +439,17 @@ "idna", "internal/timeseries", "netutil", - "trace", + "trace" ] - pruneopts = "UT" revision = "292b43bbf7cb8d35ddf40f8d5100ef3837cced3f" [[projects]] branch = "master" - digest = "1:d773e525476aefa22ea944a5425a9bfb99819b2e67eeb9b1966454fd57522bbf" name = "golang.org/x/sys" packages = ["unix"] - pruneopts = "UT" revision = "1b2967e3c290b7c545b3db0deeda16e9be4f98a2" [[projects]] - digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" name = "golang.org/x/text" packages = [ "collate", @@ -557,22 +465,18 @@ "unicode/bidi", "unicode/cldr", "unicode/norm", - "unicode/rangetable", + "unicode/rangetable" ] - pruneopts = "UT" revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" version = "v0.3.0" [[projects]] branch = "master" - digest = "1:601e63e7d4577f907118bec825902505291918859d223bce015539e79f1160e3" name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] - pruneopts = "UT" revision = "e92b116572682a5b432ddd840aeaba2a559eeff1" [[projects]] - digest = "1:2dab32a43451e320e49608ff4542fdfc653c95dcc35d0065ec9c6c3dd540ed74" name = "google.golang.org/grpc" packages = [ ".", @@ -599,69 +503,20 @@ "stats", "status", "tap", - "transport", + "transport" ] - pruneopts = "UT" revision = "168a6198bcb0ef175f7dacec0b8691fc141dc9b8" version = "v1.13.0" [[projects]] - digest = "1:342378ac4dcb378a5448dd723f0784ae519383532f5e70ade24132c4c8693202" name = "gopkg.in/yaml.v2" packages = ["."] - pruneopts = "UT" revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" version = "v2.2.1" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - input-imports = [ - "github.com/bartekn/go-bip39", - "github.com/bgentry/speakeasy", - "github.com/btcsuite/btcd/btcec", - "github.com/golang/protobuf/proto", - "github.com/gorilla/mux", - "github.com/mattn/go-isatty", - "github.com/pkg/errors", - "github.com/spf13/cobra", - "github.com/spf13/pflag", - "github.com/spf13/viper", - "github.com/stretchr/testify/assert", - "github.com/stretchr/testify/require", - "github.com/tendermint/go-amino", - "github.com/tendermint/iavl", - "github.com/tendermint/tendermint/abci/server", - "github.com/tendermint/tendermint/abci/types", - "github.com/tendermint/tendermint/cmd/tendermint/commands", - "github.com/tendermint/tendermint/config", - "github.com/tendermint/tendermint/crypto", - "github.com/tendermint/tendermint/crypto/armor", - "github.com/tendermint/tendermint/crypto/ed25519", - "github.com/tendermint/tendermint/crypto/encoding/amino", - "github.com/tendermint/tendermint/crypto/merkle", - "github.com/tendermint/tendermint/crypto/secp256k1", - "github.com/tendermint/tendermint/crypto/tmhash", - "github.com/tendermint/tendermint/crypto/xsalsa20symmetric", - "github.com/tendermint/tendermint/libs/bech32", - "github.com/tendermint/tendermint/libs/cli", - "github.com/tendermint/tendermint/libs/cli/flags", - "github.com/tendermint/tendermint/libs/common", - "github.com/tendermint/tendermint/libs/db", - "github.com/tendermint/tendermint/libs/log", - "github.com/tendermint/tendermint/node", - "github.com/tendermint/tendermint/p2p", - "github.com/tendermint/tendermint/privval", - "github.com/tendermint/tendermint/proxy", - "github.com/tendermint/tendermint/rpc/client", - "github.com/tendermint/tendermint/rpc/core/types", - "github.com/tendermint/tendermint/rpc/lib/client", - "github.com/tendermint/tendermint/rpc/lib/server", - "github.com/tendermint/tendermint/types", - "github.com/tendermint/tendermint/version", - "github.com/zondax/ledger-goclient", - "golang.org/x/crypto/blowfish", - "golang.org/x/crypto/ripemd160", - ] + inputs-digest = "a74828152213e53070f4d5fd94dbf37b58c44743558c62ee0d1be99f470e0070" solver-name = "gps-cdcl" solver-version = 1 diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 87566cff9335..e72d522b06d7 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -26,7 +26,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/stake" ) func init() { @@ -374,56 +373,6 @@ func TestValidatorsQuery(t *testing.T) { require.True(t, foundVal, "pkBech %v, owner %v", pkBech, validators[0].Owner) } -func TestBonding(t *testing.T) { - name, password, denom := "test", "1234567890", "steak" - addr, seed := CreateAddr(t, "test", password, GetKeyBase(t)) - cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) - defer cleanup() - - validator1Owner := sdk.AccAddress(pks[0].Address()) - - // create bond TX - resultTx := doDelegate(t, port, seed, name, password, addr, validator1Owner) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.CheckTx.Code) - require.Equal(t, uint32(0), resultTx.DeliverTx.Code) - - // query sender - acc := getAccount(t, port, addr) - coins := acc.GetCoins() - - require.Equal(t, int64(40), coins.AmountOf(denom).Int64()) - - // query validator - bond := getDelegation(t, port, addr, validator1Owner) - require.Equal(t, "60/1", bond.Shares.String()) - - ////////////////////// - // testing unbonding - - // create unbond TX - resultTx = doBeginUnbonding(t, port, seed, name, password, addr, validator1Owner) - tests.WaitForHeight(resultTx.Height+1, port) - - // query validator - bond = getDelegation(t, port, addr, validator1Owner) - require.Equal(t, "30/1", bond.Shares.String()) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.CheckTx.Code) - require.Equal(t, uint32(0), resultTx.DeliverTx.Code) - - // should the sender should have not received any coins as the unbonding has only just begun - // query sender - acc = getAccount(t, port, addr) - coins = acc.GetCoins() - require.Equal(t, int64(40), coins.AmountOf("steak").Int64()) - - // TODO add redelegation, need more complex capabilities such to mock context and -} - func TestSubmitProposal(t *testing.T) { name, password := "test", "1234567890" addr, seed := CreateAddr(t, "test", password, GetKeyBase(t)) @@ -719,146 +668,6 @@ func getSigningInfo(t *testing.T, port string, validatorAddr sdk.ValAddress) sla return signingInfo } -func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.AccAddress) stake.Delegation { - - // get the account to get the sequence - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/%s/delegation/%s", delegatorAddr, validatorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var bond stake.Delegation - err := cdc.UnmarshalJSON([]byte(body), &bond) - require.Nil(t, err) - return bond -} - -func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { - // get the account to get the sequence - acc := getAccount(t, port, delegatorAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - - chainID := viper.GetString(client.FlagChainID) - - // send - jsonStr := []byte(fmt.Sprintf(`{ - "name": "%s", - "password": "%s", - "account_number": "%d", - "sequence": "%d", - "gas": "10000", - "chain_id": "%s", - "delegations": [ - { - "delegator_addr": "%s", - "validator_addr": "%s", - "delegation": { "denom": "%s", "amount": "60" } - } - ], - "begin_unbondings": [], - "complete_unbondings": [], - "begin_redelegates": [], - "complete_redelegates": [] - }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr, "steak")) - res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var results []ctypes.ResultBroadcastTxCommit - err := cdc.UnmarshalJSON([]byte(body), &results) - require.Nil(t, err) - - return results[0] -} - -func doBeginUnbonding(t *testing.T, port, seed, name, password string, - delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { - - // get the account to get the sequence - acc := getAccount(t, port, delegatorAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - - chainID := viper.GetString(client.FlagChainID) - - // send - jsonStr := []byte(fmt.Sprintf(`{ - "name": "%s", - "password": "%s", - "account_number": "%d", - "sequence": "%d", - "gas": "20000", - "chain_id": "%s", - "delegations": [], - "begin_unbondings": [ - { - "delegator_addr": "%s", - "validator_addr": "%s", - "shares": "30" - } - ], - "complete_unbondings": [], - "begin_redelegates": [], - "complete_redelegates": [] - }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr)) - res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var results []ctypes.ResultBroadcastTxCommit - err := cdc.UnmarshalJSON([]byte(body), &results) - require.Nil(t, err) - - return results[0] -} - -func doBeginRedelegation(t *testing.T, port, seed, name, password string, - delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { - - // get the account to get the sequence - acc := getAccount(t, port, delegatorAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - - chainID := viper.GetString(client.FlagChainID) - - // send - jsonStr := []byte(fmt.Sprintf(`{ - "name": "%s", - "password": "%s", - "account_number": "%d", - "sequence": "%d", - "gas": "10000", - "chain_id": "%s", - "delegations": [], - "begin_unbondings": [], - "complete_unbondings": [], - "begin_redelegates": [ - { - "delegator_addr": "%s", - "validator_src_addr": "%s", - "validator_dst_addr": "%s", - "shares": "30" - } - ], - "complete_redelegates": [] - }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorSrcAddr, validatorDstAddr)) - res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var results []ctypes.ResultBroadcastTxCommit - err := cdc.UnmarshalJSON([]byte(body), &results) - require.Nil(t, err) - - return results[0] -} - -func getValidators(t *testing.T, port string) []stake.BechValidator { - // get the account to get the sequence - res, body := Request(t, port, "GET", "/stake/validators", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var validators []stake.BechValidator - err := cdc.UnmarshalJSON([]byte(body), &validators) - require.Nil(t, err) - return validators -} - func getProposal(t *testing.T, port string, proposalID int64) gov.Proposal { res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d", proposalID), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) diff --git a/x/stake/client/rest/lcd_test.go b/x/stake/client/rest/lcd_test.go new file mode 100644 index 000000000000..8ef80d8013d2 --- /dev/null +++ b/x/stake/client/rest/lcd_test.go @@ -0,0 +1,315 @@ +package rest + +import ( + "fmt" + "net/http" + "testing" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/tests" + "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/spf13/viper" + "github.com/stretchr/testify/require" + "github.com/tendermint/tmlibs/common" +) + +// import ( +// "encoding/hex" +// "fmt" +// "net/http" +// "regexp" +// "testing" +// +// "github.com/spf13/viper" +// "github.com/stretchr/testify/assert" +// "github.com/stretchr/testify/require" +// +// cryptoKeys "github.com/cosmos/cosmos-sdk/crypto/keys" +// abci "github.com/tendermint/tendermint/abci/types" +// "github.com/tendermint/tendermint/libs/common" +// p2p "github.com/tendermint/tendermint/p2p" +// ctypes "github.com/tendermint/tendermint/rpc/core/types" +// +// client "github.com/cosmos/cosmos-sdk/client" +// keys "github.com/cosmos/cosmos-sdk/client/keys" +// rpc "github.com/cosmos/cosmos-sdk/client/rpc" +// tests "github.com/cosmos/cosmos-sdk/tests" +// sdk "github.com/cosmos/cosmos-sdk/types" +// "github.com/cosmos/cosmos-sdk/wire" +// "github.com/cosmos/cosmos-sdk/x/slashing" +// ) + +func TestStakingTxs(t *testing.T) { + name, password := "test", "1234567890" + addr, seed := CreateAddr(t, "test", password, GetKeyBase(t)) + cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) + defer cleanup() + + // query empty + res, body = Request(t, port, "GET", fmt.Sprintf("stake/delegators/'%s'/txs", "cosmosaccaddr1jawd35d9aq4u76sr3fjalmcqc8hqygs9gtnmv3"), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + require.Equal(t, "[]", body) + + // query empty bonding txs + res, body = Request(t, port, "GET", fmt.Sprintf("stake/delegators/'%s'/txs?type=bond", "cosmosaccaddr1jawd35d9aq4u76sr3fjalmcqc8hqygs9gtnmv3"), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + require.Equal(t, "[]", body) + + // query empty unbonding txs + res, body = Request(t, port, "GET", fmt.Sprintf("stake/delegators/'%s'/txs?type=unbond", "cosmosaccaddr1jawd35d9aq4u76sr3fjalmcqc8hqygs9gtnmv3"), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + require.Equal(t, "[]", body) + + // query empty redelegation txs + res, body = Request(t, port, "GET", fmt.Sprintf("stake/delegators/'%s'/txs?type=redelegate", "cosmosaccaddr1jawd35d9aq4u76sr3fjalmcqc8hqygs9gtnmv3"), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + require.Equal(t, "[]", body) + + // create TX + receiveAddr, resultTx := doSend(t, port, seed, name, password, addr) + + tests.WaitForHeight(resultTx.Height+1, port) + + // check if tx is findable + res, body = Request(t, port, "GET", fmt.Sprintf("/txs/%s", resultTx.Hash), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + + type txInfo struct { + Hash common.HexBytes `json:"hash"` + Height int64 `json:"height"` + Tx sdk.Tx `json:"tx"` + Result abci.ResponseDeliverTx `json:"result"` + } + var indexedTxs []txInfo + + // check if tx is queryable + res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=tx.hash='%s'", resultTx.Hash), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + require.NotEqual(t, "[]", body) + + err := cdc.UnmarshalJSON([]byte(body), &indexedTxs) + require.NoError(t, err) + require.Equal(t, 1, len(indexedTxs)) + + // XXX should this move into some other testfile for txs in general? + // test if created TX hash is the correct hash + require.Equal(t, resultTx.Hash, indexedTxs[0].Hash) + + // query sender + // also tests url decoding + res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=sender_bech32=%%27%s%%27", addr), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + + err = cdc.UnmarshalJSON([]byte(body), &indexedTxs) + require.NoError(t, err) + require.Equal(t, 1, len(indexedTxs), "%v", indexedTxs) // there are 2 txs created with doSend + require.Equal(t, resultTx.Height, indexedTxs[0].Height) + + // query recipient + res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=recipient_bech32='%s'", receiveAddr), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + + err = cdc.UnmarshalJSON([]byte(body), &indexedTxs) + require.NoError(t, err) + require.Equal(t, 1, len(indexedTxs)) + require.Equal(t, resultTx.Height, indexedTxs[0].Height) +} + +func TestBonding(t *testing.T) { + name, password, denom := "test", "1234567890", "steak" + addr, seed := CreateAddr(t, "test", password, GetKeyBase(t)) + cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) + defer cleanup() + + validator1Owner := sdk.AccAddress(pks[0].Address()) + + // create bond TX + resultTx := doDelegate(t, port, seed, name, password, addr, validator1Owner) + tests.WaitForHeight(resultTx.Height+1, port) + + // check if tx was committed + require.Equal(t, uint32(0), resultTx.CheckTx.Code) + require.Equal(t, uint32(0), resultTx.DeliverTx.Code) + + // query sender + acc := getAccount(t, port, addr) + coins := acc.GetCoins() + + require.Equal(t, int64(40), coins.AmountOf(denom).Int64()) + + // query validator + bond := getDelegation(t, port, addr, validator1Owner) + require.Equal(t, "60/1", bond.Shares.String()) + + // query bonding tx + res, body = Request(t, port, "GET", fmt.Sprintf("stake/delegators/'%s'/txs", "cosmosaccaddr1jawd35d9aq4u76sr3fjalmcqc8hqygs9gtnmv3"), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + require.Equal(t, "[]", body) + + res, body = Request(t, port, "GET", fmt.Sprintf("stake/delegators/'%s'/validators/'%s'/txs", "cosmosaccaddr1jawd35d9aq4u76sr3fjalmcqc8hqygs9gtnmv3"), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + require.Equal(t, "[]", body) + + ////////////////////// + // testing unbonding + + // create unbond TX + resultTx = doBeginUnbonding(t, port, seed, name, password, addr, validator1Owner) + tests.WaitForHeight(resultTx.Height+1, port) + + // query validator + bond = getDelegation(t, port, addr, validator1Owner) + require.Equal(t, "30/1", bond.Shares.String()) + + // check if tx was committed + require.Equal(t, uint32(0), resultTx.CheckTx.Code) + require.Equal(t, uint32(0), resultTx.DeliverTx.Code) + + // should the sender should have not received any coins as the unbonding has only just begun + // query sender + acc = getAccount(t, port, addr) + coins = acc.GetCoins() + require.Equal(t, int64(40), coins.AmountOf("steak").Int64()) + + // TODO add redelegation, need more complex capabilities such to mock context and +} + +func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.AccAddress) stake.Delegation { + + // get the account to get the sequence + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/%s/delegation/%s", delegatorAddr, validatorAddr), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + var bond stake.Delegation + err := cdc.UnmarshalJSON([]byte(body), &bond) + require.Nil(t, err) + return bond +} + +func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { + // get the account to get the sequence + acc := getAccount(t, port, delegatorAddr) + accnum := acc.GetAccountNumber() + sequence := acc.GetSequence() + + chainID := viper.GetString(client.FlagChainID) + + // send + jsonStr := []byte(fmt.Sprintf(`{ + "name": "%s", + "password": "%s", + "account_number": "%d", + "sequence": "%d", + "gas": "10000", + "chain_id": "%s", + "delegations": [ + { + "delegator_addr": "%s", + "validator_addr": "%s", + "delegation": { "denom": "%s", "amount": "60" } + } + ], + "begin_unbondings": [], + "complete_unbondings": [], + "begin_redelegates": [], + "complete_redelegates": [] + }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr, "steak")) + res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) + require.Equal(t, http.StatusOK, res.StatusCode, body) + + var results []ctypes.ResultBroadcastTxCommit + err := cdc.UnmarshalJSON([]byte(body), &results) + require.Nil(t, err) + + return results[0] +} + +func doBeginUnbonding(t *testing.T, port, seed, name, password string, + delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { + + // get the account to get the sequence + acc := getAccount(t, port, delegatorAddr) + accnum := acc.GetAccountNumber() + sequence := acc.GetSequence() + + chainID := viper.GetString(client.FlagChainID) + + // send + jsonStr := []byte(fmt.Sprintf(`{ + "name": "%s", + "password": "%s", + "account_number": "%d", + "sequence": "%d", + "gas": "20000", + "chain_id": "%s", + "delegations": [], + "begin_unbondings": [ + { + "delegator_addr": "%s", + "validator_addr": "%s", + "shares": "30" + } + ], + "complete_unbondings": [], + "begin_redelegates": [], + "complete_redelegates": [] + }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr)) + res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) + require.Equal(t, http.StatusOK, res.StatusCode, body) + + var results []ctypes.ResultBroadcastTxCommit + err := cdc.UnmarshalJSON([]byte(body), &results) + require.Nil(t, err) + + return results[0] +} + +func doBeginRedelegation(t *testing.T, port, seed, name, password string, + delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { + + // get the account to get the sequence + acc := getAccount(t, port, delegatorAddr) + accnum := acc.GetAccountNumber() + sequence := acc.GetSequence() + + chainID := viper.GetString(client.FlagChainID) + + // send + jsonStr := []byte(fmt.Sprintf(`{ + "name": "%s", + "password": "%s", + "account_number": "%d", + "sequence": "%d", + "gas": "10000", + "chain_id": "%s", + "delegations": [], + "begin_unbondings": [], + "complete_unbondings": [], + "begin_redelegates": [ + { + "delegator_addr": "%s", + "validator_src_addr": "%s", + "validator_dst_addr": "%s", + "shares": "30" + } + ], + "complete_redelegates": [] + }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorSrcAddr, validatorDstAddr)) + res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) + require.Equal(t, http.StatusOK, res.StatusCode, body) + + var results []ctypes.ResultBroadcastTxCommit + err := cdc.UnmarshalJSON([]byte(body), &results) + require.Nil(t, err) + + return results[0] +} + +func getValidatorsREST(t *testing.T, port string) []stake.BechValidator { + // get the account to get the sequence + res, body := Request(t, port, "GET", "/stake/validators", nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + var validators []stake.BechValidator + err := cdc.UnmarshalJSON([]byte(body), &validators) + require.Nil(t, err) + return validators +} diff --git a/x/stake/client/rest/test_helpers.go b/x/stake/client/rest/test_helpers.go new file mode 100644 index 000000000000..b8492e8aa652 --- /dev/null +++ b/x/stake/client/rest/test_helpers.go @@ -0,0 +1,287 @@ +package rest + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "net" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" + keys "github.com/cosmos/cosmos-sdk/client/keys" + gapp "github.com/cosmos/cosmos-sdk/cmd/gaia/app" + crkeys "github.com/cosmos/cosmos-sdk/crypto/keys" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/tests" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/gorilla/mux" + + "github.com/spf13/viper" + "github.com/stretchr/testify/require" + + abci "github.com/tendermint/tendermint/abci/types" + tmcfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/crypto/ed25519" + "github.com/tendermint/tendermint/libs/cli" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" + nm "github.com/tendermint/tendermint/node" + pvm "github.com/tendermint/tendermint/privval" + "github.com/tendermint/tendermint/proxy" + tmrpc "github.com/tendermint/tendermint/rpc/lib/server" + tmtypes "github.com/tendermint/tendermint/types" +) + +func createHandler(cdc *wire.Codec) http.Handler { + r := mux.NewRouter() + + kb, err := keys.GetKeyBase() //XXX + if err != nil { + panic(err) + } + + ctx := context.NewCoreContextFromViper() + RegisterRoutes(ctx, r, cdc, kb) + + return r +} + +// makePathname creates a unique pathname for each test. It will panic if it +// cannot get the current working directory. +func makePathname() string { + p, err := os.Getwd() + if err != nil { + panic(err) + } + + sep := string(filepath.Separator) + return strings.Replace(p, sep, "_", -1) +} + +// GetConfig returns a Tendermint config for the test cases. +func GetConfig() *tmcfg.Config { + pathname := makePathname() + config := tmcfg.ResetTestRoot(pathname) + + tmAddr, _, err := server.FreeTCPAddr() + if err != nil { + panic(err) + } + + rcpAddr, _, err := server.FreeTCPAddr() + if err != nil { + panic(err) + } + + grpcAddr, _, err := server.FreeTCPAddr() + if err != nil { + panic(err) + } + + config.P2P.ListenAddress = tmAddr + config.RPC.ListenAddress = rcpAddr + config.RPC.GRPCListenAddress = grpcAddr + + return config +} + +// GetKeyBase returns the LCD test keybase. It also requires that a directory +// could be made and a keybase could be fetched. +// +// NOTE: memDB cannot be used because the request is expecting to interact with +// the default location. +func GetKeyBase(t *testing.T) crkeys.Keybase { + dir, err := ioutil.TempDir("", "lcd_test") + require.NoError(t, err) + + viper.Set(cli.HomeFlag, dir) + + keybase, err := keys.GetKeyBase() + require.NoError(t, err) + + return keybase +} + +// CreateAddr adds an address to the key store and returns an address and seed. +// It also requires that the key could be created. +func CreateAddr(t *testing.T, name, password string, kb crkeys.Keybase) (sdk.AccAddress, string) { + var ( + err error + info crkeys.Info + seed string + ) + + info, seed, err = kb.CreateMnemonic(name, crkeys.English, password, crkeys.Secp256k1) + require.NoError(t, err) + + return sdk.AccAddress(info.GetPubKey().Address()), seed +} + +// InitializeTestLCD starts Tendermint and the LCD in process, listening on +// their respective sockets where nValidators is the total number of validators +// and initAddrs are the accounts to initialize with some steak tokens. It +// returns a cleanup function, a set of validator public keys, and a port. +func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress) (func(), []crypto.PubKey, string) { + config := GetConfig() + config.Consensus.TimeoutCommit = 100 + config.Consensus.SkipTimeoutCommit = false + config.TxIndex.IndexAllTags = true + + logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + logger = log.NewFilter(logger, log.AllowDebug()) + + privValidatorFile := config.PrivValidatorFile() + privVal := pvm.LoadOrGenFilePV(privValidatorFile) + privVal.Reset() + + db := dbm.NewMemDB() + app := gapp.NewGaiaApp(logger, db, nil) + cdc := gapp.MakeCodec() + + genesisFile := config.GenesisFile() + genDoc, err := tmtypes.GenesisDocFromFile(genesisFile) + require.NoError(t, err) + + if nValidators < 1 { + panic("InitializeTestLCD must use at least one validator") + } + + for i := 1; i < nValidators; i++ { + genDoc.Validators = append(genDoc.Validators, + tmtypes.GenesisValidator{ + PubKey: ed25519.GenPrivKey().PubKey(), + Power: 1, + Name: "val", + }, + ) + } + + var validatorsPKs []crypto.PubKey + + // NOTE: It's bad practice to reuse public key address for the owner + // address but doing in the test for simplicity. + var appGenTxs []json.RawMessage + for _, gdValidator := range genDoc.Validators { + pk := gdValidator.PubKey + validatorsPKs = append(validatorsPKs, pk) + + appGenTx, _, _, err := gapp.GaiaAppGenTxNF(cdc, pk, sdk.AccAddress(pk.Address()), "test_val1") + require.NoError(t, err) + + appGenTxs = append(appGenTxs, appGenTx) + } + + genesisState, err := gapp.GaiaAppGenState(cdc, appGenTxs[:]) + require.NoError(t, err) + + // add some tokens to init accounts + for _, addr := range initAddrs { + accAuth := auth.NewBaseAccountWithAddress(addr) + accAuth.Coins = sdk.Coins{sdk.NewCoin("steak", 100)} + acc := gapp.NewGenesisAccount(&accAuth) + genesisState.Accounts = append(genesisState.Accounts, acc) + genesisState.StakeData.Pool.LooseTokens = genesisState.StakeData.Pool.LooseTokens.Add(sdk.NewRat(100)) + } + + appState, err := wire.MarshalJSONIndent(cdc, genesisState) + require.NoError(t, err) + genDoc.AppState = appState + + listenAddr, port, err := server.FreeTCPAddr() + require.NoError(t, err) + + // XXX: Need to set this so LCD knows the tendermint node address! + viper.Set(client.FlagNode, config.RPC.ListenAddress) + viper.Set(client.FlagChainID, genDoc.ChainID) + + node, err := startTM(config, logger, genDoc, privVal, app) + require.NoError(t, err) + + lcd, err := startLCD(logger, listenAddr, cdc) + require.NoError(t, err) + + tests.WaitForLCDStart(port) + tests.WaitForHeight(1, port) + + cleanup := func() { + logger.Debug("cleaning up LCD initialization") + node.Stop() + node.Wait() + lcd.Close() + } + + return cleanup, validatorsPKs, port +} + +// startTM creates and starts an in-process Tendermint node with memDB and +// in-process ABCI application. It returns the new node or any error that +// occurred. +// +// TODO: Clean up the WAL dir or enable it to be not persistent! +func startTM( + tmcfg *tmcfg.Config, logger log.Logger, genDoc *tmtypes.GenesisDoc, + privVal tmtypes.PrivValidator, app abci.Application, +) (*nm.Node, error) { + genDocProvider := func() (*tmtypes.GenesisDoc, error) { return genDoc, nil } + dbProvider := func(*nm.DBContext) (dbm.DB, error) { return dbm.NewMemDB(), nil } + node, err := nm.NewNode( + tmcfg, + privVal, + proxy.NewLocalClientCreator(app), + genDocProvider, + dbProvider, + nm.DefaultMetricsProvider, + logger.With("module", "node"), + ) + if err != nil { + return nil, err + } + + err = node.Start() + if err != nil { + return nil, err + } + + tests.WaitForRPC(tmcfg.RPC.ListenAddress) + logger.Info("Tendermint running!") + + return node, err +} + +// startLCD starts the LCD. +// +// NOTE: This causes the thread to block. +func startLCD(logger log.Logger, listenAddr string, cdc *wire.Codec) (net.Listener, error) { + return tmrpc.StartHTTPServer(listenAddr, createHandler(cdc), logger, tmrpc.Config{}) +} + +// Request makes a test LCD test request. It returns a response object and a +// stringified response body. +func Request(t *testing.T, port, method, path string, payload []byte) (*http.Response, string) { + var ( + err error + res *http.Response + ) + url := fmt.Sprintf("http://localhost:%v%v", port, path) + + req, err := http.NewRequest(method, url, bytes.NewBuffer(payload)) + require.Nil(t, err) + + res, err = http.DefaultClient.Do(req) + require.Nil(t, err) + + output, err := ioutil.ReadAll(res.Body) + res.Body.Close() + require.Nil(t, err) + + return res, string(output) +} diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index d9d7e6aeb53a..9d5c089ab1bb 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -5,7 +5,11 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/stake/types" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/common" + ctypes "github.com/tendermint/tendermint/rpc/core/types" ) // Contains checks if the a given query contains one of the tx types @@ -18,6 +22,51 @@ func contains(stringSlice []string, txType string) bool { return false } +func formatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]txInfo, error) { + var err error + out := make([]txInfo, len(res)) + for i := range res { + out[i], err = formatTxResult(cdc, res[i]) + if err != nil { + return nil, err + } + } + return out, nil +} + +func formatTxResult(cdc *wire.Codec, res *ctypes.ResultTx) (txInfo, error) { + // TODO: verify the proof if requested + tx, err := parseTx(cdc, res.Tx) + if err != nil { + return txInfo{}, err + } + + info := txInfo{ + Hash: res.Hash, + Height: res.Height, + Tx: tx, + Result: res.TxResult, + } + return info, nil +} + +// txInfo is used to prepare info to display +type txInfo struct { + Hash common.HexBytes `json:"hash"` + Height int64 `json:"height"` + Tx sdk.Tx `json:"tx"` + Result abci.ResponseDeliverTx `json:"result"` +} + +func parseTx(cdc *wire.Codec, txBytes []byte) (sdk.Tx, error) { + var tx auth.StdTx + err := cdc.UnmarshalBinary(txBytes, &tx) + if err != nil { + return nil, err + } + return tx, nil +} + // get all Validators func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechValidator, error) { // parse out the validators From 3a26b4681e387126acafcd56c7b9a626d4b34e17 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 30 Jul 2018 18:53:59 +0200 Subject: [PATCH 06/46] Revert prev commit --- Gopkg.lock | 197 ++++++++++++++++++++++++++++++----- client/lcd/lcd_test.go | 191 +++++++++++++++++++++++++++++++++ x/stake/client/rest/utils.go | 49 --------- 3 files changed, 362 insertions(+), 75 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index 86b75ba33652..e6f15683550e 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -2,57 +2,76 @@ [[projects]] + digest = "1:09a7f74eb6bb3c0f14d8926610c87f569c5cff68e978d30e9a3540aeb626fdf0" name = "github.com/bartekn/go-bip39" packages = ["."] + pruneopts = "UT" revision = "a05967ea095d81c8fe4833776774cfaff8e5036c" [[projects]] branch = "master" + digest = "1:d6afaeed1502aa28e80a4ed0981d570ad91b2579193404256ce672ed0a609e0d" name = "github.com/beorn7/perks" packages = ["quantile"] + pruneopts = "UT" revision = "3a771d992973f24aa725d07868b467d1ddfceafb" [[projects]] + digest = "1:1343a2963481a305ca4d051e84bc2abd16b601ee22ed324f8d605de1adb291b0" name = "github.com/bgentry/speakeasy" packages = ["."] + pruneopts = "UT" revision = "4aabc24848ce5fd31929f7d1e4ea74d3709c14cd" version = "v0.1.0" [[projects]] branch = "master" + digest = "1:70f6b224a59b2fa453debffa85c77f71063d8754b90c8c4fbad5794e2c382b0f" name = "github.com/brejski/hid" packages = ["."] + pruneopts = "UT" revision = "06112dcfcc50a7e0e4fd06e17f9791e788fdaafc" [[projects]] branch = "master" + digest = "1:2c00f064ba355903866cbfbf3f7f4c0fe64af6638cc7d1b8bdcf3181bc67f1d8" name = "github.com/btcsuite/btcd" packages = ["btcec"] + pruneopts = "UT" revision = "fdfc19097e7ac6b57035062056f5b7b4638b8898" [[projects]] + digest = "1:386de157f7d19259a7f9c81f26ce011223ce0f090353c1152ffdf730d7d10ac2" name = "github.com/btcsuite/btcutil" packages = ["bech32"] + pruneopts = "UT" revision = "d4cc87b860166d00d6b5b9e0d3b3d71d6088d4d4" [[projects]] + digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39" name = "github.com/davecgh/go-spew" packages = ["spew"] + pruneopts = "UT" revision = "346938d642f2ec3594ed81d874461961cd0faa76" version = "v1.1.0" [[projects]] + digest = "1:c7644c73a3d23741fdba8a99b1464e021a224b7e205be497271a8003a15ca41b" name = "github.com/ebuchman/fail-test" packages = ["."] + pruneopts = "UT" revision = "95f809107225be108efcf10a3509e4ea6ceef3c4" [[projects]] + digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd" name = "github.com/fsnotify/fsnotify" packages = ["."] + pruneopts = "UT" revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" version = "v1.4.7" [[projects]] + digest = "1:fdf5169073fb0ad6dc12a70c249145e30f4058647bea25f0abd48b6d9f228a11" name = "github.com/go-kit/kit" packages = [ "log", @@ -61,24 +80,30 @@ "metrics", "metrics/discard", "metrics/internal/lv", - "metrics/prometheus" + "metrics/prometheus", ] + pruneopts = "UT" revision = "4dc7be5d2d12881735283bcab7352178e190fc71" version = "v0.6.0" [[projects]] + digest = "1:31a18dae27a29aa074515e43a443abfd2ba6deb6d69309d8d7ce789c45f34659" name = "github.com/go-logfmt/logfmt" packages = ["."] + pruneopts = "UT" revision = "390ab7935ee28ec6b286364bba9b4dd6410cb3d5" version = "v0.3.0" [[projects]] + digest = "1:c4a2528ccbcabf90f9f3c464a5fc9e302d592861bbfd0b7135a7de8a943d0406" name = "github.com/go-stack/stack" packages = ["."] + pruneopts = "UT" revision = "259ab82a6cad3992b4e21ff5cac294ccb06474bc" version = "v1.7.0" [[projects]] + digest = "1:35621fe20f140f05a0c4ef662c26c0ab4ee50bca78aa30fe87d33120bd28165e" name = "github.com/gogo/protobuf" packages = [ "gogoproto", @@ -86,49 +111,61 @@ "proto", "protoc-gen-gogo/descriptor", "sortkeys", - "types" + "types", ] + pruneopts = "UT" revision = "636bf0302bc95575d69441b25a2603156ffdddf1" version = "v1.1.1" [[projects]] + digest = "1:17fe264ee908afc795734e8c4e63db2accabaf57326dbf21763a7d6b86096260" name = "github.com/golang/protobuf" packages = [ "proto", "ptypes", "ptypes/any", "ptypes/duration", - "ptypes/timestamp" + "ptypes/timestamp", ] + pruneopts = "UT" revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" version = "v1.1.0" [[projects]] branch = "master" + digest = "1:4a0c6bb4805508a6287675fac876be2ac1182539ca8a32468d8128882e9d5009" name = "github.com/golang/snappy" packages = ["."] + pruneopts = "UT" revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" [[projects]] + digest = "1:c79fb010be38a59d657c48c6ba1d003a8aa651fa56b579d959d74573b7dff8e1" name = "github.com/gorilla/context" packages = ["."] + pruneopts = "UT" revision = "08b5f424b9271eedf6f9f0ce86cb9396ed337a42" version = "v1.1.1" [[projects]] + digest = "1:e73f5b0152105f18bc131fba127d9949305c8693f8a762588a82a48f61756f5f" name = "github.com/gorilla/mux" packages = ["."] + pruneopts = "UT" revision = "e3702bed27f0d39777b0b37b664b6280e8ef8fbf" version = "v1.6.2" [[projects]] + digest = "1:43dd08a10854b2056e615d1b1d22ac94559d822e1f8b6fcc92c1a1057e85188e" name = "github.com/gorilla/websocket" packages = ["."] + pruneopts = "UT" revision = "ea4d1f681babbce9545c9c5f3d5194a789c89f5b" version = "v1.2.0" [[projects]] branch = "master" + digest = "1:12247a2e99a060cc692f6680e5272c8adf0b8f572e6bce0d7095e624c958a240" name = "github.com/hashicorp/hcl" packages = [ ".", @@ -139,160 +176,206 @@ "hcl/token", "json/parser", "json/scanner", - "json/token" + "json/token", ] + pruneopts = "UT" revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" [[projects]] + digest = "1:870d441fe217b8e689d7949fef6e43efbc787e50f200cb1e70dbca9204a1d6be" name = "github.com/inconshreveable/mousetrap" packages = ["."] + pruneopts = "UT" revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75" version = "v1.0" [[projects]] branch = "master" + digest = "1:39b27d1381a30421f9813967a5866fba35dc1d4df43a6eefe3b7a5444cb07214" name = "github.com/jmhodges/levigo" packages = ["."] + pruneopts = "UT" revision = "c42d9e0ca023e2198120196f842701bb4c55d7b9" [[projects]] branch = "master" + digest = "1:a64e323dc06b73892e5bb5d040ced475c4645d456038333883f58934abbf6f72" name = "github.com/kr/logfmt" packages = ["."] + pruneopts = "UT" revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0" [[projects]] + digest = "1:c568d7727aa262c32bdf8a3f7db83614f7af0ed661474b24588de635c20024c7" name = "github.com/magiconair/properties" packages = ["."] + pruneopts = "UT" revision = "c2353362d570a7bfa228149c62842019201cfb71" version = "v1.8.0" [[projects]] + digest = "1:d4d17353dbd05cb52a2a52b7fe1771883b682806f68db442b436294926bbfafb" name = "github.com/mattn/go-isatty" packages = ["."] + pruneopts = "UT" revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" version = "v0.0.3" [[projects]] + digest = "1:ff5ebae34cfbf047d505ee150de27e60570e8c394b3b8fdbb720ff6ac71985fc" name = "github.com/matttproud/golang_protobuf_extensions" packages = ["pbutil"] + pruneopts = "UT" revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" version = "v1.0.1" [[projects]] branch = "master" + digest = "1:e730597b38a4d56e2361e0b6236cb800e52c73cace2ff91396f4ff35792ddfa7" name = "github.com/mitchellh/mapstructure" packages = ["."] + pruneopts = "UT" revision = "bb74f1db0675b241733089d5a1faa5dd8b0ef57b" [[projects]] + digest = "1:95741de3af260a92cc5c7f3f3061e85273f5a81b5db20d4bd68da74bd521675e" name = "github.com/pelletier/go-toml" packages = ["."] + pruneopts = "UT" revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194" version = "v1.2.0" [[projects]] + digest = "1:40e195917a951a8bf867cd05de2a46aaf1806c50cf92eebf4c16f78cd196f747" name = "github.com/pkg/errors" packages = ["."] + pruneopts = "UT" revision = "645ef00459ed84a119197bfb8d8205042c6df63d" version = "v0.8.0" [[projects]] + digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" name = "github.com/pmezard/go-difflib" packages = ["difflib"] + pruneopts = "UT" revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" [[projects]] + digest = "1:c1a04665f9613e082e1209cf288bf64f4068dcd6c87a64bf1c4ff006ad422ba0" name = "github.com/prometheus/client_golang" packages = [ "prometheus", - "prometheus/promhttp" + "prometheus/promhttp", ] + pruneopts = "UT" revision = "ae27198cdd90bf12cd134ad79d1366a6cf49f632" [[projects]] branch = "master" + digest = "1:32d10bdfa8f09ecf13598324dba86ab891f11db3c538b6a34d1c3b5b99d7c36b" name = "github.com/prometheus/client_model" packages = ["go"] + pruneopts = "UT" revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c" [[projects]] branch = "master" + digest = "1:e469cd65badf7694aeb44874518606d93c1d59e7735d3754ad442782437d3cc3" name = "github.com/prometheus/common" packages = [ "expfmt", "internal/bitbucket.org/ww/goautoneg", - "model" + "model", ] + pruneopts = "UT" revision = "7600349dcfe1abd18d72d3a1770870d9800a7801" [[projects]] branch = "master" + digest = "1:20d9bb50dbee172242f9bcd6ec24a917dd7a5bb17421bf16a79c33111dea7db1" name = "github.com/prometheus/procfs" packages = [ ".", "internal/util", "nfs", - "xfs" + "xfs", ] + pruneopts = "UT" revision = "ae68e2d4c00fed4943b5f6698d504a5fe083da8a" [[projects]] + digest = "1:c4556a44e350b50a490544d9b06e9fba9c286c21d6c0e47f54f3a9214597298c" name = "github.com/rcrowley/go-metrics" packages = ["."] + pruneopts = "UT" revision = "e2704e165165ec55d062f5919b4b29494e9fa790" [[projects]] + digest = "1:bd1ae00087d17c5a748660b8e89e1043e1e5479d0fea743352cda2f8dd8c4f84" name = "github.com/spf13/afero" packages = [ ".", - "mem" + "mem", ] + pruneopts = "UT" revision = "787d034dfe70e44075ccc060d346146ef53270ad" version = "v1.1.1" [[projects]] + digest = "1:516e71bed754268937f57d4ecb190e01958452336fa73dbac880894164e91c1f" name = "github.com/spf13/cast" packages = ["."] + pruneopts = "UT" revision = "8965335b8c7107321228e3e3702cab9832751bac" version = "v1.2.0" [[projects]] + digest = "1:7ffc0983035bc7e297da3688d9fe19d60a420e9c38bef23f845c53788ed6a05e" name = "github.com/spf13/cobra" packages = ["."] + pruneopts = "UT" revision = "7b2c5ac9fc04fc5efafb60700713d4fa609b777b" version = "v0.0.1" [[projects]] branch = "master" + digest = "1:080e5f630945ad754f4b920e60b4d3095ba0237ebf88dc462eb28002932e3805" name = "github.com/spf13/jwalterweatherman" packages = ["."] + pruneopts = "UT" revision = "7c0cea34c8ece3fbeb2b27ab9b59511d360fb394" [[projects]] + digest = "1:9424f440bba8f7508b69414634aef3b2b3a877e522d8a4624692412805407bb7" name = "github.com/spf13/pflag" packages = ["."] + pruneopts = "UT" revision = "583c0c0531f06d5278b7d917446061adc344b5cd" version = "v1.0.1" [[projects]] + digest = "1:f8e1a678a2571e265f4bf91a3e5e32aa6b1474a55cb0ea849750cc177b664d96" name = "github.com/spf13/viper" packages = ["."] + pruneopts = "UT" revision = "25b30aa063fc18e48662b86996252eabdcf2f0c7" version = "v1.0.0" [[projects]] + digest = "1:7e8d267900c7fa7f35129a2a37596e38ed0f11ca746d6d9ba727980ee138f9f6" name = "github.com/stretchr/testify" packages = [ "assert", - "require" + "require", ] + pruneopts = "UT" revision = "12b6f73e6084dad08a7c6e575284b177ecafbc71" version = "v1.2.1" [[projects]] branch = "master" + digest = "1:b3cfb8d82b1601a846417c3f31c03a7961862cb2c98dcf0959c473843e6d9a2b" name = "github.com/syndtr/goleveldb" packages = [ "leveldb", @@ -306,33 +389,41 @@ "leveldb/opt", "leveldb/storage", "leveldb/table", - "leveldb/util" + "leveldb/util", ] + pruneopts = "UT" revision = "c4c61651e9e37fa117f53c5a906d3b63090d8445" [[projects]] branch = "master" + digest = "1:087aaa7920e5d0bf79586feb57ce01c35c830396ab4392798112e8aae8c47722" name = "github.com/tendermint/ed25519" packages = [ ".", "edwards25519", - "extra25519" + "extra25519", ] + pruneopts = "UT" revision = "d8387025d2b9d158cf4efb07e7ebf814bcce2057" [[projects]] + digest = "1:e9113641c839c21d8eaeb2c907c7276af1eddeed988df8322168c56b7e06e0e1" name = "github.com/tendermint/go-amino" packages = ["."] + pruneopts = "UT" revision = "2106ca61d91029c931fd54968c2bb02dc96b1412" version = "0.10.1" [[projects]] + digest = "1:d4a15d404afbf591e8be16fcda7f5ac87948d5c7531f9d909fd84cc730ab16e2" name = "github.com/tendermint/iavl" packages = ["."] + pruneopts = "UT" revision = "35f66e53d9b01e83b30de68b931f54b2477a94c9" version = "v0.9.2" [[projects]] + digest = "1:e10e95fd9f0a3a31686c9696f8995f6c04b0bc1b4ed0562a4f53cddc0b89d059" name = "github.com/tendermint/tendermint" packages = [ "abci/client", @@ -392,27 +483,22 @@ "state/txindex/kv", "state/txindex/null", "types", - "version" + "version", ] + pruneopts = "UT" revision = "5fdbcd70df57b71ffba71e1ff5f00d617852a9c0" version = "v0.22.6" [[projects]] - name = "github.com/tendermint/tmlibs" - packages = [ - "common", - "log" - ] - revision = "49596e0a1f48866603813df843c9409fc19805c6" - version = "v0.9.0" - -[[projects]] + digest = "1:5bd938386bd1f61a581bf8cd6ff2b7b2f79c542929176db4ceb44965440dae07" name = "github.com/zondax/ledger-goclient" packages = ["."] + pruneopts = "UT" revision = "39ba4728c137c75718a21f9b4b3280fa31b9139b" [[projects]] branch = "master" + digest = "1:65a21a9e051d54eb6a3f70c659a765f706a998d9287c302269f4ed8054b2a852" name = "golang.org/x/crypto" packages = [ "blowfish", @@ -425,11 +511,13 @@ "pbkdf2", "poly1305", "ripemd160", - "salsa20/salsa" + "salsa20/salsa", ] + pruneopts = "UT" revision = "a49355c7e3f8fe157a85be2f77e6e269a0f89602" [[projects]] + digest = "1:d36f55a999540d29b6ea3c2ea29d71c76b1d9853fdcd3e5c5cb4836f2ba118f1" name = "golang.org/x/net" packages = [ "context", @@ -439,17 +527,21 @@ "idna", "internal/timeseries", "netutil", - "trace" + "trace", ] + pruneopts = "UT" revision = "292b43bbf7cb8d35ddf40f8d5100ef3837cced3f" [[projects]] branch = "master" + digest = "1:d773e525476aefa22ea944a5425a9bfb99819b2e67eeb9b1966454fd57522bbf" name = "golang.org/x/sys" packages = ["unix"] + pruneopts = "UT" revision = "1b2967e3c290b7c545b3db0deeda16e9be4f98a2" [[projects]] + digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" name = "golang.org/x/text" packages = [ "collate", @@ -465,18 +557,22 @@ "unicode/bidi", "unicode/cldr", "unicode/norm", - "unicode/rangetable" + "unicode/rangetable", ] + pruneopts = "UT" revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" version = "v0.3.0" [[projects]] branch = "master" + digest = "1:601e63e7d4577f907118bec825902505291918859d223bce015539e79f1160e3" name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] + pruneopts = "UT" revision = "e92b116572682a5b432ddd840aeaba2a559eeff1" [[projects]] + digest = "1:2dab32a43451e320e49608ff4542fdfc653c95dcc35d0065ec9c6c3dd540ed74" name = "google.golang.org/grpc" packages = [ ".", @@ -503,20 +599,69 @@ "stats", "status", "tap", - "transport" + "transport", ] + pruneopts = "UT" revision = "168a6198bcb0ef175f7dacec0b8691fc141dc9b8" version = "v1.13.0" [[projects]] + digest = "1:342378ac4dcb378a5448dd723f0784ae519383532f5e70ade24132c4c8693202" name = "gopkg.in/yaml.v2" packages = ["."] + pruneopts = "UT" revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" version = "v2.2.1" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "a74828152213e53070f4d5fd94dbf37b58c44743558c62ee0d1be99f470e0070" + input-imports = [ + "github.com/bartekn/go-bip39", + "github.com/bgentry/speakeasy", + "github.com/btcsuite/btcd/btcec", + "github.com/golang/protobuf/proto", + "github.com/gorilla/mux", + "github.com/mattn/go-isatty", + "github.com/pkg/errors", + "github.com/spf13/cobra", + "github.com/spf13/pflag", + "github.com/spf13/viper", + "github.com/stretchr/testify/assert", + "github.com/stretchr/testify/require", + "github.com/tendermint/go-amino", + "github.com/tendermint/iavl", + "github.com/tendermint/tendermint/abci/server", + "github.com/tendermint/tendermint/abci/types", + "github.com/tendermint/tendermint/cmd/tendermint/commands", + "github.com/tendermint/tendermint/config", + "github.com/tendermint/tendermint/crypto", + "github.com/tendermint/tendermint/crypto/armor", + "github.com/tendermint/tendermint/crypto/ed25519", + "github.com/tendermint/tendermint/crypto/encoding/amino", + "github.com/tendermint/tendermint/crypto/merkle", + "github.com/tendermint/tendermint/crypto/secp256k1", + "github.com/tendermint/tendermint/crypto/tmhash", + "github.com/tendermint/tendermint/crypto/xsalsa20symmetric", + "github.com/tendermint/tendermint/libs/bech32", + "github.com/tendermint/tendermint/libs/cli", + "github.com/tendermint/tendermint/libs/cli/flags", + "github.com/tendermint/tendermint/libs/common", + "github.com/tendermint/tendermint/libs/db", + "github.com/tendermint/tendermint/libs/log", + "github.com/tendermint/tendermint/node", + "github.com/tendermint/tendermint/p2p", + "github.com/tendermint/tendermint/privval", + "github.com/tendermint/tendermint/proxy", + "github.com/tendermint/tendermint/rpc/client", + "github.com/tendermint/tendermint/rpc/core/types", + "github.com/tendermint/tendermint/rpc/lib/client", + "github.com/tendermint/tendermint/rpc/lib/server", + "github.com/tendermint/tendermint/types", + "github.com/tendermint/tendermint/version", + "github.com/zondax/ledger-goclient", + "golang.org/x/crypto/blowfish", + "golang.org/x/crypto/ripemd160", + ] solver-name = "gps-cdcl" solver-version = 1 diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index e72d522b06d7..87566cff9335 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -26,6 +26,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/stake" ) func init() { @@ -373,6 +374,56 @@ func TestValidatorsQuery(t *testing.T) { require.True(t, foundVal, "pkBech %v, owner %v", pkBech, validators[0].Owner) } +func TestBonding(t *testing.T) { + name, password, denom := "test", "1234567890", "steak" + addr, seed := CreateAddr(t, "test", password, GetKeyBase(t)) + cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) + defer cleanup() + + validator1Owner := sdk.AccAddress(pks[0].Address()) + + // create bond TX + resultTx := doDelegate(t, port, seed, name, password, addr, validator1Owner) + tests.WaitForHeight(resultTx.Height+1, port) + + // check if tx was committed + require.Equal(t, uint32(0), resultTx.CheckTx.Code) + require.Equal(t, uint32(0), resultTx.DeliverTx.Code) + + // query sender + acc := getAccount(t, port, addr) + coins := acc.GetCoins() + + require.Equal(t, int64(40), coins.AmountOf(denom).Int64()) + + // query validator + bond := getDelegation(t, port, addr, validator1Owner) + require.Equal(t, "60/1", bond.Shares.String()) + + ////////////////////// + // testing unbonding + + // create unbond TX + resultTx = doBeginUnbonding(t, port, seed, name, password, addr, validator1Owner) + tests.WaitForHeight(resultTx.Height+1, port) + + // query validator + bond = getDelegation(t, port, addr, validator1Owner) + require.Equal(t, "30/1", bond.Shares.String()) + + // check if tx was committed + require.Equal(t, uint32(0), resultTx.CheckTx.Code) + require.Equal(t, uint32(0), resultTx.DeliverTx.Code) + + // should the sender should have not received any coins as the unbonding has only just begun + // query sender + acc = getAccount(t, port, addr) + coins = acc.GetCoins() + require.Equal(t, int64(40), coins.AmountOf("steak").Int64()) + + // TODO add redelegation, need more complex capabilities such to mock context and +} + func TestSubmitProposal(t *testing.T) { name, password := "test", "1234567890" addr, seed := CreateAddr(t, "test", password, GetKeyBase(t)) @@ -668,6 +719,146 @@ func getSigningInfo(t *testing.T, port string, validatorAddr sdk.ValAddress) sla return signingInfo } +func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.AccAddress) stake.Delegation { + + // get the account to get the sequence + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/%s/delegation/%s", delegatorAddr, validatorAddr), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + var bond stake.Delegation + err := cdc.UnmarshalJSON([]byte(body), &bond) + require.Nil(t, err) + return bond +} + +func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { + // get the account to get the sequence + acc := getAccount(t, port, delegatorAddr) + accnum := acc.GetAccountNumber() + sequence := acc.GetSequence() + + chainID := viper.GetString(client.FlagChainID) + + // send + jsonStr := []byte(fmt.Sprintf(`{ + "name": "%s", + "password": "%s", + "account_number": "%d", + "sequence": "%d", + "gas": "10000", + "chain_id": "%s", + "delegations": [ + { + "delegator_addr": "%s", + "validator_addr": "%s", + "delegation": { "denom": "%s", "amount": "60" } + } + ], + "begin_unbondings": [], + "complete_unbondings": [], + "begin_redelegates": [], + "complete_redelegates": [] + }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr, "steak")) + res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) + require.Equal(t, http.StatusOK, res.StatusCode, body) + + var results []ctypes.ResultBroadcastTxCommit + err := cdc.UnmarshalJSON([]byte(body), &results) + require.Nil(t, err) + + return results[0] +} + +func doBeginUnbonding(t *testing.T, port, seed, name, password string, + delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { + + // get the account to get the sequence + acc := getAccount(t, port, delegatorAddr) + accnum := acc.GetAccountNumber() + sequence := acc.GetSequence() + + chainID := viper.GetString(client.FlagChainID) + + // send + jsonStr := []byte(fmt.Sprintf(`{ + "name": "%s", + "password": "%s", + "account_number": "%d", + "sequence": "%d", + "gas": "20000", + "chain_id": "%s", + "delegations": [], + "begin_unbondings": [ + { + "delegator_addr": "%s", + "validator_addr": "%s", + "shares": "30" + } + ], + "complete_unbondings": [], + "begin_redelegates": [], + "complete_redelegates": [] + }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr)) + res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) + require.Equal(t, http.StatusOK, res.StatusCode, body) + + var results []ctypes.ResultBroadcastTxCommit + err := cdc.UnmarshalJSON([]byte(body), &results) + require.Nil(t, err) + + return results[0] +} + +func doBeginRedelegation(t *testing.T, port, seed, name, password string, + delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { + + // get the account to get the sequence + acc := getAccount(t, port, delegatorAddr) + accnum := acc.GetAccountNumber() + sequence := acc.GetSequence() + + chainID := viper.GetString(client.FlagChainID) + + // send + jsonStr := []byte(fmt.Sprintf(`{ + "name": "%s", + "password": "%s", + "account_number": "%d", + "sequence": "%d", + "gas": "10000", + "chain_id": "%s", + "delegations": [], + "begin_unbondings": [], + "complete_unbondings": [], + "begin_redelegates": [ + { + "delegator_addr": "%s", + "validator_src_addr": "%s", + "validator_dst_addr": "%s", + "shares": "30" + } + ], + "complete_redelegates": [] + }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorSrcAddr, validatorDstAddr)) + res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) + require.Equal(t, http.StatusOK, res.StatusCode, body) + + var results []ctypes.ResultBroadcastTxCommit + err := cdc.UnmarshalJSON([]byte(body), &results) + require.Nil(t, err) + + return results[0] +} + +func getValidators(t *testing.T, port string) []stake.BechValidator { + // get the account to get the sequence + res, body := Request(t, port, "GET", "/stake/validators", nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + var validators []stake.BechValidator + err := cdc.UnmarshalJSON([]byte(body), &validators) + require.Nil(t, err) + return validators +} + func getProposal(t *testing.T, port string, proposalID int64) gov.Proposal { res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d", proposalID), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 9d5c089ab1bb..d9d7e6aeb53a 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -5,11 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/stake/types" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/common" - ctypes "github.com/tendermint/tendermint/rpc/core/types" ) // Contains checks if the a given query contains one of the tx types @@ -22,51 +18,6 @@ func contains(stringSlice []string, txType string) bool { return false } -func formatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]txInfo, error) { - var err error - out := make([]txInfo, len(res)) - for i := range res { - out[i], err = formatTxResult(cdc, res[i]) - if err != nil { - return nil, err - } - } - return out, nil -} - -func formatTxResult(cdc *wire.Codec, res *ctypes.ResultTx) (txInfo, error) { - // TODO: verify the proof if requested - tx, err := parseTx(cdc, res.Tx) - if err != nil { - return txInfo{}, err - } - - info := txInfo{ - Hash: res.Hash, - Height: res.Height, - Tx: tx, - Result: res.TxResult, - } - return info, nil -} - -// txInfo is used to prepare info to display -type txInfo struct { - Hash common.HexBytes `json:"hash"` - Height int64 `json:"height"` - Tx sdk.Tx `json:"tx"` - Result abci.ResponseDeliverTx `json:"result"` -} - -func parseTx(cdc *wire.Codec, txBytes []byte) (sdk.Tx, error) { - var tx auth.StdTx - err := cdc.UnmarshalBinary(txBytes, &tx) - if err != nil { - return nil, err - } - return tx, nil -} - // get all Validators func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechValidator, error) { // parse out the validators From efcc11bb4b556950321ac7375bb1222def0e2782 Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Tue, 31 Jul 2018 11:55:49 +0200 Subject: [PATCH 07/46] remove logger output --- client/lcd/test_helpers.go | 2 +- x/stake/client/rest/test_helpers.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/client/lcd/test_helpers.go b/client/lcd/test_helpers.go index 11fcfc50941d..f50c0975183d 100644 --- a/client/lcd/test_helpers.go +++ b/client/lcd/test_helpers.go @@ -121,7 +121,7 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress config.TxIndex.IndexAllTags = true logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) - logger = log.NewFilter(logger, log.AllowDebug()) + logger = log.NewFilter(logger, log.AllowError()) privValidatorFile := config.PrivValidatorFile() privVal := pvm.LoadOrGenFilePV(privValidatorFile) diff --git a/x/stake/client/rest/test_helpers.go b/x/stake/client/rest/test_helpers.go index b8492e8aa652..a02ad0d91ac8 100644 --- a/x/stake/client/rest/test_helpers.go +++ b/x/stake/client/rest/test_helpers.go @@ -137,7 +137,7 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress config.TxIndex.IndexAllTags = true logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) - logger = log.NewFilter(logger, log.AllowDebug()) + logger = log.NewFilter(logger, log.AllowNone()) privValidatorFile := config.PrivValidatorFile() privVal := pvm.LoadOrGenFilePV(privValidatorFile) From 8f5334a701436c555e5e7e7c649750a8489e9443 Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Tue, 31 Jul 2018 11:56:59 +0200 Subject: [PATCH 08/46] linted --- x/stake/client/rest/utils.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index d9d7e6aeb53a..796afc36d8ec 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -42,7 +42,7 @@ func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechVali // get Validator given an Account Address func getValidator(address sdk.AccAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (sdk.Validator, error) { // parse out the validators - for i, kv := range validatorKVs { + for _, kv := range validatorKVs { addr := kv.Key[1:] validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) if err != nil { From f0d2eb5ef40767b94cbf46c141b53137626f4e7d Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Tue, 31 Jul 2018 11:57:46 +0200 Subject: [PATCH 09/46] removed module test --- x/stake/client/rest/lcd_test.go | 315 -------------------------------- 1 file changed, 315 deletions(-) delete mode 100644 x/stake/client/rest/lcd_test.go diff --git a/x/stake/client/rest/lcd_test.go b/x/stake/client/rest/lcd_test.go deleted file mode 100644 index 8ef80d8013d2..000000000000 --- a/x/stake/client/rest/lcd_test.go +++ /dev/null @@ -1,315 +0,0 @@ -package rest - -import ( - "fmt" - "net/http" - "testing" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/tests" - "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/spf13/viper" - "github.com/stretchr/testify/require" - "github.com/tendermint/tmlibs/common" -) - -// import ( -// "encoding/hex" -// "fmt" -// "net/http" -// "regexp" -// "testing" -// -// "github.com/spf13/viper" -// "github.com/stretchr/testify/assert" -// "github.com/stretchr/testify/require" -// -// cryptoKeys "github.com/cosmos/cosmos-sdk/crypto/keys" -// abci "github.com/tendermint/tendermint/abci/types" -// "github.com/tendermint/tendermint/libs/common" -// p2p "github.com/tendermint/tendermint/p2p" -// ctypes "github.com/tendermint/tendermint/rpc/core/types" -// -// client "github.com/cosmos/cosmos-sdk/client" -// keys "github.com/cosmos/cosmos-sdk/client/keys" -// rpc "github.com/cosmos/cosmos-sdk/client/rpc" -// tests "github.com/cosmos/cosmos-sdk/tests" -// sdk "github.com/cosmos/cosmos-sdk/types" -// "github.com/cosmos/cosmos-sdk/wire" -// "github.com/cosmos/cosmos-sdk/x/slashing" -// ) - -func TestStakingTxs(t *testing.T) { - name, password := "test", "1234567890" - addr, seed := CreateAddr(t, "test", password, GetKeyBase(t)) - cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) - defer cleanup() - - // query empty - res, body = Request(t, port, "GET", fmt.Sprintf("stake/delegators/'%s'/txs", "cosmosaccaddr1jawd35d9aq4u76sr3fjalmcqc8hqygs9gtnmv3"), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.Equal(t, "[]", body) - - // query empty bonding txs - res, body = Request(t, port, "GET", fmt.Sprintf("stake/delegators/'%s'/txs?type=bond", "cosmosaccaddr1jawd35d9aq4u76sr3fjalmcqc8hqygs9gtnmv3"), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.Equal(t, "[]", body) - - // query empty unbonding txs - res, body = Request(t, port, "GET", fmt.Sprintf("stake/delegators/'%s'/txs?type=unbond", "cosmosaccaddr1jawd35d9aq4u76sr3fjalmcqc8hqygs9gtnmv3"), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.Equal(t, "[]", body) - - // query empty redelegation txs - res, body = Request(t, port, "GET", fmt.Sprintf("stake/delegators/'%s'/txs?type=redelegate", "cosmosaccaddr1jawd35d9aq4u76sr3fjalmcqc8hqygs9gtnmv3"), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.Equal(t, "[]", body) - - // create TX - receiveAddr, resultTx := doSend(t, port, seed, name, password, addr) - - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx is findable - res, body = Request(t, port, "GET", fmt.Sprintf("/txs/%s", resultTx.Hash), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - type txInfo struct { - Hash common.HexBytes `json:"hash"` - Height int64 `json:"height"` - Tx sdk.Tx `json:"tx"` - Result abci.ResponseDeliverTx `json:"result"` - } - var indexedTxs []txInfo - - // check if tx is queryable - res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=tx.hash='%s'", resultTx.Hash), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NotEqual(t, "[]", body) - - err := cdc.UnmarshalJSON([]byte(body), &indexedTxs) - require.NoError(t, err) - require.Equal(t, 1, len(indexedTxs)) - - // XXX should this move into some other testfile for txs in general? - // test if created TX hash is the correct hash - require.Equal(t, resultTx.Hash, indexedTxs[0].Hash) - - // query sender - // also tests url decoding - res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=sender_bech32=%%27%s%%27", addr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - err = cdc.UnmarshalJSON([]byte(body), &indexedTxs) - require.NoError(t, err) - require.Equal(t, 1, len(indexedTxs), "%v", indexedTxs) // there are 2 txs created with doSend - require.Equal(t, resultTx.Height, indexedTxs[0].Height) - - // query recipient - res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=recipient_bech32='%s'", receiveAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - err = cdc.UnmarshalJSON([]byte(body), &indexedTxs) - require.NoError(t, err) - require.Equal(t, 1, len(indexedTxs)) - require.Equal(t, resultTx.Height, indexedTxs[0].Height) -} - -func TestBonding(t *testing.T) { - name, password, denom := "test", "1234567890", "steak" - addr, seed := CreateAddr(t, "test", password, GetKeyBase(t)) - cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) - defer cleanup() - - validator1Owner := sdk.AccAddress(pks[0].Address()) - - // create bond TX - resultTx := doDelegate(t, port, seed, name, password, addr, validator1Owner) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.CheckTx.Code) - require.Equal(t, uint32(0), resultTx.DeliverTx.Code) - - // query sender - acc := getAccount(t, port, addr) - coins := acc.GetCoins() - - require.Equal(t, int64(40), coins.AmountOf(denom).Int64()) - - // query validator - bond := getDelegation(t, port, addr, validator1Owner) - require.Equal(t, "60/1", bond.Shares.String()) - - // query bonding tx - res, body = Request(t, port, "GET", fmt.Sprintf("stake/delegators/'%s'/txs", "cosmosaccaddr1jawd35d9aq4u76sr3fjalmcqc8hqygs9gtnmv3"), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.Equal(t, "[]", body) - - res, body = Request(t, port, "GET", fmt.Sprintf("stake/delegators/'%s'/validators/'%s'/txs", "cosmosaccaddr1jawd35d9aq4u76sr3fjalmcqc8hqygs9gtnmv3"), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.Equal(t, "[]", body) - - ////////////////////// - // testing unbonding - - // create unbond TX - resultTx = doBeginUnbonding(t, port, seed, name, password, addr, validator1Owner) - tests.WaitForHeight(resultTx.Height+1, port) - - // query validator - bond = getDelegation(t, port, addr, validator1Owner) - require.Equal(t, "30/1", bond.Shares.String()) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.CheckTx.Code) - require.Equal(t, uint32(0), resultTx.DeliverTx.Code) - - // should the sender should have not received any coins as the unbonding has only just begun - // query sender - acc = getAccount(t, port, addr) - coins = acc.GetCoins() - require.Equal(t, int64(40), coins.AmountOf("steak").Int64()) - - // TODO add redelegation, need more complex capabilities such to mock context and -} - -func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.AccAddress) stake.Delegation { - - // get the account to get the sequence - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/%s/delegation/%s", delegatorAddr, validatorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var bond stake.Delegation - err := cdc.UnmarshalJSON([]byte(body), &bond) - require.Nil(t, err) - return bond -} - -func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { - // get the account to get the sequence - acc := getAccount(t, port, delegatorAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - - chainID := viper.GetString(client.FlagChainID) - - // send - jsonStr := []byte(fmt.Sprintf(`{ - "name": "%s", - "password": "%s", - "account_number": "%d", - "sequence": "%d", - "gas": "10000", - "chain_id": "%s", - "delegations": [ - { - "delegator_addr": "%s", - "validator_addr": "%s", - "delegation": { "denom": "%s", "amount": "60" } - } - ], - "begin_unbondings": [], - "complete_unbondings": [], - "begin_redelegates": [], - "complete_redelegates": [] - }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr, "steak")) - res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var results []ctypes.ResultBroadcastTxCommit - err := cdc.UnmarshalJSON([]byte(body), &results) - require.Nil(t, err) - - return results[0] -} - -func doBeginUnbonding(t *testing.T, port, seed, name, password string, - delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { - - // get the account to get the sequence - acc := getAccount(t, port, delegatorAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - - chainID := viper.GetString(client.FlagChainID) - - // send - jsonStr := []byte(fmt.Sprintf(`{ - "name": "%s", - "password": "%s", - "account_number": "%d", - "sequence": "%d", - "gas": "20000", - "chain_id": "%s", - "delegations": [], - "begin_unbondings": [ - { - "delegator_addr": "%s", - "validator_addr": "%s", - "shares": "30" - } - ], - "complete_unbondings": [], - "begin_redelegates": [], - "complete_redelegates": [] - }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr)) - res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var results []ctypes.ResultBroadcastTxCommit - err := cdc.UnmarshalJSON([]byte(body), &results) - require.Nil(t, err) - - return results[0] -} - -func doBeginRedelegation(t *testing.T, port, seed, name, password string, - delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { - - // get the account to get the sequence - acc := getAccount(t, port, delegatorAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - - chainID := viper.GetString(client.FlagChainID) - - // send - jsonStr := []byte(fmt.Sprintf(`{ - "name": "%s", - "password": "%s", - "account_number": "%d", - "sequence": "%d", - "gas": "10000", - "chain_id": "%s", - "delegations": [], - "begin_unbondings": [], - "complete_unbondings": [], - "begin_redelegates": [ - { - "delegator_addr": "%s", - "validator_src_addr": "%s", - "validator_dst_addr": "%s", - "shares": "30" - } - ], - "complete_redelegates": [] - }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorSrcAddr, validatorDstAddr)) - res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var results []ctypes.ResultBroadcastTxCommit - err := cdc.UnmarshalJSON([]byte(body), &results) - require.Nil(t, err) - - return results[0] -} - -func getValidatorsREST(t *testing.T, port string) []stake.BechValidator { - // get the account to get the sequence - res, body := Request(t, port, "GET", "/stake/validators", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var validators []stake.BechValidator - err := cdc.UnmarshalJSON([]byte(body), &validators) - require.Nil(t, err) - return validators -} From bb540d4dcb0aa0115b450fcdd60ad82a8df6e153 Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Tue, 31 Jul 2018 12:04:53 +0200 Subject: [PATCH 10/46] gopgk update --- Gopkg.lock | 188 +++++------------------------------------------------ 1 file changed, 17 insertions(+), 171 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index e6f15683550e..a3a943b3e2e7 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -2,76 +2,57 @@ [[projects]] - digest = "1:09a7f74eb6bb3c0f14d8926610c87f569c5cff68e978d30e9a3540aeb626fdf0" name = "github.com/bartekn/go-bip39" packages = ["."] - pruneopts = "UT" revision = "a05967ea095d81c8fe4833776774cfaff8e5036c" [[projects]] branch = "master" - digest = "1:d6afaeed1502aa28e80a4ed0981d570ad91b2579193404256ce672ed0a609e0d" name = "github.com/beorn7/perks" packages = ["quantile"] - pruneopts = "UT" revision = "3a771d992973f24aa725d07868b467d1ddfceafb" [[projects]] - digest = "1:1343a2963481a305ca4d051e84bc2abd16b601ee22ed324f8d605de1adb291b0" name = "github.com/bgentry/speakeasy" packages = ["."] - pruneopts = "UT" revision = "4aabc24848ce5fd31929f7d1e4ea74d3709c14cd" version = "v0.1.0" [[projects]] branch = "master" - digest = "1:70f6b224a59b2fa453debffa85c77f71063d8754b90c8c4fbad5794e2c382b0f" name = "github.com/brejski/hid" packages = ["."] - pruneopts = "UT" revision = "06112dcfcc50a7e0e4fd06e17f9791e788fdaafc" [[projects]] branch = "master" - digest = "1:2c00f064ba355903866cbfbf3f7f4c0fe64af6638cc7d1b8bdcf3181bc67f1d8" name = "github.com/btcsuite/btcd" packages = ["btcec"] - pruneopts = "UT" revision = "fdfc19097e7ac6b57035062056f5b7b4638b8898" [[projects]] - digest = "1:386de157f7d19259a7f9c81f26ce011223ce0f090353c1152ffdf730d7d10ac2" name = "github.com/btcsuite/btcutil" packages = ["bech32"] - pruneopts = "UT" revision = "d4cc87b860166d00d6b5b9e0d3b3d71d6088d4d4" [[projects]] - digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39" name = "github.com/davecgh/go-spew" packages = ["spew"] - pruneopts = "UT" revision = "346938d642f2ec3594ed81d874461961cd0faa76" version = "v1.1.0" [[projects]] - digest = "1:c7644c73a3d23741fdba8a99b1464e021a224b7e205be497271a8003a15ca41b" name = "github.com/ebuchman/fail-test" packages = ["."] - pruneopts = "UT" revision = "95f809107225be108efcf10a3509e4ea6ceef3c4" [[projects]] - digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd" name = "github.com/fsnotify/fsnotify" packages = ["."] - pruneopts = "UT" revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" version = "v1.4.7" [[projects]] - digest = "1:fdf5169073fb0ad6dc12a70c249145e30f4058647bea25f0abd48b6d9f228a11" name = "github.com/go-kit/kit" packages = [ "log", @@ -80,30 +61,24 @@ "metrics", "metrics/discard", "metrics/internal/lv", - "metrics/prometheus", + "metrics/prometheus" ] - pruneopts = "UT" revision = "4dc7be5d2d12881735283bcab7352178e190fc71" version = "v0.6.0" [[projects]] - digest = "1:31a18dae27a29aa074515e43a443abfd2ba6deb6d69309d8d7ce789c45f34659" name = "github.com/go-logfmt/logfmt" packages = ["."] - pruneopts = "UT" revision = "390ab7935ee28ec6b286364bba9b4dd6410cb3d5" version = "v0.3.0" [[projects]] - digest = "1:c4a2528ccbcabf90f9f3c464a5fc9e302d592861bbfd0b7135a7de8a943d0406" name = "github.com/go-stack/stack" packages = ["."] - pruneopts = "UT" revision = "259ab82a6cad3992b4e21ff5cac294ccb06474bc" version = "v1.7.0" [[projects]] - digest = "1:35621fe20f140f05a0c4ef662c26c0ab4ee50bca78aa30fe87d33120bd28165e" name = "github.com/gogo/protobuf" packages = [ "gogoproto", @@ -111,61 +86,49 @@ "proto", "protoc-gen-gogo/descriptor", "sortkeys", - "types", + "types" ] - pruneopts = "UT" revision = "636bf0302bc95575d69441b25a2603156ffdddf1" version = "v1.1.1" [[projects]] - digest = "1:17fe264ee908afc795734e8c4e63db2accabaf57326dbf21763a7d6b86096260" name = "github.com/golang/protobuf" packages = [ "proto", "ptypes", "ptypes/any", "ptypes/duration", - "ptypes/timestamp", + "ptypes/timestamp" ] - pruneopts = "UT" revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" version = "v1.1.0" [[projects]] branch = "master" - digest = "1:4a0c6bb4805508a6287675fac876be2ac1182539ca8a32468d8128882e9d5009" name = "github.com/golang/snappy" packages = ["."] - pruneopts = "UT" revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" [[projects]] - digest = "1:c79fb010be38a59d657c48c6ba1d003a8aa651fa56b579d959d74573b7dff8e1" name = "github.com/gorilla/context" packages = ["."] - pruneopts = "UT" revision = "08b5f424b9271eedf6f9f0ce86cb9396ed337a42" version = "v1.1.1" [[projects]] - digest = "1:e73f5b0152105f18bc131fba127d9949305c8693f8a762588a82a48f61756f5f" name = "github.com/gorilla/mux" packages = ["."] - pruneopts = "UT" revision = "e3702bed27f0d39777b0b37b664b6280e8ef8fbf" version = "v1.6.2" [[projects]] - digest = "1:43dd08a10854b2056e615d1b1d22ac94559d822e1f8b6fcc92c1a1057e85188e" name = "github.com/gorilla/websocket" packages = ["."] - pruneopts = "UT" revision = "ea4d1f681babbce9545c9c5f3d5194a789c89f5b" version = "v1.2.0" [[projects]] branch = "master" - digest = "1:12247a2e99a060cc692f6680e5272c8adf0b8f572e6bce0d7095e624c958a240" name = "github.com/hashicorp/hcl" packages = [ ".", @@ -176,206 +139,160 @@ "hcl/token", "json/parser", "json/scanner", - "json/token", + "json/token" ] - pruneopts = "UT" revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" [[projects]] - digest = "1:870d441fe217b8e689d7949fef6e43efbc787e50f200cb1e70dbca9204a1d6be" name = "github.com/inconshreveable/mousetrap" packages = ["."] - pruneopts = "UT" revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75" version = "v1.0" [[projects]] branch = "master" - digest = "1:39b27d1381a30421f9813967a5866fba35dc1d4df43a6eefe3b7a5444cb07214" name = "github.com/jmhodges/levigo" packages = ["."] - pruneopts = "UT" revision = "c42d9e0ca023e2198120196f842701bb4c55d7b9" [[projects]] branch = "master" - digest = "1:a64e323dc06b73892e5bb5d040ced475c4645d456038333883f58934abbf6f72" name = "github.com/kr/logfmt" packages = ["."] - pruneopts = "UT" revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0" [[projects]] - digest = "1:c568d7727aa262c32bdf8a3f7db83614f7af0ed661474b24588de635c20024c7" name = "github.com/magiconair/properties" packages = ["."] - pruneopts = "UT" revision = "c2353362d570a7bfa228149c62842019201cfb71" version = "v1.8.0" [[projects]] - digest = "1:d4d17353dbd05cb52a2a52b7fe1771883b682806f68db442b436294926bbfafb" name = "github.com/mattn/go-isatty" packages = ["."] - pruneopts = "UT" revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" version = "v0.0.3" [[projects]] - digest = "1:ff5ebae34cfbf047d505ee150de27e60570e8c394b3b8fdbb720ff6ac71985fc" name = "github.com/matttproud/golang_protobuf_extensions" packages = ["pbutil"] - pruneopts = "UT" revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" version = "v1.0.1" [[projects]] branch = "master" - digest = "1:e730597b38a4d56e2361e0b6236cb800e52c73cace2ff91396f4ff35792ddfa7" name = "github.com/mitchellh/mapstructure" packages = ["."] - pruneopts = "UT" revision = "bb74f1db0675b241733089d5a1faa5dd8b0ef57b" [[projects]] - digest = "1:95741de3af260a92cc5c7f3f3061e85273f5a81b5db20d4bd68da74bd521675e" name = "github.com/pelletier/go-toml" packages = ["."] - pruneopts = "UT" revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194" version = "v1.2.0" [[projects]] - digest = "1:40e195917a951a8bf867cd05de2a46aaf1806c50cf92eebf4c16f78cd196f747" name = "github.com/pkg/errors" packages = ["."] - pruneopts = "UT" revision = "645ef00459ed84a119197bfb8d8205042c6df63d" version = "v0.8.0" [[projects]] - digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" name = "github.com/pmezard/go-difflib" packages = ["difflib"] - pruneopts = "UT" revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" [[projects]] - digest = "1:c1a04665f9613e082e1209cf288bf64f4068dcd6c87a64bf1c4ff006ad422ba0" name = "github.com/prometheus/client_golang" packages = [ "prometheus", - "prometheus/promhttp", + "prometheus/promhttp" ] - pruneopts = "UT" revision = "ae27198cdd90bf12cd134ad79d1366a6cf49f632" [[projects]] branch = "master" - digest = "1:32d10bdfa8f09ecf13598324dba86ab891f11db3c538b6a34d1c3b5b99d7c36b" name = "github.com/prometheus/client_model" packages = ["go"] - pruneopts = "UT" revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c" [[projects]] branch = "master" - digest = "1:e469cd65badf7694aeb44874518606d93c1d59e7735d3754ad442782437d3cc3" name = "github.com/prometheus/common" packages = [ "expfmt", "internal/bitbucket.org/ww/goautoneg", - "model", + "model" ] - pruneopts = "UT" revision = "7600349dcfe1abd18d72d3a1770870d9800a7801" [[projects]] branch = "master" - digest = "1:20d9bb50dbee172242f9bcd6ec24a917dd7a5bb17421bf16a79c33111dea7db1" name = "github.com/prometheus/procfs" packages = [ ".", "internal/util", "nfs", - "xfs", + "xfs" ] - pruneopts = "UT" revision = "ae68e2d4c00fed4943b5f6698d504a5fe083da8a" [[projects]] - digest = "1:c4556a44e350b50a490544d9b06e9fba9c286c21d6c0e47f54f3a9214597298c" name = "github.com/rcrowley/go-metrics" packages = ["."] - pruneopts = "UT" revision = "e2704e165165ec55d062f5919b4b29494e9fa790" [[projects]] - digest = "1:bd1ae00087d17c5a748660b8e89e1043e1e5479d0fea743352cda2f8dd8c4f84" name = "github.com/spf13/afero" packages = [ ".", - "mem", + "mem" ] - pruneopts = "UT" revision = "787d034dfe70e44075ccc060d346146ef53270ad" version = "v1.1.1" [[projects]] - digest = "1:516e71bed754268937f57d4ecb190e01958452336fa73dbac880894164e91c1f" name = "github.com/spf13/cast" packages = ["."] - pruneopts = "UT" revision = "8965335b8c7107321228e3e3702cab9832751bac" version = "v1.2.0" [[projects]] - digest = "1:7ffc0983035bc7e297da3688d9fe19d60a420e9c38bef23f845c53788ed6a05e" name = "github.com/spf13/cobra" packages = ["."] - pruneopts = "UT" revision = "7b2c5ac9fc04fc5efafb60700713d4fa609b777b" version = "v0.0.1" [[projects]] branch = "master" - digest = "1:080e5f630945ad754f4b920e60b4d3095ba0237ebf88dc462eb28002932e3805" name = "github.com/spf13/jwalterweatherman" packages = ["."] - pruneopts = "UT" revision = "7c0cea34c8ece3fbeb2b27ab9b59511d360fb394" [[projects]] - digest = "1:9424f440bba8f7508b69414634aef3b2b3a877e522d8a4624692412805407bb7" name = "github.com/spf13/pflag" packages = ["."] - pruneopts = "UT" revision = "583c0c0531f06d5278b7d917446061adc344b5cd" version = "v1.0.1" [[projects]] - digest = "1:f8e1a678a2571e265f4bf91a3e5e32aa6b1474a55cb0ea849750cc177b664d96" name = "github.com/spf13/viper" packages = ["."] - pruneopts = "UT" revision = "25b30aa063fc18e48662b86996252eabdcf2f0c7" version = "v1.0.0" [[projects]] - digest = "1:7e8d267900c7fa7f35129a2a37596e38ed0f11ca746d6d9ba727980ee138f9f6" name = "github.com/stretchr/testify" packages = [ "assert", - "require", + "require" ] - pruneopts = "UT" revision = "12b6f73e6084dad08a7c6e575284b177ecafbc71" version = "v1.2.1" [[projects]] branch = "master" - digest = "1:b3cfb8d82b1601a846417c3f31c03a7961862cb2c98dcf0959c473843e6d9a2b" name = "github.com/syndtr/goleveldb" packages = [ "leveldb", @@ -389,41 +306,33 @@ "leveldb/opt", "leveldb/storage", "leveldb/table", - "leveldb/util", + "leveldb/util" ] - pruneopts = "UT" revision = "c4c61651e9e37fa117f53c5a906d3b63090d8445" [[projects]] branch = "master" - digest = "1:087aaa7920e5d0bf79586feb57ce01c35c830396ab4392798112e8aae8c47722" name = "github.com/tendermint/ed25519" packages = [ ".", "edwards25519", - "extra25519", + "extra25519" ] - pruneopts = "UT" revision = "d8387025d2b9d158cf4efb07e7ebf814bcce2057" [[projects]] - digest = "1:e9113641c839c21d8eaeb2c907c7276af1eddeed988df8322168c56b7e06e0e1" name = "github.com/tendermint/go-amino" packages = ["."] - pruneopts = "UT" revision = "2106ca61d91029c931fd54968c2bb02dc96b1412" version = "0.10.1" [[projects]] - digest = "1:d4a15d404afbf591e8be16fcda7f5ac87948d5c7531f9d909fd84cc730ab16e2" name = "github.com/tendermint/iavl" packages = ["."] - pruneopts = "UT" revision = "35f66e53d9b01e83b30de68b931f54b2477a94c9" version = "v0.9.2" [[projects]] - digest = "1:e10e95fd9f0a3a31686c9696f8995f6c04b0bc1b4ed0562a4f53cddc0b89d059" name = "github.com/tendermint/tendermint" packages = [ "abci/client", @@ -483,22 +392,18 @@ "state/txindex/kv", "state/txindex/null", "types", - "version", + "version" ] - pruneopts = "UT" revision = "5fdbcd70df57b71ffba71e1ff5f00d617852a9c0" version = "v0.22.6" [[projects]] - digest = "1:5bd938386bd1f61a581bf8cd6ff2b7b2f79c542929176db4ceb44965440dae07" name = "github.com/zondax/ledger-goclient" packages = ["."] - pruneopts = "UT" revision = "39ba4728c137c75718a21f9b4b3280fa31b9139b" [[projects]] branch = "master" - digest = "1:65a21a9e051d54eb6a3f70c659a765f706a998d9287c302269f4ed8054b2a852" name = "golang.org/x/crypto" packages = [ "blowfish", @@ -511,13 +416,11 @@ "pbkdf2", "poly1305", "ripemd160", - "salsa20/salsa", + "salsa20/salsa" ] - pruneopts = "UT" revision = "a49355c7e3f8fe157a85be2f77e6e269a0f89602" [[projects]] - digest = "1:d36f55a999540d29b6ea3c2ea29d71c76b1d9853fdcd3e5c5cb4836f2ba118f1" name = "golang.org/x/net" packages = [ "context", @@ -527,21 +430,17 @@ "idna", "internal/timeseries", "netutil", - "trace", + "trace" ] - pruneopts = "UT" revision = "292b43bbf7cb8d35ddf40f8d5100ef3837cced3f" [[projects]] branch = "master" - digest = "1:d773e525476aefa22ea944a5425a9bfb99819b2e67eeb9b1966454fd57522bbf" name = "golang.org/x/sys" packages = ["unix"] - pruneopts = "UT" revision = "1b2967e3c290b7c545b3db0deeda16e9be4f98a2" [[projects]] - digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" name = "golang.org/x/text" packages = [ "collate", @@ -557,22 +456,18 @@ "unicode/bidi", "unicode/cldr", "unicode/norm", - "unicode/rangetable", + "unicode/rangetable" ] - pruneopts = "UT" revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" version = "v0.3.0" [[projects]] branch = "master" - digest = "1:601e63e7d4577f907118bec825902505291918859d223bce015539e79f1160e3" name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] - pruneopts = "UT" revision = "e92b116572682a5b432ddd840aeaba2a559eeff1" [[projects]] - digest = "1:2dab32a43451e320e49608ff4542fdfc653c95dcc35d0065ec9c6c3dd540ed74" name = "google.golang.org/grpc" packages = [ ".", @@ -599,69 +494,20 @@ "stats", "status", "tap", - "transport", + "transport" ] - pruneopts = "UT" revision = "168a6198bcb0ef175f7dacec0b8691fc141dc9b8" version = "v1.13.0" [[projects]] - digest = "1:342378ac4dcb378a5448dd723f0784ae519383532f5e70ade24132c4c8693202" name = "gopkg.in/yaml.v2" packages = ["."] - pruneopts = "UT" revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" version = "v2.2.1" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - input-imports = [ - "github.com/bartekn/go-bip39", - "github.com/bgentry/speakeasy", - "github.com/btcsuite/btcd/btcec", - "github.com/golang/protobuf/proto", - "github.com/gorilla/mux", - "github.com/mattn/go-isatty", - "github.com/pkg/errors", - "github.com/spf13/cobra", - "github.com/spf13/pflag", - "github.com/spf13/viper", - "github.com/stretchr/testify/assert", - "github.com/stretchr/testify/require", - "github.com/tendermint/go-amino", - "github.com/tendermint/iavl", - "github.com/tendermint/tendermint/abci/server", - "github.com/tendermint/tendermint/abci/types", - "github.com/tendermint/tendermint/cmd/tendermint/commands", - "github.com/tendermint/tendermint/config", - "github.com/tendermint/tendermint/crypto", - "github.com/tendermint/tendermint/crypto/armor", - "github.com/tendermint/tendermint/crypto/ed25519", - "github.com/tendermint/tendermint/crypto/encoding/amino", - "github.com/tendermint/tendermint/crypto/merkle", - "github.com/tendermint/tendermint/crypto/secp256k1", - "github.com/tendermint/tendermint/crypto/tmhash", - "github.com/tendermint/tendermint/crypto/xsalsa20symmetric", - "github.com/tendermint/tendermint/libs/bech32", - "github.com/tendermint/tendermint/libs/cli", - "github.com/tendermint/tendermint/libs/cli/flags", - "github.com/tendermint/tendermint/libs/common", - "github.com/tendermint/tendermint/libs/db", - "github.com/tendermint/tendermint/libs/log", - "github.com/tendermint/tendermint/node", - "github.com/tendermint/tendermint/p2p", - "github.com/tendermint/tendermint/privval", - "github.com/tendermint/tendermint/proxy", - "github.com/tendermint/tendermint/rpc/client", - "github.com/tendermint/tendermint/rpc/core/types", - "github.com/tendermint/tendermint/rpc/lib/client", - "github.com/tendermint/tendermint/rpc/lib/server", - "github.com/tendermint/tendermint/types", - "github.com/tendermint/tendermint/version", - "github.com/zondax/ledger-goclient", - "golang.org/x/crypto/blowfish", - "golang.org/x/crypto/ripemd160", - ] + inputs-digest = "1d36d8462c35a9bd6f5a05cfa5f74bb2e7d532f0594e7e21c24d3105c5652166" solver-name = "gps-cdcl" solver-version = 1 From 88e1bd5d65f975dd7563605b958a2898087036b4 Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Tue, 31 Jul 2018 12:05:09 +0200 Subject: [PATCH 11/46] summary in place --- x/stake/client/rest/query.go | 892 +++++++++++++++++------------------ 1 file changed, 445 insertions(+), 447 deletions(-) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 0d2666e2caef..8503829ce4b8 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -3,7 +3,6 @@ package rest import ( "fmt" "net/http" - "strings" "github.com/gorilla/mux" @@ -21,26 +20,26 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec // GET /stake/delegators/{addr} // Get all delegations (delegation, undelegation and redelegation) from a delegator r.HandleFunc( - "/stake/delegators/{addr}", + "/stake/delegators/{delegatorAddr}", delegatorHandlerFn(ctx, cdc), ).Methods("GET") - // GET /stake/delegators/{addr}/txs // Get all staking txs (i.e msgs) from a delegator - r.HandleFunc( - "/stake/delegators/{addr}/txs", - delegatorTxsHandlerFn(ctx, cdc), - ).Queries("type", "{type}").Methods("GET") + // // GET /stake/delegators/{addr}/txs // Get all staking txs (i.e msgs) from a delegator + // r.HandleFunc( + // "/stake/delegators/{addr}/txs", + // delegatorTxsHandlerFn(ctx, cdc), + // ).Queries("type", "{type}").Methods("GET") - // GET /stake/delegators/{addr}/validators // Query all validators that a delegator is bonded to - r.HandleFunc( - "/stake/delegators/{delegatorAddr}/validators", - delegatorValidatorsHandlerFn(ctx, cdc), - ).Methods("GET") + // // GET /stake/delegators/{addr}/validators // Query all validators that a delegator is bonded to + // r.HandleFunc( + // "/stake/delegators/{delegatorAddr}/validators", + // delegatorValidatorsHandlerFn(ctx, cdc), + // ).Methods("GET") // GET /stake/delegators/{addr}/validators/{addr} // Query a validator info that a delegator is bonded to r.HandleFunc( - "/stake/delegators/{delegatorAddr}/validators/{validatorAddr}", - delegatorValidatorHandlerFn(ctx, cdc), + "/stake/delegators/{delegatorAddr}/delegations/{validatorAddr}", + delegationHandlerFn(ctx, cdc), ).Methods("GET") // GET /stake/delegators/{addr}/validators/{addr} @@ -51,10 +50,10 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec GET /stake/delegators/{addr}/validators/{addr}/txs?type=unbond // Get all unbonding txs to a validator performed by a delegator GET /stake/delegators/{addr}/validators/{addr}/txs?type=redelegate // Get all redelegation txs to a validator performed by a delegator */ - r.HandleFunc( - "/stake/delegators/{delegatorAddr}/validators/{validatorAddr}/txs", - stakingTxsHandlerFn(ctx, cdc), - ).Queries("type", "{type}").Methods("GET") + // r.HandleFunc( + // "/stake/delegators/{delegatorAddr}/validators/{validatorAddr}/txs", + // stakingTxsHandlerFn(ctx, cdc), + // ).Queries("type", "{type}").Methods("GET") // GET /stake/validators/ r.HandleFunc( @@ -63,22 +62,28 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec ).Methods("GET") // GET /stake/validators/{addr} - r.HandleFunc( - "/stake/validators/{addr}", - validatorHandlerFn(ctx, cdc), - ).Methods("GET") + // r.HandleFunc( + // "/stake/validators/{addr}", + // validatorHandlerFn(ctx, cdc), + // ).Methods("GET") // GET /stake/validators/{addr}/delegators // Don't think this is currently possible without changing keys } +// Aggregation of all delegations, unbondings and redelegations +type DelegationSummary struct { + Delegations []stake.Delegation `json:"delegations"` + UnbondingDelegations []stake.UnbondingDelegation `json:"unbonding_delegations"` + Redelegations []stake.Redelegation `json:"redelegations"` +} + // HTTP request handler to query a delegator delegations func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var validatorAddr sdk.AccAddress - var output []byte // txs from a single validator - var typesQuerySlice []string + var delegationSummary = DelegationSummary{} // read parameters vars := mux.Vars(r) @@ -91,16 +96,6 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu return } - // Get values from query - - typesQuery := r.URL.Query().Get("type") - typesQuerySlice = strings.Split(strings.TrimSpace(typesQuery), " ") - - noQuery := len(typesQuerySlice) == 0 - isBondTx := contains(typesQuerySlice, "bond") - isUnbondTx := contains(typesQuerySlice, "unbond") - isRedTx := contains(typesQuerySlice, "redelegate") - // Get all validators using key kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) if err != nil { @@ -122,334 +117,281 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu return } - for i, validator := range validators { - // get all transactions from the delegator to val and append - output = nil + for _, validator := range validators { validatorAddr = validator.Owner - // delegation - if noQuery || isBondTx { - key := stake.GetDelegationKey(delegatorAddr, validatorAddr) - - res, err := ctx.QueryStore(key, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) - return - } - // the query will return empty if there is no data for this record - if len(res) != 0 { - delegation, err := types.UnmarshalDelegation(cdc, key, res) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - outputBond, err := cdc.MarshalJSON(delegation) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - output = append(output, outputBond...) - } + delegationKey := stake.GetDelegationKey(delegatorAddr, validatorAddr) + marshalledDelegation, err := ctx.QueryStore(delegationKey, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + return } - if noQuery || isUnbondTx { - - key := stake.GetUBDKey(delegatorAddr, validatorAddr) - res, err := ctx.QueryStore(key, storeName) + // the query will return empty if there is no data for this record + if len(marshalledDelegation) != 0 { + delegation, err := types.UnmarshalDelegation(cdc, delegationKey, marshalledDelegation) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("couldn't unmarshall unbonding-delegation. Error: %s", err.Error()))) return } - // the query will return empty if there is no data for this record - if len(res) != 0 { - ubd, err := types.UnmarshalUBD(cdc, key, res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return - } - - outputUnbond, err := cdc.MarshalJSON(ubd) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - output = append(output, outputUnbond...) - } + delegationSummary.Delegations = append(delegationSummary.Delegations, delegation) } - if noQuery || isRedTx { - // keyValidatorFrom := stake.GetREDsByDelFromValSrcIndexKey(delegatorAddr, validatorAddr) - keyValidatorTo := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) - // All redelegations from source validator (i.e unbonding) - res, err := ctx.QueryStore(keyValidatorFrom, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) - return - } - - // the query will return empty if there is no data for this record - if len(res) != 0 { - red, err := types.UnmarshalRED(cdc, keyValidatorFrom, res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return - } - - outputFrom, err := cdc.MarshalJSON(red) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - output = append(output, outputFrom...) - } + undelegationKey := stake.GetUBDKey(delegatorAddr, validatorAddr) + marshalledUnbondingDelegation, err := ctx.QueryStore(undelegationKey, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } - // All redelegations to destination validator (i.e bonding) - res, err = ctx.QueryStore(keyValidatorTo, storeName) + // the query will return empty if there is no data for this record + if len(marshalledUnbondingDelegation) != 0 { + unbondingDelegation, err := types.UnmarshalUBD(cdc, undelegationKey, marshalledUnbondingDelegation) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("couldn't unmarshall unbonding-delegation. Error: %s", err.Error()))) return } - // the query will return empty if there is no data for this record - if len(res) != 0 { - red, err := types.UnmarshalRED(cdc, keyValidatorTo, res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return - } - - outputTo, err := cdc.MarshalJSON(red) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - output = append(output, outputTo...) - } - } - if len(output) == 0 { - w.WriteHeader(http.StatusNoContent) - return + delegationSummary.UnbondingDelegations = append(delegationSummary.UnbondingDelegations, unbondingDelegation) } - // success - w.Write(output) // write - } - } -} - -// HTTP request handler to query all staking txs (msgs) from a delegator -func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var output []byte - var typesQuerySlice []string - vars := mux.Vars(r) - bech32delegator := vars["addr"] - - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - node, err := ctx.GetNode() - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't get current Node information. Error: %s", err.Error()))) - return - } - - // Get values from query - - typesQuery := r.URL.Query().Get("type") - typesQuerySlice = strings.Split(strings.TrimSpace(typesQuery), " ") - - query := sdk.TagDelegator + " " + delegatorAddr.String() - noQuery := len(typesQuerySlice) == 0 - isBondTx := contains(typesQuerySlice, "bond") - isUnbondTx := contains(typesQuerySlice, "unbond") - isRedTx := contains(typesQuerySlice, "redelegate") - if !isBondTx || !isUnbondTx || !isRedTx { - w.WriteHeader(http.StatusNoContent) - return - } - - // TODO double check this - if noQuery || isBondTx { - query = query + " ANY " + sdk.TagAction - query = query + " delegate" - } - if noQuery || isUnbondTx { - query = query + " AND " + sdk.TagAction - query = query + " begin-unbonding" - - query = query + " OR " + sdk.TagAction - query = query + " complete-unbonding" - } - if noQuery || isRedTx { - query = query + " AND " + sdk.TagAction - query = query + " begin-redelegation" - - query = query + " OR " + sdk.TagAction - query = query + " complete-redelegation" - } - - page := 0 - perPage := 100 - prove := false - res, err := node.TxSearch(query, prove, page, perPage) - if err != nil { - w.WriteHeader(http.StatusNoContent) - return - } - - info, err := formatTxResults(cdc, res.Txs) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query txs. Error: %s", err.Error()))) - return - } - // success - output, err = cdc.MarshalJSON(info) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - w.Write(output) // write - } -} - -// HTTP request handler to query all delegator bonded validators -func delegatorValidatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - - var isBonded bool - var validatorAddr sdk.AccAddress - var bondedValidators []sdk.Validator - var output []byte // validators - var typesQuerySlice []string - - // read parameters - vars := mux.Vars(r) - bech32delegator := vars["delegatorAddr"] - - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - // Get all validators using key - kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query validators. Error: %s", err.Error()))) - return - } - - // the query will return empty if there are no validators - if len(kvs) == 0 { - w.WriteHeader(http.StatusNoContent) - return - } - - validators, err := getValidators(kvs, cdc) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) - return - } - for i, validator := range validators { - // get all transactions from the delegator to val and append - isBonded = false - validatorAddr = validator.Owner - - // Check if there if the delegator is bonded or redelegated to the validator - - keyDel := stake.GetDelegationKey(delegatorAddr, validatorAddr) - keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) - - res, err := ctx.QueryStore(keyDel, storeName) + // only querying redelegations to a validator as this should give us already all relegations + // if we also would put in redelegations from, we would have every redelegation double + keyRedelegateTo := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) + marshalledRedelegations, err := ctx.QueryStore(keyRedelegateTo, storeName) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) return } - if len(res) != 0 { - isBonded = true - } - - if !isBonded { - res, err = ctx.QueryStore(keyRed, storeName) + if len(marshalledRedelegations) != 0 { + redelegations, err := types.UnmarshalRED(cdc, keyRedelegateTo, marshalledRedelegations) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("couldn't unmarshall redelegations. Error: %s", err.Error()))) return } - if len(res) != 0 { - isBonded = true - } + delegationSummary.Redelegations = append(delegationSummary.Redelegations, redelegations) } - if isBonded { - kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) - return - } - - // the query will return empty if there are no validators - if len(kvs) == 0 { - continue - } - validator, err := getValidator(validatorAddr, kvs, cdc) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't get info from validator %s. Error: %s", validatorAddr.String(), err.Error()))) - return - } else if validator == nil && err == nil { - continue - } - bondedValidators = append(bondedValidators, validator) + output, err := cdc.MarshalJSON(delegationSummary) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return } + + // success + w.Write(output) // write } - // success - output, err = cdc.MarshalJSON(bondedValidators) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - w.Write(output) // write } } +// HTTP request handler to query all staking txs (msgs) from a delegator +// func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +// return func(w http.ResponseWriter, r *http.Request) { +// var output []byte +// var typesQuerySlice []string +// vars := mux.Vars(r) +// bech32delegator := vars["addr"] + +// delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) +// if err != nil { +// w.WriteHeader(http.StatusBadRequest) +// w.Write([]byte(err.Error())) +// return +// } + +// node, err := ctx.GetNode() +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("Couldn't get current Node information. Error: %s", err.Error()))) +// return +// } + +// // Get values from query + +// typesQuery := r.URL.Query().Get("type") +// typesQuerySlice = strings.Split(strings.TrimSpace(typesQuery), " ") + +// query := sdk.TagDelegator + " " + delegatorAddr.String() +// noQuery := len(typesQuerySlice) == 0 +// isBondTx := contains(typesQuerySlice, "bond") +// isUnbondTx := contains(typesQuerySlice, "unbond") +// isRedTx := contains(typesQuerySlice, "redelegate") +// if !isBondTx || !isUnbondTx || !isRedTx { +// w.WriteHeader(http.StatusNoContent) +// return +// } + +// // TODO double check this +// if noQuery || isBondTx { +// query = query + " ANY " + sdk.TagAction +// query = query + " delegate" +// } +// if noQuery || isUnbondTx { +// query = query + " AND " + sdk.TagAction +// query = query + " begin-unbonding" + +// query = query + " OR " + sdk.TagAction +// query = query + " complete-unbonding" +// } +// if noQuery || isRedTx { +// query = query + " AND " + sdk.TagAction +// query = query + " begin-redelegation" + +// query = query + " OR " + sdk.TagAction +// query = query + " complete-redelegation" +// } + +// page := 0 +// perPage := 100 +// prove := false +// res, err := node.TxSearch(query, prove, page, perPage) +// if err != nil { +// w.WriteHeader(http.StatusNoContent) +// return +// } + +// info, err := formatTxResults(cdc, res.Txs) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("couldn't query txs. Error: %s", err.Error()))) +// return +// } +// // success +// output, err = cdc.MarshalJSON(info) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(err.Error())) +// return +// } +// w.Write(output) // write +// } +// } + +// HTTP request handler to query all delegator bonded validators +// func delegatorValidatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +// return func(w http.ResponseWriter, r *http.Request) { + +// var isBonded bool +// var validatorAddr sdk.AccAddress +// var bondedValidators []sdk.Validator +// var output []byte // validators +// var typesQuerySlice []string + +// // read parameters +// vars := mux.Vars(r) +// bech32delegator := vars["delegatorAddr"] + +// delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) +// if err != nil { +// w.WriteHeader(http.StatusBadRequest) +// w.Write([]byte(err.Error())) +// return +// } + +// // Get all validators using key +// kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("couldn't query validators. Error: %s", err.Error()))) +// return +// } + +// // the query will return empty if there are no validators +// if len(kvs) == 0 { +// w.WriteHeader(http.StatusNoContent) +// return +// } + +// validators, err := getValidators(kvs, cdc) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) +// return +// } + +// for i, validator := range validators { +// // get all transactions from the delegator to val and append +// isBonded = false +// validatorAddr = validator.Owner + +// // Check if there if the delegator is bonded or redelegated to the validator + +// keyDel := stake.GetDelegationKey(delegatorAddr, validatorAddr) +// keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) + +// res, err := ctx.QueryStore(keyDel, storeName) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) +// return +// } + +// if len(res) != 0 { +// isBonded = true +// } + +// if !isBonded { +// res, err = ctx.QueryStore(keyRed, storeName) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) +// return +// } + +// if len(res) != 0 { +// isBonded = true +// } +// } + +// if isBonded { +// kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) +// return +// } + +// // the query will return empty if there are no validators +// if len(kvs) == 0 { +// continue +// } +// validator, err := getValidator(validatorAddr, kvs, cdc) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("Couldn't get info from validator %s. Error: %s", validatorAddr.String(), err.Error()))) +// return +// } else if validator == nil && err == nil { +// continue +// } +// bondedValidators = append(bondedValidators, validator) +// } +// } +// // success +// output, err = cdc.MarshalJSON(bondedValidators) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(err.Error())) +// return +// } +// w.Write(output) // write +// } +// } + // HTTP request handler to query a bonded validator -func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +func delegationHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + // read parameters - var isBonded bool - var output []byte vars := mux.Vars(r) bech32delegator := vars["delegatorAddr"] bech32validator := vars["validatorAddr"] @@ -468,110 +410,166 @@ func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http. return } - // Check if there if the delegator is bonded or redelegated to the validator + key := stake.GetDelegationKey(delegatorAddr, validatorAddr) - keyDel := stake.GetDelegationKey(delegatorAddr, validatorAddr) - keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) - - res, err := ctx.QueryStore(keyDel, storeName) + res, err := ctx.QueryStore(key, storeName) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) return } - if len(res) != 0 { - isBonded = true - } - - if !isBonded { - res, err = ctx.QueryStore(keyRed, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) - return - } - - if len(res) != 0 { - isBonded = true - } - } - - if isBonded { - kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) - return - } - - // the query will return empty if there are no validators - if len(kvs) == 0 { - w.WriteHeader(http.StatusNoContent) - return - } - validator, err := getValidator(validatorAddr, kvs, cdc) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't get info from validator %s. Error: %s", validatorAddr.String(), err.Error()))) - return - } else if validator == nil && err == nil { - w.WriteHeader(http.StatusNoContent) - return - } - // success - output, err = cdc.MarshalJSON(validator) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - } else { - // delegator is not bonded to any delegator + // the query will return empty if there is no data for this record + if len(res) == 0 { w.WriteHeader(http.StatusNoContent) return } - w.Write(output) - } -} - -// TODO Rename -func stakingTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - - // read parameters - vars := mux.Vars(r) - bech32delegator := vars["delegatorAddr"] - bech32validator := vars["validatorAddr"] - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + delegation, err := types.UnmarshalDelegation(cdc, key, res) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } - validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) + output, err := cdc.MarshalJSON(delegation) if err != nil { - w.WriteHeader(http.StatusBadRequest) + w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } - var typesQuerySlice []string - var output []byte // XXX not sure if this is append - typesQuery := r.URL.Query().Get("type") - typesQuerySlice = strings.Split(strings.TrimSpace(typesQuery), " ") - - noQuery := len(typesQuerySlice) == 0 - isBondTx := contains(typesQuerySlice, "bond") - isUnbondTx := contains(typesQuerySlice, "unbond") - isRedTx := contains(typesQuerySlice, "redelegate") - w.Write(output) } } +// func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +// return func(w http.ResponseWriter, r *http.Request) { +// // read parameters +// var isBonded bool +// var output []byte +// vars := mux.Vars(r) +// bech32delegator := vars["delegatorAddr"] +// bech32validator := vars["validatorAddr"] + +// delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) +// if err != nil { +// w.WriteHeader(http.StatusBadRequest) +// w.Write([]byte(err.Error())) +// return +// } + +// validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) +// if err != nil { +// w.WriteHeader(http.StatusBadRequest) +// w.Write([]byte(err.Error())) +// return +// } + +// // Check if there if the delegator is bonded or redelegated to the validator + +// keyDel := stake.GetDelegationKey(delegatorAddr, validatorAddr) +// keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) + +// res, err := ctx.QueryStore(keyDel, storeName) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) +// return +// } + +// if len(res) != 0 { +// isBonded = true +// } + +// if !isBonded { +// res, err = ctx.QueryStore(keyRed, storeName) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) +// return +// } + +// if len(res) != 0 { +// isBonded = true +// } +// } + +// if isBonded { +// kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) +// return +// } + +// // the query will return empty if there are no validators +// if len(kvs) == 0 { +// w.WriteHeader(http.StatusNoContent) +// return +// } +// validator, err := getValidator(validatorAddr, kvs, cdc) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("Couldn't get info from validator %s. Error: %s", validatorAddr.String(), err.Error()))) +// return +// } else if validator == nil && err == nil { +// w.WriteHeader(http.StatusNoContent) +// return +// } +// // success +// output, err = cdc.MarshalJSON(validator) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(err.Error())) +// return +// } +// } else { +// // delegator is not bonded to any delegator +// w.WriteHeader(http.StatusNoContent) +// return +// } +// w.Write(output) +// } +// } + +// TODO Rename +// func stakingTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +// return func(w http.ResponseWriter, r *http.Request) { + +// // read parameters +// vars := mux.Vars(r) +// bech32delegator := vars["delegatorAddr"] +// bech32validator := vars["validatorAddr"] + +// delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) +// if err != nil { +// w.WriteHeader(http.StatusBadRequest) +// w.Write([]byte(err.Error())) +// return +// } + +// validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) +// if err != nil { +// w.WriteHeader(http.StatusBadRequest) +// w.Write([]byte(err.Error())) +// return +// } + +// var typesQuerySlice []string +// var output []byte // XXX not sure if this is append +// typesQuery := r.URL.Query().Get("type") +// typesQuerySlice = strings.Split(strings.TrimSpace(typesQuery), " ") + +// noQuery := len(typesQuerySlice) == 0 +// isBondTx := contains(typesQuerySlice, "bond") +// isUnbondTx := contains(typesQuerySlice, "unbond") +// isRedTx := contains(typesQuerySlice, "redelegate") + +// w.Write(output) +// } +// } + // TODO bech32 // HTTP request handler to query list of validators func validatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { @@ -608,49 +606,49 @@ func validatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF } // HTTP request handler to query the validator information from a given validator address -func validatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - - var output []byte - // read parameters - vars := mux.Vars(r) - bech32validatorAddr := vars["addr"] - valAddress, err := sdk.AccAddressFromBech32(bech32validatorAddr) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) - return - } - - kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) - return - } - - // the query will return empty if there are no validators - if len(kvs) == 0 { - w.WriteHeader(http.StatusNoContent) - return - } - - validator, err := getValidator(valAddress, kvs, cdc) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return - } - output, err = cdc.MarshalJSON(validator) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - if output == nil { - w.WriteHeader(http.StatusNoContent) - return - } - w.Write(output) - } -} +// func validatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +// return func(w http.ResponseWriter, r *http.Request) { + +// var output []byte +// // read parameters +// vars := mux.Vars(r) +// bech32validatorAddr := vars["addr"] +// valAddress, err := sdk.AccAddressFromBech32(bech32validatorAddr) +// if err != nil { +// w.WriteHeader(http.StatusBadRequest) +// w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) +// return +// } + +// kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) +// return +// } + +// // the query will return empty if there are no validators +// if len(kvs) == 0 { +// w.WriteHeader(http.StatusNoContent) +// return +// } + +// validator, err := getValidator(valAddress, kvs, cdc) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) +// return +// } +// output, err = cdc.MarshalJSON(validator) +// if err != nil { +// w.WriteHeader(http.StatusInternalServerError) +// w.Write([]byte(err.Error())) +// return +// } +// if output == nil { +// w.WriteHeader(http.StatusNoContent) +// return +// } +// w.Write(output) +// } +// } From dbc284df2f8811eb8a1c8e1d4914f0aef314410e Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Tue, 31 Jul 2018 12:10:44 +0200 Subject: [PATCH 12/46] simple test for summary --- client/lcd/lcd_test.go | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 87566cff9335..4bfc0e949134 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -27,6 +27,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/stake/client/rest" ) func init() { @@ -421,7 +422,16 @@ func TestBonding(t *testing.T) { coins = acc.GetCoins() require.Equal(t, int64(40), coins.AmountOf("steak").Int64()) + summary := getDelegationSummary(t, port, addr) + + assert.Len(t, summary.Delegations, 1, "Delegation summary holds all delegations") + assert.Equal(t, "30/1", summary.Delegations[0].Shares.String()) + assert.Len(t, summary.UnbondingDelegations, 1, "Delegation summary holds all unbonding-delegations") + assert.Equal(t, "30", summary.UnbondingDelegations[0].Balance.Amount.String()) + // TODO add redelegation, need more complex capabilities such to mock context and + // TODO check summary for redelegation + // assert.Len(t, summary.Redelegations, 1, "Delegation summary holds all redelegations") } func TestSubmitProposal(t *testing.T) { @@ -722,7 +732,7 @@ func getSigningInfo(t *testing.T, port string, validatorAddr sdk.ValAddress) sla func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.AccAddress) stake.Delegation { // get the account to get the sequence - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/%s/delegation/%s", delegatorAddr, validatorAddr), nil) + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/delegations/%s", delegatorAddr, validatorAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) var bond stake.Delegation err := cdc.UnmarshalJSON([]byte(body), &bond) @@ -730,6 +740,18 @@ func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.A return bond } +func getDelegationSummary(t *testing.T, port string, delegatorAddr sdk.AccAddress) rest.DelegationSummary { + + // get the account to get the sequence + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s", delegatorAddr), nil) + fmt.Println("SUMMARY " + body) + require.Equal(t, http.StatusOK, res.StatusCode, body) + var summary rest.DelegationSummary + err := cdc.UnmarshalJSON([]byte(body), &summary) + require.Nil(t, err) + return summary +} + func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { // get the account to get the sequence acc := getAccount(t, port, delegatorAddr) From 551cef2ec4739e15e87efc8cf174d954bf28496b Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Tue, 31 Jul 2018 12:31:11 +0200 Subject: [PATCH 13/46] remove rat from share output --- client/lcd/lcd_test.go | 10 +++++----- x/stake/client/rest/query.go | 28 +++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 4bfc0e949134..5a4f18c3b75e 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -399,7 +399,7 @@ func TestBonding(t *testing.T) { // query validator bond := getDelegation(t, port, addr, validator1Owner) - require.Equal(t, "60/1", bond.Shares.String()) + require.Equal(t, "60.0000000000", bond.Shares) ////////////////////// // testing unbonding @@ -410,7 +410,7 @@ func TestBonding(t *testing.T) { // query validator bond = getDelegation(t, port, addr, validator1Owner) - require.Equal(t, "30/1", bond.Shares.String()) + require.Equal(t, "30.0000000000", bond.Shares) // check if tx was committed require.Equal(t, uint32(0), resultTx.CheckTx.Code) @@ -425,7 +425,7 @@ func TestBonding(t *testing.T) { summary := getDelegationSummary(t, port, addr) assert.Len(t, summary.Delegations, 1, "Delegation summary holds all delegations") - assert.Equal(t, "30/1", summary.Delegations[0].Shares.String()) + assert.Equal(t, "30.0000000000", summary.Delegations[0].Shares) assert.Len(t, summary.UnbondingDelegations, 1, "Delegation summary holds all unbonding-delegations") assert.Equal(t, "30", summary.UnbondingDelegations[0].Balance.Amount.String()) @@ -729,12 +729,12 @@ func getSigningInfo(t *testing.T, port string, validatorAddr sdk.ValAddress) sla return signingInfo } -func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.AccAddress) stake.Delegation { +func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.AccAddress) rest.DelegationWithoutRat { // get the account to get the sequence res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/delegations/%s", delegatorAddr, validatorAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var bond stake.Delegation + var bond rest.DelegationWithoutRat err := cdc.UnmarshalJSON([]byte(body), &bond) require.Nil(t, err) return bond diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 8503829ce4b8..e55f6e0b73d4 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -71,9 +71,17 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec // Don't think this is currently possible without changing keys } +// already resolve the rational shares to not handle this in the client +type DelegationWithoutRat struct { + DelegatorAddr sdk.AccAddress `json:"delegator_addr"` + ValidatorAddr sdk.AccAddress `json:"validator_addr"` + Shares string `json:"shares"` + Height int64 `json:"height"` +} + // Aggregation of all delegations, unbondings and redelegations type DelegationSummary struct { - Delegations []stake.Delegation `json:"delegations"` + Delegations []DelegationWithoutRat `json:"delegations"` UnbondingDelegations []stake.UnbondingDelegation `json:"unbonding_delegations"` Redelegations []stake.Redelegation `json:"redelegations"` } @@ -137,7 +145,14 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu return } - delegationSummary.Delegations = append(delegationSummary.Delegations, delegation) + outputDelegation := DelegationWithoutRat{ + DelegatorAddr: delegation.DelegatorAddr, + ValidatorAddr: delegation.ValidatorAddr, + Height: delegation.Height, + Shares: delegation.Shares.FloatString(), + } + + delegationSummary.Delegations = append(delegationSummary.Delegations, outputDelegation) } undelegationKey := stake.GetUBDKey(delegatorAddr, validatorAddr) @@ -432,7 +447,14 @@ func delegationHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF return } - output, err := cdc.MarshalJSON(delegation) + outputDelegation := DelegationWithoutRat{ + DelegatorAddr: delegation.DelegatorAddr, + ValidatorAddr: delegation.ValidatorAddr, + Height: delegation.Height, + Shares: delegation.Shares.FloatString(), + } + + output, err := cdc.MarshalJSON(outputDelegation) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) From deedd2c42a383498140025cbcd258fb39f138541 Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Tue, 31 Jul 2018 13:14:28 +0200 Subject: [PATCH 14/46] added validator endpoint --- client/lcd/lcd_test.go | 25 +++++++++- client/lcd/test_helpers.go | 1 + x/stake/client/rest/query.go | 88 +++++++++++++++++------------------- x/stake/client/rest/utils.go | 17 +++++-- 4 files changed, 79 insertions(+), 52 deletions(-) diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 5a4f18c3b75e..654610d6e1d8 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -375,6 +375,19 @@ func TestValidatorsQuery(t *testing.T) { require.True(t, foundVal, "pkBech %v, owner %v", pkBech, validators[0].Owner) } +func TestValidatorQuery(t *testing.T) { + cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}) + defer cleanup() + require.Equal(t, 1, len(pks)) + + validator1Owner := sdk.ValAddress(pks[0].Address()) + + validator := getValidator(t, port, validator1Owner) + bech32ValAddress, err := sdk.Bech32ifyValPub(pks[0]) + require.NoError(t, err) + assert.Equal(t, validator.PubKey, bech32ValAddress, "The returned validator does not hold the correct data") +} + func TestBonding(t *testing.T) { name, password, denom := "test", "1234567890", "steak" addr, seed := CreateAddr(t, "test", password, GetKeyBase(t)) @@ -744,7 +757,6 @@ func getDelegationSummary(t *testing.T, port string, delegatorAddr sdk.AccAddres // get the account to get the sequence res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s", delegatorAddr), nil) - fmt.Println("SUMMARY " + body) require.Equal(t, http.StatusOK, res.StatusCode, body) var summary rest.DelegationSummary err := cdc.UnmarshalJSON([]byte(body), &summary) @@ -881,6 +893,17 @@ func getValidators(t *testing.T, port string) []stake.BechValidator { return validators } +func getValidator(t *testing.T, port string, validatorAddr sdk.ValAddress) stake.BechValidator { + // get the account to get the sequence + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/validators/%s", validatorAddr.String()), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + fmt.Println(body) + var validator stake.BechValidator + err := cdc.UnmarshalJSON([]byte(body), &validator) + require.Nil(t, err) + return validator +} + func getProposal(t *testing.T, port string, proposalID int64) gov.Proposal { res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d", proposalID), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) diff --git a/client/lcd/test_helpers.go b/client/lcd/test_helpers.go index f50c0975183d..eccafb8c6121 100644 --- a/client/lcd/test_helpers.go +++ b/client/lcd/test_helpers.go @@ -256,6 +256,7 @@ func Request(t *testing.T, port, method, path string, payload []byte) (*http.Res res *http.Response ) url := fmt.Sprintf("http://localhost:%v%v", port, path) + fmt.Println("REQUEST " + method + " " + url) req, err := http.NewRequest(method, url, bytes.NewBuffer(payload)) require.Nil(t, err) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index e55f6e0b73d4..2da750fde5d8 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -62,10 +62,10 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec ).Methods("GET") // GET /stake/validators/{addr} - // r.HandleFunc( - // "/stake/validators/{addr}", - // validatorHandlerFn(ctx, cdc), - // ).Methods("GET") + r.HandleFunc( + "/stake/validators/{addr}", + validatorHandlerFn(ctx, cdc), + ).Methods("GET") // GET /stake/validators/{addr}/delegators // Don't think this is currently possible without changing keys @@ -628,49 +628,45 @@ func validatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF } // HTTP request handler to query the validator information from a given validator address -// func validatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { -// return func(w http.ResponseWriter, r *http.Request) { +func validatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { -// var output []byte -// // read parameters -// vars := mux.Vars(r) -// bech32validatorAddr := vars["addr"] -// valAddress, err := sdk.AccAddressFromBech32(bech32validatorAddr) -// if err != nil { -// w.WriteHeader(http.StatusBadRequest) -// w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) -// return -// } + var output []byte + // read parameters + vars := mux.Vars(r) + bech32validatorAddr := vars["addr"] + valAddress, err := sdk.ValAddressFromBech32(bech32validatorAddr) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return + } -// kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) -// return -// } + kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return + } -// // the query will return empty if there are no validators -// if len(kvs) == 0 { -// w.WriteHeader(http.StatusNoContent) -// return -// } + validator, err := getValidator(valAddress, kvs, cdc) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query validator. Error: %s", err.Error()))) + return + } -// validator, err := getValidator(valAddress, kvs, cdc) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) -// return -// } -// output, err = cdc.MarshalJSON(validator) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(err.Error())) -// return -// } -// if output == nil { -// w.WriteHeader(http.StatusNoContent) -// return -// } -// w.Write(output) -// } -// } + output, err = cdc.MarshalJSON(validator) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return + } + + if output == nil { + w.WriteHeader(http.StatusNoContent) + return + } + w.Write(output) + } +} diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 796afc36d8ec..c89c042a73b1 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -5,7 +5,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/x/stake" "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/pkg/errors" ) // Contains checks if the a given query contains one of the tx types @@ -40,19 +42,24 @@ func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechVali } // get Validator given an Account Address -func getValidator(address sdk.AccAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (sdk.Validator, error) { +func getValidator(address sdk.ValAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (stake.BechValidator, error) { // parse out the validators for _, kv := range validatorKVs { addr := kv.Key[1:] validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) if err != nil { - return nil, err + return stake.BechValidator{}, err } - ownerAddress := validator.GetOwner() + ownerAddress := validator.PubKey.Address() if reflect.DeepEqual(ownerAddress.Bytes(), address.Bytes()) { - return validator, nil + bech32Validator, err := validator.Bech32Validator() + if err != nil { + return stake.BechValidator{}, err + } + + return bech32Validator, nil } } - return nil, nil // validator Not Found + return stake.BechValidator{}, errors.Errorf("Couldn't find validator") // validator Not Found } From a013f84d64b9982c09fbf66e1ab53a2cbf6c6c87 Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Tue, 31 Jul 2018 13:37:22 +0200 Subject: [PATCH 15/46] added unbonding delegations endpoint --- client/lcd/lcd_test.go | 19 +++++ x/stake/client/rest/query.go | 157 +++++++++++++---------------------- 2 files changed, 76 insertions(+), 100 deletions(-) diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 654610d6e1d8..e8ad900280c1 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -435,6 +435,13 @@ func TestBonding(t *testing.T) { coins = acc.GetCoins() require.Equal(t, int64(40), coins.AmountOf("steak").Int64()) + // query unbonding delegation + validatorAddr := sdk.ValAddress(pks[0].Address()) + unbondings := getUndelegations(t, port, addr, validatorAddr) + assert.Len(t, unbondings, 1, "Unbondings holds all unbonding-delegations") + assert.Equal(t, "30", unbondings[0].Balance.Amount.String()) + + // query summary summary := getDelegationSummary(t, port, addr) assert.Len(t, summary.Delegations, 1, "Delegation summary holds all delegations") @@ -753,6 +760,18 @@ func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.A return bond } +func getUndelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) []stake.UnbondingDelegation { + + // get the account to get the sequence + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/unbonding_delegations/%s", delegatorAddr, validatorAddr), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + fmt.Println(body) + var unbondings []stake.UnbondingDelegation + err := cdc.UnmarshalJSON([]byte(body), &unbondings) + require.Nil(t, err) + return unbondings +} + func getDelegationSummary(t *testing.T, port string, delegatorAddr sdk.AccAddress) rest.DelegationSummary { // get the account to get the sequence diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 2da750fde5d8..3a8f8b94996c 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -36,12 +36,18 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec // delegatorValidatorsHandlerFn(ctx, cdc), // ).Methods("GET") - // GET /stake/delegators/{addr}/validators/{addr} // Query a validator info that a delegator is bonded to + // GET /stake/delegators/{addr}/delegations/{validatorAddr} // Query a delegation between a delegator and a validator r.HandleFunc( "/stake/delegators/{delegatorAddr}/delegations/{validatorAddr}", delegationHandlerFn(ctx, cdc), ).Methods("GET") + // GET /stake/delegators/{addr}/unbonding_delegations/{validatorAddr} // Query all unbonding_delegations between a delegator and a validator + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}", + unbondingDelegationsHandlerFn(ctx, cdc), + ).Methods("GET") + // GET /stake/delegators/{addr}/validators/{addr} /* @@ -292,115 +298,66 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu // } // } -// HTTP request handler to query all delegator bonded validators -// func delegatorValidatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { -// return func(w http.ResponseWriter, r *http.Request) { - -// var isBonded bool -// var validatorAddr sdk.AccAddress -// var bondedValidators []sdk.Validator -// var output []byte // validators -// var typesQuerySlice []string - -// // read parameters -// vars := mux.Vars(r) -// bech32delegator := vars["delegatorAddr"] - -// delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) -// if err != nil { -// w.WriteHeader(http.StatusBadRequest) -// w.Write([]byte(err.Error())) -// return -// } +// http request handler to query an unbonding-delegation +func unbondingDelegationsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { -// // Get all validators using key -// kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("couldn't query validators. Error: %s", err.Error()))) -// return -// } + // read parameters + vars := mux.Vars(r) + bech32delegator := vars["delegatorAddr"] + bech32validator := vars["validatorAddr"] -// // the query will return empty if there are no validators -// if len(kvs) == 0 { -// w.WriteHeader(http.StatusNoContent) -// return -// } + delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } -// validators, err := getValidators(kvs, cdc) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) -// return -// } + validatorAddr, err := sdk.ValAddressFromBech32(bech32validator) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + //TODO this seems wrong. we should query with the sdk.ValAddress and not sdk.AccAddress + validatorAddrAcc := sdk.AccAddress(validatorAddr) -// for i, validator := range validators { -// // get all transactions from the delegator to val and append -// isBonded = false -// validatorAddr = validator.Owner + key := stake.GetUBDKey(delegatorAddr, validatorAddrAcc) -// // Check if there if the delegator is bonded or redelegated to the validator + res, err := ctx.QueryStore(key, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } -// keyDel := stake.GetDelegationKey(delegatorAddr, validatorAddr) -// keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) + // the query will return empty if there is no data for this record + if len(res) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } -// res, err := ctx.QueryStore(keyDel, storeName) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) -// return -// } + ubd, err := types.UnmarshalUBD(cdc, key, res) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } -// if len(res) != 0 { -// isBonded = true -// } + // unbondings will be a list in the future but is not yet, but we want to keep the API consistent + ubdArray := []stake.UnbondingDelegation{ubd} -// if !isBonded { -// res, err = ctx.QueryStore(keyRed, storeName) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) -// return -// } - -// if len(res) != 0 { -// isBonded = true -// } -// } + output, err := cdc.MarshalJSON(ubdArray) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } -// if isBonded { -// kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) -// return -// } - -// // the query will return empty if there are no validators -// if len(kvs) == 0 { -// continue -// } -// validator, err := getValidator(validatorAddr, kvs, cdc) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("Couldn't get info from validator %s. Error: %s", validatorAddr.String(), err.Error()))) -// return -// } else if validator == nil && err == nil { -// continue -// } -// bondedValidators = append(bondedValidators, validator) -// } -// } -// // success -// output, err = cdc.MarshalJSON(bondedValidators) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(err.Error())) -// return -// } -// w.Write(output) // write -// } -// } + w.Write(output) + } +} // HTTP request handler to query a bonded validator func delegationHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { From 35c4ff76148482205382374ac74187394bb25fce Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Tue, 31 Jul 2018 13:52:08 +0200 Subject: [PATCH 16/46] fixed wrongly using accaddress for validators --- client/lcd/lcd_test.go | 16 ++++++++-------- x/stake/client/rest/query.go | 6 ++++-- x/stake/client/rest/tx.go | 33 ++++++++++++++++++++------------- 3 files changed, 32 insertions(+), 23 deletions(-) diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index e8ad900280c1..f35eb970e775 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -394,7 +394,7 @@ func TestBonding(t *testing.T) { cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) defer cleanup() - validator1Owner := sdk.AccAddress(pks[0].Address()) + validator1Owner := sdk.ValAddress(pks[0].Address()) // create bond TX resultTx := doDelegate(t, port, seed, name, password, addr, validator1Owner) @@ -749,7 +749,7 @@ func getSigningInfo(t *testing.T, port string, validatorAddr sdk.ValAddress) sla return signingInfo } -func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.AccAddress) rest.DelegationWithoutRat { +func getDelegation(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) rest.DelegationWithoutRat { // get the account to get the sequence res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/delegations/%s", delegatorAddr, validatorAddr), nil) @@ -783,7 +783,7 @@ func getDelegationSummary(t *testing.T, port string, delegatorAddr sdk.AccAddres return summary } -func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { +func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) (resultTx ctypes.ResultBroadcastTxCommit) { // get the account to get the sequence acc := getAccount(t, port, delegatorAddr) accnum := acc.GetAccountNumber() @@ -811,7 +811,7 @@ func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, "begin_redelegates": [], "complete_redelegates": [] }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr, "steak")) - res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) + res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delegatorAddr), jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) var results []ctypes.ResultBroadcastTxCommit @@ -822,7 +822,7 @@ func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, } func doBeginUnbonding(t *testing.T, port, seed, name, password string, - delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { + delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) (resultTx ctypes.ResultBroadcastTxCommit) { // get the account to get the sequence acc := getAccount(t, port, delegatorAddr) @@ -851,7 +851,7 @@ func doBeginUnbonding(t *testing.T, port, seed, name, password string, "begin_redelegates": [], "complete_redelegates": [] }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr)) - res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) + res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delegatorAddr), jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) var results []ctypes.ResultBroadcastTxCommit @@ -862,7 +862,7 @@ func doBeginUnbonding(t *testing.T, port, seed, name, password string, } func doBeginRedelegation(t *testing.T, port, seed, name, password string, - delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { + delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress) (resultTx ctypes.ResultBroadcastTxCommit) { // get the account to get the sequence acc := getAccount(t, port, delegatorAddr) @@ -892,7 +892,7 @@ func doBeginRedelegation(t *testing.T, port, seed, name, password string, ], "complete_redelegates": [] }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorSrcAddr, validatorDstAddr)) - res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) + res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delegatorAddr), jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) var results []ctypes.ResultBroadcastTxCommit diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 3a8f8b94996c..830e30e9039e 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -375,14 +375,16 @@ func delegationHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF return } - validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) + validatorAddr, err := sdk.ValAddressFromBech32(bech32validator) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } + //TODO this seems wrong. we should query with the sdk.ValAddress and not sdk.AccAddress + validatorAddrAcc := sdk.AccAddress(validatorAddr) - key := stake.GetDelegationKey(delegatorAddr, validatorAddr) + key := stake.GetDelegationKey(delegatorAddr, validatorAddrAcc) res, err := ctx.QueryStore(key, storeName) if err != nil { diff --git a/x/stake/client/rest/tx.go b/x/stake/client/rest/tx.go index a0f0416549d3..d5719bc24b81 100644 --- a/x/stake/client/rest/tx.go +++ b/x/stake/client/rest/tx.go @@ -19,7 +19,7 @@ import ( func registerTxRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { r.HandleFunc( - "/stake/delegations", + "/stake/delegators/{delegatorAddr}/delegations", editDelegationsRequestHandlerFn(cdc, kb, ctx), ).Methods("POST") } @@ -67,6 +67,7 @@ type EditDelegationsBody struct { // nolint: gocyclo // TODO: Split this up into several smaller functions, and remove the above nolint +// TODO: use sdk.ValAddress instead of sdk.AccAddress for validators in messages func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var m EditDelegationsBody @@ -105,7 +106,8 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) return } - validatorAddr, err := sdk.AccAddressFromBech32(msg.ValidatorAddr) + validatorAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) + validatorAddrAcc := sdk.AccAddress(validatorAddr) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) @@ -118,7 +120,7 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte } messages[i] = stake.MsgDelegate{ DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, + ValidatorAddr: validatorAddrAcc, Delegation: msg.Delegation, } i++ @@ -136,13 +138,15 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte w.Write([]byte("Must use own delegator address")) return } - validatorSrcAddr, err := sdk.AccAddressFromBech32(msg.ValidatorSrcAddr) + validatorSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) + validatorSrcAddrAcc := sdk.AccAddress(validatorSrcAddr) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } - validatorDstAddr, err := sdk.AccAddressFromBech32(msg.ValidatorDstAddr) + ValidatorDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) + ValidatorDstAddrAcc := sdk.AccAddress(ValidatorDstAddr) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) @@ -156,8 +160,8 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte } messages[i] = stake.MsgBeginRedelegate{ DelegatorAddr: delegatorAddr, - ValidatorSrcAddr: validatorSrcAddr, - ValidatorDstAddr: validatorDstAddr, + ValidatorSrcAddr: validatorSrcAddrAcc, + ValidatorDstAddr: ValidatorDstAddrAcc, SharesAmount: shares, } i++ @@ -170,13 +174,15 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) return } - validatorSrcAddr, err := sdk.AccAddressFromBech32(msg.ValidatorSrcAddr) + validatorSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) + validatorSrcAddrAcc := sdk.AccAddress(validatorSrcAddr) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } - validatorDstAddr, err := sdk.AccAddressFromBech32(msg.ValidatorDstAddr) + ValidatorDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) + ValidatorDstAddrAcc := sdk.AccAddress(ValidatorDstAddr) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) @@ -189,8 +195,8 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte } messages[i] = stake.MsgCompleteRedelegate{ DelegatorAddr: delegatorAddr, - ValidatorSrcAddr: validatorSrcAddr, - ValidatorDstAddr: validatorDstAddr, + ValidatorSrcAddr: validatorSrcAddrAcc, + ValidatorDstAddr: ValidatorDstAddrAcc, } i++ } @@ -207,7 +213,8 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte w.Write([]byte("Must use own delegator address")) return } - validatorAddr, err := sdk.AccAddressFromBech32(msg.ValidatorAddr) + validatorAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) + validatorAddrAcc := sdk.AccAddress(validatorAddr) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) @@ -221,7 +228,7 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte } messages[i] = stake.MsgBeginUnbonding{ DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, + ValidatorAddr: validatorAddrAcc, SharesAmount: shares, } i++ From 21a05d13849df2942e40e0982d57cf76317ee431 Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Tue, 31 Jul 2018 14:44:26 +0200 Subject: [PATCH 17/46] adding txs endpoint (not working) --- client/lcd/lcd_test.go | 28 ++++-- client/tx/query.go | 10 +- client/tx/search.go | 9 +- x/stake/client/rest/query.go | 179 +++++++++++++++++++---------------- 4 files changed, 129 insertions(+), 97 deletions(-) diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index f35eb970e775..9ae8720fce09 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -7,13 +7,13 @@ import ( "regexp" "testing" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/spf13/viper" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" cryptoKeys "github.com/cosmos/cosmos-sdk/crypto/keys" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/common" p2p "github.com/tendermint/tendermint/p2p" ctypes "github.com/tendermint/tendermint/rpc/core/types" @@ -317,13 +317,7 @@ func TestTxs(t *testing.T) { res, body = Request(t, port, "GET", fmt.Sprintf("/txs/%s", resultTx.Hash), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - type txInfo struct { - Hash common.HexBytes `json:"hash"` - Height int64 `json:"height"` - Tx sdk.Tx `json:"tx"` - Result abci.ResponseDeliverTx `json:"result"` - } - var indexedTxs []txInfo + var indexedTxs []tx.TxInfo // check if tx is queryable res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=tx.hash='%s'", resultTx.Hash), nil) @@ -452,6 +446,11 @@ func TestBonding(t *testing.T) { // TODO add redelegation, need more complex capabilities such to mock context and // TODO check summary for redelegation // assert.Len(t, summary.Redelegations, 1, "Delegation summary holds all redelegations") + + // query txs + // TODO fix, not returning txs + // txs := getBondingTxs(t, port, addr, "") + // assert.Len(t, txs, 2, "All Txs found") } func TestSubmitProposal(t *testing.T) { @@ -783,6 +782,17 @@ func getDelegationSummary(t *testing.T, port string, delegatorAddr sdk.AccAddres return summary } +func getBondingTxs(t *testing.T, port string, delegatorAddr sdk.AccAddress, query string) []tx.TxInfo { + + // get the account to get the sequence + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/txs?type=%s", delegatorAddr, query), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + var txs []tx.TxInfo + err := cdc.UnmarshalJSON([]byte(body), &txs) + require.Nil(t, err) + return txs +} + func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) (resultTx ctypes.ResultBroadcastTxCommit) { // get the account to get the sequence acc := getAccount(t, port, delegatorAddr) diff --git a/client/tx/query.go b/client/tx/query.go index dfe626c38cb8..6861d9b9db12 100644 --- a/client/tx/query.go +++ b/client/tx/query.go @@ -74,14 +74,14 @@ func queryTx(cdc *wire.Codec, ctx context.CoreContext, hashHexStr string, trustN return wire.MarshalJSONIndent(cdc, info) } -func formatTxResult(cdc *wire.Codec, res *ctypes.ResultTx) (txInfo, error) { +func formatTxResult(cdc *wire.Codec, res *ctypes.ResultTx) (TxInfo, error) { // TODO: verify the proof if requested tx, err := parseTx(cdc, res.Tx) if err != nil { - return txInfo{}, err + return TxInfo{}, err } - info := txInfo{ + info := TxInfo{ Hash: res.Hash, Height: res.Height, Tx: tx, @@ -90,8 +90,8 @@ func formatTxResult(cdc *wire.Codec, res *ctypes.ResultTx) (txInfo, error) { return info, nil } -// txInfo is used to prepare info to display -type txInfo struct { +// TxInfo is used to prepare info to display +type TxInfo struct { Hash common.HexBytes `json:"hash"` Height int64 `json:"height"` Tx sdk.Tx `json:"tx"` diff --git a/client/tx/search.go b/client/tx/search.go index 76c394f92855..a0231439d911 100644 --- a/client/tx/search.go +++ b/client/tx/search.go @@ -53,7 +53,7 @@ func SearchTxCmd(cdc *wire.Codec) *cobra.Command { return cmd } -func searchTxs(ctx context.CoreContext, cdc *wire.Codec, tags []string) ([]txInfo, error) { +func searchTxs(ctx context.CoreContext, cdc *wire.Codec, tags []string) ([]TxInfo, error) { if len(tags) == 0 { return nil, errors.New("must declare at least one tag to search") } @@ -74,7 +74,7 @@ func searchTxs(ctx context.CoreContext, cdc *wire.Codec, tags []string) ([]txInf return nil, err } - info, err := formatTxResults(cdc, res.Txs) + info, err := FormatTxResults(cdc, res.Txs) if err != nil { return nil, err } @@ -82,9 +82,10 @@ func searchTxs(ctx context.CoreContext, cdc *wire.Codec, tags []string) ([]txInf return info, nil } -func formatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]txInfo, error) { +// parse the indexed txs into an array of TxInfo +func FormatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]TxInfo, error) { var err error - out := make([]txInfo, len(res)) + out := make([]TxInfo, len(res)) for i := range res { out[i], err = formatTxResult(cdc, res[i]) if err != nil { diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 830e30e9039e..12e7208f8420 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -3,14 +3,19 @@ package rest import ( "fmt" "net/http" + "strings" "github.com/gorilla/mux" + rpcclient "github.com/tendermint/tendermint/rpc/client" + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/stake/tags" "github.com/cosmos/cosmos-sdk/x/stake/types" ) @@ -18,17 +23,17 @@ const storeName = "stake" func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec) { - // GET /stake/delegators/{addr} // Get all delegations (delegation, undelegation and redelegation) from a delegator + // GET /stake/delegators/{delegatorAddr} // Get all delegations (delegation, undelegation and redelegation) from a delegator r.HandleFunc( "/stake/delegators/{delegatorAddr}", delegatorHandlerFn(ctx, cdc), ).Methods("GET") - // // GET /stake/delegators/{addr}/txs // Get all staking txs (i.e msgs) from a delegator - // r.HandleFunc( - // "/stake/delegators/{addr}/txs", - // delegatorTxsHandlerFn(ctx, cdc), - // ).Queries("type", "{type}").Methods("GET") + // GET /stake/delegators/{delegatorAddr}/txs // Get all staking txs (i.e msgs) from a delegator + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/txs", + delegatorTxsHandlerFn(ctx, cdc), + ).Queries("type", "{type}").Methods("GET") // // GET /stake/delegators/{addr}/validators // Query all validators that a delegator is bonded to // r.HandleFunc( @@ -36,13 +41,13 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec // delegatorValidatorsHandlerFn(ctx, cdc), // ).Methods("GET") - // GET /stake/delegators/{addr}/delegations/{validatorAddr} // Query a delegation between a delegator and a validator + // GET /stake/delegators/{delegatorAddr}/delegations/{validatorAddr} // Query a delegation between a delegator and a validator r.HandleFunc( "/stake/delegators/{delegatorAddr}/delegations/{validatorAddr}", delegationHandlerFn(ctx, cdc), ).Methods("GET") - // GET /stake/delegators/{addr}/unbonding_delegations/{validatorAddr} // Query all unbonding_delegations between a delegator and a validator + // GET /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr} // Query all unbonding_delegations between a delegator and a validator r.HandleFunc( "/stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}", unbondingDelegationsHandlerFn(ctx, cdc), @@ -216,87 +221,103 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu } // HTTP request handler to query all staking txs (msgs) from a delegator -// func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { -// return func(w http.ResponseWriter, r *http.Request) { -// var output []byte -// var typesQuerySlice []string -// vars := mux.Vars(r) -// bech32delegator := vars["addr"] +func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var output []byte + var typesQuerySlice []string + vars := mux.Vars(r) + delegatorAddr := vars["delegatorAddr"] -// delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) -// if err != nil { -// w.WriteHeader(http.StatusBadRequest) -// w.Write([]byte(err.Error())) -// return -// } + _, err := sdk.AccAddressFromBech32(delegatorAddr) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } -// node, err := ctx.GetNode() -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("Couldn't get current Node information. Error: %s", err.Error()))) -// return -// } + node, err := ctx.GetNode() + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Couldn't get current Node information. Error: %s", err.Error()))) + return + } -// // Get values from query + // Get values from query -// typesQuery := r.URL.Query().Get("type") -// typesQuerySlice = strings.Split(strings.TrimSpace(typesQuery), " ") + typesQuery := r.URL.Query().Get("type") + typesQuerySlice = strings.Split(strings.TrimSpace(typesQuery), " ") -// query := sdk.TagDelegator + " " + delegatorAddr.String() -// noQuery := len(typesQuerySlice) == 0 -// isBondTx := contains(typesQuerySlice, "bond") -// isUnbondTx := contains(typesQuerySlice, "unbond") -// isRedTx := contains(typesQuerySlice, "redelegate") -// if !isBondTx || !isUnbondTx || !isRedTx { -// w.WriteHeader(http.StatusNoContent) -// return -// } + fmt.Println(delegatorAddr, typesQuerySlice) -// // TODO double check this -// if noQuery || isBondTx { -// query = query + " ANY " + sdk.TagAction -// query = query + " delegate" -// } -// if noQuery || isUnbondTx { -// query = query + " AND " + sdk.TagAction -// query = query + " begin-unbonding" + noQuery := len(typesQuerySlice) == 0 + isBondTx := contains(typesQuerySlice, "bond") + isUnbondTx := contains(typesQuerySlice, "unbond") + isRedTx := contains(typesQuerySlice, "redelegate") + var txs []tx.TxInfo = []tx.TxInfo{} -// query = query + " OR " + sdk.TagAction -// query = query + " complete-unbonding" -// } -// if noQuery || isRedTx { -// query = query + " AND " + sdk.TagAction -// query = query + " begin-redelegation" + // TODO double check this + if noQuery || isBondTx { + foundTxs, err := queryTxs(node, cdc, string(tags.ActionDelegate), delegatorAddr) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) + } + txs = append(txs, foundTxs...) + } + if noQuery || isUnbondTx { + foundTxs, err := queryTxs(node, cdc, string(tags.ActionBeginUnbonding), delegatorAddr) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) + } + txs = append(txs, foundTxs...) -// query = query + " OR " + sdk.TagAction -// query = query + " complete-redelegation" -// } + foundTxs, err = queryTxs(node, cdc, string(tags.ActionCompleteUnbonding), delegatorAddr) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) + } + txs = append(txs, foundTxs...) + } + if noQuery || isRedTx { + foundTxs, err := queryTxs(node, cdc, string(tags.ActionBeginRedelegation), delegatorAddr) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) + } + txs = append(txs, foundTxs...) -// page := 0 -// perPage := 100 -// prove := false -// res, err := node.TxSearch(query, prove, page, perPage) -// if err != nil { -// w.WriteHeader(http.StatusNoContent) -// return -// } + foundTxs, err = queryTxs(node, cdc, string(tags.ActionCompleteRedelegation), delegatorAddr) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) + } + txs = append(txs, foundTxs...) + } -// info, err := formatTxResults(cdc, res.Txs) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("couldn't query txs. Error: %s", err.Error()))) -// return -// } -// // success -// output, err = cdc.MarshalJSON(info) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(err.Error())) -// return -// } -// w.Write(output) // write -// } -// } + // success + output, err = cdc.MarshalJSON(txs) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + w.Write(output) // write + } +} + +func queryTxs(node rpcclient.Client, cdc *wire.Codec, tag string, delegatorAddr string) ([]tx.TxInfo, error) { + page := 0 + perPage := 100 + prove := false + query := tag + " AND " + delegatorAddr + res, err := node.TxSearch(query, prove, page, perPage) + if err != nil { + return nil, err + } + + return tx.FormatTxResults(cdc, res.Txs) +} // http request handler to query an unbonding-delegation func unbondingDelegationsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { From ee875370da68e0de0474623b28b7d93a7531bc02 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 31 Jul 2018 16:38:55 +0200 Subject: [PATCH 18/46] Refactor completed but redelegation txs --- client/lcd/lcd_test.go | 23 +++++++++++++++++++---- x/stake/client/rest/query.go | 13 +++++++------ 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 9ae8720fce09..c94018a40f2e 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -448,9 +448,14 @@ func TestBonding(t *testing.T) { // assert.Len(t, summary.Redelegations, 1, "Delegation summary holds all redelegations") // query txs - // TODO fix, not returning txs - // txs := getBondingTxs(t, port, addr, "") - // assert.Len(t, txs, 2, "All Txs found") + txs := getBondingTxs(t, port, addr, "") + assert.Len(t, txs, 2, "All Txs found") + + txs = getBondingTxs(t, port, addr, "bond") + assert.Len(t, txs, 1, "All bonding txs found") + + txs = getBondingTxs(t, port, addr, "unbond") + assert.Len(t, txs, 1, "All unbonding txs found") } func TestSubmitProposal(t *testing.T) { @@ -748,6 +753,8 @@ func getSigningInfo(t *testing.T, port string, validatorAddr sdk.ValAddress) sla return signingInfo } +// ============= Stake Module ================ + func getDelegation(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) rest.DelegationWithoutRat { // get the account to get the sequence @@ -785,7 +792,13 @@ func getDelegationSummary(t *testing.T, port string, delegatorAddr sdk.AccAddres func getBondingTxs(t *testing.T, port string, delegatorAddr sdk.AccAddress, query string) []tx.TxInfo { // get the account to get the sequence - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/txs?type=%s", delegatorAddr, query), nil) + var res *http.Response + var body string + if len(query) > 0 { + res, body = Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/txs?type=%s", delegatorAddr, query), nil) + } else { + res, body = Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/txs", delegatorAddr), nil) + } require.Equal(t, http.StatusOK, res.StatusCode, body) var txs []tx.TxInfo err := cdc.UnmarshalJSON([]byte(body), &txs) @@ -933,6 +946,8 @@ func getValidator(t *testing.T, port string, validatorAddr sdk.ValAddress) stake return validator } +// ============= Governance Module ================ + func getProposal(t *testing.T, port string, proposalID int64) gov.Proposal { res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d", proposalID), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 12e7208f8420..bdccecc57f6a 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -33,7 +33,7 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec r.HandleFunc( "/stake/delegators/{delegatorAddr}/txs", delegatorTxsHandlerFn(ctx, cdc), - ).Queries("type", "{type}").Methods("GET") + ).Methods("GET") // // GET /stake/delegators/{addr}/validators // Query all validators that a delegator is bonded to // r.HandleFunc( @@ -245,15 +245,16 @@ func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Handle // Get values from query typesQuery := r.URL.Query().Get("type") - typesQuerySlice = strings.Split(strings.TrimSpace(typesQuery), " ") - - fmt.Println(delegatorAddr, typesQuerySlice) + trimmedQuery := strings.TrimSpace(typesQuery) + if len(trimmedQuery) != 0 { + typesQuerySlice = strings.Split(trimmedQuery, " ") + } noQuery := len(typesQuerySlice) == 0 isBondTx := contains(typesQuerySlice, "bond") isUnbondTx := contains(typesQuerySlice, "unbond") isRedTx := contains(typesQuerySlice, "redelegate") - var txs []tx.TxInfo = []tx.TxInfo{} + var txs = []tx.TxInfo{} // TODO double check this if noQuery || isBondTx { @@ -310,7 +311,7 @@ func queryTxs(node rpcclient.Client, cdc *wire.Codec, tag string, delegatorAddr page := 0 perPage := 100 prove := false - query := tag + " AND " + delegatorAddr + query := tags.Action + "='" + tag + "' AND " + tags.Delegator + "='" + delegatorAddr + "'" res, err := node.TxSearch(query, prove, page, perPage) if err != nil { return nil, err From c3b29fa5babaca2d628ca63392bea75d9e30a683 Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Tue, 31 Jul 2018 16:44:46 +0200 Subject: [PATCH 19/46] removed some prints --- client/lcd/lcd_test.go | 2 -- cmd/cosmos-sdk-cli/cmd/init.go | 3 ++- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index c94018a40f2e..aa81a1d2dcb8 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -771,7 +771,6 @@ func getUndelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress, v // get the account to get the sequence res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/unbonding_delegations/%s", delegatorAddr, validatorAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - fmt.Println(body) var unbondings []stake.UnbondingDelegation err := cdc.UnmarshalJSON([]byte(body), &unbondings) require.Nil(t, err) @@ -939,7 +938,6 @@ func getValidator(t *testing.T, port string, validatorAddr sdk.ValAddress) stake // get the account to get the sequence res, body := Request(t, port, "GET", fmt.Sprintf("/stake/validators/%s", validatorAddr.String()), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - fmt.Println(body) var validator stake.BechValidator err := cdc.UnmarshalJSON([]byte(body), &validator) require.Nil(t, err) diff --git a/cmd/cosmos-sdk-cli/cmd/init.go b/cmd/cosmos-sdk-cli/cmd/init.go index d5d6422add3c..8cebc48f29a1 100644 --- a/cmd/cosmos-sdk-cli/cmd/init.go +++ b/cmd/cosmos-sdk-cli/cmd/init.go @@ -7,10 +7,11 @@ import ( "os" "strings" + "path/filepath" + "github.com/cosmos/cosmos-sdk/version" "github.com/spf13/cobra" tmversion "github.com/tendermint/tendermint/version" - "path/filepath" ) var remoteBasecoinPath = "github.com/cosmos/cosmos-sdk/examples/basecoin" From e867c8c5eb122fb5d2e3e9ed4f3ca9d48be89d03 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Tue, 31 Jul 2018 11:00:09 -0400 Subject: [PATCH 20/46] Merge pull request #1880: Staking Gaia-lite (ex LCD) refactor --- Gopkg.lock | 27 +- PENDING.md | 2 + client/lcd/lcd_test.go | 129 +++++++-- client/lcd/test_helpers.go | 3 +- client/tx/query.go | 10 +- client/tx/search.go | 9 +- cmd/cosmos-sdk-cli/cmd/init.go | 3 +- x/stake/client/rest/query.go | 397 +++++++++++++++++++++++----- x/stake/client/rest/test_helpers.go | 287 ++++++++++++++++++++ x/stake/client/rest/tx.go | 33 ++- x/stake/client/rest/utils.go | 65 +++++ x/stake/keeper/key.go | 8 + 12 files changed, 847 insertions(+), 126 deletions(-) create mode 100644 x/stake/client/rest/test_helpers.go create mode 100644 x/stake/client/rest/utils.go diff --git a/Gopkg.lock b/Gopkg.lock index e6f15683550e..888aa5011377 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -38,7 +38,7 @@ name = "github.com/btcsuite/btcd" packages = ["btcec"] pruneopts = "UT" - revision = "fdfc19097e7ac6b57035062056f5b7b4638b8898" + revision = "9a2f9524024889e129a5422aca2cff73cb3eabf6" [[projects]] digest = "1:386de157f7d19259a7f9c81f26ce011223ce0f090353c1152ffdf730d7d10ac2" @@ -165,12 +165,13 @@ [[projects]] branch = "master" - digest = "1:12247a2e99a060cc692f6680e5272c8adf0b8f572e6bce0d7095e624c958a240" + digest = "1:a361611b8c8c75a1091f00027767f7779b29cb37c456a71b8f2604c88057ab40" name = "github.com/hashicorp/hcl" packages = [ ".", "hcl/ast", "hcl/parser", + "hcl/printer", "hcl/scanner", "hcl/strconv", "hcl/token", @@ -231,11 +232,11 @@ [[projects]] branch = "master" - digest = "1:e730597b38a4d56e2361e0b6236cb800e52c73cace2ff91396f4ff35792ddfa7" + digest = "1:5ab79470a1d0fb19b041a624415612f8236b3c06070161a910562f2b2d064355" name = "github.com/mitchellh/mapstructure" packages = ["."] pruneopts = "UT" - revision = "bb74f1db0675b241733089d5a1faa5dd8b0ef57b" + revision = "f15292f7a699fcc1a38a80977f80a046874ba8ac" [[projects]] digest = "1:95741de3af260a92cc5c7f3f3061e85273f5a81b5db20d4bd68da74bd521675e" @@ -273,11 +274,11 @@ [[projects]] branch = "master" - digest = "1:32d10bdfa8f09ecf13598324dba86ab891f11db3c538b6a34d1c3b5b99d7c36b" + digest = "1:2d5cd61daa5565187e1d96bae64dbbc6080dacf741448e9629c64fd93203b0d4" name = "github.com/prometheus/client_model" packages = ["go"] pruneopts = "UT" - revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c" + revision = "5c3871d89910bfb32f5fcab2aa4b9ec68e65a99f" [[projects]] branch = "master" @@ -293,7 +294,7 @@ [[projects]] branch = "master" - digest = "1:20d9bb50dbee172242f9bcd6ec24a917dd7a5bb17421bf16a79c33111dea7db1" + digest = "1:8c49953a1414305f2ff5465147ee576dd705487c35b15918fcd4efdc0cb7a290" name = "github.com/prometheus/procfs" packages = [ ".", @@ -302,7 +303,7 @@ "xfs", ] pruneopts = "UT" - revision = "ae68e2d4c00fed4943b5f6698d504a5fe083da8a" + revision = "05ee40e3a273f7245e8777337fc7b46e533a9a92" [[projects]] digest = "1:c4556a44e350b50a490544d9b06e9fba9c286c21d6c0e47f54f3a9214597298c" @@ -514,7 +515,7 @@ "salsa20/salsa", ] pruneopts = "UT" - revision = "a49355c7e3f8fe157a85be2f77e6e269a0f89602" + revision = "c126467f60eb25f8f27e5a981f32a87e3965053f" [[projects]] digest = "1:d36f55a999540d29b6ea3c2ea29d71c76b1d9853fdcd3e5c5cb4836f2ba118f1" @@ -534,11 +535,11 @@ [[projects]] branch = "master" - digest = "1:d773e525476aefa22ea944a5425a9bfb99819b2e67eeb9b1966454fd57522bbf" + digest = "1:8466957fb2af510f68b13aec64ccad13e9e756dc1da3ea28c422f8ac410e56f0" name = "golang.org/x/sys" packages = ["unix"] pruneopts = "UT" - revision = "1b2967e3c290b7c545b3db0deeda16e9be4f98a2" + revision = "bd9dbc187b6e1dacfdd2722a87e83093c2d7bd6e" [[projects]] digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" @@ -565,11 +566,11 @@ [[projects]] branch = "master" - digest = "1:601e63e7d4577f907118bec825902505291918859d223bce015539e79f1160e3" + digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c" name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] pruneopts = "UT" - revision = "e92b116572682a5b432ddd840aeaba2a559eeff1" + revision = "2a72893556e4d1f6c795a4c039314c9fa751eedb" [[projects]] digest = "1:2dab32a43451e320e49608ff4542fdfc653c95dcc35d0065ec9c6c3dd540ed74" diff --git a/PENDING.md b/PENDING.md index 45a606016c13..b0eeef8d2cd3 100644 --- a/PENDING.md +++ b/PENDING.md @@ -1,6 +1,8 @@ ## PENDING BREAKING CHANGES +* API + - \#1880 [x/stake] changed the endpoints to be more REST-ful * Update to tendermint v0.22.5. This involves changing all of the cryptography imports. [Ref](https://github.com/tendermint/tendermint/pull/1966) * [baseapp] Msgs are no longer run on CheckTx, removed `ctx.IsCheckTx()` * [x/gov] CLI flag changed from `proposalID` to `proposal-id` diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 25c47ba6d150..aab88125840f 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -7,13 +7,13 @@ import ( "regexp" "testing" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/spf13/viper" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" cryptoKeys "github.com/cosmos/cosmos-sdk/crypto/keys" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/common" p2p "github.com/tendermint/tendermint/p2p" ctypes "github.com/tendermint/tendermint/rpc/core/types" @@ -27,6 +27,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/stake/client/rest" ) func init() { @@ -316,13 +317,7 @@ func TestTxs(t *testing.T) { res, body = Request(t, port, "GET", fmt.Sprintf("/txs/%s", resultTx.Hash), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - type txInfo struct { - Hash common.HexBytes `json:"hash"` - Height int64 `json:"height"` - Tx sdk.Tx `json:"tx"` - Result abci.ResponseDeliverTx `json:"result"` - } - var indexedTxs []txInfo + var indexedTxs []tx.TxInfo // check if tx is queryable res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=tx.hash='%s'", resultTx.Hash), nil) @@ -374,13 +369,26 @@ func TestValidatorsQuery(t *testing.T) { require.True(t, foundVal, "pkBech %v, owner %v", pkBech, validators[0].Owner) } +func TestValidatorQuery(t *testing.T) { + cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}) + defer cleanup() + require.Equal(t, 1, len(pks)) + + validator1Owner := sdk.ValAddress(pks[0].Address()) + + validator := getValidator(t, port, validator1Owner) + bech32ValAddress, err := sdk.Bech32ifyValPub(pks[0]) + require.NoError(t, err) + assert.Equal(t, validator.PubKey, bech32ValAddress, "The returned validator does not hold the correct data") +} + func TestBonding(t *testing.T) { name, password, denom := "test", "1234567890", "steak" addr, seed := CreateAddr(t, "test", password, GetKeyBase(t)) cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) defer cleanup() - validator1Owner := sdk.AccAddress(pks[0].Address()) + validator1Owner := sdk.ValAddress(pks[0].Address()) // create bond TX resultTx := doDelegate(t, port, seed, name, password, addr, validator1Owner) @@ -398,7 +406,7 @@ func TestBonding(t *testing.T) { // query validator bond := getDelegation(t, port, addr, validator1Owner) - require.Equal(t, "60/1", bond.Shares.String()) + require.Equal(t, "60.0000000000", bond.Shares) ////////////////////// // testing unbonding @@ -409,7 +417,7 @@ func TestBonding(t *testing.T) { // query validator bond = getDelegation(t, port, addr, validator1Owner) - require.Equal(t, "30/1", bond.Shares.String()) + require.Equal(t, "30.0000000000", bond.Shares) // check if tx was committed require.Equal(t, uint32(0), resultTx.CheckTx.Code) @@ -421,7 +429,33 @@ func TestBonding(t *testing.T) { coins = acc.GetCoins() require.Equal(t, int64(40), coins.AmountOf("steak").Int64()) + // query unbonding delegation + validatorAddr := sdk.ValAddress(pks[0].Address()) + unbondings := getUndelegations(t, port, addr, validatorAddr) + assert.Len(t, unbondings, 1, "Unbondings holds all unbonding-delegations") + assert.Equal(t, "30", unbondings[0].Balance.Amount.String()) + + // query summary + summary := getDelegationSummary(t, port, addr) + + assert.Len(t, summary.Delegations, 1, "Delegation summary holds all delegations") + assert.Equal(t, "30.0000000000", summary.Delegations[0].Shares) + assert.Len(t, summary.UnbondingDelegations, 1, "Delegation summary holds all unbonding-delegations") + assert.Equal(t, "30", summary.UnbondingDelegations[0].Balance.Amount.String()) + // TODO add redelegation, need more complex capabilities such to mock context and + // TODO check summary for redelegation + // assert.Len(t, summary.Redelegations, 1, "Delegation summary holds all redelegations") + + // query txs + txs := getBondingTxs(t, port, addr, "") + assert.Len(t, txs, 2, "All Txs found") + + txs = getBondingTxs(t, port, addr, "bond") + assert.Len(t, txs, 1, "All bonding txs found") + + txs = getBondingTxs(t, port, addr, "unbond") + assert.Len(t, txs, 1, "All unbonding txs found") } func TestSubmitProposal(t *testing.T) { @@ -719,18 +753,59 @@ func getSigningInfo(t *testing.T, port string, validatorAddr sdk.ValAddress) sla return signingInfo } -func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.AccAddress) stake.Delegation { +// ============= Stake Module ================ + +func getDelegation(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) rest.DelegationWithoutRat { // get the account to get the sequence - res, body := Request(t, port, "GET", fmt.Sprintf("/stake/%s/delegation/%s", delegatorAddr, validatorAddr), nil) + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/delegations/%s", delegatorAddr, validatorAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var bond stake.Delegation + var bond rest.DelegationWithoutRat err := cdc.UnmarshalJSON([]byte(body), &bond) require.Nil(t, err) return bond } -func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { +func getUndelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) []stake.UnbondingDelegation { + + // get the account to get the sequence + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/unbonding_delegations/%s", delegatorAddr, validatorAddr), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + var unbondings []stake.UnbondingDelegation + err := cdc.UnmarshalJSON([]byte(body), &unbondings) + require.Nil(t, err) + return unbondings +} + +func getDelegationSummary(t *testing.T, port string, delegatorAddr sdk.AccAddress) rest.DelegationSummary { + + // get the account to get the sequence + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s", delegatorAddr), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + var summary rest.DelegationSummary + err := cdc.UnmarshalJSON([]byte(body), &summary) + require.Nil(t, err) + return summary +} + +func getBondingTxs(t *testing.T, port string, delegatorAddr sdk.AccAddress, query string) []tx.TxInfo { + + // get the account to get the sequence + var res *http.Response + var body string + if len(query) > 0 { + res, body = Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/txs?type=%s", delegatorAddr, query), nil) + } else { + res, body = Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/txs", delegatorAddr), nil) + } + require.Equal(t, http.StatusOK, res.StatusCode, body) + var txs []tx.TxInfo + err := cdc.UnmarshalJSON([]byte(body), &txs) + require.Nil(t, err) + return txs +} + +func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) (resultTx ctypes.ResultBroadcastTxCommit) { // get the account to get the sequence acc := getAccount(t, port, delegatorAddr) accnum := acc.GetAccountNumber() @@ -758,7 +833,7 @@ func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, "begin_redelegates": [], "complete_redelegates": [] }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr, "steak")) - res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) + res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delegatorAddr), jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) var results []ctypes.ResultBroadcastTxCommit @@ -769,7 +844,7 @@ func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, } func doBeginUnbonding(t *testing.T, port, seed, name, password string, - delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { + delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) (resultTx ctypes.ResultBroadcastTxCommit) { // get the account to get the sequence acc := getAccount(t, port, delegatorAddr) @@ -798,7 +873,7 @@ func doBeginUnbonding(t *testing.T, port, seed, name, password string, "begin_redelegates": [], "complete_redelegates": [] }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorAddr)) - res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) + res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delegatorAddr), jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) var results []ctypes.ResultBroadcastTxCommit @@ -809,7 +884,7 @@ func doBeginUnbonding(t *testing.T, port, seed, name, password string, } func doBeginRedelegation(t *testing.T, port, seed, name, password string, - delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { + delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress) (resultTx ctypes.ResultBroadcastTxCommit) { // get the account to get the sequence acc := getAccount(t, port, delegatorAddr) @@ -839,7 +914,7 @@ func doBeginRedelegation(t *testing.T, port, seed, name, password string, ], "complete_redelegates": [] }`, name, password, accnum, sequence, chainID, delegatorAddr, validatorSrcAddr, validatorDstAddr)) - res, body := Request(t, port, "POST", "/stake/delegations", jsonStr) + res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delegatorAddr), jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) var results []ctypes.ResultBroadcastTxCommit @@ -859,6 +934,18 @@ func getValidators(t *testing.T, port string) []stake.BechValidator { return validators } +func getValidator(t *testing.T, port string, validatorAddr sdk.ValAddress) stake.BechValidator { + // get the account to get the sequence + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/validators/%s", validatorAddr.String()), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + var validator stake.BechValidator + err := cdc.UnmarshalJSON([]byte(body), &validator) + require.Nil(t, err) + return validator +} + +// ============= Governance Module ================ + func getProposal(t *testing.T, port string, proposalID int64) gov.Proposal { res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d", proposalID), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) diff --git a/client/lcd/test_helpers.go b/client/lcd/test_helpers.go index 6db10ef6795f..48de9598c28d 100644 --- a/client/lcd/test_helpers.go +++ b/client/lcd/test_helpers.go @@ -121,7 +121,7 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress config.TxIndex.IndexAllTags = true logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) - logger = log.NewFilter(logger, log.AllowDebug()) + logger = log.NewFilter(logger, log.AllowError()) privValidatorFile := config.PrivValidatorFile() privVal := pvm.LoadOrGenFilePV(privValidatorFile) @@ -256,6 +256,7 @@ func Request(t *testing.T, port, method, path string, payload []byte) (*http.Res res *http.Response ) url := fmt.Sprintf("http://localhost:%v%v", port, path) + fmt.Println("REQUEST " + method + " " + url) req, err := http.NewRequest(method, url, bytes.NewBuffer(payload)) require.Nil(t, err) diff --git a/client/tx/query.go b/client/tx/query.go index dfe626c38cb8..6861d9b9db12 100644 --- a/client/tx/query.go +++ b/client/tx/query.go @@ -74,14 +74,14 @@ func queryTx(cdc *wire.Codec, ctx context.CoreContext, hashHexStr string, trustN return wire.MarshalJSONIndent(cdc, info) } -func formatTxResult(cdc *wire.Codec, res *ctypes.ResultTx) (txInfo, error) { +func formatTxResult(cdc *wire.Codec, res *ctypes.ResultTx) (TxInfo, error) { // TODO: verify the proof if requested tx, err := parseTx(cdc, res.Tx) if err != nil { - return txInfo{}, err + return TxInfo{}, err } - info := txInfo{ + info := TxInfo{ Hash: res.Hash, Height: res.Height, Tx: tx, @@ -90,8 +90,8 @@ func formatTxResult(cdc *wire.Codec, res *ctypes.ResultTx) (txInfo, error) { return info, nil } -// txInfo is used to prepare info to display -type txInfo struct { +// TxInfo is used to prepare info to display +type TxInfo struct { Hash common.HexBytes `json:"hash"` Height int64 `json:"height"` Tx sdk.Tx `json:"tx"` diff --git a/client/tx/search.go b/client/tx/search.go index 76c394f92855..a0231439d911 100644 --- a/client/tx/search.go +++ b/client/tx/search.go @@ -53,7 +53,7 @@ func SearchTxCmd(cdc *wire.Codec) *cobra.Command { return cmd } -func searchTxs(ctx context.CoreContext, cdc *wire.Codec, tags []string) ([]txInfo, error) { +func searchTxs(ctx context.CoreContext, cdc *wire.Codec, tags []string) ([]TxInfo, error) { if len(tags) == 0 { return nil, errors.New("must declare at least one tag to search") } @@ -74,7 +74,7 @@ func searchTxs(ctx context.CoreContext, cdc *wire.Codec, tags []string) ([]txInf return nil, err } - info, err := formatTxResults(cdc, res.Txs) + info, err := FormatTxResults(cdc, res.Txs) if err != nil { return nil, err } @@ -82,9 +82,10 @@ func searchTxs(ctx context.CoreContext, cdc *wire.Codec, tags []string) ([]txInf return info, nil } -func formatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]txInfo, error) { +// parse the indexed txs into an array of TxInfo +func FormatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]TxInfo, error) { var err error - out := make([]txInfo, len(res)) + out := make([]TxInfo, len(res)) for i := range res { out[i], err = formatTxResult(cdc, res[i]) if err != nil { diff --git a/cmd/cosmos-sdk-cli/cmd/init.go b/cmd/cosmos-sdk-cli/cmd/init.go index d5d6422add3c..8cebc48f29a1 100644 --- a/cmd/cosmos-sdk-cli/cmd/init.go +++ b/cmd/cosmos-sdk-cli/cmd/init.go @@ -7,10 +7,11 @@ import ( "os" "strings" + "path/filepath" + "github.com/cosmos/cosmos-sdk/version" "github.com/spf13/cobra" tmversion "github.com/tendermint/tendermint/version" - "path/filepath" ) var remoteBasecoinPath = "github.com/cosmos/cosmos-sdk/examples/basecoin" diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 9a4c3755ddcc..16ee07f35ced 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -3,14 +3,19 @@ package rest import ( "fmt" "net/http" + "strings" "github.com/gorilla/mux" + rpcclient "github.com/tendermint/tendermint/rpc/client" + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/stake/tags" "github.com/cosmos/cosmos-sdk/x/stake/types" ) @@ -18,35 +23,90 @@ const storeName = "stake" func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec) { + // GET /stake/delegators/{delegatorAddr} // Get all delegations (delegation, undelegation and redelegation) from a delegator r.HandleFunc( - "/stake/{delegator}/delegation/{validator}", - delegationHandlerFn(ctx, cdc), + "/stake/delegators/{delegatorAddr}", + delegatorHandlerFn(ctx, cdc), ).Methods("GET") + // GET /stake/delegators/{delegatorAddr}/txs // Get all staking txs (i.e msgs) from a delegator r.HandleFunc( - "/stake/{delegator}/ubd/{validator}", - ubdHandlerFn(ctx, cdc), + "/stake/delegators/{delegatorAddr}/txs", + delegatorTxsHandlerFn(ctx, cdc), ).Methods("GET") + // // GET /stake/delegators/{addr}/validators // Query all validators that a delegator is bonded to + // r.HandleFunc( + // "/stake/delegators/{delegatorAddr}/validators", + // delegatorValidatorsHandlerFn(ctx, cdc), + // ).Methods("GET") + + // GET /stake/delegators/{delegatorAddr}/delegations/{validatorAddr} // Query a delegation between a delegator and a validator r.HandleFunc( - "/stake/{delegator}/red/{validator_src}/{validator_dst}", - redHandlerFn(ctx, cdc), + "/stake/delegators/{delegatorAddr}/delegations/{validatorAddr}", + delegationHandlerFn(ctx, cdc), ).Methods("GET") + // GET /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr} // Query all unbonding_delegations between a delegator and a validator + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}", + unbondingDelegationsHandlerFn(ctx, cdc), + ).Methods("GET") + + // GET /stake/delegators/{addr}/validators/{addr} + + /* + GET /stake/delegators/{addr}/validators/{addr}/txs // Get all txs to a validator performed by a delegator + GET /stake/delegators/{addr}/validators/{addr}/txs?type=bond // Get all bonding txs to a validator performed by a delegator + GET /stake/delegators/{addr}/validators/{addr}/txs?type=unbond // Get all unbonding txs to a validator performed by a delegator + GET /stake/delegators/{addr}/validators/{addr}/txs?type=redelegate // Get all redelegation txs to a validator performed by a delegator + */ + // r.HandleFunc( + // "/stake/delegators/{delegatorAddr}/validators/{validatorAddr}/txs", + // stakingTxsHandlerFn(ctx, cdc), + // ).Queries("type", "{type}").Methods("GET") + + // GET /stake/validators/ r.HandleFunc( "/stake/validators", validatorsHandlerFn(ctx, cdc), ).Methods("GET") + + // GET /stake/validators/{addr} + r.HandleFunc( + "/stake/validators/{addr}", + validatorHandlerFn(ctx, cdc), + ).Methods("GET") + + // GET /stake/validators/{addr}/delegators + // Don't think this is currently possible without changing keys } -// http request handler to query a delegation -func delegationHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +// already resolve the rational shares to not handle this in the client +type DelegationWithoutRat struct { + DelegatorAddr sdk.AccAddress `json:"delegator_addr"` + ValidatorAddr sdk.AccAddress `json:"validator_addr"` + Shares string `json:"shares"` + Height int64 `json:"height"` +} + +// Aggregation of all delegations, unbondings and redelegations +type DelegationSummary struct { + Delegations []DelegationWithoutRat `json:"delegations"` + UnbondingDelegations []stake.UnbondingDelegation `json:"unbonding_delegations"` + Redelegations []stake.Redelegation `json:"redelegations"` +} + +// HTTP request handler to query a delegator delegations +func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + var validatorAddr sdk.AccAddress + var delegationSummary = DelegationSummary{} + // read parameters vars := mux.Vars(r) - bech32delegator := vars["delegator"] - bech32validator := vars["validator"] + bech32delegator := vars["delegatorAddr"] delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) if err != nil { @@ -55,54 +115,219 @@ func delegationHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF return } - validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) + // Get all validators using key + kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query validators. Error: %s", err.Error()))) return } - key := stake.GetDelegationKey(delegatorAddr, validatorAddr) + // the query will return empty if there are no validators + if len(kvs) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } - res, err := ctx.QueryStore(key, storeName) + validators, err := getValidators(kvs, cdc) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) return } - // the query will return empty if there is no data for this record - if len(res) == 0 { - w.WriteHeader(http.StatusNoContent) - return + for _, validator := range validators { + validatorAddr = validator.Owner + + delegationKey := stake.GetDelegationKey(delegatorAddr, validatorAddr) + marshalledDelegation, err := ctx.QueryStore(delegationKey, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + return + } + + // the query will return empty if there is no data for this record + if len(marshalledDelegation) != 0 { + delegation, err := types.UnmarshalDelegation(cdc, delegationKey, marshalledDelegation) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't unmarshall unbonding-delegation. Error: %s", err.Error()))) + return + } + + outputDelegation := DelegationWithoutRat{ + DelegatorAddr: delegation.DelegatorAddr, + ValidatorAddr: delegation.ValidatorAddr, + Height: delegation.Height, + Shares: delegation.Shares.FloatString(), + } + + delegationSummary.Delegations = append(delegationSummary.Delegations, outputDelegation) + } + + undelegationKey := stake.GetUBDKey(delegatorAddr, validatorAddr) + marshalledUnbondingDelegation, err := ctx.QueryStore(undelegationKey, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + return + } + + // the query will return empty if there is no data for this record + if len(marshalledUnbondingDelegation) != 0 { + unbondingDelegation, err := types.UnmarshalUBD(cdc, undelegationKey, marshalledUnbondingDelegation) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't unmarshall unbonding-delegation. Error: %s", err.Error()))) + return + } + + delegationSummary.UnbondingDelegations = append(delegationSummary.UnbondingDelegations, unbondingDelegation) + } + + // only querying redelegations to a validator as this should give us already all relegations + // if we also would put in redelegations from, we would have every redelegation double + keyRedelegateTo := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) + marshalledRedelegations, err := ctx.QueryStore(keyRedelegateTo, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) + return + } + + if len(marshalledRedelegations) != 0 { + redelegations, err := types.UnmarshalRED(cdc, keyRedelegateTo, marshalledRedelegations) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't unmarshall redelegations. Error: %s", err.Error()))) + return + } + + delegationSummary.Redelegations = append(delegationSummary.Redelegations, redelegations) + } + + output, err := cdc.MarshalJSON(delegationSummary) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + // success + w.Write(output) // write } + } +} - delegation, err := types.UnmarshalDelegation(cdc, key, res) +// HTTP request handler to query all staking txs (msgs) from a delegator +func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var output []byte + var typesQuerySlice []string + vars := mux.Vars(r) + delegatorAddr := vars["delegatorAddr"] + + _, err := sdk.AccAddressFromBech32(delegatorAddr) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } - output, err := cdc.MarshalJSON(delegation) + node, err := ctx.GetNode() + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Couldn't get current Node information. Error: %s", err.Error()))) + return + } + + // Get values from query + + typesQuery := r.URL.Query().Get("type") + trimmedQuery := strings.TrimSpace(typesQuery) + if len(trimmedQuery) != 0 { + typesQuerySlice = strings.Split(trimmedQuery, " ") + } + + noQuery := len(typesQuerySlice) == 0 + isBondTx := contains(typesQuerySlice, "bond") + isUnbondTx := contains(typesQuerySlice, "unbond") + isRedTx := contains(typesQuerySlice, "redelegate") + var txs = []tx.TxInfo{} + + // TODO double check this + if noQuery || isBondTx { + foundTxs, err := queryTxs(node, cdc, string(tags.ActionDelegate), delegatorAddr) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) + } + txs = append(txs, foundTxs...) + } + if noQuery || isUnbondTx { + foundTxs, err := queryTxs(node, cdc, string(tags.ActionBeginUnbonding), delegatorAddr) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) + } + txs = append(txs, foundTxs...) + + foundTxs, err = queryTxs(node, cdc, string(tags.ActionCompleteUnbonding), delegatorAddr) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) + } + txs = append(txs, foundTxs...) + } + if noQuery || isRedTx { + foundTxs, err := queryTxs(node, cdc, string(tags.ActionBeginRedelegation), delegatorAddr) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) + } + txs = append(txs, foundTxs...) + + foundTxs, err = queryTxs(node, cdc, string(tags.ActionCompleteRedelegation), delegatorAddr) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) + } + txs = append(txs, foundTxs...) + } + + // success + output, err = cdc.MarshalJSON(txs) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } + w.Write(output) // write + } +} - w.Write(output) +func queryTxs(node rpcclient.Client, cdc *wire.Codec, tag string, delegatorAddr string) ([]tx.TxInfo, error) { + page := 0 + perPage := 100 + prove := false + query := tags.Action + "='" + tag + "' AND " + tags.Delegator + "='" + delegatorAddr + "'" + res, err := node.TxSearch(query, prove, page, perPage) + if err != nil { + return nil, err } + + return tx.FormatTxResults(cdc, res.Txs) } // http request handler to query an unbonding-delegation -func ubdHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +func unbondingDelegationsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // read parameters vars := mux.Vars(r) - bech32delegator := vars["delegator"] - bech32validator := vars["validator"] + bech32delegator := vars["delegatorAddr"] + bech32validator := vars["validatorAddr"] delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) if err != nil { @@ -111,14 +336,16 @@ func ubdHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return } - validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) + validatorAddr, err := sdk.ValAddressFromBech32(bech32validator) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } + //TODO this seems wrong. we should query with the sdk.ValAddress and not sdk.AccAddress + validatorAddrAcc := sdk.AccAddress(validatorAddr) - key := stake.GetUBDKey(delegatorAddr, validatorAddr) + key := stake.GetUBDKey(delegatorAddr, validatorAddrAcc) res, err := ctx.QueryStore(key, storeName) if err != nil { @@ -140,7 +367,10 @@ func ubdHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return } - output, err := cdc.MarshalJSON(ubd) + // unbondings will be a list in the future but is not yet, but we want to keep the API consistent + ubdArray := []stake.UnbondingDelegation{ubd} + + output, err := cdc.MarshalJSON(ubdArray) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) @@ -151,15 +381,14 @@ func ubdHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { } } -// http request handler to query an redelegation -func redHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +// HTTP request handler to query a bonded validator +func delegationHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // read parameters vars := mux.Vars(r) - bech32delegator := vars["delegator"] - bech32validatorSrc := vars["validator_src"] - bech32validatorDst := vars["validator_dst"] + bech32delegator := vars["delegatorAddr"] + bech32validator := vars["validatorAddr"] delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) if err != nil { @@ -168,26 +397,21 @@ func redHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return } - validatorSrcAddr, err := sdk.AccAddressFromBech32(bech32validatorSrc) + validatorAddr, err := sdk.ValAddressFromBech32(bech32validator) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } + //TODO this seems wrong. we should query with the sdk.ValAddress and not sdk.AccAddress + validatorAddrAcc := sdk.AccAddress(validatorAddr) - validatorDstAddr, err := sdk.AccAddressFromBech32(bech32validatorDst) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - key := stake.GetREDKey(delegatorAddr, validatorSrcAddr, validatorDstAddr) + key := stake.GetDelegationKey(delegatorAddr, validatorAddrAcc) res, err := ctx.QueryStore(key, storeName) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) return } @@ -197,14 +421,21 @@ func redHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return } - red, err := types.UnmarshalRED(cdc, key, res) + delegation, err := types.UnmarshalDelegation(cdc, key, res) if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) return } - output, err := cdc.MarshalJSON(red) + outputDelegation := DelegationWithoutRat{ + DelegatorAddr: delegation.DelegatorAddr, + ValidatorAddr: delegation.ValidatorAddr, + Height: delegation.Height, + Shares: delegation.Shares.FloatString(), + } + + output, err := cdc.MarshalJSON(outputDelegation) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) @@ -216,7 +447,7 @@ func redHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { } // TODO bech32 -// http request handler to query list of validators +// HTTP request handler to query list of validators func validatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) @@ -232,25 +463,11 @@ func validatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF return } - // parse out the validators - validators := make([]types.BechValidator, len(kvs)) - for i, kv := range kvs { - - addr := kv.Key[1:] - validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return - } - - bech32Validator, err := validator.Bech32Validator() - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - validators[i] = bech32Validator + validators, err := getValidators(kvs, cdc) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return } output, err := cdc.MarshalJSON(validators) @@ -263,3 +480,47 @@ func validatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF w.Write(output) } } + +// HTTP request handler to query the validator information from a given validator address +func validatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var output []byte + // read parameters + vars := mux.Vars(r) + bech32validatorAddr := vars["addr"] + valAddress, err := sdk.ValAddressFromBech32(bech32validatorAddr) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return + } + + kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return + } + + validator, err := getValidator(valAddress, kvs, cdc) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query validator. Error: %s", err.Error()))) + return + } + + output, err = cdc.MarshalJSON(validator) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return + } + + if output == nil { + w.WriteHeader(http.StatusNoContent) + return + } + w.Write(output) + } +} diff --git a/x/stake/client/rest/test_helpers.go b/x/stake/client/rest/test_helpers.go new file mode 100644 index 000000000000..a02ad0d91ac8 --- /dev/null +++ b/x/stake/client/rest/test_helpers.go @@ -0,0 +1,287 @@ +package rest + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "net" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" + keys "github.com/cosmos/cosmos-sdk/client/keys" + gapp "github.com/cosmos/cosmos-sdk/cmd/gaia/app" + crkeys "github.com/cosmos/cosmos-sdk/crypto/keys" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/tests" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/gorilla/mux" + + "github.com/spf13/viper" + "github.com/stretchr/testify/require" + + abci "github.com/tendermint/tendermint/abci/types" + tmcfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/crypto/ed25519" + "github.com/tendermint/tendermint/libs/cli" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" + nm "github.com/tendermint/tendermint/node" + pvm "github.com/tendermint/tendermint/privval" + "github.com/tendermint/tendermint/proxy" + tmrpc "github.com/tendermint/tendermint/rpc/lib/server" + tmtypes "github.com/tendermint/tendermint/types" +) + +func createHandler(cdc *wire.Codec) http.Handler { + r := mux.NewRouter() + + kb, err := keys.GetKeyBase() //XXX + if err != nil { + panic(err) + } + + ctx := context.NewCoreContextFromViper() + RegisterRoutes(ctx, r, cdc, kb) + + return r +} + +// makePathname creates a unique pathname for each test. It will panic if it +// cannot get the current working directory. +func makePathname() string { + p, err := os.Getwd() + if err != nil { + panic(err) + } + + sep := string(filepath.Separator) + return strings.Replace(p, sep, "_", -1) +} + +// GetConfig returns a Tendermint config for the test cases. +func GetConfig() *tmcfg.Config { + pathname := makePathname() + config := tmcfg.ResetTestRoot(pathname) + + tmAddr, _, err := server.FreeTCPAddr() + if err != nil { + panic(err) + } + + rcpAddr, _, err := server.FreeTCPAddr() + if err != nil { + panic(err) + } + + grpcAddr, _, err := server.FreeTCPAddr() + if err != nil { + panic(err) + } + + config.P2P.ListenAddress = tmAddr + config.RPC.ListenAddress = rcpAddr + config.RPC.GRPCListenAddress = grpcAddr + + return config +} + +// GetKeyBase returns the LCD test keybase. It also requires that a directory +// could be made and a keybase could be fetched. +// +// NOTE: memDB cannot be used because the request is expecting to interact with +// the default location. +func GetKeyBase(t *testing.T) crkeys.Keybase { + dir, err := ioutil.TempDir("", "lcd_test") + require.NoError(t, err) + + viper.Set(cli.HomeFlag, dir) + + keybase, err := keys.GetKeyBase() + require.NoError(t, err) + + return keybase +} + +// CreateAddr adds an address to the key store and returns an address and seed. +// It also requires that the key could be created. +func CreateAddr(t *testing.T, name, password string, kb crkeys.Keybase) (sdk.AccAddress, string) { + var ( + err error + info crkeys.Info + seed string + ) + + info, seed, err = kb.CreateMnemonic(name, crkeys.English, password, crkeys.Secp256k1) + require.NoError(t, err) + + return sdk.AccAddress(info.GetPubKey().Address()), seed +} + +// InitializeTestLCD starts Tendermint and the LCD in process, listening on +// their respective sockets where nValidators is the total number of validators +// and initAddrs are the accounts to initialize with some steak tokens. It +// returns a cleanup function, a set of validator public keys, and a port. +func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress) (func(), []crypto.PubKey, string) { + config := GetConfig() + config.Consensus.TimeoutCommit = 100 + config.Consensus.SkipTimeoutCommit = false + config.TxIndex.IndexAllTags = true + + logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + logger = log.NewFilter(logger, log.AllowNone()) + + privValidatorFile := config.PrivValidatorFile() + privVal := pvm.LoadOrGenFilePV(privValidatorFile) + privVal.Reset() + + db := dbm.NewMemDB() + app := gapp.NewGaiaApp(logger, db, nil) + cdc := gapp.MakeCodec() + + genesisFile := config.GenesisFile() + genDoc, err := tmtypes.GenesisDocFromFile(genesisFile) + require.NoError(t, err) + + if nValidators < 1 { + panic("InitializeTestLCD must use at least one validator") + } + + for i := 1; i < nValidators; i++ { + genDoc.Validators = append(genDoc.Validators, + tmtypes.GenesisValidator{ + PubKey: ed25519.GenPrivKey().PubKey(), + Power: 1, + Name: "val", + }, + ) + } + + var validatorsPKs []crypto.PubKey + + // NOTE: It's bad practice to reuse public key address for the owner + // address but doing in the test for simplicity. + var appGenTxs []json.RawMessage + for _, gdValidator := range genDoc.Validators { + pk := gdValidator.PubKey + validatorsPKs = append(validatorsPKs, pk) + + appGenTx, _, _, err := gapp.GaiaAppGenTxNF(cdc, pk, sdk.AccAddress(pk.Address()), "test_val1") + require.NoError(t, err) + + appGenTxs = append(appGenTxs, appGenTx) + } + + genesisState, err := gapp.GaiaAppGenState(cdc, appGenTxs[:]) + require.NoError(t, err) + + // add some tokens to init accounts + for _, addr := range initAddrs { + accAuth := auth.NewBaseAccountWithAddress(addr) + accAuth.Coins = sdk.Coins{sdk.NewCoin("steak", 100)} + acc := gapp.NewGenesisAccount(&accAuth) + genesisState.Accounts = append(genesisState.Accounts, acc) + genesisState.StakeData.Pool.LooseTokens = genesisState.StakeData.Pool.LooseTokens.Add(sdk.NewRat(100)) + } + + appState, err := wire.MarshalJSONIndent(cdc, genesisState) + require.NoError(t, err) + genDoc.AppState = appState + + listenAddr, port, err := server.FreeTCPAddr() + require.NoError(t, err) + + // XXX: Need to set this so LCD knows the tendermint node address! + viper.Set(client.FlagNode, config.RPC.ListenAddress) + viper.Set(client.FlagChainID, genDoc.ChainID) + + node, err := startTM(config, logger, genDoc, privVal, app) + require.NoError(t, err) + + lcd, err := startLCD(logger, listenAddr, cdc) + require.NoError(t, err) + + tests.WaitForLCDStart(port) + tests.WaitForHeight(1, port) + + cleanup := func() { + logger.Debug("cleaning up LCD initialization") + node.Stop() + node.Wait() + lcd.Close() + } + + return cleanup, validatorsPKs, port +} + +// startTM creates and starts an in-process Tendermint node with memDB and +// in-process ABCI application. It returns the new node or any error that +// occurred. +// +// TODO: Clean up the WAL dir or enable it to be not persistent! +func startTM( + tmcfg *tmcfg.Config, logger log.Logger, genDoc *tmtypes.GenesisDoc, + privVal tmtypes.PrivValidator, app abci.Application, +) (*nm.Node, error) { + genDocProvider := func() (*tmtypes.GenesisDoc, error) { return genDoc, nil } + dbProvider := func(*nm.DBContext) (dbm.DB, error) { return dbm.NewMemDB(), nil } + node, err := nm.NewNode( + tmcfg, + privVal, + proxy.NewLocalClientCreator(app), + genDocProvider, + dbProvider, + nm.DefaultMetricsProvider, + logger.With("module", "node"), + ) + if err != nil { + return nil, err + } + + err = node.Start() + if err != nil { + return nil, err + } + + tests.WaitForRPC(tmcfg.RPC.ListenAddress) + logger.Info("Tendermint running!") + + return node, err +} + +// startLCD starts the LCD. +// +// NOTE: This causes the thread to block. +func startLCD(logger log.Logger, listenAddr string, cdc *wire.Codec) (net.Listener, error) { + return tmrpc.StartHTTPServer(listenAddr, createHandler(cdc), logger, tmrpc.Config{}) +} + +// Request makes a test LCD test request. It returns a response object and a +// stringified response body. +func Request(t *testing.T, port, method, path string, payload []byte) (*http.Response, string) { + var ( + err error + res *http.Response + ) + url := fmt.Sprintf("http://localhost:%v%v", port, path) + + req, err := http.NewRequest(method, url, bytes.NewBuffer(payload)) + require.Nil(t, err) + + res, err = http.DefaultClient.Do(req) + require.Nil(t, err) + + output, err := ioutil.ReadAll(res.Body) + res.Body.Close() + require.Nil(t, err) + + return res, string(output) +} diff --git a/x/stake/client/rest/tx.go b/x/stake/client/rest/tx.go index a0f0416549d3..d5719bc24b81 100644 --- a/x/stake/client/rest/tx.go +++ b/x/stake/client/rest/tx.go @@ -19,7 +19,7 @@ import ( func registerTxRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { r.HandleFunc( - "/stake/delegations", + "/stake/delegators/{delegatorAddr}/delegations", editDelegationsRequestHandlerFn(cdc, kb, ctx), ).Methods("POST") } @@ -67,6 +67,7 @@ type EditDelegationsBody struct { // nolint: gocyclo // TODO: Split this up into several smaller functions, and remove the above nolint +// TODO: use sdk.ValAddress instead of sdk.AccAddress for validators in messages func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var m EditDelegationsBody @@ -105,7 +106,8 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) return } - validatorAddr, err := sdk.AccAddressFromBech32(msg.ValidatorAddr) + validatorAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) + validatorAddrAcc := sdk.AccAddress(validatorAddr) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) @@ -118,7 +120,7 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte } messages[i] = stake.MsgDelegate{ DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, + ValidatorAddr: validatorAddrAcc, Delegation: msg.Delegation, } i++ @@ -136,13 +138,15 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte w.Write([]byte("Must use own delegator address")) return } - validatorSrcAddr, err := sdk.AccAddressFromBech32(msg.ValidatorSrcAddr) + validatorSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) + validatorSrcAddrAcc := sdk.AccAddress(validatorSrcAddr) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } - validatorDstAddr, err := sdk.AccAddressFromBech32(msg.ValidatorDstAddr) + ValidatorDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) + ValidatorDstAddrAcc := sdk.AccAddress(ValidatorDstAddr) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) @@ -156,8 +160,8 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte } messages[i] = stake.MsgBeginRedelegate{ DelegatorAddr: delegatorAddr, - ValidatorSrcAddr: validatorSrcAddr, - ValidatorDstAddr: validatorDstAddr, + ValidatorSrcAddr: validatorSrcAddrAcc, + ValidatorDstAddr: ValidatorDstAddrAcc, SharesAmount: shares, } i++ @@ -170,13 +174,15 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) return } - validatorSrcAddr, err := sdk.AccAddressFromBech32(msg.ValidatorSrcAddr) + validatorSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) + validatorSrcAddrAcc := sdk.AccAddress(validatorSrcAddr) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } - validatorDstAddr, err := sdk.AccAddressFromBech32(msg.ValidatorDstAddr) + ValidatorDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) + ValidatorDstAddrAcc := sdk.AccAddress(ValidatorDstAddr) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) @@ -189,8 +195,8 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte } messages[i] = stake.MsgCompleteRedelegate{ DelegatorAddr: delegatorAddr, - ValidatorSrcAddr: validatorSrcAddr, - ValidatorDstAddr: validatorDstAddr, + ValidatorSrcAddr: validatorSrcAddrAcc, + ValidatorDstAddr: ValidatorDstAddrAcc, } i++ } @@ -207,7 +213,8 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte w.Write([]byte("Must use own delegator address")) return } - validatorAddr, err := sdk.AccAddressFromBech32(msg.ValidatorAddr) + validatorAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) + validatorAddrAcc := sdk.AccAddress(validatorAddr) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) @@ -221,7 +228,7 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte } messages[i] = stake.MsgBeginUnbonding{ DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, + ValidatorAddr: validatorAddrAcc, SharesAmount: shares, } i++ diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go new file mode 100644 index 000000000000..c89c042a73b1 --- /dev/null +++ b/x/stake/client/rest/utils.go @@ -0,0 +1,65 @@ +package rest + +import ( + "reflect" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/pkg/errors" +) + +// Contains checks if the a given query contains one of the tx types +func contains(stringSlice []string, txType string) bool { + for _, word := range stringSlice { + if word == txType { + return true + } + } + return false +} + +// get all Validators +func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechValidator, error) { + // parse out the validators + validators := make([]types.BechValidator, len(validatorKVs)) + for i, kv := range validatorKVs { + + addr := kv.Key[1:] + validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) + if err != nil { + return nil, err + } + + bech32Validator, err := validator.Bech32Validator() + if err != nil { + return nil, err + } + validators[i] = bech32Validator + } + return validators, nil +} + +// get Validator given an Account Address +func getValidator(address sdk.ValAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (stake.BechValidator, error) { + // parse out the validators + for _, kv := range validatorKVs { + addr := kv.Key[1:] + validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) + if err != nil { + return stake.BechValidator{}, err + } + + ownerAddress := validator.PubKey.Address() + if reflect.DeepEqual(ownerAddress.Bytes(), address.Bytes()) { + bech32Validator, err := validator.Bech32Validator() + if err != nil { + return stake.BechValidator{}, err + } + + return bech32Validator, nil + } + } + return stake.BechValidator{}, errors.Errorf("Couldn't find validator") // validator Not Found +} diff --git a/x/stake/keeper/key.go b/x/stake/keeper/key.go index e373ede18a45..b6330b29eb25 100644 --- a/x/stake/keeper/key.go +++ b/x/stake/keeper/key.go @@ -230,3 +230,11 @@ func GetREDsByDelToValDstIndexKey(delegatorAddr, validatorDstAddr sdk.AccAddress GetREDsToValDstIndexKey(validatorDstAddr), delegatorAddr.Bytes()...) } + +// get the prefix keyspace for all redelegations redelegating from a source validator +// from a particular delegator +func GetREDsByDelFromValSrcIndexKey(delegatorAddr, validatorSrcAddr sdk.AccAddress) []byte { + return append( + GetREDsFromValSrcIndexKey(validatorSrcAddr), + delegatorAddr.Bytes()...) +} From d7297b59a3716002ebbf805c8b10d8475a3f94a3 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 31 Jul 2018 19:27:48 +0200 Subject: [PATCH 21/46] updated endpoints API docs --- docs/clients/lcd-rest-api.yaml | 330 +++++++++++++++++++-------------- 1 file changed, 190 insertions(+), 140 deletions(-) diff --git a/docs/clients/lcd-rest-api.yaml b/docs/clients/lcd-rest-api.yaml index a39b7bf08973..f52d7cfcce8e 100644 --- a/docs/clients/lcd-rest-api.yaml +++ b/docs/clients/lcd-rest-api.yaml @@ -1,8 +1,26 @@ swagger: '2.0' info: version: '1.1.0' - title: Light client daemon to interface with Cosmos baseserver via REST - description: Specification for the LCD provided by `gaiacli advanced rest-server` + title: Gaia-Lite (former LCD) to interface with Cosmos BaseServer via REST + description: Specification for Gaia-lite provided by `gaiacli advanced rest-server` + +tags: +- name: keys + description: Key management to add or view local private keys +- name: send + description: Create and sign a send tx +- name: stake + description: Stake module API for staking and validation +- name: account + description: Query account balance +- name: query + description: Information about blocks and txs +- name: validator set + description: Check the state of the validator set +- name: node + description: Information of the connected node +- name: version + description: Information about the app version securityDefinitions: @@ -12,22 +30,28 @@ securityDefinitions: paths: /version: get: - summary: Version of the light client daemon - description: Get the version of the LCD running locally to compare against expected + summary: Version of Gaia-lite + tags: + - version + description: Get the version of gaia-lite running locally to compare against expected responses: 200: description: Plaintext version i.e. "v0.5.0" /node_version: get: summary: Version of the connected node + tags: + - node description: Get the version of the SDK running on the connected node to compare against expected responses: 200: description: Plaintext version i.e. "v0.5.0" /node_info: get: - description: Only the node info. Block information can be queried via /block/latest - summary: The propertied of the connected node + description: Information about the connected node + summary: The properties of the connected node + tags: + - node produces: - application/json responses: @@ -61,6 +85,8 @@ paths: /syncing: get: summary: Syncing state of node + tags: + - node description: Get if the node is currently syning with other nodes responses: 200: @@ -69,6 +95,8 @@ paths: /keys: get: summary: List of accounts stored locally + tags: + - keys produces: - application/json responses: @@ -80,6 +108,8 @@ paths: $ref: '#/definitions/Account' post: summary: Create a new account locally + tags: + - keys consumes: - application/json parameters: @@ -105,6 +135,8 @@ paths: /keys/seed: get: summary: Create a new seed to create a new account with + tags: + - keys produces: - application/json responses: @@ -121,6 +153,8 @@ paths: type: string get: summary: Get a certain locally stored account + tags: + - keys produces: - application/json responses: @@ -132,6 +166,8 @@ paths: description: Account is not available put: summary: Update the password for this account in the KMS + tags: + - keys consumes: - application/json parameters: @@ -157,6 +193,8 @@ paths: description: Account is not available delete: summary: Remove an account + tags: + - keys consumes: - application/json parameters: @@ -216,6 +254,8 @@ paths: type: string get: summary: Get the account balances + tags: + - account produces: - application/json responses: @@ -234,6 +274,8 @@ paths: type: string post: summary: Send coins (build -> sign -> send) + tags: + - send security: - kms: [] consumes: @@ -265,6 +307,8 @@ paths: /blocks/latest: get: summary: Get the latest block + tags: + - query produces: - application/json responses: @@ -281,6 +325,8 @@ paths: type: number get: summary: Get a block at a certain height + tags: + - query produces: - application/json responses: @@ -293,6 +339,8 @@ paths: /validatorsets/latest: get: summary: Get the latest validator set + tags: + - validator set produces: - application/json responses: @@ -316,6 +364,8 @@ paths: type: number get: summary: Get a validator set a certain height + tags: + - validator set produces: - application/json responses: @@ -407,6 +457,8 @@ paths: type: string get: summary: Get a Tx by hash + tags: + - query produces: - application/json responses: @@ -416,140 +468,138 @@ paths: $ref: "#/definitions/Tx" 404: description: Tx not available for provided hash - # /delegates: - # parameters: - # - in: query - # name: delegator - # description: Query for all delegates a delegator has stake with - # schema: - # $ref: "#/definitions/Address" - # get: - # summary: Get a list of canidates/delegates/validators (optionally filtered by delegator) - # responses: - # 200: - # description: List of delegates, filtered by provided delegator address - # content: - # application/json: - # schema: - # type: array - # items: - # $ref: "#/definitions/Delegate" - # /delegates/bond: - # post: - # summary: Bond atoms (build -> sign -> send) - # security: - # - sign: [] - # requestBody: - # content: - # application/json: - # schema: - # type: array - # items: - # type: object - # properties: - # amount: - # $ref: "#/definitions/Coins" - # pub_key: - # $ref: "#/definitions/PubKey" - # responses: - # 202: - # description: Tx was send and will probably be added to the next block - # 400: - # description: The Tx was malformated - # /delegates/unbond: - # post: - # summary: Unbond atoms (build -> sign -> send) - # security: - # - sign: [] - # requestBody: - # content: - # application/json: - # schema: - # type: array - # items: - # type: object - # properties: - # amount: - # $ref: "#/definitions/Coins" - # pub_key: - # $ref: "#/definitions/PubKey" - # responses: - # 202: - # description: Tx was send and will probably be added to the next block - # 400: - # description: The Tx was malformated - # /delegates/{pubkey}: - # parameters: - # - in: path - # name: pubkey - # description: Pubkey of a delegate - # required: true - # schema: - # type: string - # example: 81B11E717789600CC192B26F452A983DF13B985EE75ABD9DD9E68D7BA007A958 - # get: - # summary: Get a certain canidate/delegate/validator - # responses: - # 200: - # description: Delegate for specified pub_key - # content: - # application/json: - # schema: - # $ref: "#/definitions/Delegate" - # 404: - # description: No delegate found for provided pub_key - # /delegates/{pubkey}/bond: - # parameters: - # - in: path - # name: pubkey - # description: Pubkey of a delegate - # required: true - # schema: - # type: string - # example: 81B11E717789600CC192B26F452A983DF13B985EE75ABD9DD9E68D7BA007A958 - # post: - # summary: Bond atoms (build -> sign -> send) - # security: - # - sign: [] - # requestBody: - # content: - # application/json: - # schema: - # type: object - # properties: - # amount: - # $ref: "#/definitions/Coins" - # responses: - # 202: - # description: Tx was send and will probably be added to the next block - # 400: - # description: The Tx was malformated - # /delegates/{pubkey}/unbond: - # parameters: - # - in: path - # name: pubkey - # description: Pubkey of a delegate - # required: true - # schema: - # type: string - # example: 81B11E717789600CC192B26F452A983DF13B985EE75ABD9DD9E68D7BA007A958 - # post: - # summary: Unbond atoms (build -> sign -> send) - # security: - # - sign: [] - # requestBody: - # content: - # application/json: - # schema: - # type: object - # properties: - # amount: - # $ref: "#/definitions/Coins" - # responses: - # 202: - # description: Tx was send and will probably be added to the next block - # 400: - # description: The Tx was malformated + +# ================== Staking Module # ================== + /stake/delegators/{delegatorAddr}: + parameters: + - in: path + name: delegatorAddr + description: AccAddress of Delegator + required: true + type: string + get: + summary: Get all delegations (delegation, undelegation) from a delegator + tags: + - stake + produces: + - application/json + responses: + 200: + description: Delegations + schema: + $ref: "#/definitions/Tx" + 404: + description: Tx not available for provided hash + + /stake/delegators/{delegatorAddr}/txs: + parameters: + - in: path + name: delegatorAddr + description: AccAddress of Delegator + required: true + type: string + get: + summary: Get all staking txs (i.e msgs) from a delegator + tags: + - stake + produces: + - application/json + responses: + 200: + description: Tx with the provided hash + schema: + $ref: "#/definitions/Tx" + 404: + description: Tx not available for provided hash + + /stake/delegators/{delegatorAddr}/delegations/{validatorAddr}: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + - in: path + name: validatorAddr + description: Bech32 ValAddress of Delegator + required: true + type: string + get: + summary: Query the current delegation status between a delegator and a validator + tags: + - stake + produces: + - application/json + responses: + 200: + description: Delegations + schema: + $ref: "#/definitions/Tx" + 404: + description: Tx not available for provided hash + + /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + - in: path + name: validatorAddr + description: Bech32 ValAddress of Delegator + required: true + type: string + get: + summary: Query all unbonding delegations between a delegator and a validator + tags: + - stake + produces: + - application/json + responses: + 200: + description: Delegations + schema: + $ref: "#/definitions/Tx" + 404: + description: Tx not available for provided hash + + /stake/validators: + get: + summary: Get all validator candidates + tags: + - stake + produces: + - application/json + responses: + 200: + description: Delegations + schema: + $ref: "#/definitions/Tx" + 404: + description: Tx not available for provided hash + + /stake/validators/{validatorAddr}: + parameters: + - in: path + name: validatorAddr + description: Bech32 ValAddress of Delegator + required: true + type: string + get: + summary: Query the information from a single validator + tags: + - stake + produces: + - application/json + responses: + 200: + description: Delegations + schema: + $ref: "#/definitions/Tx" + 404: + description: Tx not available for provided hash + definitions: Address: From 00baf3f8632ed94f3423792961590b0e92f071d5 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 1 Aug 2018 10:25:43 +0200 Subject: [PATCH 22/46] Updated docs with staking Gaia Lite routes --- docs/clients/lcd-rest-api.yaml | 110 +++++++++++++---- docs/light/api.md | 216 +++++++++++++++++++++++++++++++++ docs/light/readme.md | 4 +- docs/light/specification.md | 40 +++++- 4 files changed, 339 insertions(+), 31 deletions(-) diff --git a/docs/clients/lcd-rest-api.yaml b/docs/clients/lcd-rest-api.yaml index f52d7cfcce8e..780666947f42 100644 --- a/docs/clients/lcd-rest-api.yaml +++ b/docs/clients/lcd-rest-api.yaml @@ -470,6 +470,8 @@ paths: description: Tx not available for provided hash # ================== Staking Module # ================== + +# TODO create D /stake/delegators/{delegatorAddr}: parameters: - in: path @@ -485,11 +487,11 @@ paths: - application/json responses: 200: - description: Delegations - schema: - $ref: "#/definitions/Tx" + description: OK 404: - description: Tx not available for provided hash + description: Not Found + 500: + description: Internal Server Error /stake/delegators/{delegatorAddr}/txs: parameters: @@ -506,11 +508,75 @@ paths: - application/json responses: 200: - description: Tx with the provided hash + description: OK schema: $ref: "#/definitions/Tx" 404: - description: Tx not available for provided hash + description: Not Found + 500: + description: Internal Server Error + + /stake/delegators/{delegatorAddr}/delegations: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + post: + summary: Edit a delegation + parameters: + - in: body + name: delegation + description: The password of the account to remove from the KMS + schema: + type: object + properties: + name: + type: string + password: + type: string + account_number: + type: number + delegations: + type: array + items: + type: string + begin_unbondings: + type: array + items: + type: string + complete_unbondings: + type: array + items: + type: string + begin_redelegates: + type: array + items: + type: string + complete_redelegates: + type: array + items: + type: string + chain_id: + type: string + gas: + type: number + sequence: + type: number + tags: + - stake + produces: + - application/json + responses: + 200: + description: OK + schema: + $ref: "#/definitions/Tx" + 404: + description: Not Found + 500: + description: Internal Server Error /stake/delegators/{delegatorAddr}/delegations/{validatorAddr}: parameters: @@ -532,11 +598,9 @@ paths: - application/json responses: 200: - description: Delegations - schema: - $ref: "#/definitions/Tx" + description: OK 404: - description: Tx not available for provided hash + description: Not Found /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}: parameters: @@ -558,11 +622,11 @@ paths: - application/json responses: 200: - description: Delegations - schema: - $ref: "#/definitions/Tx" + description: OK 404: - description: Tx not available for provided hash + description: Not Found + 500: + description: Internal Server Error /stake/validators: get: @@ -573,11 +637,9 @@ paths: - application/json responses: 200: - description: Delegations - schema: - $ref: "#/definitions/Tx" - 404: - description: Tx not available for provided hash + description: OK + 500: + description: Internal Server Error /stake/validators/{validatorAddr}: parameters: @@ -594,13 +656,13 @@ paths: - application/json responses: 200: - description: Delegations - schema: - $ref: "#/definitions/Tx" + description: OK 404: - description: Tx not available for provided hash - + description: Not Found + 500: + description: Internal Server Error +# TODO Add staking definitions definitions: Address: type: string diff --git a/docs/light/api.md b/docs/light/api.md index 26fbe77c2ff7..c6b34d68c8a8 100644 --- a/docs/light/api.md +++ b/docs/light/api.md @@ -442,3 +442,219 @@ Returns on failure: "result":{} } ``` + +## ICS21 - StakingAPI + +The StakingAPI exposes all functionality needed for validation and delegation in Proof-of-Stake. + +### /stake/delegators/{delegatorAddr} - GET + +url: /stake/delegators/{delegatorAddr} + +Functionality: Get all delegations (delegation, undelegation) from a delegator. + +Returns on success: + +```json +{ + "rest api":"2.0", + "code":200, + "error":"", + "result": { + "atom":1000, + "photon":500, + "ether":20 + } +} +``` + +Returns on error: + +```json +{ + "rest api":"2.0", + "code":500, + "error":"Could not find any balance for the specified account.", + "result":{} +} +``` + +### /stake/delegators/{delegatorAddr}/txs - GET + +url: /stake/delegators/{delegatorAddr}/txs + +Functionality: Get all staking txs (i.e msgs) from a delegator. + +Returns on success: + +```json +{ + "rest api":"2.0", + "code":200, + "error":"", + "result":{ + "transaction":"TODO" + } +} +``` + +Returns on failure: + +```json +{ + "rest api":"2.0", + "code":500, + "error":"Could not create the transaction.", + "result":{} +} +``` + +### /stake/delegators/{delegatorAddr}/delegations - POST + +url: /stake/delegators/{delegatorAddr}/delegations + +Functionality: Edit a delegation. + +Returns on success: + +```json +{ + "rest api":"2.0", + "code":200, + "error":"", + "result":{ + "transaction":"TODO" + } +} +``` + +Returns on failure: + +```json +{ + "rest api":"2.0", + "code":500, + "error":"Could not create the transaction.", + "result":{} +} +``` + +### /stake/delegators/{delegatorAddr}/delegations/{validatorAddr} - GET + +url: /stake/delegators/{delegatorAddr}/delegations/{validatorAddr} + +Functionality: Query the current delegation status between a delegator and a validator. + +Returns on success: + +```json +{ + "rest api":"2.0", + "code":200, + "error":"", + "result":{ + "transaction":"TODO" + } +} +``` + +Returns on failure: + +```json +{ + "rest api":"2.0", + "code":500, + "error":"Could not create the transaction.", + "result":{} +} +``` + +### /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr} - GET + +url: /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr} + +Functionality: Query all unbonding delegations between a delegator and a validator. + +Returns on success: + +```json +{ + "rest api":"2.0", + "code":200, + "error":"", + "result":{ + "transaction":"TODO" + } +} +``` + +Returns on failure: + +```json +{ + "rest api":"2.0", + "code":500, + "error":"Could not create the transaction.", + "result":{} +} +``` + +### /stake/validators - GET + +url: /stake/validators + +Functionality: Get all validator candidates. + +Returns on success: + +```json +{ + "rest api":"2.0", + "code":200, + "error":"", + "result":{ + "transaction":"TODO" + } +} +``` + +Returns on failure: + +```json +{ + "rest api":"2.0", + "code":500, + "error":"Could not create the transaction.", + "result":{} +} +``` + +### /stake/validators/{validatorAddr} - GET + +url: /stake/validators/{validatorAddr} + +Functionality: Query the information from a single validator. + +Returns on success: + +```json +{ + "rest api":"2.0", + "code":200, + "error":"", + "result":{ + "transaction":"TODO" + } +} +``` + +Returns on failure: + +```json +{ + "rest api":"2.0", + "code":500, + "error":"Could not create the transaction.", + "result":{} +} +``` diff --git a/docs/light/readme.md b/docs/light/readme.md index 53e3b59bd452..a9cdb2fff457 100644 --- a/docs/light/readme.md +++ b/docs/light/readme.md @@ -19,7 +19,7 @@ LCD will be used in the Cosmos Hub, the first Hub in the Cosmos network. 1. [**Overview**](##Overview) 2. [**Get Started**](getting_started.md) 3. [**API**](api.md) -4. [**Specifications**](hspecification.md) +4. [**Specifications**](specification.md) ## Overview @@ -67,7 +67,7 @@ A full node of ABCI is different from its light client in the following ways: | Provide APIs|All cosmos APIs|Modular APIs|Full node supports all cosmos APIs. LCD provides modular APIs according to users' configuration| | Secuity level| High|High|Full node will verify all transactions and blocks by itself. LCD can't do this, but it can query any data from other full nodes and verify the data independently. So both full node and LCD don't need to trust any third nodes, they all can achieve high security| -According to the above table, LCD can meet all users' functionality and security requirements, but +According to the above table, LCD can meet all users' functionality and security requirements, but only requires little resource on bandwidth, computing, storage and power. ## How does LCD achieve high security? diff --git a/docs/light/specification.md b/docs/light/specification.md index 48c87d047573..d8897b2444a0 100644 --- a/docs/light/specification.md +++ b/docs/light/specification.md @@ -14,7 +14,7 @@ tree is the AppHash which will be included in block header. ![Simple Merkle Tree](pics/simpleMerkleTree.png) -As we have discussed in [LCD trust-propagation](https://github.com/irisnet/cosmos-sdk/tree/bianjie/lcd_spec/docs/spec/lcd#trust-propagation), +As we have discussed in [LCD trust-propagation](https://github.com/irisnet/cosmos-sdk/tree/bianjie/lcd_spec/docs/spec/lcd#trust-propagation), the AppHash can be verified by checking voting power against a trusted validator set. Here we just need to build proof from ABCI state to AppHash. The proof contains two parts: @@ -212,7 +212,7 @@ For instance: To improve LCD reliability and TPS, we recommend to connect LCD to more than one fullnode. But the complexity will increase a lot. So load balancing module will be imported as the adapter. Please -refer to this link for detailed description: [load balancing](https://github.com/irisnet/cosmos-sdk/blob/bianjie/lcd_spec/docs/spec/lcd/loadbalance.md) +refer to this link for detailed description: [load balancer](load_balancer.md) ## ICS1 (KeyAPI) @@ -305,14 +305,44 @@ return KeyOutput{ ## ICS20 (TokenAPI) -### [/bank/balance/{account}](api.md#balanceaccount---get) +### [/bank/balance/{account}](api.md#bankbalanceaccount---get) 1. Decode the address from bech32 to hex. 2. Send a query request to a full node. Ask for proof if required by Gaia Light. 3. Verify the proof against the root of trust. -### [/bank/create_transfer](api.md#create_transfer---post) - +### [/bank/create_transfer](api.md#bankcreate_transfer---post) + 1. Check the parameters. 2. Build the transaction with the specified parameters. 3. Serialise the transaction and return the JSON encoded sign bytes. + +## ICS21 (StakingAPI) + +### [/stake/delegators/{delegatorAddr}](api.md#stakedelegatorsdelegatorAddr---get) + +TODO + +### [/stake/delegators/{delegatorAddr}/txs](api.md#stakedelegatorsdelegatorAddrtxs---get) + +TODO + +### [/stake/delegators/{delegatorAddr}/delegations](api.md#stakedelegatorsdelegatorAddrdelegations---post) + +TODO + +### [/stake/delegators/{delegatorAddr}/delegations/{validatorAddr}](api.md#stakedelegatorsdelegatorAddrdelegationsvalidatorAddr---get) + +TODO + +### [/stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}](api.md#stakedelegatorsdelegatorAddrunbonding_delegationsvalidatorAddr---get) + +TODO + +### [/stake/validators](api.md#stakevalidators---get) + +TODO + +### [/stake/validators/{validatorAddr}](api.md#stakevalidatorsvalidatorAddr---get) + +TODO From 0f4040c53a80fda102935b9a3627f7bd18b05a13 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 1 Aug 2018 10:40:13 +0200 Subject: [PATCH 23/46] deleted unused helpers file --- x/stake/client/rest/test_helpers.go | 287 ---------------------------- 1 file changed, 287 deletions(-) delete mode 100644 x/stake/client/rest/test_helpers.go diff --git a/x/stake/client/rest/test_helpers.go b/x/stake/client/rest/test_helpers.go deleted file mode 100644 index a02ad0d91ac8..000000000000 --- a/x/stake/client/rest/test_helpers.go +++ /dev/null @@ -1,287 +0,0 @@ -package rest - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net" - "net/http" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - keys "github.com/cosmos/cosmos-sdk/client/keys" - gapp "github.com/cosmos/cosmos-sdk/cmd/gaia/app" - crkeys "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/tests" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/gorilla/mux" - - "github.com/spf13/viper" - "github.com/stretchr/testify/require" - - abci "github.com/tendermint/tendermint/abci/types" - tmcfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/libs/cli" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - nm "github.com/tendermint/tendermint/node" - pvm "github.com/tendermint/tendermint/privval" - "github.com/tendermint/tendermint/proxy" - tmrpc "github.com/tendermint/tendermint/rpc/lib/server" - tmtypes "github.com/tendermint/tendermint/types" -) - -func createHandler(cdc *wire.Codec) http.Handler { - r := mux.NewRouter() - - kb, err := keys.GetKeyBase() //XXX - if err != nil { - panic(err) - } - - ctx := context.NewCoreContextFromViper() - RegisterRoutes(ctx, r, cdc, kb) - - return r -} - -// makePathname creates a unique pathname for each test. It will panic if it -// cannot get the current working directory. -func makePathname() string { - p, err := os.Getwd() - if err != nil { - panic(err) - } - - sep := string(filepath.Separator) - return strings.Replace(p, sep, "_", -1) -} - -// GetConfig returns a Tendermint config for the test cases. -func GetConfig() *tmcfg.Config { - pathname := makePathname() - config := tmcfg.ResetTestRoot(pathname) - - tmAddr, _, err := server.FreeTCPAddr() - if err != nil { - panic(err) - } - - rcpAddr, _, err := server.FreeTCPAddr() - if err != nil { - panic(err) - } - - grpcAddr, _, err := server.FreeTCPAddr() - if err != nil { - panic(err) - } - - config.P2P.ListenAddress = tmAddr - config.RPC.ListenAddress = rcpAddr - config.RPC.GRPCListenAddress = grpcAddr - - return config -} - -// GetKeyBase returns the LCD test keybase. It also requires that a directory -// could be made and a keybase could be fetched. -// -// NOTE: memDB cannot be used because the request is expecting to interact with -// the default location. -func GetKeyBase(t *testing.T) crkeys.Keybase { - dir, err := ioutil.TempDir("", "lcd_test") - require.NoError(t, err) - - viper.Set(cli.HomeFlag, dir) - - keybase, err := keys.GetKeyBase() - require.NoError(t, err) - - return keybase -} - -// CreateAddr adds an address to the key store and returns an address and seed. -// It also requires that the key could be created. -func CreateAddr(t *testing.T, name, password string, kb crkeys.Keybase) (sdk.AccAddress, string) { - var ( - err error - info crkeys.Info - seed string - ) - - info, seed, err = kb.CreateMnemonic(name, crkeys.English, password, crkeys.Secp256k1) - require.NoError(t, err) - - return sdk.AccAddress(info.GetPubKey().Address()), seed -} - -// InitializeTestLCD starts Tendermint and the LCD in process, listening on -// their respective sockets where nValidators is the total number of validators -// and initAddrs are the accounts to initialize with some steak tokens. It -// returns a cleanup function, a set of validator public keys, and a port. -func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress) (func(), []crypto.PubKey, string) { - config := GetConfig() - config.Consensus.TimeoutCommit = 100 - config.Consensus.SkipTimeoutCommit = false - config.TxIndex.IndexAllTags = true - - logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) - logger = log.NewFilter(logger, log.AllowNone()) - - privValidatorFile := config.PrivValidatorFile() - privVal := pvm.LoadOrGenFilePV(privValidatorFile) - privVal.Reset() - - db := dbm.NewMemDB() - app := gapp.NewGaiaApp(logger, db, nil) - cdc := gapp.MakeCodec() - - genesisFile := config.GenesisFile() - genDoc, err := tmtypes.GenesisDocFromFile(genesisFile) - require.NoError(t, err) - - if nValidators < 1 { - panic("InitializeTestLCD must use at least one validator") - } - - for i := 1; i < nValidators; i++ { - genDoc.Validators = append(genDoc.Validators, - tmtypes.GenesisValidator{ - PubKey: ed25519.GenPrivKey().PubKey(), - Power: 1, - Name: "val", - }, - ) - } - - var validatorsPKs []crypto.PubKey - - // NOTE: It's bad practice to reuse public key address for the owner - // address but doing in the test for simplicity. - var appGenTxs []json.RawMessage - for _, gdValidator := range genDoc.Validators { - pk := gdValidator.PubKey - validatorsPKs = append(validatorsPKs, pk) - - appGenTx, _, _, err := gapp.GaiaAppGenTxNF(cdc, pk, sdk.AccAddress(pk.Address()), "test_val1") - require.NoError(t, err) - - appGenTxs = append(appGenTxs, appGenTx) - } - - genesisState, err := gapp.GaiaAppGenState(cdc, appGenTxs[:]) - require.NoError(t, err) - - // add some tokens to init accounts - for _, addr := range initAddrs { - accAuth := auth.NewBaseAccountWithAddress(addr) - accAuth.Coins = sdk.Coins{sdk.NewCoin("steak", 100)} - acc := gapp.NewGenesisAccount(&accAuth) - genesisState.Accounts = append(genesisState.Accounts, acc) - genesisState.StakeData.Pool.LooseTokens = genesisState.StakeData.Pool.LooseTokens.Add(sdk.NewRat(100)) - } - - appState, err := wire.MarshalJSONIndent(cdc, genesisState) - require.NoError(t, err) - genDoc.AppState = appState - - listenAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) - - // XXX: Need to set this so LCD knows the tendermint node address! - viper.Set(client.FlagNode, config.RPC.ListenAddress) - viper.Set(client.FlagChainID, genDoc.ChainID) - - node, err := startTM(config, logger, genDoc, privVal, app) - require.NoError(t, err) - - lcd, err := startLCD(logger, listenAddr, cdc) - require.NoError(t, err) - - tests.WaitForLCDStart(port) - tests.WaitForHeight(1, port) - - cleanup := func() { - logger.Debug("cleaning up LCD initialization") - node.Stop() - node.Wait() - lcd.Close() - } - - return cleanup, validatorsPKs, port -} - -// startTM creates and starts an in-process Tendermint node with memDB and -// in-process ABCI application. It returns the new node or any error that -// occurred. -// -// TODO: Clean up the WAL dir or enable it to be not persistent! -func startTM( - tmcfg *tmcfg.Config, logger log.Logger, genDoc *tmtypes.GenesisDoc, - privVal tmtypes.PrivValidator, app abci.Application, -) (*nm.Node, error) { - genDocProvider := func() (*tmtypes.GenesisDoc, error) { return genDoc, nil } - dbProvider := func(*nm.DBContext) (dbm.DB, error) { return dbm.NewMemDB(), nil } - node, err := nm.NewNode( - tmcfg, - privVal, - proxy.NewLocalClientCreator(app), - genDocProvider, - dbProvider, - nm.DefaultMetricsProvider, - logger.With("module", "node"), - ) - if err != nil { - return nil, err - } - - err = node.Start() - if err != nil { - return nil, err - } - - tests.WaitForRPC(tmcfg.RPC.ListenAddress) - logger.Info("Tendermint running!") - - return node, err -} - -// startLCD starts the LCD. -// -// NOTE: This causes the thread to block. -func startLCD(logger log.Logger, listenAddr string, cdc *wire.Codec) (net.Listener, error) { - return tmrpc.StartHTTPServer(listenAddr, createHandler(cdc), logger, tmrpc.Config{}) -} - -// Request makes a test LCD test request. It returns a response object and a -// stringified response body. -func Request(t *testing.T, port, method, path string, payload []byte) (*http.Response, string) { - var ( - err error - res *http.Response - ) - url := fmt.Sprintf("http://localhost:%v%v", port, path) - - req, err := http.NewRequest(method, url, bytes.NewBuffer(payload)) - require.Nil(t, err) - - res, err = http.DefaultClient.Do(req) - require.Nil(t, err) - - output, err := ioutil.ReadAll(res.Body) - res.Body.Close() - require.Nil(t, err) - - return res, string(output) -} From 20c490f4adbfa0253c2c16b3b5c65db5c6df0cf4 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 1 Aug 2018 11:00:17 +0200 Subject: [PATCH 24/46] Fixed some linter errors --- x/stake/client/rest/query.go | 32 +++++++++++++++++--------------- x/stake/client/rest/tx.go | 2 +- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index bdccecc57f6a..dee060e5da30 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -83,6 +83,8 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec } // already resolve the rational shares to not handle this in the client + +// DelegationWithoutRat defines a delegation without type Rat for shares type DelegationWithoutRat struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` ValidatorAddr sdk.AccAddress `json:"validator_addr"` @@ -90,7 +92,7 @@ type DelegationWithoutRat struct { Height int64 `json:"height"` } -// Aggregation of all delegations, unbondings and redelegations +// DelegationSummary The aggregation of all delegations, unbondings and redelegations type DelegationSummary struct { Delegations []DelegationWithoutRat `json:"delegations"` UnbondingDelegations []stake.UnbondingDelegation `json:"unbonding_delegations"` @@ -149,8 +151,8 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu // the query will return empty if there is no data for this record if len(marshalledDelegation) != 0 { - delegation, err := types.UnmarshalDelegation(cdc, delegationKey, marshalledDelegation) - if err != nil { + delegation, errUnmarshal := types.UnmarshalDelegation(cdc, delegationKey, marshalledDelegation) + if errUnmarshal != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("couldn't unmarshall unbonding-delegation. Error: %s", err.Error()))) return @@ -176,8 +178,8 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu // the query will return empty if there is no data for this record if len(marshalledUnbondingDelegation) != 0 { - unbondingDelegation, err := types.UnmarshalUBD(cdc, undelegationKey, marshalledUnbondingDelegation) - if err != nil { + unbondingDelegation, errUnmarshal := types.UnmarshalUBD(cdc, undelegationKey, marshalledUnbondingDelegation) + if errUnmarshal != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("couldn't unmarshall unbonding-delegation. Error: %s", err.Error()))) return @@ -197,8 +199,8 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu } if len(marshalledRedelegations) != 0 { - redelegations, err := types.UnmarshalRED(cdc, keyRedelegateTo, marshalledRedelegations) - if err != nil { + redelegations, errUnmarshal := types.UnmarshalRED(cdc, keyRedelegateTo, marshalledRedelegations) + if errUnmarshal != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("couldn't unmarshall redelegations. Error: %s", err.Error()))) return @@ -258,31 +260,31 @@ func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Handle // TODO double check this if noQuery || isBondTx { - foundTxs, err := queryTxs(node, cdc, string(tags.ActionDelegate), delegatorAddr) - if err != nil { + foundTxs, errQuery := queryTxs(node, cdc, string(tags.ActionDelegate), delegatorAddr) + if errQuery != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) } txs = append(txs, foundTxs...) } if noQuery || isUnbondTx { - foundTxs, err := queryTxs(node, cdc, string(tags.ActionBeginUnbonding), delegatorAddr) - if err != nil { + foundTxs, errQuery := queryTxs(node, cdc, string(tags.ActionBeginUnbonding), delegatorAddr) + if errQuery != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) } txs = append(txs, foundTxs...) - foundTxs, err = queryTxs(node, cdc, string(tags.ActionCompleteUnbonding), delegatorAddr) - if err != nil { + foundTxs, errQuery = queryTxs(node, cdc, string(tags.ActionCompleteUnbonding), delegatorAddr) + if errQuery != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) } txs = append(txs, foundTxs...) } if noQuery || isRedTx { - foundTxs, err := queryTxs(node, cdc, string(tags.ActionBeginRedelegation), delegatorAddr) - if err != nil { + foundTxs, errQuery := queryTxs(node, cdc, string(tags.ActionBeginRedelegation), delegatorAddr) + if errQuery != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) } diff --git a/x/stake/client/rest/tx.go b/x/stake/client/rest/tx.go index d5719bc24b81..6d1f9c46ae03 100644 --- a/x/stake/client/rest/tx.go +++ b/x/stake/client/rest/tx.go @@ -50,7 +50,7 @@ type msgCompleteUnbondingInput struct { ValidatorAddr string `json:"validator_addr"` // in bech32 } -// request body for edit delegations +// EditDelegationsBody The request body for edit delegations type EditDelegationsBody struct { LocalAccountName string `json:"name"` Password string `json:"password"` From d6dc1566a01892fa1778bfe6344a6e4020d256bd Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 1 Aug 2018 11:28:00 +0200 Subject: [PATCH 25/46] Reduced complexity of staking tx query --- x/stake/client/rest/query.go | 45 ++++++++++++------------------------ 1 file changed, 15 insertions(+), 30 deletions(-) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index dee060e5da30..b0d4b62bf330 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -141,6 +141,7 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu for _, validator := range validators { validatorAddr = validator.Owner + // Delegations delegationKey := stake.GetDelegationKey(delegatorAddr, validatorAddr) marshalledDelegation, err := ctx.QueryStore(delegationKey, storeName) if err != nil { @@ -168,6 +169,7 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu delegationSummary.Delegations = append(delegationSummary.Delegations, outputDelegation) } + // Undelegations undelegationKey := stake.GetUBDKey(delegatorAddr, validatorAddr) marshalledUnbondingDelegation, err := ctx.QueryStore(undelegationKey, storeName) if err != nil { @@ -188,6 +190,7 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu delegationSummary.UnbondingDelegations = append(delegationSummary.UnbondingDelegations, unbondingDelegation) } + // Redelegations // only querying redelegations to a validator as this should give us already all relegations // if we also would put in redelegations from, we would have every redelegation double keyRedelegateTo := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) @@ -257,41 +260,23 @@ func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Handle isUnbondTx := contains(typesQuerySlice, "unbond") isRedTx := contains(typesQuerySlice, "redelegate") var txs = []tx.TxInfo{} + var actions []string - // TODO double check this if noQuery || isBondTx { - foundTxs, errQuery := queryTxs(node, cdc, string(tags.ActionDelegate), delegatorAddr) - if errQuery != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) - } - txs = append(txs, foundTxs...) + actions = append(actions, string(tags.ActionDelegate)) } if noQuery || isUnbondTx { - foundTxs, errQuery := queryTxs(node, cdc, string(tags.ActionBeginUnbonding), delegatorAddr) - if errQuery != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) - } - txs = append(txs, foundTxs...) - - foundTxs, errQuery = queryTxs(node, cdc, string(tags.ActionCompleteUnbonding), delegatorAddr) - if errQuery != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) - } - txs = append(txs, foundTxs...) + actions = append(actions, string(tags.ActionBeginUnbonding)) + actions = append(actions, string(tags.ActionCompleteUnbonding)) } if noQuery || isRedTx { - foundTxs, errQuery := queryTxs(node, cdc, string(tags.ActionBeginRedelegation), delegatorAddr) - if errQuery != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) - } - txs = append(txs, foundTxs...) + actions = append(actions, string(tags.ActionBeginRedelegation)) + actions = append(actions, string(tags.ActionCompleteRedelegation)) + } - foundTxs, err = queryTxs(node, cdc, string(tags.ActionCompleteRedelegation), delegatorAddr) - if err != nil { + for _, action := range actions { + foundTxs, errQuery := queryTxs(node, cdc, action, delegatorAddr) + if errQuery != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) } @@ -365,7 +350,7 @@ func unbondingDelegationsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) htt ubd, err := types.UnmarshalUBD(cdc, key, res) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("couldn't unmarshall unbonding-delegation. Error: %s", err.Error()))) return } @@ -375,7 +360,7 @@ func unbondingDelegationsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) htt output, err := cdc.MarshalJSON(ubdArray) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) + w.Write([]byte(fmt.Sprintf("couldn't marshall unbonding-delegation. Error: %s", err.Error()))) return } From e2cab9ff3a4ebbbac9ce9bb4b2c420b44b4ef72d Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 1 Aug 2018 11:55:39 +0200 Subject: [PATCH 26/46] More golinter fixes --- client/lcd/lcd_test.go | 6 +++--- client/tx/query.go | 10 +++++----- client/tx/search.go | 8 ++++---- docs/clients/lcd-rest-api.yaml | 2 +- docs/light/api.md | 2 +- x/stake/client/rest/query.go | 21 ++++++++++++++------- x/stake/client/rest/tx.go | 4 ++-- 7 files changed, 30 insertions(+), 23 deletions(-) diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index b9e52eab47f8..e41966287ff3 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -317,7 +317,7 @@ func TestTxs(t *testing.T) { res, body = Request(t, port, "GET", fmt.Sprintf("/txs/%s", resultTx.Hash), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var indexedTxs []tx.TxInfo + var indexedTxs []tx.Info // check if tx is queryable res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=tx.hash='%s'", resultTx.Hash), nil) @@ -788,7 +788,7 @@ func getDelegationSummary(t *testing.T, port string, delegatorAddr sdk.AccAddres return summary } -func getBondingTxs(t *testing.T, port string, delegatorAddr sdk.AccAddress, query string) []tx.TxInfo { +func getBondingTxs(t *testing.T, port string, delegatorAddr sdk.AccAddress, query string) []tx.Info { // get the account to get the sequence var res *http.Response @@ -799,7 +799,7 @@ func getBondingTxs(t *testing.T, port string, delegatorAddr sdk.AccAddress, quer res, body = Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/txs", delegatorAddr), nil) } require.Equal(t, http.StatusOK, res.StatusCode, body) - var txs []tx.TxInfo + var txs []tx.Info err := cdc.UnmarshalJSON([]byte(body), &txs) require.Nil(t, err) return txs diff --git a/client/tx/query.go b/client/tx/query.go index 6861d9b9db12..1ce1571fde8f 100644 --- a/client/tx/query.go +++ b/client/tx/query.go @@ -74,14 +74,14 @@ func queryTx(cdc *wire.Codec, ctx context.CoreContext, hashHexStr string, trustN return wire.MarshalJSONIndent(cdc, info) } -func formatTxResult(cdc *wire.Codec, res *ctypes.ResultTx) (TxInfo, error) { +func formatTxResult(cdc *wire.Codec, res *ctypes.ResultTx) (Info, error) { // TODO: verify the proof if requested tx, err := parseTx(cdc, res.Tx) if err != nil { - return TxInfo{}, err + return Info{}, err } - info := TxInfo{ + info := Info{ Hash: res.Hash, Height: res.Height, Tx: tx, @@ -90,8 +90,8 @@ func formatTxResult(cdc *wire.Codec, res *ctypes.ResultTx) (TxInfo, error) { return info, nil } -// TxInfo is used to prepare info to display -type TxInfo struct { +// Info is used to prepare info to display +type Info struct { Hash common.HexBytes `json:"hash"` Height int64 `json:"height"` Tx sdk.Tx `json:"tx"` diff --git a/client/tx/search.go b/client/tx/search.go index a0231439d911..8ae8217c7aab 100644 --- a/client/tx/search.go +++ b/client/tx/search.go @@ -53,7 +53,7 @@ func SearchTxCmd(cdc *wire.Codec) *cobra.Command { return cmd } -func searchTxs(ctx context.CoreContext, cdc *wire.Codec, tags []string) ([]TxInfo, error) { +func searchTxs(ctx context.CoreContext, cdc *wire.Codec, tags []string) ([]Info, error) { if len(tags) == 0 { return nil, errors.New("must declare at least one tag to search") } @@ -82,10 +82,10 @@ func searchTxs(ctx context.CoreContext, cdc *wire.Codec, tags []string) ([]TxInf return info, nil } -// parse the indexed txs into an array of TxInfo -func FormatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]TxInfo, error) { +// parse the indexed txs into an array of Info +func FormatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]Info, error) { var err error - out := make([]TxInfo, len(res)) + out := make([]Info, len(res)) for i := range res { out[i], err = formatTxResult(cdc, res[i]) if err != nil { diff --git a/docs/clients/lcd-rest-api.yaml b/docs/clients/lcd-rest-api.yaml index 780666947f42..063e3a55b857 100644 --- a/docs/clients/lcd-rest-api.yaml +++ b/docs/clients/lcd-rest-api.yaml @@ -524,7 +524,7 @@ paths: required: true type: string post: - summary: Edit a delegation + summary: Submit delegation parameters: - in: body name: delegation diff --git a/docs/light/api.md b/docs/light/api.md index c6b34d68c8a8..41abed5da6ef 100644 --- a/docs/light/api.md +++ b/docs/light/api.md @@ -513,7 +513,7 @@ Returns on failure: url: /stake/delegators/{delegatorAddr}/delegations -Functionality: Edit a delegation. +Functionality: Submit a delegation. Returns on success: diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index b0d4b62bf330..d110c9e68977 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -259,19 +259,26 @@ func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Handle isBondTx := contains(typesQuerySlice, "bond") isUnbondTx := contains(typesQuerySlice, "unbond") isRedTx := contains(typesQuerySlice, "redelegate") - var txs = []tx.TxInfo{} + var txs = []tx.Info{} var actions []string - if noQuery || isBondTx { + if isBondTx { actions = append(actions, string(tags.ActionDelegate)) - } - if noQuery || isUnbondTx { + } else if isUnbondTx { actions = append(actions, string(tags.ActionBeginUnbonding)) actions = append(actions, string(tags.ActionCompleteUnbonding)) - } - if noQuery || isRedTx { + } else if isRedTx { actions = append(actions, string(tags.ActionBeginRedelegation)) actions = append(actions, string(tags.ActionCompleteRedelegation)) + } else if noQuery { + actions = append(actions, string(tags.ActionDelegate)) + actions = append(actions, string(tags.ActionBeginUnbonding)) + actions = append(actions, string(tags.ActionCompleteUnbonding)) + actions = append(actions, string(tags.ActionBeginRedelegation)) + actions = append(actions, string(tags.ActionCompleteRedelegation)) + } else { + w.WriteHeader(http.StatusNoContent) + return } for _, action := range actions { @@ -294,7 +301,7 @@ func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Handle } } -func queryTxs(node rpcclient.Client, cdc *wire.Codec, tag string, delegatorAddr string) ([]tx.TxInfo, error) { +func queryTxs(node rpcclient.Client, cdc *wire.Codec, tag string, delegatorAddr string) ([]tx.Info, error) { page := 0 perPage := 100 prove := false diff --git a/x/stake/client/rest/tx.go b/x/stake/client/rest/tx.go index 6d1f9c46ae03..64cec51dc5dd 100644 --- a/x/stake/client/rest/tx.go +++ b/x/stake/client/rest/tx.go @@ -20,7 +20,7 @@ import ( func registerTxRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { r.HandleFunc( "/stake/delegators/{delegatorAddr}/delegations", - editDelegationsRequestHandlerFn(cdc, kb, ctx), + delegationsRequestHandlerFn(cdc, kb, ctx), ).Methods("POST") } @@ -68,7 +68,7 @@ type EditDelegationsBody struct { // nolint: gocyclo // TODO: Split this up into several smaller functions, and remove the above nolint // TODO: use sdk.ValAddress instead of sdk.AccAddress for validators in messages -func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { +func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var m EditDelegationsBody body, err := ioutil.ReadAll(r.Body) From 84b3de7d5a977f561b6eb3e1d6f002c09c1bbc1c Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 1 Aug 2018 13:12:06 +0200 Subject: [PATCH 27/46] Logic for delegatorValidators routes. Tests missing --- client/tx/broadcast.go | 4 +- client/tx/root.go | 2 +- client/tx/search.go | 6 +- client/tx/sign.go | 4 +- x/stake/client/rest/query.go | 323 +++++++++++++++++++---------------- x/stake/client/rest/tx.go | 92 +++++----- x/stake/client/rest/utils.go | 42 ++++- 7 files changed, 273 insertions(+), 200 deletions(-) diff --git a/client/tx/broadcast.go b/client/tx/broadcast.go index 21f576db419f..176b6a5b521a 100644 --- a/client/tx/broadcast.go +++ b/client/tx/broadcast.go @@ -7,12 +7,12 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" ) -// Tx Broadcast Body +// BroadcastTxBody Tx Broadcast Body type BroadcastTxBody struct { TxBytes string `json:"tx"` } -// BroadcastTx REST Handler +// BroadcastTxRequestHandlerFn BroadcastTx REST Handler func BroadcastTxRequestHandlerFn(ctx context.CoreContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var m BroadcastTxBody diff --git a/client/tx/root.go b/client/tx/root.go index 5def5a544091..2e71cdc44c5a 100644 --- a/client/tx/root.go +++ b/client/tx/root.go @@ -16,7 +16,7 @@ func AddCommands(cmd *cobra.Command, cdc *wire.Codec) { ) } -// register REST routes +// RegisterRoutes Registers REST routes for txs func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec) { r.HandleFunc("/txs/{hash}", QueryTxRequestHandlerFn(cdc, ctx)).Methods("GET") r.HandleFunc("/txs", SearchTxRequestHandlerFn(ctx, cdc)).Methods("GET") diff --git a/client/tx/search.go b/client/tx/search.go index 8ae8217c7aab..35e5a9191770 100644 --- a/client/tx/search.go +++ b/client/tx/search.go @@ -23,7 +23,7 @@ const ( flagAny = "any" ) -// default client command to search through tagged transactions +// SearchTxCmd Default client command to search through tagged transactions func SearchTxCmd(cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "txs", @@ -82,7 +82,7 @@ func searchTxs(ctx context.CoreContext, cdc *wire.Codec, tags []string) ([]Info, return info, nil } -// parse the indexed txs into an array of Info +// FormatTxResults Parse the indexed txs into an array of Info func FormatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]Info, error) { var err error out := make([]Info, len(res)) @@ -98,7 +98,7 @@ func FormatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]Info, error) { ///////////////////////////////////////// // REST -// Search Tx REST Handler +// SearchTxRequestHandlerFn Search Tx REST Handler func SearchTxRequestHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { tag := r.FormValue("tag") diff --git a/client/tx/sign.go b/client/tx/sign.go index bedd202b48b3..f2f34b13ceb4 100644 --- a/client/tx/sign.go +++ b/client/tx/sign.go @@ -8,7 +8,7 @@ import ( keys "github.com/cosmos/cosmos-sdk/crypto/keys" ) -// REST request body +// SignTxBody REST request body for signed txs // TODO does this need to be exposed? type SignTxBody struct { Name string `json:"name"` @@ -16,7 +16,7 @@ type SignTxBody struct { TxBytes string `json:"tx"` } -// sign transaction REST Handler +// SignTxRequstHandler Sign transaction REST Handler func SignTxRequstHandler(w http.ResponseWriter, r *http.Request) { var kb keys.Keybase var m SignTxBody diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index d110c9e68977..2032436eeeeb 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -7,8 +7,6 @@ import ( "github.com/gorilla/mux" - rpcclient "github.com/tendermint/tendermint/rpc/client" - "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" @@ -35,12 +33,18 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec delegatorTxsHandlerFn(ctx, cdc), ).Methods("GET") - // // GET /stake/delegators/{addr}/validators // Query all validators that a delegator is bonded to + // // GET /stake/delegators/{delegatorAddr}/validators // Query all validators that a delegator is bonded to // r.HandleFunc( // "/stake/delegators/{delegatorAddr}/validators", // delegatorValidatorsHandlerFn(ctx, cdc), // ).Methods("GET") + // GET /stake/delegators/{delegatorAddr}/validators/{validatorAddr} // Query a validator that a delegator is bonded to + // r.HandleFunc( + // "/stake/delegators/{delegatorAddr}/validators", + // delegatorValidatorHandlerFn(ctx, cdc), + // ).Methods("GET") + // GET /stake/delegators/{delegatorAddr}/delegations/{validatorAddr} // Query a delegation between a delegator and a validator r.HandleFunc( "/stake/delegators/{delegatorAddr}/delegations/{validatorAddr}", @@ -53,8 +57,6 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec unbondingDelegationsHandlerFn(ctx, cdc), ).Methods("GET") - // GET /stake/delegators/{addr}/validators/{addr} - /* GET /stake/delegators/{addr}/validators/{addr}/txs // Get all txs to a validator performed by a delegator GET /stake/delegators/{addr}/validators/{addr}/txs?type=bond // Get all bonding txs to a validator performed by a delegator @@ -285,7 +287,7 @@ func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Handle foundTxs, errQuery := queryTxs(node, cdc, action, delegatorAddr) if errQuery != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", errQuery.Error()))) } txs = append(txs, foundTxs...) } @@ -301,19 +303,6 @@ func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Handle } } -func queryTxs(node rpcclient.Client, cdc *wire.Codec, tag string, delegatorAddr string) ([]tx.Info, error) { - page := 0 - perPage := 100 - prove := false - query := tags.Action + "='" + tag + "' AND " + tags.Delegator + "='" + delegatorAddr + "'" - res, err := node.TxSearch(query, prove, page, perPage) - if err != nil { - return nil, err - } - - return tx.FormatTxResults(cdc, res.Txs) -} - // http request handler to query an unbonding-delegation func unbondingDelegationsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { @@ -440,132 +429,176 @@ func delegationHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF } } -// func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { -// return func(w http.ResponseWriter, r *http.Request) { -// // read parameters -// var isBonded bool -// var output []byte -// vars := mux.Vars(r) -// bech32delegator := vars["delegatorAddr"] -// bech32validator := vars["validatorAddr"] - -// delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) -// if err != nil { -// w.WriteHeader(http.StatusBadRequest) -// w.Write([]byte(err.Error())) -// return -// } - -// validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) -// if err != nil { -// w.WriteHeader(http.StatusBadRequest) -// w.Write([]byte(err.Error())) -// return -// } - -// // Check if there if the delegator is bonded or redelegated to the validator - -// keyDel := stake.GetDelegationKey(delegatorAddr, validatorAddr) -// keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) - -// res, err := ctx.QueryStore(keyDel, storeName) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) -// return -// } - -// if len(res) != 0 { -// isBonded = true -// } - -// if !isBonded { -// res, err = ctx.QueryStore(keyRed, storeName) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) -// return -// } - -// if len(res) != 0 { -// isBonded = true -// } -// } - -// if isBonded { -// kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) -// return -// } - -// // the query will return empty if there are no validators -// if len(kvs) == 0 { -// w.WriteHeader(http.StatusNoContent) -// return -// } -// validator, err := getValidator(validatorAddr, kvs, cdc) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(fmt.Sprintf("Couldn't get info from validator %s. Error: %s", validatorAddr.String(), err.Error()))) -// return -// } else if validator == nil && err == nil { -// w.WriteHeader(http.StatusNoContent) -// return -// } -// // success -// output, err = cdc.MarshalJSON(validator) -// if err != nil { -// w.WriteHeader(http.StatusInternalServerError) -// w.Write([]byte(err.Error())) -// return -// } -// } else { -// // delegator is not bonded to any delegator -// w.WriteHeader(http.StatusNoContent) -// return -// } -// w.Write(output) -// } -// } - -// TODO Rename -// func stakingTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { -// return func(w http.ResponseWriter, r *http.Request) { - -// // read parameters -// vars := mux.Vars(r) -// bech32delegator := vars["delegatorAddr"] -// bech32validator := vars["validatorAddr"] - -// delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) -// if err != nil { -// w.WriteHeader(http.StatusBadRequest) -// w.Write([]byte(err.Error())) -// return -// } - -// validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) -// if err != nil { -// w.WriteHeader(http.StatusBadRequest) -// w.Write([]byte(err.Error())) -// return -// } - -// var typesQuerySlice []string -// var output []byte // XXX not sure if this is append -// typesQuery := r.URL.Query().Get("type") -// typesQuerySlice = strings.Split(strings.TrimSpace(typesQuery), " ") - -// noQuery := len(typesQuerySlice) == 0 -// isBondTx := contains(typesQuerySlice, "bond") -// isUnbondTx := contains(typesQuerySlice, "unbond") -// isRedTx := contains(typesQuerySlice, "redelegate") - -// w.Write(output) -// } -// } +// HTTP request handler to query all delegator bonded validators +func delegatorValidatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var validatorAccAddr sdk.AccAddress + var bondedValidators []types.BechValidator + + // read parameters + vars := mux.Vars(r) + bech32delegator := vars["delegatorAddr"] + + delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + + // Get all validators using key + kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query validators. Error: %s", err.Error()))) + return + } + + // the query will return empty if there are no validators + if len(kvs) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + + validators, err := getValidators(kvs, cdc) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return + } + + for _, validator := range validators { + // get all transactions from the delegator to val and append + validatorAccAddr = validator.Owner + + // Check if the delegator is bonded or redelegated to the validator + keyDel := stake.GetDelegationKey(delegatorAddr, validatorAccAddr) + // keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAccAddr) + + res, errQuery := ctx.QueryStore(keyDel, storeName) + if errQuery != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", errQuery.Error()))) + return + } + + // if len(res) == 0 { + // res, err = ctx.QueryStore(keyRed, storeName) + // if err != nil { + // w.WriteHeader(http.StatusInternalServerError) + // w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + // return + // } + // } + + if len(res) != 0 { + + kvs, errQuery := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + if errQuery != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Error: %s", errQuery.Error()))) + return + } + // the query will return empty if there are no validators + if len(kvs) == 0 { + continue + } + validator, errVal := getValidatorFromAccAdrr(validatorAccAddr, kvs, cdc) + if errVal != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Couldn't get info from validator %s. Error: %s", validatorAccAddr.String(), errVal.Error()))) + return + } + bondedValidators = append(bondedValidators, validator) + } + } + // success + output, err := cdc.MarshalJSON(bondedValidators) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + w.Write(output) // write + } +} + +// HTTP request handler to get information from a currently bonded validator +func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + // read parameters + var output []byte + vars := mux.Vars(r) + bech32delegator := vars["delegatorAddr"] + bech32validator := vars["validatorAddr"] + + delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + validatorAccAddr, err := sdk.AccAddressFromBech32(bech32validator) + validatorValAddress, err := sdk.ValAddressFromBech32(bech32validator) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return + } + + // Check if there if the delegator is bonded or redelegated to the validator + + keyDel := stake.GetDelegationKey(delegatorAddr, validatorAccAddr) + // keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAccAddr) + + res, err := ctx.QueryStore(keyDel, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + return + } + + // TODO Double check if this is necessary or not + // if delegator has no delegations + // if len(res) == 0 { + // res, err = ctx.QueryStore(keyRed, storeName) + // if err != nil { + // w.WriteHeader(http.StatusInternalServerError) + // w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + // return + // } + // } + // if delegator delegations + if len(res) != 0 { + kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + return + } + + // the query will return empty if there are no validators + if len(kvs) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + validator, err := getValidator(validatorValAddress, kvs, cdc) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Couldn't get info from validator %s. Error: %s", validatorValAddress.String(), err.Error()))) + return + } + // success + output, err = cdc.MarshalJSON(validator) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + } else { + // delegator is not bonded to any delegator + w.WriteHeader(http.StatusNoContent) + return + } + w.Write(output) + } +} // TODO bech32 // HTTP request handler to query list of validators diff --git a/x/stake/client/rest/tx.go b/x/stake/client/rest/tx.go index 64cec51dc5dd..0f75939dc98b 100644 --- a/x/stake/client/rest/tx.go +++ b/x/stake/client/rest/tx.go @@ -100,17 +100,17 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C i := 0 for _, msg := range m.Delegations { - delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) - if err != nil { + delegatorAddr, errAddr := sdk.AccAddressFromBech32(msg.DelegatorAddr) + if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", errAddr.Error()))) return } - validatorAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) + validatorAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorAddr) validatorAddrAcc := sdk.AccAddress(validatorAddr) - if err != nil { + if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) return } if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { @@ -127,10 +127,10 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C } for _, msg := range m.BeginRedelegates { - delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) - if err != nil { + delegatorAddr, errAddr := sdk.AccAddressFromBech32(msg.DelegatorAddr) + if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", errAddr.Error()))) return } if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { @@ -138,24 +138,24 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C w.Write([]byte("Must use own delegator address")) return } - validatorSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) + validatorSrcAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) validatorSrcAddrAcc := sdk.AccAddress(validatorSrcAddr) - if err != nil { + if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) return } - ValidatorDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) + ValidatorDstAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) ValidatorDstAddrAcc := sdk.AccAddress(ValidatorDstAddr) - if err != nil { + if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) return } - shares, err := sdk.NewRatFromDecimal(msg.SharesAmount, types.MaxBondDenominatorPrecision) - if err != nil { + shares, errRat := sdk.NewRatFromDecimal(msg.SharesAmount, types.MaxBondDenominatorPrecision) + if errRat != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode shares amount. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode shares amount. Error: %s", errRat.Error()))) return } messages[i] = stake.MsgBeginRedelegate{ @@ -168,24 +168,24 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C } for _, msg := range m.CompleteRedelegates { - delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) - if err != nil { + delegatorAddr, errAddr := sdk.AccAddressFromBech32(msg.DelegatorAddr) + if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", errAddr.Error()))) return } - validatorSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) + validatorSrcAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) validatorSrcAddrAcc := sdk.AccAddress(validatorSrcAddr) - if err != nil { + if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) return } - ValidatorDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) + ValidatorDstAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) ValidatorDstAddrAcc := sdk.AccAddress(ValidatorDstAddr) - if err != nil { + if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) return } if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { @@ -202,10 +202,10 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C } for _, msg := range m.BeginUnbondings { - delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) - if err != nil { + delegatorAddr, errAddr := sdk.AccAddressFromBech32(msg.DelegatorAddr) + if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", errAddr.Error()))) return } if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { @@ -213,17 +213,17 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C w.Write([]byte("Must use own delegator address")) return } - validatorAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) + validatorAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorAddr) validatorAddrAcc := sdk.AccAddress(validatorAddr) - if err != nil { + if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) return } - shares, err := sdk.NewRatFromDecimal(msg.SharesAmount, types.MaxBondDenominatorPrecision) - if err != nil { + shares, errRat := sdk.NewRatFromDecimal(msg.SharesAmount, types.MaxBondDenominatorPrecision) + if errRat != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode shares amount. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode shares amount. Error: %s", errRat.Error()))) return } messages[i] = stake.MsgBeginUnbonding{ @@ -235,16 +235,16 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C } for _, msg := range m.CompleteUnbondings { - delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) - if err != nil { + delegatorAddr, errAddr := sdk.AccAddressFromBech32(msg.DelegatorAddr) + if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", errAddr.Error()))) return } - validatorAddr, err := sdk.AccAddressFromBech32(msg.ValidatorAddr) - if err != nil { + validatorAddr, errAddr := sdk.AccAddressFromBech32(msg.ValidatorAddr) + if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) return } if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { @@ -270,8 +270,8 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C ctx = ctx.WithSequence(m.Sequence) m.Sequence++ - txBytes, err := ctx.SignAndBuild(m.LocalAccountName, m.Password, []sdk.Msg{msg}, cdc) - if err != nil { + txBytes, errSign := ctx.SignAndBuild(m.LocalAccountName, m.Password, []sdk.Msg{msg}, cdc) + if errSign != nil { w.WriteHeader(http.StatusUnauthorized) w.Write([]byte(err.Error())) return @@ -285,8 +285,8 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C // should we have a sdk.MultiMsg type to make sending atomic? results := make([]*ctypes.ResultBroadcastTxCommit, len(signedTxs[:])) for i, txBytes := range signedTxs { - res, err := ctx.BroadcastTx(txBytes) - if err != nil { + res, errTx := ctx.BroadcastTx(txBytes) + if errTx != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index c89c042a73b1..35117f7d701c 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -3,11 +3,14 @@ package rest import ( "reflect" + "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/stake/tags" "github.com/cosmos/cosmos-sdk/x/stake/types" "github.com/pkg/errors" + rpcclient "github.com/tendermint/tendermint/rpc/client" ) // Contains checks if the a given query contains one of the tx types @@ -20,6 +23,20 @@ func contains(stringSlice []string, txType string) bool { return false } +// Query staking txs +func queryTxs(node rpcclient.Client, cdc *wire.Codec, tag string, delegatorAddr string) ([]tx.Info, error) { + page := 0 + perPage := 100 + prove := false + query := tags.Action + "='" + tag + "' AND " + tags.Delegator + "='" + delegatorAddr + "'" + res, err := node.TxSearch(query, prove, page, perPage) + if err != nil { + return nil, err + } + + return tx.FormatTxResults(cdc, res.Txs) +} + // get all Validators func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechValidator, error) { // parse out the validators @@ -41,7 +58,7 @@ func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechVali return validators, nil } -// get Validator given an Account Address +// get Validator given a ValAddress func getValidator(address sdk.ValAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (stake.BechValidator, error) { // parse out the validators for _, kv := range validatorKVs { @@ -63,3 +80,26 @@ func getValidator(address sdk.ValAddress, validatorKVs []sdk.KVPair, cdc *wire.C } return stake.BechValidator{}, errors.Errorf("Couldn't find validator") // validator Not Found } + +// get Validator given an AccAddress +func getValidatorFromAccAdrr(address sdk.AccAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (stake.BechValidator, error) { + // parse out the validators + for _, kv := range validatorKVs { + addr := kv.Key[1:] + validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) + if err != nil { + return stake.BechValidator{}, err + } + + ownerAddress := validator.PubKey.Address() + if reflect.DeepEqual(ownerAddress.Bytes(), address.Bytes()) { + bech32Validator, err := validator.Bech32Validator() + if err != nil { + return stake.BechValidator{}, err + } + + return bech32Validator, nil + } + } + return stake.BechValidator{}, errors.Errorf("Couldn't find validator") // validator Not Found +} From eb611e1081137990dbc82fb7cacca234bf9ab3fd Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 1 Aug 2018 15:49:53 +0200 Subject: [PATCH 28/46] Addressed Aleks comments --- x/stake/client/rest/query.go | 43 ++++++++-------------------- x/stake/client/rest/utils.go | 17 ++++++------ x/stake/keeper/key.go | 54 +++++++++++++++--------------------- 3 files changed, 43 insertions(+), 71 deletions(-) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 2032436eeeeb..573ca168ff7a 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -453,10 +453,8 @@ func delegatorValidatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("couldn't query validators. Error: %s", err.Error()))) return - } - - // the query will return empty if there are no validators - if len(kvs) == 0 { + } else if len(kvs) == 0 { + // the query will return empty if there are no validators w.WriteHeader(http.StatusNoContent) return } @@ -483,27 +481,17 @@ func delegatorValidatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http return } - // if len(res) == 0 { - // res, err = ctx.QueryStore(keyRed, storeName) - // if err != nil { - // w.WriteHeader(http.StatusInternalServerError) - // w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) - // return - // } - // } - if len(res) != 0 { - kvs, errQuery := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) if errQuery != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Error: %s", errQuery.Error()))) return - } - // the query will return empty if there are no validators - if len(kvs) == 0 { + } else if len(kvs) == 0 { + // the query will return empty if there are no delegations continue } + validator, errVal := getValidatorFromAccAdrr(validatorAccAddr, kvs, cdc) if errVal != nil { w.WriteHeader(http.StatusInternalServerError) @@ -511,6 +499,10 @@ func delegatorValidatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http return } bondedValidators = append(bondedValidators, validator) + } else { + // delegator is not bonded to any delegator + w.WriteHeader(http.StatusNoContent) + return } } // success @@ -553,17 +545,6 @@ func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http. w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) return } - - // TODO Double check if this is necessary or not - // if delegator has no delegations - // if len(res) == 0 { - // res, err = ctx.QueryStore(keyRed, storeName) - // if err != nil { - // w.WriteHeader(http.StatusInternalServerError) - // w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) - // return - // } - // } // if delegator delegations if len(res) != 0 { kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) @@ -571,10 +552,8 @@ func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http. w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) return - } - - // the query will return empty if there are no validators - if len(kvs) == 0 { + } else if len(kvs) == 0 { + // the query will return empty if there are no delegations w.WriteHeader(http.StatusNoContent) return } diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 35117f7d701c..5419e6cb1108 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -1,6 +1,8 @@ package rest import ( + "bytes" + "fmt" "reflect" "github.com/cosmos/cosmos-sdk/client/tx" @@ -13,7 +15,7 @@ import ( rpcclient "github.com/tendermint/tendermint/rpc/client" ) -// Contains checks if the a given query contains one of the tx types +// contains Checks if the a given query contains one of the tx types func contains(stringSlice []string, txType string) bool { for _, word := range stringSlice { if word == txType { @@ -28,7 +30,7 @@ func queryTxs(node rpcclient.Client, cdc *wire.Codec, tag string, delegatorAddr page := 0 perPage := 100 prove := false - query := tags.Action + "='" + tag + "' AND " + tags.Delegator + "='" + delegatorAddr + "'" + query := fmt.Sprintf("%s='%s' AND %s='%s'", tags.Action, tag, tags.Delegator, delegatorAddr) res, err := node.TxSearch(query, prove, page, perPage) if err != nil { return nil, err @@ -39,7 +41,6 @@ func queryTxs(node rpcclient.Client, cdc *wire.Codec, tag string, delegatorAddr // get all Validators func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechValidator, error) { - // parse out the validators validators := make([]types.BechValidator, len(validatorKVs)) for i, kv := range validatorKVs { @@ -58,7 +59,7 @@ func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechVali return validators, nil } -// get Validator given a ValAddress +// getValidator Gets a validator given a ValAddress func getValidator(address sdk.ValAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (stake.BechValidator, error) { // parse out the validators for _, kv := range validatorKVs { @@ -78,10 +79,10 @@ func getValidator(address sdk.ValAddress, validatorKVs []sdk.KVPair, cdc *wire.C return bech32Validator, nil } } - return stake.BechValidator{}, errors.Errorf("Couldn't find validator") // validator Not Found + return stake.BechValidator{}, errors.Errorf("Couldn't find validator") } -// get Validator given an AccAddress +// getValidatorFromAccAdrr Gets a validator given an AccAddress func getValidatorFromAccAdrr(address sdk.AccAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (stake.BechValidator, error) { // parse out the validators for _, kv := range validatorKVs { @@ -92,7 +93,7 @@ func getValidatorFromAccAdrr(address sdk.AccAddress, validatorKVs []sdk.KVPair, } ownerAddress := validator.PubKey.Address() - if reflect.DeepEqual(ownerAddress.Bytes(), address.Bytes()) { + if bytes.Equal(ownerAddress.Bytes(), address.Bytes()) { bech32Validator, err := validator.Bech32Validator() if err != nil { return stake.BechValidator{}, err @@ -101,5 +102,5 @@ func getValidatorFromAccAdrr(address sdk.AccAddress, validatorKVs []sdk.KVPair, return bech32Validator, nil } } - return stake.BechValidator{}, errors.Errorf("Couldn't find validator") // validator Not Found + return stake.BechValidator{}, errors.Errorf("Couldn't find validator") } diff --git a/x/stake/keeper/key.go b/x/stake/keeper/key.go index b6330b29eb25..74fc02f090c8 100644 --- a/x/stake/keeper/key.go +++ b/x/stake/keeper/key.go @@ -34,30 +34,30 @@ var ( const maxDigitsForAccount = 12 // ~220,000,000 atoms created at launch -// get the key for the validator with address. +// GetValidatorKey Gets the key for the validator with address. // VALUE: stake/types.Validator func GetValidatorKey(ownerAddr sdk.AccAddress) []byte { return append(ValidatorsKey, ownerAddr.Bytes()...) } -// get the key for the validator with pubkey. +// GetValidatorByPubKeyIndexKey Gets the key for the validator with pubkey. // VALUE: validator owner address ([]byte) func GetValidatorByPubKeyIndexKey(pubkey crypto.PubKey) []byte { return append(ValidatorsByPubKeyIndexKey, pubkey.Bytes()...) } -// get the key for the current validator group +// GetValidatorsBondedIndexKey Gets the key for the current validator group // VALUE: none (key rearrangement with GetValKeyFromValBondedIndexKey) func GetValidatorsBondedIndexKey(ownerAddr sdk.AccAddress) []byte { return append(ValidatorsBondedIndexKey, ownerAddr.Bytes()...) } -// Get the validator owner address from ValBondedIndexKey +// GetAddressFromValBondedIndexKey Get the validator owner address from ValBondedIndexKey func GetAddressFromValBondedIndexKey(IndexKey []byte) []byte { return IndexKey[1:] // remove prefix bytes } -// get the validator by power index. power index is the key used in the power-store, +// GetValidatorsByPowerIndexKey Get the validator by power index. power index is the key used in the power-store, // and represents the relative power ranking of the validator. // VALUE: validator owner address ([]byte) func GetValidatorsByPowerIndexKey(validator types.Validator, pool types.Pool) []byte { @@ -65,7 +65,7 @@ func GetValidatorsByPowerIndexKey(validator types.Validator, pool types.Pool) [] return getValidatorPowerRank(validator, pool) } -// get the power ranking of a validator +// getValidatorPowerRank Get the power ranking of a validator // NOTE the larger values are of higher value func getValidatorPowerRank(validator types.Validator, pool types.Pool) []byte { @@ -93,7 +93,7 @@ func getValidatorPowerRank(validator types.Validator, pool types.Pool) []byte { counterBytes...) } -// get the key for the accumulated update validators. +// GetTendermintUpdatesKey Get the key for the accumulated update validators. // VALUE: abci.Validator // note records using these keys should never persist between blocks func GetTendermintUpdatesKey(ownerAddr sdk.AccAddress) []byte { @@ -102,20 +102,20 @@ func GetTendermintUpdatesKey(ownerAddr sdk.AccAddress) []byte { //________________________________________________________________________________ -// get the key for delegator bond with validator. +// GetDelegationKey Gets the key for delegator bond with validator. // VALUE: stake/types.Delegation func GetDelegationKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { return append(GetDelegationsKey(delegatorAddr), validatorAddr.Bytes()...) } -// get the prefix for a delegator for all validators +// GetDelegationsKey Gets the prefix for a delegator for all validators func GetDelegationsKey(delegatorAddr sdk.AccAddress) []byte { return append(DelegationKey, delegatorAddr.Bytes()...) } //________________________________________________________________________________ -// get the key for an unbonding delegation by delegator and validator addr. +// GetUBDKey Gets the key for an unbonding delegation by delegator and validator addr. // VALUE: stake/types.UnbondingDelegation func GetUBDKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { return append( @@ -123,13 +123,13 @@ func GetUBDKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { validatorAddr.Bytes()...) } -// get the index-key for an unbonding delegation, stored by validator-index +// GetUBDByValIndexKey Gets the index-key for an unbonding delegation, stored by validator-index // VALUE: none (key rearrangement used) func GetUBDByValIndexKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { return append(GetUBDsByValIndexKey(validatorAddr), delegatorAddr.Bytes()...) } -// rearrange the ValIndexKey to get the UBDKey +// GetUBDKeyFromValIndexKey Rearranges the ValIndexKey to get the UBDKey func GetUBDKeyFromValIndexKey(IndexKey []byte) []byte { addrs := IndexKey[1:] // remove prefix bytes if len(addrs) != 2*sdk.AddrLen { @@ -142,19 +142,19 @@ func GetUBDKeyFromValIndexKey(IndexKey []byte) []byte { //______________ -// get the prefix for all unbonding delegations from a delegator +// GetUBDsKey Gets the prefix for all unbonding delegations from a delegator func GetUBDsKey(delegatorAddr sdk.AccAddress) []byte { return append(UnbondingDelegationKey, delegatorAddr.Bytes()...) } -// get the prefix keyspace for the indexes of unbonding delegations for a validator +// GetUBDsByValIndexKey Gets the prefix keyspace for the indexes of unbonding delegations for a validator func GetUBDsByValIndexKey(validatorAddr sdk.AccAddress) []byte { return append(UnbondingDelegationByValIndexKey, validatorAddr.Bytes()...) } //________________________________________________________________________________ -// get the key for a redelegation +// GetREDKey Gets the key for a redelegation // VALUE: stake/types.RedelegationKey func GetREDKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { return append(append( @@ -163,7 +163,7 @@ func GetREDKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) validatorDstAddr.Bytes()...) } -// get the index-key for a redelegation, stored by source-validator-index +// GetREDByValSrcIndexKey Gets the index-key for a redelegation, stored by source-validator-index // VALUE: none (key rearrangement used) func GetREDByValSrcIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { return append(append( @@ -172,7 +172,7 @@ func GetREDByValSrcIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sd validatorDstAddr.Bytes()...) } -// get the index-key for a redelegation, stored by destination-validator-index +// GetREDByValDstIndexKey Gets the index-key for a redelegation, stored by destination-validator-index // VALUE: none (key rearrangement used) func GetREDByValDstIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { return append(append( @@ -181,7 +181,7 @@ func GetREDByValDstIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sd validatorSrcAddr.Bytes()...) } -// rearrange the ValSrcIndexKey to get the REDKey +// GetREDKeyFromValSrcIndexKey Rearranges the ValSrcIndexKey to get the REDKey func GetREDKeyFromValSrcIndexKey(IndexKey []byte) []byte { addrs := IndexKey[1:] // remove prefix bytes if len(addrs) != 3*sdk.AddrLen { @@ -194,7 +194,7 @@ func GetREDKeyFromValSrcIndexKey(IndexKey []byte) []byte { return GetREDKey(delAddr, valSrcAddr, valDstAddr) } -// rearrange the ValDstIndexKey to get the REDKey +// GetREDKeyFromValDstIndexKey Rearranges the ValDstIndexKey to get the REDKey func GetREDKeyFromValDstIndexKey(IndexKey []byte) []byte { addrs := IndexKey[1:] // remove prefix bytes if len(addrs) != 3*sdk.AddrLen { @@ -208,33 +208,25 @@ func GetREDKeyFromValDstIndexKey(IndexKey []byte) []byte { //______________ -// get the prefix keyspace for redelegations from a delegator +// GetREDsKey Gets the prefix keyspace for redelegations from a delegator func GetREDsKey(delegatorAddr sdk.AccAddress) []byte { return append(RedelegationKey, delegatorAddr.Bytes()...) } -// get the prefix keyspace for all redelegations redelegating away from a source validator +// GetREDsFromValSrcIndexKey Gets the prefix keyspace for all redelegations redelegating away from a source validator func GetREDsFromValSrcIndexKey(validatorSrcAddr sdk.AccAddress) []byte { return append(RedelegationByValSrcIndexKey, validatorSrcAddr.Bytes()...) } -// get the prefix keyspace for all redelegations redelegating towards a destination validator +// GetREDsToValDstIndexKey Gets the prefix keyspace for all redelegations redelegating towards a destination validator func GetREDsToValDstIndexKey(validatorDstAddr sdk.AccAddress) []byte { return append(RedelegationByValDstIndexKey, validatorDstAddr.Bytes()...) } -// get the prefix keyspace for all redelegations redelegating towards a destination validator +// GetREDsByDelToValDstIndexKey Gets the prefix keyspace for all redelegations redelegating towards a destination validator // from a particular delegator func GetREDsByDelToValDstIndexKey(delegatorAddr, validatorDstAddr sdk.AccAddress) []byte { return append( GetREDsToValDstIndexKey(validatorDstAddr), delegatorAddr.Bytes()...) } - -// get the prefix keyspace for all redelegations redelegating from a source validator -// from a particular delegator -func GetREDsByDelFromValSrcIndexKey(delegatorAddr, validatorSrcAddr sdk.AccAddress) []byte { - return append( - GetREDsFromValSrcIndexKey(validatorSrcAddr), - delegatorAddr.Bytes()...) -} From 14ec6253b6dbdeb316a2d301d5791b959a9551dd Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 1 Aug 2018 18:17:38 +0200 Subject: [PATCH 29/46] Refactor handlers with util funcs --- x/stake/client/rest/query.go | 66 ++++++------------------------- x/stake/client/rest/utils.go | 75 +++++++++++++++++++++++++++++++++++- 2 files changed, 85 insertions(+), 56 deletions(-) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 573ca168ff7a..34721616be5f 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -144,75 +144,33 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu validatorAddr = validator.Owner // Delegations - delegationKey := stake.GetDelegationKey(delegatorAddr, validatorAddr) - marshalledDelegation, err := ctx.QueryStore(delegationKey, storeName) + delegations, statusCode, errMsg, err := getDelegatorDelegations(ctx, cdc, delegatorAddr, validatorAddr) if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + w.WriteHeader(statusCode) + w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) return } - - // the query will return empty if there is no data for this record - if len(marshalledDelegation) != 0 { - delegation, errUnmarshal := types.UnmarshalDelegation(cdc, delegationKey, marshalledDelegation) - if errUnmarshal != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't unmarshall unbonding-delegation. Error: %s", err.Error()))) - return - } - - outputDelegation := DelegationWithoutRat{ - DelegatorAddr: delegation.DelegatorAddr, - ValidatorAddr: delegation.ValidatorAddr, - Height: delegation.Height, - Shares: delegation.Shares.FloatString(), - } - - delegationSummary.Delegations = append(delegationSummary.Delegations, outputDelegation) - } + delegationSummary.Delegations = append(delegationSummary.Delegations, delegations) // Undelegations - undelegationKey := stake.GetUBDKey(delegatorAddr, validatorAddr) - marshalledUnbondingDelegation, err := ctx.QueryStore(undelegationKey, storeName) + unbondingDelegation, statusCode, errMsg, err := getDelegatorUndelegations(ctx, cdc, delegatorAddr, validatorAddr) if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) + w.WriteHeader(statusCode) + w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) return } - - // the query will return empty if there is no data for this record - if len(marshalledUnbondingDelegation) != 0 { - unbondingDelegation, errUnmarshal := types.UnmarshalUBD(cdc, undelegationKey, marshalledUnbondingDelegation) - if errUnmarshal != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't unmarshall unbonding-delegation. Error: %s", err.Error()))) - return - } - - delegationSummary.UnbondingDelegations = append(delegationSummary.UnbondingDelegations, unbondingDelegation) - } + delegationSummary.UnbondingDelegations = append(delegationSummary.UnbondingDelegations, unbondingDelegation) // Redelegations // only querying redelegations to a validator as this should give us already all relegations // if we also would put in redelegations from, we would have every redelegation double - keyRedelegateTo := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) - marshalledRedelegations, err := ctx.QueryStore(keyRedelegateTo, storeName) + redelegations, statusCode, errMsg, err := getDelegatorRedelegations(ctx, cdc, delegatorAddr, validatorAddr) if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query redelegation. Error: %s", err.Error()))) + w.WriteHeader(statusCode) + w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) return } - - if len(marshalledRedelegations) != 0 { - redelegations, errUnmarshal := types.UnmarshalRED(cdc, keyRedelegateTo, marshalledRedelegations) - if errUnmarshal != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't unmarshall redelegations. Error: %s", err.Error()))) - return - } - - delegationSummary.Redelegations = append(delegationSummary.Redelegations, redelegations) - } + delegationSummary.Redelegations = append(delegationSummary.Redelegations, redelegations) output, err := cdc.MarshalJSON(delegationSummary) if err != nil { diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 5419e6cb1108..82966570c34d 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -3,8 +3,10 @@ package rest import ( "bytes" "fmt" + "net/http" "reflect" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" @@ -25,7 +27,76 @@ func contains(stringSlice []string, txType string) bool { return false } -// Query staking txs +func getDelegatorDelegations(ctx context.CoreContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( + outputDelegation DelegationWithoutRat, httpStatusCode int, errMsg string, err error, +) { + delegationKey := stake.GetDelegationKey(delegatorAddr, validatorAddr) + marshalledDelegation, err := ctx.QueryStore(delegationKey, storeName) + if err != nil { + return DelegationWithoutRat{}, http.StatusInternalServerError, "couldn't query delegation. Error: ", err + } + + // the query will return empty if there is no data for this record + if len(marshalledDelegation) != 0 { + delegation, errUnmarshal := types.UnmarshalDelegation(cdc, delegationKey, marshalledDelegation) + if errUnmarshal != nil { + return DelegationWithoutRat{}, http.StatusInternalServerError, "couldn't unmarshall delegation. Error: ", errUnmarshal + } + + outputDelegation := DelegationWithoutRat{ + DelegatorAddr: delegation.DelegatorAddr, + ValidatorAddr: delegation.ValidatorAddr, + Height: delegation.Height, + Shares: delegation.Shares.FloatString(), + } + + return outputDelegation, 0, "", nil + } + return DelegationWithoutRat{}, http.StatusNoContent, "", nil +} + +func getDelegatorUndelegations(ctx context.CoreContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( + unbonds types.UnbondingDelegation, httpStatusCode int, errMsg string, err error, +) { + undelegationKey := stake.GetUBDKey(delegatorAddr, validatorAddr) + marshalledUnbondingDelegation, err := ctx.QueryStore(undelegationKey, storeName) + if err != nil { + return types.UnbondingDelegation{}, http.StatusInternalServerError, "couldn't query unbonding-delegation. Error: ", err + } + + // the query will return empty if there is no data for this record + if len(marshalledUnbondingDelegation) != 0 { + unbondingDelegation, errUnmarshal := types.UnmarshalUBD(cdc, undelegationKey, marshalledUnbondingDelegation) + if errUnmarshal != nil { + return types.UnbondingDelegation{}, http.StatusInternalServerError, "couldn't unmarshall unbonding-delegation. Error: ", errUnmarshal + } + return unbondingDelegation, 0, "", nil + } + return types.UnbondingDelegation{}, http.StatusNoContent, "", nil +} + +func getDelegatorRedelegations(ctx context.CoreContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( + regelegations types.Redelegation, httpStatusCode int, errMsg string, err error, +) { + + keyRedelegateTo := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) + marshalledRedelegations, err := ctx.QueryStore(keyRedelegateTo, storeName) + if err != nil { + return types.Redelegation{}, http.StatusInternalServerError, "couldn't query redelegation. Error: ", err + } + + if len(marshalledRedelegations) != 0 { + redelegations, errUnmarshal := types.UnmarshalRED(cdc, keyRedelegateTo, marshalledRedelegations) + if errUnmarshal != nil { + return types.Redelegation{}, http.StatusInternalServerError, "couldn't unmarshall redelegations. Error: ", errUnmarshal + } + + return redelegations, 0, "", nil + } + return types.Redelegation{}, http.StatusNoContent, "", nil +} + +// queryTxs Queries staking txs func queryTxs(node rpcclient.Client, cdc *wire.Codec, tag string, delegatorAddr string) ([]tx.Info, error) { page := 0 perPage := 100 @@ -39,7 +110,7 @@ func queryTxs(node rpcclient.Client, cdc *wire.Codec, tag string, delegatorAddr return tx.FormatTxResults(cdc, res.Txs) } -// get all Validators +// getValidators Gets all Validators func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechValidator, error) { validators := make([]types.BechValidator, len(validatorKVs)) for i, kv := range validatorKVs { From a7884db22af0fe3d9f96f76c9d6c3fcf3a03f32f Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 1 Aug 2018 18:52:24 +0200 Subject: [PATCH 30/46] More refactoring on handlers --- x/stake/client/rest/query.go | 85 ++++++++---------------------------- x/stake/client/rest/utils.go | 47 ++++++++++++++++---- 2 files changed, 57 insertions(+), 75 deletions(-) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 34721616be5f..1316693eba29 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -428,40 +428,16 @@ func delegatorValidatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http // get all transactions from the delegator to val and append validatorAccAddr = validator.Owner - // Check if the delegator is bonded or redelegated to the validator - keyDel := stake.GetDelegationKey(delegatorAddr, validatorAccAddr) - // keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAccAddr) - - res, errQuery := ctx.QueryStore(keyDel, storeName) - if errQuery != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", errQuery.Error()))) + validator, statusCode, errMsg, errRes := getDelegatorValidator(ctx, cdc, delegatorAddr, validatorAccAddr) + if errRes != nil { + w.WriteHeader(statusCode) + w.Write([]byte(fmt.Sprintf("%s%s", errMsg, errRes.Error()))) return + } else if statusCode == http.StatusNoContent { + continue } - if len(res) != 0 { - kvs, errQuery := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) - if errQuery != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Error: %s", errQuery.Error()))) - return - } else if len(kvs) == 0 { - // the query will return empty if there are no delegations - continue - } - - validator, errVal := getValidatorFromAccAdrr(validatorAccAddr, kvs, cdc) - if errVal != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't get info from validator %s. Error: %s", validatorAccAddr.String(), errVal.Error()))) - return - } - bondedValidators = append(bondedValidators, validator) - } else { - // delegator is not bonded to any delegator - w.WriteHeader(http.StatusNoContent) - return - } + bondedValidators = append(bondedValidators, validator) } // success output, err := cdc.MarshalJSON(bondedValidators) @@ -485,7 +461,7 @@ func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http. delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) validatorAccAddr, err := sdk.AccAddressFromBech32(bech32validator) - validatorValAddress, err := sdk.ValAddressFromBech32(bech32validator) + // validatorValAddress, err := sdk.ValAddressFromBech32(bech32validator) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) @@ -494,43 +470,20 @@ func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http. // Check if there if the delegator is bonded or redelegated to the validator - keyDel := stake.GetDelegationKey(delegatorAddr, validatorAccAddr) - // keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAccAddr) - - res, err := ctx.QueryStore(keyDel, storeName) + validator, statusCode, errMsg, err := getDelegatorValidator(ctx, cdc, delegatorAddr, validatorAccAddr) if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) + w.WriteHeader(statusCode) + w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) + return + } else if statusCode == http.StatusNoContent { + w.WriteHeader(statusCode) return } - // if delegator delegations - if len(res) != 0 { - kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) - return - } else if len(kvs) == 0 { - // the query will return empty if there are no delegations - w.WriteHeader(http.StatusNoContent) - return - } - validator, err := getValidator(validatorValAddress, kvs, cdc) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't get info from validator %s. Error: %s", validatorValAddress.String(), err.Error()))) - return - } - // success - output, err = cdc.MarshalJSON(validator) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - } else { - // delegator is not bonded to any delegator - w.WriteHeader(http.StatusNoContent) + // success + output, err = cdc.MarshalJSON(validator) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) return } w.Write(output) diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 82966570c34d..8387e9712089 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -27,9 +27,40 @@ func contains(stringSlice []string, txType string) bool { return false } +func getDelegatorValidator(ctx context.CoreContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAccAddr sdk.AccAddress) ( + validator types.BechValidator, httpStatusCode int, errMsg string, err error) { + + // Check if the delegator is bonded or redelegated to the validator + keyDel := stake.GetDelegationKey(delegatorAddr, validatorAccAddr) + // keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAccAddr) + + res, err := ctx.QueryStore(keyDel, storeName) + if err != nil { + return types.BechValidator{}, http.StatusInternalServerError, "couldn't query delegation. Error: ", err + } + + if len(res) != 0 { + kvs, errQuery := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + if errQuery != nil { + return types.BechValidator{}, http.StatusInternalServerError, "Error: ", err + } + if len(kvs) == 0 { + // the query will return empty if there are no delegations + return types.BechValidator{}, http.StatusNoContent, "", nil + } + + validator, errVal := getValidatorFromAccAdrr(validatorAccAddr, kvs, cdc) + if errVal != nil { + return types.BechValidator{}, http.StatusInternalServerError, "Couldn't get info from validator. Error: ", errVal + } + return validator, http.StatusOK, "", nil + + } + return types.BechValidator{}, http.StatusNoContent, "", nil +} + func getDelegatorDelegations(ctx context.CoreContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( - outputDelegation DelegationWithoutRat, httpStatusCode int, errMsg string, err error, -) { + outputDelegation DelegationWithoutRat, httpStatusCode int, errMsg string, err error) { delegationKey := stake.GetDelegationKey(delegatorAddr, validatorAddr) marshalledDelegation, err := ctx.QueryStore(delegationKey, storeName) if err != nil { @@ -50,14 +81,13 @@ func getDelegatorDelegations(ctx context.CoreContext, cdc *wire.Codec, delegator Shares: delegation.Shares.FloatString(), } - return outputDelegation, 0, "", nil + return outputDelegation, http.StatusOK, "", nil } return DelegationWithoutRat{}, http.StatusNoContent, "", nil } func getDelegatorUndelegations(ctx context.CoreContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( - unbonds types.UnbondingDelegation, httpStatusCode int, errMsg string, err error, -) { + unbonds types.UnbondingDelegation, httpStatusCode int, errMsg string, err error) { undelegationKey := stake.GetUBDKey(delegatorAddr, validatorAddr) marshalledUnbondingDelegation, err := ctx.QueryStore(undelegationKey, storeName) if err != nil { @@ -70,14 +100,13 @@ func getDelegatorUndelegations(ctx context.CoreContext, cdc *wire.Codec, delegat if errUnmarshal != nil { return types.UnbondingDelegation{}, http.StatusInternalServerError, "couldn't unmarshall unbonding-delegation. Error: ", errUnmarshal } - return unbondingDelegation, 0, "", nil + return unbondingDelegation, http.StatusOK, "", nil } return types.UnbondingDelegation{}, http.StatusNoContent, "", nil } func getDelegatorRedelegations(ctx context.CoreContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( - regelegations types.Redelegation, httpStatusCode int, errMsg string, err error, -) { + regelegations types.Redelegation, httpStatusCode int, errMsg string, err error) { keyRedelegateTo := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) marshalledRedelegations, err := ctx.QueryStore(keyRedelegateTo, storeName) @@ -91,7 +120,7 @@ func getDelegatorRedelegations(ctx context.CoreContext, cdc *wire.Codec, delegat return types.Redelegation{}, http.StatusInternalServerError, "couldn't unmarshall redelegations. Error: ", errUnmarshal } - return redelegations, 0, "", nil + return redelegations, http.StatusOK, "", nil } return types.Redelegation{}, http.StatusNoContent, "", nil } From 120be9c972b75eb3733df8435dd9219e11f09805 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 1 Aug 2018 20:06:21 +0200 Subject: [PATCH 31/46] minor fix --- x/stake/client/rest/utils.go | 3 +- x/stake/keeper/key.go | 54 +++++++++++++++++++++--------------- 2 files changed, 33 insertions(+), 24 deletions(-) diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 8387e9712089..b3081859cc25 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "net/http" - "reflect" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/tx" @@ -170,7 +169,7 @@ func getValidator(address sdk.ValAddress, validatorKVs []sdk.KVPair, cdc *wire.C } ownerAddress := validator.PubKey.Address() - if reflect.DeepEqual(ownerAddress.Bytes(), address.Bytes()) { + if bytes.Equal(ownerAddress.Bytes(), address.Bytes()) { bech32Validator, err := validator.Bech32Validator() if err != nil { return stake.BechValidator{}, err diff --git a/x/stake/keeper/key.go b/x/stake/keeper/key.go index 74fc02f090c8..dd0e61808aff 100644 --- a/x/stake/keeper/key.go +++ b/x/stake/keeper/key.go @@ -46,26 +46,28 @@ func GetValidatorByPubKeyIndexKey(pubkey crypto.PubKey) []byte { return append(ValidatorsByPubKeyIndexKey, pubkey.Bytes()...) } -// GetValidatorsBondedIndexKey Gets the key for the current validator group +// GetValidatorsBondedIndexKey Gets the key for the current validator group. // VALUE: none (key rearrangement with GetValKeyFromValBondedIndexKey) func GetValidatorsBondedIndexKey(ownerAddr sdk.AccAddress) []byte { return append(ValidatorsBondedIndexKey, ownerAddr.Bytes()...) } -// GetAddressFromValBondedIndexKey Get the validator owner address from ValBondedIndexKey +// GetAddressFromValBondedIndexKey Get the validator owner address. +// from ValBondedIndexKey func GetAddressFromValBondedIndexKey(IndexKey []byte) []byte { return IndexKey[1:] // remove prefix bytes } -// GetValidatorsByPowerIndexKey Get the validator by power index. power index is the key used in the power-store, -// and represents the relative power ranking of the validator. +// GetValidatorsByPowerIndexKey Get the validator by power index. +// Power index is the key used in the power-store, and represents the relative +// power ranking of the validator. // VALUE: validator owner address ([]byte) func GetValidatorsByPowerIndexKey(validator types.Validator, pool types.Pool) []byte { // NOTE the address doesn't need to be stored because counter bytes must always be different return getValidatorPowerRank(validator, pool) } -// getValidatorPowerRank Get the power ranking of a validator +// getValidatorPowerRank Get the power ranking of a validator. // NOTE the larger values are of higher value func getValidatorPowerRank(validator types.Validator, pool types.Pool) []byte { @@ -100,7 +102,7 @@ func GetTendermintUpdatesKey(ownerAddr sdk.AccAddress) []byte { return append(TendermintUpdatesKey, ownerAddr.Bytes()...) } -//________________________________________________________________________________ +//______________________________________________________________________________ // GetDelegationKey Gets the key for delegator bond with validator. // VALUE: stake/types.Delegation @@ -108,14 +110,15 @@ func GetDelegationKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { return append(GetDelegationsKey(delegatorAddr), validatorAddr.Bytes()...) } -// GetDelegationsKey Gets the prefix for a delegator for all validators +// GetDelegationsKey Gets the prefix for a delegator for all validators. func GetDelegationsKey(delegatorAddr sdk.AccAddress) []byte { return append(DelegationKey, delegatorAddr.Bytes()...) } -//________________________________________________________________________________ +//______________________________________________________________________________ -// GetUBDKey Gets the key for an unbonding delegation by delegator and validator addr. +// GetUBDKey Gets the key for an unbonding delegation by delegator and validator +// addr. // VALUE: stake/types.UnbondingDelegation func GetUBDKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { return append( @@ -123,13 +126,14 @@ func GetUBDKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { validatorAddr.Bytes()...) } -// GetUBDByValIndexKey Gets the index-key for an unbonding delegation, stored by validator-index +// GetUBDByValIndexKey Gets the index-key for an unbonding delegation, stored by +// validator-index. // VALUE: none (key rearrangement used) func GetUBDByValIndexKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { return append(GetUBDsByValIndexKey(validatorAddr), delegatorAddr.Bytes()...) } -// GetUBDKeyFromValIndexKey Rearranges the ValIndexKey to get the UBDKey +// GetUBDKeyFromValIndexKey Rearranges the ValIndexKey to get the UBDKey. func GetUBDKeyFromValIndexKey(IndexKey []byte) []byte { addrs := IndexKey[1:] // remove prefix bytes if len(addrs) != 2*sdk.AddrLen { @@ -142,19 +146,20 @@ func GetUBDKeyFromValIndexKey(IndexKey []byte) []byte { //______________ -// GetUBDsKey Gets the prefix for all unbonding delegations from a delegator +// GetUBDsKey Gets the prefix for all unbonding delegations from a delegator. func GetUBDsKey(delegatorAddr sdk.AccAddress) []byte { return append(UnbondingDelegationKey, delegatorAddr.Bytes()...) } -// GetUBDsByValIndexKey Gets the prefix keyspace for the indexes of unbonding delegations for a validator +// GetUBDsByValIndexKey Gets the prefix keyspace for the indexes of unbonding +// delegations for a validator. func GetUBDsByValIndexKey(validatorAddr sdk.AccAddress) []byte { return append(UnbondingDelegationByValIndexKey, validatorAddr.Bytes()...) } //________________________________________________________________________________ -// GetREDKey Gets the key for a redelegation +// GetREDKey Gets the key for a redelegation. // VALUE: stake/types.RedelegationKey func GetREDKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { return append(append( @@ -163,7 +168,8 @@ func GetREDKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) validatorDstAddr.Bytes()...) } -// GetREDByValSrcIndexKey Gets the index-key for a redelegation, stored by source-validator-index +// GetREDByValSrcIndexKey Gets the index-key for a redelegation, stored by +// source-validator-index. // VALUE: none (key rearrangement used) func GetREDByValSrcIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { return append(append( @@ -172,7 +178,8 @@ func GetREDByValSrcIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sd validatorDstAddr.Bytes()...) } -// GetREDByValDstIndexKey Gets the index-key for a redelegation, stored by destination-validator-index +// GetREDByValDstIndexKey Gets the index-key for a redelegation, stored by +// destination-validator-index. // VALUE: none (key rearrangement used) func GetREDByValDstIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { return append(append( @@ -181,7 +188,7 @@ func GetREDByValDstIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sd validatorSrcAddr.Bytes()...) } -// GetREDKeyFromValSrcIndexKey Rearranges the ValSrcIndexKey to get the REDKey +// GetREDKeyFromValSrcIndexKey Rearranges the ValSrcIndexKey to get the REDKey. func GetREDKeyFromValSrcIndexKey(IndexKey []byte) []byte { addrs := IndexKey[1:] // remove prefix bytes if len(addrs) != 3*sdk.AddrLen { @@ -194,7 +201,7 @@ func GetREDKeyFromValSrcIndexKey(IndexKey []byte) []byte { return GetREDKey(delAddr, valSrcAddr, valDstAddr) } -// GetREDKeyFromValDstIndexKey Rearranges the ValDstIndexKey to get the REDKey +// GetREDKeyFromValDstIndexKey Rearranges the ValDstIndexKey to get the REDKey. func GetREDKeyFromValDstIndexKey(IndexKey []byte) []byte { addrs := IndexKey[1:] // remove prefix bytes if len(addrs) != 3*sdk.AddrLen { @@ -208,22 +215,25 @@ func GetREDKeyFromValDstIndexKey(IndexKey []byte) []byte { //______________ -// GetREDsKey Gets the prefix keyspace for redelegations from a delegator +// GetREDsKey Gets the prefix keyspace for redelegations from a delegator. func GetREDsKey(delegatorAddr sdk.AccAddress) []byte { return append(RedelegationKey, delegatorAddr.Bytes()...) } -// GetREDsFromValSrcIndexKey Gets the prefix keyspace for all redelegations redelegating away from a source validator +// GetREDsFromValSrcIndexKey Gets the prefix keyspace for all redelegations +// redelegating away from a source validator. func GetREDsFromValSrcIndexKey(validatorSrcAddr sdk.AccAddress) []byte { return append(RedelegationByValSrcIndexKey, validatorSrcAddr.Bytes()...) } -// GetREDsToValDstIndexKey Gets the prefix keyspace for all redelegations redelegating towards a destination validator +// GetREDsToValDstIndexKey Gets the prefix keyspace for all redelegations +// redelegating towards a destination validator. func GetREDsToValDstIndexKey(validatorDstAddr sdk.AccAddress) []byte { return append(RedelegationByValDstIndexKey, validatorDstAddr.Bytes()...) } -// GetREDsByDelToValDstIndexKey Gets the prefix keyspace for all redelegations redelegating towards a destination validator +// GetREDsByDelToValDstIndexKey Gets the prefix keyspace for all redelegations +// redelegating towards a destination validator. // from a particular delegator func GetREDsByDelToValDstIndexKey(delegatorAddr, validatorDstAddr sdk.AccAddress) []byte { return append( From e2064a4df756d5dd2a2178b35f1ad28de0467513 Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Thu, 2 Aug 2018 10:50:43 +0200 Subject: [PATCH 32/46] addresses comments --- x/stake/client/rest/utils.go | 87 +++++++++++++++++++----------------- x/stake/keeper/key.go | 57 ++++++++++------------- 2 files changed, 69 insertions(+), 75 deletions(-) diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index b3081859cc25..768d7f092c08 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -38,24 +38,24 @@ func getDelegatorValidator(ctx context.CoreContext, cdc *wire.Codec, delegatorAd return types.BechValidator{}, http.StatusInternalServerError, "couldn't query delegation. Error: ", err } - if len(res) != 0 { - kvs, errQuery := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) - if errQuery != nil { - return types.BechValidator{}, http.StatusInternalServerError, "Error: ", err - } - if len(kvs) == 0 { - // the query will return empty if there are no delegations - return types.BechValidator{}, http.StatusNoContent, "", nil - } + if len(res) == 0 { + return types.BechValidator{}, http.StatusNoContent, "", nil + } - validator, errVal := getValidatorFromAccAdrr(validatorAccAddr, kvs, cdc) - if errVal != nil { - return types.BechValidator{}, http.StatusInternalServerError, "Couldn't get info from validator. Error: ", errVal - } - return validator, http.StatusOK, "", nil + kvs, errQuery := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + if errQuery != nil { + return types.BechValidator{}, http.StatusInternalServerError, "Error: ", err + } + if len(kvs) == 0 { + // the query will return empty if there are no delegations + return types.BechValidator{}, http.StatusNoContent, "", nil + } + validator, errVal := getValidatorFromAccAdrr(validatorAccAddr, kvs, cdc) + if errVal != nil { + return types.BechValidator{}, http.StatusInternalServerError, "Couldn't get info from validator. Error: ", errVal } - return types.BechValidator{}, http.StatusNoContent, "", nil + return validator, http.StatusOK, "", nil } func getDelegatorDelegations(ctx context.CoreContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( @@ -67,22 +67,23 @@ func getDelegatorDelegations(ctx context.CoreContext, cdc *wire.Codec, delegator } // the query will return empty if there is no data for this record - if len(marshalledDelegation) != 0 { - delegation, errUnmarshal := types.UnmarshalDelegation(cdc, delegationKey, marshalledDelegation) - if errUnmarshal != nil { - return DelegationWithoutRat{}, http.StatusInternalServerError, "couldn't unmarshall delegation. Error: ", errUnmarshal - } + if len(marshalledDelegation) == 0 { + return DelegationWithoutRat{}, http.StatusNoContent, "", nil + } - outputDelegation := DelegationWithoutRat{ - DelegatorAddr: delegation.DelegatorAddr, - ValidatorAddr: delegation.ValidatorAddr, - Height: delegation.Height, - Shares: delegation.Shares.FloatString(), - } + delegation, errUnmarshal := types.UnmarshalDelegation(cdc, delegationKey, marshalledDelegation) + if errUnmarshal != nil { + return DelegationWithoutRat{}, http.StatusInternalServerError, "couldn't unmarshall delegation. Error: ", errUnmarshal + } - return outputDelegation, http.StatusOK, "", nil + outputDelegation = DelegationWithoutRat{ + DelegatorAddr: delegation.DelegatorAddr, + ValidatorAddr: delegation.ValidatorAddr, + Height: delegation.Height, + Shares: delegation.Shares.FloatString(), } - return DelegationWithoutRat{}, http.StatusNoContent, "", nil + + return outputDelegation, http.StatusOK, "", nil } func getDelegatorUndelegations(ctx context.CoreContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( @@ -94,14 +95,15 @@ func getDelegatorUndelegations(ctx context.CoreContext, cdc *wire.Codec, delegat } // the query will return empty if there is no data for this record - if len(marshalledUnbondingDelegation) != 0 { - unbondingDelegation, errUnmarshal := types.UnmarshalUBD(cdc, undelegationKey, marshalledUnbondingDelegation) - if errUnmarshal != nil { - return types.UnbondingDelegation{}, http.StatusInternalServerError, "couldn't unmarshall unbonding-delegation. Error: ", errUnmarshal - } - return unbondingDelegation, http.StatusOK, "", nil + if len(marshalledUnbondingDelegation) == 0 { + return types.UnbondingDelegation{}, http.StatusNoContent, "", nil + } + + unbondingDelegation, errUnmarshal := types.UnmarshalUBD(cdc, undelegationKey, marshalledUnbondingDelegation) + if errUnmarshal != nil { + return types.UnbondingDelegation{}, http.StatusInternalServerError, "couldn't unmarshall unbonding-delegation. Error: ", errUnmarshal } - return types.UnbondingDelegation{}, http.StatusNoContent, "", nil + return unbondingDelegation, http.StatusOK, "", nil } func getDelegatorRedelegations(ctx context.CoreContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( @@ -113,15 +115,16 @@ func getDelegatorRedelegations(ctx context.CoreContext, cdc *wire.Codec, delegat return types.Redelegation{}, http.StatusInternalServerError, "couldn't query redelegation. Error: ", err } - if len(marshalledRedelegations) != 0 { - redelegations, errUnmarshal := types.UnmarshalRED(cdc, keyRedelegateTo, marshalledRedelegations) - if errUnmarshal != nil { - return types.Redelegation{}, http.StatusInternalServerError, "couldn't unmarshall redelegations. Error: ", errUnmarshal - } + if len(marshalledRedelegations) == 0 { + return types.Redelegation{}, http.StatusNoContent, "", nil + } - return redelegations, http.StatusOK, "", nil + redelegations, errUnmarshal := types.UnmarshalRED(cdc, keyRedelegateTo, marshalledRedelegations) + if errUnmarshal != nil { + return types.Redelegation{}, http.StatusInternalServerError, "couldn't unmarshall redelegations. Error: ", errUnmarshal } - return types.Redelegation{}, http.StatusNoContent, "", nil + + return redelegations, http.StatusOK, "", nil } // queryTxs Queries staking txs diff --git a/x/stake/keeper/key.go b/x/stake/keeper/key.go index dd0e61808aff..cf35742b9613 100644 --- a/x/stake/keeper/key.go +++ b/x/stake/keeper/key.go @@ -34,31 +34,30 @@ var ( const maxDigitsForAccount = 12 // ~220,000,000 atoms created at launch -// GetValidatorKey Gets the key for the validator with address. +// Gets the key for the validator with address. // VALUE: stake/types.Validator func GetValidatorKey(ownerAddr sdk.AccAddress) []byte { return append(ValidatorsKey, ownerAddr.Bytes()...) } -// GetValidatorByPubKeyIndexKey Gets the key for the validator with pubkey. +// Gets the key for the validator with pubkey. // VALUE: validator owner address ([]byte) func GetValidatorByPubKeyIndexKey(pubkey crypto.PubKey) []byte { return append(ValidatorsByPubKeyIndexKey, pubkey.Bytes()...) } -// GetValidatorsBondedIndexKey Gets the key for the current validator group. +// Gets the key for the current validator group. // VALUE: none (key rearrangement with GetValKeyFromValBondedIndexKey) func GetValidatorsBondedIndexKey(ownerAddr sdk.AccAddress) []byte { return append(ValidatorsBondedIndexKey, ownerAddr.Bytes()...) } -// GetAddressFromValBondedIndexKey Get the validator owner address. -// from ValBondedIndexKey +// Get the validator owner address from ValBondedIndexKey func GetAddressFromValBondedIndexKey(IndexKey []byte) []byte { return IndexKey[1:] // remove prefix bytes } -// GetValidatorsByPowerIndexKey Get the validator by power index. +// Get the validator by power index. // Power index is the key used in the power-store, and represents the relative // power ranking of the validator. // VALUE: validator owner address ([]byte) @@ -67,7 +66,7 @@ func GetValidatorsByPowerIndexKey(validator types.Validator, pool types.Pool) [] return getValidatorPowerRank(validator, pool) } -// getValidatorPowerRank Get the power ranking of a validator. +// Get the power ranking of a validator. // NOTE the larger values are of higher value func getValidatorPowerRank(validator types.Validator, pool types.Pool) []byte { @@ -95,7 +94,7 @@ func getValidatorPowerRank(validator types.Validator, pool types.Pool) []byte { counterBytes...) } -// GetTendermintUpdatesKey Get the key for the accumulated update validators. +// Get the key for the accumulated update validators. // VALUE: abci.Validator // note records using these keys should never persist between blocks func GetTendermintUpdatesKey(ownerAddr sdk.AccAddress) []byte { @@ -104,21 +103,20 @@ func GetTendermintUpdatesKey(ownerAddr sdk.AccAddress) []byte { //______________________________________________________________________________ -// GetDelegationKey Gets the key for delegator bond with validator. +// Gets the key for delegator bond with validator. // VALUE: stake/types.Delegation func GetDelegationKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { return append(GetDelegationsKey(delegatorAddr), validatorAddr.Bytes()...) } -// GetDelegationsKey Gets the prefix for a delegator for all validators. +// Gets the prefix for a delegator for all validators. func GetDelegationsKey(delegatorAddr sdk.AccAddress) []byte { return append(DelegationKey, delegatorAddr.Bytes()...) } //______________________________________________________________________________ -// GetUBDKey Gets the key for an unbonding delegation by delegator and validator -// addr. +// Gets the key for an unbonding delegation by delegator and validator addr. // VALUE: stake/types.UnbondingDelegation func GetUBDKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { return append( @@ -126,14 +124,13 @@ func GetUBDKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { validatorAddr.Bytes()...) } -// GetUBDByValIndexKey Gets the index-key for an unbonding delegation, stored by -// validator-index. +// Gets the index-key for an unbonding delegation, stored by validator-index. // VALUE: none (key rearrangement used) func GetUBDByValIndexKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { return append(GetUBDsByValIndexKey(validatorAddr), delegatorAddr.Bytes()...) } -// GetUBDKeyFromValIndexKey Rearranges the ValIndexKey to get the UBDKey. +// Rearranges the ValIndexKey to get the UBDKey. func GetUBDKeyFromValIndexKey(IndexKey []byte) []byte { addrs := IndexKey[1:] // remove prefix bytes if len(addrs) != 2*sdk.AddrLen { @@ -146,20 +143,19 @@ func GetUBDKeyFromValIndexKey(IndexKey []byte) []byte { //______________ -// GetUBDsKey Gets the prefix for all unbonding delegations from a delegator. +// Gets the prefix for all unbonding delegations from a delegator. func GetUBDsKey(delegatorAddr sdk.AccAddress) []byte { return append(UnbondingDelegationKey, delegatorAddr.Bytes()...) } -// GetUBDsByValIndexKey Gets the prefix keyspace for the indexes of unbonding -// delegations for a validator. +// Gets the prefix keyspace for the indexes of unbonding delegations for a validator. func GetUBDsByValIndexKey(validatorAddr sdk.AccAddress) []byte { return append(UnbondingDelegationByValIndexKey, validatorAddr.Bytes()...) } //________________________________________________________________________________ -// GetREDKey Gets the key for a redelegation. +// Gets the key for a redelegation. // VALUE: stake/types.RedelegationKey func GetREDKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { return append(append( @@ -168,8 +164,7 @@ func GetREDKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) validatorDstAddr.Bytes()...) } -// GetREDByValSrcIndexKey Gets the index-key for a redelegation, stored by -// source-validator-index. +// Gets the index-key for a redelegation, stored by source-validator-index. // VALUE: none (key rearrangement used) func GetREDByValSrcIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { return append(append( @@ -178,8 +173,7 @@ func GetREDByValSrcIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sd validatorDstAddr.Bytes()...) } -// GetREDByValDstIndexKey Gets the index-key for a redelegation, stored by -// destination-validator-index. +// Gets the index-key for a redelegation, stored by destination-validator-index. // VALUE: none (key rearrangement used) func GetREDByValDstIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { return append(append( @@ -188,7 +182,7 @@ func GetREDByValDstIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sd validatorSrcAddr.Bytes()...) } -// GetREDKeyFromValSrcIndexKey Rearranges the ValSrcIndexKey to get the REDKey. +// Rearranges the ValSrcIndexKey to get the REDKey. func GetREDKeyFromValSrcIndexKey(IndexKey []byte) []byte { addrs := IndexKey[1:] // remove prefix bytes if len(addrs) != 3*sdk.AddrLen { @@ -201,7 +195,7 @@ func GetREDKeyFromValSrcIndexKey(IndexKey []byte) []byte { return GetREDKey(delAddr, valSrcAddr, valDstAddr) } -// GetREDKeyFromValDstIndexKey Rearranges the ValDstIndexKey to get the REDKey. +// Rearranges the ValDstIndexKey to get the REDKey. func GetREDKeyFromValDstIndexKey(IndexKey []byte) []byte { addrs := IndexKey[1:] // remove prefix bytes if len(addrs) != 3*sdk.AddrLen { @@ -215,26 +209,23 @@ func GetREDKeyFromValDstIndexKey(IndexKey []byte) []byte { //______________ -// GetREDsKey Gets the prefix keyspace for redelegations from a delegator. +// Gets the prefix keyspace for redelegations from a delegator. func GetREDsKey(delegatorAddr sdk.AccAddress) []byte { return append(RedelegationKey, delegatorAddr.Bytes()...) } -// GetREDsFromValSrcIndexKey Gets the prefix keyspace for all redelegations -// redelegating away from a source validator. +// Gets the prefix keyspace for all redelegations redelegating away from a source validator. func GetREDsFromValSrcIndexKey(validatorSrcAddr sdk.AccAddress) []byte { return append(RedelegationByValSrcIndexKey, validatorSrcAddr.Bytes()...) } -// GetREDsToValDstIndexKey Gets the prefix keyspace for all redelegations -// redelegating towards a destination validator. +// Gets the prefix keyspace for all redelegations redelegating towards a destination validator. func GetREDsToValDstIndexKey(validatorDstAddr sdk.AccAddress) []byte { return append(RedelegationByValDstIndexKey, validatorDstAddr.Bytes()...) } -// GetREDsByDelToValDstIndexKey Gets the prefix keyspace for all redelegations -// redelegating towards a destination validator. -// from a particular delegator +// Gets the prefix keyspace for all redelegations redelegating towards a destination validator +// from a particular delegator. func GetREDsByDelToValDstIndexKey(delegatorAddr, validatorDstAddr sdk.AccAddress) []byte { return append( GetREDsToValDstIndexKey(validatorDstAddr), From 7722435d4faa18fe81353021d00e227a3e6ecdf3 Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Thu, 2 Aug 2018 16:24:21 +0200 Subject: [PATCH 33/46] added validator address to output --- x/stake/types/validator.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index 837b8f8e8a02..65b6ff21033e 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -178,6 +178,7 @@ func (v Validator) HumanReadableString() (string, error) { // validator struct for bech output type BechValidator struct { Owner sdk.AccAddress `json:"owner"` // in bech32 + Address sdk.ValAddress `json:"address"` // in bech32 PubKey string `json:"pub_key"` // in bech32 Revoked bool `json:"revoked"` // has the validator been revoked from bonded status? @@ -208,6 +209,7 @@ func (v Validator) Bech32Validator() (BechValidator, error) { return BechValidator{ Owner: v.Owner, + Address: sdk.ValAddress(v.PubKey.Address()), PubKey: bechValPubkey, Revoked: v.Revoked, From 9ee3d47dc63cadaa3a6a375542f05f396277e70d Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Thu, 2 Aug 2018 16:24:21 +0200 Subject: [PATCH 34/46] Revert "added validator address to output" This reverts commit 7722435d4faa18fe81353021d00e227a3e6ecdf3. --- x/stake/types/validator.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index 65b6ff21033e..837b8f8e8a02 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -178,7 +178,6 @@ func (v Validator) HumanReadableString() (string, error) { // validator struct for bech output type BechValidator struct { Owner sdk.AccAddress `json:"owner"` // in bech32 - Address sdk.ValAddress `json:"address"` // in bech32 PubKey string `json:"pub_key"` // in bech32 Revoked bool `json:"revoked"` // has the validator been revoked from bonded status? @@ -209,7 +208,6 @@ func (v Validator) Bech32Validator() (BechValidator, error) { return BechValidator{ Owner: v.Owner, - Address: sdk.ValAddress(v.PubKey.Address()), PubKey: bechValPubkey, Revoked: v.Revoked, From c68308978523a6cf41a2e1cf3daf40196a880eed Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Thu, 2 Aug 2018 18:33:14 +0200 Subject: [PATCH 35/46] do not add empty delegations et al --- x/stake/client/rest/query.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 1316693eba29..0235b967f985 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -150,7 +150,9 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) return } - delegationSummary.Delegations = append(delegationSummary.Delegations, delegations) + if statusCode != http.StatusNoContent { + delegationSummary.Delegations = append(delegationSummary.Delegations, delegations) + } // Undelegations unbondingDelegation, statusCode, errMsg, err := getDelegatorUndelegations(ctx, cdc, delegatorAddr, validatorAddr) @@ -159,7 +161,9 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) return } - delegationSummary.UnbondingDelegations = append(delegationSummary.UnbondingDelegations, unbondingDelegation) + if statusCode != http.StatusNoContent { + delegationSummary.UnbondingDelegations = append(delegationSummary.UnbondingDelegations, unbondingDelegation) + } // Redelegations // only querying redelegations to a validator as this should give us already all relegations @@ -170,7 +174,9 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) return } - delegationSummary.Redelegations = append(delegationSummary.Redelegations, redelegations) + if statusCode != http.StatusNoContent { + delegationSummary.Redelegations = append(delegationSummary.Redelegations, redelegations) + } output, err := cdc.MarshalJSON(delegationSummary) if err != nil { From 43f3ca81eb8c9adc3eef3fb8301af4a290256fbb Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 2 Aug 2018 19:32:39 +0200 Subject: [PATCH 36/46] reduced complexity --- x/stake/client/rest/query.go | 19 +++---------------- x/stake/client/rest/utils.go | 25 +++++++++++++++++++++++-- 2 files changed, 26 insertions(+), 18 deletions(-) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 0235b967f985..4fc81479abd9 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -120,23 +120,10 @@ func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu } // Get all validators using key - kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query validators. Error: %s", err.Error()))) - return - } - - // the query will return empty if there are no validators - if len(kvs) == 0 { - w.WriteHeader(http.StatusNoContent) - return - } - - validators, err := getValidators(kvs, cdc) + validators, statusCode, errMsg, err := getBech32Validators(storeName, ctx, cdc) if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + w.WriteHeader(statusCode) + w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) return } diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 768d7f092c08..6b8d941dc3ea 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -161,7 +161,7 @@ func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechVali return validators, nil } -// getValidator Gets a validator given a ValAddress +// Gets a validator given a ValAddress func getValidator(address sdk.ValAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (stake.BechValidator, error) { // parse out the validators for _, kv := range validatorKVs { @@ -184,7 +184,7 @@ func getValidator(address sdk.ValAddress, validatorKVs []sdk.KVPair, cdc *wire.C return stake.BechValidator{}, errors.Errorf("Couldn't find validator") } -// getValidatorFromAccAdrr Gets a validator given an AccAddress +// Gets a validator given an AccAddress func getValidatorFromAccAdrr(address sdk.AccAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (stake.BechValidator, error) { // parse out the validators for _, kv := range validatorKVs { @@ -206,3 +206,24 @@ func getValidatorFromAccAdrr(address sdk.AccAddress, validatorKVs []sdk.KVPair, } return stake.BechValidator{}, errors.Errorf("Couldn't find validator") } + +// Gets all Bech32 validators from a key +func getBech32Validators(storeName string, ctx context.CoreContext, cdc *wire.Codec) ( + validators []types.BechValidator, httpStatusCode int, errMsg string, err error) { + // Get all validators using key + kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + if err != nil { + return nil, http.StatusInternalServerError, "couldn't query validators. Error: ", err + } + + // the query will return empty if there are no validators + if len(kvs) == 0 { + return nil, http.StatusNoContent, "", nil + } + + validators, err = getValidators(kvs, cdc) + if err != nil { + return nil, http.StatusInternalServerError, "Error: ", err + } + return validators, http.StatusOK, "", nil +} From f53130f4f0956ab70be59f0ab40c4815b8bca08a Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 3 Aug 2018 10:15:06 +0200 Subject: [PATCH 37/46] updated comments --- client/tx/search.go | 6 +-- client/tx/sign.go | 4 +- x/stake/client/rest/query.go | 6 +-- x/stake/client/rest/tx.go | 92 ++++++++++++++++++------------------ x/stake/client/rest/utils.go | 22 ++++----- x/stake/keeper/key.go | 46 +++++++++--------- 6 files changed, 88 insertions(+), 88 deletions(-) diff --git a/client/tx/search.go b/client/tx/search.go index 35e5a9191770..ed869cfe77f5 100644 --- a/client/tx/search.go +++ b/client/tx/search.go @@ -23,7 +23,7 @@ const ( flagAny = "any" ) -// SearchTxCmd Default client command to search through tagged transactions +// Default client command to search through tagged transactions func SearchTxCmd(cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "txs", @@ -82,7 +82,7 @@ func searchTxs(ctx context.CoreContext, cdc *wire.Codec, tags []string) ([]Info, return info, nil } -// FormatTxResults Parse the indexed txs into an array of Info +// Parse the indexed txs into an array of Info func FormatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]Info, error) { var err error out := make([]Info, len(res)) @@ -98,7 +98,7 @@ func FormatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]Info, error) { ///////////////////////////////////////// // REST -// SearchTxRequestHandlerFn Search Tx REST Handler +// Search Tx REST Handler func SearchTxRequestHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { tag := r.FormValue("tag") diff --git a/client/tx/sign.go b/client/tx/sign.go index f2f34b13ceb4..75239ef7b33b 100644 --- a/client/tx/sign.go +++ b/client/tx/sign.go @@ -8,7 +8,7 @@ import ( keys "github.com/cosmos/cosmos-sdk/crypto/keys" ) -// SignTxBody REST request body for signed txs +// REST request body for signed txs // TODO does this need to be exposed? type SignTxBody struct { Name string `json:"name"` @@ -16,7 +16,7 @@ type SignTxBody struct { TxBytes string `json:"tx"` } -// SignTxRequstHandler Sign transaction REST Handler +// sign transaction REST Handler func SignTxRequstHandler(w http.ResponseWriter, r *http.Request) { var kb keys.Keybase var m SignTxBody diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 4fc81479abd9..73d3b55a4d09 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -86,7 +86,7 @@ func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec // already resolve the rational shares to not handle this in the client -// DelegationWithoutRat defines a delegation without type Rat for shares +// defines a delegation without type Rat for shares type DelegationWithoutRat struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` ValidatorAddr sdk.AccAddress `json:"validator_addr"` @@ -94,7 +94,7 @@ type DelegationWithoutRat struct { Height int64 `json:"height"` } -// DelegationSummary The aggregation of all delegations, unbondings and redelegations +// aggregation of all delegations, unbondings and redelegations type DelegationSummary struct { Delegations []DelegationWithoutRat `json:"delegations"` UnbondingDelegations []stake.UnbondingDelegation `json:"unbonding_delegations"` @@ -254,7 +254,7 @@ func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Handle } } -// http request handler to query an unbonding-delegation +// HTTP request handler to query an unbonding-delegation func unbondingDelegationsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { diff --git a/x/stake/client/rest/tx.go b/x/stake/client/rest/tx.go index 0f75939dc98b..64cec51dc5dd 100644 --- a/x/stake/client/rest/tx.go +++ b/x/stake/client/rest/tx.go @@ -100,17 +100,17 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C i := 0 for _, msg := range m.Delegations { - delegatorAddr, errAddr := sdk.AccAddressFromBech32(msg.DelegatorAddr) - if errAddr != nil { + delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) + if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", errAddr.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) return } - validatorAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorAddr) + validatorAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) validatorAddrAcc := sdk.AccAddress(validatorAddr) - if errAddr != nil { + if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { @@ -127,10 +127,10 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C } for _, msg := range m.BeginRedelegates { - delegatorAddr, errAddr := sdk.AccAddressFromBech32(msg.DelegatorAddr) - if errAddr != nil { + delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) + if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", errAddr.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) return } if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { @@ -138,24 +138,24 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C w.Write([]byte("Must use own delegator address")) return } - validatorSrcAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) + validatorSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) validatorSrcAddrAcc := sdk.AccAddress(validatorSrcAddr) - if errAddr != nil { + if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } - ValidatorDstAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) + ValidatorDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) ValidatorDstAddrAcc := sdk.AccAddress(ValidatorDstAddr) - if errAddr != nil { + if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } - shares, errRat := sdk.NewRatFromDecimal(msg.SharesAmount, types.MaxBondDenominatorPrecision) - if errRat != nil { + shares, err := sdk.NewRatFromDecimal(msg.SharesAmount, types.MaxBondDenominatorPrecision) + if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode shares amount. Error: %s", errRat.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode shares amount. Error: %s", err.Error()))) return } messages[i] = stake.MsgBeginRedelegate{ @@ -168,24 +168,24 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C } for _, msg := range m.CompleteRedelegates { - delegatorAddr, errAddr := sdk.AccAddressFromBech32(msg.DelegatorAddr) - if errAddr != nil { + delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) + if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", errAddr.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) return } - validatorSrcAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) + validatorSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) validatorSrcAddrAcc := sdk.AccAddress(validatorSrcAddr) - if errAddr != nil { + if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } - ValidatorDstAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) + ValidatorDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) ValidatorDstAddrAcc := sdk.AccAddress(ValidatorDstAddr) - if errAddr != nil { + if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { @@ -202,10 +202,10 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C } for _, msg := range m.BeginUnbondings { - delegatorAddr, errAddr := sdk.AccAddressFromBech32(msg.DelegatorAddr) - if errAddr != nil { + delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) + if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", errAddr.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) return } if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { @@ -213,17 +213,17 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C w.Write([]byte("Must use own delegator address")) return } - validatorAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorAddr) + validatorAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddr) validatorAddrAcc := sdk.AccAddress(validatorAddr) - if errAddr != nil { + if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } - shares, errRat := sdk.NewRatFromDecimal(msg.SharesAmount, types.MaxBondDenominatorPrecision) - if errRat != nil { + shares, err := sdk.NewRatFromDecimal(msg.SharesAmount, types.MaxBondDenominatorPrecision) + if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode shares amount. Error: %s", errRat.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode shares amount. Error: %s", err.Error()))) return } messages[i] = stake.MsgBeginUnbonding{ @@ -235,16 +235,16 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C } for _, msg := range m.CompleteUnbondings { - delegatorAddr, errAddr := sdk.AccAddressFromBech32(msg.DelegatorAddr) - if errAddr != nil { + delegatorAddr, err := sdk.AccAddressFromBech32(msg.DelegatorAddr) + if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", errAddr.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) return } - validatorAddr, errAddr := sdk.AccAddressFromBech32(msg.ValidatorAddr) - if errAddr != nil { + validatorAddr, err := sdk.AccAddressFromBech32(msg.ValidatorAddr) + if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } if !bytes.Equal(info.GetPubKey().Address(), delegatorAddr) { @@ -270,8 +270,8 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C ctx = ctx.WithSequence(m.Sequence) m.Sequence++ - txBytes, errSign := ctx.SignAndBuild(m.LocalAccountName, m.Password, []sdk.Msg{msg}, cdc) - if errSign != nil { + txBytes, err := ctx.SignAndBuild(m.LocalAccountName, m.Password, []sdk.Msg{msg}, cdc) + if err != nil { w.WriteHeader(http.StatusUnauthorized) w.Write([]byte(err.Error())) return @@ -285,8 +285,8 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C // should we have a sdk.MultiMsg type to make sending atomic? results := make([]*ctypes.ResultBroadcastTxCommit, len(signedTxs[:])) for i, txBytes := range signedTxs { - res, errTx := ctx.BroadcastTx(txBytes) - if errTx != nil { + res, err := ctx.BroadcastTx(txBytes) + if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 6b8d941dc3ea..140c4af095ac 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -42,8 +42,8 @@ func getDelegatorValidator(ctx context.CoreContext, cdc *wire.Codec, delegatorAd return types.BechValidator{}, http.StatusNoContent, "", nil } - kvs, errQuery := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) - if errQuery != nil { + kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + if err != nil { return types.BechValidator{}, http.StatusInternalServerError, "Error: ", err } if len(kvs) == 0 { @@ -71,9 +71,9 @@ func getDelegatorDelegations(ctx context.CoreContext, cdc *wire.Codec, delegator return DelegationWithoutRat{}, http.StatusNoContent, "", nil } - delegation, errUnmarshal := types.UnmarshalDelegation(cdc, delegationKey, marshalledDelegation) - if errUnmarshal != nil { - return DelegationWithoutRat{}, http.StatusInternalServerError, "couldn't unmarshall delegation. Error: ", errUnmarshal + delegation, err := types.UnmarshalDelegation(cdc, delegationKey, marshalledDelegation) + if err != nil { + return DelegationWithoutRat{}, http.StatusInternalServerError, "couldn't unmarshall delegation. Error: ", err } outputDelegation = DelegationWithoutRat{ @@ -99,9 +99,9 @@ func getDelegatorUndelegations(ctx context.CoreContext, cdc *wire.Codec, delegat return types.UnbondingDelegation{}, http.StatusNoContent, "", nil } - unbondingDelegation, errUnmarshal := types.UnmarshalUBD(cdc, undelegationKey, marshalledUnbondingDelegation) - if errUnmarshal != nil { - return types.UnbondingDelegation{}, http.StatusInternalServerError, "couldn't unmarshall unbonding-delegation. Error: ", errUnmarshal + unbondingDelegation, err := types.UnmarshalUBD(cdc, undelegationKey, marshalledUnbondingDelegation) + if err != nil { + return types.UnbondingDelegation{}, http.StatusInternalServerError, "couldn't unmarshall unbonding-delegation. Error: ", err } return unbondingDelegation, http.StatusOK, "", nil } @@ -119,9 +119,9 @@ func getDelegatorRedelegations(ctx context.CoreContext, cdc *wire.Codec, delegat return types.Redelegation{}, http.StatusNoContent, "", nil } - redelegations, errUnmarshal := types.UnmarshalRED(cdc, keyRedelegateTo, marshalledRedelegations) - if errUnmarshal != nil { - return types.Redelegation{}, http.StatusInternalServerError, "couldn't unmarshall redelegations. Error: ", errUnmarshal + redelegations, err := types.UnmarshalRED(cdc, keyRedelegateTo, marshalledRedelegations) + if err != nil { + return types.Redelegation{}, http.StatusInternalServerError, "couldn't unmarshall redelegations. Error: ", err } return redelegations, http.StatusOK, "", nil diff --git a/x/stake/keeper/key.go b/x/stake/keeper/key.go index cf35742b9613..502ec2654419 100644 --- a/x/stake/keeper/key.go +++ b/x/stake/keeper/key.go @@ -34,19 +34,19 @@ var ( const maxDigitsForAccount = 12 // ~220,000,000 atoms created at launch -// Gets the key for the validator with address. +// gets the key for the validator with address // VALUE: stake/types.Validator func GetValidatorKey(ownerAddr sdk.AccAddress) []byte { return append(ValidatorsKey, ownerAddr.Bytes()...) } -// Gets the key for the validator with pubkey. +// gets the key for the validator with pubkey // VALUE: validator owner address ([]byte) func GetValidatorByPubKeyIndexKey(pubkey crypto.PubKey) []byte { return append(ValidatorsByPubKeyIndexKey, pubkey.Bytes()...) } -// Gets the key for the current validator group. +// gets the key for the current validator group // VALUE: none (key rearrangement with GetValKeyFromValBondedIndexKey) func GetValidatorsBondedIndexKey(ownerAddr sdk.AccAddress) []byte { return append(ValidatorsBondedIndexKey, ownerAddr.Bytes()...) @@ -57,7 +57,7 @@ func GetAddressFromValBondedIndexKey(IndexKey []byte) []byte { return IndexKey[1:] // remove prefix bytes } -// Get the validator by power index. +// get the validator by power index. // Power index is the key used in the power-store, and represents the relative // power ranking of the validator. // VALUE: validator owner address ([]byte) @@ -66,7 +66,7 @@ func GetValidatorsByPowerIndexKey(validator types.Validator, pool types.Pool) [] return getValidatorPowerRank(validator, pool) } -// Get the power ranking of a validator. +// get the power ranking of a validator // NOTE the larger values are of higher value func getValidatorPowerRank(validator types.Validator, pool types.Pool) []byte { @@ -94,7 +94,7 @@ func getValidatorPowerRank(validator types.Validator, pool types.Pool) []byte { counterBytes...) } -// Get the key for the accumulated update validators. +// get the key for the accumulated update validators // VALUE: abci.Validator // note records using these keys should never persist between blocks func GetTendermintUpdatesKey(ownerAddr sdk.AccAddress) []byte { @@ -103,20 +103,20 @@ func GetTendermintUpdatesKey(ownerAddr sdk.AccAddress) []byte { //______________________________________________________________________________ -// Gets the key for delegator bond with validator. +// gets the key for delegator bond with validator // VALUE: stake/types.Delegation func GetDelegationKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { return append(GetDelegationsKey(delegatorAddr), validatorAddr.Bytes()...) } -// Gets the prefix for a delegator for all validators. +// gets the prefix for a delegator for all validators func GetDelegationsKey(delegatorAddr sdk.AccAddress) []byte { return append(DelegationKey, delegatorAddr.Bytes()...) } //______________________________________________________________________________ -// Gets the key for an unbonding delegation by delegator and validator addr. +// gets the key for an unbonding delegation by delegator and validator addr // VALUE: stake/types.UnbondingDelegation func GetUBDKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { return append( @@ -124,13 +124,13 @@ func GetUBDKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { validatorAddr.Bytes()...) } -// Gets the index-key for an unbonding delegation, stored by validator-index. +// gets the index-key for an unbonding delegation, stored by validator-index // VALUE: none (key rearrangement used) func GetUBDByValIndexKey(delegatorAddr, validatorAddr sdk.AccAddress) []byte { return append(GetUBDsByValIndexKey(validatorAddr), delegatorAddr.Bytes()...) } -// Rearranges the ValIndexKey to get the UBDKey. +// rearranges the ValIndexKey to get the UBDKey func GetUBDKeyFromValIndexKey(IndexKey []byte) []byte { addrs := IndexKey[1:] // remove prefix bytes if len(addrs) != 2*sdk.AddrLen { @@ -143,19 +143,19 @@ func GetUBDKeyFromValIndexKey(IndexKey []byte) []byte { //______________ -// Gets the prefix for all unbonding delegations from a delegator. +// gets the prefix for all unbonding delegations from a delegator func GetUBDsKey(delegatorAddr sdk.AccAddress) []byte { return append(UnbondingDelegationKey, delegatorAddr.Bytes()...) } -// Gets the prefix keyspace for the indexes of unbonding delegations for a validator. +// gets the prefix keyspace for the indexes of unbonding delegations for a validator func GetUBDsByValIndexKey(validatorAddr sdk.AccAddress) []byte { return append(UnbondingDelegationByValIndexKey, validatorAddr.Bytes()...) } //________________________________________________________________________________ -// Gets the key for a redelegation. +// gets the key for a redelegation // VALUE: stake/types.RedelegationKey func GetREDKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { return append(append( @@ -164,7 +164,7 @@ func GetREDKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) validatorDstAddr.Bytes()...) } -// Gets the index-key for a redelegation, stored by source-validator-index. +// gets the index-key for a redelegation, stored by source-validator-index // VALUE: none (key rearrangement used) func GetREDByValSrcIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { return append(append( @@ -173,7 +173,7 @@ func GetREDByValSrcIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sd validatorDstAddr.Bytes()...) } -// Gets the index-key for a redelegation, stored by destination-validator-index. +// gets the index-key for a redelegation, stored by destination-validator-index // VALUE: none (key rearrangement used) func GetREDByValDstIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte { return append(append( @@ -182,7 +182,7 @@ func GetREDByValDstIndexKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sd validatorSrcAddr.Bytes()...) } -// Rearranges the ValSrcIndexKey to get the REDKey. +// rearranges the ValSrcIndexKey to get the REDKey func GetREDKeyFromValSrcIndexKey(IndexKey []byte) []byte { addrs := IndexKey[1:] // remove prefix bytes if len(addrs) != 3*sdk.AddrLen { @@ -195,7 +195,7 @@ func GetREDKeyFromValSrcIndexKey(IndexKey []byte) []byte { return GetREDKey(delAddr, valSrcAddr, valDstAddr) } -// Rearranges the ValDstIndexKey to get the REDKey. +// rearranges the ValDstIndexKey to get the REDKey func GetREDKeyFromValDstIndexKey(IndexKey []byte) []byte { addrs := IndexKey[1:] // remove prefix bytes if len(addrs) != 3*sdk.AddrLen { @@ -209,23 +209,23 @@ func GetREDKeyFromValDstIndexKey(IndexKey []byte) []byte { //______________ -// Gets the prefix keyspace for redelegations from a delegator. +// gets the prefix keyspace for redelegations from a delegator func GetREDsKey(delegatorAddr sdk.AccAddress) []byte { return append(RedelegationKey, delegatorAddr.Bytes()...) } -// Gets the prefix keyspace for all redelegations redelegating away from a source validator. +// gets the prefix keyspace for all redelegations redelegating away from a source validator func GetREDsFromValSrcIndexKey(validatorSrcAddr sdk.AccAddress) []byte { return append(RedelegationByValSrcIndexKey, validatorSrcAddr.Bytes()...) } -// Gets the prefix keyspace for all redelegations redelegating towards a destination validator. +// gets the prefix keyspace for all redelegations redelegating towards a destination validator func GetREDsToValDstIndexKey(validatorDstAddr sdk.AccAddress) []byte { return append(RedelegationByValDstIndexKey, validatorDstAddr.Bytes()...) } -// Gets the prefix keyspace for all redelegations redelegating towards a destination validator -// from a particular delegator. +// gets the prefix keyspace for all redelegations redelegating towards a destination validator +// from a particular delegator func GetREDsByDelToValDstIndexKey(delegatorAddr, validatorDstAddr sdk.AccAddress) []byte { return append( GetREDsToValDstIndexKey(validatorDstAddr), From 724aae61ec240dea6bd979d0bfe7efa34174d08f Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Fri, 3 Aug 2018 10:24:10 +0200 Subject: [PATCH 38/46] reverted valaddr back to accaddr --- x/stake/client/rest/tx.go | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/x/stake/client/rest/tx.go b/x/stake/client/rest/tx.go index 0f75939dc98b..58e3ccb8970a 100644 --- a/x/stake/client/rest/tx.go +++ b/x/stake/client/rest/tx.go @@ -106,8 +106,7 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", errAddr.Error()))) return } - validatorAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorAddr) - validatorAddrAcc := sdk.AccAddress(validatorAddr) + validatorAddr, errAddr := sdk.AccAddressFromBech32(msg.ValidatorAddr) if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) @@ -120,7 +119,7 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C } messages[i] = stake.MsgDelegate{ DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddrAcc, + ValidatorAddr: validatorAddr, Delegation: msg.Delegation, } i++ @@ -138,15 +137,13 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C w.Write([]byte("Must use own delegator address")) return } - validatorSrcAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) - validatorSrcAddrAcc := sdk.AccAddress(validatorSrcAddr) + validatorSrcAddr, errAddr := sdk.AccAddressFromBech32(msg.ValidatorSrcAddr) if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) return } - ValidatorDstAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) - ValidatorDstAddrAcc := sdk.AccAddress(ValidatorDstAddr) + ValidatorDstAddr, errAddr := sdk.AccAddressFromBech32(msg.ValidatorDstAddr) if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) @@ -160,8 +157,8 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C } messages[i] = stake.MsgBeginRedelegate{ DelegatorAddr: delegatorAddr, - ValidatorSrcAddr: validatorSrcAddrAcc, - ValidatorDstAddr: ValidatorDstAddrAcc, + ValidatorSrcAddr: validatorSrcAddr, + ValidatorDstAddr: ValidatorDstAddr, SharesAmount: shares, } i++ @@ -174,15 +171,13 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", errAddr.Error()))) return } - validatorSrcAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorSrcAddr) - validatorSrcAddrAcc := sdk.AccAddress(validatorSrcAddr) + validatorSrcAddr, errAddr := sdk.AccAddressFromBech32(msg.ValidatorSrcAddr) if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) return } - ValidatorDstAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorDstAddr) - ValidatorDstAddrAcc := sdk.AccAddress(ValidatorDstAddr) + ValidatorDstAddr, errAddr := sdk.AccAddressFromBech32(msg.ValidatorDstAddr) if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) @@ -195,8 +190,8 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C } messages[i] = stake.MsgCompleteRedelegate{ DelegatorAddr: delegatorAddr, - ValidatorSrcAddr: validatorSrcAddrAcc, - ValidatorDstAddr: ValidatorDstAddrAcc, + ValidatorSrcAddr: validatorSrcAddr, + ValidatorDstAddr: ValidatorDstAddr, } i++ } @@ -213,8 +208,7 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C w.Write([]byte("Must use own delegator address")) return } - validatorAddr, errAddr := sdk.ValAddressFromBech32(msg.ValidatorAddr) - validatorAddrAcc := sdk.AccAddress(validatorAddr) + validatorAddr, errAddr := sdk.AccAddressFromBech32(msg.ValidatorAddr) if errAddr != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", errAddr.Error()))) @@ -228,7 +222,7 @@ func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.C } messages[i] = stake.MsgBeginUnbonding{ DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddrAcc, + ValidatorAddr: validatorAddr, SharesAmount: shares, } i++ From e0a8f0414c6feb6fc551713df056b0d312b14884 Mon Sep 17 00:00:00 2001 From: Fabian Weber Date: Fri, 3 Aug 2018 11:53:51 +0200 Subject: [PATCH 39/46] fixed tests --- client/lcd/lcd_test.go | 18 +++++++++--------- x/stake/client/rest/query.go | 9 +++------ x/stake/client/rest/utils.go | 2 +- 3 files changed, 13 insertions(+), 16 deletions(-) diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index e41966287ff3..8725a22d8591 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -374,7 +374,7 @@ func TestValidatorQuery(t *testing.T) { defer cleanup() require.Equal(t, 1, len(pks)) - validator1Owner := sdk.ValAddress(pks[0].Address()) + validator1Owner := sdk.AccAddress(pks[0].Address()) validator := getValidator(t, port, validator1Owner) bech32ValAddress, err := sdk.Bech32ifyValPub(pks[0]) @@ -388,7 +388,7 @@ func TestBonding(t *testing.T) { cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) defer cleanup() - validator1Owner := sdk.ValAddress(pks[0].Address()) + validator1Owner := sdk.AccAddress(pks[0].Address()) // create bond TX resultTx := doDelegate(t, port, seed, name, password, addr, validator1Owner) @@ -430,7 +430,7 @@ func TestBonding(t *testing.T) { require.Equal(t, int64(40), coins.AmountOf("steak").Int64()) // query unbonding delegation - validatorAddr := sdk.ValAddress(pks[0].Address()) + validatorAddr := sdk.AccAddress(pks[0].Address()) unbondings := getUndelegations(t, port, addr, validatorAddr) assert.Len(t, unbondings, 1, "Unbondings holds all unbonding-delegations") assert.Equal(t, "30", unbondings[0].Balance.Amount.String()) @@ -755,7 +755,7 @@ func getSigningInfo(t *testing.T, port string, validatorPubKey string) slashing. // ============= Stake Module ================ -func getDelegation(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) rest.DelegationWithoutRat { +func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.AccAddress) rest.DelegationWithoutRat { // get the account to get the sequence res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/delegations/%s", delegatorAddr, validatorAddr), nil) @@ -766,7 +766,7 @@ func getDelegation(t *testing.T, port string, delegatorAddr sdk.AccAddress, vali return bond } -func getUndelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) []stake.UnbondingDelegation { +func getUndelegations(t *testing.T, port string, delegatorAddr, validatorAddr sdk.AccAddress) []stake.UnbondingDelegation { // get the account to get the sequence res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/unbonding_delegations/%s", delegatorAddr, validatorAddr), nil) @@ -805,7 +805,7 @@ func getBondingTxs(t *testing.T, port string, delegatorAddr sdk.AccAddress, quer return txs } -func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) (resultTx ctypes.ResultBroadcastTxCommit) { +func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { // get the account to get the sequence acc := getAccount(t, port, delegatorAddr) accnum := acc.GetAccountNumber() @@ -844,7 +844,7 @@ func doDelegate(t *testing.T, port, seed, name, password string, delegatorAddr s } func doBeginUnbonding(t *testing.T, port, seed, name, password string, - delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) (resultTx ctypes.ResultBroadcastTxCommit) { + delegatorAddr, validatorAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { // get the account to get the sequence acc := getAccount(t, port, delegatorAddr) @@ -884,7 +884,7 @@ func doBeginUnbonding(t *testing.T, port, seed, name, password string, } func doBeginRedelegation(t *testing.T, port, seed, name, password string, - delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress) (resultTx ctypes.ResultBroadcastTxCommit) { + delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) (resultTx ctypes.ResultBroadcastTxCommit) { // get the account to get the sequence acc := getAccount(t, port, delegatorAddr) @@ -934,7 +934,7 @@ func getValidators(t *testing.T, port string) []stake.BechValidator { return validators } -func getValidator(t *testing.T, port string, validatorAddr sdk.ValAddress) stake.BechValidator { +func getValidator(t *testing.T, port string, validatorAddr sdk.AccAddress) stake.BechValidator { // get the account to get the sequence res, body := Request(t, port, "GET", fmt.Sprintf("/stake/validators/%s", validatorAddr.String()), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 73d3b55a4d09..64dea004129f 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -270,13 +270,12 @@ func unbondingDelegationsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) htt return } - validatorAddr, err := sdk.ValAddressFromBech32(bech32validator) + validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } - //TODO this seems wrong. we should query with the sdk.ValAddress and not sdk.AccAddress validatorAddrAcc := sdk.AccAddress(validatorAddr) key := stake.GetUBDKey(delegatorAddr, validatorAddrAcc) @@ -331,13 +330,12 @@ func delegationHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerF return } - validatorAddr, err := sdk.ValAddressFromBech32(bech32validator) + validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } - //TODO this seems wrong. we should query with the sdk.ValAddress and not sdk.AccAddress validatorAddrAcc := sdk.AccAddress(validatorAddr) key := stake.GetDelegationKey(delegatorAddr, validatorAddrAcc) @@ -454,7 +452,6 @@ func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http. delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) validatorAccAddr, err := sdk.AccAddressFromBech32(bech32validator) - // validatorValAddress, err := sdk.ValAddressFromBech32(bech32validator) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) @@ -526,7 +523,7 @@ func validatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu // read parameters vars := mux.Vars(r) bech32validatorAddr := vars["addr"] - valAddress, err := sdk.ValAddressFromBech32(bech32validatorAddr) + valAddress, err := sdk.AccAddressFromBech32(bech32validatorAddr) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 140c4af095ac..470bec62eb76 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -162,7 +162,7 @@ func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechVali } // Gets a validator given a ValAddress -func getValidator(address sdk.ValAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (stake.BechValidator, error) { +func getValidator(address sdk.AccAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (stake.BechValidator, error) { // parse out the validators for _, kv := range validatorKVs { addr := kv.Key[1:] From 33f763fdeff7a9d8ad4e9a490c0159d5d3d41fc1 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 7 Aug 2018 11:01:56 +0200 Subject: [PATCH 40/46] Fixed conflicts --- client/tx/search.go | 2 +- x/stake/client/rest/query.go | 95 ++++++++++-------------------------- x/stake/client/rest/tx.go | 31 +++--------- x/stake/client/rest/utils.go | 22 ++++----- 4 files changed, 44 insertions(+), 106 deletions(-) diff --git a/client/tx/search.go b/client/tx/search.go index 096f4ce7932d..79bb058191f2 100644 --- a/client/tx/search.go +++ b/client/tx/search.go @@ -57,7 +57,7 @@ func SearchTxCmd(cdc *wire.Codec) *cobra.Command { return cmd } -func searchTxs(cliCtx context.CLIContext, cdc *wire.Codec, tags []string) ([]txInfo, error) { +func searchTxs(cliCtx context.CLIContext, cdc *wire.Codec, tags []string) ([]Info, error) { if len(tags) == 0 { return nil, errors.New("must declare at least one tag to search") } diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 75b4d6a33318..19809b84617c 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -18,59 +18,42 @@ import ( const storeName = "stake" -<<<<<<< HEAD -func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec) { +func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Codec) { // GET /stake/delegators/{delegatorAddr} // Get all delegations (delegation, undelegation and redelegation) from a delegator r.HandleFunc( "/stake/delegators/{delegatorAddr}", - delegatorHandlerFn(ctx, cdc), + delegatorHandlerFn(cliCtx, cdc), ).Methods("GET") // GET /stake/delegators/{delegatorAddr}/txs // Get all staking txs (i.e msgs) from a delegator r.HandleFunc( "/stake/delegators/{delegatorAddr}/txs", - delegatorTxsHandlerFn(ctx, cdc), -======= -func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Codec) { - r.HandleFunc( - "/stake/{delegator}/delegation/{validator}", - delegationHandlerFn(cliCtx, cdc), ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c + delegatorTxsHandlerFn(cliCtx, cdc), ).Methods("GET") // // GET /stake/delegators/{delegatorAddr}/validators // Query all validators that a delegator is bonded to // r.HandleFunc( // "/stake/delegators/{delegatorAddr}/validators", - // delegatorValidatorsHandlerFn(ctx, cdc), + // delegatorValidatorsHandlerFn(cliCtx, cdc), // ).Methods("GET") // GET /stake/delegators/{delegatorAddr}/validators/{validatorAddr} // Query a validator that a delegator is bonded to // r.HandleFunc( // "/stake/delegators/{delegatorAddr}/validators", - // delegatorValidatorHandlerFn(ctx, cdc), + // delegatorValidatorHandlerFn(cliCtx, cdc), // ).Methods("GET") // GET /stake/delegators/{delegatorAddr}/delegations/{validatorAddr} // Query a delegation between a delegator and a validator r.HandleFunc( -<<<<<<< HEAD "/stake/delegators/{delegatorAddr}/delegations/{validatorAddr}", - delegationHandlerFn(ctx, cdc), -======= - "/stake/{delegator}/ubd/{validator}", - ubdHandlerFn(cliCtx, cdc), ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c + delegationHandlerFn(cliCtx, cdc), ).Methods("GET") // GET /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr} // Query all unbonding_delegations between a delegator and a validator r.HandleFunc( -<<<<<<< HEAD "/stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}", - unbondingDelegationsHandlerFn(ctx, cdc), -======= - "/stake/{delegator}/red/{validator_src}/{validator_dst}", - redHandlerFn(cliCtx, cdc), ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c + unbondingDelegationsHandlerFn(cliCtx, cdc), ).Methods("GET") /* @@ -81,7 +64,7 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Cod */ // r.HandleFunc( // "/stake/delegators/{delegatorAddr}/validators/{validatorAddr}/txs", - // stakingTxsHandlerFn(ctx, cdc), + // stakingTxsHandlerFn(cliCtx, cdc), // ).Queries("type", "{type}").Methods("GET") // GET /stake/validators/ @@ -93,14 +76,13 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Cod // GET /stake/validators/{addr} r.HandleFunc( "/stake/validators/{addr}", - validatorHandlerFn(ctx, cdc), + validatorHandlerFn(cliCtx, cdc), ).Methods("GET") // GET /stake/validators/{addr}/delegators // Don't think this is currently possible without changing keys } -<<<<<<< HEAD // already resolve the rational shares to not handle this in the client // defines a delegation without type Rat for shares @@ -119,18 +101,13 @@ type DelegationSummary struct { } // HTTP request handler to query a delegator delegations -func delegatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +func delegatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var validatorAddr sdk.AccAddress var delegationSummary = DelegationSummary{} // read parameters -======= -// http request handler to query a delegation -func delegationHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c vars := mux.Vars(r) bech32delegator := vars["delegatorAddr"] @@ -142,7 +119,7 @@ func delegationHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Handle } // Get all validators using key - validators, statusCode, errMsg, err := getBech32Validators(storeName, ctx, cdc) + validators, statusCode, errMsg, err := getBech32Validators(storeName, cliCtx, cdc) if err != nil { w.WriteHeader(statusCode) w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) @@ -153,7 +130,7 @@ func delegationHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Handle validatorAddr = validator.Owner // Delegations - delegations, statusCode, errMsg, err := getDelegatorDelegations(ctx, cdc, delegatorAddr, validatorAddr) + delegations, statusCode, errMsg, err := getDelegatorDelegations(cliCtx, cdc, delegatorAddr, validatorAddr) if err != nil { w.WriteHeader(statusCode) w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) @@ -164,7 +141,7 @@ func delegationHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Handle } // Undelegations - unbondingDelegation, statusCode, errMsg, err := getDelegatorUndelegations(ctx, cdc, delegatorAddr, validatorAddr) + unbondingDelegation, statusCode, errMsg, err := getDelegatorUndelegations(cliCtx, cdc, delegatorAddr, validatorAddr) if err != nil { w.WriteHeader(statusCode) w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) @@ -177,7 +154,7 @@ func delegationHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Handle // Redelegations // only querying redelegations to a validator as this should give us already all relegations // if we also would put in redelegations from, we would have every redelegation double - redelegations, statusCode, errMsg, err := getDelegatorRedelegations(ctx, cdc, delegatorAddr, validatorAddr) + redelegations, statusCode, errMsg, err := getDelegatorRedelegations(cliCtx, cdc, delegatorAddr, validatorAddr) if err != nil { w.WriteHeader(statusCode) w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) @@ -201,7 +178,7 @@ func delegationHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Handle } // HTTP request handler to query all staking txs (msgs) from a delegator -func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +func delegatorTxsHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var output []byte var typesQuerySlice []string @@ -215,13 +192,7 @@ func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Handle return } -<<<<<<< HEAD - node, err := ctx.GetNode() -======= - key := stake.GetDelegationKey(delegatorAddr, validatorAddr) - - res, err := cliCtx.QueryStore(key, storeName) ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c + node, err := cliCtx.GetNode() if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't get current Node information. Error: %s", err.Error()))) @@ -282,13 +253,8 @@ func delegatorTxsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.Handle } } -<<<<<<< HEAD // HTTP request handler to query an unbonding-delegation -func unbondingDelegationsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { -======= -// http request handler to query an unbonding-delegation -func ubdHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c +func unbondingDelegationsHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) bech32delegator := vars["delegatorAddr"] @@ -345,13 +311,8 @@ func ubdHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { } } -<<<<<<< HEAD // HTTP request handler to query a bonded validator -func delegationHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { -======= -// http request handler to query an redelegation -func redHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c +func delegationHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // read parameters vars := mux.Vars(r) @@ -375,7 +336,7 @@ func redHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { key := stake.GetDelegationKey(delegatorAddr, validatorAddrAcc) - res, err := ctx.QueryStore(key, storeName) + res, err := cliCtx.QueryStore(key, storeName) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) @@ -402,11 +363,7 @@ func redHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { Shares: delegation.Shares.FloatString(), } -<<<<<<< HEAD output, err := cdc.MarshalJSON(outputDelegation) -======= - res, err := cliCtx.QueryStore(key, storeName) ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) @@ -418,7 +375,7 @@ func redHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { } // HTTP request handler to query all delegator bonded validators -func delegatorValidatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +func delegatorValidatorsHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var validatorAccAddr sdk.AccAddress @@ -436,7 +393,7 @@ func delegatorValidatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http } // Get all validators using key - kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + kvs, err := cliCtx.QuerySubspace(stake.ValidatorsKey, storeName) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("couldn't query validators. Error: %s", err.Error()))) @@ -458,7 +415,7 @@ func delegatorValidatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http // get all transactions from the delegator to val and append validatorAccAddr = validator.Owner - validator, statusCode, errMsg, errRes := getDelegatorValidator(ctx, cdc, delegatorAddr, validatorAccAddr) + validator, statusCode, errMsg, errRes := getDelegatorValidator(cliCtx, cdc, delegatorAddr, validatorAccAddr) if errRes != nil { w.WriteHeader(statusCode) w.Write([]byte(fmt.Sprintf("%s%s", errMsg, errRes.Error()))) @@ -481,7 +438,7 @@ func delegatorValidatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http } // HTTP request handler to get information from a currently bonded validator -func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +func delegatorValidatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // read parameters var output []byte @@ -499,7 +456,7 @@ func delegatorValidatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http. // Check if there if the delegator is bonded or redelegated to the validator - validator, statusCode, errMsg, err := getDelegatorValidator(ctx, cdc, delegatorAddr, validatorAccAddr) + validator, statusCode, errMsg, err := getDelegatorValidator(cliCtx, cdc, delegatorAddr, validatorAccAddr) if err != nil { w.WriteHeader(statusCode) w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) @@ -555,7 +512,7 @@ func validatorsHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Handle } // HTTP request handler to query the validator information from a given validator address -func validatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { +func validatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var output []byte @@ -569,7 +526,7 @@ func validatorHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFu return } - kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + kvs, err := cliCtx.QuerySubspace(stake.ValidatorsKey, storeName) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) diff --git a/x/stake/client/rest/tx.go b/x/stake/client/rest/tx.go index 3e86d78aed6d..88f9741252cd 100644 --- a/x/stake/client/rest/tx.go +++ b/x/stake/client/rest/tx.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" - authctx "github.com/cosmos/cosmos-sdk/x/auth/client/context" + authcliCtx "github.com/cosmos/cosmos-sdk/x/auth/client/context" "github.com/cosmos/cosmos-sdk/x/stake" "github.com/cosmos/cosmos-sdk/x/stake/types" @@ -21,13 +21,8 @@ import ( func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { r.HandleFunc( -<<<<<<< HEAD "/stake/delegators/{delegatorAddr}/delegations", - delegationsRequestHandlerFn(cdc, kb, ctx), -======= - "/stake/delegations", - editDelegationsRequestHandlerFn(cdc, kb, cliCtx), ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c + delegationsRequestHandlerFn(cdc, kb, cliCtx), ).Methods("POST") } @@ -74,12 +69,8 @@ type EditDelegationsBody struct { // nolint: gocyclo // TODO: Split this up into several smaller functions, and remove the above nolint -<<<<<<< HEAD // TODO: use sdk.ValAddress instead of sdk.AccAddress for validators in messages -func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { -======= -func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c +func delegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var m EditDelegationsBody @@ -162,12 +153,7 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx co w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } -<<<<<<< HEAD - ValidatorDstAddr, err := sdk.AccAddressFromBech32(msg.ValidatorDstAddr) -======= - validatorDstAddr, err := sdk.AccAddressFromBech32(msg.ValidatorDstAddr) ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) @@ -184,7 +170,7 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx co messages[i] = stake.MsgBeginRedelegate{ DelegatorAddr: delegatorAddr, ValidatorSrcAddr: validatorSrcAddr, - ValidatorDstAddr: ValidatorDstAddr, + ValidatorDstAddr: validatorDstAddr, SharesAmount: shares, } @@ -205,12 +191,7 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx co w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } -<<<<<<< HEAD - ValidatorDstAddr, err := sdk.AccAddressFromBech32(msg.ValidatorDstAddr) -======= - validatorDstAddr, err := sdk.AccAddressFromBech32(msg.ValidatorDstAddr) ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) @@ -226,7 +207,7 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx co messages[i] = stake.MsgCompleteRedelegate{ DelegatorAddr: delegatorAddr, ValidatorSrcAddr: validatorSrcAddr, - ValidatorDstAddr: ValidatorDstAddr, + ValidatorDstAddr: validatorDstAddr, } i++ @@ -298,7 +279,7 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, cliCtx co i++ } - txCtx := authctx.TxContext{ + txCtx := authcliCtx.TxContext{ Codec: cdc, ChainID: m.ChainID, Gas: m.Gas, diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 470bec62eb76..90ded63dbd14 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -26,14 +26,14 @@ func contains(stringSlice []string, txType string) bool { return false } -func getDelegatorValidator(ctx context.CoreContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAccAddr sdk.AccAddress) ( +func getDelegatorValidator(cliCtx context.CLIContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAccAddr sdk.AccAddress) ( validator types.BechValidator, httpStatusCode int, errMsg string, err error) { // Check if the delegator is bonded or redelegated to the validator keyDel := stake.GetDelegationKey(delegatorAddr, validatorAccAddr) // keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAccAddr) - res, err := ctx.QueryStore(keyDel, storeName) + res, err := cliCtx.QueryStore(keyDel, storeName) if err != nil { return types.BechValidator{}, http.StatusInternalServerError, "couldn't query delegation. Error: ", err } @@ -42,7 +42,7 @@ func getDelegatorValidator(ctx context.CoreContext, cdc *wire.Codec, delegatorAd return types.BechValidator{}, http.StatusNoContent, "", nil } - kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + kvs, err := cliCtx.QuerySubspace(stake.ValidatorsKey, storeName) if err != nil { return types.BechValidator{}, http.StatusInternalServerError, "Error: ", err } @@ -58,10 +58,10 @@ func getDelegatorValidator(ctx context.CoreContext, cdc *wire.Codec, delegatorAd return validator, http.StatusOK, "", nil } -func getDelegatorDelegations(ctx context.CoreContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( +func getDelegatorDelegations(cliCtx context.CLIContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( outputDelegation DelegationWithoutRat, httpStatusCode int, errMsg string, err error) { delegationKey := stake.GetDelegationKey(delegatorAddr, validatorAddr) - marshalledDelegation, err := ctx.QueryStore(delegationKey, storeName) + marshalledDelegation, err := cliCtx.QueryStore(delegationKey, storeName) if err != nil { return DelegationWithoutRat{}, http.StatusInternalServerError, "couldn't query delegation. Error: ", err } @@ -86,10 +86,10 @@ func getDelegatorDelegations(ctx context.CoreContext, cdc *wire.Codec, delegator return outputDelegation, http.StatusOK, "", nil } -func getDelegatorUndelegations(ctx context.CoreContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( +func getDelegatorUndelegations(cliCtx context.CLIContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( unbonds types.UnbondingDelegation, httpStatusCode int, errMsg string, err error) { undelegationKey := stake.GetUBDKey(delegatorAddr, validatorAddr) - marshalledUnbondingDelegation, err := ctx.QueryStore(undelegationKey, storeName) + marshalledUnbondingDelegation, err := cliCtx.QueryStore(undelegationKey, storeName) if err != nil { return types.UnbondingDelegation{}, http.StatusInternalServerError, "couldn't query unbonding-delegation. Error: ", err } @@ -106,11 +106,11 @@ func getDelegatorUndelegations(ctx context.CoreContext, cdc *wire.Codec, delegat return unbondingDelegation, http.StatusOK, "", nil } -func getDelegatorRedelegations(ctx context.CoreContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( +func getDelegatorRedelegations(cliCtx context.CLIContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( regelegations types.Redelegation, httpStatusCode int, errMsg string, err error) { keyRedelegateTo := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) - marshalledRedelegations, err := ctx.QueryStore(keyRedelegateTo, storeName) + marshalledRedelegations, err := cliCtx.QueryStore(keyRedelegateTo, storeName) if err != nil { return types.Redelegation{}, http.StatusInternalServerError, "couldn't query redelegation. Error: ", err } @@ -208,10 +208,10 @@ func getValidatorFromAccAdrr(address sdk.AccAddress, validatorKVs []sdk.KVPair, } // Gets all Bech32 validators from a key -func getBech32Validators(storeName string, ctx context.CoreContext, cdc *wire.Codec) ( +func getBech32Validators(storeName string, cliCtx context.CLIContext, cdc *wire.Codec) ( validators []types.BechValidator, httpStatusCode int, errMsg string, err error) { // Get all validators using key - kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) + kvs, err := cliCtx.QuerySubspace(stake.ValidatorsKey, storeName) if err != nil { return nil, http.StatusInternalServerError, "couldn't query validators. Error: ", err } From 8abcdaa8d6a9fe8a8d21e3a01c911278ab8f3ec1 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 7 Aug 2018 11:05:53 +0200 Subject: [PATCH 41/46] Fixed Gopkg.lock --- Gopkg.lock | 187 ++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 157 insertions(+), 30 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index e1b054c23fa8..08b12f279ebe 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -2,58 +2,76 @@ [[projects]] + digest = "1:09a7f74eb6bb3c0f14d8926610c87f569c5cff68e978d30e9a3540aeb626fdf0" name = "github.com/bartekn/go-bip39" packages = ["."] + pruneopts = "UT" revision = "a05967ea095d81c8fe4833776774cfaff8e5036c" [[projects]] branch = "master" + digest = "1:d6afaeed1502aa28e80a4ed0981d570ad91b2579193404256ce672ed0a609e0d" name = "github.com/beorn7/perks" packages = ["quantile"] + pruneopts = "UT" revision = "3a771d992973f24aa725d07868b467d1ddfceafb" [[projects]] + digest = "1:1343a2963481a305ca4d051e84bc2abd16b601ee22ed324f8d605de1adb291b0" name = "github.com/bgentry/speakeasy" packages = ["."] + pruneopts = "UT" revision = "4aabc24848ce5fd31929f7d1e4ea74d3709c14cd" version = "v0.1.0" [[projects]] branch = "master" + digest = "1:70f6b224a59b2fa453debffa85c77f71063d8754b90c8c4fbad5794e2c382b0f" name = "github.com/brejski/hid" packages = ["."] + pruneopts = "UT" revision = "06112dcfcc50a7e0e4fd06e17f9791e788fdaafc" [[projects]] branch = "master" + digest = "1:2c00f064ba355903866cbfbf3f7f4c0fe64af6638cc7d1b8bdcf3181bc67f1d8" name = "github.com/btcsuite/btcd" packages = ["btcec"] pruneopts = "UT" revision = "9a2f9524024889e129a5422aca2cff73cb3eabf6" [[projects]] + digest = "1:386de157f7d19259a7f9c81f26ce011223ce0f090353c1152ffdf730d7d10ac2" name = "github.com/btcsuite/btcutil" packages = ["bech32"] + pruneopts = "UT" revision = "d4cc87b860166d00d6b5b9e0d3b3d71d6088d4d4" [[projects]] + digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39" name = "github.com/davecgh/go-spew" packages = ["spew"] + pruneopts = "UT" revision = "346938d642f2ec3594ed81d874461961cd0faa76" version = "v1.1.0" [[projects]] + digest = "1:c7644c73a3d23741fdba8a99b1464e021a224b7e205be497271a8003a15ca41b" name = "github.com/ebuchman/fail-test" packages = ["."] + pruneopts = "UT" revision = "95f809107225be108efcf10a3509e4ea6ceef3c4" [[projects]] + digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd" name = "github.com/fsnotify/fsnotify" packages = ["."] + pruneopts = "UT" revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" version = "v1.4.7" [[projects]] + digest = "1:fdf5169073fb0ad6dc12a70c249145e30f4058647bea25f0abd48b6d9f228a11" name = "github.com/go-kit/kit" packages = [ "log", @@ -62,24 +80,30 @@ "metrics", "metrics/discard", "metrics/internal/lv", - "metrics/prometheus" + "metrics/prometheus", ] + pruneopts = "UT" revision = "4dc7be5d2d12881735283bcab7352178e190fc71" version = "v0.6.0" [[projects]] + digest = "1:31a18dae27a29aa074515e43a443abfd2ba6deb6d69309d8d7ce789c45f34659" name = "github.com/go-logfmt/logfmt" packages = ["."] + pruneopts = "UT" revision = "390ab7935ee28ec6b286364bba9b4dd6410cb3d5" version = "v0.3.0" [[projects]] + digest = "1:c4a2528ccbcabf90f9f3c464a5fc9e302d592861bbfd0b7135a7de8a943d0406" name = "github.com/go-stack/stack" packages = ["."] + pruneopts = "UT" revision = "259ab82a6cad3992b4e21ff5cac294ccb06474bc" version = "v1.7.0" [[projects]] + digest = "1:35621fe20f140f05a0c4ef662c26c0ab4ee50bca78aa30fe87d33120bd28165e" name = "github.com/gogo/protobuf" packages = [ "gogoproto", @@ -87,98 +111,121 @@ "proto", "protoc-gen-gogo/descriptor", "sortkeys", - "types" + "types", ] + pruneopts = "UT" revision = "636bf0302bc95575d69441b25a2603156ffdddf1" version = "v1.1.1" [[projects]] + digest = "1:17fe264ee908afc795734e8c4e63db2accabaf57326dbf21763a7d6b86096260" name = "github.com/golang/protobuf" packages = [ "proto", "ptypes", "ptypes/any", "ptypes/duration", - "ptypes/timestamp" + "ptypes/timestamp", ] + pruneopts = "UT" revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" version = "v1.1.0" [[projects]] branch = "master" + digest = "1:4a0c6bb4805508a6287675fac876be2ac1182539ca8a32468d8128882e9d5009" name = "github.com/golang/snappy" packages = ["."] + pruneopts = "UT" revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" [[projects]] + digest = "1:c79fb010be38a59d657c48c6ba1d003a8aa651fa56b579d959d74573b7dff8e1" name = "github.com/gorilla/context" packages = ["."] + pruneopts = "UT" revision = "08b5f424b9271eedf6f9f0ce86cb9396ed337a42" version = "v1.1.1" [[projects]] + digest = "1:e73f5b0152105f18bc131fba127d9949305c8693f8a762588a82a48f61756f5f" name = "github.com/gorilla/mux" packages = ["."] + pruneopts = "UT" revision = "e3702bed27f0d39777b0b37b664b6280e8ef8fbf" version = "v1.6.2" [[projects]] + digest = "1:43dd08a10854b2056e615d1b1d22ac94559d822e1f8b6fcc92c1a1057e85188e" name = "github.com/gorilla/websocket" packages = ["."] + pruneopts = "UT" revision = "ea4d1f681babbce9545c9c5f3d5194a789c89f5b" version = "v1.2.0" [[projects]] branch = "master" - digest = "1:a361611b8c8c75a1091f00027767f7779b29cb37c456a71b8f2604c88057ab40" + digest = "1:12247a2e99a060cc692f6680e5272c8adf0b8f572e6bce0d7095e624c958a240" name = "github.com/hashicorp/hcl" packages = [ ".", "hcl/ast", "hcl/parser", - "hcl/printer", "hcl/scanner", "hcl/strconv", "hcl/token", "json/parser", "json/scanner", - "json/token" + "json/token", ] + pruneopts = "UT" revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" [[projects]] + digest = "1:870d441fe217b8e689d7949fef6e43efbc787e50f200cb1e70dbca9204a1d6be" name = "github.com/inconshreveable/mousetrap" packages = ["."] + pruneopts = "UT" revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75" version = "v1.0" [[projects]] branch = "master" + digest = "1:39b27d1381a30421f9813967a5866fba35dc1d4df43a6eefe3b7a5444cb07214" name = "github.com/jmhodges/levigo" packages = ["."] + pruneopts = "UT" revision = "c42d9e0ca023e2198120196f842701bb4c55d7b9" [[projects]] branch = "master" + digest = "1:a64e323dc06b73892e5bb5d040ced475c4645d456038333883f58934abbf6f72" name = "github.com/kr/logfmt" packages = ["."] + pruneopts = "UT" revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0" [[projects]] + digest = "1:c568d7727aa262c32bdf8a3f7db83614f7af0ed661474b24588de635c20024c7" name = "github.com/magiconair/properties" packages = ["."] + pruneopts = "UT" revision = "c2353362d570a7bfa228149c62842019201cfb71" version = "v1.8.0" [[projects]] + digest = "1:d4d17353dbd05cb52a2a52b7fe1771883b682806f68db442b436294926bbfafb" name = "github.com/mattn/go-isatty" packages = ["."] + pruneopts = "UT" revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" version = "v0.0.3" [[projects]] + digest = "1:ff5ebae34cfbf047d505ee150de27e60570e8c394b3b8fdbb720ff6ac71985fc" name = "github.com/matttproud/golang_protobuf_extensions" packages = ["pbutil"] + pruneopts = "UT" revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" version = "v1.0.1" @@ -191,29 +238,37 @@ revision = "f15292f7a699fcc1a38a80977f80a046874ba8ac" [[projects]] + digest = "1:95741de3af260a92cc5c7f3f3061e85273f5a81b5db20d4bd68da74bd521675e" name = "github.com/pelletier/go-toml" packages = ["."] + pruneopts = "UT" revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194" version = "v1.2.0" [[projects]] + digest = "1:40e195917a951a8bf867cd05de2a46aaf1806c50cf92eebf4c16f78cd196f747" name = "github.com/pkg/errors" packages = ["."] + pruneopts = "UT" revision = "645ef00459ed84a119197bfb8d8205042c6df63d" version = "v0.8.0" [[projects]] + digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" name = "github.com/pmezard/go-difflib" packages = ["difflib"] + pruneopts = "UT" revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" [[projects]] + digest = "1:c1a04665f9613e082e1209cf288bf64f4068dcd6c87a64bf1c4ff006ad422ba0" name = "github.com/prometheus/client_golang" packages = [ "prometheus", - "prometheus/promhttp" + "prometheus/promhttp", ] + pruneopts = "UT" revision = "ae27198cdd90bf12cd134ad79d1366a6cf49f632" [[projects]] @@ -226,22 +281,15 @@ [[projects]] branch = "master" -<<<<<<< HEAD -======= digest = "1:63b68062b8968092eb86bedc4e68894bd096ea6b24920faca8b9dcf451f54bb5" ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c name = "github.com/prometheus/common" packages = [ "expfmt", "internal/bitbucket.org/ww/goautoneg", - "model" + "model", ] -<<<<<<< HEAD - revision = "7600349dcfe1abd18d72d3a1770870d9800a7801" -======= pruneopts = "UT" revision = "c7de2306084e37d54b8be01f3541a8464345e9a5" ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c [[projects]] branch = "master" @@ -251,66 +299,83 @@ ".", "internal/util", "nfs", - "xfs" + "xfs", ] pruneopts = "UT" revision = "05ee40e3a273f7245e8777337fc7b46e533a9a92" [[projects]] + digest = "1:c4556a44e350b50a490544d9b06e9fba9c286c21d6c0e47f54f3a9214597298c" name = "github.com/rcrowley/go-metrics" packages = ["."] + pruneopts = "UT" revision = "e2704e165165ec55d062f5919b4b29494e9fa790" [[projects]] + digest = "1:bd1ae00087d17c5a748660b8e89e1043e1e5479d0fea743352cda2f8dd8c4f84" name = "github.com/spf13/afero" packages = [ ".", - "mem" + "mem", ] + pruneopts = "UT" revision = "787d034dfe70e44075ccc060d346146ef53270ad" version = "v1.1.1" [[projects]] + digest = "1:516e71bed754268937f57d4ecb190e01958452336fa73dbac880894164e91c1f" name = "github.com/spf13/cast" packages = ["."] + pruneopts = "UT" revision = "8965335b8c7107321228e3e3702cab9832751bac" version = "v1.2.0" [[projects]] + digest = "1:7ffc0983035bc7e297da3688d9fe19d60a420e9c38bef23f845c53788ed6a05e" name = "github.com/spf13/cobra" packages = ["."] + pruneopts = "UT" revision = "7b2c5ac9fc04fc5efafb60700713d4fa609b777b" version = "v0.0.1" [[projects]] branch = "master" + digest = "1:080e5f630945ad754f4b920e60b4d3095ba0237ebf88dc462eb28002932e3805" name = "github.com/spf13/jwalterweatherman" packages = ["."] + pruneopts = "UT" revision = "7c0cea34c8ece3fbeb2b27ab9b59511d360fb394" [[projects]] + digest = "1:9424f440bba8f7508b69414634aef3b2b3a877e522d8a4624692412805407bb7" name = "github.com/spf13/pflag" packages = ["."] + pruneopts = "UT" revision = "583c0c0531f06d5278b7d917446061adc344b5cd" version = "v1.0.1" [[projects]] + digest = "1:f8e1a678a2571e265f4bf91a3e5e32aa6b1474a55cb0ea849750cc177b664d96" name = "github.com/spf13/viper" packages = ["."] + pruneopts = "UT" revision = "25b30aa063fc18e48662b86996252eabdcf2f0c7" version = "v1.0.0" [[projects]] + digest = "1:7e8d267900c7fa7f35129a2a37596e38ed0f11ca746d6d9ba727980ee138f9f6" name = "github.com/stretchr/testify" packages = [ "assert", - "require" + "require", ] + pruneopts = "UT" revision = "12b6f73e6084dad08a7c6e575284b177ecafbc71" version = "v1.2.1" [[projects]] branch = "master" + digest = "1:b3cfb8d82b1601a846417c3f31c03a7961862cb2c98dcf0959c473843e6d9a2b" name = "github.com/syndtr/goleveldb" packages = [ "leveldb", @@ -324,33 +389,41 @@ "leveldb/opt", "leveldb/storage", "leveldb/table", - "leveldb/util" + "leveldb/util", ] + pruneopts = "UT" revision = "c4c61651e9e37fa117f53c5a906d3b63090d8445" [[projects]] branch = "master" + digest = "1:087aaa7920e5d0bf79586feb57ce01c35c830396ab4392798112e8aae8c47722" name = "github.com/tendermint/ed25519" packages = [ ".", "edwards25519", - "extra25519" + "extra25519", ] + pruneopts = "UT" revision = "d8387025d2b9d158cf4efb07e7ebf814bcce2057" [[projects]] + digest = "1:e9113641c839c21d8eaeb2c907c7276af1eddeed988df8322168c56b7e06e0e1" name = "github.com/tendermint/go-amino" packages = ["."] + pruneopts = "UT" revision = "2106ca61d91029c931fd54968c2bb02dc96b1412" version = "0.10.1" [[projects]] + digest = "1:d4a15d404afbf591e8be16fcda7f5ac87948d5c7531f9d909fd84cc730ab16e2" name = "github.com/tendermint/iavl" packages = ["."] + pruneopts = "UT" revision = "35f66e53d9b01e83b30de68b931f54b2477a94c9" version = "v0.9.2" [[projects]] + digest = "1:e10e95fd9f0a3a31686c9696f8995f6c04b0bc1b4ed0562a4f53cddc0b89d059" name = "github.com/tendermint/tendermint" packages = [ "abci/client", @@ -410,18 +483,22 @@ "state/txindex/kv", "state/txindex/null", "types", - "version" + "version", ] + pruneopts = "UT" revision = "5fdbcd70df57b71ffba71e1ff5f00d617852a9c0" version = "v0.22.6" [[projects]] + digest = "1:5bd938386bd1f61a581bf8cd6ff2b7b2f79c542929176db4ceb44965440dae07" name = "github.com/zondax/ledger-goclient" packages = ["."] + pruneopts = "UT" revision = "39ba4728c137c75718a21f9b4b3280fa31b9139b" [[projects]] branch = "master" + digest = "1:65a21a9e051d54eb6a3f70c659a765f706a998d9287c302269f4ed8054b2a852" name = "golang.org/x/crypto" packages = [ "blowfish", @@ -434,12 +511,13 @@ "pbkdf2", "poly1305", "ripemd160", - "salsa20/salsa" + "salsa20/salsa", ] pruneopts = "UT" revision = "c126467f60eb25f8f27e5a981f32a87e3965053f" [[projects]] + digest = "1:d36f55a999540d29b6ea3c2ea29d71c76b1d9853fdcd3e5c5cb4836f2ba118f1" name = "golang.org/x/net" packages = [ "context", @@ -449,8 +527,9 @@ "idna", "internal/timeseries", "netutil", - "trace" + "trace", ] + pruneopts = "UT" revision = "292b43bbf7cb8d35ddf40f8d5100ef3837cced3f" [[projects]] @@ -462,6 +541,7 @@ revision = "bd9dbc187b6e1dacfdd2722a87e83093c2d7bd6e" [[projects]] + digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" name = "golang.org/x/text" packages = [ "collate", @@ -477,8 +557,9 @@ "unicode/bidi", "unicode/cldr", "unicode/norm", - "unicode/rangetable" + "unicode/rangetable", ] + pruneopts = "UT" revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" version = "v0.3.0" @@ -488,13 +569,10 @@ name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] pruneopts = "UT" -<<<<<<< HEAD - revision = "2a72893556e4d1f6c795a4c039314c9fa751eedb" -======= revision = "daca94659cb50e9f37c1b834680f2e46358f10b0" ->>>>>>> 46382994a3db68b17fe69b23bf0af1f377ba4f2c [[projects]] + digest = "1:2dab32a43451e320e49608ff4542fdfc653c95dcc35d0065ec9c6c3dd540ed74" name = "google.golang.org/grpc" packages = [ ".", @@ -521,20 +599,69 @@ "stats", "status", "tap", - "transport" + "transport", ] + pruneopts = "UT" revision = "168a6198bcb0ef175f7dacec0b8691fc141dc9b8" version = "v1.13.0" [[projects]] + digest = "1:342378ac4dcb378a5448dd723f0784ae519383532f5e70ade24132c4c8693202" name = "gopkg.in/yaml.v2" packages = ["."] + pruneopts = "UT" revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" version = "v2.2.1" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "1d36d8462c35a9bd6f5a05cfa5f74bb2e7d532f0594e7e21c24d3105c5652166" + input-imports = [ + "github.com/bartekn/go-bip39", + "github.com/bgentry/speakeasy", + "github.com/btcsuite/btcd/btcec", + "github.com/golang/protobuf/proto", + "github.com/gorilla/mux", + "github.com/mattn/go-isatty", + "github.com/pkg/errors", + "github.com/spf13/cobra", + "github.com/spf13/pflag", + "github.com/spf13/viper", + "github.com/stretchr/testify/assert", + "github.com/stretchr/testify/require", + "github.com/tendermint/go-amino", + "github.com/tendermint/iavl", + "github.com/tendermint/tendermint/abci/server", + "github.com/tendermint/tendermint/abci/types", + "github.com/tendermint/tendermint/cmd/tendermint/commands", + "github.com/tendermint/tendermint/config", + "github.com/tendermint/tendermint/crypto", + "github.com/tendermint/tendermint/crypto/armor", + "github.com/tendermint/tendermint/crypto/ed25519", + "github.com/tendermint/tendermint/crypto/encoding/amino", + "github.com/tendermint/tendermint/crypto/merkle", + "github.com/tendermint/tendermint/crypto/secp256k1", + "github.com/tendermint/tendermint/crypto/tmhash", + "github.com/tendermint/tendermint/crypto/xsalsa20symmetric", + "github.com/tendermint/tendermint/libs/bech32", + "github.com/tendermint/tendermint/libs/cli", + "github.com/tendermint/tendermint/libs/cli/flags", + "github.com/tendermint/tendermint/libs/common", + "github.com/tendermint/tendermint/libs/db", + "github.com/tendermint/tendermint/libs/log", + "github.com/tendermint/tendermint/node", + "github.com/tendermint/tendermint/p2p", + "github.com/tendermint/tendermint/privval", + "github.com/tendermint/tendermint/proxy", + "github.com/tendermint/tendermint/rpc/client", + "github.com/tendermint/tendermint/rpc/core/types", + "github.com/tendermint/tendermint/rpc/lib/client", + "github.com/tendermint/tendermint/rpc/lib/server", + "github.com/tendermint/tendermint/types", + "github.com/tendermint/tendermint/version", + "github.com/zondax/ledger-goclient", + "golang.org/x/crypto/blowfish", + "golang.org/x/crypto/ripemd160", + ] solver-name = "gps-cdcl" solver-version = 1 From 7030081ad202d555b2a06f58feb42759d5a935a2 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 7 Aug 2018 20:59:52 -0400 Subject: [PATCH 42/46] formatting --- client/tx/broadcast.go | 2 +- client/tx/search.go | 4 ++-- x/stake/client/rest/tx.go | 2 +- x/stake/client/rest/utils.go | 14 +++++++------- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/client/tx/broadcast.go b/client/tx/broadcast.go index 69a15184a1ae..89ad48f43f81 100644 --- a/client/tx/broadcast.go +++ b/client/tx/broadcast.go @@ -7,7 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" ) -// BroadcastTxBody Tx Broadcast Body +// Tx Broadcast Body type BroadcastTxBody struct { TxBytes string `json:"tx"` } diff --git a/client/tx/search.go b/client/tx/search.go index 79bb058191f2..adad29d7dd9d 100644 --- a/client/tx/search.go +++ b/client/tx/search.go @@ -23,7 +23,7 @@ const ( flagAny = "any" ) -// Default client command to search through tagged transactions +// default client command to search through tagged transactions func SearchTxCmd(cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "txs", @@ -89,7 +89,7 @@ func searchTxs(cliCtx context.CLIContext, cdc *wire.Codec, tags []string) ([]Inf return info, nil } -// Parse the indexed txs into an array of Info +// parse the indexed txs into an array of Info func FormatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]Info, error) { var err error out := make([]Info, len(res)) diff --git a/x/stake/client/rest/tx.go b/x/stake/client/rest/tx.go index 88f9741252cd..fbefc7f21987 100644 --- a/x/stake/client/rest/tx.go +++ b/x/stake/client/rest/tx.go @@ -52,7 +52,7 @@ type msgCompleteUnbondingInput struct { ValidatorAddr string `json:"validator_addr"` // in bech32 } -// EditDelegationsBody The request body for edit delegations +// the request body for edit delegations type EditDelegationsBody struct { LocalAccountName string `json:"name"` Password string `json:"password"` diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 90ded63dbd14..123b4bc33893 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -16,7 +16,7 @@ import ( rpcclient "github.com/tendermint/tendermint/rpc/client" ) -// contains Checks if the a given query contains one of the tx types +// contains checks if the a given query contains one of the tx types func contains(stringSlice []string, txType string) bool { for _, word := range stringSlice { if word == txType { @@ -29,7 +29,7 @@ func contains(stringSlice []string, txType string) bool { func getDelegatorValidator(cliCtx context.CLIContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAccAddr sdk.AccAddress) ( validator types.BechValidator, httpStatusCode int, errMsg string, err error) { - // Check if the delegator is bonded or redelegated to the validator + // check if the delegator is bonded or redelegated to the validator keyDel := stake.GetDelegationKey(delegatorAddr, validatorAccAddr) // keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAccAddr) @@ -127,7 +127,7 @@ func getDelegatorRedelegations(cliCtx context.CLIContext, cdc *wire.Codec, deleg return redelegations, http.StatusOK, "", nil } -// queryTxs Queries staking txs +// queries staking txs func queryTxs(node rpcclient.Client, cdc *wire.Codec, tag string, delegatorAddr string) ([]tx.Info, error) { page := 0 perPage := 100 @@ -141,7 +141,7 @@ func queryTxs(node rpcclient.Client, cdc *wire.Codec, tag string, delegatorAddr return tx.FormatTxResults(cdc, res.Txs) } -// getValidators Gets all Validators +// gets all validators func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechValidator, error) { validators := make([]types.BechValidator, len(validatorKVs)) for i, kv := range validatorKVs { @@ -161,7 +161,7 @@ func getValidators(validatorKVs []sdk.KVPair, cdc *wire.Codec) ([]types.BechVali return validators, nil } -// Gets a validator given a ValAddress +// gets a validator given a ValAddress func getValidator(address sdk.AccAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (stake.BechValidator, error) { // parse out the validators for _, kv := range validatorKVs { @@ -184,7 +184,7 @@ func getValidator(address sdk.AccAddress, validatorKVs []sdk.KVPair, cdc *wire.C return stake.BechValidator{}, errors.Errorf("Couldn't find validator") } -// Gets a validator given an AccAddress +// gets a validator given an AccAddress func getValidatorFromAccAdrr(address sdk.AccAddress, validatorKVs []sdk.KVPair, cdc *wire.Codec) (stake.BechValidator, error) { // parse out the validators for _, kv := range validatorKVs { @@ -207,7 +207,7 @@ func getValidatorFromAccAdrr(address sdk.AccAddress, validatorKVs []sdk.KVPair, return stake.BechValidator{}, errors.Errorf("Couldn't find validator") } -// Gets all Bech32 validators from a key +// gets all Bech32 validators from a key func getBech32Validators(storeName string, cliCtx context.CLIContext, cdc *wire.Codec) ( validators []types.BechValidator, httpStatusCode int, errMsg string, err error) { // Get all validators using key From a8261a30ede1a42f67814cb4dd0faebe4473607b Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 8 Aug 2018 11:05:09 +0200 Subject: [PATCH 43/46] addressed new comments by Rige --- x/stake/client/rest/query.go | 29 +++++++++-------------------- 1 file changed, 9 insertions(+), 20 deletions(-) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 19809b84617c..c8f5396abe16 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -26,18 +26,20 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Cod delegatorHandlerFn(cliCtx, cdc), ).Methods("GET") - // GET /stake/delegators/{delegatorAddr}/txs // Get all staking txs (i.e msgs) from a delegator + // GET /stake/delegators/{delegatorAddr}/txs?type= // Get all staking txs (i.e msgs) from a delegator r.HandleFunc( "/stake/delegators/{delegatorAddr}/txs", delegatorTxsHandlerFn(cliCtx, cdc), ).Methods("GET") + // TODO Tests // // GET /stake/delegators/{delegatorAddr}/validators // Query all validators that a delegator is bonded to // r.HandleFunc( // "/stake/delegators/{delegatorAddr}/validators", // delegatorValidatorsHandlerFn(cliCtx, cdc), // ).Methods("GET") + // TODO Tests // GET /stake/delegators/{delegatorAddr}/validators/{validatorAddr} // Query a validator that a delegator is bonded to // r.HandleFunc( // "/stake/delegators/{delegatorAddr}/validators", @@ -56,17 +58,6 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Cod unbondingDelegationsHandlerFn(cliCtx, cdc), ).Methods("GET") - /* - GET /stake/delegators/{addr}/validators/{addr}/txs // Get all txs to a validator performed by a delegator - GET /stake/delegators/{addr}/validators/{addr}/txs?type=bond // Get all bonding txs to a validator performed by a delegator - GET /stake/delegators/{addr}/validators/{addr}/txs?type=unbond // Get all unbonding txs to a validator performed by a delegator - GET /stake/delegators/{addr}/validators/{addr}/txs?type=redelegate // Get all redelegation txs to a validator performed by a delegator - */ - // r.HandleFunc( - // "/stake/delegators/{delegatorAddr}/validators/{validatorAddr}/txs", - // stakingTxsHandlerFn(cliCtx, cdc), - // ).Queries("type", "{type}").Methods("GET") - // GET /stake/validators/ r.HandleFunc( "/stake/validators", @@ -78,9 +69,6 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Cod "/stake/validators/{addr}", validatorHandlerFn(cliCtx, cdc), ).Methods("GET") - - // GET /stake/validators/{addr}/delegators - // Don't think this is currently possible without changing keys } // already resolve the rational shares to not handle this in the client @@ -214,21 +202,22 @@ func delegatorTxsHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Hand var txs = []tx.Info{} var actions []string - if isBondTx { + switch { + case isBondTx: actions = append(actions, string(tags.ActionDelegate)) - } else if isUnbondTx { + case isUnbondTx: actions = append(actions, string(tags.ActionBeginUnbonding)) actions = append(actions, string(tags.ActionCompleteUnbonding)) - } else if isRedTx { + case isRedTx: actions = append(actions, string(tags.ActionBeginRedelegation)) actions = append(actions, string(tags.ActionCompleteRedelegation)) - } else if noQuery { + case noQuery: actions = append(actions, string(tags.ActionDelegate)) actions = append(actions, string(tags.ActionBeginUnbonding)) actions = append(actions, string(tags.ActionCompleteUnbonding)) actions = append(actions, string(tags.ActionBeginRedelegation)) actions = append(actions, string(tags.ActionCompleteRedelegation)) - } else { + default: w.WriteHeader(http.StatusNoContent) return } From 9ea4d6df447a74dbcd240611f1f9f41faba97e0f Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 8 Aug 2018 11:35:15 +0200 Subject: [PATCH 44/46] Deleted key comment --- x/stake/client/rest/utils.go | 1 - 1 file changed, 1 deletion(-) diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 123b4bc33893..86e714662861 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -31,7 +31,6 @@ func getDelegatorValidator(cliCtx context.CLIContext, cdc *wire.Codec, delegator // check if the delegator is bonded or redelegated to the validator keyDel := stake.GetDelegationKey(delegatorAddr, validatorAccAddr) - // keyRed := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAccAddr) res, err := cliCtx.QueryStore(keyDel, storeName) if err != nil { From 94c750779c31cec0c18bdacbe181b3394409ad52 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 8 Aug 2018 12:07:26 +0200 Subject: [PATCH 45/46] Deleted comments for TODO in #1939 --- x/stake/client/rest/query.go | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index c8f5396abe16..0eba14aacd6c 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -32,20 +32,6 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Cod delegatorTxsHandlerFn(cliCtx, cdc), ).Methods("GET") - // TODO Tests - // // GET /stake/delegators/{delegatorAddr}/validators // Query all validators that a delegator is bonded to - // r.HandleFunc( - // "/stake/delegators/{delegatorAddr}/validators", - // delegatorValidatorsHandlerFn(cliCtx, cdc), - // ).Methods("GET") - - // TODO Tests - // GET /stake/delegators/{delegatorAddr}/validators/{validatorAddr} // Query a validator that a delegator is bonded to - // r.HandleFunc( - // "/stake/delegators/{delegatorAddr}/validators", - // delegatorValidatorHandlerFn(cliCtx, cdc), - // ).Methods("GET") - // GET /stake/delegators/{delegatorAddr}/delegations/{validatorAddr} // Query a delegation between a delegator and a validator r.HandleFunc( "/stake/delegators/{delegatorAddr}/delegations/{validatorAddr}", @@ -165,6 +151,7 @@ func delegatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Handler } } +// nolint gocyclo // HTTP request handler to query all staking txs (msgs) from a delegator func delegatorTxsHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { From ccb3fcbeabbba02b7d7132e65a4f905eab3ddb73 Mon Sep 17 00:00:00 2001 From: Christopher Goes Date: Wed, 8 Aug 2018 12:20:59 +0200 Subject: [PATCH 46/46] dep ensure -v -update --- Gopkg.lock | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index fbf92d9cc0d7..c69af1c2e1bf 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -34,11 +34,11 @@ [[projects]] branch = "master" - digest = "1:2c00f064ba355903866cbfbf3f7f4c0fe64af6638cc7d1b8bdcf3181bc67f1d8" + digest = "1:6aabc1566d6351115d561d038da82a4c19b46c3b6e17f4a0a2fa60260663dc79" name = "github.com/btcsuite/btcd" packages = ["btcec"] pruneopts = "UT" - revision = "9a2f9524024889e129a5422aca2cff73cb3eabf6" + revision = "cf05f92c3f815bbd5091ed6c73eff51f7b1945e8" [[projects]] digest = "1:386de157f7d19259a7f9c81f26ce011223ce0f090353c1152ffdf730d7d10ac2" @@ -71,7 +71,7 @@ version = "v1.4.7" [[projects]] - digest = "1:fdf5169073fb0ad6dc12a70c249145e30f4058647bea25f0abd48b6d9f228a11" + digest = "1:fa30c0652956e159cdb97dcb2ef8b8db63ed668c02a5c3a40961c8f0641252fe" name = "github.com/go-kit/kit" packages = [ "log", @@ -103,7 +103,7 @@ version = "v1.7.0" [[projects]] - digest = "1:35621fe20f140f05a0c4ef662c26c0ab4ee50bca78aa30fe87d33120bd28165e" + digest = "1:212285efb97b9ec2e20550d81f0446cb7897e57cbdfd7301b1363ab113d8be45" name = "github.com/gogo/protobuf" packages = [ "gogoproto", @@ -118,7 +118,7 @@ version = "v1.1.1" [[projects]] - digest = "1:17fe264ee908afc795734e8c4e63db2accabaf57326dbf21763a7d6b86096260" + digest = "1:cb22af0ed7c72d495d8be1106233ee553898950f15fd3f5404406d44c2e86888" name = "github.com/golang/protobuf" packages = [ "proto", @@ -165,12 +165,13 @@ [[projects]] branch = "master" - digest = "1:12247a2e99a060cc692f6680e5272c8adf0b8f572e6bce0d7095e624c958a240" + digest = "1:ac64f01acc5eeea9dde40e326de6b6471e501392ec06524c3b51033aa50789bc" name = "github.com/hashicorp/hcl" packages = [ ".", "hcl/ast", "hcl/parser", + "hcl/printer", "hcl/scanner", "hcl/strconv", "hcl/token", @@ -262,7 +263,7 @@ version = "v1.0.0" [[projects]] - digest = "1:c1a04665f9613e082e1209cf288bf64f4068dcd6c87a64bf1c4ff006ad422ba0" + digest = "1:98225904b7abff96c052b669b25788f18225a36673fba022fb93514bb9a2a64e" name = "github.com/prometheus/client_golang" packages = [ "prometheus", @@ -273,7 +274,7 @@ [[projects]] branch = "master" - digest = "1:2d5cd61daa5565187e1d96bae64dbbc6080dacf741448e9629c64fd93203b0d4" + digest = "1:0f37e09b3e92aaeda5991581311f8dbf38944b36a3edec61cc2d1991f527554a" name = "github.com/prometheus/client_model" packages = ["go"] pruneopts = "UT" @@ -281,7 +282,7 @@ [[projects]] branch = "master" - digest = "1:63b68062b8968092eb86bedc4e68894bd096ea6b24920faca8b9dcf451f54bb5" + digest = "1:dad2e5a2153ee7a6c9ab8fc13673a16ee4fb64434a7da980965a3741b0c981a3" name = "github.com/prometheus/common" packages = [ "expfmt", @@ -293,7 +294,7 @@ [[projects]] branch = "master" - digest = "1:8c49953a1414305f2ff5465147ee576dd705487c35b15918fcd4efdc0cb7a290" + digest = "1:a37c98f4b7a66bb5c539c0539f0915a74ef1c8e0b3b6f45735289d94cae92bfd" name = "github.com/prometheus/procfs" packages = [ ".", @@ -312,7 +313,7 @@ revision = "e2704e165165ec55d062f5919b4b29494e9fa790" [[projects]] - digest = "1:bd1ae00087d17c5a748660b8e89e1043e1e5479d0fea743352cda2f8dd8c4f84" + digest = "1:37ace7f35375adec11634126944bdc45a673415e2fcc07382d03b75ec76ea94c" name = "github.com/spf13/afero" packages = [ ".", @@ -331,7 +332,7 @@ version = "v1.2.0" [[projects]] - digest = "1:7ffc0983035bc7e297da3688d9fe19d60a420e9c38bef23f845c53788ed6a05e" + digest = "1:627ab2f549a6a55c44f46fa24a4307f4d0da81bfc7934ed0473bf38b24051d26" name = "github.com/spf13/cobra" packages = ["."] pruneopts = "UT" @@ -363,7 +364,7 @@ version = "v1.0.0" [[projects]] - digest = "1:7e8d267900c7fa7f35129a2a37596e38ed0f11ca746d6d9ba727980ee138f9f6" + digest = "1:73697231b93fb74a73ebd8384b68b9a60c57ea6b13c56d2425414566a72c8e6d" name = "github.com/stretchr/testify" packages = [ "assert", @@ -375,7 +376,7 @@ [[projects]] branch = "master" - digest = "1:b3cfb8d82b1601a846417c3f31c03a7961862cb2c98dcf0959c473843e6d9a2b" + digest = "1:922191411ad8f61bcd8018ac127589bb489712c1d1a0ab2497aca4b16de417d2" name = "github.com/syndtr/goleveldb" packages = [ "leveldb", @@ -396,7 +397,7 @@ [[projects]] branch = "master" - digest = "1:087aaa7920e5d0bf79586feb57ce01c35c830396ab4392798112e8aae8c47722" + digest = "1:203b409c21115233a576f99e8f13d8e07ad82b25500491f7e1cca12588fb3232" name = "github.com/tendermint/ed25519" packages = [ ".", @@ -423,7 +424,7 @@ version = "v0.9.2" [[projects]] - digest = "1:e10e95fd9f0a3a31686c9696f8995f6c04b0bc1b4ed0562a4f53cddc0b89d059" + digest = "1:049c779b867a182cea567c65d7c81e3b9e4e4a7eece4c35a19639f75d2aa7da9" name = "github.com/tendermint/tendermint" packages = [ "abci/client", @@ -498,7 +499,7 @@ [[projects]] branch = "master" - digest = "1:65a21a9e051d54eb6a3f70c659a765f706a998d9287c302269f4ed8054b2a852" + digest = "1:e8206c1653e050116ec8c9a823a86413fc9f9ee3c2f3ae977c96d6a1747f7325" name = "golang.org/x/crypto" packages = [ "blowfish", @@ -514,10 +515,10 @@ "salsa20/salsa", ] pruneopts = "UT" - revision = "c126467f60eb25f8f27e5a981f32a87e3965053f" + revision = "f027049dab0ad238e394a753dba2d14753473a04" [[projects]] - digest = "1:d36f55a999540d29b6ea3c2ea29d71c76b1d9853fdcd3e5c5cb4836f2ba118f1" + digest = "1:04dda8391c3e2397daf254ac68003f30141c069b228d06baec8324a5f81dc1e9" name = "golang.org/x/net" packages = [ "context", @@ -534,14 +535,14 @@ [[projects]] branch = "master" - digest = "1:8466957fb2af510f68b13aec64ccad13e9e756dc1da3ea28c422f8ac410e56f0" + digest = "1:4d7a8265af700258feaff86722049eb5b787240d66dfaf45ff4962f09de6e0be" name = "golang.org/x/sys" packages = ["unix"] pruneopts = "UT" - revision = "bd9dbc187b6e1dacfdd2722a87e83093c2d7bd6e" + revision = "acbc56fc7007d2a01796d5bde54f39e3b3e95945" [[projects]] - digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" + digest = "1:7509ba4347d1f8de6ae9be8818b0cd1abc3deeffe28aeaf4be6d4b6b5178d9ca" name = "golang.org/x/text" packages = [ "collate", @@ -572,7 +573,7 @@ revision = "daca94659cb50e9f37c1b834680f2e46358f10b0" [[projects]] - digest = "1:2dab32a43451e320e49608ff4542fdfc653c95dcc35d0065ec9c6c3dd540ed74" + digest = "1:4515e3030c440845b046354fd5d57671238428b820deebce2e9dabb5cd3c51ac" name = "google.golang.org/grpc" packages = [ ".", @@ -616,7 +617,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "71e86b1f1e9ec71901c20d8532dc8477df66eff37a407322379f6a8b03e5d91b" input-imports = [ "github.com/bartekn/go-bip39", "github.com/bgentry/speakeasy",