From c1cb6f1121ad42b8b282a2b14515ddd2f448a080 Mon Sep 17 00:00:00 2001 From: Haifeng Xi Date: Tue, 6 Mar 2018 15:20:56 +0800 Subject: [PATCH 001/124] Initial commit --- README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 000000000..be65b7de3 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# iris-hub +IRIS Hub - a regional Cosmos hub with a powerful iService infrastructure From 2b23f34cc0332b92af126cdc42d13fd0bcf49a9d Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Wed, 7 Mar 2018 18:11:56 +0800 Subject: [PATCH 002/124] add iservice definition --- .gitignore | 2 + LICENSE | 204 +++++++++++++++++++ Makefile | 14 ++ README.md | 2 - cmd/iris/client.go | 102 ++++++++++ cmd/iris/main.go | 50 +++++ cmd/iris/node.go | 71 +++++++ cmd/iris/rest.go | 89 +++++++++ cmd/iris/sh_tests/stake.sh | 276 ++++++++++++++++++++++++++ glide.lock | 305 +++++++++++++++++++++++++++++ glide.yaml | 17 ++ modules/iservice/commands/query.go | 45 +++++ modules/iservice/commands/tx.go | 41 ++++ modules/iservice/errors.go | 23 +++ modules/iservice/handler.go | 185 +++++++++++++++++ modules/iservice/handler_test.go | 50 +++++ modules/iservice/iservice.go | 58 ++++++ modules/iservice/iservice_test.go | 8 + modules/iservice/tx.go | 51 +++++ modules/iservice/tx_test.go | 37 ++++ modules/iservice/types.go | 19 ++ modules/iservice/types_test.go | 15 ++ 22 files changed, 1662 insertions(+), 2 deletions(-) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 Makefile delete mode 100644 README.md create mode 100644 cmd/iris/client.go create mode 100644 cmd/iris/main.go create mode 100644 cmd/iris/node.go create mode 100644 cmd/iris/rest.go create mode 100644 cmd/iris/sh_tests/stake.sh create mode 100644 glide.lock create mode 100644 glide.yaml create mode 100644 modules/iservice/commands/query.go create mode 100644 modules/iservice/commands/tx.go create mode 100644 modules/iservice/errors.go create mode 100644 modules/iservice/handler.go create mode 100644 modules/iservice/handler_test.go create mode 100644 modules/iservice/iservice.go create mode 100644 modules/iservice/iservice_test.go create mode 100644 modules/iservice/tx.go create mode 100644 modules/iservice/tx_test.go create mode 100644 modules/iservice/types.go create mode 100644 modules/iservice/types_test.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..cb756e9ec --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +vendor +.idea \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..9c9fbae55 --- /dev/null +++ b/LICENSE @@ -0,0 +1,204 @@ +Tendermint Basecoin +License: Apache2.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2016 All in Bits, Inc + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Makefile b/Makefile new file mode 100644 index 000000000..01c6f3c5a --- /dev/null +++ b/Makefile @@ -0,0 +1,14 @@ +all: get_vendor_deps install test + +get_vendor_deps: + go get github.com/Masterminds/glide + glide install + +install: + go install ./cmd/iris + +test: + @go test `glide novendor` + +test_cli: + bash ./cmd/iris/sh_tests/stake.sh diff --git a/README.md b/README.md deleted file mode 100644 index be65b7de3..000000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# iris-hub -IRIS Hub - a regional Cosmos hub with a powerful iService infrastructure diff --git a/cmd/iris/client.go b/cmd/iris/client.go new file mode 100644 index 000000000..7ccd967ef --- /dev/null +++ b/cmd/iris/client.go @@ -0,0 +1,102 @@ +package main + +import ( + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client/commands" + "github.com/cosmos/cosmos-sdk/client/commands/commits" + "github.com/cosmos/cosmos-sdk/client/commands/keys" + "github.com/cosmos/cosmos-sdk/client/commands/proxy" + "github.com/cosmos/cosmos-sdk/client/commands/query" + rpccmd "github.com/cosmos/cosmos-sdk/client/commands/rpc" + txcmd "github.com/cosmos/cosmos-sdk/client/commands/txs" + authcmd "github.com/cosmos/cosmos-sdk/modules/auth/commands" + basecmd "github.com/cosmos/cosmos-sdk/modules/base/commands" + coincmd "github.com/cosmos/cosmos-sdk/modules/coin/commands" + feecmd "github.com/cosmos/cosmos-sdk/modules/fee/commands" + ibccmd "github.com/cosmos/cosmos-sdk/modules/ibc/commands" + noncecmd "github.com/cosmos/cosmos-sdk/modules/nonce/commands" + rolecmd "github.com/cosmos/cosmos-sdk/modules/roles/commands" + + stakecmd "github.com/cosmos/gaia/modules/stake/commands" + iservicecmd "github.com/irisnet/iris-hub/modules/iservice/commands" +) + +// clientCmd is the entry point for this binary +var clientCmd = &cobra.Command{ + Use: "client", + Short: "Iris light client", + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} + +func prepareClientCommands() { + commands.AddBasicFlags(clientCmd) + + // Prepare queries + query.RootCmd.AddCommand( + // These are default parsers, but optional in your app (you can remove key) + query.TxQueryCmd, + query.KeyQueryCmd, + coincmd.AccountQueryCmd, + noncecmd.NonceQueryCmd, + rolecmd.RoleQueryCmd, + ibccmd.IBCQueryCmd, + + //stakecmd.CmdQueryValidator, + stakecmd.CmdQueryCandidates, + stakecmd.CmdQueryCandidate, + stakecmd.CmdQueryDelegatorBond, + stakecmd.CmdQueryDelegatorCandidates, + + iservicecmd.CmdQueryServiceDefinition, + ) + + // set up the middleware + txcmd.Middleware = txcmd.Wrappers{ + feecmd.FeeWrapper{}, + rolecmd.RoleWrapper{}, + noncecmd.NonceWrapper{}, + basecmd.ChainWrapper{}, + authcmd.SigWrapper{}, + } + txcmd.Middleware.Register(txcmd.RootCmd.PersistentFlags()) + + // you will always want this for the base send command + txcmd.RootCmd.AddCommand( + // This is the default transaction, optional in your app + coincmd.SendTxCmd, + coincmd.CreditTxCmd, + // this enables creating roles + rolecmd.CreateRoleTxCmd, + // these are for handling ibc + ibccmd.RegisterChainTxCmd, + ibccmd.UpdateChainTxCmd, + ibccmd.PostPacketTxCmd, + + stakecmd.CmdDeclareCandidacy, + stakecmd.CmdEditCandidacy, + stakecmd.CmdDelegate, + stakecmd.CmdUnbond, + + iservicecmd.CmdDefineService, + ) + + clientCmd.AddCommand( + proxy.RootCmd, + lineBreak, + + txcmd.RootCmd, + query.RootCmd, + rpccmd.RootCmd, + lineBreak, + + keys.RootCmd, + commands.InitCmd, + commands.ResetCmd, + commits.RootCmd, + lineBreak, + ) + +} diff --git a/cmd/iris/main.go b/cmd/iris/main.go new file mode 100644 index 000000000..6d652c920 --- /dev/null +++ b/cmd/iris/main.go @@ -0,0 +1,50 @@ +package main + +import ( + "os" + + "github.com/spf13/cobra" + + "github.com/tendermint/tmlibs/cli" + + basecmd "github.com/cosmos/cosmos-sdk/server/commands" + "github.com/cosmos/gaia/version" +) + +// IrisCmd is the entry point for this binary +var ( + IrisCmd = &cobra.Command{ + Use: "iris", + Short: "IRIS Hub - a regional Cosmos Hub with a powerful iService infrastructure", + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, + } + + lineBreak = &cobra.Command{Run: func(*cobra.Command, []string) {}} +) + +func main() { + // disable sorting + cobra.EnableCommandSorting = false + + // add commands + prepareNodeCommands() + prepareRestServerCommands() + prepareClientCommands() + + IrisCmd.AddCommand( + nodeCmd, + restServerCmd, + clientCmd, + + lineBreak, + version.VersionCmd, + //auto.AutoCompleteCmd, + ) + + // prepare and add flags + basecmd.SetUpRoot(IrisCmd) + executor := cli.PrepareMainCmd(IrisCmd, "GA", os.ExpandEnv("$HOME/.iris-cli")) + executor.Execute() +} diff --git a/cmd/iris/node.go b/cmd/iris/node.go new file mode 100644 index 000000000..4ab76e520 --- /dev/null +++ b/cmd/iris/node.go @@ -0,0 +1,71 @@ +package main + +import ( + "github.com/spf13/cobra" + + abci "github.com/tendermint/abci/types" + + sdk "github.com/cosmos/cosmos-sdk" + "github.com/cosmos/cosmos-sdk/modules/auth" + "github.com/cosmos/cosmos-sdk/modules/base" + "github.com/cosmos/cosmos-sdk/modules/coin" + "github.com/cosmos/cosmos-sdk/modules/fee" + "github.com/cosmos/cosmos-sdk/modules/ibc" + "github.com/cosmos/cosmos-sdk/modules/nonce" + "github.com/cosmos/cosmos-sdk/modules/roles" + basecmd "github.com/cosmos/cosmos-sdk/server/commands" + "github.com/cosmos/cosmos-sdk/stack" + "github.com/cosmos/cosmos-sdk/state" + + "github.com/cosmos/gaia/modules/stake" + "github.com/irisnet/iris-hub/modules/iservice" +) + +// nodeCmd is the entry point for this binary +var nodeCmd = &cobra.Command{ + Use: "node", + Short: "The Cosmos Network delegation-game blockchain test", + Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, +} + +func prepareNodeCommands() { + + basecmd.Handler = stack.New( + base.Logger{}, + stack.Recovery{}, + auth.Signatures{}, + base.Chain{}, + stack.Checkpoint{OnCheck: true}, + nonce.ReplayCheck{}, + ). + IBC(ibc.NewMiddleware()). + Apps( + roles.NewMiddleware(), + fee.NewSimpleFeeMiddleware(coin.Coin{"fermion", 0}, fee.Bank), + stack.Checkpoint{OnDeliver: true}, + ). + Dispatch( + coin.NewHandler(), + stack.WrapHandler(roles.NewHandler()), + stack.WrapHandler(ibc.NewHandler()), + stake.NewHandler(), + iservice.NewHandler(), + ) + + nodeCmd.AddCommand( + basecmd.GetInitCmd("fermion", []string{"stake/allowed_bond_denom/fermion"}), + basecmd.GetTickStartCmd(sdk.TickerFunc(tickFn)), + basecmd.UnsafeResetAllCmd, + ) +} + +// Tick - Called every block even if no transaction, process all queues, +// validator rewards, and calculate the validator set difference +func tickFn(ctx sdk.Context, store state.SimpleDB) (change []abci.Validator, err error) { + // first need to prefix the store, at this point it's a global store + store = stack.PrefixedStore(stake.Name(), store) + + // execute Tick + change, err = stake.UpdateValidatorSet(store) + return +} diff --git a/cmd/iris/rest.go b/cmd/iris/rest.go new file mode 100644 index 000000000..45c8c5ff2 --- /dev/null +++ b/cmd/iris/rest.go @@ -0,0 +1,89 @@ +package main + +import ( + "fmt" + "log" + "net/http" + + "github.com/gorilla/mux" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/tendermint/tmlibs/cli" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/commands" + rest "github.com/cosmos/cosmos-sdk/client/rest" + coinrest "github.com/cosmos/cosmos-sdk/modules/coin/rest" + noncerest "github.com/cosmos/cosmos-sdk/modules/nonce/rest" + rolerest "github.com/cosmos/cosmos-sdk/modules/roles/rest" + + stakerest "github.com/cosmos/gaia/modules/stake/rest" +) + +const defaultAlgo = "ed25519" + +var ( + restServerCmd = &cobra.Command{ + Use: "rest-server", + Short: "REST client for iris commands", + Long: `Irisserver presents a nice (not raw hex) interface to the iris blockchain structure.`, + RunE: func(cmd *cobra.Command, args []string) error { + return cmdRestServer(cmd, args) + }, + } + + flagPort = "port" +) + +func prepareRestServerCommands() { + commands.AddBasicFlags(restServerCmd) + restServerCmd.PersistentFlags().IntP(flagPort, "p", 8998, "port to run the server on") +} + +func cmdRestServer(cmd *cobra.Command, args []string) error { + router := mux.NewRouter() + + rootDir := viper.GetString(cli.HomeFlag) + keyMan := client.GetKeyManager(rootDir) + serviceKeys := rest.NewServiceKeys(keyMan) + serviceTxs := rest.NewServiceTxs(commands.GetNode()) + + routeRegistrars := []func(*mux.Router) error{ + // rest.Keys handlers + serviceKeys.RegisterCRUD, + + // Coin handlers (Send, Query, SearchSent) + coinrest.RegisterAll, + + // Roles createRole handler + rolerest.RegisterCreateRole, + + // Iris sign transactions handler + serviceKeys.RegisterSignTx, + // Iris post transaction handler + serviceTxs.RegisterPostTx, + + // Nonce query handler + noncerest.RegisterQueryNonce, + + // Staking query handlers + stakerest.RegisterQueryCandidate, + stakerest.RegisterQueryCandidates, + stakerest.RegisterQueryDelegatorBond, + stakerest.RegisterQueryDelegatorCandidates, + // Staking tx builders + stakerest.RegisterDelegate, + stakerest.RegisterUnbond, + } + + for _, routeRegistrar := range routeRegistrars { + if err := routeRegistrar(router); err != nil { + log.Fatal(err) + } + } + + addr := fmt.Sprintf(":%d", viper.GetInt(flagPort)) + + log.Printf("Serving on %q", addr) + return http.ListenAndServe(addr, router) +} diff --git a/cmd/iris/sh_tests/stake.sh b/cmd/iris/sh_tests/stake.sh new file mode 100644 index 000000000..6682ec347 --- /dev/null +++ b/cmd/iris/sh_tests/stake.sh @@ -0,0 +1,276 @@ +#!/bin/bash +set -u + +# These global variables are required for common.sh +SERVER_EXE="iris node --log_level=debug" +CLIENT_EXE="iris client" +ACCOUNTS=(jae ethan bucky rigel igor) +RICH=${ACCOUNTS[0]} +DELEGATOR=${ACCOUNTS[2]} +POOR=${ACCOUNTS[4]} + +BASE_DIR=$HOME/stake_test +BASE_DIR2=$HOME/stake_test2 +SERVER1=$BASE_DIR/server +SERVER2=$BASE_DIR2/server + +oneTimeSetUp() { + #[ "$2" ] || echo "missing parameters, line=${LINENO}" ; exit 1; + + + # These are passed in as args + CHAIN_ID="stake_test" + + # TODO Make this more robust + if [ "$BASE_DIR" == "$HOME/" ]; then + echo "Must be called with argument, or it will wipe your home directory" + exit 1 + fi + + rm -rf $BASE_DIR 2>/dev/null + mkdir -p $BASE_DIR + + if [ "$BASE_DIR2" == "$HOME/" ]; then + echo "Must be called with argument, or it will wipe your home directory" + exit 1 + fi + rm -rf $BASE_DIR2 2>/dev/null + mkdir -p $BASE_DIR2 + + # Set up client - make sure you use the proper prefix if you set + # a custom CLIENT_EXE + export BC_HOME=${BASE_DIR}/client + prepareClient + + # start the node server + set +u ; initServer $BASE_DIR $CHAIN_ID ; set -u + if [ $? != 0 ]; then return 1; fi + + set +u ; initClient $CHAIN_ID ; set -u + if [ $? != 0 ]; then return 1; fi + + printf "...Testing may begin!\n\n\n" + +} + +oneTimeTearDown() { + kill -9 $PID_SERVER2 >/dev/null 2>&1 + set +u ; quickTearDown ; set -u +} + +# XXX Ex Usage: checkCandidate $PUBKEY $EXPECTED_VOTING_POWER +checkCandidate() { + CANDIDATE=$(${CLIENT_EXE} query candidate --pubkey=$1) + if ! assertTrue "line=${LINENO}, bad query" $?; then + return 1 + fi + assertEquals "line=${LINENO}, proper voting power" "$2" $(echo $CANDIDATE | jq .data.voting_power) + return $? +} + +# XXX Ex Usage: checkCandidate $PUBKEY +checkCandidateEmpty() { + CANDIDATE=$(${CLIENT_EXE} query candidate --pubkey=$1 2>/dev/null) + if ! assertFalse "line=${LINENO}, expected empty query" $?; then + return 1 + fi +} + +# XXX Ex Usage: checkCandidate $DELEGATOR_ADDR $PUBKEY $EXPECTED_SHARES +checkDelegatorBond() { + BOND=$(${CLIENT_EXE} query delegator-bond --delegator-address=$1 --pubkey=$2) + if ! assertTrue "line=${LINENO}, account must exist" $?; then + return 1 + fi + assertEquals "line=${LINENO}, proper bond amount" "$3" $(echo $BOND | jq .data.Shares) + return $? +} + +# XXX Ex Usage: checkCandidate $DELEGATOR_ADDR $PUBKEY +checkDelegatorBondEmpty() { + BOND=$(${CLIENT_EXE} query delegator-bond --delegator-address=$1 --pubkey=$2 2>/dev/null) + if ! assertFalse "line=${LINENO}, expected empty query" $?; then + return 1 + fi +} + +#______________________________________________________________________________________ + +test00GetAccount() { + SENDER=$(getAddr $RICH) + RECV=$(getAddr $POOR) + + assertFalse "line=${LINENO}, requires arg" "${CLIENT_EXE} query account" + + set +u ; checkAccount $SENDER "9007199254740992" ; set -u + + ACCT2=$(${CLIENT_EXE} query account $RECV 2>/dev/null) + assertFalse "line=${LINENO}, has no genesis account" $? +} + +test01SendTx() { + assertFalse "line=${LINENO}, missing dest" "${CLIENT_EXE} tx send --amount=992fermion --sequence=1" + assertFalse "line=${LINENO}, bad password" "echo foo | ${CLIENT_EXE} tx send --amount=992fermion --sequence=1 --to=$RECV --name=$RICH" + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx send --amount=992fermion --sequence=1 --to=$RECV --name=$RICH) + txSucceeded $? "$TX" "$RECV" + HASH=$(echo $TX | jq .hash | tr -d \") + TX_HEIGHT=$(echo $TX | jq .height) + + set +u + checkAccount $SENDER "9007199254740000" $TX_HEIGHT + # make sure 0x prefix also works + checkAccount "0x$SENDER" "9007199254740000" $TX_HEIGHT + checkAccount $RECV "992" $TX_HEIGHT + + # Make sure tx is indexed + checkSendTx $HASH $TX_HEIGHT $SENDER "992" + set -u +} + +test02DeclareCandidacy() { + + # the premise of this test is to run a second validator (from rich) and then bond and unbond some tokens + # first create a second node to run and connect to the system + + # init the second node + SERVER_LOG2=$BASE_DIR2/node2.log + GENKEY=$(${CLIENT_EXE} keys get ${RICH} | awk '{print $2}') + ${SERVER_EXE} init $GENKEY --chain-id $CHAIN_ID --home=$SERVER2 >>$SERVER_LOG2 + if [ $? != 0 ]; then return 1; fi + + # copy in the genesis from the first initialization to the new server + cp $SERVER1/config/genesis.json $SERVER2/config/genesis.json + + # point the new config to the old server location + rm $SERVER2/config/config.toml + echo 'proxy_app = "tcp://127.0.0.1:46668" + moniker = "anonymous" + fast_sync = true + db_backend = "leveldb" + log_level = "state:info,*:error" + + [rpc] + laddr = "tcp://0.0.0.0:46667" + + [p2p] + laddr = "tcp://0.0.0.0:46666" + seeds = "0.0.0.0:46656"' >$SERVER2/config/config.toml + + # start the second node + ${SERVER_EXE} start --home=$SERVER2 >>$SERVER_LOG2 2>&1 & + sleep 1 + PID_SERVER2=$! + disown + if ! ps $PID_SERVER2 >/dev/null; then + echo "**FAILED**" + cat $SERVER_LOG2 + return 1 + fi + + # get the pubkey of the second validator + PK2=$(cat $SERVER2/config/priv_validator.json | jq -r .pub_key.data) + + CAND_ADDR=$(getAddr $POOR) + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx declare-candidacy --sequence=1 --amount=2fermion --name=$POOR --pubkey=$PK2 --moniker=rigey) + if [ $? != 0 ]; then return 1; fi + HASH=$(echo $TX | jq .hash | tr -d \") + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $CAND_ADDR "990" $TX_HEIGHT ; set -u + checkCandidate $PK2 "2" + checkDelegatorBond $CAND_ADDR $PK2 "2" +} + +test03Delegate() { + # send some coins to a delegator + DELA_ADDR=$(getAddr $DELEGATOR) + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx send --sequence=2 --amount=5fermion --to=$DELA_ADDR --name=$RICH) + txSucceeded $? "$TX" "$DELA_ADDR" + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "5" $TX_HEIGHT ; set -u + + # delegate some coins to the new + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=1 --amount=1fermion --name=$DELEGATOR --pubkey=$PK2) + if [ $? != 0 ]; then return 1; fi + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "4" $TX_HEIGHT ; set -u + checkCandidate $PK2 "3" + checkDelegatorBond $DELA_ADDR $PK2 "1" + + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=2 --amount=2fermion --name=$DELEGATOR --pubkey=$PK2) + if [ $? != 0 ]; then return 1; fi + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u + checkCandidate $PK2 "5" + checkDelegatorBond $DELA_ADDR $PK2 "3" + + # attempt a delegation without enough funds + # NOTE the sequence number still increments here because it will fail + # only during DeliverTx - however this should be updated (TODO) in new + # SDK when we can fail in CheckTx + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=3 --amount=3fermion --name=$DELEGATOR --pubkey=$PK2 2>/dev/null) + if [ $? == 0 ]; then return 1; fi + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u + checkCandidate $PK2 "5" + checkDelegatorBond $DELA_ADDR $PK2 "3" + + # perform the final delegation which should empty the delegators account + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=4 --amount=2fermion --name=$DELEGATOR --pubkey=$PK2) + if [ $? != 0 ]; then return 1; fi + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "null" $TX_HEIGHT ; set -u #empty account is null + checkCandidate $PK2 "7" + checkDelegatorBond $DELA_ADDR $PK2 "5" +} + +test04Unbond() { + # unbond from the delegator a bit + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=5 --shares=2 --name=$DELEGATOR --pubkey=$PK2) + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u + checkCandidate $PK2 "5" + checkDelegatorBond $DELA_ADDR $PK2 "3" + + # attempt to unbond more shares than exist + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=6 --shares=10 --name=$DELEGATOR --pubkey=$PK2 2>/dev/null) + if [ $? == 0 ]; then return 1; fi + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u + checkCandidate $PK2 "5" + checkDelegatorBond $DELA_ADDR $PK2 "3" + + # unbond entirely from the delegator + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=6 --shares=3 --name=$DELEGATOR --pubkey=$PK2) + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "5" $TX_HEIGHT ; set -u + checkCandidate $PK2 "2" + checkDelegatorBondEmpty $DELA_ADDR $PK2 + + # unbond a bit from the owner + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=2 --shares=1 --name=$POOR --pubkey=$PK2) + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $CAND_ADDR "991" $TX_HEIGHT ; set -u + checkCandidate $PK2 "1" + checkDelegatorBond $CAND_ADDR $PK2 "1" + + # attempt to unbond more shares than exist + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=3 --shares=10 --name=$POOR --pubkey=$PK2 2>/dev/null) + if [ $? == 0 ]; then return 1; fi + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $CAND_ADDR "991" $TX_HEIGHT ; set -u + checkCandidate $PK2 "1" + checkDelegatorBond $CAND_ADDR $PK2 "1" + + # unbond entirely from the validator + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=3 --shares=1 --name=$POOR --pubkey=$PK2) + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $CAND_ADDR "992" $TX_HEIGHT ; set -u + checkCandidateEmpty $PK2 + checkDelegatorBondEmpty $CAND_ADDR $PK2 +} + +# Load common then run these tests with shunit2! +CLI_DIR=$GOPATH/src/github.com/cosmos/gaia/vendor/github.com/cosmos/cosmos-sdk/tests/cli + +. $CLI_DIR/common.sh +. $CLI_DIR/shunit2 diff --git a/glide.lock b/glide.lock new file mode 100644 index 000000000..aa50d9ced --- /dev/null +++ b/glide.lock @@ -0,0 +1,305 @@ +hash: 20e25ba77f4c08127c8b87786d0bb7d3868e6c8a0bfe9f80f63ce831b25663ec +updated: 2018-03-07T11:54:26.85382+08:00 +imports: +- name: github.com/bgentry/speakeasy + version: 4aabc24848ce5fd31929f7d1e4ea74d3709c14cd +- name: github.com/btcsuite/btcd + version: 2e60448ffcc6bf78332d1fe590260095f554dd78 + subpackages: + - btcec +- name: github.com/BurntSushi/toml + version: b26d9c308763d68093482582cea63d69be07a0f0 +- name: github.com/cosmos/cosmos-sdk + version: f1b1d36324812dc221da87f56734a5c25d8754aa + subpackages: + - app + - client + - client/commands + - client/commands/commits + - client/commands/keys + - client/commands/proxy + - client/commands/query + - client/commands/rpc + - client/commands/search + - client/commands/txs + - client/rest + - errors + - genesis + - modules/auth + - modules/auth/commands + - modules/base + - modules/base/commands + - modules/coin + - modules/coin/commands + - modules/coin/rest + - modules/fee + - modules/fee/commands + - modules/ibc + - modules/ibc/commands + - modules/nonce + - modules/nonce/commands + - modules/nonce/rest + - modules/roles + - modules/roles/commands + - modules/roles/rest + - server/commands + - stack + - state + - version +- name: github.com/cosmos/gaia + version: 2ac7ed920446ef8edf582c2b3e890cb7676a7d77 + subpackages: + - modules/stake + - modules/stake/commands + - modules/stake/rest + - version +- name: github.com/ebuchman/fail-test + version: 95f809107225be108efcf10a3509e4ea6ceef3c4 +- name: github.com/fsnotify/fsnotify + version: 4da3e2cfbabc9f751898f250b49f2439785783a1 +- name: github.com/go-kit/kit + version: 4dc7be5d2d12881735283bcab7352178e190fc71 + subpackages: + - log + - log/level + - log/term +- name: github.com/go-logfmt/logfmt + version: 390ab7935ee28ec6b286364bba9b4dd6410cb3d5 +- name: github.com/go-playground/locales + version: e4cbcb5d0652150d40ad0646651076b6bd2be4f6 + subpackages: + - currency +- name: github.com/go-playground/universal-translator + version: 71201497bace774495daed26a3874fd339e0b538 +- name: github.com/go-stack/stack + version: 259ab82a6cad3992b4e21ff5cac294ccb06474bc +- name: github.com/gogo/protobuf + version: 1adfc126b41513cc696b209667c8656ea7aac67c + subpackages: + - gogoproto + - jsonpb + - proto + - protoc-gen-gogo/descriptor + - sortkeys + - types +- name: github.com/golang/protobuf + version: 925541529c1fa6821df4e44ce2723319eb2be768 + subpackages: + - proto + - ptypes + - ptypes/any + - ptypes/duration + - ptypes/timestamp +- name: github.com/golang/snappy + version: 553a641470496b2327abcac10b36396bd98e45c9 +- name: github.com/gorilla/context + version: 08b5f424b9271eedf6f9f0ce86cb9396ed337a42 +- name: github.com/gorilla/mux + version: 53c1911da2b537f792e7cafcb446b05ffe33b996 +- name: github.com/gorilla/websocket + version: ea4d1f681babbce9545c9c5f3d5194a789c89f5b +- name: github.com/hashicorp/hcl + version: 23c074d0eceb2b8a5bfdbb271ab780cde70f05a8 + subpackages: + - hcl/ast + - hcl/parser + - hcl/scanner + - hcl/strconv + - hcl/token + - json/parser + - json/scanner + - json/token +- name: github.com/howeyc/crc16 + version: 2b2a61e366a66d3efb279e46176e7291001e0354 +- name: github.com/inconshreveable/mousetrap + version: 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 +- name: github.com/jmhodges/levigo + version: c42d9e0ca023e2198120196f842701bb4c55d7b9 +- name: github.com/kr/logfmt + version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0 +- name: github.com/magiconair/properties + version: 49d762b9817ba1c2e9d0c69183c2b4a8b8f1d934 +- name: github.com/mattn/go-isatty + version: 0360b2af4f38e8d38c7fce2a9f4e702702d73a39 +- name: github.com/mitchellh/mapstructure + version: 06020f85339e21b2478f756a78e295255ffa4d6a +- name: github.com/pelletier/go-toml + version: 4e9e0ee19b60b13eb79915933f44d8ed5f268bdd +- name: github.com/pkg/errors + version: 645ef00459ed84a119197bfb8d8205042c6df63d +- name: github.com/rcrowley/go-metrics + version: e181e095bae94582363434144c61a9653aff6e50 +- name: github.com/spf13/afero + version: 8d919cbe7e2627e417f3e45c3c0e489a5b7e2536 + subpackages: + - mem +- name: github.com/spf13/cast + version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 +- name: github.com/spf13/cobra + version: 7b2c5ac9fc04fc5efafb60700713d4fa609b777b +- name: github.com/spf13/jwalterweatherman + version: 12bd96e66386c1960ab0f74ced1362f66f552f7b +- name: github.com/spf13/pflag + version: e57e3eeb33f795204c1ca35f56c44f83227c6e66 +- name: github.com/spf13/viper + version: 25b30aa063fc18e48662b86996252eabdcf2f0c7 +- name: github.com/syndtr/goleveldb + version: adf24ef3f94bd13ec4163060b21a5678f22b429b + subpackages: + - leveldb + - leveldb/cache + - leveldb/comparer + - leveldb/errors + - leveldb/filter + - leveldb/iterator + - leveldb/journal + - leveldb/memdb + - leveldb/opt + - leveldb/storage + - leveldb/table + - leveldb/util +- name: github.com/tendermint/abci + version: 3d5f0a8b94bbbfa70ecd4072fc55854f8210425b + subpackages: + - client + - example/code + - example/kvstore + - server + - types +- name: github.com/tendermint/ed25519 + version: d8387025d2b9d158cf4efb07e7ebf814bcce2057 + subpackages: + - edwards25519 + - extra25519 +- name: github.com/tendermint/go-crypto + version: 2017856384589234024cda848a6332157d1f527c + subpackages: + - keys + - keys/cryptostore + - keys/storage/filestorage + - keys/wordlist +- name: github.com/tendermint/go-wire + version: b6fc872b42d41158a60307db4da051dd6f179415 + subpackages: + - data +- name: github.com/tendermint/iavl + version: 39de8f0b4ee758fdd5bb3a9afc6dd9bf42c04785 +- name: github.com/tendermint/tendermint + version: 9c5937df969de23e9087f183c52b5088d4b6f268 + subpackages: + - blockchain + - cmd/tendermint/commands + - config + - consensus + - consensus/types + - evidence + - lite + - lite/client + - lite/errors + - lite/files + - lite/proxy + - mempool + - node + - p2p + - p2p/conn + - p2p/pex + - p2p/trust + - p2p/upnp + - proxy + - rpc/client + - rpc/core + - rpc/core/types + - rpc/grpc + - rpc/lib + - rpc/lib/client + - rpc/lib/server + - rpc/lib/types + - state + - state/txindex + - state/txindex/kv + - state/txindex/null + - types + - version +- name: github.com/tendermint/tmlibs + version: 26f2ab65f82cfc6873c312e8030104c47c05f10e + subpackages: + - autofile + - cli + - cli/flags + - clist + - common + - db + - flowrate + - log + - merkle + - pubsub + - pubsub/query +- name: golang.org/x/crypto + version: 94eea52f7b742c7cbe0b03b22f0c4c8631ece122 + subpackages: + - curve25519 + - nacl/box + - nacl/secretbox + - openpgp/armor + - openpgp/errors + - poly1305 + - ripemd160 + - salsa20/salsa +- name: golang.org/x/net + version: 5ccada7d0a7ba9aeb5d3aca8d3501b4c2a509fec + subpackages: + - context + - http2 + - http2/hpack + - idna + - internal/timeseries + - lex/httplex + - trace +- name: golang.org/x/sys + version: 8b4580aae2a0dd0c231a45d3ccb8434ff533b840 + subpackages: + - unix +- name: golang.org/x/text + version: 57961680700a5336d15015c8c50686ca5ba362a4 + subpackages: + - secure/bidirule + - transform + - unicode/bidi + - unicode/norm +- name: google.golang.org/genproto + version: a8101f21cf983e773d0c1133ebc5424792003214 + repo: https://github.com/google/go-genproto + vcs: git + subpackages: + - googleapis/rpc/status +- name: google.golang.org/grpc + version: 401e0e00e4bb830a10496d64cd95e068c5bf50de + repo: https://github.com/grpc/grpc-go + vcs: git + subpackages: + - balancer + - codes + - connectivity + - credentials + - grpclb/grpc_lb_v1/messages + - grpclog + - internal + - keepalive + - metadata + - naming + - peer + - resolver + - stats + - status + - tap + - transport +- name: gopkg.in/go-playground/validator.v9 + version: 1b8c8e19cd250435025214492d9a08411d760fdd +- name: gopkg.in/yaml.v2 + version: 287cf08546ab5e7e37d55a84f7ed3fd1db036de5 +testImports: +- name: github.com/stretchr/testify + version: 2aa2c176b9dab406a6970f6a55f513e8a8c8b18f + subpackages: + - assert + - require diff --git a/glide.yaml b/glide.yaml new file mode 100644 index 000000000..92b323dee --- /dev/null +++ b/glide.yaml @@ -0,0 +1,17 @@ +package: github.com/irisnet/iris-hub +import: +- package: github.com/cosmos/iris + version: develop +- package: github.com/cosmos/cosmos-sdk + version: tm-develop +- package: google.golang.org/grpc + repo: https://github.com/grpc/grpc-go + vcs: git +- package: google.golang.org/genproto + repo: https://github.com/google/go-genproto + vcs: git +testImport: +- package: github.com/stretchr/testify + subpackages: + - assert + - require diff --git a/modules/iservice/commands/query.go b/modules/iservice/commands/query.go new file mode 100644 index 000000000..bd57d4595 --- /dev/null +++ b/modules/iservice/commands/query.go @@ -0,0 +1,45 @@ +package commands + +import ( + "github.com/spf13/cobra" + flag "github.com/spf13/pflag" + "github.com/spf13/viper" + + "github.com/cosmos/cosmos-sdk/client/commands" + "github.com/cosmos/cosmos-sdk/client/commands/query" + "github.com/cosmos/cosmos-sdk/stack" + "github.com/irisnet/iris-hub/modules/iservice" +) + +//nolint +var ( + CmdQueryServiceDefinition = &cobra.Command{ + Use: "service-definition", + RunE: cmdQueryServiceDefinition, + Short: "Query a service definition based on name", + } + + FlagServiceName = "svc-name" +) + +func init() { + //Add Flags + fsSn := flag.NewFlagSet("", flag.ContinueOnError) + fsSn.String(FlagServiceName, "", "Name of the service") + + CmdQueryServiceDefinition.Flags().AddFlagSet(fsSn) +} + +func cmdQueryServiceDefinition(cmd *cobra.Command, args []string) error { + + name := viper.GetString(FlagServiceName) + prove := !viper.GetBool(commands.FlagTrustNode) + key := stack.PrefixedKey(iservice.Name(), iservice.GetServiceDefinitionKey(name)) + var svc iservice.ServiceDefinition + height, err := query.GetParsed(key, &svc, query.GetHeight(), prove) + if err != nil { + return err + } + + return query.OutputProof(svc, height) +} diff --git a/modules/iservice/commands/tx.go b/modules/iservice/commands/tx.go new file mode 100644 index 000000000..4da259d90 --- /dev/null +++ b/modules/iservice/commands/tx.go @@ -0,0 +1,41 @@ +package commands + +import ( + txcmd "github.com/cosmos/cosmos-sdk/client/commands/txs" + "github.com/irisnet/iris-hub/modules/iservice" + "github.com/spf13/cobra" + flag "github.com/spf13/pflag" + "github.com/spf13/viper" +) + +// nolint +const ( + FlagName = "svc-name" + FlagDescription = "svc-description" +) + +// nolint +var ( + CmdDefineService = &cobra.Command{ + Use: "define-service", + Short: "define a new service", + RunE: cmdDefineService, + } +) + +func init() { + + fsService := flag.NewFlagSet("", flag.ContinueOnError) + fsService.String(FlagName, "", "service name") + fsService.String(FlagDescription, "", "service description") + + CmdDefineService.Flags().AddFlagSet(fsService) +} + +func cmdDefineService(cmd *cobra.Command, args []string) error { + name := viper.GetString(FlagName) + desc := viper.GetString(FlagDescription) + + tx := iservice.NewTxDefineService(name, desc) + return txcmd.DoTx(tx) +} diff --git a/modules/iservice/errors.go b/modules/iservice/errors.go new file mode 100644 index 000000000..8b584e752 --- /dev/null +++ b/modules/iservice/errors.go @@ -0,0 +1,23 @@ +// nolint +package iservice + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/errors" +) + +var ( + errServiceNameEmpty = fmt.Errorf("Invalid service name") + errServiceDescEmpty = fmt.Errorf("Invalid service description") + errServiceExists = fmt.Errorf("Service already exists") + + invalidInput = errors.CodeTypeBaseInvalidInput +) + +func ErrServiceExists() error { + return errors.WithCode(errServiceExists, errors.CodeTypeBaseInvalidInput) +} +func ErrMissingSignature() error { + return errors.ErrMissingSignature() +} diff --git a/modules/iservice/handler.go b/modules/iservice/handler.go new file mode 100644 index 000000000..1897e42b0 --- /dev/null +++ b/modules/iservice/handler.go @@ -0,0 +1,185 @@ +package iservice + +import ( + "fmt" + "strconv" + + "github.com/tendermint/tmlibs/log" + + "github.com/cosmos/cosmos-sdk" + "github.com/cosmos/cosmos-sdk/errors" + "github.com/cosmos/cosmos-sdk/modules/auth" + "github.com/cosmos/cosmos-sdk/stack" + "github.com/cosmos/cosmos-sdk/state" +) + +// nolint +const iserviceModuleName = "iservice" + +// Name is the name of the modules. +func Name() string { + return iserviceModuleName +} + +//_______________________________________________________________________ + +// Handler - the transaction processing handler +type Handler struct { + stack.PassInitValidate +} + +var _ stack.Dispatchable = Handler{} // enforce interface at compile time + +// NewHandler returns a new Handler with the default Params +func NewHandler() Handler { + return Handler{} +} + +// Name - return iservice namespace +func (Handler) Name() string { + return iserviceModuleName +} + +// AssertDispatcher - placeholder for stack.Dispatchable +func (Handler) AssertDispatcher() {} + +// InitState - set genesis parameters for iservice +func (h Handler) InitState(l log.Logger, store state.SimpleDB, + module, key, value string, cb sdk.InitStater) (log string, err error) { + return "", h.initState(module, key, value, store) +} + +// separated for testing +func (Handler) initState(module, key, value string, store state.SimpleDB) error { + if module != iserviceModuleName { + return errors.ErrUnknownModule(module) + } + + params := loadParams(store) + switch key { + case "gas_define_service": + + // TODO: enforce non-negative integers in input + i, err := strconv.Atoi(value) + if err != nil { + return fmt.Errorf("input must be integer, Error: %v", err.Error()) + } + params.GasDefineService = int64(i) + default: + return errors.ErrUnknownKey(key) + } + + saveParams(store, params) + return nil +} + +// CheckTx checks if the tx is properly structured +func (h Handler) CheckTx(ctx sdk.Context, store state.SimpleDB, + tx sdk.Tx, _ sdk.Checker) (res sdk.CheckResult, err error) { + + err = tx.ValidateBasic() + if err != nil { + return res, err + } + + // get the sender + sender, err := getTxSender(ctx) + if err != nil { + return res, err + } + + params := loadParams(store) + + // create the new checker object to + checker := check{ + store: store, + sender: sender, + } + + // return the fee for each tx type + switch txInner := tx.Unwrap().(type) { + case TxDefineService: + return sdk.NewCheck(params.GasDefineService, ""), + checker.defineService(txInner) + } + + return res, errors.ErrUnknownTxType(tx) +} + +// DeliverTx executes the tx if valid +func (h Handler) DeliverTx(ctx sdk.Context, store state.SimpleDB, + tx sdk.Tx, dispatch sdk.Deliver) (res sdk.DeliverResult, err error) { + + // TODO: remove redundancy + // also we don't need to check the res - gas is already deducted in sdk + _, err = h.CheckTx(ctx, store, tx, nil) + if err != nil { + return + } + + sender, err := getTxSender(ctx) + if err != nil { + return + } + + params := loadParams(store) + deliverer := deliver{ + store: store, + sender: sender, + params: params, + } + + // Run the transaction + switch _tx := tx.Unwrap().(type) { + case TxDefineService: + res.GasUsed = params.GasDefineService + return res, deliverer.defineService(_tx) + } + return +} + +// get the sender from the ctx and ensure it matches the tx pubkey +func getTxSender(ctx sdk.Context) (sender sdk.Actor, err error) { + senders := ctx.GetPermissions("", auth.NameSigs) + if len(senders) != 1 { + return sender, ErrMissingSignature() + } + return senders[0], nil +} + +//_______________________________________________________________________ + +type check struct { + store state.SimpleDB + sender sdk.Actor +} + +func (c check) defineService(tx TxDefineService) error { + return nil +} + +type deliver struct { + store state.SimpleDB + sender sdk.Actor + params Params +} + +func (d deliver) defineService(tx TxDefineService) error { + + if d.store.Has([]byte(tx.Name)) { + return ErrServiceExists() + } + + service := ServiceDefinition{ + Name: tx.Name, + Description: tx.Description, + } + saveService(d.store, &service) + + return nil +} + +func (d deliver) getService(name string) *ServiceDefinition { + + return loadService(d.store, name) +} diff --git a/modules/iservice/handler_test.go b/modules/iservice/handler_test.go new file mode 100644 index 000000000..cf1d6a6eb --- /dev/null +++ b/modules/iservice/handler_test.go @@ -0,0 +1,50 @@ +package iservice + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk" + "github.com/cosmos/cosmos-sdk/state" + "github.com/stretchr/testify/assert" +) + +//______________________________________________________________________ + +func initAccounts(n int, amount int64) ([]sdk.Actor, map[string]int64) { + accStore := map[string]int64{} + senders := newActors(n) + for _, sender := range senders { + accStore[string(sender.Address)] = amount + } + return senders, accStore +} + +func newDeliver(sender sdk.Actor, accStore map[string]int64) deliver { + store := state.NewMemKVStore() + return deliver{ + store: store, + sender: sender, + params: loadParams(store), + } +} + +// newTxDefineService - new TxDefineService +func newTxDefineService(name string, description string) TxDefineService { + return TxDefineService{ + Name: name, + Description: description, + } +} + +func TestTxDefineService(t *testing.T) { + require := assert.New(t) + accounts, accStore := initAccounts(3, 1000) + sender := accounts[0] + deliverer := newDeliver(sender, accStore) + + //first make a candidate + txDefineService := newTxDefineService("testname", "testdesc") + deliverer.sender = sender + got := deliverer.defineService(txDefineService) + require.NoError(got, "expected tx to be ok, got %v", got) +} diff --git a/modules/iservice/iservice.go b/modules/iservice/iservice.go new file mode 100644 index 000000000..8b1d3ea0b --- /dev/null +++ b/modules/iservice/iservice.go @@ -0,0 +1,58 @@ +package iservice + +import ( + "github.com/cosmos/cosmos-sdk/state" + "github.com/tendermint/go-wire" +) + +// nolint +var ( + ParamKey = []byte{0x01} // key for global parameters relating to iservice + ServiceDefinitionKeyPrefix = []byte{0x02} // prefix for each key to a service definition +) + +//--------------------------------------------------------------------- + +// load/save the global iservice params +func loadParams(store state.SimpleDB) (params Params) { + b := store.Get(ParamKey) + if b == nil { + return defaultParams() + } + + err := wire.ReadBinaryBytes(b, ¶ms) + if err != nil { + panic(err) // This error should never occure big problem if does + } + + return +} +func saveParams(store state.SimpleDB, params Params) { + b := wire.BinaryBytes(params) + store.Set(ParamKey, b) +} + +func saveService(store state.SimpleDB, service *ServiceDefinition) { + + b := wire.BinaryBytes(*service) + store.Set(GetServiceDefinitionKey(service.Name), b) +} + +func loadService(store state.SimpleDB, name string) *ServiceDefinition { + serviceBytes := store.Get(GetServiceDefinitionKey(name)) + if serviceBytes == nil { + return nil + } + + service := new(ServiceDefinition) + err := wire.ReadBinaryBytes(serviceBytes, service) + if err != nil { + panic(err) + } + return service +} + +// GetServiceDefinitionKey - get the key for a service definition +func GetServiceDefinitionKey(name string) []byte { + return append(ServiceDefinitionKeyPrefix, wire.BinaryBytes(&name)...) +} diff --git a/modules/iservice/iservice_test.go b/modules/iservice/iservice_test.go new file mode 100644 index 000000000..e1a655af0 --- /dev/null +++ b/modules/iservice/iservice_test.go @@ -0,0 +1,8 @@ +package iservice + +import ( + "testing" +) + +func TestState(t *testing.T) { +} diff --git a/modules/iservice/tx.go b/modules/iservice/tx.go new file mode 100644 index 000000000..3897d0187 --- /dev/null +++ b/modules/iservice/tx.go @@ -0,0 +1,51 @@ +package iservice + +import ( + "github.com/cosmos/cosmos-sdk" +) + +// Tx +//-------------------------------------------------------------------------------- + +// register the tx type with its validation logic +// make sure to use the name of the handler as the prefix in the tx type, +// so it gets routed properly +const ( + ByteTxDefineService = 0x59 + TypeTxDefineService = iserviceModuleName + "/defineService" +) + +func init() { + sdk.TxMapper.RegisterImplementation(TxDefineService{}, TypeTxDefineService, ByteTxDefineService) +} + +//Verify interface at compile time +var _ sdk.TxInner = &TxDefineService{} + +// TxDefineService - struct for service define transactions +type TxDefineService struct { + Name string `json:"name"` + Description string `json:"description"` +} + +// NewTxDefineService - new TxDefineService +func NewTxDefineService(name string, description string) sdk.Tx { + return TxDefineService{ + Name: name, + Description: description, + }.Wrap() +} + +// Wrap - Wrap a Tx as a Basecoin Tx +func (tx TxDefineService) Wrap() sdk.Tx { return sdk.Tx{tx} } + +// ValidateBasic +func (tx TxDefineService) ValidateBasic() error { + if tx.Name == "" { + return errServiceNameEmpty + } + if tx.Description == "" { + return errServiceDescEmpty + } + return nil +} diff --git a/modules/iservice/tx_test.go b/modules/iservice/tx_test.go new file mode 100644 index 000000000..230351e1d --- /dev/null +++ b/modules/iservice/tx_test.go @@ -0,0 +1,37 @@ +package iservice + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/cosmos/cosmos-sdk" + wire "github.com/tendermint/go-wire" +) + +func TestAllAreTx(t *testing.T) { + assert := assert.New(t) + + txDefineSvc := NewTxDefineService("", "") + _, ok := txDefineSvc.Unwrap().(TxDefineService) + assert.True(ok, "%#v", txDefineSvc) +} + +func TestSerializeTx(t *testing.T) { + assert := assert.New(t) + + cases := []struct { + tx sdk.Tx + }{ + {NewTxDefineService("", "")}, + } + + for i, tc := range cases { + var tx sdk.Tx + bs := wire.BinaryBytes(tc.tx) + err := wire.ReadBinaryBytes(bs, &tx) + if assert.NoError(err, "%d", i) { + assert.Equal(tc.tx, tx, "%d", i) + } + } +} diff --git a/modules/iservice/types.go b/modules/iservice/types.go new file mode 100644 index 000000000..f062ec538 --- /dev/null +++ b/modules/iservice/types.go @@ -0,0 +1,19 @@ +package iservice + +// Params defines the high level settings for staking +type Params struct { + GasDefineService int64 `json:"gas_define_service"` +} + +func defaultParams() Params { + return Params{ + GasDefineService: 20, + } +} + +//_________________________________________________________________________ + +type ServiceDefinition struct { + Name string + Description string +} diff --git a/modules/iservice/types_test.go b/modules/iservice/types_test.go new file mode 100644 index 000000000..23a2db9ae --- /dev/null +++ b/modules/iservice/types_test.go @@ -0,0 +1,15 @@ +package iservice + +import ( + "fmt" + "github.com/cosmos/cosmos-sdk" +) + +func newActors(n int) (actors []sdk.Actor) { + for i := 0; i < n; i++ { + actors = append(actors, sdk.Actor{ + "testChain", "testapp", []byte(fmt.Sprintf("addr%d", i))}) + } + + return +} From 84a104095e0e818a027b5e1dccfcdfb413f1c427 Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Wed, 7 Mar 2018 18:19:05 +0800 Subject: [PATCH 003/124] Initial commit --- README.md | 2 + cmd/iris/client.go | 5 - cmd/iris/node.go | 2 - modules/iservice/commands/query.go | 45 ------- modules/iservice/commands/tx.go | 41 ------- modules/iservice/errors.go | 23 ---- modules/iservice/handler.go | 185 ----------------------------- modules/iservice/handler_test.go | 50 -------- modules/iservice/iservice.go | 58 --------- modules/iservice/iservice_test.go | 8 -- modules/iservice/tx.go | 51 -------- modules/iservice/tx_test.go | 37 ------ modules/iservice/types.go | 19 --- modules/iservice/types_test.go | 15 --- 14 files changed, 2 insertions(+), 539 deletions(-) create mode 100644 README.md delete mode 100644 modules/iservice/commands/query.go delete mode 100644 modules/iservice/commands/tx.go delete mode 100644 modules/iservice/errors.go delete mode 100644 modules/iservice/handler.go delete mode 100644 modules/iservice/handler_test.go delete mode 100644 modules/iservice/iservice.go delete mode 100644 modules/iservice/iservice_test.go delete mode 100644 modules/iservice/tx.go delete mode 100644 modules/iservice/tx_test.go delete mode 100644 modules/iservice/types.go delete mode 100644 modules/iservice/types_test.go diff --git a/README.md b/README.md new file mode 100644 index 000000000..d0fd4b453 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# Iris-Hub +Iris Hub - a regional Cosmos Hub with a powerful iService infrastructure diff --git a/cmd/iris/client.go b/cmd/iris/client.go index 7ccd967ef..11dd6b791 100644 --- a/cmd/iris/client.go +++ b/cmd/iris/client.go @@ -19,7 +19,6 @@ import ( rolecmd "github.com/cosmos/cosmos-sdk/modules/roles/commands" stakecmd "github.com/cosmos/gaia/modules/stake/commands" - iservicecmd "github.com/irisnet/iris-hub/modules/iservice/commands" ) // clientCmd is the entry point for this binary @@ -49,8 +48,6 @@ func prepareClientCommands() { stakecmd.CmdQueryCandidate, stakecmd.CmdQueryDelegatorBond, stakecmd.CmdQueryDelegatorCandidates, - - iservicecmd.CmdQueryServiceDefinition, ) // set up the middleware @@ -79,8 +76,6 @@ func prepareClientCommands() { stakecmd.CmdEditCandidacy, stakecmd.CmdDelegate, stakecmd.CmdUnbond, - - iservicecmd.CmdDefineService, ) clientCmd.AddCommand( diff --git a/cmd/iris/node.go b/cmd/iris/node.go index 4ab76e520..24037ee1a 100644 --- a/cmd/iris/node.go +++ b/cmd/iris/node.go @@ -18,7 +18,6 @@ import ( "github.com/cosmos/cosmos-sdk/state" "github.com/cosmos/gaia/modules/stake" - "github.com/irisnet/iris-hub/modules/iservice" ) // nodeCmd is the entry point for this binary @@ -49,7 +48,6 @@ func prepareNodeCommands() { stack.WrapHandler(roles.NewHandler()), stack.WrapHandler(ibc.NewHandler()), stake.NewHandler(), - iservice.NewHandler(), ) nodeCmd.AddCommand( diff --git a/modules/iservice/commands/query.go b/modules/iservice/commands/query.go deleted file mode 100644 index bd57d4595..000000000 --- a/modules/iservice/commands/query.go +++ /dev/null @@ -1,45 +0,0 @@ -package commands - -import ( - "github.com/spf13/cobra" - flag "github.com/spf13/pflag" - "github.com/spf13/viper" - - "github.com/cosmos/cosmos-sdk/client/commands" - "github.com/cosmos/cosmos-sdk/client/commands/query" - "github.com/cosmos/cosmos-sdk/stack" - "github.com/irisnet/iris-hub/modules/iservice" -) - -//nolint -var ( - CmdQueryServiceDefinition = &cobra.Command{ - Use: "service-definition", - RunE: cmdQueryServiceDefinition, - Short: "Query a service definition based on name", - } - - FlagServiceName = "svc-name" -) - -func init() { - //Add Flags - fsSn := flag.NewFlagSet("", flag.ContinueOnError) - fsSn.String(FlagServiceName, "", "Name of the service") - - CmdQueryServiceDefinition.Flags().AddFlagSet(fsSn) -} - -func cmdQueryServiceDefinition(cmd *cobra.Command, args []string) error { - - name := viper.GetString(FlagServiceName) - prove := !viper.GetBool(commands.FlagTrustNode) - key := stack.PrefixedKey(iservice.Name(), iservice.GetServiceDefinitionKey(name)) - var svc iservice.ServiceDefinition - height, err := query.GetParsed(key, &svc, query.GetHeight(), prove) - if err != nil { - return err - } - - return query.OutputProof(svc, height) -} diff --git a/modules/iservice/commands/tx.go b/modules/iservice/commands/tx.go deleted file mode 100644 index 4da259d90..000000000 --- a/modules/iservice/commands/tx.go +++ /dev/null @@ -1,41 +0,0 @@ -package commands - -import ( - txcmd "github.com/cosmos/cosmos-sdk/client/commands/txs" - "github.com/irisnet/iris-hub/modules/iservice" - "github.com/spf13/cobra" - flag "github.com/spf13/pflag" - "github.com/spf13/viper" -) - -// nolint -const ( - FlagName = "svc-name" - FlagDescription = "svc-description" -) - -// nolint -var ( - CmdDefineService = &cobra.Command{ - Use: "define-service", - Short: "define a new service", - RunE: cmdDefineService, - } -) - -func init() { - - fsService := flag.NewFlagSet("", flag.ContinueOnError) - fsService.String(FlagName, "", "service name") - fsService.String(FlagDescription, "", "service description") - - CmdDefineService.Flags().AddFlagSet(fsService) -} - -func cmdDefineService(cmd *cobra.Command, args []string) error { - name := viper.GetString(FlagName) - desc := viper.GetString(FlagDescription) - - tx := iservice.NewTxDefineService(name, desc) - return txcmd.DoTx(tx) -} diff --git a/modules/iservice/errors.go b/modules/iservice/errors.go deleted file mode 100644 index 8b584e752..000000000 --- a/modules/iservice/errors.go +++ /dev/null @@ -1,23 +0,0 @@ -// nolint -package iservice - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/errors" -) - -var ( - errServiceNameEmpty = fmt.Errorf("Invalid service name") - errServiceDescEmpty = fmt.Errorf("Invalid service description") - errServiceExists = fmt.Errorf("Service already exists") - - invalidInput = errors.CodeTypeBaseInvalidInput -) - -func ErrServiceExists() error { - return errors.WithCode(errServiceExists, errors.CodeTypeBaseInvalidInput) -} -func ErrMissingSignature() error { - return errors.ErrMissingSignature() -} diff --git a/modules/iservice/handler.go b/modules/iservice/handler.go deleted file mode 100644 index 1897e42b0..000000000 --- a/modules/iservice/handler.go +++ /dev/null @@ -1,185 +0,0 @@ -package iservice - -import ( - "fmt" - "strconv" - - "github.com/tendermint/tmlibs/log" - - "github.com/cosmos/cosmos-sdk" - "github.com/cosmos/cosmos-sdk/errors" - "github.com/cosmos/cosmos-sdk/modules/auth" - "github.com/cosmos/cosmos-sdk/stack" - "github.com/cosmos/cosmos-sdk/state" -) - -// nolint -const iserviceModuleName = "iservice" - -// Name is the name of the modules. -func Name() string { - return iserviceModuleName -} - -//_______________________________________________________________________ - -// Handler - the transaction processing handler -type Handler struct { - stack.PassInitValidate -} - -var _ stack.Dispatchable = Handler{} // enforce interface at compile time - -// NewHandler returns a new Handler with the default Params -func NewHandler() Handler { - return Handler{} -} - -// Name - return iservice namespace -func (Handler) Name() string { - return iserviceModuleName -} - -// AssertDispatcher - placeholder for stack.Dispatchable -func (Handler) AssertDispatcher() {} - -// InitState - set genesis parameters for iservice -func (h Handler) InitState(l log.Logger, store state.SimpleDB, - module, key, value string, cb sdk.InitStater) (log string, err error) { - return "", h.initState(module, key, value, store) -} - -// separated for testing -func (Handler) initState(module, key, value string, store state.SimpleDB) error { - if module != iserviceModuleName { - return errors.ErrUnknownModule(module) - } - - params := loadParams(store) - switch key { - case "gas_define_service": - - // TODO: enforce non-negative integers in input - i, err := strconv.Atoi(value) - if err != nil { - return fmt.Errorf("input must be integer, Error: %v", err.Error()) - } - params.GasDefineService = int64(i) - default: - return errors.ErrUnknownKey(key) - } - - saveParams(store, params) - return nil -} - -// CheckTx checks if the tx is properly structured -func (h Handler) CheckTx(ctx sdk.Context, store state.SimpleDB, - tx sdk.Tx, _ sdk.Checker) (res sdk.CheckResult, err error) { - - err = tx.ValidateBasic() - if err != nil { - return res, err - } - - // get the sender - sender, err := getTxSender(ctx) - if err != nil { - return res, err - } - - params := loadParams(store) - - // create the new checker object to - checker := check{ - store: store, - sender: sender, - } - - // return the fee for each tx type - switch txInner := tx.Unwrap().(type) { - case TxDefineService: - return sdk.NewCheck(params.GasDefineService, ""), - checker.defineService(txInner) - } - - return res, errors.ErrUnknownTxType(tx) -} - -// DeliverTx executes the tx if valid -func (h Handler) DeliverTx(ctx sdk.Context, store state.SimpleDB, - tx sdk.Tx, dispatch sdk.Deliver) (res sdk.DeliverResult, err error) { - - // TODO: remove redundancy - // also we don't need to check the res - gas is already deducted in sdk - _, err = h.CheckTx(ctx, store, tx, nil) - if err != nil { - return - } - - sender, err := getTxSender(ctx) - if err != nil { - return - } - - params := loadParams(store) - deliverer := deliver{ - store: store, - sender: sender, - params: params, - } - - // Run the transaction - switch _tx := tx.Unwrap().(type) { - case TxDefineService: - res.GasUsed = params.GasDefineService - return res, deliverer.defineService(_tx) - } - return -} - -// get the sender from the ctx and ensure it matches the tx pubkey -func getTxSender(ctx sdk.Context) (sender sdk.Actor, err error) { - senders := ctx.GetPermissions("", auth.NameSigs) - if len(senders) != 1 { - return sender, ErrMissingSignature() - } - return senders[0], nil -} - -//_______________________________________________________________________ - -type check struct { - store state.SimpleDB - sender sdk.Actor -} - -func (c check) defineService(tx TxDefineService) error { - return nil -} - -type deliver struct { - store state.SimpleDB - sender sdk.Actor - params Params -} - -func (d deliver) defineService(tx TxDefineService) error { - - if d.store.Has([]byte(tx.Name)) { - return ErrServiceExists() - } - - service := ServiceDefinition{ - Name: tx.Name, - Description: tx.Description, - } - saveService(d.store, &service) - - return nil -} - -func (d deliver) getService(name string) *ServiceDefinition { - - return loadService(d.store, name) -} diff --git a/modules/iservice/handler_test.go b/modules/iservice/handler_test.go deleted file mode 100644 index cf1d6a6eb..000000000 --- a/modules/iservice/handler_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package iservice - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk" - "github.com/cosmos/cosmos-sdk/state" - "github.com/stretchr/testify/assert" -) - -//______________________________________________________________________ - -func initAccounts(n int, amount int64) ([]sdk.Actor, map[string]int64) { - accStore := map[string]int64{} - senders := newActors(n) - for _, sender := range senders { - accStore[string(sender.Address)] = amount - } - return senders, accStore -} - -func newDeliver(sender sdk.Actor, accStore map[string]int64) deliver { - store := state.NewMemKVStore() - return deliver{ - store: store, - sender: sender, - params: loadParams(store), - } -} - -// newTxDefineService - new TxDefineService -func newTxDefineService(name string, description string) TxDefineService { - return TxDefineService{ - Name: name, - Description: description, - } -} - -func TestTxDefineService(t *testing.T) { - require := assert.New(t) - accounts, accStore := initAccounts(3, 1000) - sender := accounts[0] - deliverer := newDeliver(sender, accStore) - - //first make a candidate - txDefineService := newTxDefineService("testname", "testdesc") - deliverer.sender = sender - got := deliverer.defineService(txDefineService) - require.NoError(got, "expected tx to be ok, got %v", got) -} diff --git a/modules/iservice/iservice.go b/modules/iservice/iservice.go deleted file mode 100644 index 8b1d3ea0b..000000000 --- a/modules/iservice/iservice.go +++ /dev/null @@ -1,58 +0,0 @@ -package iservice - -import ( - "github.com/cosmos/cosmos-sdk/state" - "github.com/tendermint/go-wire" -) - -// nolint -var ( - ParamKey = []byte{0x01} // key for global parameters relating to iservice - ServiceDefinitionKeyPrefix = []byte{0x02} // prefix for each key to a service definition -) - -//--------------------------------------------------------------------- - -// load/save the global iservice params -func loadParams(store state.SimpleDB) (params Params) { - b := store.Get(ParamKey) - if b == nil { - return defaultParams() - } - - err := wire.ReadBinaryBytes(b, ¶ms) - if err != nil { - panic(err) // This error should never occure big problem if does - } - - return -} -func saveParams(store state.SimpleDB, params Params) { - b := wire.BinaryBytes(params) - store.Set(ParamKey, b) -} - -func saveService(store state.SimpleDB, service *ServiceDefinition) { - - b := wire.BinaryBytes(*service) - store.Set(GetServiceDefinitionKey(service.Name), b) -} - -func loadService(store state.SimpleDB, name string) *ServiceDefinition { - serviceBytes := store.Get(GetServiceDefinitionKey(name)) - if serviceBytes == nil { - return nil - } - - service := new(ServiceDefinition) - err := wire.ReadBinaryBytes(serviceBytes, service) - if err != nil { - panic(err) - } - return service -} - -// GetServiceDefinitionKey - get the key for a service definition -func GetServiceDefinitionKey(name string) []byte { - return append(ServiceDefinitionKeyPrefix, wire.BinaryBytes(&name)...) -} diff --git a/modules/iservice/iservice_test.go b/modules/iservice/iservice_test.go deleted file mode 100644 index e1a655af0..000000000 --- a/modules/iservice/iservice_test.go +++ /dev/null @@ -1,8 +0,0 @@ -package iservice - -import ( - "testing" -) - -func TestState(t *testing.T) { -} diff --git a/modules/iservice/tx.go b/modules/iservice/tx.go deleted file mode 100644 index 3897d0187..000000000 --- a/modules/iservice/tx.go +++ /dev/null @@ -1,51 +0,0 @@ -package iservice - -import ( - "github.com/cosmos/cosmos-sdk" -) - -// Tx -//-------------------------------------------------------------------------------- - -// register the tx type with its validation logic -// make sure to use the name of the handler as the prefix in the tx type, -// so it gets routed properly -const ( - ByteTxDefineService = 0x59 - TypeTxDefineService = iserviceModuleName + "/defineService" -) - -func init() { - sdk.TxMapper.RegisterImplementation(TxDefineService{}, TypeTxDefineService, ByteTxDefineService) -} - -//Verify interface at compile time -var _ sdk.TxInner = &TxDefineService{} - -// TxDefineService - struct for service define transactions -type TxDefineService struct { - Name string `json:"name"` - Description string `json:"description"` -} - -// NewTxDefineService - new TxDefineService -func NewTxDefineService(name string, description string) sdk.Tx { - return TxDefineService{ - Name: name, - Description: description, - }.Wrap() -} - -// Wrap - Wrap a Tx as a Basecoin Tx -func (tx TxDefineService) Wrap() sdk.Tx { return sdk.Tx{tx} } - -// ValidateBasic -func (tx TxDefineService) ValidateBasic() error { - if tx.Name == "" { - return errServiceNameEmpty - } - if tx.Description == "" { - return errServiceDescEmpty - } - return nil -} diff --git a/modules/iservice/tx_test.go b/modules/iservice/tx_test.go deleted file mode 100644 index 230351e1d..000000000 --- a/modules/iservice/tx_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package iservice - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/cosmos/cosmos-sdk" - wire "github.com/tendermint/go-wire" -) - -func TestAllAreTx(t *testing.T) { - assert := assert.New(t) - - txDefineSvc := NewTxDefineService("", "") - _, ok := txDefineSvc.Unwrap().(TxDefineService) - assert.True(ok, "%#v", txDefineSvc) -} - -func TestSerializeTx(t *testing.T) { - assert := assert.New(t) - - cases := []struct { - tx sdk.Tx - }{ - {NewTxDefineService("", "")}, - } - - for i, tc := range cases { - var tx sdk.Tx - bs := wire.BinaryBytes(tc.tx) - err := wire.ReadBinaryBytes(bs, &tx) - if assert.NoError(err, "%d", i) { - assert.Equal(tc.tx, tx, "%d", i) - } - } -} diff --git a/modules/iservice/types.go b/modules/iservice/types.go deleted file mode 100644 index f062ec538..000000000 --- a/modules/iservice/types.go +++ /dev/null @@ -1,19 +0,0 @@ -package iservice - -// Params defines the high level settings for staking -type Params struct { - GasDefineService int64 `json:"gas_define_service"` -} - -func defaultParams() Params { - return Params{ - GasDefineService: 20, - } -} - -//_________________________________________________________________________ - -type ServiceDefinition struct { - Name string - Description string -} diff --git a/modules/iservice/types_test.go b/modules/iservice/types_test.go deleted file mode 100644 index 23a2db9ae..000000000 --- a/modules/iservice/types_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package iservice - -import ( - "fmt" - "github.com/cosmos/cosmos-sdk" -) - -func newActors(n int) (actors []sdk.Actor) { - for i := 0; i < n; i++ { - actors = append(actors, sdk.Actor{ - "testChain", "testapp", []byte(fmt.Sprintf("addr%d", i))}) - } - - return -} From 9045083e027db047af72f69e74ee25a98061ce98 Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Thu, 8 Mar 2018 09:56:39 +0800 Subject: [PATCH 004/124] add version --- cmd/iris/main.go | 2 +- version/version.go | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 version/version.go diff --git a/cmd/iris/main.go b/cmd/iris/main.go index 6d652c920..c53e37231 100644 --- a/cmd/iris/main.go +++ b/cmd/iris/main.go @@ -8,7 +8,7 @@ import ( "github.com/tendermint/tmlibs/cli" basecmd "github.com/cosmos/cosmos-sdk/server/commands" - "github.com/cosmos/gaia/version" + "github.com/irisnet/iris-hub/version" ) // IrisCmd is the entry point for this binary diff --git a/version/version.go b/version/version.go new file mode 100644 index 000000000..720c65e4b --- /dev/null +++ b/version/version.go @@ -0,0 +1,19 @@ +package version + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +// Version - Iris Version +const Version = "0.1.0" + +// VersionCmd - The version of gaia +var VersionCmd = &cobra.Command{ + Use: "version", + Short: "Show version info", + Run: func(cmd *cobra.Command, args []string) { + fmt.Printf("v%s\n", Version) + }, +} From 4ce14a988d6281b5b223ddf38d408edb5e888c48 Mon Sep 17 00:00:00 2001 From: Yelong Zhang Date: Thu, 8 Mar 2018 14:08:34 +0800 Subject: [PATCH 005/124] Update glide.yaml --- glide.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/glide.yaml b/glide.yaml index 92b323dee..f93104cc9 100644 --- a/glide.yaml +++ b/glide.yaml @@ -1,6 +1,6 @@ package: github.com/irisnet/iris-hub import: -- package: github.com/cosmos/iris +- package: github.com/cosmos/gaia version: develop - package: github.com/cosmos/cosmos-sdk version: tm-develop From b38fb9c026fdb1d208adaf09781913f3e90b3cd4 Mon Sep 17 00:00:00 2001 From: "vincent.ch.cn" Date: Mon, 12 Mar 2018 17:17:44 +0800 Subject: [PATCH 006/124] inital installation doc --- README.md | 137 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) diff --git a/README.md b/README.md index d0fd4b453..b092b9104 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,139 @@ # Iris-Hub Iris Hub - a regional Cosmos Hub with a powerful iService infrastructure + +## Installation +``` +go get github.com/irisnet/iris-hub +cd $GOPATH/src/github.com/irisnet/iris-hub +make all +iris version +``` + +### Local-Test Example + +Here is a quick example to get you off your feet: + +First, generate a new key with a name, and save the address: + +``` +MYNAME= +iris client keys new $MYNAME +iris client keys list +MYADDR= +``` +Now initialize a iris-hub chain: + +``` +iris node init $MYADDR --home=$HOME/.iris1 --chain-id=test +``` + +This will create all the files necessary to run a single node chain in `$HOME/.iris1`: +a `config/priv_validator.json` file with the validators private key, and a `config/genesis.json` file +with the list of validators and accounts. In this case, we have one random validator, +and `$MYADDR` is an independent account that has a bunch of coins. + +We can add a second node on our local machine by initiating a node in a new directory, +and copying in the genesis: + + +``` +iris node init $MYADDR --home=$HOME/.iris2 --chain-id=test +cp $HOME/.iris1/config/genesis.json $HOME/.iris2/config/genesis.json +``` + +We need to also modify `$HOME/.iris2/config/config.toml` to set new seeds and ports. It should look like: + +``` +proxy_app = "tcp://127.0.0.1:46668" +moniker = "anonymous" +fast_sync = true +db_backend = "leveldb" +log_level = "main:info,state:info,*:error" + +[rpc] +laddr = "tcp://0.0.0.0:46667" + +[p2p] +laddr = "tcp://0.0.0.0:46666" +seeds = "ID@0.0.0.0:46656" +``` + +Great, now that we've initialized the chains, we can start both nodes in the background: + +``` +iris node start --home=$HOME/.iris1 &> iris1.log & +NODE1_PID=$! +iris node start --home=$HOME/.iris2 &> iris2.log & +NODE2_PID=$! +``` + +Note we save the `PID` so we can later kill the processes. + +Of course, you can peak at your logs with `tail iris1.log`, or follow them +for a bit with `tail -f iris1.log`. + +Now we can initialize a client for the first node, and look up our account: + +``` +iris client init --chain-id=test --node=tcp://localhost:46657 +iris client query account $MYADDR +``` + +Nice. We can also lookup the candidate set: + +``` +iris client query candidates +``` + +Notice it's empty! This is because the initial validators are special - +the app doesn't know about them, so they can't be removed. To see what +tendermint itself thinks the validator set is, use: + +``` +curl localhost:46657/validators +``` + +Ok, let's add the second node as a validator. First, we need the pubkey data: + +``` +cat $HOME/.iris2/priv_validator.json +``` + +If you have a json parser like `jq`, you can get just the pubkey: + +``` +cat $HOME/.iris2/priv_validator.json | jq .pub_key.data +``` + +Now we can delegate some coins to that pubkey: + +``` +iris client tx delegate --amount=10fermion --name=$MYNAME --pubkey= +``` + +We should see our account balance decrement, and the pubkey get added to the app's list of bonds: + +``` +iris client query account $MYADDR +iris client query candidates +``` + +To confirm for certain the new validator is active, check tendermint: + +``` +curl localhost:46657/validators +``` + +If you now kill your second node, blocks will stop streaming in, because there aren't enough validators online. +Turn her back on and they will start streaming again. + +Finally, to relinquish all your power, unbond some coins. You should see your +VotingPower reduce and your account balance increase. + +``` +iris client tx unbond --amount=10fermion --name=$MYNAME +iris client query validators +iris client query account $MYADDR +``` + +Once you unbond enough, you will no longer be needed to make new blocks. From a65b8abd8090e0f6f2a44cd92f7c6a5aec67ecec Mon Sep 17 00:00:00 2001 From: "vincent.ch.cn" Date: Mon, 12 Mar 2018 17:22:36 +0800 Subject: [PATCH 007/124] fix config --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b092b9104..426e0a3ec 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ iris client init --chain-id=test --node=tcp://localhost:46657 iris client query account $MYADDR ``` -Nice. We can also lookup the candidate set: +Nice. We can also lookup the candidate/validator set: ``` iris client query candidates @@ -96,13 +96,13 @@ curl localhost:46657/validators Ok, let's add the second node as a validator. First, we need the pubkey data: ``` -cat $HOME/.iris2/priv_validator.json +cat $HOME/.iris2/config/priv_validator.json ``` If you have a json parser like `jq`, you can get just the pubkey: ``` -cat $HOME/.iris2/priv_validator.json | jq .pub_key.data +cat $HOME/.iris2/config/priv_validator.json | jq .pub_key.data ``` Now we can delegate some coins to that pubkey: From 31a6b40fb945d35dafb3716468298cd655bc6da7 Mon Sep 17 00:00:00 2001 From: "vincent.ch.cn" Date: Mon, 12 Mar 2018 18:09:46 +0800 Subject: [PATCH 008/124] fix config --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 426e0a3ec..c533f716b 100644 --- a/README.md +++ b/README.md @@ -27,8 +27,8 @@ Now initialize a iris-hub chain: iris node init $MYADDR --home=$HOME/.iris1 --chain-id=test ``` -This will create all the files necessary to run a single node chain in `$HOME/.iris1`: -a `config/priv_validator.json` file with the validators private key, and a `config/genesis.json` file +This will create all the files necessary to run a single node chain in `$HOME/.iris1/config`: +a `priv_validator.json` file with the validators private key, and a `genesis.json` file with the list of validators and accounts. In this case, we have one random validator, and `$MYADDR` is an independent account that has a bunch of coins. From 66fefadc422d58499508fcf9d8d17d0fef132e64 Mon Sep 17 00:00:00 2001 From: Yelong Zhang Date: Tue, 13 Mar 2018 15:41:14 +0800 Subject: [PATCH 009/124] Create .gitattributes --- .gitattributes | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..70e1e3cdc --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.go linguist-language=go From c3eba0a5b53e8724463ea915103618986fab20dd Mon Sep 17 00:00:00 2001 From: Yelong Zhang Date: Tue, 13 Mar 2018 15:42:59 +0800 Subject: [PATCH 010/124] Update .gitattributes --- .gitattributes | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitattributes b/.gitattributes index 70e1e3cdc..4dab6e09a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,3 @@ *.go linguist-language=go +*.sh linguist-language=go +*.md linguist-language=go From bda15e1522b95b0a3cc09954a87085fd112d056a Mon Sep 17 00:00:00 2001 From: "vincent.ch.cn" Date: Tue, 13 Mar 2018 16:01:05 +0800 Subject: [PATCH 011/124] add byteTx --- cmd/iris/rest.go | 5 ++ cmd/iris/rest_test.go | 77 +++++++++++++++++++++++++++ rest/byteTx.go | 118 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 200 insertions(+) create mode 100644 cmd/iris/rest_test.go create mode 100644 rest/byteTx.go diff --git a/cmd/iris/rest.go b/cmd/iris/rest.go index 45c8c5ff2..e9212aad0 100644 --- a/cmd/iris/rest.go +++ b/cmd/iris/rest.go @@ -13,6 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/commands" rest "github.com/cosmos/cosmos-sdk/client/rest" + byteTx "github.com/irisnet/iris-hub/rest" coinrest "github.com/cosmos/cosmos-sdk/modules/coin/rest" noncerest "github.com/cosmos/cosmos-sdk/modules/nonce/rest" rolerest "github.com/cosmos/cosmos-sdk/modules/roles/rest" @@ -46,6 +47,7 @@ func cmdRestServer(cmd *cobra.Command, args []string) error { rootDir := viper.GetString(cli.HomeFlag) keyMan := client.GetKeyManager(rootDir) serviceKeys := rest.NewServiceKeys(keyMan) + serviceByteTx := byteTx.NewServiceByteTx(keyMan) serviceTxs := rest.NewServiceTxs(commands.GetNode()) routeRegistrars := []func(*mux.Router) error{ @@ -63,6 +65,9 @@ func cmdRestServer(cmd *cobra.Command, args []string) error { // Iris post transaction handler serviceTxs.RegisterPostTx, + // Iris transfer Tx to byte[] + serviceByteTx.RegisterByteTx, + // Nonce query handler noncerest.RegisterQueryNonce, diff --git a/cmd/iris/rest_test.go b/cmd/iris/rest_test.go new file mode 100644 index 000000000..c7b89e8d7 --- /dev/null +++ b/cmd/iris/rest_test.go @@ -0,0 +1,77 @@ +package main + +import ( + "fmt" + "log" + "net/http" + + "github.com/spf13/viper" + "github.com/gorilla/mux" + "testing" + "github.com/tendermint/tmlibs/cli" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/commands" + rest "github.com/cosmos/cosmos-sdk/client/rest" + byteTx "github.com/irisnet/iris-hub/rest" + coinrest "github.com/cosmos/cosmos-sdk/modules/coin/rest" + noncerest "github.com/cosmos/cosmos-sdk/modules/nonce/rest" + rolerest "github.com/cosmos/cosmos-sdk/modules/roles/rest" + + stakerest "github.com/cosmos/gaia/modules/stake/rest" +) + +func TestRest(t *testing.T) { + + + router := mux.NewRouter() + + rootDir := viper.GetString(cli.HomeFlag) + keyMan := client.GetKeyManager(rootDir) + serviceKeys := rest.NewServiceKeys(keyMan) + serviceByteTx := byteTx.NewServiceByteTx(keyMan) + serviceTxs := rest.NewServiceTxs(commands.GetNode()) + + + routeRegistrars := []func(*mux.Router) error{ + // rest.Keys handlers + serviceKeys.RegisterCRUD, + + // Coin handlers (Send, Query, SearchSent) + coinrest.RegisterAll, + + // Roles createRole handler + rolerest.RegisterCreateRole, + + // Iris sign transactions handler + serviceKeys.RegisterSignTx, + // Iris post transaction handler + serviceTxs.RegisterPostTx, + + // Iris transfer Tx to byte[] + serviceByteTx.RegisterByteTx, + + // Nonce query handler + noncerest.RegisterQueryNonce, + + // Staking query handlers + stakerest.RegisterQueryCandidate, + stakerest.RegisterQueryCandidates, + stakerest.RegisterQueryDelegatorBond, + stakerest.RegisterQueryDelegatorCandidates, + // Staking tx builders + stakerest.RegisterDelegate, + stakerest.RegisterUnbond, + } + + for _, routeRegistrar := range routeRegistrars { + if err := routeRegistrar(router); err != nil { + log.Fatal(err) + } + } + + addr := fmt.Sprintf(":%d", 8080) + + log.Printf("Serving on %q", addr) + http.ListenAndServe(addr, router) + +} \ No newline at end of file diff --git a/rest/byteTx.go b/rest/byteTx.go new file mode 100644 index 000000000..604af6c55 --- /dev/null +++ b/rest/byteTx.go @@ -0,0 +1,118 @@ +package rest + +import ( + "github.com/gorilla/mux" + "github.com/tendermint/go-crypto/keys" + "net/http" + sdk "github.com/cosmos/cosmos-sdk" + "encoding/hex" + "github.com/spf13/viper" + "github.com/cosmos/cosmos-sdk/client/commands" + "github.com/pkg/errors" + cmn "github.com/tendermint/tmlibs/common" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/commands/query" + "github.com/tendermint/tendermint/types" + "github.com/tendermint/go-wire" + "io" +) + + +type ServiceByteTx struct { + manager keys.Manager +} + +type RequestTx struct { + Tx sdk.Tx `json:"tx" validate:"required"` +} + +func NewServiceByteTx(manager keys.Manager) *ServiceByteTx { + return &ServiceByteTx{ + manager: manager, // XXX keycmd.GetKeyManager() + } +} + +func (s *ServiceByteTx) RegisterByteTx(r *mux.Router) error { + r.HandleFunc("/byteTx", s.ByteTx).Methods("POST") + return nil +} + + +func (s *ServiceByteTx) RegisterqueryTx(r *mux.Router) error { + r.HandleFunc("/tx/{hash}", s.queryTx).Methods("GET") + return nil +} + +func (s *ServiceByteTx) ByteTx(w http.ResponseWriter, r *http.Request) { + req := new(RequestTx) + if err := sdk.ParseRequestAndValidateJSON(r, req); err != nil { + sdk.WriteError(w, err) + return + } + + tx := req.Tx + + if sign, ok := tx.Unwrap().(keys.Signable); ok { + sdk.WriteSuccess(w, hex.EncodeToString(sign.SignBytes())) + return + } + sdk.WriteSuccess(w, "") +} + +func (s *ServiceByteTx) queryTx(w http.ResponseWriter, r *http.Request){ + args := mux.Vars(r) + hash := args["hash"] + + if hash == "" { + sdk.WriteError(w, errors.Errorf("[%s] argument must be non-empty ", "hash")) + return + } + // with tx, we always just parse key as hex and use to lookup + hashByte, err := hex.DecodeString(cmn.StripHex(hash)) + + // get the proof -> this will be used by all prover commands + node := commands.GetNode() + prove := !viper.GetBool(commands.FlagTrustNode) + res, err := node.Tx(hashByte, prove) + if err != nil { + sdk.WriteError(w, err) + return + } + + // no checks if we don't get a proof + if !prove { + sdk.WriteSuccess(w,showTx(w,res.Height, res.Tx)) + return + } + + cert, err := commands.GetCertifier() + if err != nil { + sdk.WriteError(w, err) + return + } + + check, err := client.GetCertifiedCommit(res.Height, node, cert) + if err != nil { + sdk.WriteError(w, err) + return + } + err = res.Proof.Validate(check.Header.DataHash) + if err != nil { + sdk.WriteError(w, err) + return + } + + // note that we return res.Proof.Data, not res.Tx, + // as res.Proof.Validate only verifies res.Proof.Data + sdk.WriteSuccess(w,showTx(w,res.Height, res.Proof.Data)) +} + +// showTx parses anything that was previously registered as sdk.Tx +func showTx(w io.Writer ,h int64, tx types.Tx) error { + var info sdk.Tx + err := wire.ReadBinaryBytes(tx, &info) + if err != nil { + return err + } + return query.FoutputProof(w,info,h) +} \ No newline at end of file From f57cf784615dc01909ef4c23024fa429da7aecfd Mon Sep 17 00:00:00 2001 From: kidinamoto01 Date: Fri, 23 Mar 2018 14:23:11 +0800 Subject: [PATCH 012/124] new guide --- README.md | 196 ++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 154 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index c533f716b..4a884b37f 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,89 @@ # Iris-Hub -Iris Hub - a regional Cosmos Hub with a powerful iService infrastructure +Iris Hub是在Cosmos生态中的区域性枢纽,提供iService服务 + +## 下载发行版安装 + * 进入下载页: https://github.com/irisnet/iris-hub/releases/tag/0.1.0 + * 下载对应版本的可执行文件 + * 解压缩`tar -C /usr/local -xzf iris$VERSION.$OS-$ARCH.zip` + * 拷贝到`/usr/local/`目录下 +执行 + ``` +iris version + ``` + +若出现`v 0.1.0`则说明安装成功 + + + +## 通过源码编译安装 + +### 系统要求 +操作系统:**Ubuntu 16.04** + +架构:**amd64** + +要求安装1.9版本以上的Go https://golang.org/doc/install + +GO 安装步骤 + +* 下载 +curl -O https://dl.google.com/go/go1.9.4.linux-386.tar.gz + +* 解压缩 +``` +tar xvf go1.9.4.linux-386.tar.gz +``` + +* 获得权限 +``` +sudo chown -R root:root ./go + +sudo mv go /usr/local +``` + +* 设置GOPATH +``` +export GOPATH=$HOME/work +export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin +``` + +* 测试是否安装成功 +建立一个简单的工程。 + +``` +mkdir -p work/src/github.com/user/hello +``` + +创建 "Hello World" Go文件. + + +``` +nano ~/work/src/github.com/user/hello/hello.go +``` +修改文件内容如下: + +``` +package main + +import "fmt" + +func main() { + fmt.Printf("hello, world\n") +} +``` +编译&安装 +``` +go install github.com/user/hello +``` +执行命令 +``` +hello +``` +如果安装成功,将会出现 "hello, world"输出: + + -## Installation +## 安装步骤 ``` go get github.com/irisnet/iris-hub cd $GOPATH/src/github.com/irisnet/iris-hub @@ -9,11 +91,13 @@ make all iris version ``` -### Local-Test Example +若出现`v 0.1.0`则说明安装成功 + +###本地测试网络 Here is a quick example to get you off your feet: -First, generate a new key with a name, and save the address: +1. 生成和保存测试网络中的测试账户 ``` MYNAME= @@ -21,19 +105,24 @@ iris client keys new $MYNAME iris client keys list MYADDR= ``` -Now initialize a iris-hub chain: +2. 初始化iris-hub: ``` iris node init $MYADDR --home=$HOME/.iris1 --chain-id=test ``` -This will create all the files necessary to run a single node chain in `$HOME/.iris1/config`: -a `priv_validator.json` file with the validators private key, and a `genesis.json` file -with the list of validators and accounts. In this case, we have one random validator, -and `$MYADDR` is an independent account that has a bunch of coins. +This will create all the files necessary to run a single node chain in以上命令将在 `$HOME/.iris1/config`目录下创建默认的配置文件 `priv_validator.json`和`genesis.json`。`priv_validator.json` 包含验证人的私钥。`genesis.json`文件包含其他配置信息, `$MYADDR`是默认生成的创世账户。 + +获得节点的Node_ID + +需要下载编辑develop分支的tendermint,或者下载可执行[[文件](https://github.com/kidinamoto01/gaia-testnet/blob/master/gaia-testnet/tendermint-develop-liunx-amd64.zip)] + +执行以下命令获得iris1的Node_ID +``` +tendermint show_node_id --home=$HOME/.iris1 +``` -We can add a second node on our local machine by initiating a node in a new directory, -and copying in the genesis: +同时,你也可以在本地再运行另一个Node,注意新的Node所对应的工作目录不同,但二者公用一个genesis文件。 ``` @@ -41,7 +130,7 @@ iris node init $MYADDR --home=$HOME/.iris2 --chain-id=test cp $HOME/.iris1/config/genesis.json $HOME/.iris2/config/genesis.json ``` -We need to also modify `$HOME/.iris2/config/config.toml` to set new seeds and ports. It should look like: +修改 `$HOME/.iris2/config/config.toml` 让两个Node可以发现彼此: ``` proxy_app = "tcp://127.0.0.1:46668" @@ -55,10 +144,10 @@ laddr = "tcp://0.0.0.0:46667" [p2p] laddr = "tcp://0.0.0.0:46666" -seeds = "ID@0.0.0.0:46656" +seeds = "@0.0.0.0:46656" ``` -Great, now that we've initialized the chains, we can start both nodes in the background: +然后就可以同时在后台运行: ``` iris node start --home=$HOME/.iris1 &> iris1.log & @@ -67,73 +156,96 @@ iris node start --home=$HOME/.iris2 &> iris2.log & NODE2_PID=$! ``` -Note we save the `PID` so we can later kill the processes. +`PID` 是为了方便之后杀死相关进程。 -Of course, you can peak at your logs with `tail iris1.log`, or follow them -for a bit with `tail -f iris1.log`. +通过 `tail iris1.log`,或 `tail -f iris1.log`可以对Node 进行监控。 -Now we can initialize a client for the first node, and look up our account: +现在我们初始化客户端,然后查询账户: ``` iris client init --chain-id=test --node=tcp://localhost:46657 iris client query account $MYADDR ``` -Nice. We can also lookup the candidate/validator set: +我们可以测试在账户间转账: + +``` +MYNAME1= +gaia client keys new $MYNAME1 +gaia client keys list +MYADDR1= +gaia client tx send --amount=1000fermion --to=$MYADDR1 --name=$MYNAME +gaia client query $MYADDR1 +gaia client query $MYADDR +``` + +也可以查询 candidate列表: ``` iris client query candidates ``` -Notice it's empty! This is because the initial validators are special - -the app doesn't know about them, so they can't be removed. To see what -tendermint itself thinks the validator set is, use: +很奇怪的是,iris并没有发现initial时生成的validator。这是因为这类validator比较特殊。通过查询tendermint接口,你可以获得初始的validator信息。 ``` curl localhost:46657/validators ``` -Ok, let's add the second node as a validator. First, we need the pubkey data: +接下来实现第一个validator的添加:首先获得节点的公钥: ``` -cat $HOME/.iris2/config/priv_validator.json +cat $HOME/.iris1/config/priv_validator.json ``` -If you have a json parser like `jq`, you can get just the pubkey: +使用`jq`命令可以快速获得公钥: ``` -cat $HOME/.iris2/config/priv_validator.json | jq .pub_key.data +cat $HOME/.iris1/config/priv_validator.json | jq .pub_key.data + ``` -Now we can delegate some coins to that pubkey: +通过执行以下命令完成绑定 +``` +iris client tx declare-candidacy --amount=1fermion --pubkey= --moniker= --name=$MYNAME ``` -iris client tx delegate --amount=10fermion --name=$MYNAME --pubkey= +再次查询 candidate列表: + +``` +iris client query candidates +``` +也可以查询具体的validator信息 + +``` +gaia client query candidate --pubkey= ``` -We should see our account balance decrement, and the pubkey get added to the app's list of bonds: +查询初始账户的变化,candidates页有变化: ``` iris client query account $MYADDR iris client query candidates -``` - -To confirm for certain the new validator is active, check tendermint: +``` +通过以下命令可以修改绑定的金额 ``` -curl localhost:46657/validators +gaia client tx edit-candidacy --pubkey= --moniker= --name=$MYNAME ``` - -If you now kill your second node, blocks will stop streaming in, because there aren't enough validators online. -Turn her back on and they will start streaming again. - -Finally, to relinquish all your power, unbond some coins. You should see your -VotingPower reduce and your account balance increase. +通过unbond可将抵押的代币收回,你会发现账户余额增加了。 ``` -iris client tx unbond --amount=10fermion --name=$MYNAME +iris client tx unbond --shares=1 --pubkey= --name=$MYNAME iris client query validators iris client query account $MYADDR -``` +``` +同样的,你也可以绑定用$HOME/.iris2/config/priv_validator.json代表的第二个Node +通过查询tendermint接口,你可以获得新的validator信息。 + + +``` +curl localhost:46657/validators +``` + +如果你杀死了第二个Node,那么区块链将无法继续生成新的块。这是因为只有保证2/3节点在线的情况下,才能达成共识。 -Once you unbond enough, you will no longer be needed to make new blocks. +将第二个节点重新启动,那么区块链会回归正常。 \ No newline at end of file From fe7cb17523b40b91fbf245d9ffccc161f09536f2 Mon Sep 17 00:00:00 2001 From: kidinamoto01 Date: Sat, 24 Mar 2018 00:51:02 +0800 Subject: [PATCH 013/124] fix --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 4a884b37f..049404cc0 100644 --- a/README.md +++ b/README.md @@ -171,12 +171,12 @@ iris client query account $MYADDR ``` MYNAME1= -gaia client keys new $MYNAME1 -gaia client keys list +iris client keys new $MYNAME1 +iris client keys list MYADDR1= -gaia client tx send --amount=1000fermion --to=$MYADDR1 --name=$MYNAME -gaia client query $MYADDR1 -gaia client query $MYADDR +iris client tx send --amount=1000fermion --to=$MYADDR1 --name=$MYNAME +iris client query $MYADDR1 +iris client query $MYADDR ``` 也可以查询 candidate列表: @@ -217,7 +217,7 @@ iris client query candidates 也可以查询具体的validator信息 ``` -gaia client query candidate --pubkey= +iris client query candidate --pubkey= ``` 查询初始账户的变化,candidates页有变化: @@ -229,7 +229,7 @@ iris client query candidates 通过以下命令可以修改绑定的金额 ``` -gaia client tx edit-candidacy --pubkey= --moniker= --name=$MYNAME +iris client tx edit-candidacy --pubkey= --moniker= --name=$MYNAME ``` 通过unbond可将抵押的代币收回,你会发现账户余额增加了。 From 810b52b0dbd23bba35cd1b4645dd87fbde2e1f7a Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Mon, 7 May 2018 15:48:49 +0800 Subject: [PATCH 014/124] =?UTF-8?q?IRISHUB-28:=E5=9F=BA=E4=BA=8Ecosmos-sdk?= =?UTF-8?q?[0.14.1]=E5=BC=80=E5=8F=91iservice=E7=9A=84=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E5=AE=9A=E4=B9=89=E9=83=A8=E5=88=86=E7=9A=84demo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/iris/client.go | 2 +- cmd/iris/node.go | 2 +- cmd/iris/rest.go | 2 +- glide.lock | 4 ++-- glide.yaml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cmd/iris/client.go b/cmd/iris/client.go index 11dd6b791..b79d9b6a0 100644 --- a/cmd/iris/client.go +++ b/cmd/iris/client.go @@ -18,7 +18,7 @@ import ( noncecmd "github.com/cosmos/cosmos-sdk/modules/nonce/commands" rolecmd "github.com/cosmos/cosmos-sdk/modules/roles/commands" - stakecmd "github.com/cosmos/gaia/modules/stake/commands" + stakecmd "github.com/MrXJC/gaia/modules/stake/commands" ) // clientCmd is the entry point for this binary diff --git a/cmd/iris/node.go b/cmd/iris/node.go index 24037ee1a..ece739afb 100644 --- a/cmd/iris/node.go +++ b/cmd/iris/node.go @@ -17,7 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/stack" "github.com/cosmos/cosmos-sdk/state" - "github.com/cosmos/gaia/modules/stake" + "github.com/MrXJC/gaia/modules/stake" ) // nodeCmd is the entry point for this binary diff --git a/cmd/iris/rest.go b/cmd/iris/rest.go index 45c8c5ff2..c287727b7 100644 --- a/cmd/iris/rest.go +++ b/cmd/iris/rest.go @@ -17,7 +17,7 @@ import ( noncerest "github.com/cosmos/cosmos-sdk/modules/nonce/rest" rolerest "github.com/cosmos/cosmos-sdk/modules/roles/rest" - stakerest "github.com/cosmos/gaia/modules/stake/rest" + stakerest "github.com/MrXJC/gaia/modules/stake/rest" ) const defaultAlgo = "ed25519" diff --git a/glide.lock b/glide.lock index aa50d9ced..0e912f491 100644 --- a/glide.lock +++ b/glide.lock @@ -46,8 +46,8 @@ imports: - stack - state - version -- name: github.com/cosmos/gaia - version: 2ac7ed920446ef8edf582c2b3e890cb7676a7d77 +- name: github.com/MrXJC/gaia + version: develop subpackages: - modules/stake - modules/stake/commands diff --git a/glide.yaml b/glide.yaml index f93104cc9..a279a3c69 100644 --- a/glide.yaml +++ b/glide.yaml @@ -1,6 +1,6 @@ package: github.com/irisnet/iris-hub import: -- package: github.com/cosmos/gaia +- package: github.com/MrXJC/gaia version: develop - package: github.com/cosmos/cosmos-sdk version: tm-develop From 7269a74d1e42fae1b01f06e9f2ea7ef8fa1980b5 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Tue, 8 May 2018 09:16:11 +0800 Subject: [PATCH 015/124] =?UTF-8?q?=E6=B7=BB=E5=8A=A0docker=E9=85=8D?= =?UTF-8?q?=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Dockerfile | 29 +++++++++++++++++++++++++++++ Makefile | 3 +++ 2 files changed, 32 insertions(+) create mode 100644 Dockerfile diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..94c28973d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,29 @@ +# Simple usage with a mounted data directory: +# > docker build -t iris . +# > docker run -it --rm -v "/mnt/volumes/pangu:/iris" iris init [address]--home=/iris +# > docker run -it --rm -v "/mnt/volumes/pangu:/iris" iris start --home=/iris + +FROM alpine:edge + +ADD ./build/ /usr/local/bin/ + +ENV DATA_ROOT /iris + +# Set user right away for determinism +RUN addgroup gaiauser && \ + adduser -S -G gaiauser gaiauser + +# Create directory for persistence and give our user ownership +RUN mkdir -p $DATA_ROOT && \ + chown -R gaiauser:gaiauser $DATA_ROOT + +VOLUME $DATA_ROOT + +# p2p port +EXPOSE 46656 +# rpc port +EXPOSE 46657 + +WORKDIR /bianjie/ + +ENTRYPOINT ["iris"] \ No newline at end of file diff --git a/Makefile b/Makefile index 01c6f3c5a..7295df83b 100644 --- a/Makefile +++ b/Makefile @@ -7,6 +7,9 @@ get_vendor_deps: install: go install ./cmd/iris +build_linux: + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iris ./cmd/iris + test: @go test `glide novendor` From e601a4ce9bfda4b4161377717750f9073de34934 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Wed, 16 May 2018 15:58:04 +0800 Subject: [PATCH 016/124] =?UTF-8?q?=E6=B7=BB=E5=8A=A0docker=E9=85=8D?= =?UTF-8?q?=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/iris/rest_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/iris/rest_test.go b/cmd/iris/rest_test.go index c7b89e8d7..b643f455c 100644 --- a/cmd/iris/rest_test.go +++ b/cmd/iris/rest_test.go @@ -17,7 +17,7 @@ import ( noncerest "github.com/cosmos/cosmos-sdk/modules/nonce/rest" rolerest "github.com/cosmos/cosmos-sdk/modules/roles/rest" - stakerest "github.com/cosmos/gaia/modules/stake/rest" + stakerest "github.com/MrXJC/gaia/modules/stake/rest" ) func TestRest(t *testing.T) { From c116801f39bf9e1ef1d84809a991243887b15193 Mon Sep 17 00:00:00 2001 From: "kaifei@bianjie.ai" Date: Thu, 17 May 2018 14:11:14 +0800 Subject: [PATCH 017/124] modify postTx from broadcaseAndCommit to brocastTxSync --- cmd/iris/rest.go | 3 ++- module/rest-txs/txs.go | 53 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 module/rest-txs/txs.go diff --git a/cmd/iris/rest.go b/cmd/iris/rest.go index 9908e70f9..9ca8d7a7b 100644 --- a/cmd/iris/rest.go +++ b/cmd/iris/rest.go @@ -13,6 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/commands" rest "github.com/cosmos/cosmos-sdk/client/rest" + restTxs "github.com/irisnet/iris-hub/module/rest-txs" byteTx "github.com/irisnet/iris-hub/rest" coinrest "github.com/cosmos/cosmos-sdk/modules/coin/rest" noncerest "github.com/cosmos/cosmos-sdk/modules/nonce/rest" @@ -48,7 +49,7 @@ func cmdRestServer(cmd *cobra.Command, args []string) error { keyMan := client.GetKeyManager(rootDir) serviceKeys := rest.NewServiceKeys(keyMan) serviceByteTx := byteTx.NewServiceByteTx(keyMan) - serviceTxs := rest.NewServiceTxs(commands.GetNode()) + serviceTxs := restTxs.NewServiceTxs(commands.GetNode()) routeRegistrars := []func(*mux.Router) error{ // rest.Keys handlers diff --git a/module/rest-txs/txs.go b/module/rest-txs/txs.go new file mode 100644 index 000000000..72230d389 --- /dev/null +++ b/module/rest-txs/txs.go @@ -0,0 +1,53 @@ +package rest_txs + +import ( + "net/http" + + "github.com/gorilla/mux" + wire "github.com/tendermint/go-wire" + rpcclient "github.com/tendermint/tendermint/rpc/client" + + sdk "github.com/cosmos/cosmos-sdk" +) + +// ServiceTxs exposes a REST API service for sendings txs. +// It wraps a Tendermint RPC client. +type ServiceTxs struct { + node rpcclient.Client +} + +func NewServiceTxs(c rpcclient.Client) *ServiceTxs { + return &ServiceTxs{ + node: c, + } +} + +func (s *ServiceTxs) PostTx(w http.ResponseWriter, r *http.Request) { + tx := new(sdk.Tx) + if err := sdk.ParseRequestAndValidateJSON(r, tx); err != nil { + sdk.WriteError(w, err) + return + } + + packet := wire.BinaryBytes(*tx) + // commit, err := s.node.BroadcastTxCommit(packet) + commit, err := s.node.BroadcastTxSync(packet) + if err != nil { + sdk.WriteError(w, err) + return + } + + sdk.WriteSuccess(w, commit) +} + +// mux.Router registrars + +// RegisterPostTx is a mux.Router handler that exposes POST +// method access to post a transaction to the blockchain. +func (s *ServiceTxs) RegisterPostTx(r *mux.Router) error { + r.HandleFunc("/tx", s.PostTx).Methods("POST") + return nil +} + +// End of mux.Router registrars + From ddb015c3268968155b7daa27fe68eab909123927 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Wed, 20 Jun 2018 10:48:52 +0800 Subject: [PATCH 018/124] update cosmos-sdk to v0.19.0 --- Gopkg.lock | 501 ++++++++++++++++++++++++++++++++++++ Gopkg.toml | 62 +++++ Makefile | 21 +- app/app.go | 181 +++++++++++++ app/genesis.go | 231 +++++++++++++++++ cmd/iris/client.go | 97 ------- cmd/iris/main.go | 61 ++--- cmd/iris/node.go | 69 ----- cmd/iris/rest.go | 95 ------- cmd/iris/rest_test.go | 77 ------ cmd/iris/sh_tests/stake.sh | 276 -------------------- cmd/iriscli/lcd.go | 85 ++++++ cmd/iriscli/main.go | 121 +++++++++ cmd/iriscli/offline_sign.go | 55 ++++ glide.lock | 305 ---------------------- glide.yaml | 17 -- module/rest-txs/txs.go | 53 ---- rest/byteTx.go | 118 --------- version/version.go | 2 +- 19 files changed, 1275 insertions(+), 1152 deletions(-) create mode 100644 Gopkg.lock create mode 100644 Gopkg.toml create mode 100644 app/app.go create mode 100644 app/genesis.go delete mode 100644 cmd/iris/client.go delete mode 100644 cmd/iris/node.go delete mode 100644 cmd/iris/rest.go delete mode 100644 cmd/iris/rest_test.go delete mode 100644 cmd/iris/sh_tests/stake.sh create mode 100644 cmd/iriscli/lcd.go create mode 100644 cmd/iriscli/main.go create mode 100644 cmd/iriscli/offline_sign.go delete mode 100644 glide.lock delete mode 100644 glide.yaml delete mode 100644 module/rest-txs/txs.go delete mode 100644 rest/byteTx.go diff --git a/Gopkg.lock b/Gopkg.lock new file mode 100644 index 000000000..ebf148691 --- /dev/null +++ b/Gopkg.lock @@ -0,0 +1,501 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + name = "github.com/bgentry/speakeasy" + packages = ["."] + revision = "4aabc24848ce5fd31929f7d1e4ea74d3709c14cd" + version = "v0.1.0" + +[[projects]] + branch = "master" + name = "github.com/btcsuite/btcd" + packages = ["btcec"] + revision = "86fed781132ac890ee03e906e4ecd5d6fa180c64" + +[[projects]] + branch = "master" + name = "github.com/btcsuite/btcutil" + packages = ["bech32"] + revision = "d4cc87b860166d00d6b5b9e0d3b3d71d6088d4d4" + +[[projects]] + name = "github.com/cosmos/cosmos-sdk" + packages = [ + "baseapp", + "client", + "client/context", + "client/keys", + "client/rpc", + "client/tx", + "server", + "store", + "types", + "version", + "wire", + "x/auth", + "x/auth/client/cli", + "x/auth/client/rest", + "x/bank", + "x/bank/client", + "x/bank/client/cli", + "x/bank/client/rest", + "x/ibc", + "x/ibc/client/cli", + "x/ibc/client/rest", + "x/slashing", + "x/slashing/client/cli", + "x/stake", + "x/stake/client/cli", + "x/stake/client/rest" + ] + revision = "c6711810a86f09457481a8dadae899681a9d77ab" + version = "v0.19.0" + +[[projects]] + name = "github.com/davecgh/go-spew" + packages = ["spew"] + revision = "346938d642f2ec3594ed81d874461961cd0faa76" + version = "v1.1.0" + +[[projects]] + branch = "master" + name = "github.com/ebuchman/fail-test" + packages = ["."] + revision = "95f809107225be108efcf10a3509e4ea6ceef3c4" + +[[projects]] + name = "github.com/fsnotify/fsnotify" + packages = ["."] + revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" + version = "v1.4.7" + +[[projects]] + name = "github.com/go-kit/kit" + packages = [ + "log", + "log/level", + "log/term" + ] + revision = "4dc7be5d2d12881735283bcab7352178e190fc71" + version = "v0.6.0" + +[[projects]] + name = "github.com/go-logfmt/logfmt" + packages = ["."] + revision = "390ab7935ee28ec6b286364bba9b4dd6410cb3d5" + version = "v0.3.0" + +[[projects]] + name = "github.com/go-stack/stack" + packages = ["."] + revision = "259ab82a6cad3992b4e21ff5cac294ccb06474bc" + version = "v1.7.0" + +[[projects]] + name = "github.com/gogo/protobuf" + packages = [ + "gogoproto", + "jsonpb", + "proto", + "protoc-gen-gogo/descriptor", + "sortkeys", + "types" + ] + revision = "1adfc126b41513cc696b209667c8656ea7aac67c" + version = "v1.0.0" + +[[projects]] + name = "github.com/golang/protobuf" + packages = [ + "proto", + "ptypes", + "ptypes/any", + "ptypes/duration", + "ptypes/timestamp" + ] + revision = "925541529c1fa6821df4e44ce2723319eb2be768" + version = "v1.0.0" + +[[projects]] + branch = "master" + name = "github.com/golang/snappy" + packages = ["."] + revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" + +[[projects]] + name = "github.com/gorilla/context" + packages = ["."] + revision = "08b5f424b9271eedf6f9f0ce86cb9396ed337a42" + version = "v1.1.1" + +[[projects]] + name = "github.com/gorilla/mux" + packages = ["."] + revision = "e3702bed27f0d39777b0b37b664b6280e8ef8fbf" + version = "v1.6.2" + +[[projects]] + name = "github.com/gorilla/websocket" + packages = ["."] + revision = "ea4d1f681babbce9545c9c5f3d5194a789c89f5b" + version = "v1.2.0" + +[[projects]] + branch = "master" + name = "github.com/hashicorp/hcl" + packages = [ + ".", + "hcl/ast", + "hcl/parser", + "hcl/printer", + "hcl/scanner", + "hcl/strconv", + "hcl/token", + "json/parser", + "json/scanner", + "json/token" + ] + revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" + +[[projects]] + branch = "master" + name = "github.com/howeyc/crc16" + packages = ["."] + revision = "2b2a61e366a66d3efb279e46176e7291001e0354" + +[[projects]] + name = "github.com/inconshreveable/mousetrap" + packages = ["."] + revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75" + version = "v1.0" + +[[projects]] + branch = "master" + name = "github.com/jmhodges/levigo" + packages = ["."] + revision = "c42d9e0ca023e2198120196f842701bb4c55d7b9" + +[[projects]] + branch = "master" + name = "github.com/kr/logfmt" + packages = ["."] + revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0" + +[[projects]] + name = "github.com/magiconair/properties" + packages = ["."] + revision = "c2353362d570a7bfa228149c62842019201cfb71" + version = "v1.8.0" + +[[projects]] + name = "github.com/mattn/go-isatty" + packages = ["."] + revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" + version = "v0.0.3" + +[[projects]] + branch = "master" + name = "github.com/mitchellh/mapstructure" + packages = ["."] + revision = "bb74f1db0675b241733089d5a1faa5dd8b0ef57b" + +[[projects]] + name = "github.com/pelletier/go-toml" + packages = ["."] + revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194" + version = "v1.2.0" + +[[projects]] + name = "github.com/pkg/errors" + packages = ["."] + revision = "645ef00459ed84a119197bfb8d8205042c6df63d" + version = "v0.8.0" + +[[projects]] + name = "github.com/pmezard/go-difflib" + packages = ["difflib"] + revision = "792786c7400a136282c1664665ae0a8db921c6c2" + version = "v1.0.0" + +[[projects]] + branch = "master" + name = "github.com/rcrowley/go-metrics" + packages = ["."] + revision = "e2704e165165ec55d062f5919b4b29494e9fa790" + +[[projects]] + name = "github.com/spf13/afero" + packages = [ + ".", + "mem" + ] + revision = "787d034dfe70e44075ccc060d346146ef53270ad" + version = "v1.1.1" + +[[projects]] + name = "github.com/spf13/cast" + packages = ["."] + revision = "8965335b8c7107321228e3e3702cab9832751bac" + version = "v1.2.0" + +[[projects]] + name = "github.com/spf13/cobra" + packages = ["."] + revision = "ef82de70bb3f60c65fb8eebacbb2d122ef517385" + version = "v0.0.3" + +[[projects]] + branch = "master" + name = "github.com/spf13/jwalterweatherman" + packages = ["."] + revision = "7c0cea34c8ece3fbeb2b27ab9b59511d360fb394" + +[[projects]] + name = "github.com/spf13/pflag" + packages = ["."] + revision = "583c0c0531f06d5278b7d917446061adc344b5cd" + version = "v1.0.1" + +[[projects]] + name = "github.com/spf13/viper" + packages = ["."] + revision = "b5e8006cbee93ec955a89ab31e0e3ce3204f3736" + version = "v1.0.2" + +[[projects]] + name = "github.com/stretchr/testify" + packages = [ + "assert", + "require" + ] + revision = "f35b8ab0b5a2cef36673838d662e249dd9c94686" + version = "v1.2.2" + +[[projects]] + branch = "master" + name = "github.com/syndtr/goleveldb" + packages = [ + "leveldb", + "leveldb/cache", + "leveldb/comparer", + "leveldb/errors", + "leveldb/filter", + "leveldb/iterator", + "leveldb/journal", + "leveldb/memdb", + "leveldb/opt", + "leveldb/storage", + "leveldb/table", + "leveldb/util" + ] + revision = "e2150783cd35f5b607daca48afd8c57ec54cc995" + +[[projects]] + name = "github.com/tendermint/abci" + packages = [ + "client", + "example/code", + "example/kvstore", + "server", + "types" + ] + revision = "ebee2fe114020aa49c70bbbae50b7079fc7e7b90" + version = "v0.11.0" + +[[projects]] + branch = "master" + name = "github.com/tendermint/ed25519" + packages = [ + ".", + "edwards25519", + "extra25519" + ] + revision = "d8387025d2b9d158cf4efb07e7ebf814bcce2057" + +[[projects]] + name = "github.com/tendermint/go-amino" + packages = ["."] + revision = "ed62928576cfcaf887209dc96142cd79cdfff389" + version = "0.9.9" + +[[projects]] + name = "github.com/tendermint/go-crypto" + packages = [ + ".", + "keys", + "keys/bcrypt", + "keys/words", + "keys/words/wordlist" + ] + revision = "915416979bf70efa4bcbf1c6cd5d64c5fff9fc19" + version = "v0.6.2" + +[[projects]] + name = "github.com/tendermint/iavl" + packages = [ + ".", + "sha256truncated" + ] + revision = "c9206995e8f948e99927f5084a88a7e94ca256da" + version = "v0.8.0-rc0" + +[[projects]] + name = "github.com/tendermint/tendermint" + packages = [ + "blockchain", + "cmd/tendermint/commands", + "config", + "consensus", + "consensus/types", + "evidence", + "libs/events", + "libs/pubsub", + "libs/pubsub/query", + "lite", + "lite/client", + "lite/errors", + "lite/files", + "lite/proxy", + "mempool", + "node", + "p2p", + "p2p/conn", + "p2p/pex", + "p2p/upnp", + "privval", + "proxy", + "rpc/client", + "rpc/core", + "rpc/core/types", + "rpc/grpc", + "rpc/lib", + "rpc/lib/client", + "rpc/lib/server", + "rpc/lib/types", + "state", + "state/txindex", + "state/txindex/kv", + "state/txindex/null", + "types", + "version" + ] + revision = "27bd1deabe4ba6a2d9b463b8f3e3f1e31b993e61" + version = "v0.20.0" + +[[projects]] + name = "github.com/tendermint/tmlibs" + packages = [ + "autofile", + "bech32", + "cli", + "cli/flags", + "clist", + "common", + "db", + "flowrate", + "log", + "merkle", + "merkle/tmhash" + ] + revision = "0c98d10b4ffbd87978d79c160e835b3d3df241ec" + +[[projects]] + branch = "master" + name = "golang.org/x/crypto" + packages = [ + "blowfish", + "curve25519", + "internal/subtle", + "nacl/box", + "nacl/secretbox", + "openpgp/armor", + "openpgp/errors", + "poly1305", + "ripemd160", + "salsa20/salsa" + ] + revision = "7f39a6fea4fe9364fb61e1def6a268a51b4f3a06" + +[[projects]] + branch = "master" + name = "golang.org/x/net" + packages = [ + "context", + "http/httpguts", + "http2", + "http2/hpack", + "idna", + "internal/timeseries", + "trace" + ] + revision = "db08ff08e8622530d9ed3a0e8ac279f6d4c02196" + +[[projects]] + branch = "master" + name = "golang.org/x/sys" + packages = ["unix"] + revision = "fc8bd948cf46f9c7af0f07d34151ce25fe90e477" + +[[projects]] + name = "golang.org/x/text" + packages = [ + "collate", + "collate/build", + "internal/colltab", + "internal/gen", + "internal/tag", + "internal/triegen", + "internal/ucd", + "language", + "secure/bidirule", + "transform", + "unicode/bidi", + "unicode/cldr", + "unicode/norm", + "unicode/rangetable" + ] + revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" + version = "v0.3.0" + +[[projects]] + name = "google.golang.org/genproto" + packages = ["googleapis/rpc/status"] + revision = "7fd901a49ba6a7f87732eb344f6e3c5b19d1b200" + +[[projects]] + name = "google.golang.org/grpc" + packages = [ + ".", + "balancer", + "codes", + "connectivity", + "credentials", + "grpclb/grpc_lb_v1/messages", + "grpclog", + "internal", + "keepalive", + "metadata", + "naming", + "peer", + "resolver", + "stats", + "status", + "tap", + "transport" + ] + revision = "5b3c4e850e90a4cf6a20ebd46c8b32a0a3afcb9e" + version = "v1.7.5" + +[[projects]] + name = "gopkg.in/yaml.v2" + packages = ["."] + revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" + version = "v2.2.1" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + inputs-digest = "e43d0010db3620c4c7daf0aca67fe5f6381f9fc907b1784718d189c4a47adae8" + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml new file mode 100644 index 000000000..a23280866 --- /dev/null +++ b/Gopkg.toml @@ -0,0 +1,62 @@ +# Gopkg.toml example +# +# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md +# for detailed Gopkg.toml documentation. +# +# required = ["github.com/user/thing/cmd/thing"] +# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] +# +# [[constraint]] +# name = "github.com/user/project" +# version = "1.0.0" +# +# [[constraint]] +# name = "github.com/user/project2" +# branch = "dev" +# source = "github.com/myfork/project2" +# +# [[override]] +# name = "github.com/x/y" +# version = "2.4.0" +# +# [prune] +# non-go = false +# go-tests = true +# unused-packages = true + +[[constraint]] + name = "github.com/spf13/cobra" + version = "~0.0.1" + +[[constraint]] + name = "github.com/spf13/viper" + version = "~1.0.0" + +[[constraint]] + name = "github.com/cosmos/cosmos-sdk" + version = "v0.19.0" + +[[constraint]] + name = "github.com/tendermint/abci" + version = "=0.11.0" + +[[constraint]] + name = "github.com/tendermint/go-crypto" + version = "~0.6.2" + +[[constraint]] + name = "github.com/tendermint/tendermint" + version = "=0.20.0" + +[[override]] + name = "github.com/tendermint/tmlibs" + revision = "0c98d10b4ffbd87978d79c160e835b3d3df241ec" + +# this got updated and broke, so locked to an old working commit ... +[[override]] + name = "google.golang.org/genproto" + revision = "7fd901a49ba6a7f87732eb344f6e3c5b19d1b200" + +[prune] + go-tests = true + unused-packages = true \ No newline at end of file diff --git a/Makefile b/Makefile index 7295df83b..077b9dc9d 100644 --- a/Makefile +++ b/Makefile @@ -1,17 +1,18 @@ -all: get_vendor_deps install test +all: get_vendor_deps install get_vendor_deps: - go get github.com/Masterminds/glide - glide install - + @rm -rf vendor/ + @echo "--> Running dep ensure" + @dep ensure -v + install: go install ./cmd/iris + go build ./cmd/iriscli build_linux: - CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iris ./cmd/iris - -test: - @go test `glide novendor` + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iris ./cmd/iris && \ + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iriscli ./cmd/iriscli -test_cli: - bash ./cmd/iris/sh_tests/stake.sh +build_cur: + go build -o build/iris ./cmd/iris && \ + go build -o build/iriscli ./cmd/iriscli diff --git a/app/app.go b/app/app.go new file mode 100644 index 000000000..d88c2ce88 --- /dev/null +++ b/app/app.go @@ -0,0 +1,181 @@ +package app + +import ( + "encoding/json" + "os" + + abci "github.com/tendermint/abci/types" + tmtypes "github.com/tendermint/tendermint/types" + cmn "github.com/tendermint/tmlibs/common" + dbm "github.com/tendermint/tmlibs/db" + "github.com/tendermint/tmlibs/log" + + bam "github.com/cosmos/cosmos-sdk/baseapp" + 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/bank" + "github.com/cosmos/cosmos-sdk/x/ibc" + "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/stake" +) + +const ( + appName = "IrisApp" +) + +// default home directories for expected binaries +var ( + DefaultCLIHome = os.ExpandEnv("$HOME/.iriscli") + DefaultNodeHome = os.ExpandEnv("$HOME/.iris") +) + +// Extended ABCI application +type IrisApp struct { + *bam.BaseApp + cdc *wire.Codec + + // keys to access the substores + keyMain *sdk.KVStoreKey + keyAccount *sdk.KVStoreKey + keyIBC *sdk.KVStoreKey + keyStake *sdk.KVStoreKey + keySlashing *sdk.KVStoreKey + + // Manage getting and setting accounts + accountMapper auth.AccountMapper + feeCollectionKeeper auth.FeeCollectionKeeper + coinKeeper bank.Keeper + ibcMapper ibc.Mapper + stakeKeeper stake.Keeper + slashingKeeper slashing.Keeper +} + +func NewIrisApp(logger log.Logger, db dbm.DB) *IrisApp { + cdc := MakeCodec() + + // create your application object + var app = &IrisApp{ + BaseApp: bam.NewBaseApp(appName, cdc, logger, db), + cdc: cdc, + keyMain: sdk.NewKVStoreKey("main"), + keyAccount: sdk.NewKVStoreKey("acc"), + keyIBC: sdk.NewKVStoreKey("ibc"), + keyStake: sdk.NewKVStoreKey("stake"), + keySlashing: sdk.NewKVStoreKey("slashing"), + } + + // define the accountMapper + app.accountMapper = auth.NewAccountMapper( + app.cdc, + app.keyAccount, // target store + &auth.BaseAccount{}, // prototype + ) + + // add handlers + app.coinKeeper = bank.NewKeeper(app.accountMapper) + app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace)) + app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) + app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.RegisterCodespace(slashing.DefaultCodespace)) + + // register message routes + app.Router(). + AddRoute("bank", bank.NewHandler(app.coinKeeper)). + AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)). + AddRoute("stake", stake.NewHandler(app.stakeKeeper)). + AddRoute("slashing", slashing.NewHandler(app.slashingKeeper)) + + // initialize BaseApp + app.SetInitChainer(app.initChainer) + app.SetBeginBlocker(app.BeginBlocker) + app.SetEndBlocker(app.EndBlocker) + app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) + app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing) + err := app.LoadLatestVersion(app.keyMain) + if err != nil { + cmn.Exit(err.Error()) + } + + return app +} + +// custom tx codec +func MakeCodec() *wire.Codec { + var cdc = wire.NewCodec() + ibc.RegisterWire(cdc) + bank.RegisterWire(cdc) + stake.RegisterWire(cdc) + slashing.RegisterWire(cdc) + auth.RegisterWire(cdc) + sdk.RegisterWire(cdc) + wire.RegisterCrypto(cdc) + return cdc +} + +// application updates every end block +func (app *IrisApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { + tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) + + return abci.ResponseBeginBlock{ + Tags: tags.ToKVPairs(), + } +} + +// application updates every end block +func (app *IrisApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { + validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) + + return abci.ResponseEndBlock{ + ValidatorUpdates: validatorUpdates, + } +} + +// custom logic for gaia initialization +func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { + stateJSON := req.AppStateBytes + // TODO is this now the whole genesis file? + + var genesisState GenesisState + err := app.cdc.UnmarshalJSON(stateJSON, &genesisState) + if err != nil { + panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 + // return sdk.ErrGenesisParse("").TraceCause(err, "") + } + + // load the accounts + for _, gacc := range genesisState.Accounts { + acc := gacc.ToAccount() + acc.AccountNumber = app.accountMapper.GetNextAccountNumber(ctx) + app.accountMapper.SetAccount(ctx, acc) + } + + // load the initial stake information + stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData) + + return abci.ResponseInitChain{} +} + +// export the state of gaia for a genesis file +func (app *IrisApp) ExportAppStateAndValidators() (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) { + ctx := app.NewContext(true, abci.Header{}) + + // iterate to get the accounts + accounts := []GenesisAccount{} + appendAccount := func(acc auth.Account) (stop bool) { + account := NewGenesisAccountI(acc) + accounts = append(accounts, account) + return false + } + app.accountMapper.IterateAccounts(ctx, appendAccount) + + genState := GenesisState{ + Accounts: accounts, + StakeData: stake.WriteGenesis(ctx, app.stakeKeeper), + } + appState, err = wire.MarshalJSONIndent(app.cdc, genState) + if err != nil { + return nil, nil, err + } + validators = stake.WriteValidators(ctx, app.stakeKeeper) + return appState, validators, nil +} \ No newline at end of file diff --git a/app/genesis.go b/app/genesis.go new file mode 100644 index 000000000..c504662b2 --- /dev/null +++ b/app/genesis.go @@ -0,0 +1,231 @@ +package app + +import ( + "encoding/json" + "errors" + + "github.com/spf13/pflag" + "github.com/spf13/viper" + crypto "github.com/tendermint/go-crypto" + tmtypes "github.com/tendermint/tendermint/types" + + "github.com/cosmos/cosmos-sdk/server" + 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" +) + +// State to Unmarshal +type GenesisState struct { + Accounts []GenesisAccount `json:"accounts"` + StakeData stake.GenesisState `json:"stake"` +} + +// GenesisAccount doesn't need pubkey or sequence +type GenesisAccount struct { + Address sdk.Address `json:"address"` + Coins sdk.Coins `json:"coins"` +} + +func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount { + return GenesisAccount{ + Address: acc.Address, + Coins: acc.Coins, + } +} + +func NewGenesisAccountI(acc auth.Account) GenesisAccount { + return GenesisAccount{ + Address: acc.GetAddress(), + Coins: acc.GetCoins(), + } +} + +// convert GenesisAccount to auth.BaseAccount +func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { + return &auth.BaseAccount{ + Address: ga.Address, + Coins: ga.Coins.Sort(), + } +} + +var ( + flagName = "name" + flagClientHome = "home-client" + flagOWK = "owk" + denom = "iris" + + + // bonded tokens given to genesis validators/accounts + freeFermionVal = int64(100) + + totalTokenAmt = int64(200000000) +) + +// get app init parameters for server init command +func GaiaAppInit() server.AppInit { + fsAppGenState := pflag.NewFlagSet("", pflag.ContinueOnError) + + fsAppGenTx := pflag.NewFlagSet("", pflag.ContinueOnError) + fsAppGenTx.String(flagName, "", "validator moniker, required") + fsAppGenTx.String(flagClientHome, DefaultCLIHome, + "home directory for the client, used for key generation") + fsAppGenTx.Bool(flagOWK, false, "overwrite the accounts created") + + return server.AppInit{ + FlagsAppGenState: fsAppGenState, + FlagsAppGenTx: fsAppGenTx, + AppGenTx: IrisAppGenTx, + AppGenState: IrisAppGenStateJSON, + } +} + +// simple genesis tx +type GaiaGenTx struct { + Name string `json:"name"` + Address sdk.Address `json:"address"` + PubKey crypto.PubKey `json:"pub_key"` +} + +// Generate a gaia genesis transaction with flags +func IrisAppGenTx(cdc *wire.Codec, pk crypto.PubKey) ( + appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { + clientRoot := viper.GetString(flagClientHome) + overwrite := viper.GetBool(flagOWK) + name := viper.GetString(flagName) + if name == "" { + return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)") + } + + var addr sdk.Address + var secret string + addr, secret, err = server.GenerateSaveCoinKey(clientRoot, name, "1234567890", overwrite) + if err != nil { + return + } + mm := map[string]string{"secret": secret} + var bz []byte + bz, err = cdc.MarshalJSON(mm) + if err != nil { + return + } + cliPrint = json.RawMessage(bz) + appGenTx,_,validator,err = IrisAppGenTxNF(cdc, pk, addr, name, overwrite) + return +} + +// Generate a gaia genesis transaction without flags +func IrisAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.Address, name string, overwrite bool) ( + appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { + + var bz []byte + gaiaGenTx := GaiaGenTx{ + Name: name, + Address: addr, + PubKey: pk, + } + bz, err = wire.MarshalJSONIndent(cdc, gaiaGenTx) + if err != nil { + return + } + appGenTx = json.RawMessage(bz) + + validator = tmtypes.GenesisValidator{ + PubKey: pk, + Power: freeFermionVal, + } + return +} + +// Create the core parameters for genesis initialization for gaia +// note that the pubkey input is this machines pubkey +func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState GenesisState, err error) { + + if len(appGenTxs) == 0 { + err = errors.New("must provide at least genesis transaction") + return + } + + // start with the default staking genesis state + //stakeData := stake.DefaultGenesisState() + stakeData := createGenesisState() + + // get genesis flag account information + genaccs := make([]GenesisAccount, len(appGenTxs)) + for i, appGenTx := range appGenTxs { + + var genTx GaiaGenTx + err = cdc.UnmarshalJSON(appGenTx, &genTx) + if err != nil { + return + } + + // create the genesis account, give'm few steaks and a buncha token with there name + accAuth := auth.NewBaseAccountWithAddress(genTx.Address) + accAuth.Coins = sdk.Coins{ + {denom, totalTokenAmt}, + } + acc := NewGenesisAccount(&accAuth) + genaccs[i] = acc + stakeData.Pool.LooseUnbondedTokens += totalTokenAmt // increase the supply + + // add the validator + if len(genTx.Name) > 0 { + desc := stake.NewDescription(genTx.Name, "", "", "") + validator := stake.NewValidator(genTx.Address, genTx.PubKey, desc) + validator.PoolShares = stake.NewBondedShares(sdk.NewRat(freeFermionVal)) + stakeData.Validators = append(stakeData.Validators, validator) + + // pool logic + stakeData.Pool.BondedTokens += freeFermionVal + stakeData.Pool.BondedShares = sdk.NewRat(stakeData.Pool.BondedTokens) + } + } + + // create the final app state + genesisState = GenesisState{ + Accounts: genaccs, + StakeData: stakeData, + } + return +} + +// IrisAppGenState but with JSON +func IrisAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) { + + // create the final app state + genesisState, err := IrisAppGenState(cdc, appGenTxs) + if err != nil { + return nil, err + } + appState, err = wire.MarshalJSONIndent(cdc, genesisState) + return +} + +// TODO +func createGenesisState() stake.GenesisState{ + return stake.GenesisState{ + Pool: stake.Pool{ + LooseUnbondedTokens: 0, + BondedTokens: 0, + UnbondingTokens: 0, + UnbondedTokens: 0, + BondedShares: sdk.ZeroRat(), + UnbondingShares: sdk.ZeroRat(), + UnbondedShares: sdk.ZeroRat(), + InflationLastTime: 0, + Inflation: sdk.NewRat(7, 100), + DateLastCommissionReset: 0, + PrevBondedShares: sdk.ZeroRat(), + }, + Params: stake.Params{ + InflationRateChange: sdk.NewRat(13, 100), + InflationMax: sdk.NewRat(20, 100), + InflationMin: sdk.NewRat(7, 100), + GoalBonded: sdk.NewRat(67, 100), + MaxValidators: 100, + BondDenom: denom, + }, + } +} \ No newline at end of file diff --git a/cmd/iris/client.go b/cmd/iris/client.go deleted file mode 100644 index b79d9b6a0..000000000 --- a/cmd/iris/client.go +++ /dev/null @@ -1,97 +0,0 @@ -package main - -import ( - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client/commands" - "github.com/cosmos/cosmos-sdk/client/commands/commits" - "github.com/cosmos/cosmos-sdk/client/commands/keys" - "github.com/cosmos/cosmos-sdk/client/commands/proxy" - "github.com/cosmos/cosmos-sdk/client/commands/query" - rpccmd "github.com/cosmos/cosmos-sdk/client/commands/rpc" - txcmd "github.com/cosmos/cosmos-sdk/client/commands/txs" - authcmd "github.com/cosmos/cosmos-sdk/modules/auth/commands" - basecmd "github.com/cosmos/cosmos-sdk/modules/base/commands" - coincmd "github.com/cosmos/cosmos-sdk/modules/coin/commands" - feecmd "github.com/cosmos/cosmos-sdk/modules/fee/commands" - ibccmd "github.com/cosmos/cosmos-sdk/modules/ibc/commands" - noncecmd "github.com/cosmos/cosmos-sdk/modules/nonce/commands" - rolecmd "github.com/cosmos/cosmos-sdk/modules/roles/commands" - - stakecmd "github.com/MrXJC/gaia/modules/stake/commands" -) - -// clientCmd is the entry point for this binary -var clientCmd = &cobra.Command{ - Use: "client", - Short: "Iris light client", - Run: func(cmd *cobra.Command, args []string) { - cmd.Help() - }, -} - -func prepareClientCommands() { - commands.AddBasicFlags(clientCmd) - - // Prepare queries - query.RootCmd.AddCommand( - // These are default parsers, but optional in your app (you can remove key) - query.TxQueryCmd, - query.KeyQueryCmd, - coincmd.AccountQueryCmd, - noncecmd.NonceQueryCmd, - rolecmd.RoleQueryCmd, - ibccmd.IBCQueryCmd, - - //stakecmd.CmdQueryValidator, - stakecmd.CmdQueryCandidates, - stakecmd.CmdQueryCandidate, - stakecmd.CmdQueryDelegatorBond, - stakecmd.CmdQueryDelegatorCandidates, - ) - - // set up the middleware - txcmd.Middleware = txcmd.Wrappers{ - feecmd.FeeWrapper{}, - rolecmd.RoleWrapper{}, - noncecmd.NonceWrapper{}, - basecmd.ChainWrapper{}, - authcmd.SigWrapper{}, - } - txcmd.Middleware.Register(txcmd.RootCmd.PersistentFlags()) - - // you will always want this for the base send command - txcmd.RootCmd.AddCommand( - // This is the default transaction, optional in your app - coincmd.SendTxCmd, - coincmd.CreditTxCmd, - // this enables creating roles - rolecmd.CreateRoleTxCmd, - // these are for handling ibc - ibccmd.RegisterChainTxCmd, - ibccmd.UpdateChainTxCmd, - ibccmd.PostPacketTxCmd, - - stakecmd.CmdDeclareCandidacy, - stakecmd.CmdEditCandidacy, - stakecmd.CmdDelegate, - stakecmd.CmdUnbond, - ) - - clientCmd.AddCommand( - proxy.RootCmd, - lineBreak, - - txcmd.RootCmd, - query.RootCmd, - rpccmd.RootCmd, - lineBreak, - - keys.RootCmd, - commands.InitCmd, - commands.ResetCmd, - commits.RootCmd, - lineBreak, - ) - -} diff --git a/cmd/iris/main.go b/cmd/iris/main.go index c53e37231..b36718838 100644 --- a/cmd/iris/main.go +++ b/cmd/iris/main.go @@ -1,50 +1,43 @@ package main import ( - "os" + "encoding/json" "github.com/spf13/cobra" + abci "github.com/tendermint/abci/types" + tmtypes "github.com/tendermint/tendermint/types" "github.com/tendermint/tmlibs/cli" - - basecmd "github.com/cosmos/cosmos-sdk/server/commands" - "github.com/irisnet/iris-hub/version" -) - -// IrisCmd is the entry point for this binary -var ( - IrisCmd = &cobra.Command{ - Use: "iris", - Short: "IRIS Hub - a regional Cosmos Hub with a powerful iService infrastructure", - Run: func(cmd *cobra.Command, args []string) { - cmd.Help() - }, - } - - lineBreak = &cobra.Command{Run: func(*cobra.Command, []string) {}} + dbm "github.com/tendermint/tmlibs/db" + "github.com/tendermint/tmlibs/log" + "github.com/cosmos/cosmos-sdk/server" + "github.com/irisnet/iris-hub/app" ) func main() { - // disable sorting + cdc := app.MakeCodec() + ctx := server.NewDefaultContext() cobra.EnableCommandSorting = false + rootCmd := &cobra.Command{ + Use: "iris", + Short: "iris Daemon (server)", + PersistentPreRunE: server.PersistentPreRunEFn(ctx), + } - // add commands - prepareNodeCommands() - prepareRestServerCommands() - prepareClientCommands() - - IrisCmd.AddCommand( - nodeCmd, - restServerCmd, - clientCmd, - - lineBreak, - version.VersionCmd, - //auto.AutoCompleteCmd, - ) + server.AddCommands(ctx, cdc, rootCmd, app.GaiaAppInit(), + server.ConstructAppCreator(newApp, "iris"), + server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")) // prepare and add flags - basecmd.SetUpRoot(IrisCmd) - executor := cli.PrepareMainCmd(IrisCmd, "GA", os.ExpandEnv("$HOME/.iris-cli")) + executor := cli.PrepareBaseCmd(rootCmd, "IRIS", app.DefaultNodeHome) executor.Execute() } + +func newApp(logger log.Logger, db dbm.DB) abci.Application { + return app.NewIrisApp(logger, db) +} + +func exportAppStateAndTMValidators(logger log.Logger, db dbm.DB) (json.RawMessage, []tmtypes.GenesisValidator, error) { + irisApp := app.NewIrisApp(logger, db) + return irisApp.ExportAppStateAndValidators() +} \ No newline at end of file diff --git a/cmd/iris/node.go b/cmd/iris/node.go deleted file mode 100644 index ece739afb..000000000 --- a/cmd/iris/node.go +++ /dev/null @@ -1,69 +0,0 @@ -package main - -import ( - "github.com/spf13/cobra" - - abci "github.com/tendermint/abci/types" - - sdk "github.com/cosmos/cosmos-sdk" - "github.com/cosmos/cosmos-sdk/modules/auth" - "github.com/cosmos/cosmos-sdk/modules/base" - "github.com/cosmos/cosmos-sdk/modules/coin" - "github.com/cosmos/cosmos-sdk/modules/fee" - "github.com/cosmos/cosmos-sdk/modules/ibc" - "github.com/cosmos/cosmos-sdk/modules/nonce" - "github.com/cosmos/cosmos-sdk/modules/roles" - basecmd "github.com/cosmos/cosmos-sdk/server/commands" - "github.com/cosmos/cosmos-sdk/stack" - "github.com/cosmos/cosmos-sdk/state" - - "github.com/MrXJC/gaia/modules/stake" -) - -// nodeCmd is the entry point for this binary -var nodeCmd = &cobra.Command{ - Use: "node", - Short: "The Cosmos Network delegation-game blockchain test", - Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, -} - -func prepareNodeCommands() { - - basecmd.Handler = stack.New( - base.Logger{}, - stack.Recovery{}, - auth.Signatures{}, - base.Chain{}, - stack.Checkpoint{OnCheck: true}, - nonce.ReplayCheck{}, - ). - IBC(ibc.NewMiddleware()). - Apps( - roles.NewMiddleware(), - fee.NewSimpleFeeMiddleware(coin.Coin{"fermion", 0}, fee.Bank), - stack.Checkpoint{OnDeliver: true}, - ). - Dispatch( - coin.NewHandler(), - stack.WrapHandler(roles.NewHandler()), - stack.WrapHandler(ibc.NewHandler()), - stake.NewHandler(), - ) - - nodeCmd.AddCommand( - basecmd.GetInitCmd("fermion", []string{"stake/allowed_bond_denom/fermion"}), - basecmd.GetTickStartCmd(sdk.TickerFunc(tickFn)), - basecmd.UnsafeResetAllCmd, - ) -} - -// Tick - Called every block even if no transaction, process all queues, -// validator rewards, and calculate the validator set difference -func tickFn(ctx sdk.Context, store state.SimpleDB) (change []abci.Validator, err error) { - // first need to prefix the store, at this point it's a global store - store = stack.PrefixedStore(stake.Name(), store) - - // execute Tick - change, err = stake.UpdateValidatorSet(store) - return -} diff --git a/cmd/iris/rest.go b/cmd/iris/rest.go deleted file mode 100644 index 9ca8d7a7b..000000000 --- a/cmd/iris/rest.go +++ /dev/null @@ -1,95 +0,0 @@ -package main - -import ( - "fmt" - "log" - "net/http" - - "github.com/gorilla/mux" - "github.com/spf13/cobra" - "github.com/spf13/viper" - "github.com/tendermint/tmlibs/cli" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/commands" - rest "github.com/cosmos/cosmos-sdk/client/rest" - restTxs "github.com/irisnet/iris-hub/module/rest-txs" - byteTx "github.com/irisnet/iris-hub/rest" - coinrest "github.com/cosmos/cosmos-sdk/modules/coin/rest" - noncerest "github.com/cosmos/cosmos-sdk/modules/nonce/rest" - rolerest "github.com/cosmos/cosmos-sdk/modules/roles/rest" - - stakerest "github.com/MrXJC/gaia/modules/stake/rest" -) - -const defaultAlgo = "ed25519" - -var ( - restServerCmd = &cobra.Command{ - Use: "rest-server", - Short: "REST client for iris commands", - Long: `Irisserver presents a nice (not raw hex) interface to the iris blockchain structure.`, - RunE: func(cmd *cobra.Command, args []string) error { - return cmdRestServer(cmd, args) - }, - } - - flagPort = "port" -) - -func prepareRestServerCommands() { - commands.AddBasicFlags(restServerCmd) - restServerCmd.PersistentFlags().IntP(flagPort, "p", 8998, "port to run the server on") -} - -func cmdRestServer(cmd *cobra.Command, args []string) error { - router := mux.NewRouter() - - rootDir := viper.GetString(cli.HomeFlag) - keyMan := client.GetKeyManager(rootDir) - serviceKeys := rest.NewServiceKeys(keyMan) - serviceByteTx := byteTx.NewServiceByteTx(keyMan) - serviceTxs := restTxs.NewServiceTxs(commands.GetNode()) - - routeRegistrars := []func(*mux.Router) error{ - // rest.Keys handlers - serviceKeys.RegisterCRUD, - - // Coin handlers (Send, Query, SearchSent) - coinrest.RegisterAll, - - // Roles createRole handler - rolerest.RegisterCreateRole, - - // Iris sign transactions handler - serviceKeys.RegisterSignTx, - // Iris post transaction handler - serviceTxs.RegisterPostTx, - - // Iris transfer Tx to byte[] - serviceByteTx.RegisterByteTx, - - // Nonce query handler - noncerest.RegisterQueryNonce, - - // Staking query handlers - stakerest.RegisterQueryCandidate, - stakerest.RegisterQueryCandidates, - stakerest.RegisterQueryDelegatorBond, - stakerest.RegisterQueryDelegatorCandidates, - // Staking tx builders - stakerest.RegisterDelegate, - stakerest.RegisterUnbond, - } - - for _, routeRegistrar := range routeRegistrars { - if err := routeRegistrar(router); err != nil { - log.Fatal(err) - } - } - - addr := fmt.Sprintf(":%d", viper.GetInt(flagPort)) - - log.Printf("Serving on %q", addr) - return http.ListenAndServe(addr, router) -} diff --git a/cmd/iris/rest_test.go b/cmd/iris/rest_test.go deleted file mode 100644 index b643f455c..000000000 --- a/cmd/iris/rest_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package main - -import ( - "fmt" - "log" - "net/http" - - "github.com/spf13/viper" - "github.com/gorilla/mux" - "testing" - "github.com/tendermint/tmlibs/cli" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/commands" - rest "github.com/cosmos/cosmos-sdk/client/rest" - byteTx "github.com/irisnet/iris-hub/rest" - coinrest "github.com/cosmos/cosmos-sdk/modules/coin/rest" - noncerest "github.com/cosmos/cosmos-sdk/modules/nonce/rest" - rolerest "github.com/cosmos/cosmos-sdk/modules/roles/rest" - - stakerest "github.com/MrXJC/gaia/modules/stake/rest" -) - -func TestRest(t *testing.T) { - - - router := mux.NewRouter() - - rootDir := viper.GetString(cli.HomeFlag) - keyMan := client.GetKeyManager(rootDir) - serviceKeys := rest.NewServiceKeys(keyMan) - serviceByteTx := byteTx.NewServiceByteTx(keyMan) - serviceTxs := rest.NewServiceTxs(commands.GetNode()) - - - routeRegistrars := []func(*mux.Router) error{ - // rest.Keys handlers - serviceKeys.RegisterCRUD, - - // Coin handlers (Send, Query, SearchSent) - coinrest.RegisterAll, - - // Roles createRole handler - rolerest.RegisterCreateRole, - - // Iris sign transactions handler - serviceKeys.RegisterSignTx, - // Iris post transaction handler - serviceTxs.RegisterPostTx, - - // Iris transfer Tx to byte[] - serviceByteTx.RegisterByteTx, - - // Nonce query handler - noncerest.RegisterQueryNonce, - - // Staking query handlers - stakerest.RegisterQueryCandidate, - stakerest.RegisterQueryCandidates, - stakerest.RegisterQueryDelegatorBond, - stakerest.RegisterQueryDelegatorCandidates, - // Staking tx builders - stakerest.RegisterDelegate, - stakerest.RegisterUnbond, - } - - for _, routeRegistrar := range routeRegistrars { - if err := routeRegistrar(router); err != nil { - log.Fatal(err) - } - } - - addr := fmt.Sprintf(":%d", 8080) - - log.Printf("Serving on %q", addr) - http.ListenAndServe(addr, router) - -} \ No newline at end of file diff --git a/cmd/iris/sh_tests/stake.sh b/cmd/iris/sh_tests/stake.sh deleted file mode 100644 index 6682ec347..000000000 --- a/cmd/iris/sh_tests/stake.sh +++ /dev/null @@ -1,276 +0,0 @@ -#!/bin/bash -set -u - -# These global variables are required for common.sh -SERVER_EXE="iris node --log_level=debug" -CLIENT_EXE="iris client" -ACCOUNTS=(jae ethan bucky rigel igor) -RICH=${ACCOUNTS[0]} -DELEGATOR=${ACCOUNTS[2]} -POOR=${ACCOUNTS[4]} - -BASE_DIR=$HOME/stake_test -BASE_DIR2=$HOME/stake_test2 -SERVER1=$BASE_DIR/server -SERVER2=$BASE_DIR2/server - -oneTimeSetUp() { - #[ "$2" ] || echo "missing parameters, line=${LINENO}" ; exit 1; - - - # These are passed in as args - CHAIN_ID="stake_test" - - # TODO Make this more robust - if [ "$BASE_DIR" == "$HOME/" ]; then - echo "Must be called with argument, or it will wipe your home directory" - exit 1 - fi - - rm -rf $BASE_DIR 2>/dev/null - mkdir -p $BASE_DIR - - if [ "$BASE_DIR2" == "$HOME/" ]; then - echo "Must be called with argument, or it will wipe your home directory" - exit 1 - fi - rm -rf $BASE_DIR2 2>/dev/null - mkdir -p $BASE_DIR2 - - # Set up client - make sure you use the proper prefix if you set - # a custom CLIENT_EXE - export BC_HOME=${BASE_DIR}/client - prepareClient - - # start the node server - set +u ; initServer $BASE_DIR $CHAIN_ID ; set -u - if [ $? != 0 ]; then return 1; fi - - set +u ; initClient $CHAIN_ID ; set -u - if [ $? != 0 ]; then return 1; fi - - printf "...Testing may begin!\n\n\n" - -} - -oneTimeTearDown() { - kill -9 $PID_SERVER2 >/dev/null 2>&1 - set +u ; quickTearDown ; set -u -} - -# XXX Ex Usage: checkCandidate $PUBKEY $EXPECTED_VOTING_POWER -checkCandidate() { - CANDIDATE=$(${CLIENT_EXE} query candidate --pubkey=$1) - if ! assertTrue "line=${LINENO}, bad query" $?; then - return 1 - fi - assertEquals "line=${LINENO}, proper voting power" "$2" $(echo $CANDIDATE | jq .data.voting_power) - return $? -} - -# XXX Ex Usage: checkCandidate $PUBKEY -checkCandidateEmpty() { - CANDIDATE=$(${CLIENT_EXE} query candidate --pubkey=$1 2>/dev/null) - if ! assertFalse "line=${LINENO}, expected empty query" $?; then - return 1 - fi -} - -# XXX Ex Usage: checkCandidate $DELEGATOR_ADDR $PUBKEY $EXPECTED_SHARES -checkDelegatorBond() { - BOND=$(${CLIENT_EXE} query delegator-bond --delegator-address=$1 --pubkey=$2) - if ! assertTrue "line=${LINENO}, account must exist" $?; then - return 1 - fi - assertEquals "line=${LINENO}, proper bond amount" "$3" $(echo $BOND | jq .data.Shares) - return $? -} - -# XXX Ex Usage: checkCandidate $DELEGATOR_ADDR $PUBKEY -checkDelegatorBondEmpty() { - BOND=$(${CLIENT_EXE} query delegator-bond --delegator-address=$1 --pubkey=$2 2>/dev/null) - if ! assertFalse "line=${LINENO}, expected empty query" $?; then - return 1 - fi -} - -#______________________________________________________________________________________ - -test00GetAccount() { - SENDER=$(getAddr $RICH) - RECV=$(getAddr $POOR) - - assertFalse "line=${LINENO}, requires arg" "${CLIENT_EXE} query account" - - set +u ; checkAccount $SENDER "9007199254740992" ; set -u - - ACCT2=$(${CLIENT_EXE} query account $RECV 2>/dev/null) - assertFalse "line=${LINENO}, has no genesis account" $? -} - -test01SendTx() { - assertFalse "line=${LINENO}, missing dest" "${CLIENT_EXE} tx send --amount=992fermion --sequence=1" - assertFalse "line=${LINENO}, bad password" "echo foo | ${CLIENT_EXE} tx send --amount=992fermion --sequence=1 --to=$RECV --name=$RICH" - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx send --amount=992fermion --sequence=1 --to=$RECV --name=$RICH) - txSucceeded $? "$TX" "$RECV" - HASH=$(echo $TX | jq .hash | tr -d \") - TX_HEIGHT=$(echo $TX | jq .height) - - set +u - checkAccount $SENDER "9007199254740000" $TX_HEIGHT - # make sure 0x prefix also works - checkAccount "0x$SENDER" "9007199254740000" $TX_HEIGHT - checkAccount $RECV "992" $TX_HEIGHT - - # Make sure tx is indexed - checkSendTx $HASH $TX_HEIGHT $SENDER "992" - set -u -} - -test02DeclareCandidacy() { - - # the premise of this test is to run a second validator (from rich) and then bond and unbond some tokens - # first create a second node to run and connect to the system - - # init the second node - SERVER_LOG2=$BASE_DIR2/node2.log - GENKEY=$(${CLIENT_EXE} keys get ${RICH} | awk '{print $2}') - ${SERVER_EXE} init $GENKEY --chain-id $CHAIN_ID --home=$SERVER2 >>$SERVER_LOG2 - if [ $? != 0 ]; then return 1; fi - - # copy in the genesis from the first initialization to the new server - cp $SERVER1/config/genesis.json $SERVER2/config/genesis.json - - # point the new config to the old server location - rm $SERVER2/config/config.toml - echo 'proxy_app = "tcp://127.0.0.1:46668" - moniker = "anonymous" - fast_sync = true - db_backend = "leveldb" - log_level = "state:info,*:error" - - [rpc] - laddr = "tcp://0.0.0.0:46667" - - [p2p] - laddr = "tcp://0.0.0.0:46666" - seeds = "0.0.0.0:46656"' >$SERVER2/config/config.toml - - # start the second node - ${SERVER_EXE} start --home=$SERVER2 >>$SERVER_LOG2 2>&1 & - sleep 1 - PID_SERVER2=$! - disown - if ! ps $PID_SERVER2 >/dev/null; then - echo "**FAILED**" - cat $SERVER_LOG2 - return 1 - fi - - # get the pubkey of the second validator - PK2=$(cat $SERVER2/config/priv_validator.json | jq -r .pub_key.data) - - CAND_ADDR=$(getAddr $POOR) - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx declare-candidacy --sequence=1 --amount=2fermion --name=$POOR --pubkey=$PK2 --moniker=rigey) - if [ $? != 0 ]; then return 1; fi - HASH=$(echo $TX | jq .hash | tr -d \") - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $CAND_ADDR "990" $TX_HEIGHT ; set -u - checkCandidate $PK2 "2" - checkDelegatorBond $CAND_ADDR $PK2 "2" -} - -test03Delegate() { - # send some coins to a delegator - DELA_ADDR=$(getAddr $DELEGATOR) - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx send --sequence=2 --amount=5fermion --to=$DELA_ADDR --name=$RICH) - txSucceeded $? "$TX" "$DELA_ADDR" - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "5" $TX_HEIGHT ; set -u - - # delegate some coins to the new - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=1 --amount=1fermion --name=$DELEGATOR --pubkey=$PK2) - if [ $? != 0 ]; then return 1; fi - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "4" $TX_HEIGHT ; set -u - checkCandidate $PK2 "3" - checkDelegatorBond $DELA_ADDR $PK2 "1" - - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=2 --amount=2fermion --name=$DELEGATOR --pubkey=$PK2) - if [ $? != 0 ]; then return 1; fi - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u - checkCandidate $PK2 "5" - checkDelegatorBond $DELA_ADDR $PK2 "3" - - # attempt a delegation without enough funds - # NOTE the sequence number still increments here because it will fail - # only during DeliverTx - however this should be updated (TODO) in new - # SDK when we can fail in CheckTx - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=3 --amount=3fermion --name=$DELEGATOR --pubkey=$PK2 2>/dev/null) - if [ $? == 0 ]; then return 1; fi - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u - checkCandidate $PK2 "5" - checkDelegatorBond $DELA_ADDR $PK2 "3" - - # perform the final delegation which should empty the delegators account - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=4 --amount=2fermion --name=$DELEGATOR --pubkey=$PK2) - if [ $? != 0 ]; then return 1; fi - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "null" $TX_HEIGHT ; set -u #empty account is null - checkCandidate $PK2 "7" - checkDelegatorBond $DELA_ADDR $PK2 "5" -} - -test04Unbond() { - # unbond from the delegator a bit - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=5 --shares=2 --name=$DELEGATOR --pubkey=$PK2) - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u - checkCandidate $PK2 "5" - checkDelegatorBond $DELA_ADDR $PK2 "3" - - # attempt to unbond more shares than exist - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=6 --shares=10 --name=$DELEGATOR --pubkey=$PK2 2>/dev/null) - if [ $? == 0 ]; then return 1; fi - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u - checkCandidate $PK2 "5" - checkDelegatorBond $DELA_ADDR $PK2 "3" - - # unbond entirely from the delegator - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=6 --shares=3 --name=$DELEGATOR --pubkey=$PK2) - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "5" $TX_HEIGHT ; set -u - checkCandidate $PK2 "2" - checkDelegatorBondEmpty $DELA_ADDR $PK2 - - # unbond a bit from the owner - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=2 --shares=1 --name=$POOR --pubkey=$PK2) - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $CAND_ADDR "991" $TX_HEIGHT ; set -u - checkCandidate $PK2 "1" - checkDelegatorBond $CAND_ADDR $PK2 "1" - - # attempt to unbond more shares than exist - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=3 --shares=10 --name=$POOR --pubkey=$PK2 2>/dev/null) - if [ $? == 0 ]; then return 1; fi - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $CAND_ADDR "991" $TX_HEIGHT ; set -u - checkCandidate $PK2 "1" - checkDelegatorBond $CAND_ADDR $PK2 "1" - - # unbond entirely from the validator - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=3 --shares=1 --name=$POOR --pubkey=$PK2) - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $CAND_ADDR "992" $TX_HEIGHT ; set -u - checkCandidateEmpty $PK2 - checkDelegatorBondEmpty $CAND_ADDR $PK2 -} - -# Load common then run these tests with shunit2! -CLI_DIR=$GOPATH/src/github.com/cosmos/gaia/vendor/github.com/cosmos/cosmos-sdk/tests/cli - -. $CLI_DIR/common.sh -. $CLI_DIR/shunit2 diff --git a/cmd/iriscli/lcd.go b/cmd/iriscli/lcd.go new file mode 100644 index 000000000..172a466c3 --- /dev/null +++ b/cmd/iriscli/lcd.go @@ -0,0 +1,85 @@ +package main + +import ( + "net/http" + "os" + + "github.com/gorilla/mux" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/tendermint/tmlibs/log" + + tmserver "github.com/tendermint/tendermint/rpc/lib/server" + cmn "github.com/tendermint/tmlibs/common" + + client "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" + keys "github.com/cosmos/cosmos-sdk/client/keys" + rpc "github.com/cosmos/cosmos-sdk/client/rpc" + tx "github.com/cosmos/cosmos-sdk/client/tx" + version "github.com/cosmos/cosmos-sdk/version" + "github.com/cosmos/cosmos-sdk/wire" + auth "github.com/cosmos/cosmos-sdk/x/auth/client/rest" + bank "github.com/cosmos/cosmos-sdk/x/bank/client/rest" + ibc "github.com/cosmos/cosmos-sdk/x/ibc/client/rest" + stake "github.com/cosmos/cosmos-sdk/x/stake/client/rest" +) + +// ServeCommand will generate a long-running rest server +// (aka Light Client Daemon) that exposes functionality similar +// to the cli, but over rest +func ServeCommand(cdc *wire.Codec) *cobra.Command { + flagListenAddr := "laddr" + flagCORS := "cors" + + cmd := &cobra.Command{ + Use: "rest-server", + Short: "Start LCD (light-client daemon), a local REST server", + RunE: func(cmd *cobra.Command, args []string) error { + listenAddr := viper.GetString(flagListenAddr) + handler := createHandler(cdc) + logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)). + With("module", "rest-server") + listener, err := tmserver.StartHTTPServer(listenAddr, handler, logger) + if err != nil { + return err + } + logger.Info("REST server started") + + // Wait forever and cleanup + cmn.TrapSignal(func() { + err := listener.Close() + logger.Error("Error closing listener", "err", err) + }) + return nil + }, + } + cmd.Flags().StringP(flagListenAddr, "a", "tcp://localhost:1317", "Address for server to listen on") + cmd.Flags().String(flagCORS, "", "Set to domains that can make CORS requests (* for all)") + cmd.Flags().StringP(client.FlagChainID, "c", "", "ID of chain we connect to") + cmd.Flags().StringP(client.FlagNode, "n", "tcp://localhost:46657", "Node to connect to") + return cmd +} + +func createHandler(cdc *wire.Codec) http.Handler { + r := mux.NewRouter() + r.HandleFunc("/version", version.RequestHandler).Methods("GET") + + kb, err := keys.GetKeyBase() //XXX + if err != nil { + panic(err) + } + + ctx := context.NewCoreContextFromViper() + + // TODO make more functional? aka r = keys.RegisterRoutes(r) + keys.RegisterRoutes(r) + rpc.RegisterRoutes(ctx, r) + tx.RegisterRoutes(ctx, r, cdc) + auth.RegisterRoutes(ctx, r, cdc, "acc") + bank.RegisterRoutes(ctx, r, cdc, kb) + ibc.RegisterRoutes(ctx, r, cdc, kb) + stake.RegisterRoutes(ctx, r, cdc, kb) + RegisterRoutes(ctx,r,cdc,kb) + return r +} diff --git a/cmd/iriscli/main.go b/cmd/iriscli/main.go new file mode 100644 index 000000000..412a265db --- /dev/null +++ b/cmd/iriscli/main.go @@ -0,0 +1,121 @@ +package main + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/client/rpc" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/spf13/cobra" + "github.com/tendermint/tmlibs/cli" + + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" + ibccmd "github.com/cosmos/cosmos-sdk/x/ibc/client/cli" + slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" + stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" + "github.com/irisnet/iris-hub/app" + "github.com/irisnet/iris-hub/version" +) + +// rootCmd is the entry point for this binary +var ( + rootCmd = &cobra.Command{ + Use: "iriscli", + Short: "iris-hub light-client", + } +) + +func main() { + cobra.EnableCommandSorting = false + cdc := app.MakeCodec() + + // TODO: setup keybase, viper object, etc. to be passed into + // the below functions and eliminate global vars, like we do + // with the cdc + + // add standard rpc commands + rpc.AddCommands(rootCmd) + + //Add state commands + tendermintCmd := &cobra.Command{ + Use: "tendermint", + Short: "Tendermint state querying subcommands", + } + tendermintCmd.AddCommand( + rpc.BlockCommand(), + rpc.ValidatorCommand(), + ) + tx.AddCommands(tendermintCmd, cdc) + + //Add IBC commands + ibcCmd := &cobra.Command{ + Use: "ibc", + Short: "Inter-Blockchain Communication subcommands", + } + ibcCmd.AddCommand( + client.PostCommands( + ibccmd.IBCTransferCmd(cdc), + ibccmd.IBCRelayCmd(cdc), + )...) + + advancedCmd := &cobra.Command{ + Use: "advanced", + Short: "Advanced subcommands", + } + + advancedCmd.AddCommand( + tendermintCmd, + ibcCmd, + ServeCommand(cdc), + ) + rootCmd.AddCommand( + advancedCmd, + client.LineBreak, + ) + + //Add stake commands + stakeCmd := &cobra.Command{ + Use: "stake", + Short: "Stake and validation subcommands", + } + stakeCmd.AddCommand( + client.GetCommands( + stakecmd.GetCmdQueryValidator("stake", cdc), + stakecmd.GetCmdQueryValidators("stake", cdc), + stakecmd.GetCmdQueryDelegation("stake", cdc), + stakecmd.GetCmdQueryDelegations("stake", cdc), + slashingcmd.GetCmdQuerySigningInfo("slashing", cdc), + )...) + stakeCmd.AddCommand( + client.PostCommands( + stakecmd.GetCmdCreateValidator(cdc), + stakecmd.GetCmdEditValidator(cdc), + stakecmd.GetCmdDelegate(cdc), + stakecmd.GetCmdUnbond(cdc), + slashingcmd.GetCmdUnrevoke(cdc), + )...) + rootCmd.AddCommand( + stakeCmd, + ) + + //Add auth and bank commands + rootCmd.AddCommand( + client.GetCommands( + authcmd.GetAccountCmd("acc", cdc, authcmd.GetAccountDecoder(cdc)), + )...) + rootCmd.AddCommand( + client.PostCommands( + bankcmd.SendTxCmd(cdc), + )...) + + // add proxy, version and key info + rootCmd.AddCommand( + keys.Commands(), + client.LineBreak, + version.VersionCmd, + ) + + // prepare and add flags + executor := cli.PrepareMainCmd(rootCmd, "IRIS", app.DefaultCLIHome) + executor.Execute() +} diff --git a/cmd/iriscli/offline_sign.go b/cmd/iriscli/offline_sign.go new file mode 100644 index 000000000..180d705ca --- /dev/null +++ b/cmd/iriscli/offline_sign.go @@ -0,0 +1,55 @@ +package main + +import ( + "github.com/cosmos/cosmos-sdk/wire" + "encoding/json" + "github.com/tendermint/go-crypto/keys" + "github.com/cosmos/cosmos-sdk/client/context" + "net/http" + "github.com/gorilla/mux" + "io/ioutil" +) + + +func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { + r.HandleFunc("/tx/send", SendTxRequestHandlerFn(cdc, kb, ctx)).Methods("POST") +} + +// /accounts/{address} +type sendTxReq struct { + tx []byte +} + +//send traction(sign with rainbow) to irishub +func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var sendReq sendTxReq + body, err := ioutil.ReadAll(r.Body) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + if err = json.Unmarshal(body, &sendReq); err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + // send + res, err := ctx.BroadcastTx(sendReq.tx) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + output, err := json.MarshalIndent(res, "", " ") + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + w.Write(output) + } +} \ No newline at end of file diff --git a/glide.lock b/glide.lock deleted file mode 100644 index 0e912f491..000000000 --- a/glide.lock +++ /dev/null @@ -1,305 +0,0 @@ -hash: 20e25ba77f4c08127c8b87786d0bb7d3868e6c8a0bfe9f80f63ce831b25663ec -updated: 2018-03-07T11:54:26.85382+08:00 -imports: -- name: github.com/bgentry/speakeasy - version: 4aabc24848ce5fd31929f7d1e4ea74d3709c14cd -- name: github.com/btcsuite/btcd - version: 2e60448ffcc6bf78332d1fe590260095f554dd78 - subpackages: - - btcec -- name: github.com/BurntSushi/toml - version: b26d9c308763d68093482582cea63d69be07a0f0 -- name: github.com/cosmos/cosmos-sdk - version: f1b1d36324812dc221da87f56734a5c25d8754aa - subpackages: - - app - - client - - client/commands - - client/commands/commits - - client/commands/keys - - client/commands/proxy - - client/commands/query - - client/commands/rpc - - client/commands/search - - client/commands/txs - - client/rest - - errors - - genesis - - modules/auth - - modules/auth/commands - - modules/base - - modules/base/commands - - modules/coin - - modules/coin/commands - - modules/coin/rest - - modules/fee - - modules/fee/commands - - modules/ibc - - modules/ibc/commands - - modules/nonce - - modules/nonce/commands - - modules/nonce/rest - - modules/roles - - modules/roles/commands - - modules/roles/rest - - server/commands - - stack - - state - - version -- name: github.com/MrXJC/gaia - version: develop - subpackages: - - modules/stake - - modules/stake/commands - - modules/stake/rest - - version -- name: github.com/ebuchman/fail-test - version: 95f809107225be108efcf10a3509e4ea6ceef3c4 -- name: github.com/fsnotify/fsnotify - version: 4da3e2cfbabc9f751898f250b49f2439785783a1 -- name: github.com/go-kit/kit - version: 4dc7be5d2d12881735283bcab7352178e190fc71 - subpackages: - - log - - log/level - - log/term -- name: github.com/go-logfmt/logfmt - version: 390ab7935ee28ec6b286364bba9b4dd6410cb3d5 -- name: github.com/go-playground/locales - version: e4cbcb5d0652150d40ad0646651076b6bd2be4f6 - subpackages: - - currency -- name: github.com/go-playground/universal-translator - version: 71201497bace774495daed26a3874fd339e0b538 -- name: github.com/go-stack/stack - version: 259ab82a6cad3992b4e21ff5cac294ccb06474bc -- name: github.com/gogo/protobuf - version: 1adfc126b41513cc696b209667c8656ea7aac67c - subpackages: - - gogoproto - - jsonpb - - proto - - protoc-gen-gogo/descriptor - - sortkeys - - types -- name: github.com/golang/protobuf - version: 925541529c1fa6821df4e44ce2723319eb2be768 - subpackages: - - proto - - ptypes - - ptypes/any - - ptypes/duration - - ptypes/timestamp -- name: github.com/golang/snappy - version: 553a641470496b2327abcac10b36396bd98e45c9 -- name: github.com/gorilla/context - version: 08b5f424b9271eedf6f9f0ce86cb9396ed337a42 -- name: github.com/gorilla/mux - version: 53c1911da2b537f792e7cafcb446b05ffe33b996 -- name: github.com/gorilla/websocket - version: ea4d1f681babbce9545c9c5f3d5194a789c89f5b -- name: github.com/hashicorp/hcl - version: 23c074d0eceb2b8a5bfdbb271ab780cde70f05a8 - subpackages: - - hcl/ast - - hcl/parser - - hcl/scanner - - hcl/strconv - - hcl/token - - json/parser - - json/scanner - - json/token -- name: github.com/howeyc/crc16 - version: 2b2a61e366a66d3efb279e46176e7291001e0354 -- name: github.com/inconshreveable/mousetrap - version: 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 -- name: github.com/jmhodges/levigo - version: c42d9e0ca023e2198120196f842701bb4c55d7b9 -- name: github.com/kr/logfmt - version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0 -- name: github.com/magiconair/properties - version: 49d762b9817ba1c2e9d0c69183c2b4a8b8f1d934 -- name: github.com/mattn/go-isatty - version: 0360b2af4f38e8d38c7fce2a9f4e702702d73a39 -- name: github.com/mitchellh/mapstructure - version: 06020f85339e21b2478f756a78e295255ffa4d6a -- name: github.com/pelletier/go-toml - version: 4e9e0ee19b60b13eb79915933f44d8ed5f268bdd -- name: github.com/pkg/errors - version: 645ef00459ed84a119197bfb8d8205042c6df63d -- name: github.com/rcrowley/go-metrics - version: e181e095bae94582363434144c61a9653aff6e50 -- name: github.com/spf13/afero - version: 8d919cbe7e2627e417f3e45c3c0e489a5b7e2536 - subpackages: - - mem -- name: github.com/spf13/cast - version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 -- name: github.com/spf13/cobra - version: 7b2c5ac9fc04fc5efafb60700713d4fa609b777b -- name: github.com/spf13/jwalterweatherman - version: 12bd96e66386c1960ab0f74ced1362f66f552f7b -- name: github.com/spf13/pflag - version: e57e3eeb33f795204c1ca35f56c44f83227c6e66 -- name: github.com/spf13/viper - version: 25b30aa063fc18e48662b86996252eabdcf2f0c7 -- name: github.com/syndtr/goleveldb - version: adf24ef3f94bd13ec4163060b21a5678f22b429b - subpackages: - - leveldb - - leveldb/cache - - leveldb/comparer - - leveldb/errors - - leveldb/filter - - leveldb/iterator - - leveldb/journal - - leveldb/memdb - - leveldb/opt - - leveldb/storage - - leveldb/table - - leveldb/util -- name: github.com/tendermint/abci - version: 3d5f0a8b94bbbfa70ecd4072fc55854f8210425b - subpackages: - - client - - example/code - - example/kvstore - - server - - types -- name: github.com/tendermint/ed25519 - version: d8387025d2b9d158cf4efb07e7ebf814bcce2057 - subpackages: - - edwards25519 - - extra25519 -- name: github.com/tendermint/go-crypto - version: 2017856384589234024cda848a6332157d1f527c - subpackages: - - keys - - keys/cryptostore - - keys/storage/filestorage - - keys/wordlist -- name: github.com/tendermint/go-wire - version: b6fc872b42d41158a60307db4da051dd6f179415 - subpackages: - - data -- name: github.com/tendermint/iavl - version: 39de8f0b4ee758fdd5bb3a9afc6dd9bf42c04785 -- name: github.com/tendermint/tendermint - version: 9c5937df969de23e9087f183c52b5088d4b6f268 - subpackages: - - blockchain - - cmd/tendermint/commands - - config - - consensus - - consensus/types - - evidence - - lite - - lite/client - - lite/errors - - lite/files - - lite/proxy - - mempool - - node - - p2p - - p2p/conn - - p2p/pex - - p2p/trust - - p2p/upnp - - proxy - - rpc/client - - rpc/core - - rpc/core/types - - rpc/grpc - - rpc/lib - - rpc/lib/client - - rpc/lib/server - - rpc/lib/types - - state - - state/txindex - - state/txindex/kv - - state/txindex/null - - types - - version -- name: github.com/tendermint/tmlibs - version: 26f2ab65f82cfc6873c312e8030104c47c05f10e - subpackages: - - autofile - - cli - - cli/flags - - clist - - common - - db - - flowrate - - log - - merkle - - pubsub - - pubsub/query -- name: golang.org/x/crypto - version: 94eea52f7b742c7cbe0b03b22f0c4c8631ece122 - subpackages: - - curve25519 - - nacl/box - - nacl/secretbox - - openpgp/armor - - openpgp/errors - - poly1305 - - ripemd160 - - salsa20/salsa -- name: golang.org/x/net - version: 5ccada7d0a7ba9aeb5d3aca8d3501b4c2a509fec - subpackages: - - context - - http2 - - http2/hpack - - idna - - internal/timeseries - - lex/httplex - - trace -- name: golang.org/x/sys - version: 8b4580aae2a0dd0c231a45d3ccb8434ff533b840 - subpackages: - - unix -- name: golang.org/x/text - version: 57961680700a5336d15015c8c50686ca5ba362a4 - subpackages: - - secure/bidirule - - transform - - unicode/bidi - - unicode/norm -- name: google.golang.org/genproto - version: a8101f21cf983e773d0c1133ebc5424792003214 - repo: https://github.com/google/go-genproto - vcs: git - subpackages: - - googleapis/rpc/status -- name: google.golang.org/grpc - version: 401e0e00e4bb830a10496d64cd95e068c5bf50de - repo: https://github.com/grpc/grpc-go - vcs: git - subpackages: - - balancer - - codes - - connectivity - - credentials - - grpclb/grpc_lb_v1/messages - - grpclog - - internal - - keepalive - - metadata - - naming - - peer - - resolver - - stats - - status - - tap - - transport -- name: gopkg.in/go-playground/validator.v9 - version: 1b8c8e19cd250435025214492d9a08411d760fdd -- name: gopkg.in/yaml.v2 - version: 287cf08546ab5e7e37d55a84f7ed3fd1db036de5 -testImports: -- name: github.com/stretchr/testify - version: 2aa2c176b9dab406a6970f6a55f513e8a8c8b18f - subpackages: - - assert - - require diff --git a/glide.yaml b/glide.yaml deleted file mode 100644 index a279a3c69..000000000 --- a/glide.yaml +++ /dev/null @@ -1,17 +0,0 @@ -package: github.com/irisnet/iris-hub -import: -- package: github.com/MrXJC/gaia - version: develop -- package: github.com/cosmos/cosmos-sdk - version: tm-develop -- package: google.golang.org/grpc - repo: https://github.com/grpc/grpc-go - vcs: git -- package: google.golang.org/genproto - repo: https://github.com/google/go-genproto - vcs: git -testImport: -- package: github.com/stretchr/testify - subpackages: - - assert - - require diff --git a/module/rest-txs/txs.go b/module/rest-txs/txs.go deleted file mode 100644 index 72230d389..000000000 --- a/module/rest-txs/txs.go +++ /dev/null @@ -1,53 +0,0 @@ -package rest_txs - -import ( - "net/http" - - "github.com/gorilla/mux" - wire "github.com/tendermint/go-wire" - rpcclient "github.com/tendermint/tendermint/rpc/client" - - sdk "github.com/cosmos/cosmos-sdk" -) - -// ServiceTxs exposes a REST API service for sendings txs. -// It wraps a Tendermint RPC client. -type ServiceTxs struct { - node rpcclient.Client -} - -func NewServiceTxs(c rpcclient.Client) *ServiceTxs { - return &ServiceTxs{ - node: c, - } -} - -func (s *ServiceTxs) PostTx(w http.ResponseWriter, r *http.Request) { - tx := new(sdk.Tx) - if err := sdk.ParseRequestAndValidateJSON(r, tx); err != nil { - sdk.WriteError(w, err) - return - } - - packet := wire.BinaryBytes(*tx) - // commit, err := s.node.BroadcastTxCommit(packet) - commit, err := s.node.BroadcastTxSync(packet) - if err != nil { - sdk.WriteError(w, err) - return - } - - sdk.WriteSuccess(w, commit) -} - -// mux.Router registrars - -// RegisterPostTx is a mux.Router handler that exposes POST -// method access to post a transaction to the blockchain. -func (s *ServiceTxs) RegisterPostTx(r *mux.Router) error { - r.HandleFunc("/tx", s.PostTx).Methods("POST") - return nil -} - -// End of mux.Router registrars - diff --git a/rest/byteTx.go b/rest/byteTx.go deleted file mode 100644 index 604af6c55..000000000 --- a/rest/byteTx.go +++ /dev/null @@ -1,118 +0,0 @@ -package rest - -import ( - "github.com/gorilla/mux" - "github.com/tendermint/go-crypto/keys" - "net/http" - sdk "github.com/cosmos/cosmos-sdk" - "encoding/hex" - "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client/commands" - "github.com/pkg/errors" - cmn "github.com/tendermint/tmlibs/common" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/commands/query" - "github.com/tendermint/tendermint/types" - "github.com/tendermint/go-wire" - "io" -) - - -type ServiceByteTx struct { - manager keys.Manager -} - -type RequestTx struct { - Tx sdk.Tx `json:"tx" validate:"required"` -} - -func NewServiceByteTx(manager keys.Manager) *ServiceByteTx { - return &ServiceByteTx{ - manager: manager, // XXX keycmd.GetKeyManager() - } -} - -func (s *ServiceByteTx) RegisterByteTx(r *mux.Router) error { - r.HandleFunc("/byteTx", s.ByteTx).Methods("POST") - return nil -} - - -func (s *ServiceByteTx) RegisterqueryTx(r *mux.Router) error { - r.HandleFunc("/tx/{hash}", s.queryTx).Methods("GET") - return nil -} - -func (s *ServiceByteTx) ByteTx(w http.ResponseWriter, r *http.Request) { - req := new(RequestTx) - if err := sdk.ParseRequestAndValidateJSON(r, req); err != nil { - sdk.WriteError(w, err) - return - } - - tx := req.Tx - - if sign, ok := tx.Unwrap().(keys.Signable); ok { - sdk.WriteSuccess(w, hex.EncodeToString(sign.SignBytes())) - return - } - sdk.WriteSuccess(w, "") -} - -func (s *ServiceByteTx) queryTx(w http.ResponseWriter, r *http.Request){ - args := mux.Vars(r) - hash := args["hash"] - - if hash == "" { - sdk.WriteError(w, errors.Errorf("[%s] argument must be non-empty ", "hash")) - return - } - // with tx, we always just parse key as hex and use to lookup - hashByte, err := hex.DecodeString(cmn.StripHex(hash)) - - // get the proof -> this will be used by all prover commands - node := commands.GetNode() - prove := !viper.GetBool(commands.FlagTrustNode) - res, err := node.Tx(hashByte, prove) - if err != nil { - sdk.WriteError(w, err) - return - } - - // no checks if we don't get a proof - if !prove { - sdk.WriteSuccess(w,showTx(w,res.Height, res.Tx)) - return - } - - cert, err := commands.GetCertifier() - if err != nil { - sdk.WriteError(w, err) - return - } - - check, err := client.GetCertifiedCommit(res.Height, node, cert) - if err != nil { - sdk.WriteError(w, err) - return - } - err = res.Proof.Validate(check.Header.DataHash) - if err != nil { - sdk.WriteError(w, err) - return - } - - // note that we return res.Proof.Data, not res.Tx, - // as res.Proof.Validate only verifies res.Proof.Data - sdk.WriteSuccess(w,showTx(w,res.Height, res.Proof.Data)) -} - -// showTx parses anything that was previously registered as sdk.Tx -func showTx(w io.Writer ,h int64, tx types.Tx) error { - var info sdk.Tx - err := wire.ReadBinaryBytes(tx, &info) - if err != nil { - return err - } - return query.FoutputProof(w,info,h) -} \ No newline at end of file diff --git a/version/version.go b/version/version.go index 720c65e4b..c1fef8fe7 100644 --- a/version/version.go +++ b/version/version.go @@ -7,7 +7,7 @@ import ( ) // Version - Iris Version -const Version = "0.1.0" +const Version = "0.2.0" // VersionCmd - The version of gaia var VersionCmd = &cobra.Command{ From c2d5df780af9f6aa23d765d4f96a0911f5be147f Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Wed, 20 Jun 2018 11:48:38 +0800 Subject: [PATCH 019/124] update iris-hub to irishub --- README.md | 10 +++++----- cmd/iris/main.go | 2 +- cmd/iriscli/main.go | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 049404cc0..2b00f4b59 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# Iris-Hub +# irishub Iris Hub是在Cosmos生态中的区域性枢纽,提供iService服务 ## 下载发行版安装 - * 进入下载页: https://github.com/irisnet/iris-hub/releases/tag/0.1.0 + * 进入下载页: https://github.com/irisnet/irishub/releases/tag/0.1.0 * 下载对应版本的可执行文件 * 解压缩`tar -C /usr/local -xzf iris$VERSION.$OS-$ARCH.zip` * 拷贝到`/usr/local/`目录下 @@ -85,8 +85,8 @@ hello ## 安装步骤 ``` -go get github.com/irisnet/iris-hub -cd $GOPATH/src/github.com/irisnet/iris-hub +go get github.com/irisnet/irishub +cd $GOPATH/src/github.com/irisnet/irishub make all iris version ``` @@ -105,7 +105,7 @@ iris client keys new $MYNAME iris client keys list MYADDR= ``` -2. 初始化iris-hub: +2. 初始化irishub: ``` iris node init $MYADDR --home=$HOME/.iris1 --chain-id=test diff --git a/cmd/iris/main.go b/cmd/iris/main.go index b36718838..4d292dcd7 100644 --- a/cmd/iris/main.go +++ b/cmd/iris/main.go @@ -11,7 +11,7 @@ import ( dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/tmlibs/log" "github.com/cosmos/cosmos-sdk/server" - "github.com/irisnet/iris-hub/app" + "github.com/irisnet/irishub/app" ) func main() { diff --git a/cmd/iriscli/main.go b/cmd/iriscli/main.go index 412a265db..e379c208e 100644 --- a/cmd/iriscli/main.go +++ b/cmd/iriscli/main.go @@ -13,15 +13,15 @@ import ( ibccmd "github.com/cosmos/cosmos-sdk/x/ibc/client/cli" slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" - "github.com/irisnet/iris-hub/app" - "github.com/irisnet/iris-hub/version" + "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/version" ) // rootCmd is the entry point for this binary var ( rootCmd = &cobra.Command{ Use: "iriscli", - Short: "iris-hub light-client", + Short: "irishub light-client", } ) From 39b30a61e07d41cfef9747578f5958a149aa16af Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Wed, 20 Jun 2018 11:54:23 +0800 Subject: [PATCH 020/124] update iris-hub to irishub --- Makefile | 2 +- cmd/iris/main.go | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 077b9dc9d..345f80662 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ get_vendor_deps: install: go install ./cmd/iris - go build ./cmd/iriscli + go install ./cmd/iriscli build_linux: CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iris ./cmd/iris && \ diff --git a/cmd/iris/main.go b/cmd/iris/main.go index 4d292dcd7..1ff4de55c 100644 --- a/cmd/iris/main.go +++ b/cmd/iris/main.go @@ -12,6 +12,7 @@ import ( "github.com/tendermint/tmlibs/log" "github.com/cosmos/cosmos-sdk/server" "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/version" ) func main() { @@ -28,6 +29,8 @@ func main() { server.ConstructAppCreator(newApp, "iris"), server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")) + + rootCmd.AddCommand(version.VersionCmd) // prepare and add flags executor := cli.PrepareBaseCmd(rootCmd, "IRIS", app.DefaultNodeHome) executor.Execute() From 1ec9da258677dcc56ae88c92cce8943fa4785207 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Wed, 20 Jun 2018 13:27:08 +0800 Subject: [PATCH 021/124] update iris version command --- cmd/iris/main.go | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/cmd/iris/main.go b/cmd/iris/main.go index 1ff4de55c..69dcf0bf4 100644 --- a/cmd/iris/main.go +++ b/cmd/iris/main.go @@ -10,6 +10,7 @@ import ( "github.com/tendermint/tmlibs/cli" dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/tmlibs/log" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" "github.com/irisnet/irishub/app" "github.com/irisnet/irishub/version" @@ -25,12 +26,29 @@ func main() { PersistentPreRunE: server.PersistentPreRunEFn(ctx), } - server.AddCommands(ctx, cdc, rootCmd, app.GaiaAppInit(), - server.ConstructAppCreator(newApp, "iris"), - server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")) + rootCmd.PersistentFlags().String("log_level", ctx.Config.LogLevel, "Log level") + tendermintCmd := &cobra.Command{ + Use: "tendermint", + Short: "Tendermint subcommands", + } + + tendermintCmd.AddCommand( + server.ShowNodeIDCmd(ctx), + server.ShowValidatorCmd(ctx), + ) + + rootCmd.AddCommand( + server.InitCmd(ctx, cdc, app.GaiaAppInit()), + server.StartCmd(ctx, server.ConstructAppCreator(newApp, "iris")), + server.UnsafeResetAllCmd(ctx), + client.LineBreak, + tendermintCmd, + server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), + client.LineBreak, + version.VersionCmd, + ) - rootCmd.AddCommand(version.VersionCmd) // prepare and add flags executor := cli.PrepareBaseCmd(rootCmd, "IRIS", app.DefaultNodeHome) executor.Execute() From 727829851d4d835664338a5f01eb3e922848a9d0 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Wed, 20 Jun 2018 18:30:03 +0800 Subject: [PATCH 022/124] update genesis --- app/genesis.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/genesis.go b/app/genesis.go index c504662b2..736bf1ff5 100644 --- a/app/genesis.go +++ b/app/genesis.go @@ -149,7 +149,7 @@ func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState // start with the default staking genesis state //stakeData := stake.DefaultGenesisState() - stakeData := createGenesisState() + stakeData := stake.DefaultGenesisState() // get genesis flag account information genaccs := make([]GenesisAccount, len(appGenTxs)) @@ -165,10 +165,11 @@ func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState accAuth := auth.NewBaseAccountWithAddress(genTx.Address) accAuth.Coins = sdk.Coins{ {denom, totalTokenAmt}, + {"steak", freeFermionVal}, } acc := NewGenesisAccount(&accAuth) genaccs[i] = acc - stakeData.Pool.LooseUnbondedTokens += totalTokenAmt // increase the supply + stakeData.Pool.LooseUnbondedTokens += freeFermionVal // increase the supply // add the validator if len(genTx.Name) > 0 { @@ -225,7 +226,7 @@ func createGenesisState() stake.GenesisState{ InflationMin: sdk.NewRat(7, 100), GoalBonded: sdk.NewRat(67, 100), MaxValidators: 100, - BondDenom: denom, + BondDenom: "steak", }, } } \ No newline at end of file From 2b3bcf8cebb3d07812c76fb1a422883a2f4c8a3a Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Wed, 20 Jun 2018 19:17:45 +0800 Subject: [PATCH 023/124] #DEVOPS-61 update README.md --- README.md | 217 +++++++++++++++++++----------------------------------- 1 file changed, 75 insertions(+), 142 deletions(-) diff --git a/README.md b/README.md index 2b00f4b59..06606302f 100644 --- a/README.md +++ b/README.md @@ -1,136 +1,92 @@ -# irishub -Iris Hub是在Cosmos生态中的区域性枢纽,提供iService服务 +# IRIS-Hub + +IRIS Hub是在Cosmos生态中的区域性枢纽,提供iService服务 ## 下载发行版安装 - * 进入下载页: https://github.com/irisnet/irishub/releases/tag/0.1.0 - * 下载对应版本的可执行文件 - * 解压缩`tar -C /usr/local -xzf iris$VERSION.$OS-$ARCH.zip` - * 拷贝到`/usr/local/`目录下 -执行 - ``` + +- 进入下载页: https://github.com/irisnet/irishub/releases/ +- 下载对应版本的可执行文件 +- 解压缩`tar -C /usr/local/bin -xzf iris$VERSION.$OS-$ARCH.zip` +- 拷贝到`/usr/local/bin/`目录下 + 执行 + +``` iris version - ``` +``` -若出现`v 0.1.0`则说明安装成功 +若出现对应的版本号则说明安装成功 ## 通过源码编译安装 ### 系统要求 + 操作系统:**Ubuntu 16.04** 架构:**amd64** 要求安装1.9版本以上的Go https://golang.org/doc/install -GO 安装步骤 - -* 下载 -curl -O https://dl.google.com/go/go1.9.4.linux-386.tar.gz +### 安装步骤 -* 解压缩 ``` -tar xvf go1.9.4.linux-386.tar.gz -``` - -* 获得权限 +go get github.com/irisnet/irishub +cd $GOPATH/src/github.com/irisnet/irishub +make all +iris version ``` -sudo chown -R root:root ./go -sudo mv go /usr/local -``` +若出现对应的版本号则说明安装成功 -* 设置GOPATH -``` -export GOPATH=$HOME/work -export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin -``` +### 本地测试网络 -* 测试是否安装成功 -建立一个简单的工程。 +1. 初始化irishub: ``` -mkdir -p work/src/github.com/user/hello +MYNAME1= +iris init --chain-id=test --name=$MYNAME1 --home=$HOME/.iris1 ``` -创建 "Hello World" Go文件. - - -``` -nano ~/work/src/github.com/user/hello/hello.go -``` -修改文件内容如下: +以上命令将在 `$HOME/.iris1/config`目录下创建默认的配置文件 `priv_validator.json`和`genesis.json`。`priv_validator.json` 包含验证人的私钥。`genesis.json`文件包含其他配置信息, 包括创世账户,创世账户的默认密码为`1234567890`,创世账户的助记词会在执行以上命令后输出在控制台,例如: ``` -package main - -import "fmt" - -func main() { - fmt.Printf("hello, world\n") +{ + "chain_id": "test", + "node_id": "e4bcb3c7df9783d32c8a876028a45952b4146c78", + "app_message": { + "secret": "spare detail grass load memory robust expect plunge thank hen limb electric town slot annual abandon" + } } ``` -编译&安装 -``` -go install github.com/user/hello -``` -执行命令 -``` -hello -``` -如果安装成功,将会出现 "hello, world"输出: +其中secret便是创世账户的助记词,可以导入该助记词到iris客户端以重置密码: - -## 安装步骤 ``` -go get github.com/irisnet/irishub -cd $GOPATH/src/github.com/irisnet/irishub -make all -iris version +iriscli keys add $MYNAME1 --recover +override the existing name XXX [y/n]: y +Enter a passphrase for your key: +Repeat the passphrase: +Enter your recovery seed phrase: ``` -若出现`v 0.1.0`则说明安装成功 - -###本地测试网络 - -Here is a quick example to get you off your feet: - -1. 生成和保存测试网络中的测试账户 - -``` -MYNAME= -iris client keys new $MYNAME -iris client keys list -MYADDR= -``` -2. 初始化irishub: +1. 启动irishub: ``` -iris node init $MYADDR --home=$HOME/.iris1 --chain-id=test +iris start --home=$HOME/.iris1 ``` -This will create all the files necessary to run a single node chain in以上命令将在 `$HOME/.iris1/config`目录下创建默认的配置文件 `priv_validator.json`和`genesis.json`。`priv_validator.json` 包含验证人的私钥。`genesis.json`文件包含其他配置信息, `$MYADDR`是默认生成的创世账户。 - -获得节点的Node_ID - -需要下载编辑develop分支的tendermint,或者下载可执行[[文件](https://github.com/kidinamoto01/gaia-testnet/blob/master/gaia-testnet/tendermint-develop-liunx-amd64.zip)] - -执行以下命令获得iris1的Node_ID -``` -tendermint show_node_id --home=$HOME/.iris1 -``` +1. 多节点配置: 同时,你也可以在本地再运行另一个Node,注意新的Node所对应的工作目录不同,但二者公用一个genesis文件。 - ``` -iris node init $MYADDR --home=$HOME/.iris2 --chain-id=test +MYNAME2= +iris init --chain-id=test --name=$MYNAME2 --home=$HOME/.iris2 cp $HOME/.iris1/config/genesis.json $HOME/.iris2/config/genesis.json ``` -修改 `$HOME/.iris2/config/config.toml` 让两个Node可以发现彼此: +修改 `$HOME/.iris2/config/config.toml` ,防止端口冲突,并让两个Node可以发现彼此: ``` proxy_app = "tcp://127.0.0.1:46668" @@ -147,105 +103,82 @@ laddr = "tcp://0.0.0.0:46666" seeds = "@0.0.0.0:46656" ``` +其中node_id可以通过以下命令获取: + +``` +iris tendermint show_node_id --home=$HOME/.iris1 +iris tendermint show_node_id --home=$HOME/.iris2 +``` + 然后就可以同时在后台运行: ``` -iris node start --home=$HOME/.iris1 &> iris1.log & -NODE1_PID=$! -iris node start --home=$HOME/.iris2 &> iris2.log & -NODE2_PID=$! +iris start --home=$HOME/.iris1 &> iris1.log & NODE1_PID=$! +iris start --home=$HOME/.iris2 &> iris2.log & NODE2_PID=$! ``` `PID` 是为了方便之后杀死相关进程。 通过 `tail iris1.log`,或 `tail -f iris1.log`可以对Node 进行监控。 -现在我们初始化客户端,然后查询账户: - -``` -iris client init --chain-id=test --node=tcp://localhost:46657 -iris client query account $MYADDR -``` +1. 现在我们可以使用客户端进行操作 -我们可以测试在账户间转账: +查询本地账户: ``` -MYNAME1= -iris client keys new $MYNAME1 -iris client keys list -MYADDR1= -iris client tx send --amount=1000fermion --to=$MYADDR1 --name=$MYNAME -iris client query $MYADDR1 -iris client query $MYADDR +iriscli keys list ``` -也可以查询 candidate列表: +查询账户余额: ``` -iris client query candidates +iriscli account
``` -很奇怪的是,iris并没有发现initial时生成的validator。这是因为这类validator比较特殊。通过查询tendermint接口,你可以获得初始的validator信息。 +我们可以测试在账户间转账: ``` -curl localhost:46657/validators +iriscli send --name=$MYNAME1 --to=$MYADDR2 --amount=10steak --chain-id=test +iriscli account $MYADDR1 +iriscli account $MYADDR2 ``` -接下来实现第一个validator的添加:首先获得节点的公钥: +也可以查询Validator列表: ``` -cat $HOME/.iris1/config/priv_validator.json -``` - -使用`jq`命令可以快速获得公钥: - +iriscli stake validators ``` -cat $HOME/.iris1/config/priv_validator.json | jq .pub_key.data -``` +接下来实现第一个validator的添加:首先获得节点的公钥: -通过执行以下命令完成绑定 ``` -iris client tx declare-candidacy --amount=1fermion --pubkey= --moniker= --name=$MYNAME - +iris tendermint show_validator --home=$HOME/.iris2 ``` -再次查询 candidate列表: -``` -iris client query candidates -``` -也可以查询具体的validator信息 +通过执行以下命令完成绑定: ``` -iris client query candidate --pubkey= +iriscli stake create-validator --amount=10steak --pubkey= --address-validator= --moniker= --chain-id=test --name= ``` -查询初始账户的变化,candidates页有变化: +再次查询 Validator列表: ``` -iris client query account $MYADDR -iris client query candidates +iriscli stake validators ``` -通过以下命令可以修改绑定的金额 -``` -iris client tx edit-candidacy --pubkey= --moniker= --name=$MYNAME -``` -通过unbond可将抵押的代币收回,你会发现账户余额增加了。 +通过以下命令为Validator添加更多信息: ``` -iris client tx unbond --shares=1 --pubkey= --name=$MYNAME -iris client query validators -iris client query account $MYADDR +iriscli stake edit-validator --details="To the IRISnet !" --website="https://irisnet.org" ``` -同样的,你也可以绑定用$HOME/.iris2/config/priv_validator.json代表的第二个Node -通过查询tendermint接口,你可以获得新的validator信息。 +检查Validator是否生效: ``` -curl localhost:46657/validators +iriscli advanced tendermint validator-set ``` -如果你杀死了第二个Node,那么区块链将无法继续生成新的块。这是因为只有保证2/3节点在线的情况下,才能达成共识。 +如果你杀死了第一个Node,那么区块链将无法继续生成新的块。这是因为只有保证Voting Power总数超过 2/3 的节点在线的情况下,才能达成共识。 -将第二个节点重新启动,那么区块链会回归正常。 \ No newline at end of file +将第一个节点重新启动,那么区块链会回归正常。 \ No newline at end of file From b73ca802d3ea969c8fc33e0ac2d2dde87636bf76 Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Wed, 20 Jun 2018 22:29:15 +0800 Subject: [PATCH 024/124] #DEVOPS-64 configs for sandbox --- .dockerignore | 3 + Dockerfile | 41 ++++++++----- Dockerfile-dev | 42 +++++++++++++ testnets/develop/README.md | 5 ++ testnets/develop/genesis.json | 102 +++++++++++++++++++++++++++++++ testnets/develop/seed_phrase | 1 + testnets/develop/start-docker.sh | 7 +++ testnets/develop/start.sh | 15 +++++ 8 files changed, 200 insertions(+), 16 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile-dev create mode 100644 testnets/develop/README.md create mode 100644 testnets/develop/genesis.json create mode 100644 testnets/develop/seed_phrase create mode 100644 testnets/develop/start-docker.sh create mode 100644 testnets/develop/start.sh diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..ddf1a56b6 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,3 @@ +Dockerfile +build/ +vendor/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 94c28973d..28f663a27 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,29 +1,38 @@ + # Simple usage with a mounted data directory: -# > docker build -t iris . -# > docker run -it --rm -v "/mnt/volumes/pangu:/iris" iris init [address]--home=/iris -# > docker run -it --rm -v "/mnt/volumes/pangu:/iris" iris start --home=/iris +# > docker build -t irishub . +# > docker run -v $HOME/.iris:/root/.iris iris init +# > docker run -v $HOME/.iris:/root/.iris iris start FROM alpine:edge -ADD ./build/ /usr/local/bin/ - -ENV DATA_ROOT /iris - -# Set user right away for determinism -RUN addgroup gaiauser && \ - adduser -S -G gaiauser gaiauser +# Set up dependencies +ENV PACKAGES go make git libc-dev bash -# Create directory for persistence and give our user ownership -RUN mkdir -p $DATA_ROOT && \ - chown -R gaiauser:gaiauser $DATA_ROOT +# Set up GOPATH & PATH -VOLUME $DATA_ROOT +ENV GOPATH /root/go +ENV BASE_PATH $GOPATH/src/github.com/irisnet +ENV REPO_PATH $BASE_PATH/irishub +ENV PATH $GOPATH/bin:$PATH # p2p port EXPOSE 46656 # rpc port EXPOSE 46657 -WORKDIR /bianjie/ +# Add source files +COPY . $REPO_PATH/ + +# Install minimum necessary dependencies, build Cosmos SDK, remove packages +RUN cd $REPO_PATH && \ + apk add --no-cache $PACKAGES && \ + go get github.com/golang/dep/cmd/dep && \ + make get_vendor_deps && \ + make build_linux && \ + cp build/* /usr/local/bin/ && \ + cd / && \ + apk del $PACKAGES && \ + rm -rf $GOPATH/ && \ + rm -rf /root/.cache/ -ENTRYPOINT ["iris"] \ No newline at end of file diff --git a/Dockerfile-dev b/Dockerfile-dev new file mode 100644 index 000000000..de04a6f32 --- /dev/null +++ b/Dockerfile-dev @@ -0,0 +1,42 @@ +# Using cache for development +# Simple usage with a mounted data directory: +# > docker build -t irishub:develop -f Dockerfile-dev . +# > docker run -v $HOME/.iris:/root/.iris iris init +# > docker run -v $HOME/.iris:/root/.iris iris start + +FROM alpine:edge + +# Set up dependencies +ENV PACKAGES go glide make git libc-dev bash + +# Set up GOPATH & PATH + +ENV GOPATH /root/go +ENV BASE_PATH $GOPATH/src/github.com/irisnet +ENV REPO_PATH $BASE_PATH/irishub +ENV PATH $GOPATH/bin:$PATH + +# Link expected Go repo path + +RUN mkdir -p $WORKDIR $GOPATH/pkg $GOPATH/bin $BASE_PATH && \ + apk add --no-cache $PACKAGES && \ + go get github.com/golang/dep/cmd/dep + +# List project dependencies with Gopkg.toml and Gopkg.lock +# These layers are only re-built when Gopkg files are updated +COPY Gopkg.lock Gopkg.toml $REPO_PATH/ + +WORKDIR $REPO_PATH + +RUN dep ensure -vendor-only + +# p2p port +EXPOSE 46656 +# rpc port +EXPOSE 46657 + +# Add source files +COPY . $REPO_PATH/ + +RUN make build_linux && \ + mv build/* /usr/local/bin/ \ No newline at end of file diff --git a/testnets/develop/README.md b/testnets/develop/README.md new file mode 100644 index 000000000..00db0b64c --- /dev/null +++ b/testnets/develop/README.md @@ -0,0 +1,5 @@ +### 运行docker +这个命令会启动一个基于最新develop分支构建的镜像的docker容器,启动前需要确认`46656`和`46657`端口没有被占用 +``` +sh run-docker.sh +``` diff --git a/testnets/develop/genesis.json b/testnets/develop/genesis.json new file mode 100644 index 000000000..062cc6dc3 --- /dev/null +++ b/testnets/develop/genesis.json @@ -0,0 +1,102 @@ +{ + "chain_id": "fuxi-develop", + "app_state": { + "accounts": [ + { + "address": "F7A90A57210A77FEEC55B0F4BF657F7D4B7351DC", + "coins": [ + { + "denom": "iris", + "amount": 200000000 + }, + { + "denom": "steak", + "amount": 100 + } + ] + } + ], + "stake": { + "pool": { + "loose_unbonded_tokens": 100, + "unbonded_tokens": 0, + "unbonding_tokens": 0, + "bonded_tokens": 100, + "unbonded_shares": "0", + "unbonding_shares": "0", + "bonded_shares": "100", + "inflation_last_time": 0, + "inflation": "7/100", + "date_last_commission_reset": 0, + "prev_bonded_shares": "0" + }, + "params": { + "inflation_rate_change": "13/100", + "inflation_max": "1/5", + "inflation_min": "7/100", + "goal_bonded": "67/100", + "max_validators": 100, + "bond_denom": "steak" + }, + "validators": [ + { + "owner": "F7A90A57210A77FEEC55B0F4BF657F7D4B7351DC", + "pub_key": { + "type": "AC26791624DE60", + "value": "WemH8kR8dJ6mzJVsOF/fQjh+xUrwuAopDJd82c5p4BU=" + }, + "revoked": false, + "pool_shares": { + "status": 2, + "amount": "100" + }, + "delegator_shares": "0", + "description": { + "moniker": "init1", + "identity": "", + "website": "", + "details": "" + }, + "bond_height": 0, + "bond_intra_tx_counter": 0, + "proposer_reward_pool": [], + "commission": "0", + "commission_max": "0", + "commission_change_rate": "0", + "commission_change_today": "0", + "prev_bonded_shares": "0" + } + ], + "bonds": null + } + }, + "consensus_params": { + "block_size_params": { + "max_bytes": 22020096, + "max_txs": 100000, + "max_gas": -1 + }, + "tx_size_params": { + "max_bytes": 10240, + "max_gas": -1 + }, + "block_gossip_params": { + "block_part_size_bytes": 65536 + }, + "evidence_params": { + "max_age": 100000 + } + }, + "validators": [ + { + "pub_key": { + "type": "AC26791624DE60", + "value": "WemH8kR8dJ6mzJVsOF/fQjh+xUrwuAopDJd82c5p4BU=" + }, + "power": 100, + "name": "" + } + ], + "app_hash": "", + "genesis_time": "2018-06-20T21:03:55.946921+08:00" +} \ No newline at end of file diff --git a/testnets/develop/seed_phrase b/testnets/develop/seed_phrase new file mode 100644 index 000000000..d7eeb9ddd --- /dev/null +++ b/testnets/develop/seed_phrase @@ -0,0 +1 @@ +east avoid grain vague soul impulse shock crater elegant render exclude region stereo mosquito ankle abandon \ No newline at end of file diff --git a/testnets/develop/start-docker.sh b/testnets/develop/start-docker.sh new file mode 100644 index 000000000..15a12a039 --- /dev/null +++ b/testnets/develop/start-docker.sh @@ -0,0 +1,7 @@ +#!/bin/bash +docker run -d -p 46656:46656 -p 46657:46657 -it irishub:develop sh -c ' + iris init --chain-id=fuxi-develop --name=init1 && \ + apk add --no-cache curl && \ + curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/genesis.json -o ~/.iris/config/genesis.json && \ + + iris start' \ No newline at end of file diff --git a/testnets/develop/start.sh b/testnets/develop/start.sh new file mode 100644 index 000000000..e953873dc --- /dev/null +++ b/testnets/develop/start.sh @@ -0,0 +1,15 @@ +#!/bin/bash +iris init --chain-id=fuxi-develop --name=init1 +curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/genesis.json -o ~/.iris/config/genesis.json +SP=$(curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/seed_phrase) +command="iriscli keys add init1 --recover" +expect -c " + spawn $command; + expect { + \"override the existing name init1 [y/n]:\" {send \"y\r\"; exp_continue}, + \"Enter a passphrase for your key:\" {send \"1234567890\r\"; exp_continue}, + \"Repeat the passphrase:\" {send \"1234567890\r\"; exp_continue}, + \"Enter your recovery seed phrase:\" {send \"$SP\r\"; exp_continue} + } + " +iris start \ No newline at end of file From ee33fa5f57f265983e97b4edfa27848dff0ea6dc Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Wed, 20 Jun 2018 22:43:24 +0800 Subject: [PATCH 025/124] #DEVOPS-64 update genesis.json --- testnets/develop/genesis.json | 66 +++++++++++++++++------------------ 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/testnets/develop/genesis.json b/testnets/develop/genesis.json index 062cc6dc3..f7cc23492 100644 --- a/testnets/develop/genesis.json +++ b/testnets/develop/genesis.json @@ -1,9 +1,38 @@ { "chain_id": "fuxi-develop", + "genesis_time": "2018-06-20T22:39:44.742488+08:00", + "consensus_params": { + "block_size_params": { + "max_bytes": 22020096, + "max_txs": 100000, + "max_gas": -1 + }, + "tx_size_params": { + "max_bytes": 10240, + "max_gas": -1 + }, + "block_gossip_params": { + "block_part_size_bytes": 65536 + }, + "evidence_params": { + "max_age": 100000 + } + }, + "validators": [ + { + "pub_key": { + "type": "AC26791624DE60", + "value": "zh8afqExhzuqUeSqd8APwGnYYgOiQ0kLMCT53acKwoQ=" + }, + "power": 100, + "name": "" + } + ], + "app_hash": "", "app_state": { "accounts": [ { - "address": "F7A90A57210A77FEEC55B0F4BF657F7D4B7351DC", + "address": "811410FC668643F7CBB1ED544DB0FB8738F57BEA", "coins": [ { "denom": "iris", @@ -40,10 +69,10 @@ }, "validators": [ { - "owner": "F7A90A57210A77FEEC55B0F4BF657F7D4B7351DC", + "owner": "811410FC668643F7CBB1ED544DB0FB8738F57BEA", "pub_key": { "type": "AC26791624DE60", - "value": "WemH8kR8dJ6mzJVsOF/fQjh+xUrwuAopDJd82c5p4BU=" + "value": "zh8afqExhzuqUeSqd8APwGnYYgOiQ0kLMCT53acKwoQ=" }, "revoked": false, "pool_shares": { @@ -69,34 +98,5 @@ ], "bonds": null } - }, - "consensus_params": { - "block_size_params": { - "max_bytes": 22020096, - "max_txs": 100000, - "max_gas": -1 - }, - "tx_size_params": { - "max_bytes": 10240, - "max_gas": -1 - }, - "block_gossip_params": { - "block_part_size_bytes": 65536 - }, - "evidence_params": { - "max_age": 100000 - } - }, - "validators": [ - { - "pub_key": { - "type": "AC26791624DE60", - "value": "WemH8kR8dJ6mzJVsOF/fQjh+xUrwuAopDJd82c5p4BU=" - }, - "power": 100, - "name": "" - } - ], - "app_hash": "", - "genesis_time": "2018-06-20T21:03:55.946921+08:00" + } } \ No newline at end of file From 0e67e6da93f3f96ce0e8084c7bfbfff9bc2d446d Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Wed, 20 Jun 2018 23:00:30 +0800 Subject: [PATCH 026/124] #DEVOPS-64 add config for sandbox --- testnets/develop/{ => config}/genesis.json | 68 ++++++++++----------- testnets/develop/config/node_key.json | 1 + testnets/develop/config/priv_validator.json | 14 +++++ testnets/develop/seed_phrase | 2 +- testnets/develop/start.sh | 4 +- 5 files changed, 53 insertions(+), 36 deletions(-) rename testnets/develop/{ => config}/genesis.json (87%) create mode 100644 testnets/develop/config/node_key.json create mode 100644 testnets/develop/config/priv_validator.json diff --git a/testnets/develop/genesis.json b/testnets/develop/config/genesis.json similarity index 87% rename from testnets/develop/genesis.json rename to testnets/develop/config/genesis.json index f7cc23492..839776001 100644 --- a/testnets/develop/genesis.json +++ b/testnets/develop/config/genesis.json @@ -1,38 +1,8 @@ { - "chain_id": "fuxi-develop", - "genesis_time": "2018-06-20T22:39:44.742488+08:00", - "consensus_params": { - "block_size_params": { - "max_bytes": 22020096, - "max_txs": 100000, - "max_gas": -1 - }, - "tx_size_params": { - "max_bytes": 10240, - "max_gas": -1 - }, - "block_gossip_params": { - "block_part_size_bytes": 65536 - }, - "evidence_params": { - "max_age": 100000 - } - }, - "validators": [ - { - "pub_key": { - "type": "AC26791624DE60", - "value": "zh8afqExhzuqUeSqd8APwGnYYgOiQ0kLMCT53acKwoQ=" - }, - "power": 100, - "name": "" - } - ], - "app_hash": "", "app_state": { "accounts": [ { - "address": "811410FC668643F7CBB1ED544DB0FB8738F57BEA", + "address": "7E8CDBA5F5973D6996DF39C84D3A82A6A11CCEFB", "coins": [ { "denom": "iris", @@ -69,10 +39,10 @@ }, "validators": [ { - "owner": "811410FC668643F7CBB1ED544DB0FB8738F57BEA", + "owner": "7E8CDBA5F5973D6996DF39C84D3A82A6A11CCEFB", "pub_key": { "type": "AC26791624DE60", - "value": "zh8afqExhzuqUeSqd8APwGnYYgOiQ0kLMCT53acKwoQ=" + "value": "DOF6e3lo7XwtGzGZs0RVQTkrPg2i19NiCdkoQg3wxDs=" }, "revoked": false, "pool_shares": { @@ -98,5 +68,35 @@ ], "bonds": null } - } + }, + "chain_id": "fuxi-develop", + "consensus_params": { + "block_size_params": { + "max_bytes": 22020096, + "max_txs": 100000, + "max_gas": -1 + }, + "tx_size_params": { + "max_bytes": 10240, + "max_gas": -1 + }, + "block_gossip_params": { + "block_part_size_bytes": 65536 + }, + "evidence_params": { + "max_age": 100000 + } + }, + "validators": [ + { + "pub_key": { + "type": "AC26791624DE60", + "value": "DOF6e3lo7XwtGzGZs0RVQTkrPg2i19NiCdkoQg3wxDs=" + }, + "power": 100, + "name": "" + } + ], + "app_hash": "", + "genesis_time": "2018-06-20T22:52:04.66882+08:00" } \ No newline at end of file diff --git a/testnets/develop/config/node_key.json b/testnets/develop/config/node_key.json new file mode 100644 index 000000000..ea893e48c --- /dev/null +++ b/testnets/develop/config/node_key.json @@ -0,0 +1 @@ +{"priv_key":{"type":"954568A3288910","value":"phX/aA6Vl/WtPsVilSLytac//BQb77NYQhwhfjsRZbgCNAHDoB/81f2S0KZBt2GEwyen8ot2si7jePzS06bi1w=="}} \ No newline at end of file diff --git a/testnets/develop/config/priv_validator.json b/testnets/develop/config/priv_validator.json new file mode 100644 index 000000000..b321d0e2d --- /dev/null +++ b/testnets/develop/config/priv_validator.json @@ -0,0 +1,14 @@ +{ + "address": "98DA9184DAC66F71F7E7023E8440FE2FE40D66E7", + "pub_key": { + "type": "AC26791624DE60", + "value": "DOF6e3lo7XwtGzGZs0RVQTkrPg2i19NiCdkoQg3wxDs=" + }, + "last_height": 0, + "last_round": 0, + "last_step": 0, + "priv_key": { + "type": "954568A3288910", + "value": "/2rWLbTCpEUCQu20MeHCqJ7cP8k9aB1YzRGnkvbDxsoM4Xp7eWjtfC0bMZmzRFVBOSs+DaLX02IJ2ShCDfDEOw==" + } +} \ No newline at end of file diff --git a/testnets/develop/seed_phrase b/testnets/develop/seed_phrase index d7eeb9ddd..71028a71c 100644 --- a/testnets/develop/seed_phrase +++ b/testnets/develop/seed_phrase @@ -1 +1 @@ -east avoid grain vague soul impulse shock crater elegant render exclude region stereo mosquito ankle abandon \ No newline at end of file +speak toddler resource cost tonight idle erupt swap easy helmet crater salute spring current apple abandon \ No newline at end of file diff --git a/testnets/develop/start.sh b/testnets/develop/start.sh index e953873dc..f57a85ca9 100644 --- a/testnets/develop/start.sh +++ b/testnets/develop/start.sh @@ -1,6 +1,8 @@ #!/bin/bash iris init --chain-id=fuxi-develop --name=init1 -curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/genesis.json -o ~/.iris/config/genesis.json +curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/genesis.json -o ~/.iris/config/genesis.json +curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/node_key.json -o ~/.iris/config/node_key.json +curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/priv_validator.json -o ~/.iris/config/priv_validator.json SP=$(curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/seed_phrase) command="iriscli keys add init1 --recover" expect -c " From 8cf23735ffb53e6ecf7d3846cece57044c61c761 Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Wed, 20 Jun 2018 23:14:14 +0800 Subject: [PATCH 027/124] #DEVOPS-64 update config for sandbox --- testnets/develop/config/genesis.json | 10 +++++----- testnets/develop/config/node_key.json | 2 +- testnets/develop/config/priv_validator.json | 6 +++--- testnets/develop/seed_phrase | 2 +- testnets/develop/start.sh | 20 ++++++++++++++------ 5 files changed, 24 insertions(+), 16 deletions(-) diff --git a/testnets/develop/config/genesis.json b/testnets/develop/config/genesis.json index 839776001..68dee5217 100644 --- a/testnets/develop/config/genesis.json +++ b/testnets/develop/config/genesis.json @@ -2,7 +2,7 @@ "app_state": { "accounts": [ { - "address": "7E8CDBA5F5973D6996DF39C84D3A82A6A11CCEFB", + "address": "167BCF028628A90E4DAC4CCF7F346782F1FD8995", "coins": [ { "denom": "iris", @@ -39,10 +39,10 @@ }, "validators": [ { - "owner": "7E8CDBA5F5973D6996DF39C84D3A82A6A11CCEFB", + "owner": "167BCF028628A90E4DAC4CCF7F346782F1FD8995", "pub_key": { "type": "AC26791624DE60", - "value": "DOF6e3lo7XwtGzGZs0RVQTkrPg2i19NiCdkoQg3wxDs=" + "value": "26EDlJj+Jie78gtKZZrqgU1kXPbyUJh4ISuq42OSpEs=" }, "revoked": false, "pool_shares": { @@ -91,12 +91,12 @@ { "pub_key": { "type": "AC26791624DE60", - "value": "DOF6e3lo7XwtGzGZs0RVQTkrPg2i19NiCdkoQg3wxDs=" + "value": "26EDlJj+Jie78gtKZZrqgU1kXPbyUJh4ISuq42OSpEs=" }, "power": 100, "name": "" } ], "app_hash": "", - "genesis_time": "2018-06-20T22:52:04.66882+08:00" + "genesis_time": "2018-06-20T23:13:03.472182+08:00" } \ No newline at end of file diff --git a/testnets/develop/config/node_key.json b/testnets/develop/config/node_key.json index ea893e48c..d9d7434a7 100644 --- a/testnets/develop/config/node_key.json +++ b/testnets/develop/config/node_key.json @@ -1 +1 @@ -{"priv_key":{"type":"954568A3288910","value":"phX/aA6Vl/WtPsVilSLytac//BQb77NYQhwhfjsRZbgCNAHDoB/81f2S0KZBt2GEwyen8ot2si7jePzS06bi1w=="}} \ No newline at end of file +{"priv_key":{"type":"954568A3288910","value":"B3rhUt853W47IDCxc0/1+vxtVMQAmaMg+wVepGmllceEGAENh4LOcKsogvTEUUtWqnL2WO82IL9Ji9ChQKd3ww=="}} \ No newline at end of file diff --git a/testnets/develop/config/priv_validator.json b/testnets/develop/config/priv_validator.json index b321d0e2d..5ef17ce6a 100644 --- a/testnets/develop/config/priv_validator.json +++ b/testnets/develop/config/priv_validator.json @@ -1,14 +1,14 @@ { - "address": "98DA9184DAC66F71F7E7023E8440FE2FE40D66E7", + "address": "0760AE8E77A592F25216BE02D25DBAEDAB0F3B8D", "pub_key": { "type": "AC26791624DE60", - "value": "DOF6e3lo7XwtGzGZs0RVQTkrPg2i19NiCdkoQg3wxDs=" + "value": "26EDlJj+Jie78gtKZZrqgU1kXPbyUJh4ISuq42OSpEs=" }, "last_height": 0, "last_round": 0, "last_step": 0, "priv_key": { "type": "954568A3288910", - "value": "/2rWLbTCpEUCQu20MeHCqJ7cP8k9aB1YzRGnkvbDxsoM4Xp7eWjtfC0bMZmzRFVBOSs+DaLX02IJ2ShCDfDEOw==" + "value": "PXeMbgX6/atwu2XSpwi9Avtzlh2x7b4kzS9YIc4OqtTboQOUmP4mJ7vyC0plmuqBTWRc9vJQmHghK6rjY5KkSw==" } } \ No newline at end of file diff --git a/testnets/develop/seed_phrase b/testnets/develop/seed_phrase index 71028a71c..f7a276945 100644 --- a/testnets/develop/seed_phrase +++ b/testnets/develop/seed_phrase @@ -1 +1 @@ -speak toddler resource cost tonight idle erupt swap easy helmet crater salute spring current apple abandon \ No newline at end of file +estate stone trip dignity oblige keep jelly apology cheese message slide devote funny attitude anchor abandon \ No newline at end of file diff --git a/testnets/develop/start.sh b/testnets/develop/start.sh index f57a85ca9..ed3050ae9 100644 --- a/testnets/develop/start.sh +++ b/testnets/develop/start.sh @@ -1,4 +1,5 @@ #!/bin/bash +rm -rf ~/.iris* iris init --chain-id=fuxi-develop --name=init1 curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/genesis.json -o ~/.iris/config/genesis.json curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/node_key.json -o ~/.iris/config/node_key.json @@ -8,10 +9,17 @@ command="iriscli keys add init1 --recover" expect -c " spawn $command; expect { - \"override the existing name init1 [y/n]:\" {send \"y\r\"; exp_continue}, - \"Enter a passphrase for your key:\" {send \"1234567890\r\"; exp_continue}, - \"Repeat the passphrase:\" {send \"1234567890\r\"; exp_continue}, - \"Enter your recovery seed phrase:\" {send \"$SP\r\"; exp_continue} - } - " + \"override the existing name*\" {send \"y\r\"; + expect { + \"Enter a passphrase for your key:\" {send \"1234567890\r\"; + expect { + \"Repeat the passphrase:\" {send \"1234567890\r\"; expect { + \"Enter your recovery seed phrase:\" {send \"$SP\r\"; exp_continue} + }}} + }}} + }} + + }; + +" iris start \ No newline at end of file From 0d2970b8b6ec62346fe49842efda051e6c5a99a5 Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Wed, 20 Jun 2018 23:22:46 +0800 Subject: [PATCH 028/124] #DEVOPS-64 update config for sandbox --- testnets/develop/config/genesis.json | 68 ++++++++++----------- testnets/develop/config/node_key.json | 2 +- testnets/develop/config/priv_validator.json | 6 +- testnets/develop/seed_phrase | 2 +- testnets/develop/start.sh | 3 +- 5 files changed, 41 insertions(+), 40 deletions(-) diff --git a/testnets/develop/config/genesis.json b/testnets/develop/config/genesis.json index 68dee5217..843578782 100644 --- a/testnets/develop/config/genesis.json +++ b/testnets/develop/config/genesis.json @@ -1,8 +1,38 @@ { + "app_hash": "", + "genesis_time": "2018-06-20T23:18:44.402001+08:00", + "chain_id": "fuxi-develop", + "consensus_params": { + "block_size_params": { + "max_bytes": 22020096, + "max_txs": 100000, + "max_gas": -1 + }, + "tx_size_params": { + "max_bytes": 10240, + "max_gas": -1 + }, + "block_gossip_params": { + "block_part_size_bytes": 65536 + }, + "evidence_params": { + "max_age": 100000 + } + }, + "validators": [ + { + "pub_key": { + "type": "AC26791624DE60", + "value": "uEPy5Z/i0Pex4fI/2b/O+pM8ABzAx9WNXCxWzfUqiGI=" + }, + "power": 100, + "name": "" + } + ], "app_state": { "accounts": [ { - "address": "167BCF028628A90E4DAC4CCF7F346782F1FD8995", + "address": "D16CD25DB283833178E39CDA54D6C949E9A25554", "coins": [ { "denom": "iris", @@ -39,10 +69,10 @@ }, "validators": [ { - "owner": "167BCF028628A90E4DAC4CCF7F346782F1FD8995", + "owner": "D16CD25DB283833178E39CDA54D6C949E9A25554", "pub_key": { "type": "AC26791624DE60", - "value": "26EDlJj+Jie78gtKZZrqgU1kXPbyUJh4ISuq42OSpEs=" + "value": "uEPy5Z/i0Pex4fI/2b/O+pM8ABzAx9WNXCxWzfUqiGI=" }, "revoked": false, "pool_shares": { @@ -68,35 +98,5 @@ ], "bonds": null } - }, - "chain_id": "fuxi-develop", - "consensus_params": { - "block_size_params": { - "max_bytes": 22020096, - "max_txs": 100000, - "max_gas": -1 - }, - "tx_size_params": { - "max_bytes": 10240, - "max_gas": -1 - }, - "block_gossip_params": { - "block_part_size_bytes": 65536 - }, - "evidence_params": { - "max_age": 100000 - } - }, - "validators": [ - { - "pub_key": { - "type": "AC26791624DE60", - "value": "26EDlJj+Jie78gtKZZrqgU1kXPbyUJh4ISuq42OSpEs=" - }, - "power": 100, - "name": "" - } - ], - "app_hash": "", - "genesis_time": "2018-06-20T23:13:03.472182+08:00" + } } \ No newline at end of file diff --git a/testnets/develop/config/node_key.json b/testnets/develop/config/node_key.json index d9d7434a7..6556451c2 100644 --- a/testnets/develop/config/node_key.json +++ b/testnets/develop/config/node_key.json @@ -1 +1 @@ -{"priv_key":{"type":"954568A3288910","value":"B3rhUt853W47IDCxc0/1+vxtVMQAmaMg+wVepGmllceEGAENh4LOcKsogvTEUUtWqnL2WO82IL9Ji9ChQKd3ww=="}} \ No newline at end of file +{"priv_key":{"type":"954568A3288910","value":"UR7rC98PubZuW2lDxch03Y7C9tun+qnyikqdhwB0GNKzvEnNXXp3fv02pvecD7WWpCJYMjB2qWB9XbdpUOx4/Q=="}} \ No newline at end of file diff --git a/testnets/develop/config/priv_validator.json b/testnets/develop/config/priv_validator.json index 5ef17ce6a..c6bf1efb0 100644 --- a/testnets/develop/config/priv_validator.json +++ b/testnets/develop/config/priv_validator.json @@ -1,14 +1,14 @@ { - "address": "0760AE8E77A592F25216BE02D25DBAEDAB0F3B8D", + "address": "ED090454E2F2C9162BFEC8DF5575A36669FE8795", "pub_key": { "type": "AC26791624DE60", - "value": "26EDlJj+Jie78gtKZZrqgU1kXPbyUJh4ISuq42OSpEs=" + "value": "uEPy5Z/i0Pex4fI/2b/O+pM8ABzAx9WNXCxWzfUqiGI=" }, "last_height": 0, "last_round": 0, "last_step": 0, "priv_key": { "type": "954568A3288910", - "value": "PXeMbgX6/atwu2XSpwi9Avtzlh2x7b4kzS9YIc4OqtTboQOUmP4mJ7vyC0plmuqBTWRc9vJQmHghK6rjY5KkSw==" + "value": "Aztt+aKxxGEZuyS3W5g1qXpbAYt5b2N82r8KhXkSi0y4Q/Lln+LQ97Hh8j/Zv876kzwAHMDH1Y1cLFbN9SqIYg==" } } \ No newline at end of file diff --git a/testnets/develop/seed_phrase b/testnets/develop/seed_phrase index f7a276945..4c177b5e3 100644 --- a/testnets/develop/seed_phrase +++ b/testnets/develop/seed_phrase @@ -1 +1 @@ -estate stone trip dignity oblige keep jelly apology cheese message slide devote funny attitude anchor abandon \ No newline at end of file +neglect winner page breeze knock winter grace truly boring cargo glare aware penalty tenant apart abandon \ No newline at end of file diff --git a/testnets/develop/start.sh b/testnets/develop/start.sh index ed3050ae9..ff473b2b2 100644 --- a/testnets/develop/start.sh +++ b/testnets/develop/start.sh @@ -1,9 +1,10 @@ #!/bin/bash rm -rf ~/.iris* -iris init --chain-id=fuxi-develop --name=init1 +iris init gen-tx --chain-id=fuxi-develop --name=init1 curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/genesis.json -o ~/.iris/config/genesis.json curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/node_key.json -o ~/.iris/config/node_key.json curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/priv_validator.json -o ~/.iris/config/priv_validator.json +curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json -o ~/.iris/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json SP=$(curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/seed_phrase) command="iriscli keys add init1 --recover" expect -c " From bf39d6220ccbd1140af1a7652be6d823882519cd Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Wed, 20 Jun 2018 23:23:07 +0800 Subject: [PATCH 029/124] #DEVOPS-64 update config for sandbox --- ...1af84e5cc261178eaa328978b0dd61adc561a.json | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 testnets/develop/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json diff --git a/testnets/develop/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json b/testnets/develop/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json new file mode 100644 index 000000000..55e06aa8b --- /dev/null +++ b/testnets/develop/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json @@ -0,0 +1,20 @@ +{ + "node_id": "3b11af84e5cc261178eaa328978b0dd61adc561a", + "ip": "192.168.150.125", + "validator": { + "pub_key": { + "type": "AC26791624DE60", + "value": "uEPy5Z/i0Pex4fI/2b/O+pM8ABzAx9WNXCxWzfUqiGI=" + }, + "power": 100, + "name": "" + }, + "app_gen_tx": { + "name": "init1", + "address": "6CCB575E797BB262F55DEB0825FC723C379E0F98", + "pub_key": { + "type": "AC26791624DE60", + "value": "uEPy5Z/i0Pex4fI/2b/O+pM8ABzAx9WNXCxWzfUqiGI=" + } + } +} \ No newline at end of file From 99f106076a5dce263acb2e3daea0d3906182048c Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Wed, 20 Jun 2018 23:36:49 +0800 Subject: [PATCH 030/124] #DEVOPS-64 update config for sandbox --- testnets/develop/config/genesis.json | 30 +++++++++---------- ...1af84e5cc261178eaa328978b0dd61adc561a.json | 20 ------------- ...17b3821cf22382b7afe03e30bd04d1b4f10eb.json | 20 +++++++++++++ testnets/develop/config/node_key.json | 2 +- testnets/develop/config/priv_validator.json | 6 ++-- testnets/develop/seed_phrase | 2 +- testnets/develop/start.sh | 11 +++---- 7 files changed, 44 insertions(+), 47 deletions(-) delete mode 100644 testnets/develop/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json create mode 100644 testnets/develop/config/gentx/gentx-7db17b3821cf22382b7afe03e30bd04d1b4f10eb.json diff --git a/testnets/develop/config/genesis.json b/testnets/develop/config/genesis.json index 843578782..7e45a374f 100644 --- a/testnets/develop/config/genesis.json +++ b/testnets/develop/config/genesis.json @@ -1,6 +1,6 @@ { "app_hash": "", - "genesis_time": "2018-06-20T23:18:44.402001+08:00", + "genesis_time": "2018-06-20T23:34:15.721008+08:00", "chain_id": "fuxi-develop", "consensus_params": { "block_size_params": { @@ -19,20 +19,10 @@ "max_age": 100000 } }, - "validators": [ - { - "pub_key": { - "type": "AC26791624DE60", - "value": "uEPy5Z/i0Pex4fI/2b/O+pM8ABzAx9WNXCxWzfUqiGI=" - }, - "power": 100, - "name": "" - } - ], "app_state": { "accounts": [ { - "address": "D16CD25DB283833178E39CDA54D6C949E9A25554", + "address": "507405661F2DB1940941FA0A6B3642015A015387", "coins": [ { "denom": "iris", @@ -69,10 +59,10 @@ }, "validators": [ { - "owner": "D16CD25DB283833178E39CDA54D6C949E9A25554", + "owner": "507405661F2DB1940941FA0A6B3642015A015387", "pub_key": { "type": "AC26791624DE60", - "value": "uEPy5Z/i0Pex4fI/2b/O+pM8ABzAx9WNXCxWzfUqiGI=" + "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" }, "revoked": false, "pool_shares": { @@ -98,5 +88,15 @@ ], "bonds": null } - } + }, + "validators": [ + { + "pub_key": { + "type": "AC26791624DE60", + "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" + }, + "power": 100, + "name": "" + } + ] } \ No newline at end of file diff --git a/testnets/develop/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json b/testnets/develop/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json deleted file mode 100644 index 55e06aa8b..000000000 --- a/testnets/develop/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "node_id": "3b11af84e5cc261178eaa328978b0dd61adc561a", - "ip": "192.168.150.125", - "validator": { - "pub_key": { - "type": "AC26791624DE60", - "value": "uEPy5Z/i0Pex4fI/2b/O+pM8ABzAx9WNXCxWzfUqiGI=" - }, - "power": 100, - "name": "" - }, - "app_gen_tx": { - "name": "init1", - "address": "6CCB575E797BB262F55DEB0825FC723C379E0F98", - "pub_key": { - "type": "AC26791624DE60", - "value": "uEPy5Z/i0Pex4fI/2b/O+pM8ABzAx9WNXCxWzfUqiGI=" - } - } -} \ No newline at end of file diff --git a/testnets/develop/config/gentx/gentx-7db17b3821cf22382b7afe03e30bd04d1b4f10eb.json b/testnets/develop/config/gentx/gentx-7db17b3821cf22382b7afe03e30bd04d1b4f10eb.json new file mode 100644 index 000000000..9eb7c6484 --- /dev/null +++ b/testnets/develop/config/gentx/gentx-7db17b3821cf22382b7afe03e30bd04d1b4f10eb.json @@ -0,0 +1,20 @@ +{ + "node_id": "7db17b3821cf22382b7afe03e30bd04d1b4f10eb", + "ip": "192.168.150.125", + "validator": { + "pub_key": { + "type": "AC26791624DE60", + "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" + }, + "power": 100, + "name": "" + }, + "app_gen_tx": { + "name": "init1", + "address": "507405661F2DB1940941FA0A6B3642015A015387", + "pub_key": { + "type": "AC26791624DE60", + "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" + } + } +} \ No newline at end of file diff --git a/testnets/develop/config/node_key.json b/testnets/develop/config/node_key.json index 6556451c2..b1bcf6126 100644 --- a/testnets/develop/config/node_key.json +++ b/testnets/develop/config/node_key.json @@ -1 +1 @@ -{"priv_key":{"type":"954568A3288910","value":"UR7rC98PubZuW2lDxch03Y7C9tun+qnyikqdhwB0GNKzvEnNXXp3fv02pvecD7WWpCJYMjB2qWB9XbdpUOx4/Q=="}} \ No newline at end of file +{"priv_key":{"type":"954568A3288910","value":"6TWNBR3I7mIZ0IbeAVuhRU8eqEo/9QxlBxxVdO9TFodLtd05OpOiXFrI+xST4Sy4p11qV11agb33Iiv5i8GAzA=="}} \ No newline at end of file diff --git a/testnets/develop/config/priv_validator.json b/testnets/develop/config/priv_validator.json index c6bf1efb0..48a1ab5ea 100644 --- a/testnets/develop/config/priv_validator.json +++ b/testnets/develop/config/priv_validator.json @@ -1,14 +1,14 @@ { - "address": "ED090454E2F2C9162BFEC8DF5575A36669FE8795", + "address": "823E3266359570A41A6B31C7A1F738F19923A0F0", "pub_key": { "type": "AC26791624DE60", - "value": "uEPy5Z/i0Pex4fI/2b/O+pM8ABzAx9WNXCxWzfUqiGI=" + "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" }, "last_height": 0, "last_round": 0, "last_step": 0, "priv_key": { "type": "954568A3288910", - "value": "Aztt+aKxxGEZuyS3W5g1qXpbAYt5b2N82r8KhXkSi0y4Q/Lln+LQ97Hh8j/Zv876kzwAHMDH1Y1cLFbN9SqIYg==" + "value": "wVB2h4AeVpuWJ/xJlfKV3cf/6WNrVfxLr+CkbWU7E/4ImPavmwYnSOfyZoukSIVh5hy3KMY2yQPi1boNrP99WQ==" } } \ No newline at end of file diff --git a/testnets/develop/seed_phrase b/testnets/develop/seed_phrase index 4c177b5e3..4d9127cc2 100644 --- a/testnets/develop/seed_phrase +++ b/testnets/develop/seed_phrase @@ -1 +1 @@ -neglect winner page breeze knock winter grace truly boring cargo glare aware penalty tenant apart abandon \ No newline at end of file +segment winner ability purse fiction robust glass find mechanic bind park attend jealous symbol artefact abandon \ No newline at end of file diff --git a/testnets/develop/start.sh b/testnets/develop/start.sh index ff473b2b2..b1b985a81 100644 --- a/testnets/develop/start.sh +++ b/testnets/develop/start.sh @@ -1,10 +1,11 @@ #!/bin/bash rm -rf ~/.iris* -iris init gen-tx --chain-id=fuxi-develop --name=init1 +mkdir -p ~/.iris/config/gentx/ curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/genesis.json -o ~/.iris/config/genesis.json curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/node_key.json -o ~/.iris/config/node_key.json curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/priv_validator.json -o ~/.iris/config/priv_validator.json curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json -o ~/.iris/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json +iris init --gen-txs --chain-id=fuxi-develop SP=$(curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/seed_phrase) command="iriscli keys add init1 --recover" expect -c " @@ -18,9 +19,5 @@ expect -c " \"Enter your recovery seed phrase:\" {send \"$SP\r\"; exp_continue} }}} }}} - }} - - }; - -" -iris start \ No newline at end of file + }" +#iris start \ No newline at end of file From 1180fa2d1961d694611d627203868d495488990c Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Thu, 21 Jun 2018 00:01:23 +0800 Subject: [PATCH 031/124] #DEVOPS-64 fix start.sh for sandbox --- testnets/develop/start.sh | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/testnets/develop/start.sh b/testnets/develop/start.sh index b1b985a81..53bf8fdd6 100644 --- a/testnets/develop/start.sh +++ b/testnets/develop/start.sh @@ -5,19 +5,16 @@ curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/ curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/node_key.json -o ~/.iris/config/node_key.json curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/priv_validator.json -o ~/.iris/config/priv_validator.json curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json -o ~/.iris/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json -iris init --gen-txs --chain-id=fuxi-develop +iris init --chain-id=fuxi-develop --name=init1 SP=$(curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/seed_phrase) command="iriscli keys add init1 --recover" expect -c " spawn $command; expect { - \"override the existing name*\" {send \"y\r\"; - expect { - \"Enter a passphrase for your key:\" {send \"1234567890\r\"; - expect { - \"Repeat the passphrase:\" {send \"1234567890\r\"; expect { - \"Enter your recovery seed phrase:\" {send \"$SP\r\"; exp_continue} - }}} - }}} - }" -#iris start \ No newline at end of file + \"override the existing name*\" {send \"y\r\"; exp_continue} + \"Enter a passphrase for your key:\" {send \"1234567890\r\"; exp_continue} + \"Repeat the passphrase:\" {send \"1234567890\r\"; exp_continue} + \"Enter your recovery seed phrase:\" {send \"$SP\r\"; exp_continue} + } +" +iris start \ No newline at end of file From 889faa943ccb378c531846315e75e176f04e798b Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Thu, 21 Jun 2018 00:25:23 +0800 Subject: [PATCH 032/124] #DEVOPS-64 update start-docker.sh & add README file --- testnets/develop/README.md | 27 +++++++++++++++++++++++++-- testnets/develop/start-docker.sh | 10 ++++------ 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/testnets/develop/README.md b/testnets/develop/README.md index 00db0b64c..98725486f 100644 --- a/testnets/develop/README.md +++ b/testnets/develop/README.md @@ -1,5 +1,28 @@ -### 运行docker +### Running in command line +这个命令会在宿主机后台启动一个iris进程,启动前需要确认宿主机已安装iris、iriscli,并确认`46656`和`46657`端口没有被占用, +命令会删除$HOME/.iris*目录,请注意做好备份 +``` +nohup sh start.sh > iris.log 2>&1 & +``` +查看日志: +```$xslt +tail -f iris.log +``` +查看账户列表: +```$xslt +iriscli keys list +``` + +### Running in docker 这个命令会启动一个基于最新develop分支构建的镜像的docker容器,启动前需要确认`46656`和`46657`端口没有被占用 ``` -sh run-docker.sh +sh start-docker.sh +``` +查看日志: +```$xslt +docker logs -f irishub-sandbox ``` +查看账户列表: +```$xslt +docker exec -it irishub-sandbox iriscli keys list +``` \ No newline at end of file diff --git a/testnets/develop/start-docker.sh b/testnets/develop/start-docker.sh index 15a12a039..3dce2829c 100644 --- a/testnets/develop/start-docker.sh +++ b/testnets/develop/start-docker.sh @@ -1,7 +1,5 @@ #!/bin/bash -docker run -d -p 46656:46656 -p 46657:46657 -it irishub:develop sh -c ' - iris init --chain-id=fuxi-develop --name=init1 && \ - apk add --no-cache curl && \ - curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/genesis.json -o ~/.iris/config/genesis.json && \ - - iris start' \ No newline at end of file +docker run -d -p 46656:46656 -p 46657:46657 --name irishub-sandbox -it irishub:develop sh -c ' + apk add --no-cache curl expect && \ + curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/start.sh -o start.sh && \ + sh start.sh' \ No newline at end of file From 86b7847026260b0b4449d706e94a04e9a2f4ba5c Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Sun, 24 Jun 2018 13:17:28 +0800 Subject: [PATCH 033/124] Add offline signature API --- cmd/iriscli/offline_sign.go | 38 +++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/cmd/iriscli/offline_sign.go b/cmd/iriscli/offline_sign.go index 180d705ca..847c56744 100644 --- a/cmd/iriscli/offline_sign.go +++ b/cmd/iriscli/offline_sign.go @@ -8,6 +8,9 @@ import ( "net/http" "github.com/gorilla/mux" "io/ioutil" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/tendermint/go-crypto" ) @@ -15,28 +18,51 @@ func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb r.HandleFunc("/tx/send", SendTxRequestHandlerFn(cdc, kb, ctx)).Methods("POST") } -// /accounts/{address} -type sendTxReq struct { - tx []byte + +type sendTx struct { + Msg bank.MsgSend `json:"msg"` + Fee auth.StdFee `json:"fee"` + Signatures []StdSignature `json:"signatures"` +} + +type StdSignature struct { + PubKey crypto.PubKeyEd25519 `json:"pub_key"` // optional + Signature crypto.SignatureEd25519 `json:"signature"` + AccountNumber int64 `json:"account_number"` + Sequence int64 `json:"sequence"` } //send traction(sign with rainbow) to irishub func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var sendReq sendTxReq + var tx sendTx body, err := ioutil.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } - if err = json.Unmarshal(body, &sendReq); err != nil { + + if err = json.Unmarshal(body, &tx); err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } + var sig = make([]auth.StdSignature,len(tx.Signatures)) + for index,s := range tx.Signatures { + sig[index].PubKey = s.PubKey + sig[index].Signature = s.Signature + sig[index].AccountNumber =s.AccountNumber + sig[index].Sequence = s.Sequence + } + var stdTx = auth.StdTx{ + Msg:tx.Msg, + Fee:tx.Fee, + Signatures:sig, + } + txByte,_ := cdc.MarshalBinary(stdTx) // send - res, err := ctx.BroadcastTx(sendReq.tx) + res, err := ctx.BroadcastTx(txByte) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) From 271208ec9b1e7383b078c76ccde4d21e3d83fd29 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Sun, 24 Jun 2018 17:11:31 +0800 Subject: [PATCH 034/124] =?UTF-8?q?Add=20offline=20signature=20API?= =?UTF-8?q?=EF=BC=88delegate,unbond=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/iriscli/offline_sign.go | 43 +++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/cmd/iriscli/offline_sign.go b/cmd/iriscli/offline_sign.go index 847c56744..a6d4546eb 100644 --- a/cmd/iriscli/offline_sign.go +++ b/cmd/iriscli/offline_sign.go @@ -11,6 +11,9 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/tendermint/go-crypto" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/pkg/errors" ) @@ -20,7 +23,8 @@ func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb type sendTx struct { - Msg bank.MsgSend `json:"msg"` + Msg string `json:"msg"` + MsgType string `json:"type"` Fee auth.StdFee `json:"fee"` Signatures []StdSignature `json:"signatures"` } @@ -55,8 +59,16 @@ func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreCo sig[index].AccountNumber =s.AccountNumber sig[index].Sequence = s.Sequence } + + msg,err := convertMsg(tx) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + var stdTx = auth.StdTx{ - Msg:tx.Msg, + Msg:msg, Fee:tx.Fee, Signatures:sig, } @@ -78,4 +90,31 @@ func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreCo w.Write(output) } +} + +func convertMsg(tx sendTx) (sdk.Msg,error){ + data := []byte(tx.Msg) + switch tx.MsgType { + case "transfer":{ + var msg bank.MsgSend + if err := json.Unmarshal(data, &msg); err != nil { + return nil,err + } + return msg,nil + } + case "delegate": + var msg stake.MsgDelegate + if err := json.Unmarshal(data, &msg); err != nil { + return nil,err + } + return msg,nil + case "unbond": + var msg stake.MsgUnbond + if err := json.Unmarshal(data, &msg); err != nil { + return nil,err + } + return msg,nil + } + + return nil,errors.New("invalid message type") } \ No newline at end of file From ef321e2e758c2ce03117c57005268c2fbe283830 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Sun, 24 Jun 2018 17:14:37 +0800 Subject: [PATCH 035/124] =?UTF-8?q?Add=20offline=20signature=20API?= =?UTF-8?q?=EF=BC=88delegate,unbond=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/iriscli/lcd_test.go | 265 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 265 insertions(+) create mode 100644 cmd/iriscli/lcd_test.go diff --git a/cmd/iriscli/lcd_test.go b/cmd/iriscli/lcd_test.go new file mode 100644 index 000000000..f3b7f1907 --- /dev/null +++ b/cmd/iriscli/lcd_test.go @@ -0,0 +1,265 @@ +package main + +import ("testing" + "github.com/irisnet/irishub/app" + "github.com/spf13/viper" + "fmt" + "github.com/tendermint/go-amino" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/types" + "encoding/json" + "github.com/magiconair/properties/assert" + "github.com/cosmos/cosmos-sdk/x/auth" + "bytes" + "log" + "os" + "encoding/hex" +) + +func TestRestServer(t *testing.T) { + cdc := app.MakeCodec() + comm := ServeCommand(cdc) + viper.Set("chain-id","fuxi") + viper.Set("node","tcp://localhost:46657") + viper.Set("laddr","tcp://localhost:1317") + + comm.ExecuteC() +} +//var cdc = wire.NewCodec() +// +//func init() { +// cdc.RegisterConcrete(person{},"person",nil) +//} + +func TestAmino(t *testing.T) { + var cdc = amino.NewCodec() + + type Person struct { + Name string + Age int + } + + p := Person{ + Name :"zhangsn", + Age:18, + } + + bz,_ := cdc.MarshalJSON(p) + fmt.Println(bz) + + var p1 Person + if err := cdc.UnmarshalJSON(bz,&p1);err != nil { + fmt.Println(err) + return + } + //cdc.MustUnmarshalBinaryBare(bz,p1) + fmt.Printf("%+v",p1) + +} + +func TestMarshalJson(t *testing.T) { + add,_ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") + conis := types.Coins{ + types.Coin{ + Denom:"iris", + Amount:10, + }, + } + //fmt.Println(types.MustBech32ifyAcc(add)) + input := bank.Input{ + Address:add, + Coins:conis, + } + input1Byte := input.GetSignBytes() + fmt.Println(input1Byte) + + input2Byte,_ := json.Marshal(struct { + Address string `json:"address"` + Coins types.Coins `json:"coins"` + }{ + Address: types.MustBech32ifyAcc(add), + Coins: conis, + }) + + assert.Equal(t,input1Byte,input2Byte) + +} + +func TestMarshal(t *testing.T) { + add,_ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") + conis := types.Coins{ + types.Coin{ + Denom:"iris", + Amount:10, + }, + } + //fmt.Println(types.MustBech32ifyAcc(add)) + input := bank.Input{ + Address:add, + Coins:conis, + } + input1Byte := input.GetSignBytes() + + input2Byte,_ := json.Marshal(struct { + Address string `json:"address"` + Coins types.Coins `json:"coins"` + }{ + Address: types.MustBech32ifyAcc(add), + Coins: conis, + }) + + assert.Equal(t,input1Byte,input2Byte) + +} + +func TestSignByte(t *testing.T) { + from,_ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") + + chainID := "fuxi" + accnums := []int64{0} + sequences := []int64{3} + + conis := types.Coins{ + types.Coin{ + Denom:"iris", + Amount:10, + }, + } + + fees := types.Coins{ + types.Coin{ + Denom:"iris", + Amount:0, + }, + } + + type put struct { + Address string `json:"address"` + Coins types.Coins `json:"coins"` + } + + input := bank.Input{ + Address:from, + Coins:conis, + } + + input1 := input.GetSignBytes() + input2,_ := json.Marshal(put{ + Address: types.MustBech32ifyAcc(from), + Coins: conis, + }) + + assert.Equal(t,input1,input2) + + to,_ := types.GetAccAddressHex("3A058A8B5468AE0EA2D2517CE3BAFDD281E50C2F") + output := bank.Output{ + Address:to, + Coins:conis, + } + + output1 := output.GetSignBytes() + output2,_ := json.Marshal(put{ + Address: types.MustBech32ifyAcc(to), + Coins: conis, + }) + + assert.Equal(t,output1,output2) + + msg := bank.MsgSend{ + []bank.Input{input},[]bank.Output{output}, + } + + msg1 := msg.GetSignBytes() + + var inputs, outputs []json.RawMessage + for _, input := range msg.Inputs { + inputs = append(inputs, input.GetSignBytes()) + } + for _, output := range msg.Outputs { + outputs = append(outputs, output.GetSignBytes()) + } + + msg2,_ := json.Marshal(struct { + Inputs []json.RawMessage `json:"inputs"` + Outputs []json.RawMessage `json:"outputs"` + }{ + Inputs: inputs, + Outputs: outputs, + }) + //fmt.Print(msg2) + assert.Equal(t,msg1,msg2) + + fee := auth.StdFee{ + Amount:fees, + Gas:int64(0), + } + + fee1 := fee.Bytes() + fee2,_:= json.Marshal(struct { + Amount types.Coins `json:"amount"` + Gas int64 `json:"gas"` + }{ + Amount:fees, + Gas:int64(0), + }) + + assert.Equal(t,fee1,fee2) + + signMsg := auth.StdSignMsg{ + ChainID:chainID, + AccountNumbers:accnums, + Sequences:sequences, + Msg:msg, + Fee:fee, + } + + signByte1 := signMsg.Bytes() + signByte2,_ := json.Marshal(auth.StdSignDoc{ + ChainID: chainID, + AccountNumbers: accnums, + Sequences: sequences, + FeeBytes: fee2, + MsgBytes: msg2, + }) + + str := string(signByte1) + + fmt.Println(str) + + //printJson(signByte2) + + assert.Equal(t,signByte1,signByte2) + + fmt.Println(signByte1) + +} + +func printJson(b []byte) { + var out bytes.Buffer + err := json.Indent(&out, b, "", "\t") + + if err != nil { + log.Fatalln(err) + } + + out.WriteTo(os.Stdout) +} + +func TestH(t *testing.T){ + client := []byte{123,34,99,104,97,105,110,95,105,100,34,58,34,102,117,120,105,34,44,34,97,99,99,111,117,110,116,95,110,117,109,98,101,114,115,34,58,91,48,93,44,34,115,101,113,117,101,110,99,101,115,34,58,91,51,93,44,34,102,101,101,95,98,121,116,101,115,34,58,34,101,121,74,104,98,87,57,49,98,110,81,105,79,108,116,55,73,109,70,116,98,51,86,117,100,67,73,54,77,67,119,105,90,71,86,117,98,50,48,105,79,105,74,112,99,109,108,122,73,110,49,100,76,67,74,110,89,88,77,105,79,106,66,57,34,44,34,109,115,103,95,98,121,116,101,115,34,58,34,101,121,74,112,98,110,66,49,100,72,77,105,79,108,116,55,73,109,70,107,90,72,74,108,99,51,77,105,79,105,74,106,98,51,78,116,98,51,78,104,89,50,78,104,90,71,82,121,77,88,74,116,99,72,100,122,89,51,73,53,78,109,104,111,89,122,78,110,98,71,82,50,97,51,86,48,79,71,90,119,97,110,112,121,89,87,82,117,77,50,70,113,100,110,74,116,98,71,100,107,73,105,119,105,89,50,57,112,98,110,77,105,79,108,116,55,73,109,70,116,98,51,86,117,100,67,73,54,77,84,65,115,73,109,82,108,98,109,57,116,73,106,111,105,97,88,74,112,99,121,74,57,88,88,49,100,76,67,74,118,100,88,82,119,100,88,82,122,73,106,112,98,101,121,74,104,90,71,82,121,90,88,78,122,73,106,111,105,89,50,57,122,98,87,57,122,89,87,78,106,89,87,82,107,99,106,69,52,90,51,112,106,78,72,111,50,78,87,82,54,97,72,70,104,90,50,116,113,77,106,107,51,100,122,104,51,97,71,69,50,77,110,69,51,77,110,74,119,77,72,100,108,101,87,53,48,79,67,73,115,73,109,78,118,97,87,53,122,73,106,112,98,101,121,74,104,98,87,57,49,98,110,81,105,79,106,69,119,76,67,74,107,90,87,53,118,98,83,73,54,73,109,108,121,97,88,77,105,102,86,49,57,88,88,48,61,34,44,34,97,108,116,95,98,121,116,101,115,34,58,110,117,108,108,125} + clientS := string(client) + + //fmt.Println(str1) + fmt.Println(clientS) + + server := []byte{123,34,99,104,97,105,110,95,105,100,34,58,34,102,117,120,105,34,44,34,97,99,99,111,117,110,116,95,110,117,109,98,101,114,115,34,58,91,48,93,44,34,115,101,113,117,101,110,99,101,115,34,58,91,51,93,44,34,102,101,101,95,98,121,116,101,115,34,58,34,101,121,74,104,98,87,57,49,98,110,81,105,79,108,116,55,73,109,82,108,98,109,57,116,73,106,111,105,97,88,74,112,99,121,73,115,73,109,70,116,98,51,86,117,100,67,73,54,77,72,49,100,76,67,74,110,89,88,77,105,79,106,66,57,34,44,34,109,115,103,95,98,121,116,101,115,34,58,34,101,121,74,112,98,110,66,49,100,72,77,105,79,108,116,55,73,109,70,107,90,72,74,108,99,51,77,105,79,105,74,106,98,51,78,116,98,51,78,104,89,50,78,104,90,71,82,121,77,88,74,116,99,72,100,122,89,51,73,53,78,109,104,111,89,122,78,110,98,71,82,50,97,51,86,48,79,71,90,119,97,110,112,121,89,87,82,117,77,50,70,113,100,110,74,116,98,71,100,107,73,105,119,105,89,50,57,112,98,110,77,105,79,108,116,55,73,109,82,108,98,109,57,116,73,106,111,105,97,88,74,112,99,121,73,115,73,109,70,116,98,51,86,117,100,67,73,54,77,84,66,57,88,88,49,100,76,67,74,118,100,88,82,119,100,88,82,122,73,106,112,98,101,121,74,104,90,71,82,121,90,88,78,122,73,106,111,105,89,50,57,122,98,87,57,122,89,87,78,106,89,87,82,107,99,106,69,52,90,51,112,106,78,72,111,50,78,87,82,54,97,72,70,104,90,50,116,113,77,106,107,51,100,122,104,51,97,71,69,50,77,110,69,51,77,110,74,119,77,72,100,108,101,87,53,48,79,67,73,115,73,109,78,118,97,87,53,122,73,106,112,98,101,121,74,107,90,87,53,118,98,83,73,54,73,109,108,121,97,88,77,105,76,67,74,104,98,87,57,49,98,110,81,105,79,106,69,119,102,86,49,57,88,88,48,61,34,44,34,97,108,116,95,98,121,116,101,115,34,58,110,117,108,108,125} + serverS := string(server) + fmt.Println(serverS) +} + +func TestBech32(t *testing.T){ + addr,_ := types.GetAccAddressBech32("cosmosaccaddr1wp4shn6zzv0l52hfat9c2ryu0gvwa4h3dj2k92") + fmt.Print(hex.EncodeToString(addr)) +} + + From 194f2348a4f67aab0990f18cc955e61a7cded153 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Thu, 28 Jun 2018 10:23:15 +0800 Subject: [PATCH 036/124] Code optimization --- app/genesis.go | 8 ++++---- cmd/iris/main.go | 2 +- cmd/iriscli/lcd.go | 2 +- version/version.go | 6 ++++++ 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/app/genesis.go b/app/genesis.go index 736bf1ff5..e19b6ca87 100644 --- a/app/genesis.go +++ b/app/genesis.go @@ -64,7 +64,7 @@ var ( ) // get app init parameters for server init command -func GaiaAppInit() server.AppInit { +func IrisAppInit() server.AppInit { fsAppGenState := pflag.NewFlagSet("", pflag.ContinueOnError) fsAppGenTx := pflag.NewFlagSet("", pflag.ContinueOnError) @@ -82,7 +82,7 @@ func GaiaAppInit() server.AppInit { } // simple genesis tx -type GaiaGenTx struct { +type IrisGenTx struct { Name string `json:"name"` Address sdk.Address `json:"address"` PubKey crypto.PubKey `json:"pub_key"` @@ -120,7 +120,7 @@ func IrisAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.Address, name st appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { var bz []byte - gaiaGenTx := GaiaGenTx{ + gaiaGenTx := IrisGenTx{ Name: name, Address: addr, PubKey: pk, @@ -155,7 +155,7 @@ func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState genaccs := make([]GenesisAccount, len(appGenTxs)) for i, appGenTx := range appGenTxs { - var genTx GaiaGenTx + var genTx IrisGenTx err = cdc.UnmarshalJSON(appGenTx, &genTx) if err != nil { return diff --git a/cmd/iris/main.go b/cmd/iris/main.go index 69dcf0bf4..0835f8f5d 100644 --- a/cmd/iris/main.go +++ b/cmd/iris/main.go @@ -39,7 +39,7 @@ func main() { ) rootCmd.AddCommand( - server.InitCmd(ctx, cdc, app.GaiaAppInit()), + server.InitCmd(ctx, cdc, app.IrisAppInit()), server.StartCmd(ctx, server.ConstructAppCreator(newApp, "iris")), server.UnsafeResetAllCmd(ctx), client.LineBreak, diff --git a/cmd/iriscli/lcd.go b/cmd/iriscli/lcd.go index 172a466c3..8d9cdb194 100644 --- a/cmd/iriscli/lcd.go +++ b/cmd/iriscli/lcd.go @@ -17,7 +17,7 @@ import ( keys "github.com/cosmos/cosmos-sdk/client/keys" rpc "github.com/cosmos/cosmos-sdk/client/rpc" tx "github.com/cosmos/cosmos-sdk/client/tx" - version "github.com/cosmos/cosmos-sdk/version" + version "github.com/irisnet/irishub/version" "github.com/cosmos/cosmos-sdk/wire" auth "github.com/cosmos/cosmos-sdk/x/auth/client/rest" bank "github.com/cosmos/cosmos-sdk/x/bank/client/rest" diff --git a/version/version.go b/version/version.go index c1fef8fe7..885bbb7fa 100644 --- a/version/version.go +++ b/version/version.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/spf13/cobra" + "net/http" ) // Version - Iris Version @@ -17,3 +18,8 @@ var VersionCmd = &cobra.Command{ fmt.Printf("v%s\n", Version) }, } + +// version REST handler endpoint +func RequestHandler(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(Version)) +} From 67105cd99819423aa17ecb3767edc9bada1f5fcc Mon Sep 17 00:00:00 2001 From: Zhiqiang Zhang Date: Thu, 28 Jun 2018 13:47:23 +0800 Subject: [PATCH 037/124] Add offline signature API (#16) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add offline signature API * Add offline signature API(delegate,unbond) * Add offline signature API(delegate,unbond) * Code optimization --- app/genesis.go | 8 +- cmd/iris/main.go | 2 +- cmd/iriscli/lcd.go | 2 +- cmd/iriscli/lcd_test.go | 265 ++++++++++++++++++++++++++++++++++++ cmd/iriscli/offline_sign.go | 77 ++++++++++- version/version.go | 6 + 6 files changed, 348 insertions(+), 12 deletions(-) create mode 100644 cmd/iriscli/lcd_test.go diff --git a/app/genesis.go b/app/genesis.go index 736bf1ff5..e19b6ca87 100644 --- a/app/genesis.go +++ b/app/genesis.go @@ -64,7 +64,7 @@ var ( ) // get app init parameters for server init command -func GaiaAppInit() server.AppInit { +func IrisAppInit() server.AppInit { fsAppGenState := pflag.NewFlagSet("", pflag.ContinueOnError) fsAppGenTx := pflag.NewFlagSet("", pflag.ContinueOnError) @@ -82,7 +82,7 @@ func GaiaAppInit() server.AppInit { } // simple genesis tx -type GaiaGenTx struct { +type IrisGenTx struct { Name string `json:"name"` Address sdk.Address `json:"address"` PubKey crypto.PubKey `json:"pub_key"` @@ -120,7 +120,7 @@ func IrisAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.Address, name st appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { var bz []byte - gaiaGenTx := GaiaGenTx{ + gaiaGenTx := IrisGenTx{ Name: name, Address: addr, PubKey: pk, @@ -155,7 +155,7 @@ func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState genaccs := make([]GenesisAccount, len(appGenTxs)) for i, appGenTx := range appGenTxs { - var genTx GaiaGenTx + var genTx IrisGenTx err = cdc.UnmarshalJSON(appGenTx, &genTx) if err != nil { return diff --git a/cmd/iris/main.go b/cmd/iris/main.go index 69dcf0bf4..0835f8f5d 100644 --- a/cmd/iris/main.go +++ b/cmd/iris/main.go @@ -39,7 +39,7 @@ func main() { ) rootCmd.AddCommand( - server.InitCmd(ctx, cdc, app.GaiaAppInit()), + server.InitCmd(ctx, cdc, app.IrisAppInit()), server.StartCmd(ctx, server.ConstructAppCreator(newApp, "iris")), server.UnsafeResetAllCmd(ctx), client.LineBreak, diff --git a/cmd/iriscli/lcd.go b/cmd/iriscli/lcd.go index 172a466c3..8d9cdb194 100644 --- a/cmd/iriscli/lcd.go +++ b/cmd/iriscli/lcd.go @@ -17,7 +17,7 @@ import ( keys "github.com/cosmos/cosmos-sdk/client/keys" rpc "github.com/cosmos/cosmos-sdk/client/rpc" tx "github.com/cosmos/cosmos-sdk/client/tx" - version "github.com/cosmos/cosmos-sdk/version" + version "github.com/irisnet/irishub/version" "github.com/cosmos/cosmos-sdk/wire" auth "github.com/cosmos/cosmos-sdk/x/auth/client/rest" bank "github.com/cosmos/cosmos-sdk/x/bank/client/rest" diff --git a/cmd/iriscli/lcd_test.go b/cmd/iriscli/lcd_test.go new file mode 100644 index 000000000..f3b7f1907 --- /dev/null +++ b/cmd/iriscli/lcd_test.go @@ -0,0 +1,265 @@ +package main + +import ("testing" + "github.com/irisnet/irishub/app" + "github.com/spf13/viper" + "fmt" + "github.com/tendermint/go-amino" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/types" + "encoding/json" + "github.com/magiconair/properties/assert" + "github.com/cosmos/cosmos-sdk/x/auth" + "bytes" + "log" + "os" + "encoding/hex" +) + +func TestRestServer(t *testing.T) { + cdc := app.MakeCodec() + comm := ServeCommand(cdc) + viper.Set("chain-id","fuxi") + viper.Set("node","tcp://localhost:46657") + viper.Set("laddr","tcp://localhost:1317") + + comm.ExecuteC() +} +//var cdc = wire.NewCodec() +// +//func init() { +// cdc.RegisterConcrete(person{},"person",nil) +//} + +func TestAmino(t *testing.T) { + var cdc = amino.NewCodec() + + type Person struct { + Name string + Age int + } + + p := Person{ + Name :"zhangsn", + Age:18, + } + + bz,_ := cdc.MarshalJSON(p) + fmt.Println(bz) + + var p1 Person + if err := cdc.UnmarshalJSON(bz,&p1);err != nil { + fmt.Println(err) + return + } + //cdc.MustUnmarshalBinaryBare(bz,p1) + fmt.Printf("%+v",p1) + +} + +func TestMarshalJson(t *testing.T) { + add,_ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") + conis := types.Coins{ + types.Coin{ + Denom:"iris", + Amount:10, + }, + } + //fmt.Println(types.MustBech32ifyAcc(add)) + input := bank.Input{ + Address:add, + Coins:conis, + } + input1Byte := input.GetSignBytes() + fmt.Println(input1Byte) + + input2Byte,_ := json.Marshal(struct { + Address string `json:"address"` + Coins types.Coins `json:"coins"` + }{ + Address: types.MustBech32ifyAcc(add), + Coins: conis, + }) + + assert.Equal(t,input1Byte,input2Byte) + +} + +func TestMarshal(t *testing.T) { + add,_ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") + conis := types.Coins{ + types.Coin{ + Denom:"iris", + Amount:10, + }, + } + //fmt.Println(types.MustBech32ifyAcc(add)) + input := bank.Input{ + Address:add, + Coins:conis, + } + input1Byte := input.GetSignBytes() + + input2Byte,_ := json.Marshal(struct { + Address string `json:"address"` + Coins types.Coins `json:"coins"` + }{ + Address: types.MustBech32ifyAcc(add), + Coins: conis, + }) + + assert.Equal(t,input1Byte,input2Byte) + +} + +func TestSignByte(t *testing.T) { + from,_ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") + + chainID := "fuxi" + accnums := []int64{0} + sequences := []int64{3} + + conis := types.Coins{ + types.Coin{ + Denom:"iris", + Amount:10, + }, + } + + fees := types.Coins{ + types.Coin{ + Denom:"iris", + Amount:0, + }, + } + + type put struct { + Address string `json:"address"` + Coins types.Coins `json:"coins"` + } + + input := bank.Input{ + Address:from, + Coins:conis, + } + + input1 := input.GetSignBytes() + input2,_ := json.Marshal(put{ + Address: types.MustBech32ifyAcc(from), + Coins: conis, + }) + + assert.Equal(t,input1,input2) + + to,_ := types.GetAccAddressHex("3A058A8B5468AE0EA2D2517CE3BAFDD281E50C2F") + output := bank.Output{ + Address:to, + Coins:conis, + } + + output1 := output.GetSignBytes() + output2,_ := json.Marshal(put{ + Address: types.MustBech32ifyAcc(to), + Coins: conis, + }) + + assert.Equal(t,output1,output2) + + msg := bank.MsgSend{ + []bank.Input{input},[]bank.Output{output}, + } + + msg1 := msg.GetSignBytes() + + var inputs, outputs []json.RawMessage + for _, input := range msg.Inputs { + inputs = append(inputs, input.GetSignBytes()) + } + for _, output := range msg.Outputs { + outputs = append(outputs, output.GetSignBytes()) + } + + msg2,_ := json.Marshal(struct { + Inputs []json.RawMessage `json:"inputs"` + Outputs []json.RawMessage `json:"outputs"` + }{ + Inputs: inputs, + Outputs: outputs, + }) + //fmt.Print(msg2) + assert.Equal(t,msg1,msg2) + + fee := auth.StdFee{ + Amount:fees, + Gas:int64(0), + } + + fee1 := fee.Bytes() + fee2,_:= json.Marshal(struct { + Amount types.Coins `json:"amount"` + Gas int64 `json:"gas"` + }{ + Amount:fees, + Gas:int64(0), + }) + + assert.Equal(t,fee1,fee2) + + signMsg := auth.StdSignMsg{ + ChainID:chainID, + AccountNumbers:accnums, + Sequences:sequences, + Msg:msg, + Fee:fee, + } + + signByte1 := signMsg.Bytes() + signByte2,_ := json.Marshal(auth.StdSignDoc{ + ChainID: chainID, + AccountNumbers: accnums, + Sequences: sequences, + FeeBytes: fee2, + MsgBytes: msg2, + }) + + str := string(signByte1) + + fmt.Println(str) + + //printJson(signByte2) + + assert.Equal(t,signByte1,signByte2) + + fmt.Println(signByte1) + +} + +func printJson(b []byte) { + var out bytes.Buffer + err := json.Indent(&out, b, "", "\t") + + if err != nil { + log.Fatalln(err) + } + + out.WriteTo(os.Stdout) +} + +func TestH(t *testing.T){ + client := []byte{123,34,99,104,97,105,110,95,105,100,34,58,34,102,117,120,105,34,44,34,97,99,99,111,117,110,116,95,110,117,109,98,101,114,115,34,58,91,48,93,44,34,115,101,113,117,101,110,99,101,115,34,58,91,51,93,44,34,102,101,101,95,98,121,116,101,115,34,58,34,101,121,74,104,98,87,57,49,98,110,81,105,79,108,116,55,73,109,70,116,98,51,86,117,100,67,73,54,77,67,119,105,90,71,86,117,98,50,48,105,79,105,74,112,99,109,108,122,73,110,49,100,76,67,74,110,89,88,77,105,79,106,66,57,34,44,34,109,115,103,95,98,121,116,101,115,34,58,34,101,121,74,112,98,110,66,49,100,72,77,105,79,108,116,55,73,109,70,107,90,72,74,108,99,51,77,105,79,105,74,106,98,51,78,116,98,51,78,104,89,50,78,104,90,71,82,121,77,88,74,116,99,72,100,122,89,51,73,53,78,109,104,111,89,122,78,110,98,71,82,50,97,51,86,48,79,71,90,119,97,110,112,121,89,87,82,117,77,50,70,113,100,110,74,116,98,71,100,107,73,105,119,105,89,50,57,112,98,110,77,105,79,108,116,55,73,109,70,116,98,51,86,117,100,67,73,54,77,84,65,115,73,109,82,108,98,109,57,116,73,106,111,105,97,88,74,112,99,121,74,57,88,88,49,100,76,67,74,118,100,88,82,119,100,88,82,122,73,106,112,98,101,121,74,104,90,71,82,121,90,88,78,122,73,106,111,105,89,50,57,122,98,87,57,122,89,87,78,106,89,87,82,107,99,106,69,52,90,51,112,106,78,72,111,50,78,87,82,54,97,72,70,104,90,50,116,113,77,106,107,51,100,122,104,51,97,71,69,50,77,110,69,51,77,110,74,119,77,72,100,108,101,87,53,48,79,67,73,115,73,109,78,118,97,87,53,122,73,106,112,98,101,121,74,104,98,87,57,49,98,110,81,105,79,106,69,119,76,67,74,107,90,87,53,118,98,83,73,54,73,109,108,121,97,88,77,105,102,86,49,57,88,88,48,61,34,44,34,97,108,116,95,98,121,116,101,115,34,58,110,117,108,108,125} + clientS := string(client) + + //fmt.Println(str1) + fmt.Println(clientS) + + server := []byte{123,34,99,104,97,105,110,95,105,100,34,58,34,102,117,120,105,34,44,34,97,99,99,111,117,110,116,95,110,117,109,98,101,114,115,34,58,91,48,93,44,34,115,101,113,117,101,110,99,101,115,34,58,91,51,93,44,34,102,101,101,95,98,121,116,101,115,34,58,34,101,121,74,104,98,87,57,49,98,110,81,105,79,108,116,55,73,109,82,108,98,109,57,116,73,106,111,105,97,88,74,112,99,121,73,115,73,109,70,116,98,51,86,117,100,67,73,54,77,72,49,100,76,67,74,110,89,88,77,105,79,106,66,57,34,44,34,109,115,103,95,98,121,116,101,115,34,58,34,101,121,74,112,98,110,66,49,100,72,77,105,79,108,116,55,73,109,70,107,90,72,74,108,99,51,77,105,79,105,74,106,98,51,78,116,98,51,78,104,89,50,78,104,90,71,82,121,77,88,74,116,99,72,100,122,89,51,73,53,78,109,104,111,89,122,78,110,98,71,82,50,97,51,86,48,79,71,90,119,97,110,112,121,89,87,82,117,77,50,70,113,100,110,74,116,98,71,100,107,73,105,119,105,89,50,57,112,98,110,77,105,79,108,116,55,73,109,82,108,98,109,57,116,73,106,111,105,97,88,74,112,99,121,73,115,73,109,70,116,98,51,86,117,100,67,73,54,77,84,66,57,88,88,49,100,76,67,74,118,100,88,82,119,100,88,82,122,73,106,112,98,101,121,74,104,90,71,82,121,90,88,78,122,73,106,111,105,89,50,57,122,98,87,57,122,89,87,78,106,89,87,82,107,99,106,69,52,90,51,112,106,78,72,111,50,78,87,82,54,97,72,70,104,90,50,116,113,77,106,107,51,100,122,104,51,97,71,69,50,77,110,69,51,77,110,74,119,77,72,100,108,101,87,53,48,79,67,73,115,73,109,78,118,97,87,53,122,73,106,112,98,101,121,74,107,90,87,53,118,98,83,73,54,73,109,108,121,97,88,77,105,76,67,74,104,98,87,57,49,98,110,81,105,79,106,69,119,102,86,49,57,88,88,48,61,34,44,34,97,108,116,95,98,121,116,101,115,34,58,110,117,108,108,125} + serverS := string(server) + fmt.Println(serverS) +} + +func TestBech32(t *testing.T){ + addr,_ := types.GetAccAddressBech32("cosmosaccaddr1wp4shn6zzv0l52hfat9c2ryu0gvwa4h3dj2k92") + fmt.Print(hex.EncodeToString(addr)) +} + + diff --git a/cmd/iriscli/offline_sign.go b/cmd/iriscli/offline_sign.go index 180d705ca..a6d4546eb 100644 --- a/cmd/iriscli/offline_sign.go +++ b/cmd/iriscli/offline_sign.go @@ -8,6 +8,12 @@ import ( "net/http" "github.com/gorilla/mux" "io/ioutil" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/tendermint/go-crypto" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/pkg/errors" ) @@ -15,28 +21,60 @@ func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb r.HandleFunc("/tx/send", SendTxRequestHandlerFn(cdc, kb, ctx)).Methods("POST") } -// /accounts/{address} -type sendTxReq struct { - tx []byte + +type sendTx struct { + Msg string `json:"msg"` + MsgType string `json:"type"` + Fee auth.StdFee `json:"fee"` + Signatures []StdSignature `json:"signatures"` +} + +type StdSignature struct { + PubKey crypto.PubKeyEd25519 `json:"pub_key"` // optional + Signature crypto.SignatureEd25519 `json:"signature"` + AccountNumber int64 `json:"account_number"` + Sequence int64 `json:"sequence"` } //send traction(sign with rainbow) to irishub func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var sendReq sendTxReq + var tx sendTx body, err := ioutil.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } - if err = json.Unmarshal(body, &sendReq); err != nil { + + if err = json.Unmarshal(body, &tx); err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + var sig = make([]auth.StdSignature,len(tx.Signatures)) + for index,s := range tx.Signatures { + sig[index].PubKey = s.PubKey + sig[index].Signature = s.Signature + sig[index].AccountNumber =s.AccountNumber + sig[index].Sequence = s.Sequence + } + + msg,err := convertMsg(tx) + if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } + + var stdTx = auth.StdTx{ + Msg:msg, + Fee:tx.Fee, + Signatures:sig, + } + txByte,_ := cdc.MarshalBinary(stdTx) // send - res, err := ctx.BroadcastTx(sendReq.tx) + res, err := ctx.BroadcastTx(txByte) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) @@ -52,4 +90,31 @@ func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreCo w.Write(output) } +} + +func convertMsg(tx sendTx) (sdk.Msg,error){ + data := []byte(tx.Msg) + switch tx.MsgType { + case "transfer":{ + var msg bank.MsgSend + if err := json.Unmarshal(data, &msg); err != nil { + return nil,err + } + return msg,nil + } + case "delegate": + var msg stake.MsgDelegate + if err := json.Unmarshal(data, &msg); err != nil { + return nil,err + } + return msg,nil + case "unbond": + var msg stake.MsgUnbond + if err := json.Unmarshal(data, &msg); err != nil { + return nil,err + } + return msg,nil + } + + return nil,errors.New("invalid message type") } \ No newline at end of file diff --git a/version/version.go b/version/version.go index c1fef8fe7..885bbb7fa 100644 --- a/version/version.go +++ b/version/version.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/spf13/cobra" + "net/http" ) // Version - Iris Version @@ -17,3 +18,8 @@ var VersionCmd = &cobra.Command{ fmt.Printf("v%s\n", Version) }, } + +// version REST handler endpoint +func RequestHandler(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(Version)) +} From ddc453f4a67e39875138d3aeccaebfd9c2575e7e Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Mon, 2 Jul 2018 14:00:29 +0800 Subject: [PATCH 038/124] =?UTF-8?q?IRISHUB-9=EF=BC=9ADeals=20to=20send=20a?= =?UTF-8?q?pi=20adjusted=20by=20BroadcastTx=20to=20BroadcastTxAsync?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/iriscli/offline_sign.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/cmd/iriscli/offline_sign.go b/cmd/iriscli/offline_sign.go index a6d4546eb..1716ad58c 100644 --- a/cmd/iriscli/offline_sign.go +++ b/cmd/iriscli/offline_sign.go @@ -14,6 +14,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/stake" "github.com/pkg/errors" + ctypes "github.com/tendermint/tendermint/rpc/core/types" + rpcclient "github.com/tendermint/tendermint/rpc/client" ) @@ -74,7 +76,7 @@ func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreCo } txByte,_ := cdc.MarshalBinary(stdTx) // send - res, err := ctx.BroadcastTx(txByte) + res, err := BroadcastTxAsync(ctx,txByte) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) @@ -117,4 +119,22 @@ func convertMsg(tx sendTx) (sdk.Msg,error){ } return nil,errors.New("invalid message type") +} + +func BroadcastTxAsync(ctx context.CoreContext,tx []byte)(*ctypes.ResultBroadcastTx, error) { + nodeURI := ctx.NodeURI + if nodeURI == "" { + return nil, errors.New("rpc url is empty") + } + + var rpc rpcclient.Client + if nodeURI != "" { + rpc = rpcclient.NewHTTP(nodeURI, "/websocket") + } + + res, err := rpc.BroadcastTxAsync(tx) + if err != nil { + return res, err + } + return res, err } \ No newline at end of file From 0ae40337279430ff660c9f14f26310aed816376d Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Tue, 3 Jul 2018 13:27:01 +0800 Subject: [PATCH 039/124] =?UTF-8?q?IRISHUB-9=EF=BC=9ADeals=20to=20send=20a?= =?UTF-8?q?pi=20adjusted=20by=20BroadcastTx=20to=20BroadcastTxAsync?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/context.go | 24 ++++++++++++++++++++++++ cmd/iriscli/lcd.go | 26 +++++++++++++------------- cmd/iriscli/offline_sign.go | 28 ++++------------------------ 3 files changed, 41 insertions(+), 37 deletions(-) create mode 100644 app/context.go diff --git a/app/context.go b/app/context.go new file mode 100644 index 000000000..3e2f9562a --- /dev/null +++ b/app/context.go @@ -0,0 +1,24 @@ +package app + +import ( + "github.com/cosmos/cosmos-sdk/client/context" + ctypes "github.com/tendermint/tendermint/rpc/core/types" +) + +type Context struct { + ctx context.CoreContext +} + +func (c Context) BroadcastTxAsync(tx []byte) (*ctypes.ResultBroadcastTx, error) { + return c.ctx.Client.BroadcastTxAsync(tx) +} + +func (c Context) GetCosmosCtx() (context.CoreContext) { + return c.ctx +} + +func NewContext() Context { + return Context{ + context.NewCoreContextFromViper(), + } +} diff --git a/cmd/iriscli/lcd.go b/cmd/iriscli/lcd.go index 8d9cdb194..d90b0b360 100644 --- a/cmd/iriscli/lcd.go +++ b/cmd/iriscli/lcd.go @@ -12,17 +12,17 @@ import ( tmserver "github.com/tendermint/tendermint/rpc/lib/server" cmn "github.com/tendermint/tmlibs/common" - client "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - keys "github.com/cosmos/cosmos-sdk/client/keys" - rpc "github.com/cosmos/cosmos-sdk/client/rpc" - tx "github.com/cosmos/cosmos-sdk/client/tx" - version "github.com/irisnet/irishub/version" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/client/rpc" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/irisnet/irishub/version" "github.com/cosmos/cosmos-sdk/wire" auth "github.com/cosmos/cosmos-sdk/x/auth/client/rest" bank "github.com/cosmos/cosmos-sdk/x/bank/client/rest" ibc "github.com/cosmos/cosmos-sdk/x/ibc/client/rest" stake "github.com/cosmos/cosmos-sdk/x/stake/client/rest" + "github.com/irisnet/irishub/app" ) // ServeCommand will generate a long-running rest server @@ -70,16 +70,16 @@ func createHandler(cdc *wire.Codec) http.Handler { panic(err) } - ctx := context.NewCoreContextFromViper() + ctx := app.NewContext() // TODO make more functional? aka r = keys.RegisterRoutes(r) keys.RegisterRoutes(r) - rpc.RegisterRoutes(ctx, r) - tx.RegisterRoutes(ctx, r, cdc) - auth.RegisterRoutes(ctx, r, cdc, "acc") - bank.RegisterRoutes(ctx, r, cdc, kb) - ibc.RegisterRoutes(ctx, r, cdc, kb) - stake.RegisterRoutes(ctx, r, cdc, kb) + rpc.RegisterRoutes(ctx.GetCosmosCtx(), r) + tx.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc) + auth.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, "acc") + bank.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, kb) + ibc.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, kb) + stake.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, kb) RegisterRoutes(ctx,r,cdc,kb) return r } diff --git a/cmd/iriscli/offline_sign.go b/cmd/iriscli/offline_sign.go index 1716ad58c..81c426ce4 100644 --- a/cmd/iriscli/offline_sign.go +++ b/cmd/iriscli/offline_sign.go @@ -4,7 +4,6 @@ import ( "github.com/cosmos/cosmos-sdk/wire" "encoding/json" "github.com/tendermint/go-crypto/keys" - "github.com/cosmos/cosmos-sdk/client/context" "net/http" "github.com/gorilla/mux" "io/ioutil" @@ -14,12 +13,11 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/stake" "github.com/pkg/errors" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - rpcclient "github.com/tendermint/tendermint/rpc/client" + "github.com/irisnet/irishub/app" ) -func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { +func RegisterRoutes(ctx app.Context, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { r.HandleFunc("/tx/send", SendTxRequestHandlerFn(cdc, kb, ctx)).Methods("POST") } @@ -39,7 +37,7 @@ type StdSignature struct { } //send traction(sign with rainbow) to irishub -func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { +func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx app.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var tx sendTx body, err := ioutil.ReadAll(r.Body) @@ -76,7 +74,7 @@ func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreCo } txByte,_ := cdc.MarshalBinary(stdTx) // send - res, err := BroadcastTxAsync(ctx,txByte) + res, err := ctx.BroadcastTxAsync(txByte) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) @@ -119,22 +117,4 @@ func convertMsg(tx sendTx) (sdk.Msg,error){ } return nil,errors.New("invalid message type") -} - -func BroadcastTxAsync(ctx context.CoreContext,tx []byte)(*ctypes.ResultBroadcastTx, error) { - nodeURI := ctx.NodeURI - if nodeURI == "" { - return nil, errors.New("rpc url is empty") - } - - var rpc rpcclient.Client - if nodeURI != "" { - rpc = rpcclient.NewHTTP(nodeURI, "/websocket") - } - - res, err := rpc.BroadcastTxAsync(tx) - if err != nil { - return res, err - } - return res, err } \ No newline at end of file From 7b6ed48d1d68f6579ae9e981da506ad327b2d0dc Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Wed, 4 Jul 2018 14:05:11 +0800 Subject: [PATCH 040/124] =?UTF-8?q?IRISHUB-9=EF=BC=9AThe=20BroadcastTxAsyn?= =?UTF-8?q?c=20method=20should=20not=20be=20used=20and=20should=20be=20rep?= =?UTF-8?q?laced=20with=20BroadcastTxSync.=20the=20reason:=20=20=20=20=20?= =?UTF-8?q?=20=20=20=20=20=20The=20return=20result=20of=20BroadcastTxAsync?= =?UTF-8?q?=20has=20not=20passed=20the=20checkTx=20process=20of=20the=20ap?= =?UTF-8?q?p,=20and=20the=20illegal=20transaction=20cannot=20be=20found=20?= =?UTF-8?q?in=20time;=20=20=20=20=20=20=20=20=20=20=20The=20result=20of=20?= =?UTF-8?q?BroadcastTxSync=20is=20passed=20through=20the=20app's=20checkTx?= =?UTF-8?q?=20process,=20which=20ensures=20that=20the=20transaction=20is?= =?UTF-8?q?=20executed=20correctly=20unless=20unexpected.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/context.go | 4 ++++ cmd/iriscli/offline_sign.go | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/app/context.go b/app/context.go index 3e2f9562a..3b9b10fc8 100644 --- a/app/context.go +++ b/app/context.go @@ -13,6 +13,10 @@ func (c Context) BroadcastTxAsync(tx []byte) (*ctypes.ResultBroadcastTx, error) return c.ctx.Client.BroadcastTxAsync(tx) } +func (c Context) BroadcastTxSync(tx []byte) (*ctypes.ResultBroadcastTx, error) { + return c.ctx.Client.BroadcastTxSync(tx) +} + func (c Context) GetCosmosCtx() (context.CoreContext) { return c.ctx } diff --git a/cmd/iriscli/offline_sign.go b/cmd/iriscli/offline_sign.go index 81c426ce4..28f3f6bbc 100644 --- a/cmd/iriscli/offline_sign.go +++ b/cmd/iriscli/offline_sign.go @@ -74,7 +74,7 @@ func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx app.Context) h } txByte,_ := cdc.MarshalBinary(stdTx) // send - res, err := ctx.BroadcastTxAsync(txByte) + res, err := ctx.BroadcastTxSync(txByte) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) From 7c65f59e3be75592736d11866da99f3b7aa33bb9 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Wed, 4 Jul 2018 15:07:53 +0800 Subject: [PATCH 041/124] =?UTF-8?q?IRISHUB-9=EF=BC=9Aupdate=20cosmos-sdk?= =?UTF-8?q?=20version=20from=20v0.19.0=20to=20v0.19.1-rc1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Gopkg.lock | 30 +++++++++++++++++------------- Gopkg.toml | 14 +++++++++----- 2 files changed, 26 insertions(+), 18 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index ebf148691..ecb233db4 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -49,8 +49,8 @@ "x/stake/client/cli", "x/stake/client/rest" ] - revision = "c6711810a86f09457481a8dadae899681a9d77ab" - version = "v0.19.0" + revision = "1e6d26ad3dce18fd1dde9bbee7d2aa192c196310" + version = "v0.19.1-rc1" [[projects]] name = "github.com/davecgh/go-spew" @@ -184,7 +184,10 @@ [[projects]] name = "github.com/magiconair/properties" - packages = ["."] + packages = [ + ".", + "assert" + ] revision = "c2353362d570a7bfa228149c62842019201cfb71" version = "v1.8.0" @@ -289,7 +292,7 @@ "leveldb/table", "leveldb/util" ] - revision = "e2150783cd35f5b607daca48afd8c57ec54cc995" + revision = "0d5a0ceb10cf9ab89fdd744cc8c50a83134f6697" [[projects]] name = "github.com/tendermint/abci" @@ -300,8 +303,8 @@ "server", "types" ] - revision = "ebee2fe114020aa49c70bbbae50b7079fc7e7b90" - version = "v0.11.0" + revision = "198dccf0ddfd1bb176f87657e3286a05a6ed9540" + version = "v0.12.0" [[projects]] branch = "master" @@ -380,8 +383,8 @@ "types", "version" ] - revision = "27bd1deabe4ba6a2d9b463b8f3e3f1e31b993e61" - version = "v0.20.0" + revision = "46369a1ab76f274ab47179c4176221842b8207b4" + version = "v0.21.0" [[projects]] name = "github.com/tendermint/tmlibs" @@ -398,7 +401,8 @@ "merkle", "merkle/tmhash" ] - revision = "0c98d10b4ffbd87978d79c160e835b3d3df241ec" + revision = "49596e0a1f48866603813df843c9409fc19805c6" + version = "v0.9.0" [[projects]] branch = "master" @@ -415,7 +419,7 @@ "ripemd160", "salsa20/salsa" ] - revision = "7f39a6fea4fe9364fb61e1def6a268a51b4f3a06" + revision = "a49355c7e3f8fe157a85be2f77e6e269a0f89602" [[projects]] branch = "master" @@ -429,13 +433,13 @@ "internal/timeseries", "trace" ] - revision = "db08ff08e8622530d9ed3a0e8ac279f6d4c02196" + revision = "ed29d75add3d7c4bf7ca65aac0c6df3d1420216f" [[projects]] branch = "master" name = "golang.org/x/sys" packages = ["unix"] - revision = "fc8bd948cf46f9c7af0f07d34151ce25fe90e477" + revision = "7138fd3d9dc8335c567ca206f4333fb75eb05d56" [[projects]] name = "golang.org/x/text" @@ -496,6 +500,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "e43d0010db3620c4c7daf0aca67fe5f6381f9fc907b1784718d189c4a47adae8" + inputs-digest = "6ed9efa50c179a5bcd8256cc3324bdaed2d49a769baa90e8283474987a84c9b7" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index a23280866..641df8a99 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -34,23 +34,27 @@ [[constraint]] name = "github.com/cosmos/cosmos-sdk" - version = "v0.19.0" + version = "v0.19.1-rc1" [[constraint]] name = "github.com/tendermint/abci" - version = "=0.11.0" + version = "=0.12.0" [[constraint]] name = "github.com/tendermint/go-crypto" - version = "~0.6.2" + version = "=0.6.2" [[constraint]] name = "github.com/tendermint/tendermint" - version = "=0.20.0" + version = "=0.21.0" [[override]] name = "github.com/tendermint/tmlibs" - revision = "0c98d10b4ffbd87978d79c160e835b3d3df241ec" + version = "=v0.9.0" + +[[override]] + name = "github.com/tendermint/iavl" + version = "=0.8.0-rc0" # this got updated and broke, so locked to an old working commit ... [[override]] From f1897a105736bf4d547a3f85d0091becbda0f0f8 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Fri, 6 Jul 2018 12:01:55 +0800 Subject: [PATCH 042/124] =?UTF-8?q?IRISHUB-34=EF=BC=9Airishub=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0prometheus=E7=9B=91=E6=8E=A7=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Gopkg.lock | 57 ++++++- Gopkg.toml | 4 + cmd/iriscli/lcd_test.go | 18 ++- cmd/iriscli/main.go | 3 + tools/prometheus/consensus/metrics.go | 208 ++++++++++++++++++++++++++ tools/prometheus/mempool/metrics.go | 25 ++++ tools/prometheus/p2p/metrics.go | 24 +++ tools/prometheus/provider.go | 13 ++ tools/prometheus/server.go | 48 ++++++ 9 files changed, 391 insertions(+), 9 deletions(-) create mode 100644 tools/prometheus/consensus/metrics.go create mode 100644 tools/prometheus/mempool/metrics.go create mode 100644 tools/prometheus/p2p/metrics.go create mode 100644 tools/prometheus/provider.go create mode 100644 tools/prometheus/server.go diff --git a/Gopkg.lock b/Gopkg.lock index ecb233db4..92e47b418 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -1,6 +1,12 @@ # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. +[[projects]] + branch = "master" + name = "github.com/beorn7/perks" + packages = ["quantile"] + revision = "3a771d992973f24aa725d07868b467d1ddfceafb" + [[projects]] name = "github.com/bgentry/speakeasy" packages = ["."] @@ -75,7 +81,10 @@ packages = [ "log", "log/level", - "log/term" + "log/term", + "metrics", + "metrics/internal/lv", + "metrics/prometheus" ] revision = "4dc7be5d2d12881735283bcab7352178e190fc71" version = "v0.6.0" @@ -197,6 +206,12 @@ revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" version = "v0.0.3" +[[projects]] + name = "github.com/matttproud/golang_protobuf_extensions" + packages = ["pbutil"] + revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" + version = "v1.0.1" + [[projects]] branch = "master" name = "github.com/mitchellh/mapstructure" @@ -221,6 +236,42 @@ revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" +[[projects]] + name = "github.com/prometheus/client_golang" + packages = [ + "prometheus", + "prometheus/promhttp" + ] + revision = "c5b7fccd204277076155f10851dad72b76a49317" + version = "v0.8.0" + +[[projects]] + branch = "master" + name = "github.com/prometheus/client_model" + packages = ["go"] + revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c" + +[[projects]] + branch = "master" + name = "github.com/prometheus/common" + packages = [ + "expfmt", + "internal/bitbucket.org/ww/goautoneg", + "model" + ] + revision = "7600349dcfe1abd18d72d3a1770870d9800a7801" + +[[projects]] + branch = "master" + name = "github.com/prometheus/procfs" + packages = [ + ".", + "internal/util", + "nfs", + "xfs" + ] + revision = "40f013a808ec4fa79def444a1a56de4d1727efcb" + [[projects]] branch = "master" name = "github.com/rcrowley/go-metrics" @@ -439,7 +490,7 @@ branch = "master" name = "golang.org/x/sys" packages = ["unix"] - revision = "7138fd3d9dc8335c567ca206f4333fb75eb05d56" + revision = "151529c776cdc58ddbe7963ba9af779f3577b419" [[projects]] name = "golang.org/x/text" @@ -500,6 +551,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "6ed9efa50c179a5bcd8256cc3324bdaed2d49a769baa90e8283474987a84c9b7" + inputs-digest = "d1273093894dceda82a36f80e217187acee7f2f34b020c05fb89352ff249c850" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index 641df8a99..f5ce9e94b 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -61,6 +61,10 @@ name = "google.golang.org/genproto" revision = "7fd901a49ba6a7f87732eb344f6e3c5b19d1b200" +[[constraint]] + name = "github.com/prometheus/client_golang" + version = "0.8.0" + [prune] go-tests = true unused-packages = true \ No newline at end of file diff --git a/cmd/iriscli/lcd_test.go b/cmd/iriscli/lcd_test.go index f3b7f1907..fac3d8782 100644 --- a/cmd/iriscli/lcd_test.go +++ b/cmd/iriscli/lcd_test.go @@ -14,22 +14,26 @@ import ("testing" "log" "os" "encoding/hex" + "github.com/irisnet/irishub/tools/prometheus" ) func TestRestServer(t *testing.T) { cdc := app.MakeCodec() comm := ServeCommand(cdc) viper.Set("chain-id","fuxi") - viper.Set("node","tcp://localhost:46657") + viper.Set("node","tcp://localhost:26657") viper.Set("laddr","tcp://localhost:1317") comm.ExecuteC() } -//var cdc = wire.NewCodec() -// -//func init() { -// cdc.RegisterConcrete(person{},"person",nil) -//} + +func TestMetricsCmd(t *testing.T){ + cdc := app.MakeCodec() + comm := prometheus.MonitorCommand("stake",cdc) + viper.Set("node","tcp://0.0.0.0:46657") + viper.Set("chain-id","fuxi") + comm.ExecuteC() +} func TestAmino(t *testing.T) { var cdc = amino.NewCodec() @@ -263,3 +267,5 @@ func TestBech32(t *testing.T){ } + + diff --git a/cmd/iriscli/main.go b/cmd/iriscli/main.go index e379c208e..76b01d917 100644 --- a/cmd/iriscli/main.go +++ b/cmd/iriscli/main.go @@ -15,6 +15,7 @@ import ( stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" "github.com/irisnet/irishub/app" "github.com/irisnet/irishub/version" + "github.com/irisnet/irishub/tools/prometheus" ) // rootCmd is the entry point for this binary @@ -115,6 +116,8 @@ func main() { version.VersionCmd, ) + rootCmd.AddCommand(prometheus.MonitorCommand("stake", cdc)) + // prepare and add flags executor := cli.PrepareMainCmd(rootCmd, "IRIS", app.DefaultCLIHome) executor.Execute() diff --git a/tools/prometheus/consensus/metrics.go b/tools/prometheus/consensus/metrics.go new file mode 100644 index 000000000..81a01e163 --- /dev/null +++ b/tools/prometheus/consensus/metrics.go @@ -0,0 +1,208 @@ +package consensus + +import ( + "github.com/go-kit/kit/metrics" + "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" + "github.com/tendermint/tendermint/types" + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/wire" // XXX fix + "fmt" + "strings" + "encoding/hex" + "time" + "log" + cctx "context" +) + +// Metrics contains metrics exposed by this package. +type Metrics struct { + // Height of the chain. + Height metrics.Gauge + + // Number of rounds. + Rounds metrics.Gauge + + // Number of validators. + Validators metrics.Gauge + // Total power of all validators. + ValidatorsPower metrics.Gauge + // Number of validators who did not sign. + MissingValidators metrics.Gauge + // Total power of the missing validators. + MissingValidatorsPower metrics.Gauge + // Number of validators who tried to double sign. + ByzantineValidators metrics.Gauge + // Total power of the byzantine validators. + ByzantineValidatorsPower metrics.Gauge + + // Time between this and the last block. + BlockIntervalSeconds metrics.Histogram + + // Number of transactions. + NumTxs metrics.Gauge + // Size of the block. + BlockSizeBytes metrics.Gauge + // Total number of transactions. + TotalTxs metrics.Gauge +} + +// PrometheusMetrics returns Metrics build using Prometheus client library. +func PrometheusMetrics() *Metrics { + return &Metrics{ + Height: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "height", + Help: "Height of the chain.", + }, []string{}), + Rounds: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "rounds", + Help: "Number of rounds.", + }, []string{}), + + Validators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "validators", + Help: "Number of validators.", + }, []string{}), + ValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "validators_power", + Help: "Total power of all validators.", + }, []string{}), + MissingValidators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "missing_validators", + Help: "Number of validators who did not sign.", + }, []string{}), + MissingValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "missing_validators_power", + Help: "Total power of the missing validators.", + }, []string{}), + ByzantineValidators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "byzantine_validators", + Help: "Number of validators who tried to double sign.", + }, []string{}), + ByzantineValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "byzantine_validators_power", + Help: "Total power of the byzantine validators.", + }, []string{}), + + BlockIntervalSeconds: prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{ + Subsystem: "consensus", + Name: "block_interval_seconds", + Help: "Time between this and the last block.", + Buckets: []float64{1, 2.5, 5, 10, 60}, + }, []string{}), + + NumTxs: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "num_txs", + Help: "Number of transactions.", + }, []string{}), + BlockSizeBytes: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "block_size_bytes", + Help: "Size of the block.", + }, []string{}), + TotalTxs: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "total_txs", + Help: "Total number of transactions.", + }, []string{}), + } +} + + +func Monitor(ctx context.CoreContext,csMetrics Metrics,cdc *wire.Codec,storeName string){ + context, _ := cctx.WithTimeout(cctx.Background(), 10*time.Second) + + var client = ctx.Client + //开启监听事件 + client.Start() + + blockC := make(chan interface{}) + + err := client.Subscribe(context, "monitor", types.EventQueryNewBlock, blockC) + + if err != nil { + log.Println("got ", err) + } + + go func() { + for e := range blockC { + block := e.(types.TMEventData).(types.EventDataNewBlock) + csMetrics.RecordMetrics(ctx,cdc,block.Block,storeName) + } + }() +} + +func (cs Metrics) RecordMetrics(ctx context.CoreContext,cdc *wire.Codec,block *types.Block,storeName string) { + cs.Height.Set(float64(block.Height)) + cs.ByzantineValidators.Set(float64(len(block.Evidence.Evidence))) + + missingValidators := 0 + missingValidatorsPower := int64(0) + validators := getValidators(cdc,ctx,storeName) + + valMap := make(map[string]stake.Validator,len(validators)) + for i, val := range validators { + var vote *types.Vote + if i < len(block.LastCommit.Precommits) { + vote = block.LastCommit.Precommits[i] + } + if vote == nil { + missingValidators++ + missingValidatorsPower += val.GetPower().Evaluate() + } + + valMap[val.Owner.String()] = val + } + + cs.MissingValidators.Set(float64(missingValidators)) + cs.MissingValidatorsPower.Set(float64(missingValidatorsPower)) + + byzantineValidatorsPower := int64(0) + for _, ev := range block.Evidence.Evidence { + addr := strings.ToUpper(hex.EncodeToString(ev.Address())) + if val,ok := valMap[addr]; ok { + byzantineValidatorsPower += val.GetPower().Evaluate() + } + } + cs.ByzantineValidatorsPower.Set(float64(byzantineValidatorsPower)) + + if block.Height > 1 { + lastBlockHight := block.Height -1 + resultBlock,_ := ctx.Client.Block(&lastBlockHight) + cs.BlockIntervalSeconds.Observe( + block.Time.Sub(resultBlock.BlockMeta.Header.Time).Seconds(), + ) + } + + cs.NumTxs.Set(float64(block.NumTxs)) + cs.TotalTxs.Set(float64(block.TotalTxs)) + + bz, _ := cdc.MarshalBinaryBare(block) + cs.BlockSizeBytes.Set(float64(len(bz))) +} + + +func getValidators(cdc *wire.Codec,ctx context.CoreContext,storeName string) (validators []stake.Validator){ + key := stake.ValidatorsKey + resKVs, err := ctx.QuerySubspace(cdc, key, storeName) + if err != nil { + fmt.Println(err) + } + + for _, KV := range resKVs { + var validator stake.Validator + cdc.MustUnmarshalBinary(KV.Value, &validator) + validators = append(validators, validator) + } + return validators +} \ No newline at end of file diff --git a/tools/prometheus/mempool/metrics.go b/tools/prometheus/mempool/metrics.go new file mode 100644 index 000000000..80f877c5f --- /dev/null +++ b/tools/prometheus/mempool/metrics.go @@ -0,0 +1,25 @@ +package mempool + +import ( + "github.com/go-kit/kit/metrics" + "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +// Metrics contains metrics exposed by this package. +// see MetricsProvider for descriptions. +type Metrics struct { + // Size of the mempool. + Size metrics.Gauge +} + +// PrometheusMetrics returns Metrics build using Prometheus client library. +func PrometheusMetrics() *Metrics { + return &Metrics{ + Size: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "mempool", + Name: "size", + Help: "Size of the mempool (number of uncommitted transactions).", + }, []string{}), + } +} diff --git a/tools/prometheus/p2p/metrics.go b/tools/prometheus/p2p/metrics.go new file mode 100644 index 000000000..2c56b4b56 --- /dev/null +++ b/tools/prometheus/p2p/metrics.go @@ -0,0 +1,24 @@ +package p2p + +import ( + "github.com/go-kit/kit/metrics" + "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +// Metrics contains metrics exposed by this package. +type Metrics struct { + // Number of peers. + Peers metrics.Gauge +} + +// PrometheusMetrics returns Metrics build using Prometheus client library. +func PrometheusMetrics() *Metrics { + return &Metrics{ + Peers: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "p2p", + Name: "peers", + Help: "Number of peers.", + }, []string{}), + } +} diff --git a/tools/prometheus/provider.go b/tools/prometheus/provider.go new file mode 100644 index 000000000..429af8c27 --- /dev/null +++ b/tools/prometheus/provider.go @@ -0,0 +1,13 @@ +package prometheus + +import ( + "github.com/irisnet/irishub/tools/prometheus/p2p" + cs "github.com/irisnet/irishub/tools/prometheus/consensus" + mempl "github.com/irisnet/irishub/tools/prometheus/mempool" +) + +// DefaultMetricsProvider returns consensus, p2p and mempool Metrics build +// using Prometheus client library. +func DefaultMetricsProvider() (*cs.Metrics, *p2p.Metrics, *mempl.Metrics) { + return cs.PrometheusMetrics(), p2p.PrometheusMetrics(), mempl.PrometheusMetrics() +} \ No newline at end of file diff --git a/tools/prometheus/server.go b/tools/prometheus/server.go new file mode 100644 index 000000000..0c912abe8 --- /dev/null +++ b/tools/prometheus/server.go @@ -0,0 +1,48 @@ +package prometheus + +import ( + "github.com/spf13/cobra" + "log" + "github.com/prometheus/client_golang/prometheus/promhttp" + "net/http" + cmn "github.com/tendermint/tmlibs/common" + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/wire" // XXX fix + "github.com/irisnet/irishub/tools/prometheus/consensus" +) + + +func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "monitor", + Short: "irishub monitor", + RunE: func(cmd *cobra.Command, args []string) error { + //TODO + csMetrics,_,_ := DefaultMetricsProvider() + ctx := context.NewCoreContextFromViper() + + //监控共识参数 + consensus.Monitor(ctx,*csMetrics,cdc,storeName) + + srv := &http.Server{ + Addr: ":26660", + Handler: promhttp.Handler(), + } + go func() { + if err := srv.ListenAndServe(); err != http.ErrServerClosed { + log.Println("got ", err) + } + }() + + cmn.TrapSignal(func() { + ctx.Client.Stop() + srv.Close() + }) + + return nil + }, + } + cmd.Flags().StringP("node", "n", "tcp://localhost:46657", "Node to connect to") + cmd.Flags().String("chain-id", "", "Chain ID of tendermint node") + return cmd +} From 4d96b0f8c149b9e173077fac48cc2dca0e351c4a Mon Sep 17 00:00:00 2001 From: programokey <872127164@qq.com> Date: Fri, 6 Jul 2018 01:15:13 -0700 Subject: [PATCH 043/124] add some system monitor terms --- tools/prometheus/system/metrics.go | 1 + 1 file changed, 1 insertion(+) create mode 100644 tools/prometheus/system/metrics.go diff --git a/tools/prometheus/system/metrics.go b/tools/prometheus/system/metrics.go new file mode 100644 index 000000000..9b140a34d --- /dev/null +++ b/tools/prometheus/system/metrics.go @@ -0,0 +1 @@ +package system From 95d824b55bfabe9edfed00755ad0d3c136672534 Mon Sep 17 00:00:00 2001 From: programokey <872127164@qq.com> Date: Fri, 6 Jul 2018 01:19:20 -0700 Subject: [PATCH 044/124] add some system monitor terms --- tools/prometheus/system/metrics.go | 131 +++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) diff --git a/tools/prometheus/system/metrics.go b/tools/prometheus/system/metrics.go index 9b140a34d..32c479e81 100644 --- a/tools/prometheus/system/metrics.go +++ b/tools/prometheus/system/metrics.go @@ -1 +1,132 @@ package system + +import ( + "github.com/go-kit/kit/metrics" + "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" + "time" + "fmt" + "os/exec" + "io/ioutil" + "strings" + "strconv" + "errors" + "github.com/shirou/gopsutil/process" + "github.com/shirou/gopsutil/disk" +) +type Metrics struct{ + CPUUtilization metrics.Gauge + MemoUtilization metrics.Gauge + OpenedFilesNum metrics.Gauge + DirSize metrics.Gauge +} + + +// PrometheusMetrics returns Metrics build using Prometheus client library. +func PrometheusMetrics() *Metrics { + return &Metrics{ + CPUUtilization:prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: "CPU_Percent", + Help: "CPU Utilization Percantage", + }, []string{}), + MemoUtilization:prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: "Memo_Percent", + Help: "Memo Utilization Percantage", + }, []string{}), + OpenedFilesNum:prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: "Opened_Files_Number", + Help: "Number of Opened Files, socket and other IO is included", + }, []string{}), + DirSize: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: "Directory_Size", + Help: "total size of files in given directory (in bytes)", + }, []string{}), + } +} + +func Monitor(command string, dir_path string, metrics *Metrics)(error){ + pid, err := getPid(command) + if err != nil{ + return err + } + go func(){ + for{ + time.Sleep(1*time.Second) + metrics.RecordMetrics(int32(pid), dir_path) + } + }() + return nil +} + +func (metrics Metrics)RecordMetrics(pid int32, dir_path string) { + proc := process.Process{Pid:pid} + + if cpu_util, err := proc.CPUPercent();err != nil{ + metrics.CPUUtilization.Set(float64(-1)) + }else{ + metrics.CPUUtilization.Set(cpu_util) + } + + if memo_util, err := proc.MemoryPercent();err != nil{ + metrics.MemoUtilization.Set(float64(-1)) + }else { + metrics.MemoUtilization.Set(float64(memo_util)) + } + + if files, err := proc.OpenFiles();err != nil{ + metrics.OpenedFilesNum.Set(float64(-1)) + }else { + metrics.OpenedFilesNum.Set(float64(len(files))) + } + + if usage, err := disk.Usage(dir_path); err != nil{ + metrics.DirSize.Set(float64(-1)) + }else{ + metrics.DirSize.Set(float64(usage.Used)) + } +} + +//get the pid of process that start by the given command +//the first pid return by "ps -aux|grep ", +// the process whose command contains "grep" is omitted +func getPid(command string)(pid int, err error){ + command_str := fmt.Sprintf("ps -aux|grep '%s'", command) + cmd := exec.Command("/bin/bash", "-c", command_str) + + stdout, err := cmd.StdoutPipe() + + if err != nil{ + fmt.Printf("Error:can not obtain stdout pipe for command:%s\n", err) + return 0, err + } + + if err := cmd.Start(); err != nil { + fmt.Println("Error:Invalid command,", err) + return 0, err + } + + bytes, err := ioutil.ReadAll(stdout) + if err != nil { + fmt.Println("ReadAll Stdout:", err.Error()) + return 0, err + } + for _, item := range (strings.Split(string(bytes), "\n")){ + if !strings.Contains(item, "grep"){ + for j, s := range (strings.Split(item, " ")){ + if j > 0 && s != ""{ + pid, err = strconv.Atoi(s) + if err == nil{ + return pid, nil + }else { + return 0, err + } + } + } + } + } + return 0, errors.New("cannot find the process") +} \ No newline at end of file From 2af5d3670efe664d1541578c686b7de8e7402839 Mon Sep 17 00:00:00 2001 From: programokey <872127164@qq.com> Date: Fri, 6 Jul 2018 01:28:53 -0700 Subject: [PATCH 045/124] add some system monitor terms --- tools/prometheus/provider.go | 5 +++-- tools/prometheus/server.go | 7 ++++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/tools/prometheus/provider.go b/tools/prometheus/provider.go index 429af8c27..68d580d8f 100644 --- a/tools/prometheus/provider.go +++ b/tools/prometheus/provider.go @@ -3,11 +3,12 @@ package prometheus import ( "github.com/irisnet/irishub/tools/prometheus/p2p" cs "github.com/irisnet/irishub/tools/prometheus/consensus" + sys "github.com/programokey/irishub/tools/prometheus/system" mempl "github.com/irisnet/irishub/tools/prometheus/mempool" ) // DefaultMetricsProvider returns consensus, p2p and mempool Metrics build // using Prometheus client library. -func DefaultMetricsProvider() (*cs.Metrics, *p2p.Metrics, *mempl.Metrics) { - return cs.PrometheusMetrics(), p2p.PrometheusMetrics(), mempl.PrometheusMetrics() +func DefaultMetricsProvider() (*cs.Metrics, *p2p.Metrics, *mempl.Metrics, *sys.Metrics) { + return cs.PrometheusMetrics(), p2p.PrometheusMetrics(), mempl.PrometheusMetrics(), sys.PrometheusMetrics() } \ No newline at end of file diff --git a/tools/prometheus/server.go b/tools/prometheus/server.go index 0c912abe8..618259546 100644 --- a/tools/prometheus/server.go +++ b/tools/prometheus/server.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/wire" // XXX fix "github.com/irisnet/irishub/tools/prometheus/consensus" + sys "github.com/programokey/irishub/tools/prometheus/system" ) @@ -18,12 +19,16 @@ func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { Short: "irishub monitor", RunE: func(cmd *cobra.Command, args []string) error { //TODO - csMetrics,_,_ := DefaultMetricsProvider() + csMetrics,_,_ , sysMertrics:= DefaultMetricsProvider() ctx := context.NewCoreContextFromViper() //监控共识参数 consensus.Monitor(ctx,*csMetrics,cdc,storeName) + //monitor system info, first parameter is the command of the process to be monitor + // and the second parameter is the directory that you want to get total size of its' files + sys.Monitor("irishub", "/", sysMertrics) + srv := &http.Server{ Addr: ":26660", Handler: promhttp.Handler(), From 08ae941a871a982f163aa40a3cd5e23bc4a03d8e Mon Sep 17 00:00:00 2001 From: programokey <872127164@qq.com> Date: Fri, 6 Jul 2018 02:11:10 -0700 Subject: [PATCH 046/124] add some system monitor terms --- tools/prometheus/system/metrics.go | 121 ++++++++++++++++++++--------- 1 file changed, 83 insertions(+), 38 deletions(-) diff --git a/tools/prometheus/system/metrics.go b/tools/prometheus/system/metrics.go index 32c479e81..1b9f6c826 100644 --- a/tools/prometheus/system/metrics.go +++ b/tools/prometheus/system/metrics.go @@ -1,41 +1,83 @@ package system import ( + "errors" + "fmt" "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/prometheus" stdprometheus "github.com/prometheus/client_golang/prometheus" - "time" - "fmt" - "os/exec" + "github.com/shirou/gopsutil/disk" + "github.com/shirou/gopsutil/process" "io/ioutil" - "strings" + "os/exec" "strconv" - "errors" - "github.com/shirou/gopsutil/process" - "github.com/shirou/gopsutil/disk" + "strings" + "time" ) -type Metrics struct{ - CPUUtilization metrics.Gauge + +type Metrics struct { + CPUUtilization metrics.Gauge MemoUtilization metrics.Gauge - OpenedFilesNum metrics.Gauge - DirSize metrics.Gauge + OpenedFilesNum metrics.Gauge + DirSize metrics.Gauge + metrics []metrics.Gauge + dirPaths []string + processes []process.Process +} + +func (metrics *Metrics) AddDirectory(path string) { + metrics.dirPaths = append(metrics.dirPaths, path) + name := fmt.Sprintf("Direcotry_Size_%s", strings.Replace(path, "/", "_", -1)) + help := fmt.Sprintf("total Size of files in %s", path) + metrics.metrics = append(metrics.metrics, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: name, + Help: help, + }, []string{})) } +func (metrics *Metrics) AddProcess(command string) { + pid, err := getPid(command) + if err != nil { + return + } + process := process.Process{Pid: int32(pid)} + metrics.processes = append(metrics.processes, process) + + metrics.metrics = append(metrics.metrics, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: fmt.Sprintf("CPU_Percent_%d", pid), + Help: fmt.Sprintf("CPU Utilization Percantage of processes with pid %d", pid), + }, []string{})) + + metrics.metrics = append(metrics.metrics, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: fmt.Sprintf("Memo_Percent_%d", pid), + Help: fmt.Sprintf("Memory Utilization Percantage of processes with pid %d", pid), + }, []string{})) + + metrics.metrics = append(metrics.metrics, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: fmt.Sprintf("Opened_Files_Number_%d", pid), + Help: fmt.Sprintf("Number of Opened Files of processes with pid %d", pid), + }, []string{})) + +} // PrometheusMetrics returns Metrics build using Prometheus client library. func PrometheusMetrics() *Metrics { return &Metrics{ - CPUUtilization:prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + CPUUtilization: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", Name: "CPU_Percent", Help: "CPU Utilization Percantage", }, []string{}), - MemoUtilization:prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + MemoUtilization: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", Name: "Memo_Percent", Help: "Memo Utilization Percantage", }, []string{}), - OpenedFilesNum:prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + OpenedFilesNum: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", Name: "Opened_Files_Number", Help: "Number of Opened Files, socket and other IO is included", @@ -45,47 +87,50 @@ func PrometheusMetrics() *Metrics { Name: "Directory_Size", Help: "total size of files in given directory (in bytes)", }, []string{}), + metrics: make([]metrics.Gauge, 0), + dirPaths: make([]string, 0), + processes: make([]process.Process, 0), } } -func Monitor(command string, dir_path string, metrics *Metrics)(error){ +func Monitor(command string, dir_path string, metrics *Metrics) error { pid, err := getPid(command) - if err != nil{ + if err != nil { return err } - go func(){ - for{ - time.Sleep(1*time.Second) + go func() { + for { + time.Sleep(1 * time.Second) metrics.RecordMetrics(int32(pid), dir_path) } }() return nil } -func (metrics Metrics)RecordMetrics(pid int32, dir_path string) { - proc := process.Process{Pid:pid} +func (metrics Metrics) RecordMetrics(pid int32, dir_path string) { + proc := process.Process{Pid: pid} - if cpu_util, err := proc.CPUPercent();err != nil{ + if cpu_util, err := proc.CPUPercent(); err != nil { metrics.CPUUtilization.Set(float64(-1)) - }else{ + } else { metrics.CPUUtilization.Set(cpu_util) } - if memo_util, err := proc.MemoryPercent();err != nil{ + if memo_util, err := proc.MemoryPercent(); err != nil { metrics.MemoUtilization.Set(float64(-1)) - }else { + } else { metrics.MemoUtilization.Set(float64(memo_util)) } - if files, err := proc.OpenFiles();err != nil{ + if files, err := proc.OpenFiles(); err != nil { metrics.OpenedFilesNum.Set(float64(-1)) - }else { + } else { metrics.OpenedFilesNum.Set(float64(len(files))) } - if usage, err := disk.Usage(dir_path); err != nil{ + if usage, err := disk.Usage(dir_path); err != nil { metrics.DirSize.Set(float64(-1)) - }else{ + } else { metrics.DirSize.Set(float64(usage.Used)) } } @@ -93,13 +138,13 @@ func (metrics Metrics)RecordMetrics(pid int32, dir_path string) { //get the pid of process that start by the given command //the first pid return by "ps -aux|grep ", // the process whose command contains "grep" is omitted -func getPid(command string)(pid int, err error){ +func getPid(command string) (pid int, err error) { command_str := fmt.Sprintf("ps -aux|grep '%s'", command) cmd := exec.Command("/bin/bash", "-c", command_str) stdout, err := cmd.StdoutPipe() - if err != nil{ + if err != nil { fmt.Printf("Error:can not obtain stdout pipe for command:%s\n", err) return 0, err } @@ -114,14 +159,14 @@ func getPid(command string)(pid int, err error){ fmt.Println("ReadAll Stdout:", err.Error()) return 0, err } - for _, item := range (strings.Split(string(bytes), "\n")){ - if !strings.Contains(item, "grep"){ - for j, s := range (strings.Split(item, " ")){ - if j > 0 && s != ""{ + for _, item := range strings.Split(string(bytes), "\n") { + if !strings.Contains(item, "grep") { + for j, s := range strings.Split(item, " ") { + if j > 0 && s != "" { pid, err = strconv.Atoi(s) - if err == nil{ + if err == nil { return pid, nil - }else { + } else { return 0, err } } @@ -129,4 +174,4 @@ func getPid(command string)(pid int, err error){ } } return 0, errors.New("cannot find the process") -} \ No newline at end of file +} From 0954ee94ae3c26e14a359389e355ce000e18f7e1 Mon Sep 17 00:00:00 2001 From: programokey <872127164@qq.com> Date: Fri, 6 Jul 2018 03:01:46 -0700 Subject: [PATCH 047/124] support multiple commands & files --- tools/prometheus/server.go | 2 +- tools/prometheus/system/metrics.go | 85 +++++++++++++++++------------- 2 files changed, 48 insertions(+), 39 deletions(-) diff --git a/tools/prometheus/server.go b/tools/prometheus/server.go index 618259546..7119969a1 100644 --- a/tools/prometheus/server.go +++ b/tools/prometheus/server.go @@ -27,7 +27,7 @@ func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { //monitor system info, first parameter is the command of the process to be monitor // and the second parameter is the directory that you want to get total size of its' files - sys.Monitor("irishub", "/", sysMertrics) + sys.Monitor(sysMertrics) srv := &http.Server{ Addr: ":26660", diff --git a/tools/prometheus/system/metrics.go b/tools/prometheus/system/metrics.go index 1b9f6c826..36d4a810e 100644 --- a/tools/prometheus/system/metrics.go +++ b/tools/prometheus/system/metrics.go @@ -13,23 +13,28 @@ import ( "strconv" "strings" "time" + "github.com/shirou/gopsutil/mem" + "github.com/shirou/gopsutil/cpu" ) type Metrics struct { CPUUtilization metrics.Gauge MemoUtilization metrics.Gauge - OpenedFilesNum metrics.Gauge - DirSize metrics.Gauge - metrics []metrics.Gauge - dirPaths []string + + ProcCPUUtilization []metrics.Gauge + ProcMemoUtilization []metrics.Gauge + ProcOpenedFilesNum []metrics.Gauge processes []process.Process + + DirectorySize []metrics.Gauge + dirPaths []string } func (metrics *Metrics) AddDirectory(path string) { metrics.dirPaths = append(metrics.dirPaths, path) name := fmt.Sprintf("Direcotry_Size_%s", strings.Replace(path, "/", "_", -1)) help := fmt.Sprintf("total Size of files in %s", path) - metrics.metrics = append(metrics.metrics, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + metrics.DirectorySize = append(metrics.DirectorySize, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", Name: name, Help: help, @@ -44,19 +49,19 @@ func (metrics *Metrics) AddProcess(command string) { process := process.Process{Pid: int32(pid)} metrics.processes = append(metrics.processes, process) - metrics.metrics = append(metrics.metrics, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + metrics.ProcCPUUtilization = append(metrics.ProcCPUUtilization, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", Name: fmt.Sprintf("CPU_Percent_%d", pid), Help: fmt.Sprintf("CPU Utilization Percantage of processes with pid %d", pid), }, []string{})) - metrics.metrics = append(metrics.metrics, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + metrics.ProcMemoUtilization = append(metrics.ProcMemoUtilization, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", Name: fmt.Sprintf("Memo_Percent_%d", pid), Help: fmt.Sprintf("Memory Utilization Percantage of processes with pid %d", pid), }, []string{})) - metrics.metrics = append(metrics.metrics, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + metrics.ProcOpenedFilesNum = append(metrics.ProcOpenedFilesNum, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", Name: fmt.Sprintf("Opened_Files_Number_%d", pid), Help: fmt.Sprintf("Number of Opened Files of processes with pid %d", pid), @@ -77,23 +82,15 @@ func PrometheusMetrics() *Metrics { Name: "Memo_Percent", Help: "Memo Utilization Percantage", }, []string{}), - OpenedFilesNum: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "system", - Name: "Opened_Files_Number", - Help: "Number of Opened Files, socket and other IO is included", - }, []string{}), - DirSize: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "system", - Name: "Directory_Size", - Help: "total size of files in given directory (in bytes)", - }, []string{}), - metrics: make([]metrics.Gauge, 0), + ProcCPUUtilization: make([]metrics.Gauge, 0), + ProcMemoUtilization: make([]metrics.Gauge, 0), + ProcOpenedFilesNum: make([]metrics.Gauge, 0), dirPaths: make([]string, 0), processes: make([]process.Process, 0), } } -func Monitor(command string, dir_path string, metrics *Metrics) error { +func Monitor(metrics *Metrics) error { pid, err := getPid(command) if err != nil { return err @@ -108,31 +105,43 @@ func Monitor(command string, dir_path string, metrics *Metrics) error { } func (metrics Metrics) RecordMetrics(pid int32, dir_path string) { - proc := process.Process{Pid: pid} - if cpu_util, err := proc.CPUPercent(); err != nil { - metrics.CPUUtilization.Set(float64(-1)) - } else { - metrics.CPUUtilization.Set(cpu_util) - } + for i, process := range(metrics.processes){ + if cpu_util, err := process.CPUPercent(); err != nil { + metrics.ProcCPUUtilization[i].Set(float64(-1)) + } else { + metrics.ProcCPUUtilization[i].Set(cpu_util) + } - if memo_util, err := proc.MemoryPercent(); err != nil { - metrics.MemoUtilization.Set(float64(-1)) - } else { - metrics.MemoUtilization.Set(float64(memo_util)) + if memo_util, err := process.MemoryPercent(); err != nil { + metrics.ProcMemoUtilization[i].Set(float64(-1)) + } else { + metrics.ProcMemoUtilization[i].Set(float64(memo_util)) + } + + if files, err := process.OpenFiles(); err != nil { + metrics.ProcOpenedFilesNum[i].Set(float64(-1)) + } else { + metrics.ProcOpenedFilesNum[i].Set(float64(len(files))) + } } - if files, err := proc.OpenFiles(); err != nil { - metrics.OpenedFilesNum.Set(float64(-1)) - } else { - metrics.OpenedFilesNum.Set(float64(len(files))) + for i, dir_path := range (metrics.dirPaths){ + if usage, err := disk.Usage(dir_path); err != nil { + metrics.DirectorySize[i].Set(float64(-1)) + } else { + metrics.DirectorySize[i].Set(float64(usage.Used)) + } } + vMemoStat, _ := mem.VirtualMemory() + metrics.MemoUtilization.Set(vMemoStat.UsedPercent) - if usage, err := disk.Usage(dir_path); err != nil { - metrics.DirSize.Set(float64(-1)) - } else { - metrics.DirSize.Set(float64(usage.Used)) + CPUUsedPercent := float64(0.0) + percents, _ := cpu.Percent(time.Millisecond*100, false) + for _, percent := range (percents){ + CPUUsedPercent += percent } + metrics.CPUUtilization.Set(CPUUsedPercent/4) } //get the pid of process that start by the given command From 031836f45fc43a4acf8ccf64c14004225064cc85 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Fri, 6 Jul 2018 18:33:24 +0800 Subject: [PATCH 048/124] =?UTF-8?q?IRISHUB-34=EF=BC=9Airishub=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0prometheus=E7=9B=91=E6=8E=A7=E5=8A=9F=E8=83=BD(?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0p2p,memo=E7=9B=91=E6=8E=A7=EF=BC=8C=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E7=9B=91=E6=8E=A7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Gopkg.lock | 48 +++++++++++++- tools/context.go | 90 +++++++++++++++++++++++++++ tools/prometheus/consensus/metrics.go | 18 +++--- tools/prometheus/mempool/metrics.go | 6 ++ tools/prometheus/p2p/metrics.go | 6 ++ tools/prometheus/server.go | 23 ++++--- 6 files changed, 172 insertions(+), 19 deletions(-) create mode 100644 tools/context.go diff --git a/Gopkg.lock b/Gopkg.lock index 92e47b418..bc0d3f0f9 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -1,6 +1,12 @@ # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. +[[projects]] + name = "github.com/StackExchange/wmi" + packages = ["."] + revision = "5d049714c4a64225c3c79a7cf7d02f7fb5b96338" + version = "1.0.0" + [[projects]] branch = "master" name = "github.com/beorn7/perks" @@ -95,6 +101,15 @@ revision = "390ab7935ee28ec6b286364bba9b4dd6410cb3d5" version = "v0.3.0" +[[projects]] + name = "github.com/go-ole/go-ole" + packages = [ + ".", + "oleutil" + ] + revision = "a41e3c4b706f6ae8dfbff342b06e40fa4d2d0506" + version = "v1.2.1" + [[projects]] name = "github.com/go-stack/stack" packages = ["."] @@ -236,6 +251,12 @@ revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" +[[projects]] + branch = "feature/prometheus" + name = "github.com/programokey/irishub" + packages = ["tools/prometheus/system"] + revision = "0c610311c5e650b1f6bd11b7daca20d830db0dee" + [[projects]] name = "github.com/prometheus/client_golang" packages = [ @@ -278,6 +299,26 @@ packages = ["."] revision = "e2704e165165ec55d062f5919b4b29494e9fa790" +[[projects]] + name = "github.com/shirou/gopsutil" + packages = [ + "cpu", + "disk", + "host", + "internal/common", + "mem", + "net", + "process" + ] + revision = "4a180b209f5f494e5923cfce81ea30ba23915877" + version = "v2.18.06" + +[[projects]] + branch = "master" + name = "github.com/shirou/w32" + packages = ["."] + revision = "bb4de0191aa41b5507caa14b0650cdbddcd9280b" + [[projects]] name = "github.com/spf13/afero" packages = [ @@ -489,7 +530,10 @@ [[projects]] branch = "master" name = "golang.org/x/sys" - packages = ["unix"] + packages = [ + "unix", + "windows" + ] revision = "151529c776cdc58ddbe7963ba9af779f3577b419" [[projects]] @@ -551,6 +595,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "d1273093894dceda82a36f80e217187acee7f2f34b020c05fb89352ff249c850" + inputs-digest = "d1bbcb679276fc124a31c41805c73016c0954c40a2b153966695d188b41b09f1" solver-name = "gps-cdcl" solver-version = 1 diff --git a/tools/context.go b/tools/context.go new file mode 100644 index 000000000..b6f93136a --- /dev/null +++ b/tools/context.go @@ -0,0 +1,90 @@ +package tools + +import ( + "github.com/cosmos/cosmos-sdk/client/context" + "fmt" + "io/ioutil" + "encoding/json" + "strings" + "net/http" + ctypes "github.com/tendermint/tendermint/rpc/core/types" + +) + +type Context struct { + context.CoreContext +} + +func NewContext() Context { + ctx := context.NewCoreContextFromViper() + return Context{ + ctx, + } +} + +type JsonRpc interface { + NetInfo() *ctypes.ResultNetInfo + NumUnconfirmedTxs() *ctypes.ResultUnconfirmedTxs +} + +func (rpc Context) NetInfo() *ctypes.ResultNetInfo{ + client := &http.Client{} + + reqUri := tcpToHttpUrl(rpc.NodeURI) + "/net_info" + + resp, err := client.Get(reqUri) + if err != nil { + fmt.Println(err) + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + fmt.Println(err) + } + + var res = struct { + JsonRpc string `json:"jsonrpc"` + Id string `json:"id"` + Result ctypes.ResultNetInfo `json:"result"` + }{} + if err := json.Unmarshal(body,&res); err != nil { + fmt.Println(err) + } + + return &res.Result +} + +func (rpc Context) NumUnconfirmedTxs() *ctypes.ResultUnconfirmedTxs{ + client := &http.Client{} + reqUri := tcpToHttpUrl(rpc.NodeURI) + "/num_unconfirmed_txs" + + resp, err := client.Get(reqUri) + if err != nil { + fmt.Println(err) + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + fmt.Println(err) + } + + var res = struct { + JsonRpc string `json:"jsonrpc"` + Id string `json:"id"` + Result ctypes.ResultUnconfirmedTxs `json:"result"` + }{} + if err := json.Unmarshal(body,&res); err != nil { + fmt.Println(err) + } + + return &res.Result +} + +func tcpToHttpUrl(url string) string{ + urls := strings.Replace(url,"tcp","http",1) + return urls +} + + diff --git a/tools/prometheus/consensus/metrics.go b/tools/prometheus/consensus/metrics.go index 81a01e163..e8250e1b2 100644 --- a/tools/prometheus/consensus/metrics.go +++ b/tools/prometheus/consensus/metrics.go @@ -5,7 +5,6 @@ import ( "github.com/go-kit/kit/metrics/prometheus" stdprometheus "github.com/prometheus/client_golang/prometheus" "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/x/stake" "github.com/cosmos/cosmos-sdk/wire" // XXX fix "fmt" @@ -14,6 +13,7 @@ import ( "time" "log" cctx "context" + tools "github.com/irisnet/irishub/tools" ) // Metrics contains metrics exposed by this package. @@ -118,8 +118,7 @@ func PrometheusMetrics() *Metrics { } } - -func Monitor(ctx context.CoreContext,csMetrics Metrics,cdc *wire.Codec,storeName string){ +func (cs *Metrics)Monitor(ctx tools.Context,cdc *wire.Codec,storeName string){ context, _ := cctx.WithTimeout(cctx.Background(), 10*time.Second) var client = ctx.Client @@ -137,17 +136,18 @@ func Monitor(ctx context.CoreContext,csMetrics Metrics,cdc *wire.Codec,storeName go func() { for e := range blockC { block := e.(types.TMEventData).(types.EventDataNewBlock) - csMetrics.RecordMetrics(ctx,cdc,block.Block,storeName) + cs.RecordMetrics(ctx,cdc,block.Block,storeName) } }() } -func (cs Metrics) RecordMetrics(ctx context.CoreContext,cdc *wire.Codec,block *types.Block,storeName string) { +func (cs Metrics) RecordMetrics(ctx tools.Context,cdc *wire.Codec,block *types.Block,storeName string) { cs.Height.Set(float64(block.Height)) cs.ByzantineValidators.Set(float64(len(block.Evidence.Evidence))) missingValidators := 0 missingValidatorsPower := int64(0) + validatorsPower := int64(0) validators := getValidators(cdc,ctx,storeName) valMap := make(map[string]stake.Validator,len(validators)) @@ -162,10 +162,12 @@ func (cs Metrics) RecordMetrics(ctx context.CoreContext,cdc *wire.Codec,block *t } valMap[val.Owner.String()] = val + validatorsPower += val.GetPower().Evaluate() } cs.MissingValidators.Set(float64(missingValidators)) cs.MissingValidatorsPower.Set(float64(missingValidatorsPower)) + cs.ValidatorsPower.Set(float64(validatorsPower)) byzantineValidatorsPower := int64(0) for _, ev := range block.Evidence.Evidence { @@ -178,9 +180,9 @@ func (cs Metrics) RecordMetrics(ctx context.CoreContext,cdc *wire.Codec,block *t if block.Height > 1 { lastBlockHight := block.Height -1 - resultBlock,_ := ctx.Client.Block(&lastBlockHight) + lastBlock,_ := ctx.Client.Block(&lastBlockHight) cs.BlockIntervalSeconds.Observe( - block.Time.Sub(resultBlock.BlockMeta.Header.Time).Seconds(), + block.Time.Sub(lastBlock.BlockMeta.Header.Time).Seconds(), ) } @@ -192,7 +194,7 @@ func (cs Metrics) RecordMetrics(ctx context.CoreContext,cdc *wire.Codec,block *t } -func getValidators(cdc *wire.Codec,ctx context.CoreContext,storeName string) (validators []stake.Validator){ +func getValidators(cdc *wire.Codec,ctx tools.Context,storeName string) (validators []stake.Validator){ key := stake.ValidatorsKey resKVs, err := ctx.QuerySubspace(cdc, key, storeName) if err != nil { diff --git a/tools/prometheus/mempool/metrics.go b/tools/prometheus/mempool/metrics.go index 80f877c5f..011ea3a03 100644 --- a/tools/prometheus/mempool/metrics.go +++ b/tools/prometheus/mempool/metrics.go @@ -4,6 +4,7 @@ import ( "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/prometheus" stdprometheus "github.com/prometheus/client_golang/prometheus" + tools "github.com/irisnet/irishub/tools" ) // Metrics contains metrics exposed by this package. @@ -23,3 +24,8 @@ func PrometheusMetrics() *Metrics { }, []string{}), } } + +func (m *Metrics )Monitor(rpc tools.Context){ + result := rpc.NumUnconfirmedTxs() + m.Size.Set(float64(result.N)) +} \ No newline at end of file diff --git a/tools/prometheus/p2p/metrics.go b/tools/prometheus/p2p/metrics.go index 2c56b4b56..dedda14a0 100644 --- a/tools/prometheus/p2p/metrics.go +++ b/tools/prometheus/p2p/metrics.go @@ -4,6 +4,7 @@ import ( "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/prometheus" stdprometheus "github.com/prometheus/client_golang/prometheus" + tools "github.com/irisnet/irishub/tools" ) // Metrics contains metrics exposed by this package. @@ -22,3 +23,8 @@ func PrometheusMetrics() *Metrics { }, []string{}), } } + +func (m *Metrics) Monitor(ctx tools.Context){ + result := ctx.NetInfo() + m.Peers.Set(float64(result.NPeers)) +} diff --git a/tools/prometheus/server.go b/tools/prometheus/server.go index 618259546..34b38cfbc 100644 --- a/tools/prometheus/server.go +++ b/tools/prometheus/server.go @@ -6,10 +6,9 @@ import ( "github.com/prometheus/client_golang/prometheus/promhttp" "net/http" cmn "github.com/tendermint/tmlibs/common" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/wire" // XXX fix - "github.com/irisnet/irishub/tools/prometheus/consensus" - sys "github.com/programokey/irishub/tools/prometheus/system" + "github.com/cosmos/cosmos-sdk/wire" + "github.com/irisnet/irishub/tools" + "github.com/spf13/viper" ) @@ -19,15 +18,20 @@ func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { Short: "irishub monitor", RunE: func(cmd *cobra.Command, args []string) error { //TODO - csMetrics,_,_ , sysMertrics:= DefaultMetricsProvider() - ctx := context.NewCoreContextFromViper() + csMetrics,p2pMetrics,memMetrics, sysMertrics:= DefaultMetricsProvider() + ctx := tools.NewContext() //监控共识参数 - consensus.Monitor(ctx,*csMetrics,cdc,storeName) + csMetrics.Monitor(ctx,cdc,storeName) + //监控p2p参数 + p2pMetrics.Monitor(ctx) + //监控mempool参数 + memMetrics.Monitor(ctx) //monitor system info, first parameter is the command of the process to be monitor // and the second parameter is the directory that you want to get total size of its' files - sys.Monitor("irishub", "/", sysMertrics) + path := viper.GetString("home") + sysMertrics.Monitor("iris", path) srv := &http.Server{ Addr: ":26660", @@ -48,6 +52,7 @@ func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { }, } cmd.Flags().StringP("node", "n", "tcp://localhost:46657", "Node to connect to") - cmd.Flags().String("chain-id", "", "Chain ID of tendermint node") + cmd.Flags().String("chain-id", "fuxi", "Chain ID of tendermint node") + cmd.Flags().StringP("home", "", "", "directory for config and data") return cmd } From 9bdc080f3056f72b847ba4d7495ba20d4a26fa0b Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Mon, 9 Jul 2018 09:28:14 +0800 Subject: [PATCH 049/124] =?UTF-8?q?IRISHUB-34=EF=BC=9Airishub=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0prometheus=E7=9B=91=E6=8E=A7=E5=8A=9F=E8=83=BD(?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0p2p,memo=E7=9B=91=E6=8E=A7=EF=BC=8C=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E7=9B=91=E6=8E=A7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/prometheus/mempool/metrics.go | 11 +++++++++-- tools/prometheus/p2p/metrics.go | 10 ++++++++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/tools/prometheus/mempool/metrics.go b/tools/prometheus/mempool/metrics.go index 011ea3a03..5f2aee456 100644 --- a/tools/prometheus/mempool/metrics.go +++ b/tools/prometheus/mempool/metrics.go @@ -5,6 +5,7 @@ import ( "github.com/go-kit/kit/metrics/prometheus" stdprometheus "github.com/prometheus/client_golang/prometheus" tools "github.com/irisnet/irishub/tools" + "time" ) // Metrics contains metrics exposed by this package. @@ -26,6 +27,12 @@ func PrometheusMetrics() *Metrics { } func (m *Metrics )Monitor(rpc tools.Context){ - result := rpc.NumUnconfirmedTxs() - m.Size.Set(float64(result.N)) + go func() { + for { + time.Sleep(1 * time.Second) + result := rpc.NumUnconfirmedTxs() + m.Size.Set(float64(result.N)) + } + }() + } \ No newline at end of file diff --git a/tools/prometheus/p2p/metrics.go b/tools/prometheus/p2p/metrics.go index dedda14a0..343c85c59 100644 --- a/tools/prometheus/p2p/metrics.go +++ b/tools/prometheus/p2p/metrics.go @@ -5,6 +5,7 @@ import ( "github.com/go-kit/kit/metrics/prometheus" stdprometheus "github.com/prometheus/client_golang/prometheus" tools "github.com/irisnet/irishub/tools" + "time" ) // Metrics contains metrics exposed by this package. @@ -25,6 +26,11 @@ func PrometheusMetrics() *Metrics { } func (m *Metrics) Monitor(ctx tools.Context){ - result := ctx.NetInfo() - m.Peers.Set(float64(result.NPeers)) + go func() { + for { + time.Sleep(1 * time.Second) + result := ctx.NetInfo() + m.Peers.Set(float64(result.NPeers)) + } + }() } From 27eee2104a90fafc304a0cd9a52488ec47639163 Mon Sep 17 00:00:00 2001 From: programokey <872127164@qq.com> Date: Sun, 8 Jul 2018 20:27:40 -0700 Subject: [PATCH 050/124] update commands --- tools/prometheus/server.go | 41 ++++++++++++++++++++++-------- tools/prometheus/system/metrics.go | 10 +++----- 2 files changed, 33 insertions(+), 18 deletions(-) diff --git a/tools/prometheus/server.go b/tools/prometheus/server.go index 7119969a1..92fe45af6 100644 --- a/tools/prometheus/server.go +++ b/tools/prometheus/server.go @@ -6,10 +6,10 @@ import ( "github.com/prometheus/client_golang/prometheus/promhttp" "net/http" cmn "github.com/tendermint/tmlibs/common" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/wire" // XXX fix - "github.com/irisnet/irishub/tools/prometheus/consensus" - sys "github.com/programokey/irishub/tools/prometheus/system" + "github.com/cosmos/cosmos-sdk/wire" + "github.com/irisnet/irishub/tools" + "github.com/spf13/viper" + "strings" ) @@ -19,15 +19,29 @@ func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { Short: "irishub monitor", RunE: func(cmd *cobra.Command, args []string) error { //TODO - csMetrics,_,_ , sysMertrics:= DefaultMetricsProvider() - ctx := context.NewCoreContextFromViper() + csMetrics,p2pMetrics,memMetrics, sysMertrics:= DefaultMetricsProvider() + ctx := tools.NewContext() //监控共识参数 - consensus.Monitor(ctx,*csMetrics,cdc,storeName) + csMetrics.Monitor(ctx,cdc,storeName) + //监控p2p参数 + p2pMetrics.Monitor(ctx) + //监控mempool参数 + memMetrics.Monitor(ctx) - //monitor system info, first parameter is the command of the process to be monitor - // and the second parameter is the directory that you want to get total size of its' files - sys.Monitor(sysMertrics) + + paths := viper.GetString("paths") + commands := viper.GetString("commands") + + for _, command := range strings.Split(commands, ";"){ + sysMertrics.AddProcess(strings.TrimSpace(command)) + } + + for _, path := range strings.Split(paths, ";"){ + sysMertrics.AddDirectory(strings.TrimSpace(path)) + } + + sysMertrics.Monitor() srv := &http.Server{ Addr: ":26660", @@ -48,6 +62,11 @@ func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { }, } cmd.Flags().StringP("node", "n", "tcp://localhost:46657", "Node to connect to") - cmd.Flags().String("chain-id", "", "Chain ID of tendermint node") + cmd.Flags().String("chain-id", "fuxi", "Chain ID of tendermint node") + cmd.Flags().StringP("commands", "c", "iris", `the processes you want to monitor that started +by these commands, separated by semicolons ';'. +eg: --commands="command 0;command 1;command 2", --commands=iris by default`) + cmd.Flags().StringP("paths", "p", "", `directories for config and data, separated by semicolons ';'. +eg: --paths="/;/etc/;/root"`) return cmd } diff --git a/tools/prometheus/system/metrics.go b/tools/prometheus/system/metrics.go index 36d4a810e..554c7ff05 100644 --- a/tools/prometheus/system/metrics.go +++ b/tools/prometheus/system/metrics.go @@ -90,21 +90,17 @@ func PrometheusMetrics() *Metrics { } } -func Monitor(metrics *Metrics) error { - pid, err := getPid(command) - if err != nil { - return err - } +func (metrics *Metrics) Monitor() error { go func() { for { time.Sleep(1 * time.Second) - metrics.RecordMetrics(int32(pid), dir_path) + metrics.RecordMetrics() } }() return nil } -func (metrics Metrics) RecordMetrics(pid int32, dir_path string) { +func (metrics Metrics) RecordMetrics() { for i, process := range(metrics.processes){ if cpu_util, err := process.CPUPercent(); err != nil { From c0a3995dcab815429fbd528250c6b5e011f1e456 Mon Sep 17 00:00:00 2001 From: programokey <872127164@qq.com> Date: Sun, 8 Jul 2018 21:03:48 -0700 Subject: [PATCH 051/124] add some test cases of system/Metrics --- cmd/iriscli/lcd_test.go | 3 +++ tools/prometheus/server.go | 24 +++++++++++++++--------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/cmd/iriscli/lcd_test.go b/cmd/iriscli/lcd_test.go index fac3d8782..0ae5ae75b 100644 --- a/cmd/iriscli/lcd_test.go +++ b/cmd/iriscli/lcd_test.go @@ -17,6 +17,7 @@ import ("testing" "github.com/irisnet/irishub/tools/prometheus" ) + func TestRestServer(t *testing.T) { cdc := app.MakeCodec() comm := ServeCommand(cdc) @@ -32,6 +33,8 @@ func TestMetricsCmd(t *testing.T){ comm := prometheus.MonitorCommand("stake",cdc) viper.Set("node","tcp://0.0.0.0:46657") viper.Set("chain-id","fuxi") + viper.Set("commands","iris start ;htop") + viper.Set("paths","/etc ") comm.ExecuteC() } diff --git a/tools/prometheus/server.go b/tools/prometheus/server.go index 92fe45af6..d741bd9a6 100644 --- a/tools/prometheus/server.go +++ b/tools/prometheus/server.go @@ -7,9 +7,10 @@ import ( "net/http" cmn "github.com/tendermint/tmlibs/common" "github.com/cosmos/cosmos-sdk/wire" - "github.com/irisnet/irishub/tools" "github.com/spf13/viper" "strings" + "fmt" + "github.com/irisnet/irishub/tools" ) @@ -19,7 +20,7 @@ func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { Short: "irishub monitor", RunE: func(cmd *cobra.Command, args []string) error { //TODO - csMetrics,p2pMetrics,memMetrics, sysMertrics:= DefaultMetricsProvider() + csMetrics,p2pMetrics,memMetrics, sysMetrics:= DefaultMetricsProvider() ctx := tools.NewContext() //监控共识参数 @@ -29,19 +30,24 @@ func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { //监控mempool参数 memMetrics.Monitor(ctx) - paths := viper.GetString("paths") commands := viper.GetString("commands") for _, command := range strings.Split(commands, ";"){ - sysMertrics.AddProcess(strings.TrimSpace(command)) + if strings.TrimSpace(command) != ""{ + fmt.Println("command:", strings.TrimSpace(command)) + sysMetrics.AddProcess(strings.TrimSpace(command)) + } } for _, path := range strings.Split(paths, ";"){ - sysMertrics.AddDirectory(strings.TrimSpace(path)) + if strings.TrimSpace(path) != ""{ + fmt.Println("path:", strings.TrimSpace(path)) + sysMetrics.AddDirectory(strings.TrimSpace(path)) + } } - sysMertrics.Monitor() + sysMetrics.Monitor() srv := &http.Server{ Addr: ":26660", @@ -63,10 +69,10 @@ func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { } cmd.Flags().StringP("node", "n", "tcp://localhost:46657", "Node to connect to") cmd.Flags().String("chain-id", "fuxi", "Chain ID of tendermint node") - cmd.Flags().StringP("commands", "c", "iris", `the processes you want to monitor that started + cmd.Flags().StringP("commands", "c", "iris start", `the processes you want to monitor that started by these commands, separated by semicolons ';'. eg: --commands="command 0;command 1;command 2", --commands=iris by default`) - cmd.Flags().StringP("paths", "p", "", `directories for config and data, separated by semicolons ';'. -eg: --paths="/;/etc/;/root"`) + cmd.Flags().StringP("paths", "p", "/", `directories for config and data, separated by semicolons ';'. +eg: --paths="/;/mnt1;/mnt2"`) return cmd } From 7a0256250cee69d56ef89b2f496dba17d73560d7 Mon Sep 17 00:00:00 2001 From: programokey <872127164@qq.com> Date: Sun, 8 Jul 2018 23:19:22 -0700 Subject: [PATCH 052/124] add some test cases of system/metrics.go --- cmd/iriscli/lcd_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/iriscli/lcd_test.go b/cmd/iriscli/lcd_test.go index 0ae5ae75b..71eb6d87b 100644 --- a/cmd/iriscli/lcd_test.go +++ b/cmd/iriscli/lcd_test.go @@ -33,7 +33,7 @@ func TestMetricsCmd(t *testing.T){ comm := prometheus.MonitorCommand("stake",cdc) viper.Set("node","tcp://0.0.0.0:46657") viper.Set("chain-id","fuxi") - viper.Set("commands","iris start ;htop") + viper.Set("commands","iris start;htop") viper.Set("paths","/etc ") comm.ExecuteC() } From f05af8fba9e92000f2c94d1d9e5246f700a5a661 Mon Sep 17 00:00:00 2001 From: programokey <872127164@qq.com> Date: Mon, 9 Jul 2018 02:33:12 -0700 Subject: [PATCH 053/124] add monitor terms of disk usage, and support monitoring directories and files --- cmd/iriscli/lcd_test.go | 11 +- tools/prometheus/provider.go | 2 +- tools/prometheus/server.go | 24 +++- tools/prometheus/system/metrics.go | 205 +++++++++++++++++++++++------ 4 files changed, 195 insertions(+), 47 deletions(-) diff --git a/cmd/iriscli/lcd_test.go b/cmd/iriscli/lcd_test.go index 71eb6d87b..cb5351f96 100644 --- a/cmd/iriscli/lcd_test.go +++ b/cmd/iriscli/lcd_test.go @@ -31,10 +31,15 @@ func TestRestServer(t *testing.T) { func TestMetricsCmd(t *testing.T){ cdc := app.MakeCodec() comm := prometheus.MonitorCommand("stake",cdc) - viper.Set("node","tcp://0.0.0.0:46657") + viper.Set("node","tcp://0.0.0.0:26657") viper.Set("chain-id","fuxi") - viper.Set("commands","iris start;htop") - viper.Set("paths","/etc ") + viper.Set("commands","iris start ;htop") + /* + viper.Set("paths","/etc ;/home/") + viper.Set("recursively", false) + */ + viper.Set("paths","/etc ;/home/lmf/GoPath/src/github.com/programokey/irishub/") + viper.Set("recursively", true) comm.ExecuteC() } diff --git a/tools/prometheus/provider.go b/tools/prometheus/provider.go index 68d580d8f..4ac996530 100644 --- a/tools/prometheus/provider.go +++ b/tools/prometheus/provider.go @@ -3,7 +3,7 @@ package prometheus import ( "github.com/irisnet/irishub/tools/prometheus/p2p" cs "github.com/irisnet/irishub/tools/prometheus/consensus" - sys "github.com/programokey/irishub/tools/prometheus/system" + sys "github.com/irisnet/irishub/tools/prometheus/system" mempl "github.com/irisnet/irishub/tools/prometheus/mempool" ) diff --git a/tools/prometheus/server.go b/tools/prometheus/server.go index d741bd9a6..449821259 100644 --- a/tools/prometheus/server.go +++ b/tools/prometheus/server.go @@ -9,7 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/wire" "github.com/spf13/viper" "strings" - "fmt" "github.com/irisnet/irishub/tools" ) @@ -32,21 +31,29 @@ func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { paths := viper.GetString("paths") commands := viper.GetString("commands") + disks := viper.GetString("disks") for _, command := range strings.Split(commands, ";"){ if strings.TrimSpace(command) != ""{ - fmt.Println("command:", strings.TrimSpace(command)) sysMetrics.AddProcess(strings.TrimSpace(command)) } } + for _, disk_path := range strings.Split(disks, ";"){ + if strings.TrimSpace(disk_path) != ""{ + sysMetrics.AddDisk(strings.TrimSpace(disk_path)) + } + } + for _, path := range strings.Split(paths, ";"){ if strings.TrimSpace(path) != ""{ - fmt.Println("path:", strings.TrimSpace(path)) - sysMetrics.AddDirectory(strings.TrimSpace(path)) + sysMetrics.AddPath(strings.TrimSpace(path)) } } + recursively := viper.GetBool("recursively") + sysMetrics.SetRecursively(recursively) + sysMetrics.Monitor() srv := &http.Server{ @@ -72,7 +79,12 @@ func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { cmd.Flags().StringP("commands", "c", "iris start", `the processes you want to monitor that started by these commands, separated by semicolons ';'. eg: --commands="command 0;command 1;command 2", --commands=iris by default`) - cmd.Flags().StringP("paths", "p", "/", `directories for config and data, separated by semicolons ';'. -eg: --paths="/;/mnt1;/mnt2"`) + cmd.Flags().StringP("disks", "d", "/", `mounted paths of storage devices, separated by semicolons ';'. +eg: --disks="/;/mnt1;/mnt2"`) + cmd.Flags().StringP("paths", "p", "", `path to config and data files/directories, separated by semicolons ';'. +cannot use ~ and environment variables. eg: --paths="/etc;/home; +size of files in sub-directories is excluded. to compute the size recursively, you can use --recursively=true"`) + cmd.Flags().BoolP("recursively", "r", false, `specify whether the files in sub-directories is included, +excluded by default. If there are many files & sub-directory in given directories, this program may be very slow!`) return cmd } diff --git a/tools/prometheus/system/metrics.go b/tools/prometheus/system/metrics.go index 554c7ff05..26f5dfc98 100644 --- a/tools/prometheus/system/metrics.go +++ b/tools/prometheus/system/metrics.go @@ -6,39 +6,119 @@ import ( "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/prometheus" stdprometheus "github.com/prometheus/client_golang/prometheus" + "github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/disk" + "github.com/shirou/gopsutil/mem" "github.com/shirou/gopsutil/process" "io/ioutil" + "os" "os/exec" "strconv" "strings" "time" - "github.com/shirou/gopsutil/mem" - "github.com/shirou/gopsutil/cpu" + "container/list" + "bytes" + "unicode" ) type Metrics struct { CPUUtilization metrics.Gauge MemoUtilization metrics.Gauge + //processes related monitor term ProcCPUUtilization []metrics.Gauge ProcMemoUtilization []metrics.Gauge ProcOpenedFilesNum []metrics.Gauge - processes []process.Process + processes []process.Process + + //storage related monitor term + DiskUsedPercentage []metrics.Gauge + DiskFreeSpace []metrics.Gauge + disks []string + //file related monitor term + FileSize []metrics.Gauge + filePaths []string + recursively bool //whether compute directories size recursively DirectorySize []metrics.Gauge - dirPaths []string + dirPaths []string } -func (metrics *Metrics) AddDirectory(path string) { - metrics.dirPaths = append(metrics.dirPaths, path) - name := fmt.Sprintf("Direcotry_Size_%s", strings.Replace(path, "/", "_", -1)) - help := fmt.Sprintf("total Size of files in %s", path) - metrics.DirectorySize = append(metrics.DirectorySize, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ +// PrometheusMetrics returns Metrics build using Prometheus client library. +func PrometheusMetrics() *Metrics { + return &Metrics{ + CPUUtilization: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: "CPU_Percent", + Help: "CPU Utilization Percantage", + }, []string{}), + MemoUtilization: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: "Memo_Percent", + Help: "Memo Utilization Percantage", + }, []string{}), + ProcCPUUtilization: make([]metrics.Gauge, 0), + ProcMemoUtilization: make([]metrics.Gauge, 0), + ProcOpenedFilesNum: make([]metrics.Gauge, 0), + DiskUsedPercentage: make([]metrics.Gauge, 0), + DiskFreeSpace: make([]metrics.Gauge, 0), + FileSize: make([]metrics.Gauge, 0), + DirectorySize: make([]metrics.Gauge, 0), + processes: make([]process.Process, 0), + recursively: false, + disks: make([]string, 0), + filePaths: make([]string, 0), + dirPaths: make([]string, 0), + } +} + +func (metrics *Metrics) AddDisk(disk_path string) { + metrics.disks = append(metrics.disks, disk_path) + + name := fmt.Sprintf("Disk_Used_Percentage_%s", get_path_name(disk_path)) + help := fmt.Sprintf("Used Percentage of disk mount on path: %s", disk_path) + metrics.DiskUsedPercentage = append(metrics.DiskUsedPercentage, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", Name: name, Help: help, }, []string{})) + + name = fmt.Sprintf("Disk_Free_Space_%s", get_path_name(disk_path)) + help = fmt.Sprintf("Free space of disk mount on path: %s", disk_path) + metrics.DiskFreeSpace = append(metrics.DiskFreeSpace, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: name, + Help: help, + }, []string{})) + +} + +func (metrics *Metrics) AddPath(path string) { + if fileInfo, err := os.Stat(path); err != nil { + fmt.Println(err.Error()) + return + } else { + if fileInfo.IsDir() { + metrics.dirPaths = append(metrics.dirPaths, path) + name := fmt.Sprintf("Direcotry_Size_%s", get_path_name(path)) + //name := fmt.Sprintf("Direcotry_Size_%s", strings.Replace(path, "/", "_", -1)) + help := fmt.Sprintf("total Size of files in %s", path) + metrics.DirectorySize = append(metrics.DirectorySize, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: name, + Help: help, + }, []string{})) + } else { + metrics.filePaths = append(metrics.filePaths, path) + name := fmt.Sprintf("File_Size_%s", get_path_name(path)) + help := fmt.Sprintf("size of files: %s", path) + metrics.FileSize = append(metrics.FileSize, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: name, + Help: help, + }, []string{})) + } + } } func (metrics *Metrics) AddProcess(command string) { @@ -47,47 +127,35 @@ func (metrics *Metrics) AddProcess(command string) { return } process := process.Process{Pid: int32(pid)} + cmd, err := process.Cmdline() + if err != nil { + fmt.Println(err.Error()) + return + } metrics.processes = append(metrics.processes, process) metrics.ProcCPUUtilization = append(metrics.ProcCPUUtilization, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", Name: fmt.Sprintf("CPU_Percent_%d", pid), - Help: fmt.Sprintf("CPU Utilization Percantage of processes with pid %d", pid), + Help: fmt.Sprintf("CPU Utilization Percantage of processes with pid %d, started by command %s", pid, cmd), }, []string{})) metrics.ProcMemoUtilization = append(metrics.ProcMemoUtilization, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", Name: fmt.Sprintf("Memo_Percent_%d", pid), - Help: fmt.Sprintf("Memory Utilization Percantage of processes with pid %d", pid), + Help: fmt.Sprintf("Memory Utilization Percantage of processes with pid %d, started by command %s", pid, cmd), }, []string{})) metrics.ProcOpenedFilesNum = append(metrics.ProcOpenedFilesNum, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", Name: fmt.Sprintf("Opened_Files_Number_%d", pid), - Help: fmt.Sprintf("Number of Opened Files of processes with pid %d", pid), + Help: fmt.Sprintf("Number of Opened Files of processes with pid %d, started by command %s", pid, cmd), }, []string{})) } -// PrometheusMetrics returns Metrics build using Prometheus client library. -func PrometheusMetrics() *Metrics { - return &Metrics{ - CPUUtilization: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "system", - Name: "CPU_Percent", - Help: "CPU Utilization Percantage", - }, []string{}), - MemoUtilization: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "system", - Name: "Memo_Percent", - Help: "Memo Utilization Percantage", - }, []string{}), - ProcCPUUtilization: make([]metrics.Gauge, 0), - ProcMemoUtilization: make([]metrics.Gauge, 0), - ProcOpenedFilesNum: make([]metrics.Gauge, 0), - dirPaths: make([]string, 0), - processes: make([]process.Process, 0), - } +func (metrics *Metrics)SetRecursively(recursively bool) { + metrics.recursively = recursively } func (metrics *Metrics) Monitor() error { @@ -102,7 +170,7 @@ func (metrics *Metrics) Monitor() error { func (metrics Metrics) RecordMetrics() { - for i, process := range(metrics.processes){ + for i, process := range metrics.processes { if cpu_util, err := process.CPUPercent(); err != nil { metrics.ProcCPUUtilization[i].Set(float64(-1)) } else { @@ -122,24 +190,45 @@ func (metrics Metrics) RecordMetrics() { } } - for i, dir_path := range (metrics.dirPaths){ - if usage, err := disk.Usage(dir_path); err != nil { + for i, disk_path := range metrics.disks { + if usage, err := disk.Usage(disk_path); err != nil { metrics.DirectorySize[i].Set(float64(-1)) + metrics.DiskFreeSpace[i].Set(float64(-1)) } else { - metrics.DirectorySize[i].Set(float64(usage.Used)) + metrics.DirectorySize[i].Set(usage.UsedPercent) + metrics.DiskFreeSpace[i].Set(float64(usage.Free)) } } + + for i, file_path := range metrics.filePaths { + if fileInfo, err := os.Stat(file_path); err != nil { + metrics.FileSize[i].Set(float64(-1)) + } else { + metrics.FileSize[i].Set(float64(fileInfo.Size())) + } + } + + for i, dir_path := range metrics.dirPaths { + if size, err := get_dir_size(dir_path, metrics.recursively); err != nil { + metrics.DirectorySize[i].Set(float64(-1)) + } else { + metrics.DirectorySize[i].Set(float64(size)) + } + } + vMemoStat, _ := mem.VirtualMemory() metrics.MemoUtilization.Set(vMemoStat.UsedPercent) CPUUsedPercent := float64(0.0) percents, _ := cpu.Percent(time.Millisecond*100, false) - for _, percent := range (percents){ + for _, percent := range percents { CPUUsedPercent += percent } - metrics.CPUUtilization.Set(CPUUsedPercent/4) + metrics.CPUUtilization.Set(CPUUsedPercent / 4) } +//-----------------help functions------------------------------- + //get the pid of process that start by the given command //the first pid return by "ps -aux|grep ", // the process whose command contains "grep" is omitted @@ -180,3 +269,45 @@ func getPid(command string) (pid int, err error) { } return 0, errors.New("cannot find the process") } + +//get directory size of given path +func get_dir_size(dir_path string, recursively bool) (int64, error) { + Separator := string(os.PathSeparator) + queue := list.New() + queue.PushBack(dir_path) + size := int64(0) + for ;queue.Len() > 0;{ + path := fmt.Sprint(queue.Front().Value) + queue.Remove(queue.Front()) + + files, err := ioutil.ReadDir(path) + if err != nil { + return 0, err + } + for _, file := range files { + file_size := file.Size() + size += file_size + if file.IsDir() && recursively{ + queue.PushBack(path + Separator + file.Name()) + } + } + } + return size, nil +} + +//conver a path to a valid Gauge monitor term name +func get_path_name(path string)(path_name string){ + var buffer bytes.Buffer + + for i, ch := range path{ + if i == 0 && unicode.IsDigit(ch){ + buffer.WriteString("_") + } + if unicode.IsDigit(ch) || unicode.IsLetter(ch){ + buffer.WriteByte(byte(ch)) + }else { + buffer.WriteByte(byte('_')) + } + } + return buffer.String() +} \ No newline at end of file From adaa8d1bbd77f98d54a3bdd67807747f98180dae Mon Sep 17 00:00:00 2001 From: programokey <872127164@qq.com> Date: Mon, 9 Jul 2018 02:40:40 -0700 Subject: [PATCH 054/124] IRISHUB-32 add monitor terms of disk usage --- cmd/iriscli/lcd_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/iriscli/lcd_test.go b/cmd/iriscli/lcd_test.go index cb5351f96..9bb689f38 100644 --- a/cmd/iriscli/lcd_test.go +++ b/cmd/iriscli/lcd_test.go @@ -38,7 +38,7 @@ func TestMetricsCmd(t *testing.T){ viper.Set("paths","/etc ;/home/") viper.Set("recursively", false) */ - viper.Set("paths","/etc ;/home/lmf/GoPath/src/github.com/programokey/irishub/") + viper.Set("paths","/etc ;") viper.Set("recursively", true) comm.ExecuteC() } From f598c1a45affaaf1fdd1e83ca5200d29fd5008d4 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Mon, 9 Jul 2018 18:09:26 +0800 Subject: [PATCH 055/124] =?UTF-8?q?IRISHUB-34=EF=BC=9Airishub=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0prometheus=E7=9B=91=E6=8E=A7=E6=8C=87=E6=A0=87:consens?= =?UTF-8?q?us=5Fcandidates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/prometheus/consensus/metrics.go | 48 +++++++++++++++------------ 1 file changed, 27 insertions(+), 21 deletions(-) diff --git a/tools/prometheus/consensus/metrics.go b/tools/prometheus/consensus/metrics.go index e8250e1b2..3e1f860ad 100644 --- a/tools/prometheus/consensus/metrics.go +++ b/tools/prometheus/consensus/metrics.go @@ -26,6 +26,8 @@ type Metrics struct { // Number of validators. Validators metrics.Gauge + // Number of Candidates + Candidates metrics.Gauge // Total power of all validators. ValidatorsPower metrics.Gauge // Number of validators who did not sign. @@ -67,6 +69,13 @@ func PrometheusMetrics() *Metrics { Name: "validators", Help: "Number of validators.", }, []string{}), + + Candidates: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "candidates", + Help: "Number of Candidates.", + }, []string{}), + ValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "consensus", Name: "validators_power", @@ -141,16 +150,19 @@ func (cs *Metrics)Monitor(ctx tools.Context,cdc *wire.Codec,storeName string){ }() } -func (cs Metrics) RecordMetrics(ctx tools.Context,cdc *wire.Codec,block *types.Block,storeName string) { +func (cs *Metrics) RecordMetrics(ctx tools.Context,cdc *wire.Codec,block *types.Block,storeName string){ cs.Height.Set(float64(block.Height)) cs.ByzantineValidators.Set(float64(len(block.Evidence.Evidence))) missingValidators := 0 missingValidatorsPower := int64(0) validatorsPower := int64(0) - validators := getValidators(cdc,ctx,storeName) - - valMap := make(map[string]stake.Validator,len(validators)) + resultValidators,err := ctx.Client.Validators(&block.Height) + if err != nil { + panic(err) + } + validators := resultValidators.Validators + valMap := make(map[string]types.Validator,len(validators)) for i, val := range validators { var vote *types.Vote if i < len(block.LastCommit.Precommits) { @@ -158,22 +170,23 @@ func (cs Metrics) RecordMetrics(ctx tools.Context,cdc *wire.Codec,block *types.B } if vote == nil { missingValidators++ - missingValidatorsPower += val.GetPower().Evaluate() + missingValidatorsPower += val.VotingPower } - valMap[val.Owner.String()] = val - validatorsPower += val.GetPower().Evaluate() + valMap[val.Address.String()] = *val + validatorsPower += val.VotingPower } - + cs.Candidates.Set(float64(getCandidatesNum(cdc,ctx,storeName))) cs.MissingValidators.Set(float64(missingValidators)) cs.MissingValidatorsPower.Set(float64(missingValidatorsPower)) cs.ValidatorsPower.Set(float64(validatorsPower)) + cs.Validators.Set(float64(len(validators))) byzantineValidatorsPower := int64(0) for _, ev := range block.Evidence.Evidence { addr := strings.ToUpper(hex.EncodeToString(ev.Address())) if val,ok := valMap[addr]; ok { - byzantineValidatorsPower += val.GetPower().Evaluate() + byzantineValidatorsPower += val.VotingPower } } cs.ByzantineValidatorsPower.Set(float64(byzantineValidatorsPower)) @@ -181,9 +194,8 @@ func (cs Metrics) RecordMetrics(ctx tools.Context,cdc *wire.Codec,block *types.B if block.Height > 1 { lastBlockHight := block.Height -1 lastBlock,_ := ctx.Client.Block(&lastBlockHight) - cs.BlockIntervalSeconds.Observe( - block.Time.Sub(lastBlock.BlockMeta.Header.Time).Seconds(), - ) + interval := block.Time.Sub(lastBlock.BlockMeta.Header.Time).Seconds() + cs.BlockIntervalSeconds.Observe(interval,) } cs.NumTxs.Set(float64(block.NumTxs)) @@ -194,17 +206,11 @@ func (cs Metrics) RecordMetrics(ctx tools.Context,cdc *wire.Codec,block *types.B } -func getValidators(cdc *wire.Codec,ctx tools.Context,storeName string) (validators []stake.Validator){ +func getCandidatesNum(cdc *wire.Codec,ctx tools.Context,storeName string) (int){ key := stake.ValidatorsKey resKVs, err := ctx.QuerySubspace(cdc, key, storeName) if err != nil { fmt.Println(err) } - - for _, KV := range resKVs { - var validator stake.Validator - cdc.MustUnmarshalBinary(KV.Value, &validator) - validators = append(validators, validator) - } - return validators -} \ No newline at end of file + return len(resKVs) +} From d1c241cb881674f1ed87f1321a49e2b94bca6dce Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Tue, 10 Jul 2018 09:43:15 +0800 Subject: [PATCH 056/124] Code optimization --- app/app.go | 2 +- app/context.go | 2 +- app/genesis.go | 13 +- cmd/iris/main.go | 10 +- cmd/iriscli/lcd.go | 4 +- cmd/iriscli/lcd_test.go | 167 +++++++++++++------------- cmd/iriscli/main.go | 2 +- cmd/iriscli/offline_sign.go | 77 ++++++------ tools/context.go | 35 +++--- tools/prometheus/consensus/metrics.go | 37 +++--- tools/prometheus/mempool/metrics.go | 6 +- tools/prometheus/p2p/metrics.go | 4 +- tools/prometheus/provider.go | 6 +- tools/prometheus/server.go | 52 ++------ tools/prometheus/system/metrics.go | 113 ++++++++++------- 15 files changed, 261 insertions(+), 269 deletions(-) diff --git a/app/app.go b/app/app.go index d88c2ce88..c5072a53c 100644 --- a/app/app.go +++ b/app/app.go @@ -178,4 +178,4 @@ func (app *IrisApp) ExportAppStateAndValidators() (appState json.RawMessage, val } validators = stake.WriteValidators(ctx, app.stakeKeeper) return appState, validators, nil -} \ No newline at end of file +} diff --git a/app/context.go b/app/context.go index 3b9b10fc8..e53eee28d 100644 --- a/app/context.go +++ b/app/context.go @@ -17,7 +17,7 @@ func (c Context) BroadcastTxSync(tx []byte) (*ctypes.ResultBroadcastTx, error) { return c.ctx.Client.BroadcastTxSync(tx) } -func (c Context) GetCosmosCtx() (context.CoreContext) { +func (c Context) GetCosmosCtx() context.CoreContext { return c.ctx } diff --git a/app/genesis.go b/app/genesis.go index e19b6ca87..924cfdebc 100644 --- a/app/genesis.go +++ b/app/genesis.go @@ -56,11 +56,10 @@ var ( flagOWK = "owk" denom = "iris" - // bonded tokens given to genesis validators/accounts - freeFermionVal = int64(100) + freeFermionVal = int64(100) - totalTokenAmt = int64(200000000) + totalTokenAmt = int64(200000000) ) // get app init parameters for server init command @@ -111,7 +110,7 @@ func IrisAppGenTx(cdc *wire.Codec, pk crypto.PubKey) ( return } cliPrint = json.RawMessage(bz) - appGenTx,_,validator,err = IrisAppGenTxNF(cdc, pk, addr, name, overwrite) + appGenTx, _, validator, err = IrisAppGenTxNF(cdc, pk, addr, name, overwrite) return } @@ -205,9 +204,9 @@ func IrisAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState } // TODO -func createGenesisState() stake.GenesisState{ +func createGenesisState() stake.GenesisState { return stake.GenesisState{ - Pool: stake.Pool{ + Pool: stake.Pool{ LooseUnbondedTokens: 0, BondedTokens: 0, UnbondingTokens: 0, @@ -229,4 +228,4 @@ func createGenesisState() stake.GenesisState{ BondDenom: "steak", }, } -} \ No newline at end of file +} diff --git a/cmd/iris/main.go b/cmd/iris/main.go index 0835f8f5d..acba3c88b 100644 --- a/cmd/iris/main.go +++ b/cmd/iris/main.go @@ -5,15 +5,15 @@ import ( "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/server" + "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/version" abci "github.com/tendermint/abci/types" tmtypes "github.com/tendermint/tendermint/types" "github.com/tendermint/tmlibs/cli" dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/tmlibs/log" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/server" - "github.com/irisnet/irishub/app" - "github.com/irisnet/irishub/version" ) func main() { @@ -61,4 +61,4 @@ func newApp(logger log.Logger, db dbm.DB) abci.Application { func exportAppStateAndTMValidators(logger log.Logger, db dbm.DB) (json.RawMessage, []tmtypes.GenesisValidator, error) { irisApp := app.NewIrisApp(logger, db) return irisApp.ExportAppStateAndValidators() -} \ No newline at end of file +} diff --git a/cmd/iriscli/lcd.go b/cmd/iriscli/lcd.go index d90b0b360..49f99f2c2 100644 --- a/cmd/iriscli/lcd.go +++ b/cmd/iriscli/lcd.go @@ -16,13 +16,13 @@ import ( "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/rpc" "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/irisnet/irishub/version" "github.com/cosmos/cosmos-sdk/wire" auth "github.com/cosmos/cosmos-sdk/x/auth/client/rest" bank "github.com/cosmos/cosmos-sdk/x/bank/client/rest" ibc "github.com/cosmos/cosmos-sdk/x/ibc/client/rest" stake "github.com/cosmos/cosmos-sdk/x/stake/client/rest" "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/version" ) // ServeCommand will generate a long-running rest server @@ -80,6 +80,6 @@ func createHandler(cdc *wire.Codec) http.Handler { bank.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, kb) ibc.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, kb) stake.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, kb) - RegisterRoutes(ctx,r,cdc,kb) + RegisterRoutes(ctx, r, cdc, kb) return r } diff --git a/cmd/iriscli/lcd_test.go b/cmd/iriscli/lcd_test.go index 9bb689f38..28253d15f 100644 --- a/cmd/iriscli/lcd_test.go +++ b/cmd/iriscli/lcd_test.go @@ -1,44 +1,45 @@ package main -import ("testing" - "github.com/irisnet/irishub/app" - "github.com/spf13/viper" +import ( + "bytes" + "encoding/hex" + "encoding/json" "fmt" - "github.com/tendermint/go-amino" - "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/types" - "encoding/json" - "github.com/magiconair/properties/assert" "github.com/cosmos/cosmos-sdk/x/auth" - "bytes" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/tools/prometheus" + "github.com/magiconair/properties/assert" + "github.com/spf13/viper" + "github.com/tendermint/go-amino" "log" "os" - "encoding/hex" - "github.com/irisnet/irishub/tools/prometheus" + "testing" ) - func TestRestServer(t *testing.T) { cdc := app.MakeCodec() comm := ServeCommand(cdc) - viper.Set("chain-id","fuxi") - viper.Set("node","tcp://localhost:26657") - viper.Set("laddr","tcp://localhost:1317") + viper.Set("chain-id", "fuxi") + viper.Set("node", "tcp://localhost:26657") + viper.Set("laddr", "tcp://localhost:1317") comm.ExecuteC() } -func TestMetricsCmd(t *testing.T){ +func TestMetricsCmd(t *testing.T) { cdc := app.MakeCodec() - comm := prometheus.MonitorCommand("stake",cdc) - viper.Set("node","tcp://0.0.0.0:26657") - viper.Set("chain-id","fuxi") - viper.Set("commands","iris start ;htop") + comm := prometheus.MonitorCommand("stake", cdc) + viper.Set("node", "tcp://0.0.0.0:46657") + viper.Set("chain-id", "fuxi") + viper.Set("commands", "iris start ;htop") /* - viper.Set("paths","/etc ;/home/") - viper.Set("recursively", false) - */ - viper.Set("paths","/etc ;") + viper.Set("paths","/etc ;/home/") + viper.Set("recursively", false) + */ + viper.Set("paths", "/Users/zhangzhiqiang/.iris") + viper.Set("disks", "/") viper.Set("recursively", true) comm.ExecuteC() } @@ -52,80 +53,80 @@ func TestAmino(t *testing.T) { } p := Person{ - Name :"zhangsn", - Age:18, + Name: "zhangsn", + Age: 18, } - bz,_ := cdc.MarshalJSON(p) + bz, _ := cdc.MarshalJSON(p) fmt.Println(bz) var p1 Person - if err := cdc.UnmarshalJSON(bz,&p1);err != nil { + if err := cdc.UnmarshalJSON(bz, &p1); err != nil { fmt.Println(err) return } //cdc.MustUnmarshalBinaryBare(bz,p1) - fmt.Printf("%+v",p1) + fmt.Printf("%+v", p1) } func TestMarshalJson(t *testing.T) { - add,_ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") + add, _ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") conis := types.Coins{ types.Coin{ - Denom:"iris", - Amount:10, + Denom: "iris", + Amount: 10, }, } //fmt.Println(types.MustBech32ifyAcc(add)) input := bank.Input{ - Address:add, - Coins:conis, + Address: add, + Coins: conis, } input1Byte := input.GetSignBytes() fmt.Println(input1Byte) - input2Byte,_ := json.Marshal(struct { - Address string `json:"address"` + input2Byte, _ := json.Marshal(struct { + Address string `json:"address"` Coins types.Coins `json:"coins"` }{ Address: types.MustBech32ifyAcc(add), Coins: conis, }) - assert.Equal(t,input1Byte,input2Byte) + assert.Equal(t, input1Byte, input2Byte) } func TestMarshal(t *testing.T) { - add,_ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") + add, _ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") conis := types.Coins{ types.Coin{ - Denom:"iris", - Amount:10, + Denom: "iris", + Amount: 10, }, } //fmt.Println(types.MustBech32ifyAcc(add)) input := bank.Input{ - Address:add, - Coins:conis, + Address: add, + Coins: conis, } input1Byte := input.GetSignBytes() - input2Byte,_ := json.Marshal(struct { - Address string `json:"address"` + input2Byte, _ := json.Marshal(struct { + Address string `json:"address"` Coins types.Coins `json:"coins"` }{ Address: types.MustBech32ifyAcc(add), Coins: conis, }) - assert.Equal(t,input1Byte,input2Byte) + assert.Equal(t, input1Byte, input2Byte) } func TestSignByte(t *testing.T) { - from,_ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") + from, _ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") chainID := "fuxi" accnums := []int64{0} @@ -133,52 +134,52 @@ func TestSignByte(t *testing.T) { conis := types.Coins{ types.Coin{ - Denom:"iris", - Amount:10, + Denom: "iris", + Amount: 10, }, } fees := types.Coins{ types.Coin{ - Denom:"iris", - Amount:0, + Denom: "iris", + Amount: 0, }, } type put struct { - Address string `json:"address"` + Address string `json:"address"` Coins types.Coins `json:"coins"` } input := bank.Input{ - Address:from, - Coins:conis, + Address: from, + Coins: conis, } input1 := input.GetSignBytes() - input2,_ := json.Marshal(put{ + input2, _ := json.Marshal(put{ Address: types.MustBech32ifyAcc(from), Coins: conis, }) - assert.Equal(t,input1,input2) + assert.Equal(t, input1, input2) - to,_ := types.GetAccAddressHex("3A058A8B5468AE0EA2D2517CE3BAFDD281E50C2F") + to, _ := types.GetAccAddressHex("3A058A8B5468AE0EA2D2517CE3BAFDD281E50C2F") output := bank.Output{ - Address:to, - Coins:conis, + Address: to, + Coins: conis, } output1 := output.GetSignBytes() - output2,_ := json.Marshal(put{ + output2, _ := json.Marshal(put{ Address: types.MustBech32ifyAcc(to), Coins: conis, }) - assert.Equal(t,output1,output2) + assert.Equal(t, output1, output2) msg := bank.MsgSend{ - []bank.Input{input},[]bank.Output{output}, + []bank.Input{input}, []bank.Output{output}, } msg1 := msg.GetSignBytes() @@ -191,7 +192,7 @@ func TestSignByte(t *testing.T) { outputs = append(outputs, output.GetSignBytes()) } - msg2,_ := json.Marshal(struct { + msg2, _ := json.Marshal(struct { Inputs []json.RawMessage `json:"inputs"` Outputs []json.RawMessage `json:"outputs"` }{ @@ -199,34 +200,34 @@ func TestSignByte(t *testing.T) { Outputs: outputs, }) //fmt.Print(msg2) - assert.Equal(t,msg1,msg2) + assert.Equal(t, msg1, msg2) fee := auth.StdFee{ - Amount:fees, - Gas:int64(0), + Amount: fees, + Gas: int64(0), } fee1 := fee.Bytes() - fee2,_:= json.Marshal(struct { + fee2, _ := json.Marshal(struct { Amount types.Coins `json:"amount"` Gas int64 `json:"gas"` }{ - Amount:fees, - Gas:int64(0), + Amount: fees, + Gas: int64(0), }) - assert.Equal(t,fee1,fee2) + assert.Equal(t, fee1, fee2) signMsg := auth.StdSignMsg{ - ChainID:chainID, - AccountNumbers:accnums, - Sequences:sequences, - Msg:msg, - Fee:fee, + ChainID: chainID, + AccountNumbers: accnums, + Sequences: sequences, + Msg: msg, + Fee: fee, } signByte1 := signMsg.Bytes() - signByte2,_ := json.Marshal(auth.StdSignDoc{ + signByte2, _ := json.Marshal(auth.StdSignDoc{ ChainID: chainID, AccountNumbers: accnums, Sequences: sequences, @@ -240,13 +241,13 @@ func TestSignByte(t *testing.T) { //printJson(signByte2) - assert.Equal(t,signByte1,signByte2) + assert.Equal(t, signByte1, signByte2) fmt.Println(signByte1) } -func printJson(b []byte) { +func printJson(b []byte) { var out bytes.Buffer err := json.Indent(&out, b, "", "\t") @@ -257,23 +258,19 @@ func printJson(b []byte) { out.WriteTo(os.Stdout) } -func TestH(t *testing.T){ - client := []byte{123,34,99,104,97,105,110,95,105,100,34,58,34,102,117,120,105,34,44,34,97,99,99,111,117,110,116,95,110,117,109,98,101,114,115,34,58,91,48,93,44,34,115,101,113,117,101,110,99,101,115,34,58,91,51,93,44,34,102,101,101,95,98,121,116,101,115,34,58,34,101,121,74,104,98,87,57,49,98,110,81,105,79,108,116,55,73,109,70,116,98,51,86,117,100,67,73,54,77,67,119,105,90,71,86,117,98,50,48,105,79,105,74,112,99,109,108,122,73,110,49,100,76,67,74,110,89,88,77,105,79,106,66,57,34,44,34,109,115,103,95,98,121,116,101,115,34,58,34,101,121,74,112,98,110,66,49,100,72,77,105,79,108,116,55,73,109,70,107,90,72,74,108,99,51,77,105,79,105,74,106,98,51,78,116,98,51,78,104,89,50,78,104,90,71,82,121,77,88,74,116,99,72,100,122,89,51,73,53,78,109,104,111,89,122,78,110,98,71,82,50,97,51,86,48,79,71,90,119,97,110,112,121,89,87,82,117,77,50,70,113,100,110,74,116,98,71,100,107,73,105,119,105,89,50,57,112,98,110,77,105,79,108,116,55,73,109,70,116,98,51,86,117,100,67,73,54,77,84,65,115,73,109,82,108,98,109,57,116,73,106,111,105,97,88,74,112,99,121,74,57,88,88,49,100,76,67,74,118,100,88,82,119,100,88,82,122,73,106,112,98,101,121,74,104,90,71,82,121,90,88,78,122,73,106,111,105,89,50,57,122,98,87,57,122,89,87,78,106,89,87,82,107,99,106,69,52,90,51,112,106,78,72,111,50,78,87,82,54,97,72,70,104,90,50,116,113,77,106,107,51,100,122,104,51,97,71,69,50,77,110,69,51,77,110,74,119,77,72,100,108,101,87,53,48,79,67,73,115,73,109,78,118,97,87,53,122,73,106,112,98,101,121,74,104,98,87,57,49,98,110,81,105,79,106,69,119,76,67,74,107,90,87,53,118,98,83,73,54,73,109,108,121,97,88,77,105,102,86,49,57,88,88,48,61,34,44,34,97,108,116,95,98,121,116,101,115,34,58,110,117,108,108,125} +func TestH(t *testing.T) { + client := []byte{123, 34, 99, 104, 97, 105, 110, 95, 105, 100, 34, 58, 34, 102, 117, 120, 105, 34, 44, 34, 97, 99, 99, 111, 117, 110, 116, 95, 110, 117, 109, 98, 101, 114, 115, 34, 58, 91, 48, 93, 44, 34, 115, 101, 113, 117, 101, 110, 99, 101, 115, 34, 58, 91, 51, 93, 44, 34, 102, 101, 101, 95, 98, 121, 116, 101, 115, 34, 58, 34, 101, 121, 74, 104, 98, 87, 57, 49, 98, 110, 81, 105, 79, 108, 116, 55, 73, 109, 70, 116, 98, 51, 86, 117, 100, 67, 73, 54, 77, 67, 119, 105, 90, 71, 86, 117, 98, 50, 48, 105, 79, 105, 74, 112, 99, 109, 108, 122, 73, 110, 49, 100, 76, 67, 74, 110, 89, 88, 77, 105, 79, 106, 66, 57, 34, 44, 34, 109, 115, 103, 95, 98, 121, 116, 101, 115, 34, 58, 34, 101, 121, 74, 112, 98, 110, 66, 49, 100, 72, 77, 105, 79, 108, 116, 55, 73, 109, 70, 107, 90, 72, 74, 108, 99, 51, 77, 105, 79, 105, 74, 106, 98, 51, 78, 116, 98, 51, 78, 104, 89, 50, 78, 104, 90, 71, 82, 121, 77, 88, 74, 116, 99, 72, 100, 122, 89, 51, 73, 53, 78, 109, 104, 111, 89, 122, 78, 110, 98, 71, 82, 50, 97, 51, 86, 48, 79, 71, 90, 119, 97, 110, 112, 121, 89, 87, 82, 117, 77, 50, 70, 113, 100, 110, 74, 116, 98, 71, 100, 107, 73, 105, 119, 105, 89, 50, 57, 112, 98, 110, 77, 105, 79, 108, 116, 55, 73, 109, 70, 116, 98, 51, 86, 117, 100, 67, 73, 54, 77, 84, 65, 115, 73, 109, 82, 108, 98, 109, 57, 116, 73, 106, 111, 105, 97, 88, 74, 112, 99, 121, 74, 57, 88, 88, 49, 100, 76, 67, 74, 118, 100, 88, 82, 119, 100, 88, 82, 122, 73, 106, 112, 98, 101, 121, 74, 104, 90, 71, 82, 121, 90, 88, 78, 122, 73, 106, 111, 105, 89, 50, 57, 122, 98, 87, 57, 122, 89, 87, 78, 106, 89, 87, 82, 107, 99, 106, 69, 52, 90, 51, 112, 106, 78, 72, 111, 50, 78, 87, 82, 54, 97, 72, 70, 104, 90, 50, 116, 113, 77, 106, 107, 51, 100, 122, 104, 51, 97, 71, 69, 50, 77, 110, 69, 51, 77, 110, 74, 119, 77, 72, 100, 108, 101, 87, 53, 48, 79, 67, 73, 115, 73, 109, 78, 118, 97, 87, 53, 122, 73, 106, 112, 98, 101, 121, 74, 104, 98, 87, 57, 49, 98, 110, 81, 105, 79, 106, 69, 119, 76, 67, 74, 107, 90, 87, 53, 118, 98, 83, 73, 54, 73, 109, 108, 121, 97, 88, 77, 105, 102, 86, 49, 57, 88, 88, 48, 61, 34, 44, 34, 97, 108, 116, 95, 98, 121, 116, 101, 115, 34, 58, 110, 117, 108, 108, 125} clientS := string(client) //fmt.Println(str1) fmt.Println(clientS) - server := []byte{123,34,99,104,97,105,110,95,105,100,34,58,34,102,117,120,105,34,44,34,97,99,99,111,117,110,116,95,110,117,109,98,101,114,115,34,58,91,48,93,44,34,115,101,113,117,101,110,99,101,115,34,58,91,51,93,44,34,102,101,101,95,98,121,116,101,115,34,58,34,101,121,74,104,98,87,57,49,98,110,81,105,79,108,116,55,73,109,82,108,98,109,57,116,73,106,111,105,97,88,74,112,99,121,73,115,73,109,70,116,98,51,86,117,100,67,73,54,77,72,49,100,76,67,74,110,89,88,77,105,79,106,66,57,34,44,34,109,115,103,95,98,121,116,101,115,34,58,34,101,121,74,112,98,110,66,49,100,72,77,105,79,108,116,55,73,109,70,107,90,72,74,108,99,51,77,105,79,105,74,106,98,51,78,116,98,51,78,104,89,50,78,104,90,71,82,121,77,88,74,116,99,72,100,122,89,51,73,53,78,109,104,111,89,122,78,110,98,71,82,50,97,51,86,48,79,71,90,119,97,110,112,121,89,87,82,117,77,50,70,113,100,110,74,116,98,71,100,107,73,105,119,105,89,50,57,112,98,110,77,105,79,108,116,55,73,109,82,108,98,109,57,116,73,106,111,105,97,88,74,112,99,121,73,115,73,109,70,116,98,51,86,117,100,67,73,54,77,84,66,57,88,88,49,100,76,67,74,118,100,88,82,119,100,88,82,122,73,106,112,98,101,121,74,104,90,71,82,121,90,88,78,122,73,106,111,105,89,50,57,122,98,87,57,122,89,87,78,106,89,87,82,107,99,106,69,52,90,51,112,106,78,72,111,50,78,87,82,54,97,72,70,104,90,50,116,113,77,106,107,51,100,122,104,51,97,71,69,50,77,110,69,51,77,110,74,119,77,72,100,108,101,87,53,48,79,67,73,115,73,109,78,118,97,87,53,122,73,106,112,98,101,121,74,107,90,87,53,118,98,83,73,54,73,109,108,121,97,88,77,105,76,67,74,104,98,87,57,49,98,110,81,105,79,106,69,119,102,86,49,57,88,88,48,61,34,44,34,97,108,116,95,98,121,116,101,115,34,58,110,117,108,108,125} + server := []byte{123, 34, 99, 104, 97, 105, 110, 95, 105, 100, 34, 58, 34, 102, 117, 120, 105, 34, 44, 34, 97, 99, 99, 111, 117, 110, 116, 95, 110, 117, 109, 98, 101, 114, 115, 34, 58, 91, 48, 93, 44, 34, 115, 101, 113, 117, 101, 110, 99, 101, 115, 34, 58, 91, 51, 93, 44, 34, 102, 101, 101, 95, 98, 121, 116, 101, 115, 34, 58, 34, 101, 121, 74, 104, 98, 87, 57, 49, 98, 110, 81, 105, 79, 108, 116, 55, 73, 109, 82, 108, 98, 109, 57, 116, 73, 106, 111, 105, 97, 88, 74, 112, 99, 121, 73, 115, 73, 109, 70, 116, 98, 51, 86, 117, 100, 67, 73, 54, 77, 72, 49, 100, 76, 67, 74, 110, 89, 88, 77, 105, 79, 106, 66, 57, 34, 44, 34, 109, 115, 103, 95, 98, 121, 116, 101, 115, 34, 58, 34, 101, 121, 74, 112, 98, 110, 66, 49, 100, 72, 77, 105, 79, 108, 116, 55, 73, 109, 70, 107, 90, 72, 74, 108, 99, 51, 77, 105, 79, 105, 74, 106, 98, 51, 78, 116, 98, 51, 78, 104, 89, 50, 78, 104, 90, 71, 82, 121, 77, 88, 74, 116, 99, 72, 100, 122, 89, 51, 73, 53, 78, 109, 104, 111, 89, 122, 78, 110, 98, 71, 82, 50, 97, 51, 86, 48, 79, 71, 90, 119, 97, 110, 112, 121, 89, 87, 82, 117, 77, 50, 70, 113, 100, 110, 74, 116, 98, 71, 100, 107, 73, 105, 119, 105, 89, 50, 57, 112, 98, 110, 77, 105, 79, 108, 116, 55, 73, 109, 82, 108, 98, 109, 57, 116, 73, 106, 111, 105, 97, 88, 74, 112, 99, 121, 73, 115, 73, 109, 70, 116, 98, 51, 86, 117, 100, 67, 73, 54, 77, 84, 66, 57, 88, 88, 49, 100, 76, 67, 74, 118, 100, 88, 82, 119, 100, 88, 82, 122, 73, 106, 112, 98, 101, 121, 74, 104, 90, 71, 82, 121, 90, 88, 78, 122, 73, 106, 111, 105, 89, 50, 57, 122, 98, 87, 57, 122, 89, 87, 78, 106, 89, 87, 82, 107, 99, 106, 69, 52, 90, 51, 112, 106, 78, 72, 111, 50, 78, 87, 82, 54, 97, 72, 70, 104, 90, 50, 116, 113, 77, 106, 107, 51, 100, 122, 104, 51, 97, 71, 69, 50, 77, 110, 69, 51, 77, 110, 74, 119, 77, 72, 100, 108, 101, 87, 53, 48, 79, 67, 73, 115, 73, 109, 78, 118, 97, 87, 53, 122, 73, 106, 112, 98, 101, 121, 74, 107, 90, 87, 53, 118, 98, 83, 73, 54, 73, 109, 108, 121, 97, 88, 77, 105, 76, 67, 74, 104, 98, 87, 57, 49, 98, 110, 81, 105, 79, 106, 69, 119, 102, 86, 49, 57, 88, 88, 48, 61, 34, 44, 34, 97, 108, 116, 95, 98, 121, 116, 101, 115, 34, 58, 110, 117, 108, 108, 125} serverS := string(server) fmt.Println(serverS) } -func TestBech32(t *testing.T){ - addr,_ := types.GetAccAddressBech32("cosmosaccaddr1wp4shn6zzv0l52hfat9c2ryu0gvwa4h3dj2k92") +func TestBech32(t *testing.T) { + addr, _ := types.GetAccAddressBech32("cosmosaccaddr1wp4shn6zzv0l52hfat9c2ryu0gvwa4h3dj2k92") fmt.Print(hex.EncodeToString(addr)) } - - - - diff --git a/cmd/iriscli/main.go b/cmd/iriscli/main.go index 76b01d917..64231ec96 100644 --- a/cmd/iriscli/main.go +++ b/cmd/iriscli/main.go @@ -14,8 +14,8 @@ import ( slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" "github.com/irisnet/irishub/app" - "github.com/irisnet/irishub/version" "github.com/irisnet/irishub/tools/prometheus" + "github.com/irisnet/irishub/version" ) // rootCmd is the entry point for this binary diff --git a/cmd/iriscli/offline_sign.go b/cmd/iriscli/offline_sign.go index 28f3f6bbc..c918c610d 100644 --- a/cmd/iriscli/offline_sign.go +++ b/cmd/iriscli/offline_sign.go @@ -1,39 +1,37 @@ package main import ( - "github.com/cosmos/cosmos-sdk/wire" "encoding/json" - "github.com/tendermint/go-crypto/keys" - "net/http" - "github.com/gorilla/mux" - "io/ioutil" + 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/bank" - "github.com/tendermint/go-crypto" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/pkg/errors" + "github.com/gorilla/mux" "github.com/irisnet/irishub/app" + "github.com/pkg/errors" + "github.com/tendermint/go-crypto" + "github.com/tendermint/go-crypto/keys" + "io/ioutil" + "net/http" ) - func RegisterRoutes(ctx app.Context, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { r.HandleFunc("/tx/send", SendTxRequestHandlerFn(cdc, kb, ctx)).Methods("POST") } - type sendTx struct { - Msg string `json:"msg"` - MsgType string `json:"type"` - Fee auth.StdFee `json:"fee"` - Signatures []StdSignature `json:"signatures"` + Msg string `json:"msg"` + MsgType string `json:"type"` + Fee auth.StdFee `json:"fee"` + Signatures []StdSignature `json:"signatures"` } type StdSignature struct { - PubKey crypto.PubKeyEd25519 `json:"pub_key"` // optional - Signature crypto.SignatureEd25519 `json:"signature"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` + PubKey crypto.PubKeyEd25519 `json:"pub_key"` // optional + Signature crypto.SignatureEd25519 `json:"signature"` + AccountNumber int64 `json:"account_number"` + Sequence int64 `json:"sequence"` } //send traction(sign with rainbow) to irishub @@ -52,15 +50,15 @@ func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx app.Context) h w.Write([]byte(err.Error())) return } - var sig = make([]auth.StdSignature,len(tx.Signatures)) - for index,s := range tx.Signatures { + var sig = make([]auth.StdSignature, len(tx.Signatures)) + for index, s := range tx.Signatures { sig[index].PubKey = s.PubKey sig[index].Signature = s.Signature - sig[index].AccountNumber =s.AccountNumber + sig[index].AccountNumber = s.AccountNumber sig[index].Sequence = s.Sequence } - msg,err := convertMsg(tx) + msg, err := convertMsg(tx) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) @@ -68,11 +66,11 @@ func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx app.Context) h } var stdTx = auth.StdTx{ - Msg:msg, - Fee:tx.Fee, - Signatures:sig, + Msg: msg, + Fee: tx.Fee, + Signatures: sig, } - txByte,_ := cdc.MarshalBinary(stdTx) + txByte, _ := cdc.MarshalBinary(stdTx) // send res, err := ctx.BroadcastTxSync(txByte) if err != nil { @@ -92,29 +90,30 @@ func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx app.Context) h } } -func convertMsg(tx sendTx) (sdk.Msg,error){ +func convertMsg(tx sendTx) (sdk.Msg, error) { data := []byte(tx.Msg) switch tx.MsgType { - case "transfer":{ - var msg bank.MsgSend - if err := json.Unmarshal(data, &msg); err != nil { - return nil,err + case "transfer": + { + var msg bank.MsgSend + if err := json.Unmarshal(data, &msg); err != nil { + return nil, err + } + return msg, nil } - return msg,nil - } case "delegate": var msg stake.MsgDelegate if err := json.Unmarshal(data, &msg); err != nil { - return nil,err + return nil, err } - return msg,nil + return msg, nil case "unbond": var msg stake.MsgUnbond if err := json.Unmarshal(data, &msg); err != nil { - return nil,err + return nil, err } - return msg,nil + return msg, nil } - return nil,errors.New("invalid message type") -} \ No newline at end of file + return nil, errors.New("invalid message type") +} diff --git a/tools/context.go b/tools/context.go index b6f93136a..447f3713f 100644 --- a/tools/context.go +++ b/tools/context.go @@ -1,14 +1,13 @@ package tools import ( - "github.com/cosmos/cosmos-sdk/client/context" + "encoding/json" "fmt" + "github.com/cosmos/cosmos-sdk/client/context" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "io/ioutil" - "encoding/json" - "strings" "net/http" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - + "strings" ) type Context struct { @@ -27,7 +26,7 @@ type JsonRpc interface { NumUnconfirmedTxs() *ctypes.ResultUnconfirmedTxs } -func (rpc Context) NetInfo() *ctypes.ResultNetInfo{ +func (rpc Context) NetInfo() *ctypes.ResultNetInfo { client := &http.Client{} reqUri := tcpToHttpUrl(rpc.NodeURI) + "/net_info" @@ -44,18 +43,18 @@ func (rpc Context) NetInfo() *ctypes.ResultNetInfo{ } var res = struct { - JsonRpc string `json:"jsonrpc"` - Id string `json:"id"` - Result ctypes.ResultNetInfo `json:"result"` + JsonRpc string `json:"jsonrpc"` + Id string `json:"id"` + Result ctypes.ResultNetInfo `json:"result"` }{} - if err := json.Unmarshal(body,&res); err != nil { + if err := json.Unmarshal(body, &res); err != nil { fmt.Println(err) } return &res.Result } -func (rpc Context) NumUnconfirmedTxs() *ctypes.ResultUnconfirmedTxs{ +func (rpc Context) NumUnconfirmedTxs() *ctypes.ResultUnconfirmedTxs { client := &http.Client{} reqUri := tcpToHttpUrl(rpc.NodeURI) + "/num_unconfirmed_txs" @@ -71,20 +70,18 @@ func (rpc Context) NumUnconfirmedTxs() *ctypes.ResultUnconfirmedTxs{ } var res = struct { - JsonRpc string `json:"jsonrpc"` - Id string `json:"id"` - Result ctypes.ResultUnconfirmedTxs `json:"result"` + JsonRpc string `json:"jsonrpc"` + Id string `json:"id"` + Result ctypes.ResultUnconfirmedTxs `json:"result"` }{} - if err := json.Unmarshal(body,&res); err != nil { + if err := json.Unmarshal(body, &res); err != nil { fmt.Println(err) } return &res.Result } -func tcpToHttpUrl(url string) string{ - urls := strings.Replace(url,"tcp","http",1) +func tcpToHttpUrl(url string) string { + urls := strings.Replace(url, "tcp", "http", 1) return urls } - - diff --git a/tools/prometheus/consensus/metrics.go b/tools/prometheus/consensus/metrics.go index 3e1f860ad..ba8d67ea6 100644 --- a/tools/prometheus/consensus/metrics.go +++ b/tools/prometheus/consensus/metrics.go @@ -1,19 +1,19 @@ package consensus import ( + cctx "context" + "encoding/hex" + "fmt" + "github.com/cosmos/cosmos-sdk/wire" // XXX fix + "github.com/cosmos/cosmos-sdk/x/stake" "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/prometheus" + tools "github.com/irisnet/irishub/tools" stdprometheus "github.com/prometheus/client_golang/prometheus" "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/cosmos/cosmos-sdk/wire" // XXX fix - "fmt" + "log" "strings" - "encoding/hex" "time" - "log" - cctx "context" - tools "github.com/irisnet/irishub/tools" ) // Metrics contains metrics exposed by this package. @@ -127,7 +127,7 @@ func PrometheusMetrics() *Metrics { } } -func (cs *Metrics)Monitor(ctx tools.Context,cdc *wire.Codec,storeName string){ +func (cs *Metrics) Monitor(ctx tools.Context, cdc *wire.Codec, storeName string) { context, _ := cctx.WithTimeout(cctx.Background(), 10*time.Second) var client = ctx.Client @@ -145,24 +145,24 @@ func (cs *Metrics)Monitor(ctx tools.Context,cdc *wire.Codec,storeName string){ go func() { for e := range blockC { block := e.(types.TMEventData).(types.EventDataNewBlock) - cs.RecordMetrics(ctx,cdc,block.Block,storeName) + cs.RecordMetrics(ctx, cdc, block.Block, storeName) } }() } -func (cs *Metrics) RecordMetrics(ctx tools.Context,cdc *wire.Codec,block *types.Block,storeName string){ +func (cs *Metrics) RecordMetrics(ctx tools.Context, cdc *wire.Codec, block *types.Block, storeName string) { cs.Height.Set(float64(block.Height)) cs.ByzantineValidators.Set(float64(len(block.Evidence.Evidence))) missingValidators := 0 missingValidatorsPower := int64(0) validatorsPower := int64(0) - resultValidators,err := ctx.Client.Validators(&block.Height) + resultValidators, err := ctx.Client.Validators(&block.Height) if err != nil { panic(err) } validators := resultValidators.Validators - valMap := make(map[string]types.Validator,len(validators)) + valMap := make(map[string]types.Validator, len(validators)) for i, val := range validators { var vote *types.Vote if i < len(block.LastCommit.Precommits) { @@ -176,7 +176,7 @@ func (cs *Metrics) RecordMetrics(ctx tools.Context,cdc *wire.Codec,block *types. valMap[val.Address.String()] = *val validatorsPower += val.VotingPower } - cs.Candidates.Set(float64(getCandidatesNum(cdc,ctx,storeName))) + cs.Candidates.Set(float64(getCandidatesNum(cdc, ctx, storeName))) cs.MissingValidators.Set(float64(missingValidators)) cs.MissingValidatorsPower.Set(float64(missingValidatorsPower)) cs.ValidatorsPower.Set(float64(validatorsPower)) @@ -185,17 +185,17 @@ func (cs *Metrics) RecordMetrics(ctx tools.Context,cdc *wire.Codec,block *types. byzantineValidatorsPower := int64(0) for _, ev := range block.Evidence.Evidence { addr := strings.ToUpper(hex.EncodeToString(ev.Address())) - if val,ok := valMap[addr]; ok { + if val, ok := valMap[addr]; ok { byzantineValidatorsPower += val.VotingPower } } cs.ByzantineValidatorsPower.Set(float64(byzantineValidatorsPower)) if block.Height > 1 { - lastBlockHight := block.Height -1 - lastBlock,_ := ctx.Client.Block(&lastBlockHight) + lastBlockHight := block.Height - 1 + lastBlock, _ := ctx.Client.Block(&lastBlockHight) interval := block.Time.Sub(lastBlock.BlockMeta.Header.Time).Seconds() - cs.BlockIntervalSeconds.Observe(interval,) + cs.BlockIntervalSeconds.Observe(interval) } cs.NumTxs.Set(float64(block.NumTxs)) @@ -205,8 +205,7 @@ func (cs *Metrics) RecordMetrics(ctx tools.Context,cdc *wire.Codec,block *types. cs.BlockSizeBytes.Set(float64(len(bz))) } - -func getCandidatesNum(cdc *wire.Codec,ctx tools.Context,storeName string) (int){ +func getCandidatesNum(cdc *wire.Codec, ctx tools.Context, storeName string) int { key := stake.ValidatorsKey resKVs, err := ctx.QuerySubspace(cdc, key, storeName) if err != nil { diff --git a/tools/prometheus/mempool/metrics.go b/tools/prometheus/mempool/metrics.go index 5f2aee456..0c4423f8c 100644 --- a/tools/prometheus/mempool/metrics.go +++ b/tools/prometheus/mempool/metrics.go @@ -3,8 +3,8 @@ package mempool import ( "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/prometheus" - stdprometheus "github.com/prometheus/client_golang/prometheus" tools "github.com/irisnet/irishub/tools" + stdprometheus "github.com/prometheus/client_golang/prometheus" "time" ) @@ -26,7 +26,7 @@ func PrometheusMetrics() *Metrics { } } -func (m *Metrics )Monitor(rpc tools.Context){ +func (m *Metrics) Monitor(rpc tools.Context) { go func() { for { time.Sleep(1 * time.Second) @@ -35,4 +35,4 @@ func (m *Metrics )Monitor(rpc tools.Context){ } }() -} \ No newline at end of file +} diff --git a/tools/prometheus/p2p/metrics.go b/tools/prometheus/p2p/metrics.go index 343c85c59..8925055cc 100644 --- a/tools/prometheus/p2p/metrics.go +++ b/tools/prometheus/p2p/metrics.go @@ -3,8 +3,8 @@ package p2p import ( "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/prometheus" - stdprometheus "github.com/prometheus/client_golang/prometheus" tools "github.com/irisnet/irishub/tools" + stdprometheus "github.com/prometheus/client_golang/prometheus" "time" ) @@ -25,7 +25,7 @@ func PrometheusMetrics() *Metrics { } } -func (m *Metrics) Monitor(ctx tools.Context){ +func (m *Metrics) Monitor(ctx tools.Context) { go func() { for { time.Sleep(1 * time.Second) diff --git a/tools/prometheus/provider.go b/tools/prometheus/provider.go index 4ac996530..9d369d2f4 100644 --- a/tools/prometheus/provider.go +++ b/tools/prometheus/provider.go @@ -1,14 +1,14 @@ package prometheus import ( - "github.com/irisnet/irishub/tools/prometheus/p2p" cs "github.com/irisnet/irishub/tools/prometheus/consensus" - sys "github.com/irisnet/irishub/tools/prometheus/system" mempl "github.com/irisnet/irishub/tools/prometheus/mempool" + "github.com/irisnet/irishub/tools/prometheus/p2p" + sys "github.com/irisnet/irishub/tools/prometheus/system" ) // DefaultMetricsProvider returns consensus, p2p and mempool Metrics build // using Prometheus client library. func DefaultMetricsProvider() (*cs.Metrics, *p2p.Metrics, *mempl.Metrics, *sys.Metrics) { return cs.PrometheusMetrics(), p2p.PrometheusMetrics(), mempl.PrometheusMetrics(), sys.PrometheusMetrics() -} \ No newline at end of file +} diff --git a/tools/prometheus/server.go b/tools/prometheus/server.go index 449821259..6536845c1 100644 --- a/tools/prometheus/server.go +++ b/tools/prometheus/server.go @@ -1,59 +1,31 @@ package prometheus import ( + "github.com/cosmos/cosmos-sdk/wire" + "github.com/irisnet/irishub/tools" + "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/spf13/cobra" + cmn "github.com/tendermint/tmlibs/common" "log" - "github.com/prometheus/client_golang/prometheus/promhttp" "net/http" - cmn "github.com/tendermint/tmlibs/common" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/spf13/viper" - "strings" - "github.com/irisnet/irishub/tools" ) - func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "monitor", Short: "irishub monitor", RunE: func(cmd *cobra.Command, args []string) error { - //TODO - csMetrics,p2pMetrics,memMetrics, sysMetrics:= DefaultMetricsProvider() + + csMetrics, p2pMetrics, memMetrics, sysMetrics := DefaultMetricsProvider() ctx := tools.NewContext() - //监控共识参数 - csMetrics.Monitor(ctx,cdc,storeName) - //监控p2p参数 + //监控共识指标 + csMetrics.Monitor(ctx, cdc, storeName) + //监控p2p指标 p2pMetrics.Monitor(ctx) - //监控mempool参数 + //监控mempool指标 memMetrics.Monitor(ctx) - - paths := viper.GetString("paths") - commands := viper.GetString("commands") - disks := viper.GetString("disks") - - for _, command := range strings.Split(commands, ";"){ - if strings.TrimSpace(command) != ""{ - sysMetrics.AddProcess(strings.TrimSpace(command)) - } - } - - for _, disk_path := range strings.Split(disks, ";"){ - if strings.TrimSpace(disk_path) != ""{ - sysMetrics.AddDisk(strings.TrimSpace(disk_path)) - } - } - - for _, path := range strings.Split(paths, ";"){ - if strings.TrimSpace(path) != ""{ - sysMetrics.AddPath(strings.TrimSpace(path)) - } - } - - recursively := viper.GetBool("recursively") - sysMetrics.SetRecursively(recursively) - + //监控系统指标 sysMetrics.Monitor() srv := &http.Server{ @@ -81,7 +53,7 @@ by these commands, separated by semicolons ';'. eg: --commands="command 0;command 1;command 2", --commands=iris by default`) cmd.Flags().StringP("disks", "d", "/", `mounted paths of storage devices, separated by semicolons ';'. eg: --disks="/;/mnt1;/mnt2"`) - cmd.Flags().StringP("paths", "p", "", `path to config and data files/directories, separated by semicolons ';'. + cmd.Flags().StringP("paths", "p", "~/.iris", `path to config and data files/directories, separated by semicolons ';'. cannot use ~ and environment variables. eg: --paths="/etc;/home; size of files in sub-directories is excluded. to compute the size recursively, you can use --recursively=true"`) cmd.Flags().BoolP("recursively", "r", false, `specify whether the files in sub-directories is included, diff --git a/tools/prometheus/system/metrics.go b/tools/prometheus/system/metrics.go index 26f5dfc98..da7111de0 100644 --- a/tools/prometheus/system/metrics.go +++ b/tools/prometheus/system/metrics.go @@ -1,6 +1,8 @@ package system import ( + "bytes" + "container/list" "errors" "fmt" "github.com/go-kit/kit/metrics" @@ -10,14 +12,13 @@ import ( "github.com/shirou/gopsutil/disk" "github.com/shirou/gopsutil/mem" "github.com/shirou/gopsutil/process" + "github.com/spf13/viper" "io/ioutil" "os" "os/exec" "strconv" "strings" "time" - "container/list" - "bytes" "unicode" ) @@ -39,7 +40,7 @@ type Metrics struct { //file related monitor term FileSize []metrics.Gauge filePaths []string - recursively bool //whether compute directories size recursively + recursively bool //whether compute directories size recursively DirectorySize []metrics.Gauge dirPaths []string } @@ -49,12 +50,12 @@ func PrometheusMetrics() *Metrics { return &Metrics{ CPUUtilization: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", - Name: "CPU_Percent", + Name: "cpu_percent", Help: "CPU Utilization Percantage", }, []string{}), MemoUtilization: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", - Name: "Memo_Percent", + Name: "memo_percent", Help: "Memo Utilization Percantage", }, []string{}), ProcCPUUtilization: make([]metrics.Gauge, 0), @@ -72,19 +73,19 @@ func PrometheusMetrics() *Metrics { } } -func (metrics *Metrics) AddDisk(disk_path string) { - metrics.disks = append(metrics.disks, disk_path) +func (metrics *Metrics) addDisk(diskPath string) { + metrics.disks = append(metrics.disks, diskPath) - name := fmt.Sprintf("Disk_Used_Percentage_%s", get_path_name(disk_path)) - help := fmt.Sprintf("Used Percentage of disk mount on path: %s", disk_path) + name := fmt.Sprintf("disk_used_percentage_%s", getPathName(diskPath)) + help := fmt.Sprintf("Used Percentage of disk mount on path: %s", diskPath) metrics.DiskUsedPercentage = append(metrics.DiskUsedPercentage, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", Name: name, Help: help, }, []string{})) - name = fmt.Sprintf("Disk_Free_Space_%s", get_path_name(disk_path)) - help = fmt.Sprintf("Free space of disk mount on path: %s", disk_path) + name = fmt.Sprintf("disk_free_space_%s", getPathName(diskPath)) + help = fmt.Sprintf("Free space of disk mount on path: %s", diskPath) metrics.DiskFreeSpace = append(metrics.DiskFreeSpace, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", Name: name, @@ -93,15 +94,14 @@ func (metrics *Metrics) AddDisk(disk_path string) { } -func (metrics *Metrics) AddPath(path string) { +func (metrics *Metrics) addPath(path string) { if fileInfo, err := os.Stat(path); err != nil { fmt.Println(err.Error()) return } else { if fileInfo.IsDir() { metrics.dirPaths = append(metrics.dirPaths, path) - name := fmt.Sprintf("Direcotry_Size_%s", get_path_name(path)) - //name := fmt.Sprintf("Direcotry_Size_%s", strings.Replace(path, "/", "_", -1)) + name := fmt.Sprintf("direcotry_size_%s", getPathName(path)) help := fmt.Sprintf("total Size of files in %s", path) metrics.DirectorySize = append(metrics.DirectorySize, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", @@ -110,7 +110,7 @@ func (metrics *Metrics) AddPath(path string) { }, []string{})) } else { metrics.filePaths = append(metrics.filePaths, path) - name := fmt.Sprintf("File_Size_%s", get_path_name(path)) + name := fmt.Sprintf("file_size_%s", getPathName(path)) help := fmt.Sprintf("size of files: %s", path) metrics.FileSize = append(metrics.FileSize, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", @@ -121,7 +121,35 @@ func (metrics *Metrics) AddPath(path string) { } } -func (metrics *Metrics) AddProcess(command string) { +func (metrics *Metrics) add() { + commands := viper.GetString("commands") + for _, command := range strings.Split(commands, ";") { + if strings.TrimSpace(command) != "" { + metrics.addProcess(strings.TrimSpace(command)) + } + } + + disks := viper.GetString("disks") + for _, diskPath := range strings.Split(disks, ";") { + if strings.TrimSpace(diskPath) != "" { + metrics.addDisk(strings.TrimSpace(diskPath)) + } + } + + paths := viper.GetString("paths") + for _, path := range strings.Split(paths, ";") { + if strings.TrimSpace(path) != "" { + metrics.addPath(strings.TrimSpace(path)) + } + } + + recursively := viper.GetBool("recursively") + metrics.SetRecursively(recursively) + +} + +func (metrics *Metrics) addProcess(command string) { + pid, err := getPid(command) if err != nil { return @@ -136,29 +164,30 @@ func (metrics *Metrics) AddProcess(command string) { metrics.ProcCPUUtilization = append(metrics.ProcCPUUtilization, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", - Name: fmt.Sprintf("CPU_Percent_%d", pid), + Name: fmt.Sprintf("cpu_percent_%d", pid), Help: fmt.Sprintf("CPU Utilization Percantage of processes with pid %d, started by command %s", pid, cmd), }, []string{})) metrics.ProcMemoUtilization = append(metrics.ProcMemoUtilization, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", - Name: fmt.Sprintf("Memo_Percent_%d", pid), + Name: fmt.Sprintf("memo_percent_%d", pid), Help: fmt.Sprintf("Memory Utilization Percantage of processes with pid %d, started by command %s", pid, cmd), }, []string{})) metrics.ProcOpenedFilesNum = append(metrics.ProcOpenedFilesNum, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", - Name: fmt.Sprintf("Opened_Files_Number_%d", pid), + Name: fmt.Sprintf("opened_files_number_%d", pid), Help: fmt.Sprintf("Number of Opened Files of processes with pid %d, started by command %s", pid, cmd), }, []string{})) } -func (metrics *Metrics)SetRecursively(recursively bool) { +func (metrics *Metrics) SetRecursively(recursively bool) { metrics.recursively = recursively } func (metrics *Metrics) Monitor() error { + metrics.add() go func() { for { time.Sleep(1 * time.Second) @@ -171,16 +200,16 @@ func (metrics *Metrics) Monitor() error { func (metrics Metrics) RecordMetrics() { for i, process := range metrics.processes { - if cpu_util, err := process.CPUPercent(); err != nil { + if cpuUtil, err := process.CPUPercent(); err != nil { metrics.ProcCPUUtilization[i].Set(float64(-1)) } else { - metrics.ProcCPUUtilization[i].Set(cpu_util) + metrics.ProcCPUUtilization[i].Set(cpuUtil) } - if memo_util, err := process.MemoryPercent(); err != nil { + if memoUtil, err := process.MemoryPercent(); err != nil { metrics.ProcMemoUtilization[i].Set(float64(-1)) } else { - metrics.ProcMemoUtilization[i].Set(float64(memo_util)) + metrics.ProcMemoUtilization[i].Set(float64(memoUtil)) } if files, err := process.OpenFiles(); err != nil { @@ -190,8 +219,8 @@ func (metrics Metrics) RecordMetrics() { } } - for i, disk_path := range metrics.disks { - if usage, err := disk.Usage(disk_path); err != nil { + for i, diskPath := range metrics.disks { + if usage, err := disk.Usage(diskPath); err != nil { metrics.DirectorySize[i].Set(float64(-1)) metrics.DiskFreeSpace[i].Set(float64(-1)) } else { @@ -200,16 +229,16 @@ func (metrics Metrics) RecordMetrics() { } } - for i, file_path := range metrics.filePaths { - if fileInfo, err := os.Stat(file_path); err != nil { + for i, filePath := range metrics.filePaths { + if fileInfo, err := os.Stat(filePath); err != nil { metrics.FileSize[i].Set(float64(-1)) } else { metrics.FileSize[i].Set(float64(fileInfo.Size())) } } - for i, dir_path := range metrics.dirPaths { - if size, err := get_dir_size(dir_path, metrics.recursively); err != nil { + for i, dirPath := range metrics.dirPaths { + if size, err := getDirSize(dirPath, metrics.recursively); err != nil { metrics.DirectorySize[i].Set(float64(-1)) } else { metrics.DirectorySize[i].Set(float64(size)) @@ -233,8 +262,8 @@ func (metrics Metrics) RecordMetrics() { //the first pid return by "ps -aux|grep ", // the process whose command contains "grep" is omitted func getPid(command string) (pid int, err error) { - command_str := fmt.Sprintf("ps -aux|grep '%s'", command) - cmd := exec.Command("/bin/bash", "-c", command_str) + commandStr := fmt.Sprintf("ps -aux|grep '%s'", command) + cmd := exec.Command("/bin/bash", "-c", commandStr) stdout, err := cmd.StdoutPipe() @@ -271,12 +300,12 @@ func getPid(command string) (pid int, err error) { } //get directory size of given path -func get_dir_size(dir_path string, recursively bool) (int64, error) { +func getDirSize(path string, recursively bool) (int64, error) { Separator := string(os.PathSeparator) queue := list.New() - queue.PushBack(dir_path) + queue.PushBack(path) size := int64(0) - for ;queue.Len() > 0;{ + for queue.Len() > 0 { path := fmt.Sprint(queue.Front().Value) queue.Remove(queue.Front()) @@ -287,7 +316,7 @@ func get_dir_size(dir_path string, recursively bool) (int64, error) { for _, file := range files { file_size := file.Size() size += file_size - if file.IsDir() && recursively{ + if file.IsDir() && recursively { queue.PushBack(path + Separator + file.Name()) } } @@ -296,18 +325,18 @@ func get_dir_size(dir_path string, recursively bool) (int64, error) { } //conver a path to a valid Gauge monitor term name -func get_path_name(path string)(path_name string){ +func getPathName(path string) string { var buffer bytes.Buffer - for i, ch := range path{ - if i == 0 && unicode.IsDigit(ch){ + for i, ch := range path { + if i == 0 && unicode.IsDigit(ch) { buffer.WriteString("_") } - if unicode.IsDigit(ch) || unicode.IsLetter(ch){ + if unicode.IsDigit(ch) || unicode.IsLetter(ch) { buffer.WriteByte(byte(ch)) - }else { + } else { buffer.WriteByte(byte('_')) } } return buffer.String() -} \ No newline at end of file +} From 9801bbe4f636517214c14d788a13bc24ba68d2f9 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Tue, 10 Jul 2018 09:46:09 +0800 Subject: [PATCH 057/124] Code clear --- cmd/iriscli/lcd_test.go | 242 ---------------------------------------- 1 file changed, 242 deletions(-) diff --git a/cmd/iriscli/lcd_test.go b/cmd/iriscli/lcd_test.go index 28253d15f..cabf4acc5 100644 --- a/cmd/iriscli/lcd_test.go +++ b/cmd/iriscli/lcd_test.go @@ -1,20 +1,9 @@ package main import ( - "bytes" - "encoding/hex" - "encoding/json" - "fmt" - "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" "github.com/irisnet/irishub/app" "github.com/irisnet/irishub/tools/prometheus" - "github.com/magiconair/properties/assert" "github.com/spf13/viper" - "github.com/tendermint/go-amino" - "log" - "os" "testing" ) @@ -43,234 +32,3 @@ func TestMetricsCmd(t *testing.T) { viper.Set("recursively", true) comm.ExecuteC() } - -func TestAmino(t *testing.T) { - var cdc = amino.NewCodec() - - type Person struct { - Name string - Age int - } - - p := Person{ - Name: "zhangsn", - Age: 18, - } - - bz, _ := cdc.MarshalJSON(p) - fmt.Println(bz) - - var p1 Person - if err := cdc.UnmarshalJSON(bz, &p1); err != nil { - fmt.Println(err) - return - } - //cdc.MustUnmarshalBinaryBare(bz,p1) - fmt.Printf("%+v", p1) - -} - -func TestMarshalJson(t *testing.T) { - add, _ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") - conis := types.Coins{ - types.Coin{ - Denom: "iris", - Amount: 10, - }, - } - //fmt.Println(types.MustBech32ifyAcc(add)) - input := bank.Input{ - Address: add, - Coins: conis, - } - input1Byte := input.GetSignBytes() - fmt.Println(input1Byte) - - input2Byte, _ := json.Marshal(struct { - Address string `json:"address"` - Coins types.Coins `json:"coins"` - }{ - Address: types.MustBech32ifyAcc(add), - Coins: conis, - }) - - assert.Equal(t, input1Byte, input2Byte) - -} - -func TestMarshal(t *testing.T) { - add, _ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") - conis := types.Coins{ - types.Coin{ - Denom: "iris", - Amount: 10, - }, - } - //fmt.Println(types.MustBech32ifyAcc(add)) - input := bank.Input{ - Address: add, - Coins: conis, - } - input1Byte := input.GetSignBytes() - - input2Byte, _ := json.Marshal(struct { - Address string `json:"address"` - Coins types.Coins `json:"coins"` - }{ - Address: types.MustBech32ifyAcc(add), - Coins: conis, - }) - - assert.Equal(t, input1Byte, input2Byte) - -} - -func TestSignByte(t *testing.T) { - from, _ := types.GetAccAddressHex("1EC2E86065D5EF88A3ED65B8B3A43210FAD9C7B2") - - chainID := "fuxi" - accnums := []int64{0} - sequences := []int64{3} - - conis := types.Coins{ - types.Coin{ - Denom: "iris", - Amount: 10, - }, - } - - fees := types.Coins{ - types.Coin{ - Denom: "iris", - Amount: 0, - }, - } - - type put struct { - Address string `json:"address"` - Coins types.Coins `json:"coins"` - } - - input := bank.Input{ - Address: from, - Coins: conis, - } - - input1 := input.GetSignBytes() - input2, _ := json.Marshal(put{ - Address: types.MustBech32ifyAcc(from), - Coins: conis, - }) - - assert.Equal(t, input1, input2) - - to, _ := types.GetAccAddressHex("3A058A8B5468AE0EA2D2517CE3BAFDD281E50C2F") - output := bank.Output{ - Address: to, - Coins: conis, - } - - output1 := output.GetSignBytes() - output2, _ := json.Marshal(put{ - Address: types.MustBech32ifyAcc(to), - Coins: conis, - }) - - assert.Equal(t, output1, output2) - - msg := bank.MsgSend{ - []bank.Input{input}, []bank.Output{output}, - } - - msg1 := msg.GetSignBytes() - - var inputs, outputs []json.RawMessage - for _, input := range msg.Inputs { - inputs = append(inputs, input.GetSignBytes()) - } - for _, output := range msg.Outputs { - outputs = append(outputs, output.GetSignBytes()) - } - - msg2, _ := json.Marshal(struct { - Inputs []json.RawMessage `json:"inputs"` - Outputs []json.RawMessage `json:"outputs"` - }{ - Inputs: inputs, - Outputs: outputs, - }) - //fmt.Print(msg2) - assert.Equal(t, msg1, msg2) - - fee := auth.StdFee{ - Amount: fees, - Gas: int64(0), - } - - fee1 := fee.Bytes() - fee2, _ := json.Marshal(struct { - Amount types.Coins `json:"amount"` - Gas int64 `json:"gas"` - }{ - Amount: fees, - Gas: int64(0), - }) - - assert.Equal(t, fee1, fee2) - - signMsg := auth.StdSignMsg{ - ChainID: chainID, - AccountNumbers: accnums, - Sequences: sequences, - Msg: msg, - Fee: fee, - } - - signByte1 := signMsg.Bytes() - signByte2, _ := json.Marshal(auth.StdSignDoc{ - ChainID: chainID, - AccountNumbers: accnums, - Sequences: sequences, - FeeBytes: fee2, - MsgBytes: msg2, - }) - - str := string(signByte1) - - fmt.Println(str) - - //printJson(signByte2) - - assert.Equal(t, signByte1, signByte2) - - fmt.Println(signByte1) - -} - -func printJson(b []byte) { - var out bytes.Buffer - err := json.Indent(&out, b, "", "\t") - - if err != nil { - log.Fatalln(err) - } - - out.WriteTo(os.Stdout) -} - -func TestH(t *testing.T) { - client := []byte{123, 34, 99, 104, 97, 105, 110, 95, 105, 100, 34, 58, 34, 102, 117, 120, 105, 34, 44, 34, 97, 99, 99, 111, 117, 110, 116, 95, 110, 117, 109, 98, 101, 114, 115, 34, 58, 91, 48, 93, 44, 34, 115, 101, 113, 117, 101, 110, 99, 101, 115, 34, 58, 91, 51, 93, 44, 34, 102, 101, 101, 95, 98, 121, 116, 101, 115, 34, 58, 34, 101, 121, 74, 104, 98, 87, 57, 49, 98, 110, 81, 105, 79, 108, 116, 55, 73, 109, 70, 116, 98, 51, 86, 117, 100, 67, 73, 54, 77, 67, 119, 105, 90, 71, 86, 117, 98, 50, 48, 105, 79, 105, 74, 112, 99, 109, 108, 122, 73, 110, 49, 100, 76, 67, 74, 110, 89, 88, 77, 105, 79, 106, 66, 57, 34, 44, 34, 109, 115, 103, 95, 98, 121, 116, 101, 115, 34, 58, 34, 101, 121, 74, 112, 98, 110, 66, 49, 100, 72, 77, 105, 79, 108, 116, 55, 73, 109, 70, 107, 90, 72, 74, 108, 99, 51, 77, 105, 79, 105, 74, 106, 98, 51, 78, 116, 98, 51, 78, 104, 89, 50, 78, 104, 90, 71, 82, 121, 77, 88, 74, 116, 99, 72, 100, 122, 89, 51, 73, 53, 78, 109, 104, 111, 89, 122, 78, 110, 98, 71, 82, 50, 97, 51, 86, 48, 79, 71, 90, 119, 97, 110, 112, 121, 89, 87, 82, 117, 77, 50, 70, 113, 100, 110, 74, 116, 98, 71, 100, 107, 73, 105, 119, 105, 89, 50, 57, 112, 98, 110, 77, 105, 79, 108, 116, 55, 73, 109, 70, 116, 98, 51, 86, 117, 100, 67, 73, 54, 77, 84, 65, 115, 73, 109, 82, 108, 98, 109, 57, 116, 73, 106, 111, 105, 97, 88, 74, 112, 99, 121, 74, 57, 88, 88, 49, 100, 76, 67, 74, 118, 100, 88, 82, 119, 100, 88, 82, 122, 73, 106, 112, 98, 101, 121, 74, 104, 90, 71, 82, 121, 90, 88, 78, 122, 73, 106, 111, 105, 89, 50, 57, 122, 98, 87, 57, 122, 89, 87, 78, 106, 89, 87, 82, 107, 99, 106, 69, 52, 90, 51, 112, 106, 78, 72, 111, 50, 78, 87, 82, 54, 97, 72, 70, 104, 90, 50, 116, 113, 77, 106, 107, 51, 100, 122, 104, 51, 97, 71, 69, 50, 77, 110, 69, 51, 77, 110, 74, 119, 77, 72, 100, 108, 101, 87, 53, 48, 79, 67, 73, 115, 73, 109, 78, 118, 97, 87, 53, 122, 73, 106, 112, 98, 101, 121, 74, 104, 98, 87, 57, 49, 98, 110, 81, 105, 79, 106, 69, 119, 76, 67, 74, 107, 90, 87, 53, 118, 98, 83, 73, 54, 73, 109, 108, 121, 97, 88, 77, 105, 102, 86, 49, 57, 88, 88, 48, 61, 34, 44, 34, 97, 108, 116, 95, 98, 121, 116, 101, 115, 34, 58, 110, 117, 108, 108, 125} - clientS := string(client) - - //fmt.Println(str1) - fmt.Println(clientS) - - server := []byte{123, 34, 99, 104, 97, 105, 110, 95, 105, 100, 34, 58, 34, 102, 117, 120, 105, 34, 44, 34, 97, 99, 99, 111, 117, 110, 116, 95, 110, 117, 109, 98, 101, 114, 115, 34, 58, 91, 48, 93, 44, 34, 115, 101, 113, 117, 101, 110, 99, 101, 115, 34, 58, 91, 51, 93, 44, 34, 102, 101, 101, 95, 98, 121, 116, 101, 115, 34, 58, 34, 101, 121, 74, 104, 98, 87, 57, 49, 98, 110, 81, 105, 79, 108, 116, 55, 73, 109, 82, 108, 98, 109, 57, 116, 73, 106, 111, 105, 97, 88, 74, 112, 99, 121, 73, 115, 73, 109, 70, 116, 98, 51, 86, 117, 100, 67, 73, 54, 77, 72, 49, 100, 76, 67, 74, 110, 89, 88, 77, 105, 79, 106, 66, 57, 34, 44, 34, 109, 115, 103, 95, 98, 121, 116, 101, 115, 34, 58, 34, 101, 121, 74, 112, 98, 110, 66, 49, 100, 72, 77, 105, 79, 108, 116, 55, 73, 109, 70, 107, 90, 72, 74, 108, 99, 51, 77, 105, 79, 105, 74, 106, 98, 51, 78, 116, 98, 51, 78, 104, 89, 50, 78, 104, 90, 71, 82, 121, 77, 88, 74, 116, 99, 72, 100, 122, 89, 51, 73, 53, 78, 109, 104, 111, 89, 122, 78, 110, 98, 71, 82, 50, 97, 51, 86, 48, 79, 71, 90, 119, 97, 110, 112, 121, 89, 87, 82, 117, 77, 50, 70, 113, 100, 110, 74, 116, 98, 71, 100, 107, 73, 105, 119, 105, 89, 50, 57, 112, 98, 110, 77, 105, 79, 108, 116, 55, 73, 109, 82, 108, 98, 109, 57, 116, 73, 106, 111, 105, 97, 88, 74, 112, 99, 121, 73, 115, 73, 109, 70, 116, 98, 51, 86, 117, 100, 67, 73, 54, 77, 84, 66, 57, 88, 88, 49, 100, 76, 67, 74, 118, 100, 88, 82, 119, 100, 88, 82, 122, 73, 106, 112, 98, 101, 121, 74, 104, 90, 71, 82, 121, 90, 88, 78, 122, 73, 106, 111, 105, 89, 50, 57, 122, 98, 87, 57, 122, 89, 87, 78, 106, 89, 87, 82, 107, 99, 106, 69, 52, 90, 51, 112, 106, 78, 72, 111, 50, 78, 87, 82, 54, 97, 72, 70, 104, 90, 50, 116, 113, 77, 106, 107, 51, 100, 122, 104, 51, 97, 71, 69, 50, 77, 110, 69, 51, 77, 110, 74, 119, 77, 72, 100, 108, 101, 87, 53, 48, 79, 67, 73, 115, 73, 109, 78, 118, 97, 87, 53, 122, 73, 106, 112, 98, 101, 121, 74, 107, 90, 87, 53, 118, 98, 83, 73, 54, 73, 109, 108, 121, 97, 88, 77, 105, 76, 67, 74, 104, 98, 87, 57, 49, 98, 110, 81, 105, 79, 106, 69, 119, 102, 86, 49, 57, 88, 88, 48, 61, 34, 44, 34, 97, 108, 116, 95, 98, 121, 116, 101, 115, 34, 58, 110, 117, 108, 108, 125} - serverS := string(server) - fmt.Println(serverS) -} - -func TestBech32(t *testing.T) { - addr, _ := types.GetAccAddressBech32("cosmosaccaddr1wp4shn6zzv0l52hfat9c2ryu0gvwa4h3dj2k92") - fmt.Print(hex.EncodeToString(addr)) -} From 5a9ac0758e03048f99a1e0f928b17113fc86b2f3 Mon Sep 17 00:00:00 2001 From: programokey <872127164@qq.com> Date: Tue, 10 Jul 2018 03:00:12 -0700 Subject: [PATCH 058/124] IRISHUB-32 fixed the bug in system/metrics and add app.DefaultHome to parameter paths' default value --- tools/prometheus/server.go | 3 ++- tools/prometheus/system/metrics.go | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/tools/prometheus/server.go b/tools/prometheus/server.go index 6536845c1..566f856f5 100644 --- a/tools/prometheus/server.go +++ b/tools/prometheus/server.go @@ -8,6 +8,7 @@ import ( cmn "github.com/tendermint/tmlibs/common" "log" "net/http" + "github.com/irisnet/irishub/app" ) func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { @@ -53,7 +54,7 @@ by these commands, separated by semicolons ';'. eg: --commands="command 0;command 1;command 2", --commands=iris by default`) cmd.Flags().StringP("disks", "d", "/", `mounted paths of storage devices, separated by semicolons ';'. eg: --disks="/;/mnt1;/mnt2"`) - cmd.Flags().StringP("paths", "p", "~/.iris", `path to config and data files/directories, separated by semicolons ';'. + cmd.Flags().StringP("paths", "p", app.DefaultNodeHome, `path to config and data files/directories, separated by semicolons ';'. cannot use ~ and environment variables. eg: --paths="/etc;/home; size of files in sub-directories is excluded. to compute the size recursively, you can use --recursively=true"`) cmd.Flags().BoolP("recursively", "r", false, `specify whether the files in sub-directories is included, diff --git a/tools/prometheus/system/metrics.go b/tools/prometheus/system/metrics.go index da7111de0..006717542 100644 --- a/tools/prometheus/system/metrics.go +++ b/tools/prometheus/system/metrics.go @@ -253,7 +253,7 @@ func (metrics Metrics) RecordMetrics() { for _, percent := range percents { CPUUsedPercent += percent } - metrics.CPUUtilization.Set(CPUUsedPercent / 4) + metrics.CPUUtilization.Set(CPUUsedPercent / float64(len(percents))) } //-----------------help functions------------------------------- From 16f3179763ae272e106e23c6c2a8222e829b13f5 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Tue, 10 Jul 2018 18:46:43 +0800 Subject: [PATCH 059/124] Code optimization --- tools/context.go | 7 ++++-- tools/prometheus/consensus/metrics.go | 4 +-- tools/prometheus/mempool/metrics.go | 2 +- tools/prometheus/p2p/metrics.go | 2 +- tools/prometheus/provider.go | 36 ++++++++++++++++++++++++--- tools/prometheus/server.go | 17 ++++--------- tools/prometheus/system/metrics.go | 6 ++--- 7 files changed, 49 insertions(+), 25 deletions(-) diff --git a/tools/context.go b/tools/context.go index 447f3713f..da4d0b160 100644 --- a/tools/context.go +++ b/tools/context.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/cosmos/cosmos-sdk/client/context" ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/cosmos/cosmos-sdk/wire" "io/ioutil" "net/http" "strings" @@ -12,12 +13,14 @@ import ( type Context struct { context.CoreContext + StoreName string + Cdc *wire.Codec } -func NewContext() Context { +func NewContext(storeName string,cdc *wire.Codec) Context { ctx := context.NewCoreContextFromViper() return Context{ - ctx, + ctx,storeName,cdc, } } diff --git a/tools/prometheus/consensus/metrics.go b/tools/prometheus/consensus/metrics.go index ba8d67ea6..696162354 100644 --- a/tools/prometheus/consensus/metrics.go +++ b/tools/prometheus/consensus/metrics.go @@ -127,7 +127,7 @@ func PrometheusMetrics() *Metrics { } } -func (cs *Metrics) Monitor(ctx tools.Context, cdc *wire.Codec, storeName string) { +func (cs *Metrics) Start(ctx tools.Context) { context, _ := cctx.WithTimeout(cctx.Background(), 10*time.Second) var client = ctx.Client @@ -145,7 +145,7 @@ func (cs *Metrics) Monitor(ctx tools.Context, cdc *wire.Codec, storeName string) go func() { for e := range blockC { block := e.(types.TMEventData).(types.EventDataNewBlock) - cs.RecordMetrics(ctx, cdc, block.Block, storeName) + cs.RecordMetrics(ctx, ctx.Cdc, block.Block, ctx.StoreName) } }() } diff --git a/tools/prometheus/mempool/metrics.go b/tools/prometheus/mempool/metrics.go index 0c4423f8c..c7562993b 100644 --- a/tools/prometheus/mempool/metrics.go +++ b/tools/prometheus/mempool/metrics.go @@ -26,7 +26,7 @@ func PrometheusMetrics() *Metrics { } } -func (m *Metrics) Monitor(rpc tools.Context) { +func (m *Metrics) Start(rpc tools.Context) { go func() { for { time.Sleep(1 * time.Second) diff --git a/tools/prometheus/p2p/metrics.go b/tools/prometheus/p2p/metrics.go index 8925055cc..95817918c 100644 --- a/tools/prometheus/p2p/metrics.go +++ b/tools/prometheus/p2p/metrics.go @@ -25,7 +25,7 @@ func PrometheusMetrics() *Metrics { } } -func (m *Metrics) Monitor(ctx tools.Context) { +func (m *Metrics) Start(ctx tools.Context) { go func() { for { time.Sleep(1 * time.Second) diff --git a/tools/prometheus/provider.go b/tools/prometheus/provider.go index 9d369d2f4..a6ecd0a64 100644 --- a/tools/prometheus/provider.go +++ b/tools/prometheus/provider.go @@ -1,14 +1,42 @@ package prometheus import ( + "github.com/irisnet/irishub/tools" cs "github.com/irisnet/irishub/tools/prometheus/consensus" mempl "github.com/irisnet/irishub/tools/prometheus/mempool" "github.com/irisnet/irishub/tools/prometheus/p2p" sys "github.com/irisnet/irishub/tools/prometheus/system" ) -// DefaultMetricsProvider returns consensus, p2p and mempool Metrics build -// using Prometheus client library. -func DefaultMetricsProvider() (*cs.Metrics, *p2p.Metrics, *mempl.Metrics, *sys.Metrics) { - return cs.PrometheusMetrics(), p2p.PrometheusMetrics(), mempl.PrometheusMetrics(), sys.PrometheusMetrics() +type Monitor struct { + providers []MetricsProvider + ctx tools.Context +} + +func DefaultMonitor(ctx tools.Context) *Monitor { + var providers []MetricsProvider + monitor := &Monitor{ + providers: providers, + ctx:ctx, + } + monitor.AddMetricsProvider(cs.PrometheusMetrics()). + AddMetricsProvider(p2p.PrometheusMetrics()). + AddMetricsProvider(mempl.PrometheusMetrics()). + AddMetricsProvider(sys.PrometheusMetrics()) + return monitor +} + +func (m *Monitor) AddMetricsProvider(provider MetricsProvider) *Monitor { + m.providers = append(m.providers, provider) + return m +} + +func (m *Monitor) Start() { + for _, provider := range m.providers { + provider.Start(m.ctx) + } +} + +type MetricsProvider interface { + Start(ctx tools.Context) } diff --git a/tools/prometheus/server.go b/tools/prometheus/server.go index 6536845c1..b55d1934c 100644 --- a/tools/prometheus/server.go +++ b/tools/prometheus/server.go @@ -8,6 +8,7 @@ import ( cmn "github.com/tendermint/tmlibs/common" "log" "net/http" + "github.com/irisnet/irishub/app" ) func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { @@ -16,17 +17,9 @@ func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { Short: "irishub monitor", RunE: func(cmd *cobra.Command, args []string) error { - csMetrics, p2pMetrics, memMetrics, sysMetrics := DefaultMetricsProvider() - ctx := tools.NewContext() - - //监控共识指标 - csMetrics.Monitor(ctx, cdc, storeName) - //监控p2p指标 - p2pMetrics.Monitor(ctx) - //监控mempool指标 - memMetrics.Monitor(ctx) - //监控系统指标 - sysMetrics.Monitor() + ctx := tools.NewContext(storeName,cdc) + monitor := DefaultMonitor(ctx) + monitor.Start() srv := &http.Server{ Addr: ":26660", @@ -53,7 +46,7 @@ by these commands, separated by semicolons ';'. eg: --commands="command 0;command 1;command 2", --commands=iris by default`) cmd.Flags().StringP("disks", "d", "/", `mounted paths of storage devices, separated by semicolons ';'. eg: --disks="/;/mnt1;/mnt2"`) - cmd.Flags().StringP("paths", "p", "~/.iris", `path to config and data files/directories, separated by semicolons ';'. + cmd.Flags().StringP("paths", "p", app.DefaultNodeHome, `path to config and data files/directories, separated by semicolons ';'. cannot use ~ and environment variables. eg: --paths="/etc;/home; size of files in sub-directories is excluded. to compute the size recursively, you can use --recursively=true"`) cmd.Flags().BoolP("recursively", "r", false, `specify whether the files in sub-directories is included, diff --git a/tools/prometheus/system/metrics.go b/tools/prometheus/system/metrics.go index da7111de0..f58fe5bdc 100644 --- a/tools/prometheus/system/metrics.go +++ b/tools/prometheus/system/metrics.go @@ -20,6 +20,7 @@ import ( "strings" "time" "unicode" + "github.com/irisnet/irishub/tools" ) type Metrics struct { @@ -186,7 +187,7 @@ func (metrics *Metrics) SetRecursively(recursively bool) { metrics.recursively = recursively } -func (metrics *Metrics) Monitor() error { +func (metrics *Metrics) Start(ctx tools.Context) { metrics.add() go func() { for { @@ -194,7 +195,6 @@ func (metrics *Metrics) Monitor() error { metrics.RecordMetrics() } }() - return nil } func (metrics Metrics) RecordMetrics() { @@ -253,7 +253,7 @@ func (metrics Metrics) RecordMetrics() { for _, percent := range percents { CPUUsedPercent += percent } - metrics.CPUUtilization.Set(CPUUsedPercent / 4) + metrics.CPUUtilization.Set(CPUUsedPercent / float64(len(percents))) } //-----------------help functions------------------------------- From b172d2707c29bcb0883657f30f567b217d5456e5 Mon Sep 17 00:00:00 2001 From: Yelong Zhang Date: Wed, 11 Jul 2018 11:12:16 +0800 Subject: [PATCH 060/124] Revert "feature/prometheus" --- .dockerignore | 3 - Dockerfile | 41 +- Dockerfile-dev | 42 -- Gopkg.lock | 556 ------------------ Gopkg.toml | 70 --- Makefile | 21 +- README.md | 217 ++++--- app/app.go | 181 ------ app/context.go | 28 - app/genesis.go | 231 -------- cmd/iris/client.go | 97 +++ cmd/iris/main.go | 74 +-- cmd/iris/node.go | 69 +++ cmd/iris/rest.go | 95 +++ cmd/iris/rest_test.go | 77 +++ cmd/iris/sh_tests/stake.sh | 276 +++++++++ cmd/iriscli/lcd.go | 85 --- cmd/iriscli/lcd_test.go | 34 -- cmd/iriscli/main.go | 124 ---- cmd/iriscli/offline_sign.go | 119 ---- glide.lock | 305 ++++++++++ glide.yaml | 17 + module/rest-txs/txs.go | 53 ++ rest/byteTx.go | 118 ++++ testnets/develop/README.md | 28 - testnets/develop/config/genesis.json | 102 ---- ...17b3821cf22382b7afe03e30bd04d1b4f10eb.json | 20 - testnets/develop/config/node_key.json | 1 - testnets/develop/config/priv_validator.json | 14 - testnets/develop/seed_phrase | 1 - testnets/develop/start-docker.sh | 5 - testnets/develop/start.sh | 20 - tools/context.go | 90 --- tools/prometheus/consensus/metrics.go | 215 ------- tools/prometheus/mempool/metrics.go | 38 -- tools/prometheus/p2p/metrics.go | 36 -- tools/prometheus/provider.go | 42 -- tools/prometheus/server.go | 55 -- tools/prometheus/system/metrics.go | 342 ----------- version/version.go | 8 +- 40 files changed, 1306 insertions(+), 2644 deletions(-) delete mode 100644 .dockerignore delete mode 100644 Dockerfile-dev delete mode 100644 Gopkg.lock delete mode 100644 Gopkg.toml delete mode 100644 app/app.go delete mode 100644 app/context.go delete mode 100644 app/genesis.go create mode 100644 cmd/iris/client.go create mode 100644 cmd/iris/node.go create mode 100644 cmd/iris/rest.go create mode 100644 cmd/iris/rest_test.go create mode 100644 cmd/iris/sh_tests/stake.sh delete mode 100644 cmd/iriscli/lcd.go delete mode 100644 cmd/iriscli/lcd_test.go delete mode 100644 cmd/iriscli/main.go delete mode 100644 cmd/iriscli/offline_sign.go create mode 100644 glide.lock create mode 100644 glide.yaml create mode 100644 module/rest-txs/txs.go create mode 100644 rest/byteTx.go delete mode 100644 testnets/develop/README.md delete mode 100644 testnets/develop/config/genesis.json delete mode 100644 testnets/develop/config/gentx/gentx-7db17b3821cf22382b7afe03e30bd04d1b4f10eb.json delete mode 100644 testnets/develop/config/node_key.json delete mode 100644 testnets/develop/config/priv_validator.json delete mode 100644 testnets/develop/seed_phrase delete mode 100644 testnets/develop/start-docker.sh delete mode 100644 testnets/develop/start.sh delete mode 100644 tools/context.go delete mode 100644 tools/prometheus/consensus/metrics.go delete mode 100644 tools/prometheus/mempool/metrics.go delete mode 100644 tools/prometheus/p2p/metrics.go delete mode 100644 tools/prometheus/provider.go delete mode 100644 tools/prometheus/server.go delete mode 100644 tools/prometheus/system/metrics.go diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index ddf1a56b6..000000000 --- a/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ -Dockerfile -build/ -vendor/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 28f663a27..94c28973d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,38 +1,29 @@ - # Simple usage with a mounted data directory: -# > docker build -t irishub . -# > docker run -v $HOME/.iris:/root/.iris iris init -# > docker run -v $HOME/.iris:/root/.iris iris start +# > docker build -t iris . +# > docker run -it --rm -v "/mnt/volumes/pangu:/iris" iris init [address]--home=/iris +# > docker run -it --rm -v "/mnt/volumes/pangu:/iris" iris start --home=/iris FROM alpine:edge -# Set up dependencies -ENV PACKAGES go make git libc-dev bash +ADD ./build/ /usr/local/bin/ + +ENV DATA_ROOT /iris + +# Set user right away for determinism +RUN addgroup gaiauser && \ + adduser -S -G gaiauser gaiauser -# Set up GOPATH & PATH +# Create directory for persistence and give our user ownership +RUN mkdir -p $DATA_ROOT && \ + chown -R gaiauser:gaiauser $DATA_ROOT -ENV GOPATH /root/go -ENV BASE_PATH $GOPATH/src/github.com/irisnet -ENV REPO_PATH $BASE_PATH/irishub -ENV PATH $GOPATH/bin:$PATH +VOLUME $DATA_ROOT # p2p port EXPOSE 46656 # rpc port EXPOSE 46657 -# Add source files -COPY . $REPO_PATH/ - -# Install minimum necessary dependencies, build Cosmos SDK, remove packages -RUN cd $REPO_PATH && \ - apk add --no-cache $PACKAGES && \ - go get github.com/golang/dep/cmd/dep && \ - make get_vendor_deps && \ - make build_linux && \ - cp build/* /usr/local/bin/ && \ - cd / && \ - apk del $PACKAGES && \ - rm -rf $GOPATH/ && \ - rm -rf /root/.cache/ +WORKDIR /bianjie/ +ENTRYPOINT ["iris"] \ No newline at end of file diff --git a/Dockerfile-dev b/Dockerfile-dev deleted file mode 100644 index de04a6f32..000000000 --- a/Dockerfile-dev +++ /dev/null @@ -1,42 +0,0 @@ -# Using cache for development -# Simple usage with a mounted data directory: -# > docker build -t irishub:develop -f Dockerfile-dev . -# > docker run -v $HOME/.iris:/root/.iris iris init -# > docker run -v $HOME/.iris:/root/.iris iris start - -FROM alpine:edge - -# Set up dependencies -ENV PACKAGES go glide make git libc-dev bash - -# Set up GOPATH & PATH - -ENV GOPATH /root/go -ENV BASE_PATH $GOPATH/src/github.com/irisnet -ENV REPO_PATH $BASE_PATH/irishub -ENV PATH $GOPATH/bin:$PATH - -# Link expected Go repo path - -RUN mkdir -p $WORKDIR $GOPATH/pkg $GOPATH/bin $BASE_PATH && \ - apk add --no-cache $PACKAGES && \ - go get github.com/golang/dep/cmd/dep - -# List project dependencies with Gopkg.toml and Gopkg.lock -# These layers are only re-built when Gopkg files are updated -COPY Gopkg.lock Gopkg.toml $REPO_PATH/ - -WORKDIR $REPO_PATH - -RUN dep ensure -vendor-only - -# p2p port -EXPOSE 46656 -# rpc port -EXPOSE 46657 - -# Add source files -COPY . $REPO_PATH/ - -RUN make build_linux && \ - mv build/* /usr/local/bin/ \ No newline at end of file diff --git a/Gopkg.lock b/Gopkg.lock deleted file mode 100644 index 92e47b418..000000000 --- a/Gopkg.lock +++ /dev/null @@ -1,556 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - branch = "master" - name = "github.com/beorn7/perks" - packages = ["quantile"] - revision = "3a771d992973f24aa725d07868b467d1ddfceafb" - -[[projects]] - name = "github.com/bgentry/speakeasy" - packages = ["."] - revision = "4aabc24848ce5fd31929f7d1e4ea74d3709c14cd" - version = "v0.1.0" - -[[projects]] - branch = "master" - name = "github.com/btcsuite/btcd" - packages = ["btcec"] - revision = "86fed781132ac890ee03e906e4ecd5d6fa180c64" - -[[projects]] - branch = "master" - name = "github.com/btcsuite/btcutil" - packages = ["bech32"] - revision = "d4cc87b860166d00d6b5b9e0d3b3d71d6088d4d4" - -[[projects]] - name = "github.com/cosmos/cosmos-sdk" - packages = [ - "baseapp", - "client", - "client/context", - "client/keys", - "client/rpc", - "client/tx", - "server", - "store", - "types", - "version", - "wire", - "x/auth", - "x/auth/client/cli", - "x/auth/client/rest", - "x/bank", - "x/bank/client", - "x/bank/client/cli", - "x/bank/client/rest", - "x/ibc", - "x/ibc/client/cli", - "x/ibc/client/rest", - "x/slashing", - "x/slashing/client/cli", - "x/stake", - "x/stake/client/cli", - "x/stake/client/rest" - ] - revision = "1e6d26ad3dce18fd1dde9bbee7d2aa192c196310" - version = "v0.19.1-rc1" - -[[projects]] - name = "github.com/davecgh/go-spew" - packages = ["spew"] - revision = "346938d642f2ec3594ed81d874461961cd0faa76" - version = "v1.1.0" - -[[projects]] - branch = "master" - name = "github.com/ebuchman/fail-test" - packages = ["."] - revision = "95f809107225be108efcf10a3509e4ea6ceef3c4" - -[[projects]] - name = "github.com/fsnotify/fsnotify" - packages = ["."] - revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" - version = "v1.4.7" - -[[projects]] - name = "github.com/go-kit/kit" - packages = [ - "log", - "log/level", - "log/term", - "metrics", - "metrics/internal/lv", - "metrics/prometheus" - ] - revision = "4dc7be5d2d12881735283bcab7352178e190fc71" - version = "v0.6.0" - -[[projects]] - name = "github.com/go-logfmt/logfmt" - packages = ["."] - revision = "390ab7935ee28ec6b286364bba9b4dd6410cb3d5" - version = "v0.3.0" - -[[projects]] - name = "github.com/go-stack/stack" - packages = ["."] - revision = "259ab82a6cad3992b4e21ff5cac294ccb06474bc" - version = "v1.7.0" - -[[projects]] - name = "github.com/gogo/protobuf" - packages = [ - "gogoproto", - "jsonpb", - "proto", - "protoc-gen-gogo/descriptor", - "sortkeys", - "types" - ] - revision = "1adfc126b41513cc696b209667c8656ea7aac67c" - version = "v1.0.0" - -[[projects]] - name = "github.com/golang/protobuf" - packages = [ - "proto", - "ptypes", - "ptypes/any", - "ptypes/duration", - "ptypes/timestamp" - ] - revision = "925541529c1fa6821df4e44ce2723319eb2be768" - version = "v1.0.0" - -[[projects]] - branch = "master" - name = "github.com/golang/snappy" - packages = ["."] - revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" - -[[projects]] - name = "github.com/gorilla/context" - packages = ["."] - revision = "08b5f424b9271eedf6f9f0ce86cb9396ed337a42" - version = "v1.1.1" - -[[projects]] - name = "github.com/gorilla/mux" - packages = ["."] - revision = "e3702bed27f0d39777b0b37b664b6280e8ef8fbf" - version = "v1.6.2" - -[[projects]] - name = "github.com/gorilla/websocket" - packages = ["."] - revision = "ea4d1f681babbce9545c9c5f3d5194a789c89f5b" - version = "v1.2.0" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/hcl" - packages = [ - ".", - "hcl/ast", - "hcl/parser", - "hcl/printer", - "hcl/scanner", - "hcl/strconv", - "hcl/token", - "json/parser", - "json/scanner", - "json/token" - ] - revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" - -[[projects]] - branch = "master" - name = "github.com/howeyc/crc16" - packages = ["."] - revision = "2b2a61e366a66d3efb279e46176e7291001e0354" - -[[projects]] - name = "github.com/inconshreveable/mousetrap" - packages = ["."] - revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75" - version = "v1.0" - -[[projects]] - branch = "master" - name = "github.com/jmhodges/levigo" - packages = ["."] - revision = "c42d9e0ca023e2198120196f842701bb4c55d7b9" - -[[projects]] - branch = "master" - name = "github.com/kr/logfmt" - packages = ["."] - revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0" - -[[projects]] - name = "github.com/magiconair/properties" - packages = [ - ".", - "assert" - ] - revision = "c2353362d570a7bfa228149c62842019201cfb71" - version = "v1.8.0" - -[[projects]] - name = "github.com/mattn/go-isatty" - packages = ["."] - revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" - version = "v0.0.3" - -[[projects]] - name = "github.com/matttproud/golang_protobuf_extensions" - packages = ["pbutil"] - revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" - version = "v1.0.1" - -[[projects]] - branch = "master" - name = "github.com/mitchellh/mapstructure" - packages = ["."] - revision = "bb74f1db0675b241733089d5a1faa5dd8b0ef57b" - -[[projects]] - name = "github.com/pelletier/go-toml" - packages = ["."] - revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194" - version = "v1.2.0" - -[[projects]] - name = "github.com/pkg/errors" - packages = ["."] - revision = "645ef00459ed84a119197bfb8d8205042c6df63d" - version = "v0.8.0" - -[[projects]] - name = "github.com/pmezard/go-difflib" - packages = ["difflib"] - revision = "792786c7400a136282c1664665ae0a8db921c6c2" - version = "v1.0.0" - -[[projects]] - name = "github.com/prometheus/client_golang" - packages = [ - "prometheus", - "prometheus/promhttp" - ] - revision = "c5b7fccd204277076155f10851dad72b76a49317" - version = "v0.8.0" - -[[projects]] - branch = "master" - name = "github.com/prometheus/client_model" - packages = ["go"] - revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c" - -[[projects]] - branch = "master" - name = "github.com/prometheus/common" - packages = [ - "expfmt", - "internal/bitbucket.org/ww/goautoneg", - "model" - ] - revision = "7600349dcfe1abd18d72d3a1770870d9800a7801" - -[[projects]] - branch = "master" - name = "github.com/prometheus/procfs" - packages = [ - ".", - "internal/util", - "nfs", - "xfs" - ] - revision = "40f013a808ec4fa79def444a1a56de4d1727efcb" - -[[projects]] - branch = "master" - name = "github.com/rcrowley/go-metrics" - packages = ["."] - revision = "e2704e165165ec55d062f5919b4b29494e9fa790" - -[[projects]] - name = "github.com/spf13/afero" - packages = [ - ".", - "mem" - ] - revision = "787d034dfe70e44075ccc060d346146ef53270ad" - version = "v1.1.1" - -[[projects]] - name = "github.com/spf13/cast" - packages = ["."] - revision = "8965335b8c7107321228e3e3702cab9832751bac" - version = "v1.2.0" - -[[projects]] - name = "github.com/spf13/cobra" - packages = ["."] - revision = "ef82de70bb3f60c65fb8eebacbb2d122ef517385" - version = "v0.0.3" - -[[projects]] - branch = "master" - name = "github.com/spf13/jwalterweatherman" - packages = ["."] - revision = "7c0cea34c8ece3fbeb2b27ab9b59511d360fb394" - -[[projects]] - name = "github.com/spf13/pflag" - packages = ["."] - revision = "583c0c0531f06d5278b7d917446061adc344b5cd" - version = "v1.0.1" - -[[projects]] - name = "github.com/spf13/viper" - packages = ["."] - revision = "b5e8006cbee93ec955a89ab31e0e3ce3204f3736" - version = "v1.0.2" - -[[projects]] - name = "github.com/stretchr/testify" - packages = [ - "assert", - "require" - ] - revision = "f35b8ab0b5a2cef36673838d662e249dd9c94686" - version = "v1.2.2" - -[[projects]] - branch = "master" - name = "github.com/syndtr/goleveldb" - packages = [ - "leveldb", - "leveldb/cache", - "leveldb/comparer", - "leveldb/errors", - "leveldb/filter", - "leveldb/iterator", - "leveldb/journal", - "leveldb/memdb", - "leveldb/opt", - "leveldb/storage", - "leveldb/table", - "leveldb/util" - ] - revision = "0d5a0ceb10cf9ab89fdd744cc8c50a83134f6697" - -[[projects]] - name = "github.com/tendermint/abci" - packages = [ - "client", - "example/code", - "example/kvstore", - "server", - "types" - ] - revision = "198dccf0ddfd1bb176f87657e3286a05a6ed9540" - version = "v0.12.0" - -[[projects]] - branch = "master" - name = "github.com/tendermint/ed25519" - packages = [ - ".", - "edwards25519", - "extra25519" - ] - revision = "d8387025d2b9d158cf4efb07e7ebf814bcce2057" - -[[projects]] - name = "github.com/tendermint/go-amino" - packages = ["."] - revision = "ed62928576cfcaf887209dc96142cd79cdfff389" - version = "0.9.9" - -[[projects]] - name = "github.com/tendermint/go-crypto" - packages = [ - ".", - "keys", - "keys/bcrypt", - "keys/words", - "keys/words/wordlist" - ] - revision = "915416979bf70efa4bcbf1c6cd5d64c5fff9fc19" - version = "v0.6.2" - -[[projects]] - name = "github.com/tendermint/iavl" - packages = [ - ".", - "sha256truncated" - ] - revision = "c9206995e8f948e99927f5084a88a7e94ca256da" - version = "v0.8.0-rc0" - -[[projects]] - name = "github.com/tendermint/tendermint" - packages = [ - "blockchain", - "cmd/tendermint/commands", - "config", - "consensus", - "consensus/types", - "evidence", - "libs/events", - "libs/pubsub", - "libs/pubsub/query", - "lite", - "lite/client", - "lite/errors", - "lite/files", - "lite/proxy", - "mempool", - "node", - "p2p", - "p2p/conn", - "p2p/pex", - "p2p/upnp", - "privval", - "proxy", - "rpc/client", - "rpc/core", - "rpc/core/types", - "rpc/grpc", - "rpc/lib", - "rpc/lib/client", - "rpc/lib/server", - "rpc/lib/types", - "state", - "state/txindex", - "state/txindex/kv", - "state/txindex/null", - "types", - "version" - ] - revision = "46369a1ab76f274ab47179c4176221842b8207b4" - version = "v0.21.0" - -[[projects]] - name = "github.com/tendermint/tmlibs" - packages = [ - "autofile", - "bech32", - "cli", - "cli/flags", - "clist", - "common", - "db", - "flowrate", - "log", - "merkle", - "merkle/tmhash" - ] - revision = "49596e0a1f48866603813df843c9409fc19805c6" - version = "v0.9.0" - -[[projects]] - branch = "master" - name = "golang.org/x/crypto" - packages = [ - "blowfish", - "curve25519", - "internal/subtle", - "nacl/box", - "nacl/secretbox", - "openpgp/armor", - "openpgp/errors", - "poly1305", - "ripemd160", - "salsa20/salsa" - ] - revision = "a49355c7e3f8fe157a85be2f77e6e269a0f89602" - -[[projects]] - branch = "master" - name = "golang.org/x/net" - packages = [ - "context", - "http/httpguts", - "http2", - "http2/hpack", - "idna", - "internal/timeseries", - "trace" - ] - revision = "ed29d75add3d7c4bf7ca65aac0c6df3d1420216f" - -[[projects]] - branch = "master" - name = "golang.org/x/sys" - packages = ["unix"] - revision = "151529c776cdc58ddbe7963ba9af779f3577b419" - -[[projects]] - name = "golang.org/x/text" - packages = [ - "collate", - "collate/build", - "internal/colltab", - "internal/gen", - "internal/tag", - "internal/triegen", - "internal/ucd", - "language", - "secure/bidirule", - "transform", - "unicode/bidi", - "unicode/cldr", - "unicode/norm", - "unicode/rangetable" - ] - revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" - version = "v0.3.0" - -[[projects]] - name = "google.golang.org/genproto" - packages = ["googleapis/rpc/status"] - revision = "7fd901a49ba6a7f87732eb344f6e3c5b19d1b200" - -[[projects]] - name = "google.golang.org/grpc" - packages = [ - ".", - "balancer", - "codes", - "connectivity", - "credentials", - "grpclb/grpc_lb_v1/messages", - "grpclog", - "internal", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "stats", - "status", - "tap", - "transport" - ] - revision = "5b3c4e850e90a4cf6a20ebd46c8b32a0a3afcb9e" - version = "v1.7.5" - -[[projects]] - name = "gopkg.in/yaml.v2" - packages = ["."] - revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" - version = "v2.2.1" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - inputs-digest = "d1273093894dceda82a36f80e217187acee7f2f34b020c05fb89352ff249c850" - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml deleted file mode 100644 index f5ce9e94b..000000000 --- a/Gopkg.toml +++ /dev/null @@ -1,70 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" -# -# [prune] -# non-go = false -# go-tests = true -# unused-packages = true - -[[constraint]] - name = "github.com/spf13/cobra" - version = "~0.0.1" - -[[constraint]] - name = "github.com/spf13/viper" - version = "~1.0.0" - -[[constraint]] - name = "github.com/cosmos/cosmos-sdk" - version = "v0.19.1-rc1" - -[[constraint]] - name = "github.com/tendermint/abci" - version = "=0.12.0" - -[[constraint]] - name = "github.com/tendermint/go-crypto" - version = "=0.6.2" - -[[constraint]] - name = "github.com/tendermint/tendermint" - version = "=0.21.0" - -[[override]] - name = "github.com/tendermint/tmlibs" - version = "=v0.9.0" - -[[override]] - name = "github.com/tendermint/iavl" - version = "=0.8.0-rc0" - -# this got updated and broke, so locked to an old working commit ... -[[override]] - name = "google.golang.org/genproto" - revision = "7fd901a49ba6a7f87732eb344f6e3c5b19d1b200" - -[[constraint]] - name = "github.com/prometheus/client_golang" - version = "0.8.0" - -[prune] - go-tests = true - unused-packages = true \ No newline at end of file diff --git a/Makefile b/Makefile index 345f80662..7295df83b 100644 --- a/Makefile +++ b/Makefile @@ -1,18 +1,17 @@ -all: get_vendor_deps install +all: get_vendor_deps install test get_vendor_deps: - @rm -rf vendor/ - @echo "--> Running dep ensure" - @dep ensure -v - + go get github.com/Masterminds/glide + glide install + install: go install ./cmd/iris - go install ./cmd/iriscli build_linux: - CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iris ./cmd/iris && \ - CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iriscli ./cmd/iriscli + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iris ./cmd/iris + +test: + @go test `glide novendor` -build_cur: - go build -o build/iris ./cmd/iris && \ - go build -o build/iriscli ./cmd/iriscli +test_cli: + bash ./cmd/iris/sh_tests/stake.sh diff --git a/README.md b/README.md index 06606302f..049404cc0 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,136 @@ -# IRIS-Hub - -IRIS Hub是在Cosmos生态中的区域性枢纽,提供iService服务 +# Iris-Hub +Iris Hub是在Cosmos生态中的区域性枢纽,提供iService服务 ## 下载发行版安装 - -- 进入下载页: https://github.com/irisnet/irishub/releases/ -- 下载对应版本的可执行文件 -- 解压缩`tar -C /usr/local/bin -xzf iris$VERSION.$OS-$ARCH.zip` -- 拷贝到`/usr/local/bin/`目录下 - 执行 - -``` + * 进入下载页: https://github.com/irisnet/iris-hub/releases/tag/0.1.0 + * 下载对应版本的可执行文件 + * 解压缩`tar -C /usr/local -xzf iris$VERSION.$OS-$ARCH.zip` + * 拷贝到`/usr/local/`目录下 +执行 + ``` iris version -``` + ``` -若出现对应的版本号则说明安装成功 +若出现`v 0.1.0`则说明安装成功 ## 通过源码编译安装 ### 系统要求 - 操作系统:**Ubuntu 16.04** 架构:**amd64** 要求安装1.9版本以上的Go https://golang.org/doc/install -### 安装步骤 +GO 安装步骤 +* 下载 +curl -O https://dl.google.com/go/go1.9.4.linux-386.tar.gz + +* 解压缩 ``` -go get github.com/irisnet/irishub -cd $GOPATH/src/github.com/irisnet/irishub -make all -iris version +tar xvf go1.9.4.linux-386.tar.gz +``` + +* 获得权限 ``` +sudo chown -R root:root ./go -若出现对应的版本号则说明安装成功 +sudo mv go /usr/local +``` -### 本地测试网络 +* 设置GOPATH +``` +export GOPATH=$HOME/work +export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin +``` -1. 初始化irishub: +* 测试是否安装成功 +建立一个简单的工程。 ``` -MYNAME1= -iris init --chain-id=test --name=$MYNAME1 --home=$HOME/.iris1 +mkdir -p work/src/github.com/user/hello ``` -以上命令将在 `$HOME/.iris1/config`目录下创建默认的配置文件 `priv_validator.json`和`genesis.json`。`priv_validator.json` 包含验证人的私钥。`genesis.json`文件包含其他配置信息, 包括创世账户,创世账户的默认密码为`1234567890`,创世账户的助记词会在执行以上命令后输出在控制台,例如: +创建 "Hello World" Go文件. + ``` -{ - "chain_id": "test", - "node_id": "e4bcb3c7df9783d32c8a876028a45952b4146c78", - "app_message": { - "secret": "spare detail grass load memory robust expect plunge thank hen limb electric town slot annual abandon" - } +nano ~/work/src/github.com/user/hello/hello.go +``` +修改文件内容如下: + +``` +package main + +import "fmt" + +func main() { + fmt.Printf("hello, world\n") } ``` +编译&安装 +``` +go install github.com/user/hello +``` +执行命令 +``` +hello +``` +如果安装成功,将会出现 "hello, world"输出: + -其中secret便是创世账户的助记词,可以导入该助记词到iris客户端以重置密码: +## 安装步骤 ``` -iriscli keys add $MYNAME1 --recover -override the existing name XXX [y/n]: y -Enter a passphrase for your key: -Repeat the passphrase: -Enter your recovery seed phrase: +go get github.com/irisnet/iris-hub +cd $GOPATH/src/github.com/irisnet/iris-hub +make all +iris version ``` -1. 启动irishub: +若出现`v 0.1.0`则说明安装成功 + +###本地测试网络 + +Here is a quick example to get you off your feet: + +1. 生成和保存测试网络中的测试账户 ``` -iris start --home=$HOME/.iris1 +MYNAME= +iris client keys new $MYNAME +iris client keys list +MYADDR= ``` +2. 初始化iris-hub: -1. 多节点配置: +``` +iris node init $MYADDR --home=$HOME/.iris1 --chain-id=test +``` + +This will create all the files necessary to run a single node chain in以上命令将在 `$HOME/.iris1/config`目录下创建默认的配置文件 `priv_validator.json`和`genesis.json`。`priv_validator.json` 包含验证人的私钥。`genesis.json`文件包含其他配置信息, `$MYADDR`是默认生成的创世账户。 + +获得节点的Node_ID + +需要下载编辑develop分支的tendermint,或者下载可执行[[文件](https://github.com/kidinamoto01/gaia-testnet/blob/master/gaia-testnet/tendermint-develop-liunx-amd64.zip)] + +执行以下命令获得iris1的Node_ID +``` +tendermint show_node_id --home=$HOME/.iris1 +``` 同时,你也可以在本地再运行另一个Node,注意新的Node所对应的工作目录不同,但二者公用一个genesis文件。 + ``` -MYNAME2= -iris init --chain-id=test --name=$MYNAME2 --home=$HOME/.iris2 +iris node init $MYADDR --home=$HOME/.iris2 --chain-id=test cp $HOME/.iris1/config/genesis.json $HOME/.iris2/config/genesis.json ``` -修改 `$HOME/.iris2/config/config.toml` ,防止端口冲突,并让两个Node可以发现彼此: +修改 `$HOME/.iris2/config/config.toml` 让两个Node可以发现彼此: ``` proxy_app = "tcp://127.0.0.1:46668" @@ -103,82 +147,105 @@ laddr = "tcp://0.0.0.0:46666" seeds = "@0.0.0.0:46656" ``` -其中node_id可以通过以下命令获取: - -``` -iris tendermint show_node_id --home=$HOME/.iris1 -iris tendermint show_node_id --home=$HOME/.iris2 -``` - 然后就可以同时在后台运行: ``` -iris start --home=$HOME/.iris1 &> iris1.log & NODE1_PID=$! -iris start --home=$HOME/.iris2 &> iris2.log & NODE2_PID=$! +iris node start --home=$HOME/.iris1 &> iris1.log & +NODE1_PID=$! +iris node start --home=$HOME/.iris2 &> iris2.log & +NODE2_PID=$! ``` `PID` 是为了方便之后杀死相关进程。 通过 `tail iris1.log`,或 `tail -f iris1.log`可以对Node 进行监控。 -1. 现在我们可以使用客户端进行操作 - -查询本地账户: +现在我们初始化客户端,然后查询账户: ``` -iriscli keys list +iris client init --chain-id=test --node=tcp://localhost:46657 +iris client query account $MYADDR ``` -查询账户余额: +我们可以测试在账户间转账: ``` -iriscli account
+MYNAME1= +iris client keys new $MYNAME1 +iris client keys list +MYADDR1= +iris client tx send --amount=1000fermion --to=$MYADDR1 --name=$MYNAME +iris client query $MYADDR1 +iris client query $MYADDR ``` -我们可以测试在账户间转账: +也可以查询 candidate列表: ``` -iriscli send --name=$MYNAME1 --to=$MYADDR2 --amount=10steak --chain-id=test -iriscli account $MYADDR1 -iriscli account $MYADDR2 +iris client query candidates ``` -也可以查询Validator列表: +很奇怪的是,iris并没有发现initial时生成的validator。这是因为这类validator比较特殊。通过查询tendermint接口,你可以获得初始的validator信息。 ``` -iriscli stake validators +curl localhost:46657/validators ``` 接下来实现第一个validator的添加:首先获得节点的公钥: ``` -iris tendermint show_validator --home=$HOME/.iris2 +cat $HOME/.iris1/config/priv_validator.json ``` -通过执行以下命令完成绑定: +使用`jq`命令可以快速获得公钥: + +``` +cat $HOME/.iris1/config/priv_validator.json | jq .pub_key.data ``` -iriscli stake create-validator --amount=10steak --pubkey= --address-validator= --moniker= --chain-id=test --name= + +通过执行以下命令完成绑定 ``` +iris client tx declare-candidacy --amount=1fermion --pubkey= --moniker= --name=$MYNAME -再次查询 Validator列表: +``` +再次查询 candidate列表: ``` -iriscli stake validators +iris client query candidates ``` +也可以查询具体的validator信息 -通过以下命令为Validator添加更多信息: +``` +iris client query candidate --pubkey= +``` + +查询初始账户的变化,candidates页有变化: + +``` +iris client query account $MYADDR +iris client query candidates +``` + +通过以下命令可以修改绑定的金额 +``` +iris client tx edit-candidacy --pubkey= --moniker= --name=$MYNAME +``` +通过unbond可将抵押的代币收回,你会发现账户余额增加了。 ``` -iriscli stake edit-validator --details="To the IRISnet !" --website="https://irisnet.org" +iris client tx unbond --shares=1 --pubkey= --name=$MYNAME +iris client query validators +iris client query account $MYADDR ``` +同样的,你也可以绑定用$HOME/.iris2/config/priv_validator.json代表的第二个Node +通过查询tendermint接口,你可以获得新的validator信息。 -检查Validator是否生效: ``` -iriscli advanced tendermint validator-set +curl localhost:46657/validators ``` -如果你杀死了第一个Node,那么区块链将无法继续生成新的块。这是因为只有保证Voting Power总数超过 2/3 的节点在线的情况下,才能达成共识。 +如果你杀死了第二个Node,那么区块链将无法继续生成新的块。这是因为只有保证2/3节点在线的情况下,才能达成共识。 -将第一个节点重新启动,那么区块链会回归正常。 \ No newline at end of file +将第二个节点重新启动,那么区块链会回归正常。 \ No newline at end of file diff --git a/app/app.go b/app/app.go deleted file mode 100644 index c5072a53c..000000000 --- a/app/app.go +++ /dev/null @@ -1,181 +0,0 @@ -package app - -import ( - "encoding/json" - "os" - - abci "github.com/tendermint/abci/types" - tmtypes "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tmlibs/common" - dbm "github.com/tendermint/tmlibs/db" - "github.com/tendermint/tmlibs/log" - - bam "github.com/cosmos/cosmos-sdk/baseapp" - 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/bank" - "github.com/cosmos/cosmos-sdk/x/ibc" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/stake" -) - -const ( - appName = "IrisApp" -) - -// default home directories for expected binaries -var ( - DefaultCLIHome = os.ExpandEnv("$HOME/.iriscli") - DefaultNodeHome = os.ExpandEnv("$HOME/.iris") -) - -// Extended ABCI application -type IrisApp struct { - *bam.BaseApp - cdc *wire.Codec - - // keys to access the substores - keyMain *sdk.KVStoreKey - keyAccount *sdk.KVStoreKey - keyIBC *sdk.KVStoreKey - keyStake *sdk.KVStoreKey - keySlashing *sdk.KVStoreKey - - // Manage getting and setting accounts - accountMapper auth.AccountMapper - feeCollectionKeeper auth.FeeCollectionKeeper - coinKeeper bank.Keeper - ibcMapper ibc.Mapper - stakeKeeper stake.Keeper - slashingKeeper slashing.Keeper -} - -func NewIrisApp(logger log.Logger, db dbm.DB) *IrisApp { - cdc := MakeCodec() - - // create your application object - var app = &IrisApp{ - BaseApp: bam.NewBaseApp(appName, cdc, logger, db), - cdc: cdc, - keyMain: sdk.NewKVStoreKey("main"), - keyAccount: sdk.NewKVStoreKey("acc"), - keyIBC: sdk.NewKVStoreKey("ibc"), - keyStake: sdk.NewKVStoreKey("stake"), - keySlashing: sdk.NewKVStoreKey("slashing"), - } - - // define the accountMapper - app.accountMapper = auth.NewAccountMapper( - app.cdc, - app.keyAccount, // target store - &auth.BaseAccount{}, // prototype - ) - - // add handlers - app.coinKeeper = bank.NewKeeper(app.accountMapper) - app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace)) - app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) - app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.RegisterCodespace(slashing.DefaultCodespace)) - - // register message routes - app.Router(). - AddRoute("bank", bank.NewHandler(app.coinKeeper)). - AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)). - AddRoute("stake", stake.NewHandler(app.stakeKeeper)). - AddRoute("slashing", slashing.NewHandler(app.slashingKeeper)) - - // initialize BaseApp - app.SetInitChainer(app.initChainer) - app.SetBeginBlocker(app.BeginBlocker) - app.SetEndBlocker(app.EndBlocker) - app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) - app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing) - err := app.LoadLatestVersion(app.keyMain) - if err != nil { - cmn.Exit(err.Error()) - } - - return app -} - -// custom tx codec -func MakeCodec() *wire.Codec { - var cdc = wire.NewCodec() - ibc.RegisterWire(cdc) - bank.RegisterWire(cdc) - stake.RegisterWire(cdc) - slashing.RegisterWire(cdc) - auth.RegisterWire(cdc) - sdk.RegisterWire(cdc) - wire.RegisterCrypto(cdc) - return cdc -} - -// application updates every end block -func (app *IrisApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) - - return abci.ResponseBeginBlock{ - Tags: tags.ToKVPairs(), - } -} - -// application updates every end block -func (app *IrisApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) - - return abci.ResponseEndBlock{ - ValidatorUpdates: validatorUpdates, - } -} - -// custom logic for gaia initialization -func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { - stateJSON := req.AppStateBytes - // TODO is this now the whole genesis file? - - var genesisState GenesisState - err := app.cdc.UnmarshalJSON(stateJSON, &genesisState) - if err != nil { - panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 - // return sdk.ErrGenesisParse("").TraceCause(err, "") - } - - // load the accounts - for _, gacc := range genesisState.Accounts { - acc := gacc.ToAccount() - acc.AccountNumber = app.accountMapper.GetNextAccountNumber(ctx) - app.accountMapper.SetAccount(ctx, acc) - } - - // load the initial stake information - stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData) - - return abci.ResponseInitChain{} -} - -// export the state of gaia for a genesis file -func (app *IrisApp) ExportAppStateAndValidators() (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) { - ctx := app.NewContext(true, abci.Header{}) - - // iterate to get the accounts - accounts := []GenesisAccount{} - appendAccount := func(acc auth.Account) (stop bool) { - account := NewGenesisAccountI(acc) - accounts = append(accounts, account) - return false - } - app.accountMapper.IterateAccounts(ctx, appendAccount) - - genState := GenesisState{ - Accounts: accounts, - StakeData: stake.WriteGenesis(ctx, app.stakeKeeper), - } - appState, err = wire.MarshalJSONIndent(app.cdc, genState) - if err != nil { - return nil, nil, err - } - validators = stake.WriteValidators(ctx, app.stakeKeeper) - return appState, validators, nil -} diff --git a/app/context.go b/app/context.go deleted file mode 100644 index e53eee28d..000000000 --- a/app/context.go +++ /dev/null @@ -1,28 +0,0 @@ -package app - -import ( - "github.com/cosmos/cosmos-sdk/client/context" - ctypes "github.com/tendermint/tendermint/rpc/core/types" -) - -type Context struct { - ctx context.CoreContext -} - -func (c Context) BroadcastTxAsync(tx []byte) (*ctypes.ResultBroadcastTx, error) { - return c.ctx.Client.BroadcastTxAsync(tx) -} - -func (c Context) BroadcastTxSync(tx []byte) (*ctypes.ResultBroadcastTx, error) { - return c.ctx.Client.BroadcastTxSync(tx) -} - -func (c Context) GetCosmosCtx() context.CoreContext { - return c.ctx -} - -func NewContext() Context { - return Context{ - context.NewCoreContextFromViper(), - } -} diff --git a/app/genesis.go b/app/genesis.go deleted file mode 100644 index 924cfdebc..000000000 --- a/app/genesis.go +++ /dev/null @@ -1,231 +0,0 @@ -package app - -import ( - "encoding/json" - "errors" - - "github.com/spf13/pflag" - "github.com/spf13/viper" - crypto "github.com/tendermint/go-crypto" - tmtypes "github.com/tendermint/tendermint/types" - - "github.com/cosmos/cosmos-sdk/server" - 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" -) - -// State to Unmarshal -type GenesisState struct { - Accounts []GenesisAccount `json:"accounts"` - StakeData stake.GenesisState `json:"stake"` -} - -// GenesisAccount doesn't need pubkey or sequence -type GenesisAccount struct { - Address sdk.Address `json:"address"` - Coins sdk.Coins `json:"coins"` -} - -func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount { - return GenesisAccount{ - Address: acc.Address, - Coins: acc.Coins, - } -} - -func NewGenesisAccountI(acc auth.Account) GenesisAccount { - return GenesisAccount{ - Address: acc.GetAddress(), - Coins: acc.GetCoins(), - } -} - -// convert GenesisAccount to auth.BaseAccount -func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { - return &auth.BaseAccount{ - Address: ga.Address, - Coins: ga.Coins.Sort(), - } -} - -var ( - flagName = "name" - flagClientHome = "home-client" - flagOWK = "owk" - denom = "iris" - - // bonded tokens given to genesis validators/accounts - freeFermionVal = int64(100) - - totalTokenAmt = int64(200000000) -) - -// get app init parameters for server init command -func IrisAppInit() server.AppInit { - fsAppGenState := pflag.NewFlagSet("", pflag.ContinueOnError) - - fsAppGenTx := pflag.NewFlagSet("", pflag.ContinueOnError) - fsAppGenTx.String(flagName, "", "validator moniker, required") - fsAppGenTx.String(flagClientHome, DefaultCLIHome, - "home directory for the client, used for key generation") - fsAppGenTx.Bool(flagOWK, false, "overwrite the accounts created") - - return server.AppInit{ - FlagsAppGenState: fsAppGenState, - FlagsAppGenTx: fsAppGenTx, - AppGenTx: IrisAppGenTx, - AppGenState: IrisAppGenStateJSON, - } -} - -// simple genesis tx -type IrisGenTx struct { - Name string `json:"name"` - Address sdk.Address `json:"address"` - PubKey crypto.PubKey `json:"pub_key"` -} - -// Generate a gaia genesis transaction with flags -func IrisAppGenTx(cdc *wire.Codec, pk crypto.PubKey) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - clientRoot := viper.GetString(flagClientHome) - overwrite := viper.GetBool(flagOWK) - name := viper.GetString(flagName) - if name == "" { - return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)") - } - - var addr sdk.Address - var secret string - addr, secret, err = server.GenerateSaveCoinKey(clientRoot, name, "1234567890", overwrite) - if err != nil { - return - } - mm := map[string]string{"secret": secret} - var bz []byte - bz, err = cdc.MarshalJSON(mm) - if err != nil { - return - } - cliPrint = json.RawMessage(bz) - appGenTx, _, validator, err = IrisAppGenTxNF(cdc, pk, addr, name, overwrite) - return -} - -// Generate a gaia genesis transaction without flags -func IrisAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.Address, name string, overwrite bool) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - - var bz []byte - gaiaGenTx := IrisGenTx{ - Name: name, - Address: addr, - PubKey: pk, - } - bz, err = wire.MarshalJSONIndent(cdc, gaiaGenTx) - if err != nil { - return - } - appGenTx = json.RawMessage(bz) - - validator = tmtypes.GenesisValidator{ - PubKey: pk, - Power: freeFermionVal, - } - return -} - -// Create the core parameters for genesis initialization for gaia -// note that the pubkey input is this machines pubkey -func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState GenesisState, err error) { - - if len(appGenTxs) == 0 { - err = errors.New("must provide at least genesis transaction") - return - } - - // start with the default staking genesis state - //stakeData := stake.DefaultGenesisState() - stakeData := stake.DefaultGenesisState() - - // get genesis flag account information - genaccs := make([]GenesisAccount, len(appGenTxs)) - for i, appGenTx := range appGenTxs { - - var genTx IrisGenTx - err = cdc.UnmarshalJSON(appGenTx, &genTx) - if err != nil { - return - } - - // create the genesis account, give'm few steaks and a buncha token with there name - accAuth := auth.NewBaseAccountWithAddress(genTx.Address) - accAuth.Coins = sdk.Coins{ - {denom, totalTokenAmt}, - {"steak", freeFermionVal}, - } - acc := NewGenesisAccount(&accAuth) - genaccs[i] = acc - stakeData.Pool.LooseUnbondedTokens += freeFermionVal // increase the supply - - // add the validator - if len(genTx.Name) > 0 { - desc := stake.NewDescription(genTx.Name, "", "", "") - validator := stake.NewValidator(genTx.Address, genTx.PubKey, desc) - validator.PoolShares = stake.NewBondedShares(sdk.NewRat(freeFermionVal)) - stakeData.Validators = append(stakeData.Validators, validator) - - // pool logic - stakeData.Pool.BondedTokens += freeFermionVal - stakeData.Pool.BondedShares = sdk.NewRat(stakeData.Pool.BondedTokens) - } - } - - // create the final app state - genesisState = GenesisState{ - Accounts: genaccs, - StakeData: stakeData, - } - return -} - -// IrisAppGenState but with JSON -func IrisAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) { - - // create the final app state - genesisState, err := IrisAppGenState(cdc, appGenTxs) - if err != nil { - return nil, err - } - appState, err = wire.MarshalJSONIndent(cdc, genesisState) - return -} - -// TODO -func createGenesisState() stake.GenesisState { - return stake.GenesisState{ - Pool: stake.Pool{ - LooseUnbondedTokens: 0, - BondedTokens: 0, - UnbondingTokens: 0, - UnbondedTokens: 0, - BondedShares: sdk.ZeroRat(), - UnbondingShares: sdk.ZeroRat(), - UnbondedShares: sdk.ZeroRat(), - InflationLastTime: 0, - Inflation: sdk.NewRat(7, 100), - DateLastCommissionReset: 0, - PrevBondedShares: sdk.ZeroRat(), - }, - Params: stake.Params{ - InflationRateChange: sdk.NewRat(13, 100), - InflationMax: sdk.NewRat(20, 100), - InflationMin: sdk.NewRat(7, 100), - GoalBonded: sdk.NewRat(67, 100), - MaxValidators: 100, - BondDenom: "steak", - }, - } -} diff --git a/cmd/iris/client.go b/cmd/iris/client.go new file mode 100644 index 000000000..b79d9b6a0 --- /dev/null +++ b/cmd/iris/client.go @@ -0,0 +1,97 @@ +package main + +import ( + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client/commands" + "github.com/cosmos/cosmos-sdk/client/commands/commits" + "github.com/cosmos/cosmos-sdk/client/commands/keys" + "github.com/cosmos/cosmos-sdk/client/commands/proxy" + "github.com/cosmos/cosmos-sdk/client/commands/query" + rpccmd "github.com/cosmos/cosmos-sdk/client/commands/rpc" + txcmd "github.com/cosmos/cosmos-sdk/client/commands/txs" + authcmd "github.com/cosmos/cosmos-sdk/modules/auth/commands" + basecmd "github.com/cosmos/cosmos-sdk/modules/base/commands" + coincmd "github.com/cosmos/cosmos-sdk/modules/coin/commands" + feecmd "github.com/cosmos/cosmos-sdk/modules/fee/commands" + ibccmd "github.com/cosmos/cosmos-sdk/modules/ibc/commands" + noncecmd "github.com/cosmos/cosmos-sdk/modules/nonce/commands" + rolecmd "github.com/cosmos/cosmos-sdk/modules/roles/commands" + + stakecmd "github.com/MrXJC/gaia/modules/stake/commands" +) + +// clientCmd is the entry point for this binary +var clientCmd = &cobra.Command{ + Use: "client", + Short: "Iris light client", + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} + +func prepareClientCommands() { + commands.AddBasicFlags(clientCmd) + + // Prepare queries + query.RootCmd.AddCommand( + // These are default parsers, but optional in your app (you can remove key) + query.TxQueryCmd, + query.KeyQueryCmd, + coincmd.AccountQueryCmd, + noncecmd.NonceQueryCmd, + rolecmd.RoleQueryCmd, + ibccmd.IBCQueryCmd, + + //stakecmd.CmdQueryValidator, + stakecmd.CmdQueryCandidates, + stakecmd.CmdQueryCandidate, + stakecmd.CmdQueryDelegatorBond, + stakecmd.CmdQueryDelegatorCandidates, + ) + + // set up the middleware + txcmd.Middleware = txcmd.Wrappers{ + feecmd.FeeWrapper{}, + rolecmd.RoleWrapper{}, + noncecmd.NonceWrapper{}, + basecmd.ChainWrapper{}, + authcmd.SigWrapper{}, + } + txcmd.Middleware.Register(txcmd.RootCmd.PersistentFlags()) + + // you will always want this for the base send command + txcmd.RootCmd.AddCommand( + // This is the default transaction, optional in your app + coincmd.SendTxCmd, + coincmd.CreditTxCmd, + // this enables creating roles + rolecmd.CreateRoleTxCmd, + // these are for handling ibc + ibccmd.RegisterChainTxCmd, + ibccmd.UpdateChainTxCmd, + ibccmd.PostPacketTxCmd, + + stakecmd.CmdDeclareCandidacy, + stakecmd.CmdEditCandidacy, + stakecmd.CmdDelegate, + stakecmd.CmdUnbond, + ) + + clientCmd.AddCommand( + proxy.RootCmd, + lineBreak, + + txcmd.RootCmd, + query.RootCmd, + rpccmd.RootCmd, + lineBreak, + + keys.RootCmd, + commands.InitCmd, + commands.ResetCmd, + commits.RootCmd, + lineBreak, + ) + +} diff --git a/cmd/iris/main.go b/cmd/iris/main.go index acba3c88b..c53e37231 100644 --- a/cmd/iris/main.go +++ b/cmd/iris/main.go @@ -1,64 +1,50 @@ package main import ( - "encoding/json" + "os" "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/server" - "github.com/irisnet/irishub/app" - "github.com/irisnet/irishub/version" - abci "github.com/tendermint/abci/types" - tmtypes "github.com/tendermint/tendermint/types" "github.com/tendermint/tmlibs/cli" - dbm "github.com/tendermint/tmlibs/db" - "github.com/tendermint/tmlibs/log" + + basecmd "github.com/cosmos/cosmos-sdk/server/commands" + "github.com/irisnet/iris-hub/version" ) -func main() { - cdc := app.MakeCodec() - ctx := server.NewDefaultContext() - cobra.EnableCommandSorting = false - rootCmd := &cobra.Command{ - Use: "iris", - Short: "iris Daemon (server)", - PersistentPreRunE: server.PersistentPreRunEFn(ctx), +// IrisCmd is the entry point for this binary +var ( + IrisCmd = &cobra.Command{ + Use: "iris", + Short: "IRIS Hub - a regional Cosmos Hub with a powerful iService infrastructure", + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, } - rootCmd.PersistentFlags().String("log_level", ctx.Config.LogLevel, "Log level") + lineBreak = &cobra.Command{Run: func(*cobra.Command, []string) {}} +) - tendermintCmd := &cobra.Command{ - Use: "tendermint", - Short: "Tendermint subcommands", - } +func main() { + // disable sorting + cobra.EnableCommandSorting = false - tendermintCmd.AddCommand( - server.ShowNodeIDCmd(ctx), - server.ShowValidatorCmd(ctx), - ) + // add commands + prepareNodeCommands() + prepareRestServerCommands() + prepareClientCommands() + + IrisCmd.AddCommand( + nodeCmd, + restServerCmd, + clientCmd, - rootCmd.AddCommand( - server.InitCmd(ctx, cdc, app.IrisAppInit()), - server.StartCmd(ctx, server.ConstructAppCreator(newApp, "iris")), - server.UnsafeResetAllCmd(ctx), - client.LineBreak, - tendermintCmd, - server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), - client.LineBreak, + lineBreak, version.VersionCmd, + //auto.AutoCompleteCmd, ) // prepare and add flags - executor := cli.PrepareBaseCmd(rootCmd, "IRIS", app.DefaultNodeHome) + basecmd.SetUpRoot(IrisCmd) + executor := cli.PrepareMainCmd(IrisCmd, "GA", os.ExpandEnv("$HOME/.iris-cli")) executor.Execute() } - -func newApp(logger log.Logger, db dbm.DB) abci.Application { - return app.NewIrisApp(logger, db) -} - -func exportAppStateAndTMValidators(logger log.Logger, db dbm.DB) (json.RawMessage, []tmtypes.GenesisValidator, error) { - irisApp := app.NewIrisApp(logger, db) - return irisApp.ExportAppStateAndValidators() -} diff --git a/cmd/iris/node.go b/cmd/iris/node.go new file mode 100644 index 000000000..ece739afb --- /dev/null +++ b/cmd/iris/node.go @@ -0,0 +1,69 @@ +package main + +import ( + "github.com/spf13/cobra" + + abci "github.com/tendermint/abci/types" + + sdk "github.com/cosmos/cosmos-sdk" + "github.com/cosmos/cosmos-sdk/modules/auth" + "github.com/cosmos/cosmos-sdk/modules/base" + "github.com/cosmos/cosmos-sdk/modules/coin" + "github.com/cosmos/cosmos-sdk/modules/fee" + "github.com/cosmos/cosmos-sdk/modules/ibc" + "github.com/cosmos/cosmos-sdk/modules/nonce" + "github.com/cosmos/cosmos-sdk/modules/roles" + basecmd "github.com/cosmos/cosmos-sdk/server/commands" + "github.com/cosmos/cosmos-sdk/stack" + "github.com/cosmos/cosmos-sdk/state" + + "github.com/MrXJC/gaia/modules/stake" +) + +// nodeCmd is the entry point for this binary +var nodeCmd = &cobra.Command{ + Use: "node", + Short: "The Cosmos Network delegation-game blockchain test", + Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, +} + +func prepareNodeCommands() { + + basecmd.Handler = stack.New( + base.Logger{}, + stack.Recovery{}, + auth.Signatures{}, + base.Chain{}, + stack.Checkpoint{OnCheck: true}, + nonce.ReplayCheck{}, + ). + IBC(ibc.NewMiddleware()). + Apps( + roles.NewMiddleware(), + fee.NewSimpleFeeMiddleware(coin.Coin{"fermion", 0}, fee.Bank), + stack.Checkpoint{OnDeliver: true}, + ). + Dispatch( + coin.NewHandler(), + stack.WrapHandler(roles.NewHandler()), + stack.WrapHandler(ibc.NewHandler()), + stake.NewHandler(), + ) + + nodeCmd.AddCommand( + basecmd.GetInitCmd("fermion", []string{"stake/allowed_bond_denom/fermion"}), + basecmd.GetTickStartCmd(sdk.TickerFunc(tickFn)), + basecmd.UnsafeResetAllCmd, + ) +} + +// Tick - Called every block even if no transaction, process all queues, +// validator rewards, and calculate the validator set difference +func tickFn(ctx sdk.Context, store state.SimpleDB) (change []abci.Validator, err error) { + // first need to prefix the store, at this point it's a global store + store = stack.PrefixedStore(stake.Name(), store) + + // execute Tick + change, err = stake.UpdateValidatorSet(store) + return +} diff --git a/cmd/iris/rest.go b/cmd/iris/rest.go new file mode 100644 index 000000000..9ca8d7a7b --- /dev/null +++ b/cmd/iris/rest.go @@ -0,0 +1,95 @@ +package main + +import ( + "fmt" + "log" + "net/http" + + "github.com/gorilla/mux" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/tendermint/tmlibs/cli" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/commands" + rest "github.com/cosmos/cosmos-sdk/client/rest" + restTxs "github.com/irisnet/iris-hub/module/rest-txs" + byteTx "github.com/irisnet/iris-hub/rest" + coinrest "github.com/cosmos/cosmos-sdk/modules/coin/rest" + noncerest "github.com/cosmos/cosmos-sdk/modules/nonce/rest" + rolerest "github.com/cosmos/cosmos-sdk/modules/roles/rest" + + stakerest "github.com/MrXJC/gaia/modules/stake/rest" +) + +const defaultAlgo = "ed25519" + +var ( + restServerCmd = &cobra.Command{ + Use: "rest-server", + Short: "REST client for iris commands", + Long: `Irisserver presents a nice (not raw hex) interface to the iris blockchain structure.`, + RunE: func(cmd *cobra.Command, args []string) error { + return cmdRestServer(cmd, args) + }, + } + + flagPort = "port" +) + +func prepareRestServerCommands() { + commands.AddBasicFlags(restServerCmd) + restServerCmd.PersistentFlags().IntP(flagPort, "p", 8998, "port to run the server on") +} + +func cmdRestServer(cmd *cobra.Command, args []string) error { + router := mux.NewRouter() + + rootDir := viper.GetString(cli.HomeFlag) + keyMan := client.GetKeyManager(rootDir) + serviceKeys := rest.NewServiceKeys(keyMan) + serviceByteTx := byteTx.NewServiceByteTx(keyMan) + serviceTxs := restTxs.NewServiceTxs(commands.GetNode()) + + routeRegistrars := []func(*mux.Router) error{ + // rest.Keys handlers + serviceKeys.RegisterCRUD, + + // Coin handlers (Send, Query, SearchSent) + coinrest.RegisterAll, + + // Roles createRole handler + rolerest.RegisterCreateRole, + + // Iris sign transactions handler + serviceKeys.RegisterSignTx, + // Iris post transaction handler + serviceTxs.RegisterPostTx, + + // Iris transfer Tx to byte[] + serviceByteTx.RegisterByteTx, + + // Nonce query handler + noncerest.RegisterQueryNonce, + + // Staking query handlers + stakerest.RegisterQueryCandidate, + stakerest.RegisterQueryCandidates, + stakerest.RegisterQueryDelegatorBond, + stakerest.RegisterQueryDelegatorCandidates, + // Staking tx builders + stakerest.RegisterDelegate, + stakerest.RegisterUnbond, + } + + for _, routeRegistrar := range routeRegistrars { + if err := routeRegistrar(router); err != nil { + log.Fatal(err) + } + } + + addr := fmt.Sprintf(":%d", viper.GetInt(flagPort)) + + log.Printf("Serving on %q", addr) + return http.ListenAndServe(addr, router) +} diff --git a/cmd/iris/rest_test.go b/cmd/iris/rest_test.go new file mode 100644 index 000000000..b643f455c --- /dev/null +++ b/cmd/iris/rest_test.go @@ -0,0 +1,77 @@ +package main + +import ( + "fmt" + "log" + "net/http" + + "github.com/spf13/viper" + "github.com/gorilla/mux" + "testing" + "github.com/tendermint/tmlibs/cli" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/commands" + rest "github.com/cosmos/cosmos-sdk/client/rest" + byteTx "github.com/irisnet/iris-hub/rest" + coinrest "github.com/cosmos/cosmos-sdk/modules/coin/rest" + noncerest "github.com/cosmos/cosmos-sdk/modules/nonce/rest" + rolerest "github.com/cosmos/cosmos-sdk/modules/roles/rest" + + stakerest "github.com/MrXJC/gaia/modules/stake/rest" +) + +func TestRest(t *testing.T) { + + + router := mux.NewRouter() + + rootDir := viper.GetString(cli.HomeFlag) + keyMan := client.GetKeyManager(rootDir) + serviceKeys := rest.NewServiceKeys(keyMan) + serviceByteTx := byteTx.NewServiceByteTx(keyMan) + serviceTxs := rest.NewServiceTxs(commands.GetNode()) + + + routeRegistrars := []func(*mux.Router) error{ + // rest.Keys handlers + serviceKeys.RegisterCRUD, + + // Coin handlers (Send, Query, SearchSent) + coinrest.RegisterAll, + + // Roles createRole handler + rolerest.RegisterCreateRole, + + // Iris sign transactions handler + serviceKeys.RegisterSignTx, + // Iris post transaction handler + serviceTxs.RegisterPostTx, + + // Iris transfer Tx to byte[] + serviceByteTx.RegisterByteTx, + + // Nonce query handler + noncerest.RegisterQueryNonce, + + // Staking query handlers + stakerest.RegisterQueryCandidate, + stakerest.RegisterQueryCandidates, + stakerest.RegisterQueryDelegatorBond, + stakerest.RegisterQueryDelegatorCandidates, + // Staking tx builders + stakerest.RegisterDelegate, + stakerest.RegisterUnbond, + } + + for _, routeRegistrar := range routeRegistrars { + if err := routeRegistrar(router); err != nil { + log.Fatal(err) + } + } + + addr := fmt.Sprintf(":%d", 8080) + + log.Printf("Serving on %q", addr) + http.ListenAndServe(addr, router) + +} \ No newline at end of file diff --git a/cmd/iris/sh_tests/stake.sh b/cmd/iris/sh_tests/stake.sh new file mode 100644 index 000000000..6682ec347 --- /dev/null +++ b/cmd/iris/sh_tests/stake.sh @@ -0,0 +1,276 @@ +#!/bin/bash +set -u + +# These global variables are required for common.sh +SERVER_EXE="iris node --log_level=debug" +CLIENT_EXE="iris client" +ACCOUNTS=(jae ethan bucky rigel igor) +RICH=${ACCOUNTS[0]} +DELEGATOR=${ACCOUNTS[2]} +POOR=${ACCOUNTS[4]} + +BASE_DIR=$HOME/stake_test +BASE_DIR2=$HOME/stake_test2 +SERVER1=$BASE_DIR/server +SERVER2=$BASE_DIR2/server + +oneTimeSetUp() { + #[ "$2" ] || echo "missing parameters, line=${LINENO}" ; exit 1; + + + # These are passed in as args + CHAIN_ID="stake_test" + + # TODO Make this more robust + if [ "$BASE_DIR" == "$HOME/" ]; then + echo "Must be called with argument, or it will wipe your home directory" + exit 1 + fi + + rm -rf $BASE_DIR 2>/dev/null + mkdir -p $BASE_DIR + + if [ "$BASE_DIR2" == "$HOME/" ]; then + echo "Must be called with argument, or it will wipe your home directory" + exit 1 + fi + rm -rf $BASE_DIR2 2>/dev/null + mkdir -p $BASE_DIR2 + + # Set up client - make sure you use the proper prefix if you set + # a custom CLIENT_EXE + export BC_HOME=${BASE_DIR}/client + prepareClient + + # start the node server + set +u ; initServer $BASE_DIR $CHAIN_ID ; set -u + if [ $? != 0 ]; then return 1; fi + + set +u ; initClient $CHAIN_ID ; set -u + if [ $? != 0 ]; then return 1; fi + + printf "...Testing may begin!\n\n\n" + +} + +oneTimeTearDown() { + kill -9 $PID_SERVER2 >/dev/null 2>&1 + set +u ; quickTearDown ; set -u +} + +# XXX Ex Usage: checkCandidate $PUBKEY $EXPECTED_VOTING_POWER +checkCandidate() { + CANDIDATE=$(${CLIENT_EXE} query candidate --pubkey=$1) + if ! assertTrue "line=${LINENO}, bad query" $?; then + return 1 + fi + assertEquals "line=${LINENO}, proper voting power" "$2" $(echo $CANDIDATE | jq .data.voting_power) + return $? +} + +# XXX Ex Usage: checkCandidate $PUBKEY +checkCandidateEmpty() { + CANDIDATE=$(${CLIENT_EXE} query candidate --pubkey=$1 2>/dev/null) + if ! assertFalse "line=${LINENO}, expected empty query" $?; then + return 1 + fi +} + +# XXX Ex Usage: checkCandidate $DELEGATOR_ADDR $PUBKEY $EXPECTED_SHARES +checkDelegatorBond() { + BOND=$(${CLIENT_EXE} query delegator-bond --delegator-address=$1 --pubkey=$2) + if ! assertTrue "line=${LINENO}, account must exist" $?; then + return 1 + fi + assertEquals "line=${LINENO}, proper bond amount" "$3" $(echo $BOND | jq .data.Shares) + return $? +} + +# XXX Ex Usage: checkCandidate $DELEGATOR_ADDR $PUBKEY +checkDelegatorBondEmpty() { + BOND=$(${CLIENT_EXE} query delegator-bond --delegator-address=$1 --pubkey=$2 2>/dev/null) + if ! assertFalse "line=${LINENO}, expected empty query" $?; then + return 1 + fi +} + +#______________________________________________________________________________________ + +test00GetAccount() { + SENDER=$(getAddr $RICH) + RECV=$(getAddr $POOR) + + assertFalse "line=${LINENO}, requires arg" "${CLIENT_EXE} query account" + + set +u ; checkAccount $SENDER "9007199254740992" ; set -u + + ACCT2=$(${CLIENT_EXE} query account $RECV 2>/dev/null) + assertFalse "line=${LINENO}, has no genesis account" $? +} + +test01SendTx() { + assertFalse "line=${LINENO}, missing dest" "${CLIENT_EXE} tx send --amount=992fermion --sequence=1" + assertFalse "line=${LINENO}, bad password" "echo foo | ${CLIENT_EXE} tx send --amount=992fermion --sequence=1 --to=$RECV --name=$RICH" + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx send --amount=992fermion --sequence=1 --to=$RECV --name=$RICH) + txSucceeded $? "$TX" "$RECV" + HASH=$(echo $TX | jq .hash | tr -d \") + TX_HEIGHT=$(echo $TX | jq .height) + + set +u + checkAccount $SENDER "9007199254740000" $TX_HEIGHT + # make sure 0x prefix also works + checkAccount "0x$SENDER" "9007199254740000" $TX_HEIGHT + checkAccount $RECV "992" $TX_HEIGHT + + # Make sure tx is indexed + checkSendTx $HASH $TX_HEIGHT $SENDER "992" + set -u +} + +test02DeclareCandidacy() { + + # the premise of this test is to run a second validator (from rich) and then bond and unbond some tokens + # first create a second node to run and connect to the system + + # init the second node + SERVER_LOG2=$BASE_DIR2/node2.log + GENKEY=$(${CLIENT_EXE} keys get ${RICH} | awk '{print $2}') + ${SERVER_EXE} init $GENKEY --chain-id $CHAIN_ID --home=$SERVER2 >>$SERVER_LOG2 + if [ $? != 0 ]; then return 1; fi + + # copy in the genesis from the first initialization to the new server + cp $SERVER1/config/genesis.json $SERVER2/config/genesis.json + + # point the new config to the old server location + rm $SERVER2/config/config.toml + echo 'proxy_app = "tcp://127.0.0.1:46668" + moniker = "anonymous" + fast_sync = true + db_backend = "leveldb" + log_level = "state:info,*:error" + + [rpc] + laddr = "tcp://0.0.0.0:46667" + + [p2p] + laddr = "tcp://0.0.0.0:46666" + seeds = "0.0.0.0:46656"' >$SERVER2/config/config.toml + + # start the second node + ${SERVER_EXE} start --home=$SERVER2 >>$SERVER_LOG2 2>&1 & + sleep 1 + PID_SERVER2=$! + disown + if ! ps $PID_SERVER2 >/dev/null; then + echo "**FAILED**" + cat $SERVER_LOG2 + return 1 + fi + + # get the pubkey of the second validator + PK2=$(cat $SERVER2/config/priv_validator.json | jq -r .pub_key.data) + + CAND_ADDR=$(getAddr $POOR) + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx declare-candidacy --sequence=1 --amount=2fermion --name=$POOR --pubkey=$PK2 --moniker=rigey) + if [ $? != 0 ]; then return 1; fi + HASH=$(echo $TX | jq .hash | tr -d \") + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $CAND_ADDR "990" $TX_HEIGHT ; set -u + checkCandidate $PK2 "2" + checkDelegatorBond $CAND_ADDR $PK2 "2" +} + +test03Delegate() { + # send some coins to a delegator + DELA_ADDR=$(getAddr $DELEGATOR) + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx send --sequence=2 --amount=5fermion --to=$DELA_ADDR --name=$RICH) + txSucceeded $? "$TX" "$DELA_ADDR" + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "5" $TX_HEIGHT ; set -u + + # delegate some coins to the new + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=1 --amount=1fermion --name=$DELEGATOR --pubkey=$PK2) + if [ $? != 0 ]; then return 1; fi + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "4" $TX_HEIGHT ; set -u + checkCandidate $PK2 "3" + checkDelegatorBond $DELA_ADDR $PK2 "1" + + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=2 --amount=2fermion --name=$DELEGATOR --pubkey=$PK2) + if [ $? != 0 ]; then return 1; fi + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u + checkCandidate $PK2 "5" + checkDelegatorBond $DELA_ADDR $PK2 "3" + + # attempt a delegation without enough funds + # NOTE the sequence number still increments here because it will fail + # only during DeliverTx - however this should be updated (TODO) in new + # SDK when we can fail in CheckTx + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=3 --amount=3fermion --name=$DELEGATOR --pubkey=$PK2 2>/dev/null) + if [ $? == 0 ]; then return 1; fi + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u + checkCandidate $PK2 "5" + checkDelegatorBond $DELA_ADDR $PK2 "3" + + # perform the final delegation which should empty the delegators account + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=4 --amount=2fermion --name=$DELEGATOR --pubkey=$PK2) + if [ $? != 0 ]; then return 1; fi + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "null" $TX_HEIGHT ; set -u #empty account is null + checkCandidate $PK2 "7" + checkDelegatorBond $DELA_ADDR $PK2 "5" +} + +test04Unbond() { + # unbond from the delegator a bit + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=5 --shares=2 --name=$DELEGATOR --pubkey=$PK2) + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u + checkCandidate $PK2 "5" + checkDelegatorBond $DELA_ADDR $PK2 "3" + + # attempt to unbond more shares than exist + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=6 --shares=10 --name=$DELEGATOR --pubkey=$PK2 2>/dev/null) + if [ $? == 0 ]; then return 1; fi + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u + checkCandidate $PK2 "5" + checkDelegatorBond $DELA_ADDR $PK2 "3" + + # unbond entirely from the delegator + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=6 --shares=3 --name=$DELEGATOR --pubkey=$PK2) + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $DELA_ADDR "5" $TX_HEIGHT ; set -u + checkCandidate $PK2 "2" + checkDelegatorBondEmpty $DELA_ADDR $PK2 + + # unbond a bit from the owner + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=2 --shares=1 --name=$POOR --pubkey=$PK2) + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $CAND_ADDR "991" $TX_HEIGHT ; set -u + checkCandidate $PK2 "1" + checkDelegatorBond $CAND_ADDR $PK2 "1" + + # attempt to unbond more shares than exist + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=3 --shares=10 --name=$POOR --pubkey=$PK2 2>/dev/null) + if [ $? == 0 ]; then return 1; fi + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $CAND_ADDR "991" $TX_HEIGHT ; set -u + checkCandidate $PK2 "1" + checkDelegatorBond $CAND_ADDR $PK2 "1" + + # unbond entirely from the validator + TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=3 --shares=1 --name=$POOR --pubkey=$PK2) + TX_HEIGHT=$(echo $TX | jq .height) + set +u ; checkAccount $CAND_ADDR "992" $TX_HEIGHT ; set -u + checkCandidateEmpty $PK2 + checkDelegatorBondEmpty $CAND_ADDR $PK2 +} + +# Load common then run these tests with shunit2! +CLI_DIR=$GOPATH/src/github.com/cosmos/gaia/vendor/github.com/cosmos/cosmos-sdk/tests/cli + +. $CLI_DIR/common.sh +. $CLI_DIR/shunit2 diff --git a/cmd/iriscli/lcd.go b/cmd/iriscli/lcd.go deleted file mode 100644 index 49f99f2c2..000000000 --- a/cmd/iriscli/lcd.go +++ /dev/null @@ -1,85 +0,0 @@ -package main - -import ( - "net/http" - "os" - - "github.com/gorilla/mux" - "github.com/spf13/cobra" - "github.com/spf13/viper" - "github.com/tendermint/tmlibs/log" - - tmserver "github.com/tendermint/tendermint/rpc/lib/server" - cmn "github.com/tendermint/tmlibs/common" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/wire" - auth "github.com/cosmos/cosmos-sdk/x/auth/client/rest" - bank "github.com/cosmos/cosmos-sdk/x/bank/client/rest" - ibc "github.com/cosmos/cosmos-sdk/x/ibc/client/rest" - stake "github.com/cosmos/cosmos-sdk/x/stake/client/rest" - "github.com/irisnet/irishub/app" - "github.com/irisnet/irishub/version" -) - -// ServeCommand will generate a long-running rest server -// (aka Light Client Daemon) that exposes functionality similar -// to the cli, but over rest -func ServeCommand(cdc *wire.Codec) *cobra.Command { - flagListenAddr := "laddr" - flagCORS := "cors" - - cmd := &cobra.Command{ - Use: "rest-server", - Short: "Start LCD (light-client daemon), a local REST server", - RunE: func(cmd *cobra.Command, args []string) error { - listenAddr := viper.GetString(flagListenAddr) - handler := createHandler(cdc) - logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)). - With("module", "rest-server") - listener, err := tmserver.StartHTTPServer(listenAddr, handler, logger) - if err != nil { - return err - } - logger.Info("REST server started") - - // Wait forever and cleanup - cmn.TrapSignal(func() { - err := listener.Close() - logger.Error("Error closing listener", "err", err) - }) - return nil - }, - } - cmd.Flags().StringP(flagListenAddr, "a", "tcp://localhost:1317", "Address for server to listen on") - cmd.Flags().String(flagCORS, "", "Set to domains that can make CORS requests (* for all)") - cmd.Flags().StringP(client.FlagChainID, "c", "", "ID of chain we connect to") - cmd.Flags().StringP(client.FlagNode, "n", "tcp://localhost:46657", "Node to connect to") - return cmd -} - -func createHandler(cdc *wire.Codec) http.Handler { - r := mux.NewRouter() - r.HandleFunc("/version", version.RequestHandler).Methods("GET") - - kb, err := keys.GetKeyBase() //XXX - if err != nil { - panic(err) - } - - ctx := app.NewContext() - - // TODO make more functional? aka r = keys.RegisterRoutes(r) - keys.RegisterRoutes(r) - rpc.RegisterRoutes(ctx.GetCosmosCtx(), r) - tx.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc) - auth.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, "acc") - bank.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, kb) - ibc.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, kb) - stake.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, kb) - RegisterRoutes(ctx, r, cdc, kb) - return r -} diff --git a/cmd/iriscli/lcd_test.go b/cmd/iriscli/lcd_test.go deleted file mode 100644 index cabf4acc5..000000000 --- a/cmd/iriscli/lcd_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package main - -import ( - "github.com/irisnet/irishub/app" - "github.com/irisnet/irishub/tools/prometheus" - "github.com/spf13/viper" - "testing" -) - -func TestRestServer(t *testing.T) { - cdc := app.MakeCodec() - comm := ServeCommand(cdc) - viper.Set("chain-id", "fuxi") - viper.Set("node", "tcp://localhost:26657") - viper.Set("laddr", "tcp://localhost:1317") - - comm.ExecuteC() -} - -func TestMetricsCmd(t *testing.T) { - cdc := app.MakeCodec() - comm := prometheus.MonitorCommand("stake", cdc) - viper.Set("node", "tcp://0.0.0.0:46657") - viper.Set("chain-id", "fuxi") - viper.Set("commands", "iris start ;htop") - /* - viper.Set("paths","/etc ;/home/") - viper.Set("recursively", false) - */ - viper.Set("paths", "/Users/zhangzhiqiang/.iris") - viper.Set("disks", "/") - viper.Set("recursively", true) - comm.ExecuteC() -} diff --git a/cmd/iriscli/main.go b/cmd/iriscli/main.go deleted file mode 100644 index 64231ec96..000000000 --- a/cmd/iriscli/main.go +++ /dev/null @@ -1,124 +0,0 @@ -package main - -import ( - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/spf13/cobra" - "github.com/tendermint/tmlibs/cli" - - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - ibccmd "github.com/cosmos/cosmos-sdk/x/ibc/client/cli" - slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" - stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" - "github.com/irisnet/irishub/app" - "github.com/irisnet/irishub/tools/prometheus" - "github.com/irisnet/irishub/version" -) - -// rootCmd is the entry point for this binary -var ( - rootCmd = &cobra.Command{ - Use: "iriscli", - Short: "irishub light-client", - } -) - -func main() { - cobra.EnableCommandSorting = false - cdc := app.MakeCodec() - - // TODO: setup keybase, viper object, etc. to be passed into - // the below functions and eliminate global vars, like we do - // with the cdc - - // add standard rpc commands - rpc.AddCommands(rootCmd) - - //Add state commands - tendermintCmd := &cobra.Command{ - Use: "tendermint", - Short: "Tendermint state querying subcommands", - } - tendermintCmd.AddCommand( - rpc.BlockCommand(), - rpc.ValidatorCommand(), - ) - tx.AddCommands(tendermintCmd, cdc) - - //Add IBC commands - ibcCmd := &cobra.Command{ - Use: "ibc", - Short: "Inter-Blockchain Communication subcommands", - } - ibcCmd.AddCommand( - client.PostCommands( - ibccmd.IBCTransferCmd(cdc), - ibccmd.IBCRelayCmd(cdc), - )...) - - advancedCmd := &cobra.Command{ - Use: "advanced", - Short: "Advanced subcommands", - } - - advancedCmd.AddCommand( - tendermintCmd, - ibcCmd, - ServeCommand(cdc), - ) - rootCmd.AddCommand( - advancedCmd, - client.LineBreak, - ) - - //Add stake commands - stakeCmd := &cobra.Command{ - Use: "stake", - Short: "Stake and validation subcommands", - } - stakeCmd.AddCommand( - client.GetCommands( - stakecmd.GetCmdQueryValidator("stake", cdc), - stakecmd.GetCmdQueryValidators("stake", cdc), - stakecmd.GetCmdQueryDelegation("stake", cdc), - stakecmd.GetCmdQueryDelegations("stake", cdc), - slashingcmd.GetCmdQuerySigningInfo("slashing", cdc), - )...) - stakeCmd.AddCommand( - client.PostCommands( - stakecmd.GetCmdCreateValidator(cdc), - stakecmd.GetCmdEditValidator(cdc), - stakecmd.GetCmdDelegate(cdc), - stakecmd.GetCmdUnbond(cdc), - slashingcmd.GetCmdUnrevoke(cdc), - )...) - rootCmd.AddCommand( - stakeCmd, - ) - - //Add auth and bank commands - rootCmd.AddCommand( - client.GetCommands( - authcmd.GetAccountCmd("acc", cdc, authcmd.GetAccountDecoder(cdc)), - )...) - rootCmd.AddCommand( - client.PostCommands( - bankcmd.SendTxCmd(cdc), - )...) - - // add proxy, version and key info - rootCmd.AddCommand( - keys.Commands(), - client.LineBreak, - version.VersionCmd, - ) - - rootCmd.AddCommand(prometheus.MonitorCommand("stake", cdc)) - - // prepare and add flags - executor := cli.PrepareMainCmd(rootCmd, "IRIS", app.DefaultCLIHome) - executor.Execute() -} diff --git a/cmd/iriscli/offline_sign.go b/cmd/iriscli/offline_sign.go deleted file mode 100644 index c918c610d..000000000 --- a/cmd/iriscli/offline_sign.go +++ /dev/null @@ -1,119 +0,0 @@ -package main - -import ( - "encoding/json" - 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/bank" - "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/gorilla/mux" - "github.com/irisnet/irishub/app" - "github.com/pkg/errors" - "github.com/tendermint/go-crypto" - "github.com/tendermint/go-crypto/keys" - "io/ioutil" - "net/http" -) - -func RegisterRoutes(ctx app.Context, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { - r.HandleFunc("/tx/send", SendTxRequestHandlerFn(cdc, kb, ctx)).Methods("POST") -} - -type sendTx struct { - Msg string `json:"msg"` - MsgType string `json:"type"` - Fee auth.StdFee `json:"fee"` - Signatures []StdSignature `json:"signatures"` -} - -type StdSignature struct { - PubKey crypto.PubKeyEd25519 `json:"pub_key"` // optional - Signature crypto.SignatureEd25519 `json:"signature"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` -} - -//send traction(sign with rainbow) to irishub -func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx app.Context) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var tx sendTx - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - if err = json.Unmarshal(body, &tx); err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - var sig = make([]auth.StdSignature, len(tx.Signatures)) - for index, s := range tx.Signatures { - sig[index].PubKey = s.PubKey - sig[index].Signature = s.Signature - sig[index].AccountNumber = s.AccountNumber - sig[index].Sequence = s.Sequence - } - - msg, err := convertMsg(tx) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - var stdTx = auth.StdTx{ - Msg: msg, - Fee: tx.Fee, - Signatures: sig, - } - txByte, _ := cdc.MarshalBinary(stdTx) - // send - res, err := ctx.BroadcastTxSync(txByte) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - output, err := json.MarshalIndent(res, "", " ") - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - w.Write(output) - } -} - -func convertMsg(tx sendTx) (sdk.Msg, error) { - data := []byte(tx.Msg) - switch tx.MsgType { - case "transfer": - { - var msg bank.MsgSend - if err := json.Unmarshal(data, &msg); err != nil { - return nil, err - } - return msg, nil - } - case "delegate": - var msg stake.MsgDelegate - if err := json.Unmarshal(data, &msg); err != nil { - return nil, err - } - return msg, nil - case "unbond": - var msg stake.MsgUnbond - if err := json.Unmarshal(data, &msg); err != nil { - return nil, err - } - return msg, nil - } - - return nil, errors.New("invalid message type") -} diff --git a/glide.lock b/glide.lock new file mode 100644 index 000000000..0e912f491 --- /dev/null +++ b/glide.lock @@ -0,0 +1,305 @@ +hash: 20e25ba77f4c08127c8b87786d0bb7d3868e6c8a0bfe9f80f63ce831b25663ec +updated: 2018-03-07T11:54:26.85382+08:00 +imports: +- name: github.com/bgentry/speakeasy + version: 4aabc24848ce5fd31929f7d1e4ea74d3709c14cd +- name: github.com/btcsuite/btcd + version: 2e60448ffcc6bf78332d1fe590260095f554dd78 + subpackages: + - btcec +- name: github.com/BurntSushi/toml + version: b26d9c308763d68093482582cea63d69be07a0f0 +- name: github.com/cosmos/cosmos-sdk + version: f1b1d36324812dc221da87f56734a5c25d8754aa + subpackages: + - app + - client + - client/commands + - client/commands/commits + - client/commands/keys + - client/commands/proxy + - client/commands/query + - client/commands/rpc + - client/commands/search + - client/commands/txs + - client/rest + - errors + - genesis + - modules/auth + - modules/auth/commands + - modules/base + - modules/base/commands + - modules/coin + - modules/coin/commands + - modules/coin/rest + - modules/fee + - modules/fee/commands + - modules/ibc + - modules/ibc/commands + - modules/nonce + - modules/nonce/commands + - modules/nonce/rest + - modules/roles + - modules/roles/commands + - modules/roles/rest + - server/commands + - stack + - state + - version +- name: github.com/MrXJC/gaia + version: develop + subpackages: + - modules/stake + - modules/stake/commands + - modules/stake/rest + - version +- name: github.com/ebuchman/fail-test + version: 95f809107225be108efcf10a3509e4ea6ceef3c4 +- name: github.com/fsnotify/fsnotify + version: 4da3e2cfbabc9f751898f250b49f2439785783a1 +- name: github.com/go-kit/kit + version: 4dc7be5d2d12881735283bcab7352178e190fc71 + subpackages: + - log + - log/level + - log/term +- name: github.com/go-logfmt/logfmt + version: 390ab7935ee28ec6b286364bba9b4dd6410cb3d5 +- name: github.com/go-playground/locales + version: e4cbcb5d0652150d40ad0646651076b6bd2be4f6 + subpackages: + - currency +- name: github.com/go-playground/universal-translator + version: 71201497bace774495daed26a3874fd339e0b538 +- name: github.com/go-stack/stack + version: 259ab82a6cad3992b4e21ff5cac294ccb06474bc +- name: github.com/gogo/protobuf + version: 1adfc126b41513cc696b209667c8656ea7aac67c + subpackages: + - gogoproto + - jsonpb + - proto + - protoc-gen-gogo/descriptor + - sortkeys + - types +- name: github.com/golang/protobuf + version: 925541529c1fa6821df4e44ce2723319eb2be768 + subpackages: + - proto + - ptypes + - ptypes/any + - ptypes/duration + - ptypes/timestamp +- name: github.com/golang/snappy + version: 553a641470496b2327abcac10b36396bd98e45c9 +- name: github.com/gorilla/context + version: 08b5f424b9271eedf6f9f0ce86cb9396ed337a42 +- name: github.com/gorilla/mux + version: 53c1911da2b537f792e7cafcb446b05ffe33b996 +- name: github.com/gorilla/websocket + version: ea4d1f681babbce9545c9c5f3d5194a789c89f5b +- name: github.com/hashicorp/hcl + version: 23c074d0eceb2b8a5bfdbb271ab780cde70f05a8 + subpackages: + - hcl/ast + - hcl/parser + - hcl/scanner + - hcl/strconv + - hcl/token + - json/parser + - json/scanner + - json/token +- name: github.com/howeyc/crc16 + version: 2b2a61e366a66d3efb279e46176e7291001e0354 +- name: github.com/inconshreveable/mousetrap + version: 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 +- name: github.com/jmhodges/levigo + version: c42d9e0ca023e2198120196f842701bb4c55d7b9 +- name: github.com/kr/logfmt + version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0 +- name: github.com/magiconair/properties + version: 49d762b9817ba1c2e9d0c69183c2b4a8b8f1d934 +- name: github.com/mattn/go-isatty + version: 0360b2af4f38e8d38c7fce2a9f4e702702d73a39 +- name: github.com/mitchellh/mapstructure + version: 06020f85339e21b2478f756a78e295255ffa4d6a +- name: github.com/pelletier/go-toml + version: 4e9e0ee19b60b13eb79915933f44d8ed5f268bdd +- name: github.com/pkg/errors + version: 645ef00459ed84a119197bfb8d8205042c6df63d +- name: github.com/rcrowley/go-metrics + version: e181e095bae94582363434144c61a9653aff6e50 +- name: github.com/spf13/afero + version: 8d919cbe7e2627e417f3e45c3c0e489a5b7e2536 + subpackages: + - mem +- name: github.com/spf13/cast + version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 +- name: github.com/spf13/cobra + version: 7b2c5ac9fc04fc5efafb60700713d4fa609b777b +- name: github.com/spf13/jwalterweatherman + version: 12bd96e66386c1960ab0f74ced1362f66f552f7b +- name: github.com/spf13/pflag + version: e57e3eeb33f795204c1ca35f56c44f83227c6e66 +- name: github.com/spf13/viper + version: 25b30aa063fc18e48662b86996252eabdcf2f0c7 +- name: github.com/syndtr/goleveldb + version: adf24ef3f94bd13ec4163060b21a5678f22b429b + subpackages: + - leveldb + - leveldb/cache + - leveldb/comparer + - leveldb/errors + - leveldb/filter + - leveldb/iterator + - leveldb/journal + - leveldb/memdb + - leveldb/opt + - leveldb/storage + - leveldb/table + - leveldb/util +- name: github.com/tendermint/abci + version: 3d5f0a8b94bbbfa70ecd4072fc55854f8210425b + subpackages: + - client + - example/code + - example/kvstore + - server + - types +- name: github.com/tendermint/ed25519 + version: d8387025d2b9d158cf4efb07e7ebf814bcce2057 + subpackages: + - edwards25519 + - extra25519 +- name: github.com/tendermint/go-crypto + version: 2017856384589234024cda848a6332157d1f527c + subpackages: + - keys + - keys/cryptostore + - keys/storage/filestorage + - keys/wordlist +- name: github.com/tendermint/go-wire + version: b6fc872b42d41158a60307db4da051dd6f179415 + subpackages: + - data +- name: github.com/tendermint/iavl + version: 39de8f0b4ee758fdd5bb3a9afc6dd9bf42c04785 +- name: github.com/tendermint/tendermint + version: 9c5937df969de23e9087f183c52b5088d4b6f268 + subpackages: + - blockchain + - cmd/tendermint/commands + - config + - consensus + - consensus/types + - evidence + - lite + - lite/client + - lite/errors + - lite/files + - lite/proxy + - mempool + - node + - p2p + - p2p/conn + - p2p/pex + - p2p/trust + - p2p/upnp + - proxy + - rpc/client + - rpc/core + - rpc/core/types + - rpc/grpc + - rpc/lib + - rpc/lib/client + - rpc/lib/server + - rpc/lib/types + - state + - state/txindex + - state/txindex/kv + - state/txindex/null + - types + - version +- name: github.com/tendermint/tmlibs + version: 26f2ab65f82cfc6873c312e8030104c47c05f10e + subpackages: + - autofile + - cli + - cli/flags + - clist + - common + - db + - flowrate + - log + - merkle + - pubsub + - pubsub/query +- name: golang.org/x/crypto + version: 94eea52f7b742c7cbe0b03b22f0c4c8631ece122 + subpackages: + - curve25519 + - nacl/box + - nacl/secretbox + - openpgp/armor + - openpgp/errors + - poly1305 + - ripemd160 + - salsa20/salsa +- name: golang.org/x/net + version: 5ccada7d0a7ba9aeb5d3aca8d3501b4c2a509fec + subpackages: + - context + - http2 + - http2/hpack + - idna + - internal/timeseries + - lex/httplex + - trace +- name: golang.org/x/sys + version: 8b4580aae2a0dd0c231a45d3ccb8434ff533b840 + subpackages: + - unix +- name: golang.org/x/text + version: 57961680700a5336d15015c8c50686ca5ba362a4 + subpackages: + - secure/bidirule + - transform + - unicode/bidi + - unicode/norm +- name: google.golang.org/genproto + version: a8101f21cf983e773d0c1133ebc5424792003214 + repo: https://github.com/google/go-genproto + vcs: git + subpackages: + - googleapis/rpc/status +- name: google.golang.org/grpc + version: 401e0e00e4bb830a10496d64cd95e068c5bf50de + repo: https://github.com/grpc/grpc-go + vcs: git + subpackages: + - balancer + - codes + - connectivity + - credentials + - grpclb/grpc_lb_v1/messages + - grpclog + - internal + - keepalive + - metadata + - naming + - peer + - resolver + - stats + - status + - tap + - transport +- name: gopkg.in/go-playground/validator.v9 + version: 1b8c8e19cd250435025214492d9a08411d760fdd +- name: gopkg.in/yaml.v2 + version: 287cf08546ab5e7e37d55a84f7ed3fd1db036de5 +testImports: +- name: github.com/stretchr/testify + version: 2aa2c176b9dab406a6970f6a55f513e8a8c8b18f + subpackages: + - assert + - require diff --git a/glide.yaml b/glide.yaml new file mode 100644 index 000000000..a279a3c69 --- /dev/null +++ b/glide.yaml @@ -0,0 +1,17 @@ +package: github.com/irisnet/iris-hub +import: +- package: github.com/MrXJC/gaia + version: develop +- package: github.com/cosmos/cosmos-sdk + version: tm-develop +- package: google.golang.org/grpc + repo: https://github.com/grpc/grpc-go + vcs: git +- package: google.golang.org/genproto + repo: https://github.com/google/go-genproto + vcs: git +testImport: +- package: github.com/stretchr/testify + subpackages: + - assert + - require diff --git a/module/rest-txs/txs.go b/module/rest-txs/txs.go new file mode 100644 index 000000000..72230d389 --- /dev/null +++ b/module/rest-txs/txs.go @@ -0,0 +1,53 @@ +package rest_txs + +import ( + "net/http" + + "github.com/gorilla/mux" + wire "github.com/tendermint/go-wire" + rpcclient "github.com/tendermint/tendermint/rpc/client" + + sdk "github.com/cosmos/cosmos-sdk" +) + +// ServiceTxs exposes a REST API service for sendings txs. +// It wraps a Tendermint RPC client. +type ServiceTxs struct { + node rpcclient.Client +} + +func NewServiceTxs(c rpcclient.Client) *ServiceTxs { + return &ServiceTxs{ + node: c, + } +} + +func (s *ServiceTxs) PostTx(w http.ResponseWriter, r *http.Request) { + tx := new(sdk.Tx) + if err := sdk.ParseRequestAndValidateJSON(r, tx); err != nil { + sdk.WriteError(w, err) + return + } + + packet := wire.BinaryBytes(*tx) + // commit, err := s.node.BroadcastTxCommit(packet) + commit, err := s.node.BroadcastTxSync(packet) + if err != nil { + sdk.WriteError(w, err) + return + } + + sdk.WriteSuccess(w, commit) +} + +// mux.Router registrars + +// RegisterPostTx is a mux.Router handler that exposes POST +// method access to post a transaction to the blockchain. +func (s *ServiceTxs) RegisterPostTx(r *mux.Router) error { + r.HandleFunc("/tx", s.PostTx).Methods("POST") + return nil +} + +// End of mux.Router registrars + diff --git a/rest/byteTx.go b/rest/byteTx.go new file mode 100644 index 000000000..604af6c55 --- /dev/null +++ b/rest/byteTx.go @@ -0,0 +1,118 @@ +package rest + +import ( + "github.com/gorilla/mux" + "github.com/tendermint/go-crypto/keys" + "net/http" + sdk "github.com/cosmos/cosmos-sdk" + "encoding/hex" + "github.com/spf13/viper" + "github.com/cosmos/cosmos-sdk/client/commands" + "github.com/pkg/errors" + cmn "github.com/tendermint/tmlibs/common" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/commands/query" + "github.com/tendermint/tendermint/types" + "github.com/tendermint/go-wire" + "io" +) + + +type ServiceByteTx struct { + manager keys.Manager +} + +type RequestTx struct { + Tx sdk.Tx `json:"tx" validate:"required"` +} + +func NewServiceByteTx(manager keys.Manager) *ServiceByteTx { + return &ServiceByteTx{ + manager: manager, // XXX keycmd.GetKeyManager() + } +} + +func (s *ServiceByteTx) RegisterByteTx(r *mux.Router) error { + r.HandleFunc("/byteTx", s.ByteTx).Methods("POST") + return nil +} + + +func (s *ServiceByteTx) RegisterqueryTx(r *mux.Router) error { + r.HandleFunc("/tx/{hash}", s.queryTx).Methods("GET") + return nil +} + +func (s *ServiceByteTx) ByteTx(w http.ResponseWriter, r *http.Request) { + req := new(RequestTx) + if err := sdk.ParseRequestAndValidateJSON(r, req); err != nil { + sdk.WriteError(w, err) + return + } + + tx := req.Tx + + if sign, ok := tx.Unwrap().(keys.Signable); ok { + sdk.WriteSuccess(w, hex.EncodeToString(sign.SignBytes())) + return + } + sdk.WriteSuccess(w, "") +} + +func (s *ServiceByteTx) queryTx(w http.ResponseWriter, r *http.Request){ + args := mux.Vars(r) + hash := args["hash"] + + if hash == "" { + sdk.WriteError(w, errors.Errorf("[%s] argument must be non-empty ", "hash")) + return + } + // with tx, we always just parse key as hex and use to lookup + hashByte, err := hex.DecodeString(cmn.StripHex(hash)) + + // get the proof -> this will be used by all prover commands + node := commands.GetNode() + prove := !viper.GetBool(commands.FlagTrustNode) + res, err := node.Tx(hashByte, prove) + if err != nil { + sdk.WriteError(w, err) + return + } + + // no checks if we don't get a proof + if !prove { + sdk.WriteSuccess(w,showTx(w,res.Height, res.Tx)) + return + } + + cert, err := commands.GetCertifier() + if err != nil { + sdk.WriteError(w, err) + return + } + + check, err := client.GetCertifiedCommit(res.Height, node, cert) + if err != nil { + sdk.WriteError(w, err) + return + } + err = res.Proof.Validate(check.Header.DataHash) + if err != nil { + sdk.WriteError(w, err) + return + } + + // note that we return res.Proof.Data, not res.Tx, + // as res.Proof.Validate only verifies res.Proof.Data + sdk.WriteSuccess(w,showTx(w,res.Height, res.Proof.Data)) +} + +// showTx parses anything that was previously registered as sdk.Tx +func showTx(w io.Writer ,h int64, tx types.Tx) error { + var info sdk.Tx + err := wire.ReadBinaryBytes(tx, &info) + if err != nil { + return err + } + return query.FoutputProof(w,info,h) +} \ No newline at end of file diff --git a/testnets/develop/README.md b/testnets/develop/README.md deleted file mode 100644 index 98725486f..000000000 --- a/testnets/develop/README.md +++ /dev/null @@ -1,28 +0,0 @@ -### Running in command line -这个命令会在宿主机后台启动一个iris进程,启动前需要确认宿主机已安装iris、iriscli,并确认`46656`和`46657`端口没有被占用, -命令会删除$HOME/.iris*目录,请注意做好备份 -``` -nohup sh start.sh > iris.log 2>&1 & -``` -查看日志: -```$xslt -tail -f iris.log -``` -查看账户列表: -```$xslt -iriscli keys list -``` - -### Running in docker -这个命令会启动一个基于最新develop分支构建的镜像的docker容器,启动前需要确认`46656`和`46657`端口没有被占用 -``` -sh start-docker.sh -``` -查看日志: -```$xslt -docker logs -f irishub-sandbox -``` -查看账户列表: -```$xslt -docker exec -it irishub-sandbox iriscli keys list -``` \ No newline at end of file diff --git a/testnets/develop/config/genesis.json b/testnets/develop/config/genesis.json deleted file mode 100644 index 7e45a374f..000000000 --- a/testnets/develop/config/genesis.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "app_hash": "", - "genesis_time": "2018-06-20T23:34:15.721008+08:00", - "chain_id": "fuxi-develop", - "consensus_params": { - "block_size_params": { - "max_bytes": 22020096, - "max_txs": 100000, - "max_gas": -1 - }, - "tx_size_params": { - "max_bytes": 10240, - "max_gas": -1 - }, - "block_gossip_params": { - "block_part_size_bytes": 65536 - }, - "evidence_params": { - "max_age": 100000 - } - }, - "app_state": { - "accounts": [ - { - "address": "507405661F2DB1940941FA0A6B3642015A015387", - "coins": [ - { - "denom": "iris", - "amount": 200000000 - }, - { - "denom": "steak", - "amount": 100 - } - ] - } - ], - "stake": { - "pool": { - "loose_unbonded_tokens": 100, - "unbonded_tokens": 0, - "unbonding_tokens": 0, - "bonded_tokens": 100, - "unbonded_shares": "0", - "unbonding_shares": "0", - "bonded_shares": "100", - "inflation_last_time": 0, - "inflation": "7/100", - "date_last_commission_reset": 0, - "prev_bonded_shares": "0" - }, - "params": { - "inflation_rate_change": "13/100", - "inflation_max": "1/5", - "inflation_min": "7/100", - "goal_bonded": "67/100", - "max_validators": 100, - "bond_denom": "steak" - }, - "validators": [ - { - "owner": "507405661F2DB1940941FA0A6B3642015A015387", - "pub_key": { - "type": "AC26791624DE60", - "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" - }, - "revoked": false, - "pool_shares": { - "status": 2, - "amount": "100" - }, - "delegator_shares": "0", - "description": { - "moniker": "init1", - "identity": "", - "website": "", - "details": "" - }, - "bond_height": 0, - "bond_intra_tx_counter": 0, - "proposer_reward_pool": [], - "commission": "0", - "commission_max": "0", - "commission_change_rate": "0", - "commission_change_today": "0", - "prev_bonded_shares": "0" - } - ], - "bonds": null - } - }, - "validators": [ - { - "pub_key": { - "type": "AC26791624DE60", - "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" - }, - "power": 100, - "name": "" - } - ] -} \ No newline at end of file diff --git a/testnets/develop/config/gentx/gentx-7db17b3821cf22382b7afe03e30bd04d1b4f10eb.json b/testnets/develop/config/gentx/gentx-7db17b3821cf22382b7afe03e30bd04d1b4f10eb.json deleted file mode 100644 index 9eb7c6484..000000000 --- a/testnets/develop/config/gentx/gentx-7db17b3821cf22382b7afe03e30bd04d1b4f10eb.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "node_id": "7db17b3821cf22382b7afe03e30bd04d1b4f10eb", - "ip": "192.168.150.125", - "validator": { - "pub_key": { - "type": "AC26791624DE60", - "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" - }, - "power": 100, - "name": "" - }, - "app_gen_tx": { - "name": "init1", - "address": "507405661F2DB1940941FA0A6B3642015A015387", - "pub_key": { - "type": "AC26791624DE60", - "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" - } - } -} \ No newline at end of file diff --git a/testnets/develop/config/node_key.json b/testnets/develop/config/node_key.json deleted file mode 100644 index b1bcf6126..000000000 --- a/testnets/develop/config/node_key.json +++ /dev/null @@ -1 +0,0 @@ -{"priv_key":{"type":"954568A3288910","value":"6TWNBR3I7mIZ0IbeAVuhRU8eqEo/9QxlBxxVdO9TFodLtd05OpOiXFrI+xST4Sy4p11qV11agb33Iiv5i8GAzA=="}} \ No newline at end of file diff --git a/testnets/develop/config/priv_validator.json b/testnets/develop/config/priv_validator.json deleted file mode 100644 index 48a1ab5ea..000000000 --- a/testnets/develop/config/priv_validator.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "address": "823E3266359570A41A6B31C7A1F738F19923A0F0", - "pub_key": { - "type": "AC26791624DE60", - "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" - }, - "last_height": 0, - "last_round": 0, - "last_step": 0, - "priv_key": { - "type": "954568A3288910", - "value": "wVB2h4AeVpuWJ/xJlfKV3cf/6WNrVfxLr+CkbWU7E/4ImPavmwYnSOfyZoukSIVh5hy3KMY2yQPi1boNrP99WQ==" - } -} \ No newline at end of file diff --git a/testnets/develop/seed_phrase b/testnets/develop/seed_phrase deleted file mode 100644 index 4d9127cc2..000000000 --- a/testnets/develop/seed_phrase +++ /dev/null @@ -1 +0,0 @@ -segment winner ability purse fiction robust glass find mechanic bind park attend jealous symbol artefact abandon \ No newline at end of file diff --git a/testnets/develop/start-docker.sh b/testnets/develop/start-docker.sh deleted file mode 100644 index 3dce2829c..000000000 --- a/testnets/develop/start-docker.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash -docker run -d -p 46656:46656 -p 46657:46657 --name irishub-sandbox -it irishub:develop sh -c ' - apk add --no-cache curl expect && \ - curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/start.sh -o start.sh && \ - sh start.sh' \ No newline at end of file diff --git a/testnets/develop/start.sh b/testnets/develop/start.sh deleted file mode 100644 index 53bf8fdd6..000000000 --- a/testnets/develop/start.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash -rm -rf ~/.iris* -mkdir -p ~/.iris/config/gentx/ -curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/genesis.json -o ~/.iris/config/genesis.json -curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/node_key.json -o ~/.iris/config/node_key.json -curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/priv_validator.json -o ~/.iris/config/priv_validator.json -curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json -o ~/.iris/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json -iris init --chain-id=fuxi-develop --name=init1 -SP=$(curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/seed_phrase) -command="iriscli keys add init1 --recover" -expect -c " - spawn $command; - expect { - \"override the existing name*\" {send \"y\r\"; exp_continue} - \"Enter a passphrase for your key:\" {send \"1234567890\r\"; exp_continue} - \"Repeat the passphrase:\" {send \"1234567890\r\"; exp_continue} - \"Enter your recovery seed phrase:\" {send \"$SP\r\"; exp_continue} - } -" -iris start \ No newline at end of file diff --git a/tools/context.go b/tools/context.go deleted file mode 100644 index da4d0b160..000000000 --- a/tools/context.go +++ /dev/null @@ -1,90 +0,0 @@ -package tools - -import ( - "encoding/json" - "fmt" - "github.com/cosmos/cosmos-sdk/client/context" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - "github.com/cosmos/cosmos-sdk/wire" - "io/ioutil" - "net/http" - "strings" -) - -type Context struct { - context.CoreContext - StoreName string - Cdc *wire.Codec -} - -func NewContext(storeName string,cdc *wire.Codec) Context { - ctx := context.NewCoreContextFromViper() - return Context{ - ctx,storeName,cdc, - } -} - -type JsonRpc interface { - NetInfo() *ctypes.ResultNetInfo - NumUnconfirmedTxs() *ctypes.ResultUnconfirmedTxs -} - -func (rpc Context) NetInfo() *ctypes.ResultNetInfo { - client := &http.Client{} - - reqUri := tcpToHttpUrl(rpc.NodeURI) + "/net_info" - - resp, err := client.Get(reqUri) - if err != nil { - fmt.Println(err) - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - fmt.Println(err) - } - - var res = struct { - JsonRpc string `json:"jsonrpc"` - Id string `json:"id"` - Result ctypes.ResultNetInfo `json:"result"` - }{} - if err := json.Unmarshal(body, &res); err != nil { - fmt.Println(err) - } - - return &res.Result -} - -func (rpc Context) NumUnconfirmedTxs() *ctypes.ResultUnconfirmedTxs { - client := &http.Client{} - reqUri := tcpToHttpUrl(rpc.NodeURI) + "/num_unconfirmed_txs" - - resp, err := client.Get(reqUri) - if err != nil { - fmt.Println(err) - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - fmt.Println(err) - } - - var res = struct { - JsonRpc string `json:"jsonrpc"` - Id string `json:"id"` - Result ctypes.ResultUnconfirmedTxs `json:"result"` - }{} - if err := json.Unmarshal(body, &res); err != nil { - fmt.Println(err) - } - - return &res.Result -} - -func tcpToHttpUrl(url string) string { - urls := strings.Replace(url, "tcp", "http", 1) - return urls -} diff --git a/tools/prometheus/consensus/metrics.go b/tools/prometheus/consensus/metrics.go deleted file mode 100644 index 696162354..000000000 --- a/tools/prometheus/consensus/metrics.go +++ /dev/null @@ -1,215 +0,0 @@ -package consensus - -import ( - cctx "context" - "encoding/hex" - "fmt" - "github.com/cosmos/cosmos-sdk/wire" // XXX fix - "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/go-kit/kit/metrics" - "github.com/go-kit/kit/metrics/prometheus" - tools "github.com/irisnet/irishub/tools" - stdprometheus "github.com/prometheus/client_golang/prometheus" - "github.com/tendermint/tendermint/types" - "log" - "strings" - "time" -) - -// Metrics contains metrics exposed by this package. -type Metrics struct { - // Height of the chain. - Height metrics.Gauge - - // Number of rounds. - Rounds metrics.Gauge - - // Number of validators. - Validators metrics.Gauge - // Number of Candidates - Candidates metrics.Gauge - // Total power of all validators. - ValidatorsPower metrics.Gauge - // Number of validators who did not sign. - MissingValidators metrics.Gauge - // Total power of the missing validators. - MissingValidatorsPower metrics.Gauge - // Number of validators who tried to double sign. - ByzantineValidators metrics.Gauge - // Total power of the byzantine validators. - ByzantineValidatorsPower metrics.Gauge - - // Time between this and the last block. - BlockIntervalSeconds metrics.Histogram - - // Number of transactions. - NumTxs metrics.Gauge - // Size of the block. - BlockSizeBytes metrics.Gauge - // Total number of transactions. - TotalTxs metrics.Gauge -} - -// PrometheusMetrics returns Metrics build using Prometheus client library. -func PrometheusMetrics() *Metrics { - return &Metrics{ - Height: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "consensus", - Name: "height", - Help: "Height of the chain.", - }, []string{}), - Rounds: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "consensus", - Name: "rounds", - Help: "Number of rounds.", - }, []string{}), - - Validators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "consensus", - Name: "validators", - Help: "Number of validators.", - }, []string{}), - - Candidates: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "consensus", - Name: "candidates", - Help: "Number of Candidates.", - }, []string{}), - - ValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "consensus", - Name: "validators_power", - Help: "Total power of all validators.", - }, []string{}), - MissingValidators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "consensus", - Name: "missing_validators", - Help: "Number of validators who did not sign.", - }, []string{}), - MissingValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "consensus", - Name: "missing_validators_power", - Help: "Total power of the missing validators.", - }, []string{}), - ByzantineValidators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "consensus", - Name: "byzantine_validators", - Help: "Number of validators who tried to double sign.", - }, []string{}), - ByzantineValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "consensus", - Name: "byzantine_validators_power", - Help: "Total power of the byzantine validators.", - }, []string{}), - - BlockIntervalSeconds: prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{ - Subsystem: "consensus", - Name: "block_interval_seconds", - Help: "Time between this and the last block.", - Buckets: []float64{1, 2.5, 5, 10, 60}, - }, []string{}), - - NumTxs: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "consensus", - Name: "num_txs", - Help: "Number of transactions.", - }, []string{}), - BlockSizeBytes: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "consensus", - Name: "block_size_bytes", - Help: "Size of the block.", - }, []string{}), - TotalTxs: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "consensus", - Name: "total_txs", - Help: "Total number of transactions.", - }, []string{}), - } -} - -func (cs *Metrics) Start(ctx tools.Context) { - context, _ := cctx.WithTimeout(cctx.Background(), 10*time.Second) - - var client = ctx.Client - //开启监听事件 - client.Start() - - blockC := make(chan interface{}) - - err := client.Subscribe(context, "monitor", types.EventQueryNewBlock, blockC) - - if err != nil { - log.Println("got ", err) - } - - go func() { - for e := range blockC { - block := e.(types.TMEventData).(types.EventDataNewBlock) - cs.RecordMetrics(ctx, ctx.Cdc, block.Block, ctx.StoreName) - } - }() -} - -func (cs *Metrics) RecordMetrics(ctx tools.Context, cdc *wire.Codec, block *types.Block, storeName string) { - cs.Height.Set(float64(block.Height)) - cs.ByzantineValidators.Set(float64(len(block.Evidence.Evidence))) - - missingValidators := 0 - missingValidatorsPower := int64(0) - validatorsPower := int64(0) - resultValidators, err := ctx.Client.Validators(&block.Height) - if err != nil { - panic(err) - } - validators := resultValidators.Validators - valMap := make(map[string]types.Validator, len(validators)) - for i, val := range validators { - var vote *types.Vote - if i < len(block.LastCommit.Precommits) { - vote = block.LastCommit.Precommits[i] - } - if vote == nil { - missingValidators++ - missingValidatorsPower += val.VotingPower - } - - valMap[val.Address.String()] = *val - validatorsPower += val.VotingPower - } - cs.Candidates.Set(float64(getCandidatesNum(cdc, ctx, storeName))) - cs.MissingValidators.Set(float64(missingValidators)) - cs.MissingValidatorsPower.Set(float64(missingValidatorsPower)) - cs.ValidatorsPower.Set(float64(validatorsPower)) - cs.Validators.Set(float64(len(validators))) - - byzantineValidatorsPower := int64(0) - for _, ev := range block.Evidence.Evidence { - addr := strings.ToUpper(hex.EncodeToString(ev.Address())) - if val, ok := valMap[addr]; ok { - byzantineValidatorsPower += val.VotingPower - } - } - cs.ByzantineValidatorsPower.Set(float64(byzantineValidatorsPower)) - - if block.Height > 1 { - lastBlockHight := block.Height - 1 - lastBlock, _ := ctx.Client.Block(&lastBlockHight) - interval := block.Time.Sub(lastBlock.BlockMeta.Header.Time).Seconds() - cs.BlockIntervalSeconds.Observe(interval) - } - - cs.NumTxs.Set(float64(block.NumTxs)) - cs.TotalTxs.Set(float64(block.TotalTxs)) - - bz, _ := cdc.MarshalBinaryBare(block) - cs.BlockSizeBytes.Set(float64(len(bz))) -} - -func getCandidatesNum(cdc *wire.Codec, ctx tools.Context, storeName string) int { - key := stake.ValidatorsKey - resKVs, err := ctx.QuerySubspace(cdc, key, storeName) - if err != nil { - fmt.Println(err) - } - return len(resKVs) -} diff --git a/tools/prometheus/mempool/metrics.go b/tools/prometheus/mempool/metrics.go deleted file mode 100644 index c7562993b..000000000 --- a/tools/prometheus/mempool/metrics.go +++ /dev/null @@ -1,38 +0,0 @@ -package mempool - -import ( - "github.com/go-kit/kit/metrics" - "github.com/go-kit/kit/metrics/prometheus" - tools "github.com/irisnet/irishub/tools" - stdprometheus "github.com/prometheus/client_golang/prometheus" - "time" -) - -// Metrics contains metrics exposed by this package. -// see MetricsProvider for descriptions. -type Metrics struct { - // Size of the mempool. - Size metrics.Gauge -} - -// PrometheusMetrics returns Metrics build using Prometheus client library. -func PrometheusMetrics() *Metrics { - return &Metrics{ - Size: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "mempool", - Name: "size", - Help: "Size of the mempool (number of uncommitted transactions).", - }, []string{}), - } -} - -func (m *Metrics) Start(rpc tools.Context) { - go func() { - for { - time.Sleep(1 * time.Second) - result := rpc.NumUnconfirmedTxs() - m.Size.Set(float64(result.N)) - } - }() - -} diff --git a/tools/prometheus/p2p/metrics.go b/tools/prometheus/p2p/metrics.go deleted file mode 100644 index 95817918c..000000000 --- a/tools/prometheus/p2p/metrics.go +++ /dev/null @@ -1,36 +0,0 @@ -package p2p - -import ( - "github.com/go-kit/kit/metrics" - "github.com/go-kit/kit/metrics/prometheus" - tools "github.com/irisnet/irishub/tools" - stdprometheus "github.com/prometheus/client_golang/prometheus" - "time" -) - -// Metrics contains metrics exposed by this package. -type Metrics struct { - // Number of peers. - Peers metrics.Gauge -} - -// PrometheusMetrics returns Metrics build using Prometheus client library. -func PrometheusMetrics() *Metrics { - return &Metrics{ - Peers: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "p2p", - Name: "peers", - Help: "Number of peers.", - }, []string{}), - } -} - -func (m *Metrics) Start(ctx tools.Context) { - go func() { - for { - time.Sleep(1 * time.Second) - result := ctx.NetInfo() - m.Peers.Set(float64(result.NPeers)) - } - }() -} diff --git a/tools/prometheus/provider.go b/tools/prometheus/provider.go deleted file mode 100644 index a6ecd0a64..000000000 --- a/tools/prometheus/provider.go +++ /dev/null @@ -1,42 +0,0 @@ -package prometheus - -import ( - "github.com/irisnet/irishub/tools" - cs "github.com/irisnet/irishub/tools/prometheus/consensus" - mempl "github.com/irisnet/irishub/tools/prometheus/mempool" - "github.com/irisnet/irishub/tools/prometheus/p2p" - sys "github.com/irisnet/irishub/tools/prometheus/system" -) - -type Monitor struct { - providers []MetricsProvider - ctx tools.Context -} - -func DefaultMonitor(ctx tools.Context) *Monitor { - var providers []MetricsProvider - monitor := &Monitor{ - providers: providers, - ctx:ctx, - } - monitor.AddMetricsProvider(cs.PrometheusMetrics()). - AddMetricsProvider(p2p.PrometheusMetrics()). - AddMetricsProvider(mempl.PrometheusMetrics()). - AddMetricsProvider(sys.PrometheusMetrics()) - return monitor -} - -func (m *Monitor) AddMetricsProvider(provider MetricsProvider) *Monitor { - m.providers = append(m.providers, provider) - return m -} - -func (m *Monitor) Start() { - for _, provider := range m.providers { - provider.Start(m.ctx) - } -} - -type MetricsProvider interface { - Start(ctx tools.Context) -} diff --git a/tools/prometheus/server.go b/tools/prometheus/server.go deleted file mode 100644 index b55d1934c..000000000 --- a/tools/prometheus/server.go +++ /dev/null @@ -1,55 +0,0 @@ -package prometheus - -import ( - "github.com/cosmos/cosmos-sdk/wire" - "github.com/irisnet/irishub/tools" - "github.com/prometheus/client_golang/prometheus/promhttp" - "github.com/spf13/cobra" - cmn "github.com/tendermint/tmlibs/common" - "log" - "net/http" - "github.com/irisnet/irishub/app" -) - -func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "monitor", - Short: "irishub monitor", - RunE: func(cmd *cobra.Command, args []string) error { - - ctx := tools.NewContext(storeName,cdc) - monitor := DefaultMonitor(ctx) - monitor.Start() - - srv := &http.Server{ - Addr: ":26660", - Handler: promhttp.Handler(), - } - go func() { - if err := srv.ListenAndServe(); err != http.ErrServerClosed { - log.Println("got ", err) - } - }() - - cmn.TrapSignal(func() { - ctx.Client.Stop() - srv.Close() - }) - - return nil - }, - } - cmd.Flags().StringP("node", "n", "tcp://localhost:46657", "Node to connect to") - cmd.Flags().String("chain-id", "fuxi", "Chain ID of tendermint node") - cmd.Flags().StringP("commands", "c", "iris start", `the processes you want to monitor that started -by these commands, separated by semicolons ';'. -eg: --commands="command 0;command 1;command 2", --commands=iris by default`) - cmd.Flags().StringP("disks", "d", "/", `mounted paths of storage devices, separated by semicolons ';'. -eg: --disks="/;/mnt1;/mnt2"`) - cmd.Flags().StringP("paths", "p", app.DefaultNodeHome, `path to config and data files/directories, separated by semicolons ';'. -cannot use ~ and environment variables. eg: --paths="/etc;/home; -size of files in sub-directories is excluded. to compute the size recursively, you can use --recursively=true"`) - cmd.Flags().BoolP("recursively", "r", false, `specify whether the files in sub-directories is included, -excluded by default. If there are many files & sub-directory in given directories, this program may be very slow!`) - return cmd -} diff --git a/tools/prometheus/system/metrics.go b/tools/prometheus/system/metrics.go deleted file mode 100644 index f58fe5bdc..000000000 --- a/tools/prometheus/system/metrics.go +++ /dev/null @@ -1,342 +0,0 @@ -package system - -import ( - "bytes" - "container/list" - "errors" - "fmt" - "github.com/go-kit/kit/metrics" - "github.com/go-kit/kit/metrics/prometheus" - stdprometheus "github.com/prometheus/client_golang/prometheus" - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/disk" - "github.com/shirou/gopsutil/mem" - "github.com/shirou/gopsutil/process" - "github.com/spf13/viper" - "io/ioutil" - "os" - "os/exec" - "strconv" - "strings" - "time" - "unicode" - "github.com/irisnet/irishub/tools" -) - -type Metrics struct { - CPUUtilization metrics.Gauge - MemoUtilization metrics.Gauge - - //processes related monitor term - ProcCPUUtilization []metrics.Gauge - ProcMemoUtilization []metrics.Gauge - ProcOpenedFilesNum []metrics.Gauge - processes []process.Process - - //storage related monitor term - DiskUsedPercentage []metrics.Gauge - DiskFreeSpace []metrics.Gauge - disks []string - - //file related monitor term - FileSize []metrics.Gauge - filePaths []string - recursively bool //whether compute directories size recursively - DirectorySize []metrics.Gauge - dirPaths []string -} - -// PrometheusMetrics returns Metrics build using Prometheus client library. -func PrometheusMetrics() *Metrics { - return &Metrics{ - CPUUtilization: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "system", - Name: "cpu_percent", - Help: "CPU Utilization Percantage", - }, []string{}), - MemoUtilization: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "system", - Name: "memo_percent", - Help: "Memo Utilization Percantage", - }, []string{}), - ProcCPUUtilization: make([]metrics.Gauge, 0), - ProcMemoUtilization: make([]metrics.Gauge, 0), - ProcOpenedFilesNum: make([]metrics.Gauge, 0), - DiskUsedPercentage: make([]metrics.Gauge, 0), - DiskFreeSpace: make([]metrics.Gauge, 0), - FileSize: make([]metrics.Gauge, 0), - DirectorySize: make([]metrics.Gauge, 0), - processes: make([]process.Process, 0), - recursively: false, - disks: make([]string, 0), - filePaths: make([]string, 0), - dirPaths: make([]string, 0), - } -} - -func (metrics *Metrics) addDisk(diskPath string) { - metrics.disks = append(metrics.disks, diskPath) - - name := fmt.Sprintf("disk_used_percentage_%s", getPathName(diskPath)) - help := fmt.Sprintf("Used Percentage of disk mount on path: %s", diskPath) - metrics.DiskUsedPercentage = append(metrics.DiskUsedPercentage, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "system", - Name: name, - Help: help, - }, []string{})) - - name = fmt.Sprintf("disk_free_space_%s", getPathName(diskPath)) - help = fmt.Sprintf("Free space of disk mount on path: %s", diskPath) - metrics.DiskFreeSpace = append(metrics.DiskFreeSpace, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "system", - Name: name, - Help: help, - }, []string{})) - -} - -func (metrics *Metrics) addPath(path string) { - if fileInfo, err := os.Stat(path); err != nil { - fmt.Println(err.Error()) - return - } else { - if fileInfo.IsDir() { - metrics.dirPaths = append(metrics.dirPaths, path) - name := fmt.Sprintf("direcotry_size_%s", getPathName(path)) - help := fmt.Sprintf("total Size of files in %s", path) - metrics.DirectorySize = append(metrics.DirectorySize, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "system", - Name: name, - Help: help, - }, []string{})) - } else { - metrics.filePaths = append(metrics.filePaths, path) - name := fmt.Sprintf("file_size_%s", getPathName(path)) - help := fmt.Sprintf("size of files: %s", path) - metrics.FileSize = append(metrics.FileSize, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "system", - Name: name, - Help: help, - }, []string{})) - } - } -} - -func (metrics *Metrics) add() { - commands := viper.GetString("commands") - for _, command := range strings.Split(commands, ";") { - if strings.TrimSpace(command) != "" { - metrics.addProcess(strings.TrimSpace(command)) - } - } - - disks := viper.GetString("disks") - for _, diskPath := range strings.Split(disks, ";") { - if strings.TrimSpace(diskPath) != "" { - metrics.addDisk(strings.TrimSpace(diskPath)) - } - } - - paths := viper.GetString("paths") - for _, path := range strings.Split(paths, ";") { - if strings.TrimSpace(path) != "" { - metrics.addPath(strings.TrimSpace(path)) - } - } - - recursively := viper.GetBool("recursively") - metrics.SetRecursively(recursively) - -} - -func (metrics *Metrics) addProcess(command string) { - - pid, err := getPid(command) - if err != nil { - return - } - process := process.Process{Pid: int32(pid)} - cmd, err := process.Cmdline() - if err != nil { - fmt.Println(err.Error()) - return - } - metrics.processes = append(metrics.processes, process) - - metrics.ProcCPUUtilization = append(metrics.ProcCPUUtilization, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "system", - Name: fmt.Sprintf("cpu_percent_%d", pid), - Help: fmt.Sprintf("CPU Utilization Percantage of processes with pid %d, started by command %s", pid, cmd), - }, []string{})) - - metrics.ProcMemoUtilization = append(metrics.ProcMemoUtilization, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "system", - Name: fmt.Sprintf("memo_percent_%d", pid), - Help: fmt.Sprintf("Memory Utilization Percantage of processes with pid %d, started by command %s", pid, cmd), - }, []string{})) - - metrics.ProcOpenedFilesNum = append(metrics.ProcOpenedFilesNum, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ - Subsystem: "system", - Name: fmt.Sprintf("opened_files_number_%d", pid), - Help: fmt.Sprintf("Number of Opened Files of processes with pid %d, started by command %s", pid, cmd), - }, []string{})) - -} - -func (metrics *Metrics) SetRecursively(recursively bool) { - metrics.recursively = recursively -} - -func (metrics *Metrics) Start(ctx tools.Context) { - metrics.add() - go func() { - for { - time.Sleep(1 * time.Second) - metrics.RecordMetrics() - } - }() -} - -func (metrics Metrics) RecordMetrics() { - - for i, process := range metrics.processes { - if cpuUtil, err := process.CPUPercent(); err != nil { - metrics.ProcCPUUtilization[i].Set(float64(-1)) - } else { - metrics.ProcCPUUtilization[i].Set(cpuUtil) - } - - if memoUtil, err := process.MemoryPercent(); err != nil { - metrics.ProcMemoUtilization[i].Set(float64(-1)) - } else { - metrics.ProcMemoUtilization[i].Set(float64(memoUtil)) - } - - if files, err := process.OpenFiles(); err != nil { - metrics.ProcOpenedFilesNum[i].Set(float64(-1)) - } else { - metrics.ProcOpenedFilesNum[i].Set(float64(len(files))) - } - } - - for i, diskPath := range metrics.disks { - if usage, err := disk.Usage(diskPath); err != nil { - metrics.DirectorySize[i].Set(float64(-1)) - metrics.DiskFreeSpace[i].Set(float64(-1)) - } else { - metrics.DirectorySize[i].Set(usage.UsedPercent) - metrics.DiskFreeSpace[i].Set(float64(usage.Free)) - } - } - - for i, filePath := range metrics.filePaths { - if fileInfo, err := os.Stat(filePath); err != nil { - metrics.FileSize[i].Set(float64(-1)) - } else { - metrics.FileSize[i].Set(float64(fileInfo.Size())) - } - } - - for i, dirPath := range metrics.dirPaths { - if size, err := getDirSize(dirPath, metrics.recursively); err != nil { - metrics.DirectorySize[i].Set(float64(-1)) - } else { - metrics.DirectorySize[i].Set(float64(size)) - } - } - - vMemoStat, _ := mem.VirtualMemory() - metrics.MemoUtilization.Set(vMemoStat.UsedPercent) - - CPUUsedPercent := float64(0.0) - percents, _ := cpu.Percent(time.Millisecond*100, false) - for _, percent := range percents { - CPUUsedPercent += percent - } - metrics.CPUUtilization.Set(CPUUsedPercent / float64(len(percents))) -} - -//-----------------help functions------------------------------- - -//get the pid of process that start by the given command -//the first pid return by "ps -aux|grep ", -// the process whose command contains "grep" is omitted -func getPid(command string) (pid int, err error) { - commandStr := fmt.Sprintf("ps -aux|grep '%s'", command) - cmd := exec.Command("/bin/bash", "-c", commandStr) - - stdout, err := cmd.StdoutPipe() - - if err != nil { - fmt.Printf("Error:can not obtain stdout pipe for command:%s\n", err) - return 0, err - } - - if err := cmd.Start(); err != nil { - fmt.Println("Error:Invalid command,", err) - return 0, err - } - - bytes, err := ioutil.ReadAll(stdout) - if err != nil { - fmt.Println("ReadAll Stdout:", err.Error()) - return 0, err - } - for _, item := range strings.Split(string(bytes), "\n") { - if !strings.Contains(item, "grep") { - for j, s := range strings.Split(item, " ") { - if j > 0 && s != "" { - pid, err = strconv.Atoi(s) - if err == nil { - return pid, nil - } else { - return 0, err - } - } - } - } - } - return 0, errors.New("cannot find the process") -} - -//get directory size of given path -func getDirSize(path string, recursively bool) (int64, error) { - Separator := string(os.PathSeparator) - queue := list.New() - queue.PushBack(path) - size := int64(0) - for queue.Len() > 0 { - path := fmt.Sprint(queue.Front().Value) - queue.Remove(queue.Front()) - - files, err := ioutil.ReadDir(path) - if err != nil { - return 0, err - } - for _, file := range files { - file_size := file.Size() - size += file_size - if file.IsDir() && recursively { - queue.PushBack(path + Separator + file.Name()) - } - } - } - return size, nil -} - -//conver a path to a valid Gauge monitor term name -func getPathName(path string) string { - var buffer bytes.Buffer - - for i, ch := range path { - if i == 0 && unicode.IsDigit(ch) { - buffer.WriteString("_") - } - if unicode.IsDigit(ch) || unicode.IsLetter(ch) { - buffer.WriteByte(byte(ch)) - } else { - buffer.WriteByte(byte('_')) - } - } - return buffer.String() -} diff --git a/version/version.go b/version/version.go index 885bbb7fa..720c65e4b 100644 --- a/version/version.go +++ b/version/version.go @@ -4,11 +4,10 @@ import ( "fmt" "github.com/spf13/cobra" - "net/http" ) // Version - Iris Version -const Version = "0.2.0" +const Version = "0.1.0" // VersionCmd - The version of gaia var VersionCmd = &cobra.Command{ @@ -18,8 +17,3 @@ var VersionCmd = &cobra.Command{ fmt.Printf("v%s\n", Version) }, } - -// version REST handler endpoint -func RequestHandler(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(Version)) -} From 07188a050c9ae4fe508ea950c05879bcd25fd1e0 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Wed, 11 Jul 2018 11:43:52 +0800 Subject: [PATCH 061/124] Code optimization --- Gopkg.lock | 59 +++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 47 insertions(+), 12 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index 92e47b418..9186ec603 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -1,6 +1,12 @@ # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. +[[projects]] + name = "github.com/StackExchange/wmi" + packages = ["."] + revision = "5d049714c4a64225c3c79a7cf7d02f7fb5b96338" + version = "1.0.0" + [[projects]] branch = "master" name = "github.com/beorn7/perks" @@ -17,13 +23,13 @@ branch = "master" name = "github.com/btcsuite/btcd" packages = ["btcec"] - revision = "86fed781132ac890ee03e906e4ecd5d6fa180c64" + revision = "fdfc19097e7ac6b57035062056f5b7b4638b8898" [[projects]] branch = "master" name = "github.com/btcsuite/btcutil" packages = ["bech32"] - revision = "d4cc87b860166d00d6b5b9e0d3b3d71d6088d4d4" + revision = "ab6388e0c60ae4834a1f57511e20c17b5f78be4b" [[projects]] name = "github.com/cosmos/cosmos-sdk" @@ -95,6 +101,15 @@ revision = "390ab7935ee28ec6b286364bba9b4dd6410cb3d5" version = "v0.3.0" +[[projects]] + name = "github.com/go-ole/go-ole" + packages = [ + ".", + "oleutil" + ] + revision = "a41e3c4b706f6ae8dfbff342b06e40fa4d2d0506" + version = "v1.2.1" + [[projects]] name = "github.com/go-stack/stack" packages = ["."] @@ -193,10 +208,7 @@ [[projects]] name = "github.com/magiconair/properties" - packages = [ - ".", - "assert" - ] + packages = ["."] revision = "c2353362d570a7bfa228149c62842019201cfb71" version = "v1.8.0" @@ -270,7 +282,7 @@ "nfs", "xfs" ] - revision = "40f013a808ec4fa79def444a1a56de4d1727efcb" + revision = "ae68e2d4c00fed4943b5f6698d504a5fe083da8a" [[projects]] branch = "master" @@ -278,6 +290,26 @@ packages = ["."] revision = "e2704e165165ec55d062f5919b4b29494e9fa790" +[[projects]] + name = "github.com/shirou/gopsutil" + packages = [ + "cpu", + "disk", + "host", + "internal/common", + "mem", + "net", + "process" + ] + revision = "4a180b209f5f494e5923cfce81ea30ba23915877" + version = "v2.18.06" + +[[projects]] + branch = "master" + name = "github.com/shirou/w32" + packages = ["."] + revision = "bb4de0191aa41b5507caa14b0650cdbddcd9280b" + [[projects]] name = "github.com/spf13/afero" packages = [ @@ -343,7 +375,7 @@ "leveldb/table", "leveldb/util" ] - revision = "0d5a0ceb10cf9ab89fdd744cc8c50a83134f6697" + revision = "c4c61651e9e37fa117f53c5a906d3b63090d8445" [[projects]] name = "github.com/tendermint/abci" @@ -484,13 +516,16 @@ "internal/timeseries", "trace" ] - revision = "ed29d75add3d7c4bf7ca65aac0c6df3d1420216f" + revision = "039a4258aec0ad3c79b905677cceeab13b296a77" [[projects]] branch = "master" name = "golang.org/x/sys" - packages = ["unix"] - revision = "151529c776cdc58ddbe7963ba9af779f3577b419" + packages = [ + "unix", + "windows" + ] + revision = "1b2967e3c290b7c545b3db0deeda16e9be4f98a2" [[projects]] name = "golang.org/x/text" @@ -551,6 +586,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "d1273093894dceda82a36f80e217187acee7f2f34b020c05fb89352ff249c850" + inputs-digest = "05055f1f3d679b69505e896cdf0eff31029dc441cc947dd0e59d30b05874b8de" solver-name = "gps-cdcl" solver-version = 1 From bd8a3ca1a25481d0ffeda3c8d5888b2d77d58279 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Wed, 11 Jul 2018 18:45:51 +0800 Subject: [PATCH 062/124] change bond token from steak to iris --- Gopkg.lock | 7 ++++--- Gopkg.toml | 5 +++-- app/genesis.go | 4 +--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index 9186ec603..ee4107d13 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -61,8 +61,9 @@ "x/stake/client/cli", "x/stake/client/rest" ] - revision = "1e6d26ad3dce18fd1dde9bbee7d2aa192c196310" - version = "v0.19.1-rc1" + revision = "b0071fcae35221c1a34077890391235b85826695" + source = "https://github.com/irisnet/cosmos-sdk.git" + version = "v0.19.1-rc2" [[projects]] name = "github.com/davecgh/go-spew" @@ -586,6 +587,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "05055f1f3d679b69505e896cdf0eff31029dc441cc947dd0e59d30b05874b8de" + inputs-digest = "c8d0b1f5dfd1ecb4be7a0aa43ddf7e33b7a9dda629ada5655e831f07faad9047" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index f5ce9e94b..762dec50f 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -32,9 +32,10 @@ name = "github.com/spf13/viper" version = "~1.0.0" -[[constraint]] +[[override]] name = "github.com/cosmos/cosmos-sdk" - version = "v0.19.1-rc1" + version = "v0.19.1-rc2" + source = "https://github.com/irisnet/cosmos-sdk.git" [[constraint]] name = "github.com/tendermint/abci" diff --git a/app/genesis.go b/app/genesis.go index 924cfdebc..520a2093e 100644 --- a/app/genesis.go +++ b/app/genesis.go @@ -148,7 +148,7 @@ func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState // start with the default staking genesis state //stakeData := stake.DefaultGenesisState() - stakeData := stake.DefaultGenesisState() + stakeData := createGenesisState() // get genesis flag account information genaccs := make([]GenesisAccount, len(appGenTxs)) @@ -164,7 +164,6 @@ func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState accAuth := auth.NewBaseAccountWithAddress(genTx.Address) accAuth.Coins = sdk.Coins{ {denom, totalTokenAmt}, - {"steak", freeFermionVal}, } acc := NewGenesisAccount(&accAuth) genaccs[i] = acc @@ -203,7 +202,6 @@ func IrisAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState return } -// TODO func createGenesisState() stake.GenesisState { return stake.GenesisState{ Pool: stake.Pool{ From 1bbc10a58b4e1069158ce605cc450f98ba4f5c70 Mon Sep 17 00:00:00 2001 From: zhangzhiqiang <745124335@aa.com> Date: Thu, 12 Jul 2018 09:49:47 +0800 Subject: [PATCH 063/124] change bond token from steak to iris --- app/genesis.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/genesis.go b/app/genesis.go index 520a2093e..c4e6751d6 100644 --- a/app/genesis.go +++ b/app/genesis.go @@ -223,7 +223,7 @@ func createGenesisState() stake.GenesisState { InflationMin: sdk.NewRat(7, 100), GoalBonded: sdk.NewRat(67, 100), MaxValidators: 100, - BondDenom: "steak", + BondDenom: denom, }, } } From 8abf4f7fd3bcb77654501f1a6dd37da079f75ccb Mon Sep 17 00:00:00 2001 From: Yelong Zhang Date: Thu, 12 Jul 2018 14:29:38 +0800 Subject: [PATCH 064/124] Update genesis.json --- testnets/develop/config/genesis.json | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/testnets/develop/config/genesis.json b/testnets/develop/config/genesis.json index 7e45a374f..d802ba336 100644 --- a/testnets/develop/config/genesis.json +++ b/testnets/develop/config/genesis.json @@ -27,10 +27,6 @@ { "denom": "iris", "amount": 200000000 - }, - { - "denom": "steak", - "amount": 100 } ] } @@ -55,7 +51,7 @@ "inflation_min": "7/100", "goal_bonded": "67/100", "max_validators": 100, - "bond_denom": "steak" + "bond_denom": "iris" }, "validators": [ { @@ -99,4 +95,4 @@ "name": "" } ] -} \ No newline at end of file +} From e20e0bdb0a850255f3f885c1e5b43c1691ef0560 Mon Sep 17 00:00:00 2001 From: programokey <872127164@qq.com> Date: Thu, 12 Jul 2018 20:48:58 -0700 Subject: [PATCH 065/124] modify name of processes related monitor terms & add processes number monitor term --- tools/prometheus/system/metrics.go | 79 ++++++++++++++++++++++++++---- 1 file changed, 69 insertions(+), 10 deletions(-) diff --git a/tools/prometheus/system/metrics.go b/tools/prometheus/system/metrics.go index 006717542..1b1af752a 100644 --- a/tools/prometheus/system/metrics.go +++ b/tools/prometheus/system/metrics.go @@ -32,6 +32,10 @@ type Metrics struct { ProcOpenedFilesNum []metrics.Gauge processes []process.Process + //cmd related monitor term + cmd []string + ProcNum []metrics.Gauge + //storage related monitor term DiskUsedPercentage []metrics.Gauge DiskFreeSpace []metrics.Gauge @@ -66,10 +70,14 @@ func PrometheusMetrics() *Metrics { FileSize: make([]metrics.Gauge, 0), DirectorySize: make([]metrics.Gauge, 0), processes: make([]process.Process, 0), - recursively: false, - disks: make([]string, 0), - filePaths: make([]string, 0), - dirPaths: make([]string, 0), + + ProcNum: make([]metrics.Gauge, 0), + cmd: make([]string, 0), + + recursively: false, + disks: make([]string, 0), + filePaths: make([]string, 0), + dirPaths: make([]string, 0), } } @@ -149,6 +157,16 @@ func (metrics *Metrics) add() { } func (metrics *Metrics) addProcess(command string) { + //if num, err := getProcessNum() + name_command := getPathName(command) + + metrics.cmd = append(metrics.cmd, command) + + metrics.ProcNum = append(metrics.ProcNum, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: fmt.Sprintf("process_number_%s", name_command), + Help: fmt.Sprintf("Process number of processes started by command %s", command), + }, []string{})) pid, err := getPid(command) if err != nil { @@ -164,19 +182,19 @@ func (metrics *Metrics) addProcess(command string) { metrics.ProcCPUUtilization = append(metrics.ProcCPUUtilization, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", - Name: fmt.Sprintf("cpu_percent_%d", pid), + Name: fmt.Sprintf("cpu_percent_%s", name_command), Help: fmt.Sprintf("CPU Utilization Percantage of processes with pid %d, started by command %s", pid, cmd), }, []string{})) metrics.ProcMemoUtilization = append(metrics.ProcMemoUtilization, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", - Name: fmt.Sprintf("memo_percent_%d", pid), + Name: fmt.Sprintf("memo_percent_%s", name_command), Help: fmt.Sprintf("Memory Utilization Percantage of processes with pid %d, started by command %s", pid, cmd), }, []string{})) metrics.ProcOpenedFilesNum = append(metrics.ProcOpenedFilesNum, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ Subsystem: "system", - Name: fmt.Sprintf("opened_files_number_%d", pid), + Name: fmt.Sprintf("opened_files_number_%s", name_command), Help: fmt.Sprintf("Number of Opened Files of processes with pid %d, started by command %s", pid, cmd), }, []string{})) @@ -199,6 +217,14 @@ func (metrics *Metrics) Monitor() error { func (metrics Metrics) RecordMetrics() { + for i, cmd := range metrics.cmd { + if num, err := getProcessNum(cmd); err != nil { + metrics.ProcNum[i].Set(float64(-1)) + } else { + metrics.ProcNum[i].Set(float64(num)) + } + } + for i, process := range metrics.processes { if cpuUtil, err := process.CPUPercent(); err != nil { metrics.ProcCPUUtilization[i].Set(float64(-1)) @@ -221,10 +247,10 @@ func (metrics Metrics) RecordMetrics() { for i, diskPath := range metrics.disks { if usage, err := disk.Usage(diskPath); err != nil { - metrics.DirectorySize[i].Set(float64(-1)) + metrics.DiskUsedPercentage[i].Set(float64(-1)) metrics.DiskFreeSpace[i].Set(float64(-1)) } else { - metrics.DirectorySize[i].Set(usage.UsedPercent) + metrics.DiskUsedPercentage[i].Set(usage.UsedPercent) metrics.DiskFreeSpace[i].Set(float64(usage.Free)) } } @@ -258,7 +284,40 @@ func (metrics Metrics) RecordMetrics() { //-----------------help functions------------------------------- -//get the pid of process that start by the given command +//get the number of process that started by the given command +func getProcessNum(command string) (num int, err error) { + commandStr := fmt.Sprintf("ps -aux|grep '%s'|grep -v 'grep'|wc -l", command) + cmd := exec.Command("/bin/bash", "-c", commandStr) + + stdout, err := cmd.StdoutPipe() + + if err != nil { + fmt.Printf("Error:can not obtain stdout pipe for command:%s\n", err) + return 0, err + } + + if err := cmd.Start(); err != nil { + fmt.Println("Error:Invalid command,", err) + return 0, err + } + + bytes, err := ioutil.ReadAll(stdout) + if err != nil { + fmt.Println("ReadAll Stdout:", err.Error()) + return 0, err + } + str := string(bytes) + str = str[:len(str) - 1] + num, err = strconv.Atoi(str) + + if err == nil { + return num, nil + } else { + return 0, err + } +} + +//get the pid of process that started by the given command //the first pid return by "ps -aux|grep ", // the process whose command contains "grep" is omitted func getPid(command string) (pid int, err error) { From a364e50b340b7e8f390cb5187bf29ab1ffb24e11 Mon Sep 17 00:00:00 2001 From: programokey <872127164@qq.com> Date: Thu, 12 Jul 2018 20:56:00 -0700 Subject: [PATCH 066/124] modify name of processes related monitor terms & add processes number monitor term --- tools/prometheus/system/metrics.go | 1 - 1 file changed, 1 deletion(-) diff --git a/tools/prometheus/system/metrics.go b/tools/prometheus/system/metrics.go index 1b1af752a..53187e8be 100644 --- a/tools/prometheus/system/metrics.go +++ b/tools/prometheus/system/metrics.go @@ -157,7 +157,6 @@ func (metrics *Metrics) add() { } func (metrics *Metrics) addProcess(command string) { - //if num, err := getProcessNum() name_command := getPathName(command) metrics.cmd = append(metrics.cmd, command) From f38c2027a75654f77576f1ddd8792da411bd5864 Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Wed, 18 Jul 2018 21:27:52 +0800 Subject: [PATCH 067/124] add changelog --- CHANGELOG.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..e69de29bb From 57832f311b260173a3ae641d91c8203d8cfc28a8 Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Wed, 18 Jul 2018 21:32:02 +0800 Subject: [PATCH 068/124] update changelog --- CHANGELOG.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e69de29bb..db45eb86e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog + +## 0.2.0 + +*July 19th, 2018* + +BREAKING CHANGES: + +- [tendermint] Upgrade to Tendermint v0.21.0 +- [cosmos-sdk] Upgrade to cosmos-sdk v0.19.1-rc1 + +FEATURES: + +- [lcd] code rego + +- [cli] improve sendingand querying the transactions + +- [monitor]export data which is collected by Prometheus Server + + ​ + +## \ No newline at end of file From 004036ecd6c0ba08d7540a01bc51472db64bf1dc Mon Sep 17 00:00:00 2001 From: Yelong Zhang Date: Wed, 18 Jul 2018 21:39:41 +0800 Subject: [PATCH 069/124] Revert "Revert "feature/prometheus"" --- .dockerignore | 3 + Dockerfile | 41 +- Dockerfile-dev | 42 ++ Gopkg.lock | 556 ++++++++++++++++++ Gopkg.toml | 70 +++ Makefile | 21 +- README.md | 217 +++---- app/app.go | 181 ++++++ app/context.go | 28 + app/genesis.go | 231 ++++++++ cmd/iris/client.go | 97 --- cmd/iris/main.go | 74 ++- cmd/iris/node.go | 69 --- cmd/iris/rest.go | 95 --- cmd/iris/rest_test.go | 77 --- cmd/iris/sh_tests/stake.sh | 276 --------- cmd/iriscli/lcd.go | 85 +++ cmd/iriscli/lcd_test.go | 34 ++ cmd/iriscli/main.go | 124 ++++ cmd/iriscli/offline_sign.go | 119 ++++ glide.lock | 305 ---------- glide.yaml | 17 - module/rest-txs/txs.go | 53 -- rest/byteTx.go | 118 ---- testnets/develop/README.md | 28 + testnets/develop/config/genesis.json | 102 ++++ ...17b3821cf22382b7afe03e30bd04d1b4f10eb.json | 20 + testnets/develop/config/node_key.json | 1 + testnets/develop/config/priv_validator.json | 14 + testnets/develop/seed_phrase | 1 + testnets/develop/start-docker.sh | 5 + testnets/develop/start.sh | 20 + tools/context.go | 90 +++ tools/prometheus/consensus/metrics.go | 215 +++++++ tools/prometheus/mempool/metrics.go | 38 ++ tools/prometheus/p2p/metrics.go | 36 ++ tools/prometheus/provider.go | 42 ++ tools/prometheus/server.go | 55 ++ tools/prometheus/system/metrics.go | 342 +++++++++++ version/version.go | 8 +- 40 files changed, 2644 insertions(+), 1306 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile-dev create mode 100644 Gopkg.lock create mode 100644 Gopkg.toml create mode 100644 app/app.go create mode 100644 app/context.go create mode 100644 app/genesis.go delete mode 100644 cmd/iris/client.go delete mode 100644 cmd/iris/node.go delete mode 100644 cmd/iris/rest.go delete mode 100644 cmd/iris/rest_test.go delete mode 100644 cmd/iris/sh_tests/stake.sh create mode 100644 cmd/iriscli/lcd.go create mode 100644 cmd/iriscli/lcd_test.go create mode 100644 cmd/iriscli/main.go create mode 100644 cmd/iriscli/offline_sign.go delete mode 100644 glide.lock delete mode 100644 glide.yaml delete mode 100644 module/rest-txs/txs.go delete mode 100644 rest/byteTx.go create mode 100644 testnets/develop/README.md create mode 100644 testnets/develop/config/genesis.json create mode 100644 testnets/develop/config/gentx/gentx-7db17b3821cf22382b7afe03e30bd04d1b4f10eb.json create mode 100644 testnets/develop/config/node_key.json create mode 100644 testnets/develop/config/priv_validator.json create mode 100644 testnets/develop/seed_phrase create mode 100644 testnets/develop/start-docker.sh create mode 100644 testnets/develop/start.sh create mode 100644 tools/context.go create mode 100644 tools/prometheus/consensus/metrics.go create mode 100644 tools/prometheus/mempool/metrics.go create mode 100644 tools/prometheus/p2p/metrics.go create mode 100644 tools/prometheus/provider.go create mode 100644 tools/prometheus/server.go create mode 100644 tools/prometheus/system/metrics.go diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..ddf1a56b6 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,3 @@ +Dockerfile +build/ +vendor/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 94c28973d..28f663a27 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,29 +1,38 @@ + # Simple usage with a mounted data directory: -# > docker build -t iris . -# > docker run -it --rm -v "/mnt/volumes/pangu:/iris" iris init [address]--home=/iris -# > docker run -it --rm -v "/mnt/volumes/pangu:/iris" iris start --home=/iris +# > docker build -t irishub . +# > docker run -v $HOME/.iris:/root/.iris iris init +# > docker run -v $HOME/.iris:/root/.iris iris start FROM alpine:edge -ADD ./build/ /usr/local/bin/ - -ENV DATA_ROOT /iris - -# Set user right away for determinism -RUN addgroup gaiauser && \ - adduser -S -G gaiauser gaiauser +# Set up dependencies +ENV PACKAGES go make git libc-dev bash -# Create directory for persistence and give our user ownership -RUN mkdir -p $DATA_ROOT && \ - chown -R gaiauser:gaiauser $DATA_ROOT +# Set up GOPATH & PATH -VOLUME $DATA_ROOT +ENV GOPATH /root/go +ENV BASE_PATH $GOPATH/src/github.com/irisnet +ENV REPO_PATH $BASE_PATH/irishub +ENV PATH $GOPATH/bin:$PATH # p2p port EXPOSE 46656 # rpc port EXPOSE 46657 -WORKDIR /bianjie/ +# Add source files +COPY . $REPO_PATH/ + +# Install minimum necessary dependencies, build Cosmos SDK, remove packages +RUN cd $REPO_PATH && \ + apk add --no-cache $PACKAGES && \ + go get github.com/golang/dep/cmd/dep && \ + make get_vendor_deps && \ + make build_linux && \ + cp build/* /usr/local/bin/ && \ + cd / && \ + apk del $PACKAGES && \ + rm -rf $GOPATH/ && \ + rm -rf /root/.cache/ -ENTRYPOINT ["iris"] \ No newline at end of file diff --git a/Dockerfile-dev b/Dockerfile-dev new file mode 100644 index 000000000..de04a6f32 --- /dev/null +++ b/Dockerfile-dev @@ -0,0 +1,42 @@ +# Using cache for development +# Simple usage with a mounted data directory: +# > docker build -t irishub:develop -f Dockerfile-dev . +# > docker run -v $HOME/.iris:/root/.iris iris init +# > docker run -v $HOME/.iris:/root/.iris iris start + +FROM alpine:edge + +# Set up dependencies +ENV PACKAGES go glide make git libc-dev bash + +# Set up GOPATH & PATH + +ENV GOPATH /root/go +ENV BASE_PATH $GOPATH/src/github.com/irisnet +ENV REPO_PATH $BASE_PATH/irishub +ENV PATH $GOPATH/bin:$PATH + +# Link expected Go repo path + +RUN mkdir -p $WORKDIR $GOPATH/pkg $GOPATH/bin $BASE_PATH && \ + apk add --no-cache $PACKAGES && \ + go get github.com/golang/dep/cmd/dep + +# List project dependencies with Gopkg.toml and Gopkg.lock +# These layers are only re-built when Gopkg files are updated +COPY Gopkg.lock Gopkg.toml $REPO_PATH/ + +WORKDIR $REPO_PATH + +RUN dep ensure -vendor-only + +# p2p port +EXPOSE 46656 +# rpc port +EXPOSE 46657 + +# Add source files +COPY . $REPO_PATH/ + +RUN make build_linux && \ + mv build/* /usr/local/bin/ \ No newline at end of file diff --git a/Gopkg.lock b/Gopkg.lock new file mode 100644 index 000000000..92e47b418 --- /dev/null +++ b/Gopkg.lock @@ -0,0 +1,556 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + branch = "master" + name = "github.com/beorn7/perks" + packages = ["quantile"] + revision = "3a771d992973f24aa725d07868b467d1ddfceafb" + +[[projects]] + name = "github.com/bgentry/speakeasy" + packages = ["."] + revision = "4aabc24848ce5fd31929f7d1e4ea74d3709c14cd" + version = "v0.1.0" + +[[projects]] + branch = "master" + name = "github.com/btcsuite/btcd" + packages = ["btcec"] + revision = "86fed781132ac890ee03e906e4ecd5d6fa180c64" + +[[projects]] + branch = "master" + name = "github.com/btcsuite/btcutil" + packages = ["bech32"] + revision = "d4cc87b860166d00d6b5b9e0d3b3d71d6088d4d4" + +[[projects]] + name = "github.com/cosmos/cosmos-sdk" + packages = [ + "baseapp", + "client", + "client/context", + "client/keys", + "client/rpc", + "client/tx", + "server", + "store", + "types", + "version", + "wire", + "x/auth", + "x/auth/client/cli", + "x/auth/client/rest", + "x/bank", + "x/bank/client", + "x/bank/client/cli", + "x/bank/client/rest", + "x/ibc", + "x/ibc/client/cli", + "x/ibc/client/rest", + "x/slashing", + "x/slashing/client/cli", + "x/stake", + "x/stake/client/cli", + "x/stake/client/rest" + ] + revision = "1e6d26ad3dce18fd1dde9bbee7d2aa192c196310" + version = "v0.19.1-rc1" + +[[projects]] + name = "github.com/davecgh/go-spew" + packages = ["spew"] + revision = "346938d642f2ec3594ed81d874461961cd0faa76" + version = "v1.1.0" + +[[projects]] + branch = "master" + name = "github.com/ebuchman/fail-test" + packages = ["."] + revision = "95f809107225be108efcf10a3509e4ea6ceef3c4" + +[[projects]] + name = "github.com/fsnotify/fsnotify" + packages = ["."] + revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" + version = "v1.4.7" + +[[projects]] + name = "github.com/go-kit/kit" + packages = [ + "log", + "log/level", + "log/term", + "metrics", + "metrics/internal/lv", + "metrics/prometheus" + ] + revision = "4dc7be5d2d12881735283bcab7352178e190fc71" + version = "v0.6.0" + +[[projects]] + name = "github.com/go-logfmt/logfmt" + packages = ["."] + revision = "390ab7935ee28ec6b286364bba9b4dd6410cb3d5" + version = "v0.3.0" + +[[projects]] + name = "github.com/go-stack/stack" + packages = ["."] + revision = "259ab82a6cad3992b4e21ff5cac294ccb06474bc" + version = "v1.7.0" + +[[projects]] + name = "github.com/gogo/protobuf" + packages = [ + "gogoproto", + "jsonpb", + "proto", + "protoc-gen-gogo/descriptor", + "sortkeys", + "types" + ] + revision = "1adfc126b41513cc696b209667c8656ea7aac67c" + version = "v1.0.0" + +[[projects]] + name = "github.com/golang/protobuf" + packages = [ + "proto", + "ptypes", + "ptypes/any", + "ptypes/duration", + "ptypes/timestamp" + ] + revision = "925541529c1fa6821df4e44ce2723319eb2be768" + version = "v1.0.0" + +[[projects]] + branch = "master" + name = "github.com/golang/snappy" + packages = ["."] + revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" + +[[projects]] + name = "github.com/gorilla/context" + packages = ["."] + revision = "08b5f424b9271eedf6f9f0ce86cb9396ed337a42" + version = "v1.1.1" + +[[projects]] + name = "github.com/gorilla/mux" + packages = ["."] + revision = "e3702bed27f0d39777b0b37b664b6280e8ef8fbf" + version = "v1.6.2" + +[[projects]] + name = "github.com/gorilla/websocket" + packages = ["."] + revision = "ea4d1f681babbce9545c9c5f3d5194a789c89f5b" + version = "v1.2.0" + +[[projects]] + branch = "master" + name = "github.com/hashicorp/hcl" + packages = [ + ".", + "hcl/ast", + "hcl/parser", + "hcl/printer", + "hcl/scanner", + "hcl/strconv", + "hcl/token", + "json/parser", + "json/scanner", + "json/token" + ] + revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" + +[[projects]] + branch = "master" + name = "github.com/howeyc/crc16" + packages = ["."] + revision = "2b2a61e366a66d3efb279e46176e7291001e0354" + +[[projects]] + name = "github.com/inconshreveable/mousetrap" + packages = ["."] + revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75" + version = "v1.0" + +[[projects]] + branch = "master" + name = "github.com/jmhodges/levigo" + packages = ["."] + revision = "c42d9e0ca023e2198120196f842701bb4c55d7b9" + +[[projects]] + branch = "master" + name = "github.com/kr/logfmt" + packages = ["."] + revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0" + +[[projects]] + name = "github.com/magiconair/properties" + packages = [ + ".", + "assert" + ] + revision = "c2353362d570a7bfa228149c62842019201cfb71" + version = "v1.8.0" + +[[projects]] + name = "github.com/mattn/go-isatty" + packages = ["."] + revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" + version = "v0.0.3" + +[[projects]] + name = "github.com/matttproud/golang_protobuf_extensions" + packages = ["pbutil"] + revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" + version = "v1.0.1" + +[[projects]] + branch = "master" + name = "github.com/mitchellh/mapstructure" + packages = ["."] + revision = "bb74f1db0675b241733089d5a1faa5dd8b0ef57b" + +[[projects]] + name = "github.com/pelletier/go-toml" + packages = ["."] + revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194" + version = "v1.2.0" + +[[projects]] + name = "github.com/pkg/errors" + packages = ["."] + revision = "645ef00459ed84a119197bfb8d8205042c6df63d" + version = "v0.8.0" + +[[projects]] + name = "github.com/pmezard/go-difflib" + packages = ["difflib"] + revision = "792786c7400a136282c1664665ae0a8db921c6c2" + version = "v1.0.0" + +[[projects]] + name = "github.com/prometheus/client_golang" + packages = [ + "prometheus", + "prometheus/promhttp" + ] + revision = "c5b7fccd204277076155f10851dad72b76a49317" + version = "v0.8.0" + +[[projects]] + branch = "master" + name = "github.com/prometheus/client_model" + packages = ["go"] + revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c" + +[[projects]] + branch = "master" + name = "github.com/prometheus/common" + packages = [ + "expfmt", + "internal/bitbucket.org/ww/goautoneg", + "model" + ] + revision = "7600349dcfe1abd18d72d3a1770870d9800a7801" + +[[projects]] + branch = "master" + name = "github.com/prometheus/procfs" + packages = [ + ".", + "internal/util", + "nfs", + "xfs" + ] + revision = "40f013a808ec4fa79def444a1a56de4d1727efcb" + +[[projects]] + branch = "master" + name = "github.com/rcrowley/go-metrics" + packages = ["."] + revision = "e2704e165165ec55d062f5919b4b29494e9fa790" + +[[projects]] + name = "github.com/spf13/afero" + packages = [ + ".", + "mem" + ] + revision = "787d034dfe70e44075ccc060d346146ef53270ad" + version = "v1.1.1" + +[[projects]] + name = "github.com/spf13/cast" + packages = ["."] + revision = "8965335b8c7107321228e3e3702cab9832751bac" + version = "v1.2.0" + +[[projects]] + name = "github.com/spf13/cobra" + packages = ["."] + revision = "ef82de70bb3f60c65fb8eebacbb2d122ef517385" + version = "v0.0.3" + +[[projects]] + branch = "master" + name = "github.com/spf13/jwalterweatherman" + packages = ["."] + revision = "7c0cea34c8ece3fbeb2b27ab9b59511d360fb394" + +[[projects]] + name = "github.com/spf13/pflag" + packages = ["."] + revision = "583c0c0531f06d5278b7d917446061adc344b5cd" + version = "v1.0.1" + +[[projects]] + name = "github.com/spf13/viper" + packages = ["."] + revision = "b5e8006cbee93ec955a89ab31e0e3ce3204f3736" + version = "v1.0.2" + +[[projects]] + name = "github.com/stretchr/testify" + packages = [ + "assert", + "require" + ] + revision = "f35b8ab0b5a2cef36673838d662e249dd9c94686" + version = "v1.2.2" + +[[projects]] + branch = "master" + name = "github.com/syndtr/goleveldb" + packages = [ + "leveldb", + "leveldb/cache", + "leveldb/comparer", + "leveldb/errors", + "leveldb/filter", + "leveldb/iterator", + "leveldb/journal", + "leveldb/memdb", + "leveldb/opt", + "leveldb/storage", + "leveldb/table", + "leveldb/util" + ] + revision = "0d5a0ceb10cf9ab89fdd744cc8c50a83134f6697" + +[[projects]] + name = "github.com/tendermint/abci" + packages = [ + "client", + "example/code", + "example/kvstore", + "server", + "types" + ] + revision = "198dccf0ddfd1bb176f87657e3286a05a6ed9540" + version = "v0.12.0" + +[[projects]] + branch = "master" + name = "github.com/tendermint/ed25519" + packages = [ + ".", + "edwards25519", + "extra25519" + ] + revision = "d8387025d2b9d158cf4efb07e7ebf814bcce2057" + +[[projects]] + name = "github.com/tendermint/go-amino" + packages = ["."] + revision = "ed62928576cfcaf887209dc96142cd79cdfff389" + version = "0.9.9" + +[[projects]] + name = "github.com/tendermint/go-crypto" + packages = [ + ".", + "keys", + "keys/bcrypt", + "keys/words", + "keys/words/wordlist" + ] + revision = "915416979bf70efa4bcbf1c6cd5d64c5fff9fc19" + version = "v0.6.2" + +[[projects]] + name = "github.com/tendermint/iavl" + packages = [ + ".", + "sha256truncated" + ] + revision = "c9206995e8f948e99927f5084a88a7e94ca256da" + version = "v0.8.0-rc0" + +[[projects]] + name = "github.com/tendermint/tendermint" + packages = [ + "blockchain", + "cmd/tendermint/commands", + "config", + "consensus", + "consensus/types", + "evidence", + "libs/events", + "libs/pubsub", + "libs/pubsub/query", + "lite", + "lite/client", + "lite/errors", + "lite/files", + "lite/proxy", + "mempool", + "node", + "p2p", + "p2p/conn", + "p2p/pex", + "p2p/upnp", + "privval", + "proxy", + "rpc/client", + "rpc/core", + "rpc/core/types", + "rpc/grpc", + "rpc/lib", + "rpc/lib/client", + "rpc/lib/server", + "rpc/lib/types", + "state", + "state/txindex", + "state/txindex/kv", + "state/txindex/null", + "types", + "version" + ] + revision = "46369a1ab76f274ab47179c4176221842b8207b4" + version = "v0.21.0" + +[[projects]] + name = "github.com/tendermint/tmlibs" + packages = [ + "autofile", + "bech32", + "cli", + "cli/flags", + "clist", + "common", + "db", + "flowrate", + "log", + "merkle", + "merkle/tmhash" + ] + revision = "49596e0a1f48866603813df843c9409fc19805c6" + version = "v0.9.0" + +[[projects]] + branch = "master" + name = "golang.org/x/crypto" + packages = [ + "blowfish", + "curve25519", + "internal/subtle", + "nacl/box", + "nacl/secretbox", + "openpgp/armor", + "openpgp/errors", + "poly1305", + "ripemd160", + "salsa20/salsa" + ] + revision = "a49355c7e3f8fe157a85be2f77e6e269a0f89602" + +[[projects]] + branch = "master" + name = "golang.org/x/net" + packages = [ + "context", + "http/httpguts", + "http2", + "http2/hpack", + "idna", + "internal/timeseries", + "trace" + ] + revision = "ed29d75add3d7c4bf7ca65aac0c6df3d1420216f" + +[[projects]] + branch = "master" + name = "golang.org/x/sys" + packages = ["unix"] + revision = "151529c776cdc58ddbe7963ba9af779f3577b419" + +[[projects]] + name = "golang.org/x/text" + packages = [ + "collate", + "collate/build", + "internal/colltab", + "internal/gen", + "internal/tag", + "internal/triegen", + "internal/ucd", + "language", + "secure/bidirule", + "transform", + "unicode/bidi", + "unicode/cldr", + "unicode/norm", + "unicode/rangetable" + ] + revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" + version = "v0.3.0" + +[[projects]] + name = "google.golang.org/genproto" + packages = ["googleapis/rpc/status"] + revision = "7fd901a49ba6a7f87732eb344f6e3c5b19d1b200" + +[[projects]] + name = "google.golang.org/grpc" + packages = [ + ".", + "balancer", + "codes", + "connectivity", + "credentials", + "grpclb/grpc_lb_v1/messages", + "grpclog", + "internal", + "keepalive", + "metadata", + "naming", + "peer", + "resolver", + "stats", + "status", + "tap", + "transport" + ] + revision = "5b3c4e850e90a4cf6a20ebd46c8b32a0a3afcb9e" + version = "v1.7.5" + +[[projects]] + name = "gopkg.in/yaml.v2" + packages = ["."] + revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" + version = "v2.2.1" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + inputs-digest = "d1273093894dceda82a36f80e217187acee7f2f34b020c05fb89352ff249c850" + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml new file mode 100644 index 000000000..f5ce9e94b --- /dev/null +++ b/Gopkg.toml @@ -0,0 +1,70 @@ +# Gopkg.toml example +# +# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md +# for detailed Gopkg.toml documentation. +# +# required = ["github.com/user/thing/cmd/thing"] +# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] +# +# [[constraint]] +# name = "github.com/user/project" +# version = "1.0.0" +# +# [[constraint]] +# name = "github.com/user/project2" +# branch = "dev" +# source = "github.com/myfork/project2" +# +# [[override]] +# name = "github.com/x/y" +# version = "2.4.0" +# +# [prune] +# non-go = false +# go-tests = true +# unused-packages = true + +[[constraint]] + name = "github.com/spf13/cobra" + version = "~0.0.1" + +[[constraint]] + name = "github.com/spf13/viper" + version = "~1.0.0" + +[[constraint]] + name = "github.com/cosmos/cosmos-sdk" + version = "v0.19.1-rc1" + +[[constraint]] + name = "github.com/tendermint/abci" + version = "=0.12.0" + +[[constraint]] + name = "github.com/tendermint/go-crypto" + version = "=0.6.2" + +[[constraint]] + name = "github.com/tendermint/tendermint" + version = "=0.21.0" + +[[override]] + name = "github.com/tendermint/tmlibs" + version = "=v0.9.0" + +[[override]] + name = "github.com/tendermint/iavl" + version = "=0.8.0-rc0" + +# this got updated and broke, so locked to an old working commit ... +[[override]] + name = "google.golang.org/genproto" + revision = "7fd901a49ba6a7f87732eb344f6e3c5b19d1b200" + +[[constraint]] + name = "github.com/prometheus/client_golang" + version = "0.8.0" + +[prune] + go-tests = true + unused-packages = true \ No newline at end of file diff --git a/Makefile b/Makefile index 7295df83b..345f80662 100644 --- a/Makefile +++ b/Makefile @@ -1,17 +1,18 @@ -all: get_vendor_deps install test +all: get_vendor_deps install get_vendor_deps: - go get github.com/Masterminds/glide - glide install - + @rm -rf vendor/ + @echo "--> Running dep ensure" + @dep ensure -v + install: go install ./cmd/iris + go install ./cmd/iriscli build_linux: - CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iris ./cmd/iris - -test: - @go test `glide novendor` + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iris ./cmd/iris && \ + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iriscli ./cmd/iriscli -test_cli: - bash ./cmd/iris/sh_tests/stake.sh +build_cur: + go build -o build/iris ./cmd/iris && \ + go build -o build/iriscli ./cmd/iriscli diff --git a/README.md b/README.md index 049404cc0..06606302f 100644 --- a/README.md +++ b/README.md @@ -1,136 +1,92 @@ -# Iris-Hub -Iris Hub是在Cosmos生态中的区域性枢纽,提供iService服务 +# IRIS-Hub + +IRIS Hub是在Cosmos生态中的区域性枢纽,提供iService服务 ## 下载发行版安装 - * 进入下载页: https://github.com/irisnet/iris-hub/releases/tag/0.1.0 - * 下载对应版本的可执行文件 - * 解压缩`tar -C /usr/local -xzf iris$VERSION.$OS-$ARCH.zip` - * 拷贝到`/usr/local/`目录下 -执行 - ``` + +- 进入下载页: https://github.com/irisnet/irishub/releases/ +- 下载对应版本的可执行文件 +- 解压缩`tar -C /usr/local/bin -xzf iris$VERSION.$OS-$ARCH.zip` +- 拷贝到`/usr/local/bin/`目录下 + 执行 + +``` iris version - ``` +``` -若出现`v 0.1.0`则说明安装成功 +若出现对应的版本号则说明安装成功 ## 通过源码编译安装 ### 系统要求 + 操作系统:**Ubuntu 16.04** 架构:**amd64** 要求安装1.9版本以上的Go https://golang.org/doc/install -GO 安装步骤 +### 安装步骤 -* 下载 -curl -O https://dl.google.com/go/go1.9.4.linux-386.tar.gz - -* 解压缩 -``` -tar xvf go1.9.4.linux-386.tar.gz ``` - -* 获得权限 +go get github.com/irisnet/irishub +cd $GOPATH/src/github.com/irisnet/irishub +make all +iris version ``` -sudo chown -R root:root ./go -sudo mv go /usr/local -``` +若出现对应的版本号则说明安装成功 -* 设置GOPATH -``` -export GOPATH=$HOME/work -export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin -``` +### 本地测试网络 -* 测试是否安装成功 -建立一个简单的工程。 +1. 初始化irishub: ``` -mkdir -p work/src/github.com/user/hello +MYNAME1= +iris init --chain-id=test --name=$MYNAME1 --home=$HOME/.iris1 ``` -创建 "Hello World" Go文件. - +以上命令将在 `$HOME/.iris1/config`目录下创建默认的配置文件 `priv_validator.json`和`genesis.json`。`priv_validator.json` 包含验证人的私钥。`genesis.json`文件包含其他配置信息, 包括创世账户,创世账户的默认密码为`1234567890`,创世账户的助记词会在执行以上命令后输出在控制台,例如: ``` -nano ~/work/src/github.com/user/hello/hello.go -``` -修改文件内容如下: - -``` -package main - -import "fmt" - -func main() { - fmt.Printf("hello, world\n") +{ + "chain_id": "test", + "node_id": "e4bcb3c7df9783d32c8a876028a45952b4146c78", + "app_message": { + "secret": "spare detail grass load memory robust expect plunge thank hen limb electric town slot annual abandon" + } } ``` -编译&安装 -``` -go install github.com/user/hello -``` -执行命令 -``` -hello -``` -如果安装成功,将会出现 "hello, world"输出: - +其中secret便是创世账户的助记词,可以导入该助记词到iris客户端以重置密码: -## 安装步骤 ``` -go get github.com/irisnet/iris-hub -cd $GOPATH/src/github.com/irisnet/iris-hub -make all -iris version +iriscli keys add $MYNAME1 --recover +override the existing name XXX [y/n]: y +Enter a passphrase for your key: +Repeat the passphrase: +Enter your recovery seed phrase: ``` -若出现`v 0.1.0`则说明安装成功 - -###本地测试网络 - -Here is a quick example to get you off your feet: - -1. 生成和保存测试网络中的测试账户 +1. 启动irishub: ``` -MYNAME= -iris client keys new $MYNAME -iris client keys list -MYADDR= +iris start --home=$HOME/.iris1 ``` -2. 初始化iris-hub: -``` -iris node init $MYADDR --home=$HOME/.iris1 --chain-id=test -``` - -This will create all the files necessary to run a single node chain in以上命令将在 `$HOME/.iris1/config`目录下创建默认的配置文件 `priv_validator.json`和`genesis.json`。`priv_validator.json` 包含验证人的私钥。`genesis.json`文件包含其他配置信息, `$MYADDR`是默认生成的创世账户。 - -获得节点的Node_ID - -需要下载编辑develop分支的tendermint,或者下载可执行[[文件](https://github.com/kidinamoto01/gaia-testnet/blob/master/gaia-testnet/tendermint-develop-liunx-amd64.zip)] - -执行以下命令获得iris1的Node_ID -``` -tendermint show_node_id --home=$HOME/.iris1 -``` +1. 多节点配置: 同时,你也可以在本地再运行另一个Node,注意新的Node所对应的工作目录不同,但二者公用一个genesis文件。 - ``` -iris node init $MYADDR --home=$HOME/.iris2 --chain-id=test +MYNAME2= +iris init --chain-id=test --name=$MYNAME2 --home=$HOME/.iris2 cp $HOME/.iris1/config/genesis.json $HOME/.iris2/config/genesis.json ``` -修改 `$HOME/.iris2/config/config.toml` 让两个Node可以发现彼此: +修改 `$HOME/.iris2/config/config.toml` ,防止端口冲突,并让两个Node可以发现彼此: ``` proxy_app = "tcp://127.0.0.1:46668" @@ -147,105 +103,82 @@ laddr = "tcp://0.0.0.0:46666" seeds = "@0.0.0.0:46656" ``` +其中node_id可以通过以下命令获取: + +``` +iris tendermint show_node_id --home=$HOME/.iris1 +iris tendermint show_node_id --home=$HOME/.iris2 +``` + 然后就可以同时在后台运行: ``` -iris node start --home=$HOME/.iris1 &> iris1.log & -NODE1_PID=$! -iris node start --home=$HOME/.iris2 &> iris2.log & -NODE2_PID=$! +iris start --home=$HOME/.iris1 &> iris1.log & NODE1_PID=$! +iris start --home=$HOME/.iris2 &> iris2.log & NODE2_PID=$! ``` `PID` 是为了方便之后杀死相关进程。 通过 `tail iris1.log`,或 `tail -f iris1.log`可以对Node 进行监控。 -现在我们初始化客户端,然后查询账户: - -``` -iris client init --chain-id=test --node=tcp://localhost:46657 -iris client query account $MYADDR -``` +1. 现在我们可以使用客户端进行操作 -我们可以测试在账户间转账: +查询本地账户: ``` -MYNAME1= -iris client keys new $MYNAME1 -iris client keys list -MYADDR1= -iris client tx send --amount=1000fermion --to=$MYADDR1 --name=$MYNAME -iris client query $MYADDR1 -iris client query $MYADDR +iriscli keys list ``` -也可以查询 candidate列表: +查询账户余额: ``` -iris client query candidates +iriscli account
``` -很奇怪的是,iris并没有发现initial时生成的validator。这是因为这类validator比较特殊。通过查询tendermint接口,你可以获得初始的validator信息。 +我们可以测试在账户间转账: ``` -curl localhost:46657/validators +iriscli send --name=$MYNAME1 --to=$MYADDR2 --amount=10steak --chain-id=test +iriscli account $MYADDR1 +iriscli account $MYADDR2 ``` -接下来实现第一个validator的添加:首先获得节点的公钥: +也可以查询Validator列表: ``` -cat $HOME/.iris1/config/priv_validator.json -``` - -使用`jq`命令可以快速获得公钥: - +iriscli stake validators ``` -cat $HOME/.iris1/config/priv_validator.json | jq .pub_key.data -``` +接下来实现第一个validator的添加:首先获得节点的公钥: -通过执行以下命令完成绑定 ``` -iris client tx declare-candidacy --amount=1fermion --pubkey= --moniker= --name=$MYNAME - +iris tendermint show_validator --home=$HOME/.iris2 ``` -再次查询 candidate列表: -``` -iris client query candidates -``` -也可以查询具体的validator信息 +通过执行以下命令完成绑定: ``` -iris client query candidate --pubkey= +iriscli stake create-validator --amount=10steak --pubkey= --address-validator= --moniker= --chain-id=test --name= ``` -查询初始账户的变化,candidates页有变化: +再次查询 Validator列表: ``` -iris client query account $MYADDR -iris client query candidates +iriscli stake validators ``` -通过以下命令可以修改绑定的金额 -``` -iris client tx edit-candidacy --pubkey= --moniker= --name=$MYNAME -``` -通过unbond可将抵押的代币收回,你会发现账户余额增加了。 +通过以下命令为Validator添加更多信息: ``` -iris client tx unbond --shares=1 --pubkey= --name=$MYNAME -iris client query validators -iris client query account $MYADDR +iriscli stake edit-validator --details="To the IRISnet !" --website="https://irisnet.org" ``` -同样的,你也可以绑定用$HOME/.iris2/config/priv_validator.json代表的第二个Node -通过查询tendermint接口,你可以获得新的validator信息。 +检查Validator是否生效: ``` -curl localhost:46657/validators +iriscli advanced tendermint validator-set ``` -如果你杀死了第二个Node,那么区块链将无法继续生成新的块。这是因为只有保证2/3节点在线的情况下,才能达成共识。 +如果你杀死了第一个Node,那么区块链将无法继续生成新的块。这是因为只有保证Voting Power总数超过 2/3 的节点在线的情况下,才能达成共识。 -将第二个节点重新启动,那么区块链会回归正常。 \ No newline at end of file +将第一个节点重新启动,那么区块链会回归正常。 \ No newline at end of file diff --git a/app/app.go b/app/app.go new file mode 100644 index 000000000..c5072a53c --- /dev/null +++ b/app/app.go @@ -0,0 +1,181 @@ +package app + +import ( + "encoding/json" + "os" + + abci "github.com/tendermint/abci/types" + tmtypes "github.com/tendermint/tendermint/types" + cmn "github.com/tendermint/tmlibs/common" + dbm "github.com/tendermint/tmlibs/db" + "github.com/tendermint/tmlibs/log" + + bam "github.com/cosmos/cosmos-sdk/baseapp" + 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/bank" + "github.com/cosmos/cosmos-sdk/x/ibc" + "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/stake" +) + +const ( + appName = "IrisApp" +) + +// default home directories for expected binaries +var ( + DefaultCLIHome = os.ExpandEnv("$HOME/.iriscli") + DefaultNodeHome = os.ExpandEnv("$HOME/.iris") +) + +// Extended ABCI application +type IrisApp struct { + *bam.BaseApp + cdc *wire.Codec + + // keys to access the substores + keyMain *sdk.KVStoreKey + keyAccount *sdk.KVStoreKey + keyIBC *sdk.KVStoreKey + keyStake *sdk.KVStoreKey + keySlashing *sdk.KVStoreKey + + // Manage getting and setting accounts + accountMapper auth.AccountMapper + feeCollectionKeeper auth.FeeCollectionKeeper + coinKeeper bank.Keeper + ibcMapper ibc.Mapper + stakeKeeper stake.Keeper + slashingKeeper slashing.Keeper +} + +func NewIrisApp(logger log.Logger, db dbm.DB) *IrisApp { + cdc := MakeCodec() + + // create your application object + var app = &IrisApp{ + BaseApp: bam.NewBaseApp(appName, cdc, logger, db), + cdc: cdc, + keyMain: sdk.NewKVStoreKey("main"), + keyAccount: sdk.NewKVStoreKey("acc"), + keyIBC: sdk.NewKVStoreKey("ibc"), + keyStake: sdk.NewKVStoreKey("stake"), + keySlashing: sdk.NewKVStoreKey("slashing"), + } + + // define the accountMapper + app.accountMapper = auth.NewAccountMapper( + app.cdc, + app.keyAccount, // target store + &auth.BaseAccount{}, // prototype + ) + + // add handlers + app.coinKeeper = bank.NewKeeper(app.accountMapper) + app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace)) + app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) + app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.RegisterCodespace(slashing.DefaultCodespace)) + + // register message routes + app.Router(). + AddRoute("bank", bank.NewHandler(app.coinKeeper)). + AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)). + AddRoute("stake", stake.NewHandler(app.stakeKeeper)). + AddRoute("slashing", slashing.NewHandler(app.slashingKeeper)) + + // initialize BaseApp + app.SetInitChainer(app.initChainer) + app.SetBeginBlocker(app.BeginBlocker) + app.SetEndBlocker(app.EndBlocker) + app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) + app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing) + err := app.LoadLatestVersion(app.keyMain) + if err != nil { + cmn.Exit(err.Error()) + } + + return app +} + +// custom tx codec +func MakeCodec() *wire.Codec { + var cdc = wire.NewCodec() + ibc.RegisterWire(cdc) + bank.RegisterWire(cdc) + stake.RegisterWire(cdc) + slashing.RegisterWire(cdc) + auth.RegisterWire(cdc) + sdk.RegisterWire(cdc) + wire.RegisterCrypto(cdc) + return cdc +} + +// application updates every end block +func (app *IrisApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { + tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) + + return abci.ResponseBeginBlock{ + Tags: tags.ToKVPairs(), + } +} + +// application updates every end block +func (app *IrisApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { + validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) + + return abci.ResponseEndBlock{ + ValidatorUpdates: validatorUpdates, + } +} + +// custom logic for gaia initialization +func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { + stateJSON := req.AppStateBytes + // TODO is this now the whole genesis file? + + var genesisState GenesisState + err := app.cdc.UnmarshalJSON(stateJSON, &genesisState) + if err != nil { + panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 + // return sdk.ErrGenesisParse("").TraceCause(err, "") + } + + // load the accounts + for _, gacc := range genesisState.Accounts { + acc := gacc.ToAccount() + acc.AccountNumber = app.accountMapper.GetNextAccountNumber(ctx) + app.accountMapper.SetAccount(ctx, acc) + } + + // load the initial stake information + stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData) + + return abci.ResponseInitChain{} +} + +// export the state of gaia for a genesis file +func (app *IrisApp) ExportAppStateAndValidators() (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) { + ctx := app.NewContext(true, abci.Header{}) + + // iterate to get the accounts + accounts := []GenesisAccount{} + appendAccount := func(acc auth.Account) (stop bool) { + account := NewGenesisAccountI(acc) + accounts = append(accounts, account) + return false + } + app.accountMapper.IterateAccounts(ctx, appendAccount) + + genState := GenesisState{ + Accounts: accounts, + StakeData: stake.WriteGenesis(ctx, app.stakeKeeper), + } + appState, err = wire.MarshalJSONIndent(app.cdc, genState) + if err != nil { + return nil, nil, err + } + validators = stake.WriteValidators(ctx, app.stakeKeeper) + return appState, validators, nil +} diff --git a/app/context.go b/app/context.go new file mode 100644 index 000000000..e53eee28d --- /dev/null +++ b/app/context.go @@ -0,0 +1,28 @@ +package app + +import ( + "github.com/cosmos/cosmos-sdk/client/context" + ctypes "github.com/tendermint/tendermint/rpc/core/types" +) + +type Context struct { + ctx context.CoreContext +} + +func (c Context) BroadcastTxAsync(tx []byte) (*ctypes.ResultBroadcastTx, error) { + return c.ctx.Client.BroadcastTxAsync(tx) +} + +func (c Context) BroadcastTxSync(tx []byte) (*ctypes.ResultBroadcastTx, error) { + return c.ctx.Client.BroadcastTxSync(tx) +} + +func (c Context) GetCosmosCtx() context.CoreContext { + return c.ctx +} + +func NewContext() Context { + return Context{ + context.NewCoreContextFromViper(), + } +} diff --git a/app/genesis.go b/app/genesis.go new file mode 100644 index 000000000..924cfdebc --- /dev/null +++ b/app/genesis.go @@ -0,0 +1,231 @@ +package app + +import ( + "encoding/json" + "errors" + + "github.com/spf13/pflag" + "github.com/spf13/viper" + crypto "github.com/tendermint/go-crypto" + tmtypes "github.com/tendermint/tendermint/types" + + "github.com/cosmos/cosmos-sdk/server" + 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" +) + +// State to Unmarshal +type GenesisState struct { + Accounts []GenesisAccount `json:"accounts"` + StakeData stake.GenesisState `json:"stake"` +} + +// GenesisAccount doesn't need pubkey or sequence +type GenesisAccount struct { + Address sdk.Address `json:"address"` + Coins sdk.Coins `json:"coins"` +} + +func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount { + return GenesisAccount{ + Address: acc.Address, + Coins: acc.Coins, + } +} + +func NewGenesisAccountI(acc auth.Account) GenesisAccount { + return GenesisAccount{ + Address: acc.GetAddress(), + Coins: acc.GetCoins(), + } +} + +// convert GenesisAccount to auth.BaseAccount +func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { + return &auth.BaseAccount{ + Address: ga.Address, + Coins: ga.Coins.Sort(), + } +} + +var ( + flagName = "name" + flagClientHome = "home-client" + flagOWK = "owk" + denom = "iris" + + // bonded tokens given to genesis validators/accounts + freeFermionVal = int64(100) + + totalTokenAmt = int64(200000000) +) + +// get app init parameters for server init command +func IrisAppInit() server.AppInit { + fsAppGenState := pflag.NewFlagSet("", pflag.ContinueOnError) + + fsAppGenTx := pflag.NewFlagSet("", pflag.ContinueOnError) + fsAppGenTx.String(flagName, "", "validator moniker, required") + fsAppGenTx.String(flagClientHome, DefaultCLIHome, + "home directory for the client, used for key generation") + fsAppGenTx.Bool(flagOWK, false, "overwrite the accounts created") + + return server.AppInit{ + FlagsAppGenState: fsAppGenState, + FlagsAppGenTx: fsAppGenTx, + AppGenTx: IrisAppGenTx, + AppGenState: IrisAppGenStateJSON, + } +} + +// simple genesis tx +type IrisGenTx struct { + Name string `json:"name"` + Address sdk.Address `json:"address"` + PubKey crypto.PubKey `json:"pub_key"` +} + +// Generate a gaia genesis transaction with flags +func IrisAppGenTx(cdc *wire.Codec, pk crypto.PubKey) ( + appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { + clientRoot := viper.GetString(flagClientHome) + overwrite := viper.GetBool(flagOWK) + name := viper.GetString(flagName) + if name == "" { + return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)") + } + + var addr sdk.Address + var secret string + addr, secret, err = server.GenerateSaveCoinKey(clientRoot, name, "1234567890", overwrite) + if err != nil { + return + } + mm := map[string]string{"secret": secret} + var bz []byte + bz, err = cdc.MarshalJSON(mm) + if err != nil { + return + } + cliPrint = json.RawMessage(bz) + appGenTx, _, validator, err = IrisAppGenTxNF(cdc, pk, addr, name, overwrite) + return +} + +// Generate a gaia genesis transaction without flags +func IrisAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.Address, name string, overwrite bool) ( + appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { + + var bz []byte + gaiaGenTx := IrisGenTx{ + Name: name, + Address: addr, + PubKey: pk, + } + bz, err = wire.MarshalJSONIndent(cdc, gaiaGenTx) + if err != nil { + return + } + appGenTx = json.RawMessage(bz) + + validator = tmtypes.GenesisValidator{ + PubKey: pk, + Power: freeFermionVal, + } + return +} + +// Create the core parameters for genesis initialization for gaia +// note that the pubkey input is this machines pubkey +func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState GenesisState, err error) { + + if len(appGenTxs) == 0 { + err = errors.New("must provide at least genesis transaction") + return + } + + // start with the default staking genesis state + //stakeData := stake.DefaultGenesisState() + stakeData := stake.DefaultGenesisState() + + // get genesis flag account information + genaccs := make([]GenesisAccount, len(appGenTxs)) + for i, appGenTx := range appGenTxs { + + var genTx IrisGenTx + err = cdc.UnmarshalJSON(appGenTx, &genTx) + if err != nil { + return + } + + // create the genesis account, give'm few steaks and a buncha token with there name + accAuth := auth.NewBaseAccountWithAddress(genTx.Address) + accAuth.Coins = sdk.Coins{ + {denom, totalTokenAmt}, + {"steak", freeFermionVal}, + } + acc := NewGenesisAccount(&accAuth) + genaccs[i] = acc + stakeData.Pool.LooseUnbondedTokens += freeFermionVal // increase the supply + + // add the validator + if len(genTx.Name) > 0 { + desc := stake.NewDescription(genTx.Name, "", "", "") + validator := stake.NewValidator(genTx.Address, genTx.PubKey, desc) + validator.PoolShares = stake.NewBondedShares(sdk.NewRat(freeFermionVal)) + stakeData.Validators = append(stakeData.Validators, validator) + + // pool logic + stakeData.Pool.BondedTokens += freeFermionVal + stakeData.Pool.BondedShares = sdk.NewRat(stakeData.Pool.BondedTokens) + } + } + + // create the final app state + genesisState = GenesisState{ + Accounts: genaccs, + StakeData: stakeData, + } + return +} + +// IrisAppGenState but with JSON +func IrisAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) { + + // create the final app state + genesisState, err := IrisAppGenState(cdc, appGenTxs) + if err != nil { + return nil, err + } + appState, err = wire.MarshalJSONIndent(cdc, genesisState) + return +} + +// TODO +func createGenesisState() stake.GenesisState { + return stake.GenesisState{ + Pool: stake.Pool{ + LooseUnbondedTokens: 0, + BondedTokens: 0, + UnbondingTokens: 0, + UnbondedTokens: 0, + BondedShares: sdk.ZeroRat(), + UnbondingShares: sdk.ZeroRat(), + UnbondedShares: sdk.ZeroRat(), + InflationLastTime: 0, + Inflation: sdk.NewRat(7, 100), + DateLastCommissionReset: 0, + PrevBondedShares: sdk.ZeroRat(), + }, + Params: stake.Params{ + InflationRateChange: sdk.NewRat(13, 100), + InflationMax: sdk.NewRat(20, 100), + InflationMin: sdk.NewRat(7, 100), + GoalBonded: sdk.NewRat(67, 100), + MaxValidators: 100, + BondDenom: "steak", + }, + } +} diff --git a/cmd/iris/client.go b/cmd/iris/client.go deleted file mode 100644 index b79d9b6a0..000000000 --- a/cmd/iris/client.go +++ /dev/null @@ -1,97 +0,0 @@ -package main - -import ( - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client/commands" - "github.com/cosmos/cosmos-sdk/client/commands/commits" - "github.com/cosmos/cosmos-sdk/client/commands/keys" - "github.com/cosmos/cosmos-sdk/client/commands/proxy" - "github.com/cosmos/cosmos-sdk/client/commands/query" - rpccmd "github.com/cosmos/cosmos-sdk/client/commands/rpc" - txcmd "github.com/cosmos/cosmos-sdk/client/commands/txs" - authcmd "github.com/cosmos/cosmos-sdk/modules/auth/commands" - basecmd "github.com/cosmos/cosmos-sdk/modules/base/commands" - coincmd "github.com/cosmos/cosmos-sdk/modules/coin/commands" - feecmd "github.com/cosmos/cosmos-sdk/modules/fee/commands" - ibccmd "github.com/cosmos/cosmos-sdk/modules/ibc/commands" - noncecmd "github.com/cosmos/cosmos-sdk/modules/nonce/commands" - rolecmd "github.com/cosmos/cosmos-sdk/modules/roles/commands" - - stakecmd "github.com/MrXJC/gaia/modules/stake/commands" -) - -// clientCmd is the entry point for this binary -var clientCmd = &cobra.Command{ - Use: "client", - Short: "Iris light client", - Run: func(cmd *cobra.Command, args []string) { - cmd.Help() - }, -} - -func prepareClientCommands() { - commands.AddBasicFlags(clientCmd) - - // Prepare queries - query.RootCmd.AddCommand( - // These are default parsers, but optional in your app (you can remove key) - query.TxQueryCmd, - query.KeyQueryCmd, - coincmd.AccountQueryCmd, - noncecmd.NonceQueryCmd, - rolecmd.RoleQueryCmd, - ibccmd.IBCQueryCmd, - - //stakecmd.CmdQueryValidator, - stakecmd.CmdQueryCandidates, - stakecmd.CmdQueryCandidate, - stakecmd.CmdQueryDelegatorBond, - stakecmd.CmdQueryDelegatorCandidates, - ) - - // set up the middleware - txcmd.Middleware = txcmd.Wrappers{ - feecmd.FeeWrapper{}, - rolecmd.RoleWrapper{}, - noncecmd.NonceWrapper{}, - basecmd.ChainWrapper{}, - authcmd.SigWrapper{}, - } - txcmd.Middleware.Register(txcmd.RootCmd.PersistentFlags()) - - // you will always want this for the base send command - txcmd.RootCmd.AddCommand( - // This is the default transaction, optional in your app - coincmd.SendTxCmd, - coincmd.CreditTxCmd, - // this enables creating roles - rolecmd.CreateRoleTxCmd, - // these are for handling ibc - ibccmd.RegisterChainTxCmd, - ibccmd.UpdateChainTxCmd, - ibccmd.PostPacketTxCmd, - - stakecmd.CmdDeclareCandidacy, - stakecmd.CmdEditCandidacy, - stakecmd.CmdDelegate, - stakecmd.CmdUnbond, - ) - - clientCmd.AddCommand( - proxy.RootCmd, - lineBreak, - - txcmd.RootCmd, - query.RootCmd, - rpccmd.RootCmd, - lineBreak, - - keys.RootCmd, - commands.InitCmd, - commands.ResetCmd, - commits.RootCmd, - lineBreak, - ) - -} diff --git a/cmd/iris/main.go b/cmd/iris/main.go index c53e37231..acba3c88b 100644 --- a/cmd/iris/main.go +++ b/cmd/iris/main.go @@ -1,50 +1,64 @@ package main import ( - "os" + "encoding/json" "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/server" + "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/version" + abci "github.com/tendermint/abci/types" + tmtypes "github.com/tendermint/tendermint/types" "github.com/tendermint/tmlibs/cli" - - basecmd "github.com/cosmos/cosmos-sdk/server/commands" - "github.com/irisnet/iris-hub/version" -) - -// IrisCmd is the entry point for this binary -var ( - IrisCmd = &cobra.Command{ - Use: "iris", - Short: "IRIS Hub - a regional Cosmos Hub with a powerful iService infrastructure", - Run: func(cmd *cobra.Command, args []string) { - cmd.Help() - }, - } - - lineBreak = &cobra.Command{Run: func(*cobra.Command, []string) {}} + dbm "github.com/tendermint/tmlibs/db" + "github.com/tendermint/tmlibs/log" ) func main() { - // disable sorting + cdc := app.MakeCodec() + ctx := server.NewDefaultContext() cobra.EnableCommandSorting = false + rootCmd := &cobra.Command{ + Use: "iris", + Short: "iris Daemon (server)", + PersistentPreRunE: server.PersistentPreRunEFn(ctx), + } - // add commands - prepareNodeCommands() - prepareRestServerCommands() - prepareClientCommands() + rootCmd.PersistentFlags().String("log_level", ctx.Config.LogLevel, "Log level") - IrisCmd.AddCommand( - nodeCmd, - restServerCmd, - clientCmd, + tendermintCmd := &cobra.Command{ + Use: "tendermint", + Short: "Tendermint subcommands", + } - lineBreak, + tendermintCmd.AddCommand( + server.ShowNodeIDCmd(ctx), + server.ShowValidatorCmd(ctx), + ) + + rootCmd.AddCommand( + server.InitCmd(ctx, cdc, app.IrisAppInit()), + server.StartCmd(ctx, server.ConstructAppCreator(newApp, "iris")), + server.UnsafeResetAllCmd(ctx), + client.LineBreak, + tendermintCmd, + server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), + client.LineBreak, version.VersionCmd, - //auto.AutoCompleteCmd, ) // prepare and add flags - basecmd.SetUpRoot(IrisCmd) - executor := cli.PrepareMainCmd(IrisCmd, "GA", os.ExpandEnv("$HOME/.iris-cli")) + executor := cli.PrepareBaseCmd(rootCmd, "IRIS", app.DefaultNodeHome) executor.Execute() } + +func newApp(logger log.Logger, db dbm.DB) abci.Application { + return app.NewIrisApp(logger, db) +} + +func exportAppStateAndTMValidators(logger log.Logger, db dbm.DB) (json.RawMessage, []tmtypes.GenesisValidator, error) { + irisApp := app.NewIrisApp(logger, db) + return irisApp.ExportAppStateAndValidators() +} diff --git a/cmd/iris/node.go b/cmd/iris/node.go deleted file mode 100644 index ece739afb..000000000 --- a/cmd/iris/node.go +++ /dev/null @@ -1,69 +0,0 @@ -package main - -import ( - "github.com/spf13/cobra" - - abci "github.com/tendermint/abci/types" - - sdk "github.com/cosmos/cosmos-sdk" - "github.com/cosmos/cosmos-sdk/modules/auth" - "github.com/cosmos/cosmos-sdk/modules/base" - "github.com/cosmos/cosmos-sdk/modules/coin" - "github.com/cosmos/cosmos-sdk/modules/fee" - "github.com/cosmos/cosmos-sdk/modules/ibc" - "github.com/cosmos/cosmos-sdk/modules/nonce" - "github.com/cosmos/cosmos-sdk/modules/roles" - basecmd "github.com/cosmos/cosmos-sdk/server/commands" - "github.com/cosmos/cosmos-sdk/stack" - "github.com/cosmos/cosmos-sdk/state" - - "github.com/MrXJC/gaia/modules/stake" -) - -// nodeCmd is the entry point for this binary -var nodeCmd = &cobra.Command{ - Use: "node", - Short: "The Cosmos Network delegation-game blockchain test", - Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, -} - -func prepareNodeCommands() { - - basecmd.Handler = stack.New( - base.Logger{}, - stack.Recovery{}, - auth.Signatures{}, - base.Chain{}, - stack.Checkpoint{OnCheck: true}, - nonce.ReplayCheck{}, - ). - IBC(ibc.NewMiddleware()). - Apps( - roles.NewMiddleware(), - fee.NewSimpleFeeMiddleware(coin.Coin{"fermion", 0}, fee.Bank), - stack.Checkpoint{OnDeliver: true}, - ). - Dispatch( - coin.NewHandler(), - stack.WrapHandler(roles.NewHandler()), - stack.WrapHandler(ibc.NewHandler()), - stake.NewHandler(), - ) - - nodeCmd.AddCommand( - basecmd.GetInitCmd("fermion", []string{"stake/allowed_bond_denom/fermion"}), - basecmd.GetTickStartCmd(sdk.TickerFunc(tickFn)), - basecmd.UnsafeResetAllCmd, - ) -} - -// Tick - Called every block even if no transaction, process all queues, -// validator rewards, and calculate the validator set difference -func tickFn(ctx sdk.Context, store state.SimpleDB) (change []abci.Validator, err error) { - // first need to prefix the store, at this point it's a global store - store = stack.PrefixedStore(stake.Name(), store) - - // execute Tick - change, err = stake.UpdateValidatorSet(store) - return -} diff --git a/cmd/iris/rest.go b/cmd/iris/rest.go deleted file mode 100644 index 9ca8d7a7b..000000000 --- a/cmd/iris/rest.go +++ /dev/null @@ -1,95 +0,0 @@ -package main - -import ( - "fmt" - "log" - "net/http" - - "github.com/gorilla/mux" - "github.com/spf13/cobra" - "github.com/spf13/viper" - "github.com/tendermint/tmlibs/cli" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/commands" - rest "github.com/cosmos/cosmos-sdk/client/rest" - restTxs "github.com/irisnet/iris-hub/module/rest-txs" - byteTx "github.com/irisnet/iris-hub/rest" - coinrest "github.com/cosmos/cosmos-sdk/modules/coin/rest" - noncerest "github.com/cosmos/cosmos-sdk/modules/nonce/rest" - rolerest "github.com/cosmos/cosmos-sdk/modules/roles/rest" - - stakerest "github.com/MrXJC/gaia/modules/stake/rest" -) - -const defaultAlgo = "ed25519" - -var ( - restServerCmd = &cobra.Command{ - Use: "rest-server", - Short: "REST client for iris commands", - Long: `Irisserver presents a nice (not raw hex) interface to the iris blockchain structure.`, - RunE: func(cmd *cobra.Command, args []string) error { - return cmdRestServer(cmd, args) - }, - } - - flagPort = "port" -) - -func prepareRestServerCommands() { - commands.AddBasicFlags(restServerCmd) - restServerCmd.PersistentFlags().IntP(flagPort, "p", 8998, "port to run the server on") -} - -func cmdRestServer(cmd *cobra.Command, args []string) error { - router := mux.NewRouter() - - rootDir := viper.GetString(cli.HomeFlag) - keyMan := client.GetKeyManager(rootDir) - serviceKeys := rest.NewServiceKeys(keyMan) - serviceByteTx := byteTx.NewServiceByteTx(keyMan) - serviceTxs := restTxs.NewServiceTxs(commands.GetNode()) - - routeRegistrars := []func(*mux.Router) error{ - // rest.Keys handlers - serviceKeys.RegisterCRUD, - - // Coin handlers (Send, Query, SearchSent) - coinrest.RegisterAll, - - // Roles createRole handler - rolerest.RegisterCreateRole, - - // Iris sign transactions handler - serviceKeys.RegisterSignTx, - // Iris post transaction handler - serviceTxs.RegisterPostTx, - - // Iris transfer Tx to byte[] - serviceByteTx.RegisterByteTx, - - // Nonce query handler - noncerest.RegisterQueryNonce, - - // Staking query handlers - stakerest.RegisterQueryCandidate, - stakerest.RegisterQueryCandidates, - stakerest.RegisterQueryDelegatorBond, - stakerest.RegisterQueryDelegatorCandidates, - // Staking tx builders - stakerest.RegisterDelegate, - stakerest.RegisterUnbond, - } - - for _, routeRegistrar := range routeRegistrars { - if err := routeRegistrar(router); err != nil { - log.Fatal(err) - } - } - - addr := fmt.Sprintf(":%d", viper.GetInt(flagPort)) - - log.Printf("Serving on %q", addr) - return http.ListenAndServe(addr, router) -} diff --git a/cmd/iris/rest_test.go b/cmd/iris/rest_test.go deleted file mode 100644 index b643f455c..000000000 --- a/cmd/iris/rest_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package main - -import ( - "fmt" - "log" - "net/http" - - "github.com/spf13/viper" - "github.com/gorilla/mux" - "testing" - "github.com/tendermint/tmlibs/cli" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/commands" - rest "github.com/cosmos/cosmos-sdk/client/rest" - byteTx "github.com/irisnet/iris-hub/rest" - coinrest "github.com/cosmos/cosmos-sdk/modules/coin/rest" - noncerest "github.com/cosmos/cosmos-sdk/modules/nonce/rest" - rolerest "github.com/cosmos/cosmos-sdk/modules/roles/rest" - - stakerest "github.com/MrXJC/gaia/modules/stake/rest" -) - -func TestRest(t *testing.T) { - - - router := mux.NewRouter() - - rootDir := viper.GetString(cli.HomeFlag) - keyMan := client.GetKeyManager(rootDir) - serviceKeys := rest.NewServiceKeys(keyMan) - serviceByteTx := byteTx.NewServiceByteTx(keyMan) - serviceTxs := rest.NewServiceTxs(commands.GetNode()) - - - routeRegistrars := []func(*mux.Router) error{ - // rest.Keys handlers - serviceKeys.RegisterCRUD, - - // Coin handlers (Send, Query, SearchSent) - coinrest.RegisterAll, - - // Roles createRole handler - rolerest.RegisterCreateRole, - - // Iris sign transactions handler - serviceKeys.RegisterSignTx, - // Iris post transaction handler - serviceTxs.RegisterPostTx, - - // Iris transfer Tx to byte[] - serviceByteTx.RegisterByteTx, - - // Nonce query handler - noncerest.RegisterQueryNonce, - - // Staking query handlers - stakerest.RegisterQueryCandidate, - stakerest.RegisterQueryCandidates, - stakerest.RegisterQueryDelegatorBond, - stakerest.RegisterQueryDelegatorCandidates, - // Staking tx builders - stakerest.RegisterDelegate, - stakerest.RegisterUnbond, - } - - for _, routeRegistrar := range routeRegistrars { - if err := routeRegistrar(router); err != nil { - log.Fatal(err) - } - } - - addr := fmt.Sprintf(":%d", 8080) - - log.Printf("Serving on %q", addr) - http.ListenAndServe(addr, router) - -} \ No newline at end of file diff --git a/cmd/iris/sh_tests/stake.sh b/cmd/iris/sh_tests/stake.sh deleted file mode 100644 index 6682ec347..000000000 --- a/cmd/iris/sh_tests/stake.sh +++ /dev/null @@ -1,276 +0,0 @@ -#!/bin/bash -set -u - -# These global variables are required for common.sh -SERVER_EXE="iris node --log_level=debug" -CLIENT_EXE="iris client" -ACCOUNTS=(jae ethan bucky rigel igor) -RICH=${ACCOUNTS[0]} -DELEGATOR=${ACCOUNTS[2]} -POOR=${ACCOUNTS[4]} - -BASE_DIR=$HOME/stake_test -BASE_DIR2=$HOME/stake_test2 -SERVER1=$BASE_DIR/server -SERVER2=$BASE_DIR2/server - -oneTimeSetUp() { - #[ "$2" ] || echo "missing parameters, line=${LINENO}" ; exit 1; - - - # These are passed in as args - CHAIN_ID="stake_test" - - # TODO Make this more robust - if [ "$BASE_DIR" == "$HOME/" ]; then - echo "Must be called with argument, or it will wipe your home directory" - exit 1 - fi - - rm -rf $BASE_DIR 2>/dev/null - mkdir -p $BASE_DIR - - if [ "$BASE_DIR2" == "$HOME/" ]; then - echo "Must be called with argument, or it will wipe your home directory" - exit 1 - fi - rm -rf $BASE_DIR2 2>/dev/null - mkdir -p $BASE_DIR2 - - # Set up client - make sure you use the proper prefix if you set - # a custom CLIENT_EXE - export BC_HOME=${BASE_DIR}/client - prepareClient - - # start the node server - set +u ; initServer $BASE_DIR $CHAIN_ID ; set -u - if [ $? != 0 ]; then return 1; fi - - set +u ; initClient $CHAIN_ID ; set -u - if [ $? != 0 ]; then return 1; fi - - printf "...Testing may begin!\n\n\n" - -} - -oneTimeTearDown() { - kill -9 $PID_SERVER2 >/dev/null 2>&1 - set +u ; quickTearDown ; set -u -} - -# XXX Ex Usage: checkCandidate $PUBKEY $EXPECTED_VOTING_POWER -checkCandidate() { - CANDIDATE=$(${CLIENT_EXE} query candidate --pubkey=$1) - if ! assertTrue "line=${LINENO}, bad query" $?; then - return 1 - fi - assertEquals "line=${LINENO}, proper voting power" "$2" $(echo $CANDIDATE | jq .data.voting_power) - return $? -} - -# XXX Ex Usage: checkCandidate $PUBKEY -checkCandidateEmpty() { - CANDIDATE=$(${CLIENT_EXE} query candidate --pubkey=$1 2>/dev/null) - if ! assertFalse "line=${LINENO}, expected empty query" $?; then - return 1 - fi -} - -# XXX Ex Usage: checkCandidate $DELEGATOR_ADDR $PUBKEY $EXPECTED_SHARES -checkDelegatorBond() { - BOND=$(${CLIENT_EXE} query delegator-bond --delegator-address=$1 --pubkey=$2) - if ! assertTrue "line=${LINENO}, account must exist" $?; then - return 1 - fi - assertEquals "line=${LINENO}, proper bond amount" "$3" $(echo $BOND | jq .data.Shares) - return $? -} - -# XXX Ex Usage: checkCandidate $DELEGATOR_ADDR $PUBKEY -checkDelegatorBondEmpty() { - BOND=$(${CLIENT_EXE} query delegator-bond --delegator-address=$1 --pubkey=$2 2>/dev/null) - if ! assertFalse "line=${LINENO}, expected empty query" $?; then - return 1 - fi -} - -#______________________________________________________________________________________ - -test00GetAccount() { - SENDER=$(getAddr $RICH) - RECV=$(getAddr $POOR) - - assertFalse "line=${LINENO}, requires arg" "${CLIENT_EXE} query account" - - set +u ; checkAccount $SENDER "9007199254740992" ; set -u - - ACCT2=$(${CLIENT_EXE} query account $RECV 2>/dev/null) - assertFalse "line=${LINENO}, has no genesis account" $? -} - -test01SendTx() { - assertFalse "line=${LINENO}, missing dest" "${CLIENT_EXE} tx send --amount=992fermion --sequence=1" - assertFalse "line=${LINENO}, bad password" "echo foo | ${CLIENT_EXE} tx send --amount=992fermion --sequence=1 --to=$RECV --name=$RICH" - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx send --amount=992fermion --sequence=1 --to=$RECV --name=$RICH) - txSucceeded $? "$TX" "$RECV" - HASH=$(echo $TX | jq .hash | tr -d \") - TX_HEIGHT=$(echo $TX | jq .height) - - set +u - checkAccount $SENDER "9007199254740000" $TX_HEIGHT - # make sure 0x prefix also works - checkAccount "0x$SENDER" "9007199254740000" $TX_HEIGHT - checkAccount $RECV "992" $TX_HEIGHT - - # Make sure tx is indexed - checkSendTx $HASH $TX_HEIGHT $SENDER "992" - set -u -} - -test02DeclareCandidacy() { - - # the premise of this test is to run a second validator (from rich) and then bond and unbond some tokens - # first create a second node to run and connect to the system - - # init the second node - SERVER_LOG2=$BASE_DIR2/node2.log - GENKEY=$(${CLIENT_EXE} keys get ${RICH} | awk '{print $2}') - ${SERVER_EXE} init $GENKEY --chain-id $CHAIN_ID --home=$SERVER2 >>$SERVER_LOG2 - if [ $? != 0 ]; then return 1; fi - - # copy in the genesis from the first initialization to the new server - cp $SERVER1/config/genesis.json $SERVER2/config/genesis.json - - # point the new config to the old server location - rm $SERVER2/config/config.toml - echo 'proxy_app = "tcp://127.0.0.1:46668" - moniker = "anonymous" - fast_sync = true - db_backend = "leveldb" - log_level = "state:info,*:error" - - [rpc] - laddr = "tcp://0.0.0.0:46667" - - [p2p] - laddr = "tcp://0.0.0.0:46666" - seeds = "0.0.0.0:46656"' >$SERVER2/config/config.toml - - # start the second node - ${SERVER_EXE} start --home=$SERVER2 >>$SERVER_LOG2 2>&1 & - sleep 1 - PID_SERVER2=$! - disown - if ! ps $PID_SERVER2 >/dev/null; then - echo "**FAILED**" - cat $SERVER_LOG2 - return 1 - fi - - # get the pubkey of the second validator - PK2=$(cat $SERVER2/config/priv_validator.json | jq -r .pub_key.data) - - CAND_ADDR=$(getAddr $POOR) - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx declare-candidacy --sequence=1 --amount=2fermion --name=$POOR --pubkey=$PK2 --moniker=rigey) - if [ $? != 0 ]; then return 1; fi - HASH=$(echo $TX | jq .hash | tr -d \") - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $CAND_ADDR "990" $TX_HEIGHT ; set -u - checkCandidate $PK2 "2" - checkDelegatorBond $CAND_ADDR $PK2 "2" -} - -test03Delegate() { - # send some coins to a delegator - DELA_ADDR=$(getAddr $DELEGATOR) - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx send --sequence=2 --amount=5fermion --to=$DELA_ADDR --name=$RICH) - txSucceeded $? "$TX" "$DELA_ADDR" - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "5" $TX_HEIGHT ; set -u - - # delegate some coins to the new - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=1 --amount=1fermion --name=$DELEGATOR --pubkey=$PK2) - if [ $? != 0 ]; then return 1; fi - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "4" $TX_HEIGHT ; set -u - checkCandidate $PK2 "3" - checkDelegatorBond $DELA_ADDR $PK2 "1" - - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=2 --amount=2fermion --name=$DELEGATOR --pubkey=$PK2) - if [ $? != 0 ]; then return 1; fi - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u - checkCandidate $PK2 "5" - checkDelegatorBond $DELA_ADDR $PK2 "3" - - # attempt a delegation without enough funds - # NOTE the sequence number still increments here because it will fail - # only during DeliverTx - however this should be updated (TODO) in new - # SDK when we can fail in CheckTx - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=3 --amount=3fermion --name=$DELEGATOR --pubkey=$PK2 2>/dev/null) - if [ $? == 0 ]; then return 1; fi - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u - checkCandidate $PK2 "5" - checkDelegatorBond $DELA_ADDR $PK2 "3" - - # perform the final delegation which should empty the delegators account - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx delegate --sequence=4 --amount=2fermion --name=$DELEGATOR --pubkey=$PK2) - if [ $? != 0 ]; then return 1; fi - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "null" $TX_HEIGHT ; set -u #empty account is null - checkCandidate $PK2 "7" - checkDelegatorBond $DELA_ADDR $PK2 "5" -} - -test04Unbond() { - # unbond from the delegator a bit - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=5 --shares=2 --name=$DELEGATOR --pubkey=$PK2) - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u - checkCandidate $PK2 "5" - checkDelegatorBond $DELA_ADDR $PK2 "3" - - # attempt to unbond more shares than exist - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=6 --shares=10 --name=$DELEGATOR --pubkey=$PK2 2>/dev/null) - if [ $? == 0 ]; then return 1; fi - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "2" $TX_HEIGHT ; set -u - checkCandidate $PK2 "5" - checkDelegatorBond $DELA_ADDR $PK2 "3" - - # unbond entirely from the delegator - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=6 --shares=3 --name=$DELEGATOR --pubkey=$PK2) - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $DELA_ADDR "5" $TX_HEIGHT ; set -u - checkCandidate $PK2 "2" - checkDelegatorBondEmpty $DELA_ADDR $PK2 - - # unbond a bit from the owner - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=2 --shares=1 --name=$POOR --pubkey=$PK2) - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $CAND_ADDR "991" $TX_HEIGHT ; set -u - checkCandidate $PK2 "1" - checkDelegatorBond $CAND_ADDR $PK2 "1" - - # attempt to unbond more shares than exist - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=3 --shares=10 --name=$POOR --pubkey=$PK2 2>/dev/null) - if [ $? == 0 ]; then return 1; fi - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $CAND_ADDR "991" $TX_HEIGHT ; set -u - checkCandidate $PK2 "1" - checkDelegatorBond $CAND_ADDR $PK2 "1" - - # unbond entirely from the validator - TX=$(echo qwertyuiop | ${CLIENT_EXE} tx unbond --sequence=3 --shares=1 --name=$POOR --pubkey=$PK2) - TX_HEIGHT=$(echo $TX | jq .height) - set +u ; checkAccount $CAND_ADDR "992" $TX_HEIGHT ; set -u - checkCandidateEmpty $PK2 - checkDelegatorBondEmpty $CAND_ADDR $PK2 -} - -# Load common then run these tests with shunit2! -CLI_DIR=$GOPATH/src/github.com/cosmos/gaia/vendor/github.com/cosmos/cosmos-sdk/tests/cli - -. $CLI_DIR/common.sh -. $CLI_DIR/shunit2 diff --git a/cmd/iriscli/lcd.go b/cmd/iriscli/lcd.go new file mode 100644 index 000000000..49f99f2c2 --- /dev/null +++ b/cmd/iriscli/lcd.go @@ -0,0 +1,85 @@ +package main + +import ( + "net/http" + "os" + + "github.com/gorilla/mux" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/tendermint/tmlibs/log" + + tmserver "github.com/tendermint/tendermint/rpc/lib/server" + cmn "github.com/tendermint/tmlibs/common" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/client/rpc" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/cosmos/cosmos-sdk/wire" + auth "github.com/cosmos/cosmos-sdk/x/auth/client/rest" + bank "github.com/cosmos/cosmos-sdk/x/bank/client/rest" + ibc "github.com/cosmos/cosmos-sdk/x/ibc/client/rest" + stake "github.com/cosmos/cosmos-sdk/x/stake/client/rest" + "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/version" +) + +// ServeCommand will generate a long-running rest server +// (aka Light Client Daemon) that exposes functionality similar +// to the cli, but over rest +func ServeCommand(cdc *wire.Codec) *cobra.Command { + flagListenAddr := "laddr" + flagCORS := "cors" + + cmd := &cobra.Command{ + Use: "rest-server", + Short: "Start LCD (light-client daemon), a local REST server", + RunE: func(cmd *cobra.Command, args []string) error { + listenAddr := viper.GetString(flagListenAddr) + handler := createHandler(cdc) + logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)). + With("module", "rest-server") + listener, err := tmserver.StartHTTPServer(listenAddr, handler, logger) + if err != nil { + return err + } + logger.Info("REST server started") + + // Wait forever and cleanup + cmn.TrapSignal(func() { + err := listener.Close() + logger.Error("Error closing listener", "err", err) + }) + return nil + }, + } + cmd.Flags().StringP(flagListenAddr, "a", "tcp://localhost:1317", "Address for server to listen on") + cmd.Flags().String(flagCORS, "", "Set to domains that can make CORS requests (* for all)") + cmd.Flags().StringP(client.FlagChainID, "c", "", "ID of chain we connect to") + cmd.Flags().StringP(client.FlagNode, "n", "tcp://localhost:46657", "Node to connect to") + return cmd +} + +func createHandler(cdc *wire.Codec) http.Handler { + r := mux.NewRouter() + r.HandleFunc("/version", version.RequestHandler).Methods("GET") + + kb, err := keys.GetKeyBase() //XXX + if err != nil { + panic(err) + } + + ctx := app.NewContext() + + // TODO make more functional? aka r = keys.RegisterRoutes(r) + keys.RegisterRoutes(r) + rpc.RegisterRoutes(ctx.GetCosmosCtx(), r) + tx.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc) + auth.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, "acc") + bank.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, kb) + ibc.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, kb) + stake.RegisterRoutes(ctx.GetCosmosCtx(), r, cdc, kb) + RegisterRoutes(ctx, r, cdc, kb) + return r +} diff --git a/cmd/iriscli/lcd_test.go b/cmd/iriscli/lcd_test.go new file mode 100644 index 000000000..cabf4acc5 --- /dev/null +++ b/cmd/iriscli/lcd_test.go @@ -0,0 +1,34 @@ +package main + +import ( + "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/tools/prometheus" + "github.com/spf13/viper" + "testing" +) + +func TestRestServer(t *testing.T) { + cdc := app.MakeCodec() + comm := ServeCommand(cdc) + viper.Set("chain-id", "fuxi") + viper.Set("node", "tcp://localhost:26657") + viper.Set("laddr", "tcp://localhost:1317") + + comm.ExecuteC() +} + +func TestMetricsCmd(t *testing.T) { + cdc := app.MakeCodec() + comm := prometheus.MonitorCommand("stake", cdc) + viper.Set("node", "tcp://0.0.0.0:46657") + viper.Set("chain-id", "fuxi") + viper.Set("commands", "iris start ;htop") + /* + viper.Set("paths","/etc ;/home/") + viper.Set("recursively", false) + */ + viper.Set("paths", "/Users/zhangzhiqiang/.iris") + viper.Set("disks", "/") + viper.Set("recursively", true) + comm.ExecuteC() +} diff --git a/cmd/iriscli/main.go b/cmd/iriscli/main.go new file mode 100644 index 000000000..64231ec96 --- /dev/null +++ b/cmd/iriscli/main.go @@ -0,0 +1,124 @@ +package main + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/client/rpc" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/spf13/cobra" + "github.com/tendermint/tmlibs/cli" + + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" + ibccmd "github.com/cosmos/cosmos-sdk/x/ibc/client/cli" + slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" + stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" + "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/tools/prometheus" + "github.com/irisnet/irishub/version" +) + +// rootCmd is the entry point for this binary +var ( + rootCmd = &cobra.Command{ + Use: "iriscli", + Short: "irishub light-client", + } +) + +func main() { + cobra.EnableCommandSorting = false + cdc := app.MakeCodec() + + // TODO: setup keybase, viper object, etc. to be passed into + // the below functions and eliminate global vars, like we do + // with the cdc + + // add standard rpc commands + rpc.AddCommands(rootCmd) + + //Add state commands + tendermintCmd := &cobra.Command{ + Use: "tendermint", + Short: "Tendermint state querying subcommands", + } + tendermintCmd.AddCommand( + rpc.BlockCommand(), + rpc.ValidatorCommand(), + ) + tx.AddCommands(tendermintCmd, cdc) + + //Add IBC commands + ibcCmd := &cobra.Command{ + Use: "ibc", + Short: "Inter-Blockchain Communication subcommands", + } + ibcCmd.AddCommand( + client.PostCommands( + ibccmd.IBCTransferCmd(cdc), + ibccmd.IBCRelayCmd(cdc), + )...) + + advancedCmd := &cobra.Command{ + Use: "advanced", + Short: "Advanced subcommands", + } + + advancedCmd.AddCommand( + tendermintCmd, + ibcCmd, + ServeCommand(cdc), + ) + rootCmd.AddCommand( + advancedCmd, + client.LineBreak, + ) + + //Add stake commands + stakeCmd := &cobra.Command{ + Use: "stake", + Short: "Stake and validation subcommands", + } + stakeCmd.AddCommand( + client.GetCommands( + stakecmd.GetCmdQueryValidator("stake", cdc), + stakecmd.GetCmdQueryValidators("stake", cdc), + stakecmd.GetCmdQueryDelegation("stake", cdc), + stakecmd.GetCmdQueryDelegations("stake", cdc), + slashingcmd.GetCmdQuerySigningInfo("slashing", cdc), + )...) + stakeCmd.AddCommand( + client.PostCommands( + stakecmd.GetCmdCreateValidator(cdc), + stakecmd.GetCmdEditValidator(cdc), + stakecmd.GetCmdDelegate(cdc), + stakecmd.GetCmdUnbond(cdc), + slashingcmd.GetCmdUnrevoke(cdc), + )...) + rootCmd.AddCommand( + stakeCmd, + ) + + //Add auth and bank commands + rootCmd.AddCommand( + client.GetCommands( + authcmd.GetAccountCmd("acc", cdc, authcmd.GetAccountDecoder(cdc)), + )...) + rootCmd.AddCommand( + client.PostCommands( + bankcmd.SendTxCmd(cdc), + )...) + + // add proxy, version and key info + rootCmd.AddCommand( + keys.Commands(), + client.LineBreak, + version.VersionCmd, + ) + + rootCmd.AddCommand(prometheus.MonitorCommand("stake", cdc)) + + // prepare and add flags + executor := cli.PrepareMainCmd(rootCmd, "IRIS", app.DefaultCLIHome) + executor.Execute() +} diff --git a/cmd/iriscli/offline_sign.go b/cmd/iriscli/offline_sign.go new file mode 100644 index 000000000..c918c610d --- /dev/null +++ b/cmd/iriscli/offline_sign.go @@ -0,0 +1,119 @@ +package main + +import ( + "encoding/json" + 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/bank" + "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/gorilla/mux" + "github.com/irisnet/irishub/app" + "github.com/pkg/errors" + "github.com/tendermint/go-crypto" + "github.com/tendermint/go-crypto/keys" + "io/ioutil" + "net/http" +) + +func RegisterRoutes(ctx app.Context, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { + r.HandleFunc("/tx/send", SendTxRequestHandlerFn(cdc, kb, ctx)).Methods("POST") +} + +type sendTx struct { + Msg string `json:"msg"` + MsgType string `json:"type"` + Fee auth.StdFee `json:"fee"` + Signatures []StdSignature `json:"signatures"` +} + +type StdSignature struct { + PubKey crypto.PubKeyEd25519 `json:"pub_key"` // optional + Signature crypto.SignatureEd25519 `json:"signature"` + AccountNumber int64 `json:"account_number"` + Sequence int64 `json:"sequence"` +} + +//send traction(sign with rainbow) to irishub +func SendTxRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx app.Context) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var tx sendTx + body, err := ioutil.ReadAll(r.Body) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + if err = json.Unmarshal(body, &tx); err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + var sig = make([]auth.StdSignature, len(tx.Signatures)) + for index, s := range tx.Signatures { + sig[index].PubKey = s.PubKey + sig[index].Signature = s.Signature + sig[index].AccountNumber = s.AccountNumber + sig[index].Sequence = s.Sequence + } + + msg, err := convertMsg(tx) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + var stdTx = auth.StdTx{ + Msg: msg, + Fee: tx.Fee, + Signatures: sig, + } + txByte, _ := cdc.MarshalBinary(stdTx) + // send + res, err := ctx.BroadcastTxSync(txByte) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + output, err := json.MarshalIndent(res, "", " ") + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + w.Write(output) + } +} + +func convertMsg(tx sendTx) (sdk.Msg, error) { + data := []byte(tx.Msg) + switch tx.MsgType { + case "transfer": + { + var msg bank.MsgSend + if err := json.Unmarshal(data, &msg); err != nil { + return nil, err + } + return msg, nil + } + case "delegate": + var msg stake.MsgDelegate + if err := json.Unmarshal(data, &msg); err != nil { + return nil, err + } + return msg, nil + case "unbond": + var msg stake.MsgUnbond + if err := json.Unmarshal(data, &msg); err != nil { + return nil, err + } + return msg, nil + } + + return nil, errors.New("invalid message type") +} diff --git a/glide.lock b/glide.lock deleted file mode 100644 index 0e912f491..000000000 --- a/glide.lock +++ /dev/null @@ -1,305 +0,0 @@ -hash: 20e25ba77f4c08127c8b87786d0bb7d3868e6c8a0bfe9f80f63ce831b25663ec -updated: 2018-03-07T11:54:26.85382+08:00 -imports: -- name: github.com/bgentry/speakeasy - version: 4aabc24848ce5fd31929f7d1e4ea74d3709c14cd -- name: github.com/btcsuite/btcd - version: 2e60448ffcc6bf78332d1fe590260095f554dd78 - subpackages: - - btcec -- name: github.com/BurntSushi/toml - version: b26d9c308763d68093482582cea63d69be07a0f0 -- name: github.com/cosmos/cosmos-sdk - version: f1b1d36324812dc221da87f56734a5c25d8754aa - subpackages: - - app - - client - - client/commands - - client/commands/commits - - client/commands/keys - - client/commands/proxy - - client/commands/query - - client/commands/rpc - - client/commands/search - - client/commands/txs - - client/rest - - errors - - genesis - - modules/auth - - modules/auth/commands - - modules/base - - modules/base/commands - - modules/coin - - modules/coin/commands - - modules/coin/rest - - modules/fee - - modules/fee/commands - - modules/ibc - - modules/ibc/commands - - modules/nonce - - modules/nonce/commands - - modules/nonce/rest - - modules/roles - - modules/roles/commands - - modules/roles/rest - - server/commands - - stack - - state - - version -- name: github.com/MrXJC/gaia - version: develop - subpackages: - - modules/stake - - modules/stake/commands - - modules/stake/rest - - version -- name: github.com/ebuchman/fail-test - version: 95f809107225be108efcf10a3509e4ea6ceef3c4 -- name: github.com/fsnotify/fsnotify - version: 4da3e2cfbabc9f751898f250b49f2439785783a1 -- name: github.com/go-kit/kit - version: 4dc7be5d2d12881735283bcab7352178e190fc71 - subpackages: - - log - - log/level - - log/term -- name: github.com/go-logfmt/logfmt - version: 390ab7935ee28ec6b286364bba9b4dd6410cb3d5 -- name: github.com/go-playground/locales - version: e4cbcb5d0652150d40ad0646651076b6bd2be4f6 - subpackages: - - currency -- name: github.com/go-playground/universal-translator - version: 71201497bace774495daed26a3874fd339e0b538 -- name: github.com/go-stack/stack - version: 259ab82a6cad3992b4e21ff5cac294ccb06474bc -- name: github.com/gogo/protobuf - version: 1adfc126b41513cc696b209667c8656ea7aac67c - subpackages: - - gogoproto - - jsonpb - - proto - - protoc-gen-gogo/descriptor - - sortkeys - - types -- name: github.com/golang/protobuf - version: 925541529c1fa6821df4e44ce2723319eb2be768 - subpackages: - - proto - - ptypes - - ptypes/any - - ptypes/duration - - ptypes/timestamp -- name: github.com/golang/snappy - version: 553a641470496b2327abcac10b36396bd98e45c9 -- name: github.com/gorilla/context - version: 08b5f424b9271eedf6f9f0ce86cb9396ed337a42 -- name: github.com/gorilla/mux - version: 53c1911da2b537f792e7cafcb446b05ffe33b996 -- name: github.com/gorilla/websocket - version: ea4d1f681babbce9545c9c5f3d5194a789c89f5b -- name: github.com/hashicorp/hcl - version: 23c074d0eceb2b8a5bfdbb271ab780cde70f05a8 - subpackages: - - hcl/ast - - hcl/parser - - hcl/scanner - - hcl/strconv - - hcl/token - - json/parser - - json/scanner - - json/token -- name: github.com/howeyc/crc16 - version: 2b2a61e366a66d3efb279e46176e7291001e0354 -- name: github.com/inconshreveable/mousetrap - version: 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 -- name: github.com/jmhodges/levigo - version: c42d9e0ca023e2198120196f842701bb4c55d7b9 -- name: github.com/kr/logfmt - version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0 -- name: github.com/magiconair/properties - version: 49d762b9817ba1c2e9d0c69183c2b4a8b8f1d934 -- name: github.com/mattn/go-isatty - version: 0360b2af4f38e8d38c7fce2a9f4e702702d73a39 -- name: github.com/mitchellh/mapstructure - version: 06020f85339e21b2478f756a78e295255ffa4d6a -- name: github.com/pelletier/go-toml - version: 4e9e0ee19b60b13eb79915933f44d8ed5f268bdd -- name: github.com/pkg/errors - version: 645ef00459ed84a119197bfb8d8205042c6df63d -- name: github.com/rcrowley/go-metrics - version: e181e095bae94582363434144c61a9653aff6e50 -- name: github.com/spf13/afero - version: 8d919cbe7e2627e417f3e45c3c0e489a5b7e2536 - subpackages: - - mem -- name: github.com/spf13/cast - version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 -- name: github.com/spf13/cobra - version: 7b2c5ac9fc04fc5efafb60700713d4fa609b777b -- name: github.com/spf13/jwalterweatherman - version: 12bd96e66386c1960ab0f74ced1362f66f552f7b -- name: github.com/spf13/pflag - version: e57e3eeb33f795204c1ca35f56c44f83227c6e66 -- name: github.com/spf13/viper - version: 25b30aa063fc18e48662b86996252eabdcf2f0c7 -- name: github.com/syndtr/goleveldb - version: adf24ef3f94bd13ec4163060b21a5678f22b429b - subpackages: - - leveldb - - leveldb/cache - - leveldb/comparer - - leveldb/errors - - leveldb/filter - - leveldb/iterator - - leveldb/journal - - leveldb/memdb - - leveldb/opt - - leveldb/storage - - leveldb/table - - leveldb/util -- name: github.com/tendermint/abci - version: 3d5f0a8b94bbbfa70ecd4072fc55854f8210425b - subpackages: - - client - - example/code - - example/kvstore - - server - - types -- name: github.com/tendermint/ed25519 - version: d8387025d2b9d158cf4efb07e7ebf814bcce2057 - subpackages: - - edwards25519 - - extra25519 -- name: github.com/tendermint/go-crypto - version: 2017856384589234024cda848a6332157d1f527c - subpackages: - - keys - - keys/cryptostore - - keys/storage/filestorage - - keys/wordlist -- name: github.com/tendermint/go-wire - version: b6fc872b42d41158a60307db4da051dd6f179415 - subpackages: - - data -- name: github.com/tendermint/iavl - version: 39de8f0b4ee758fdd5bb3a9afc6dd9bf42c04785 -- name: github.com/tendermint/tendermint - version: 9c5937df969de23e9087f183c52b5088d4b6f268 - subpackages: - - blockchain - - cmd/tendermint/commands - - config - - consensus - - consensus/types - - evidence - - lite - - lite/client - - lite/errors - - lite/files - - lite/proxy - - mempool - - node - - p2p - - p2p/conn - - p2p/pex - - p2p/trust - - p2p/upnp - - proxy - - rpc/client - - rpc/core - - rpc/core/types - - rpc/grpc - - rpc/lib - - rpc/lib/client - - rpc/lib/server - - rpc/lib/types - - state - - state/txindex - - state/txindex/kv - - state/txindex/null - - types - - version -- name: github.com/tendermint/tmlibs - version: 26f2ab65f82cfc6873c312e8030104c47c05f10e - subpackages: - - autofile - - cli - - cli/flags - - clist - - common - - db - - flowrate - - log - - merkle - - pubsub - - pubsub/query -- name: golang.org/x/crypto - version: 94eea52f7b742c7cbe0b03b22f0c4c8631ece122 - subpackages: - - curve25519 - - nacl/box - - nacl/secretbox - - openpgp/armor - - openpgp/errors - - poly1305 - - ripemd160 - - salsa20/salsa -- name: golang.org/x/net - version: 5ccada7d0a7ba9aeb5d3aca8d3501b4c2a509fec - subpackages: - - context - - http2 - - http2/hpack - - idna - - internal/timeseries - - lex/httplex - - trace -- name: golang.org/x/sys - version: 8b4580aae2a0dd0c231a45d3ccb8434ff533b840 - subpackages: - - unix -- name: golang.org/x/text - version: 57961680700a5336d15015c8c50686ca5ba362a4 - subpackages: - - secure/bidirule - - transform - - unicode/bidi - - unicode/norm -- name: google.golang.org/genproto - version: a8101f21cf983e773d0c1133ebc5424792003214 - repo: https://github.com/google/go-genproto - vcs: git - subpackages: - - googleapis/rpc/status -- name: google.golang.org/grpc - version: 401e0e00e4bb830a10496d64cd95e068c5bf50de - repo: https://github.com/grpc/grpc-go - vcs: git - subpackages: - - balancer - - codes - - connectivity - - credentials - - grpclb/grpc_lb_v1/messages - - grpclog - - internal - - keepalive - - metadata - - naming - - peer - - resolver - - stats - - status - - tap - - transport -- name: gopkg.in/go-playground/validator.v9 - version: 1b8c8e19cd250435025214492d9a08411d760fdd -- name: gopkg.in/yaml.v2 - version: 287cf08546ab5e7e37d55a84f7ed3fd1db036de5 -testImports: -- name: github.com/stretchr/testify - version: 2aa2c176b9dab406a6970f6a55f513e8a8c8b18f - subpackages: - - assert - - require diff --git a/glide.yaml b/glide.yaml deleted file mode 100644 index a279a3c69..000000000 --- a/glide.yaml +++ /dev/null @@ -1,17 +0,0 @@ -package: github.com/irisnet/iris-hub -import: -- package: github.com/MrXJC/gaia - version: develop -- package: github.com/cosmos/cosmos-sdk - version: tm-develop -- package: google.golang.org/grpc - repo: https://github.com/grpc/grpc-go - vcs: git -- package: google.golang.org/genproto - repo: https://github.com/google/go-genproto - vcs: git -testImport: -- package: github.com/stretchr/testify - subpackages: - - assert - - require diff --git a/module/rest-txs/txs.go b/module/rest-txs/txs.go deleted file mode 100644 index 72230d389..000000000 --- a/module/rest-txs/txs.go +++ /dev/null @@ -1,53 +0,0 @@ -package rest_txs - -import ( - "net/http" - - "github.com/gorilla/mux" - wire "github.com/tendermint/go-wire" - rpcclient "github.com/tendermint/tendermint/rpc/client" - - sdk "github.com/cosmos/cosmos-sdk" -) - -// ServiceTxs exposes a REST API service for sendings txs. -// It wraps a Tendermint RPC client. -type ServiceTxs struct { - node rpcclient.Client -} - -func NewServiceTxs(c rpcclient.Client) *ServiceTxs { - return &ServiceTxs{ - node: c, - } -} - -func (s *ServiceTxs) PostTx(w http.ResponseWriter, r *http.Request) { - tx := new(sdk.Tx) - if err := sdk.ParseRequestAndValidateJSON(r, tx); err != nil { - sdk.WriteError(w, err) - return - } - - packet := wire.BinaryBytes(*tx) - // commit, err := s.node.BroadcastTxCommit(packet) - commit, err := s.node.BroadcastTxSync(packet) - if err != nil { - sdk.WriteError(w, err) - return - } - - sdk.WriteSuccess(w, commit) -} - -// mux.Router registrars - -// RegisterPostTx is a mux.Router handler that exposes POST -// method access to post a transaction to the blockchain. -func (s *ServiceTxs) RegisterPostTx(r *mux.Router) error { - r.HandleFunc("/tx", s.PostTx).Methods("POST") - return nil -} - -// End of mux.Router registrars - diff --git a/rest/byteTx.go b/rest/byteTx.go deleted file mode 100644 index 604af6c55..000000000 --- a/rest/byteTx.go +++ /dev/null @@ -1,118 +0,0 @@ -package rest - -import ( - "github.com/gorilla/mux" - "github.com/tendermint/go-crypto/keys" - "net/http" - sdk "github.com/cosmos/cosmos-sdk" - "encoding/hex" - "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/client/commands" - "github.com/pkg/errors" - cmn "github.com/tendermint/tmlibs/common" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/commands/query" - "github.com/tendermint/tendermint/types" - "github.com/tendermint/go-wire" - "io" -) - - -type ServiceByteTx struct { - manager keys.Manager -} - -type RequestTx struct { - Tx sdk.Tx `json:"tx" validate:"required"` -} - -func NewServiceByteTx(manager keys.Manager) *ServiceByteTx { - return &ServiceByteTx{ - manager: manager, // XXX keycmd.GetKeyManager() - } -} - -func (s *ServiceByteTx) RegisterByteTx(r *mux.Router) error { - r.HandleFunc("/byteTx", s.ByteTx).Methods("POST") - return nil -} - - -func (s *ServiceByteTx) RegisterqueryTx(r *mux.Router) error { - r.HandleFunc("/tx/{hash}", s.queryTx).Methods("GET") - return nil -} - -func (s *ServiceByteTx) ByteTx(w http.ResponseWriter, r *http.Request) { - req := new(RequestTx) - if err := sdk.ParseRequestAndValidateJSON(r, req); err != nil { - sdk.WriteError(w, err) - return - } - - tx := req.Tx - - if sign, ok := tx.Unwrap().(keys.Signable); ok { - sdk.WriteSuccess(w, hex.EncodeToString(sign.SignBytes())) - return - } - sdk.WriteSuccess(w, "") -} - -func (s *ServiceByteTx) queryTx(w http.ResponseWriter, r *http.Request){ - args := mux.Vars(r) - hash := args["hash"] - - if hash == "" { - sdk.WriteError(w, errors.Errorf("[%s] argument must be non-empty ", "hash")) - return - } - // with tx, we always just parse key as hex and use to lookup - hashByte, err := hex.DecodeString(cmn.StripHex(hash)) - - // get the proof -> this will be used by all prover commands - node := commands.GetNode() - prove := !viper.GetBool(commands.FlagTrustNode) - res, err := node.Tx(hashByte, prove) - if err != nil { - sdk.WriteError(w, err) - return - } - - // no checks if we don't get a proof - if !prove { - sdk.WriteSuccess(w,showTx(w,res.Height, res.Tx)) - return - } - - cert, err := commands.GetCertifier() - if err != nil { - sdk.WriteError(w, err) - return - } - - check, err := client.GetCertifiedCommit(res.Height, node, cert) - if err != nil { - sdk.WriteError(w, err) - return - } - err = res.Proof.Validate(check.Header.DataHash) - if err != nil { - sdk.WriteError(w, err) - return - } - - // note that we return res.Proof.Data, not res.Tx, - // as res.Proof.Validate only verifies res.Proof.Data - sdk.WriteSuccess(w,showTx(w,res.Height, res.Proof.Data)) -} - -// showTx parses anything that was previously registered as sdk.Tx -func showTx(w io.Writer ,h int64, tx types.Tx) error { - var info sdk.Tx - err := wire.ReadBinaryBytes(tx, &info) - if err != nil { - return err - } - return query.FoutputProof(w,info,h) -} \ No newline at end of file diff --git a/testnets/develop/README.md b/testnets/develop/README.md new file mode 100644 index 000000000..98725486f --- /dev/null +++ b/testnets/develop/README.md @@ -0,0 +1,28 @@ +### Running in command line +这个命令会在宿主机后台启动一个iris进程,启动前需要确认宿主机已安装iris、iriscli,并确认`46656`和`46657`端口没有被占用, +命令会删除$HOME/.iris*目录,请注意做好备份 +``` +nohup sh start.sh > iris.log 2>&1 & +``` +查看日志: +```$xslt +tail -f iris.log +``` +查看账户列表: +```$xslt +iriscli keys list +``` + +### Running in docker +这个命令会启动一个基于最新develop分支构建的镜像的docker容器,启动前需要确认`46656`和`46657`端口没有被占用 +``` +sh start-docker.sh +``` +查看日志: +```$xslt +docker logs -f irishub-sandbox +``` +查看账户列表: +```$xslt +docker exec -it irishub-sandbox iriscli keys list +``` \ No newline at end of file diff --git a/testnets/develop/config/genesis.json b/testnets/develop/config/genesis.json new file mode 100644 index 000000000..7e45a374f --- /dev/null +++ b/testnets/develop/config/genesis.json @@ -0,0 +1,102 @@ +{ + "app_hash": "", + "genesis_time": "2018-06-20T23:34:15.721008+08:00", + "chain_id": "fuxi-develop", + "consensus_params": { + "block_size_params": { + "max_bytes": 22020096, + "max_txs": 100000, + "max_gas": -1 + }, + "tx_size_params": { + "max_bytes": 10240, + "max_gas": -1 + }, + "block_gossip_params": { + "block_part_size_bytes": 65536 + }, + "evidence_params": { + "max_age": 100000 + } + }, + "app_state": { + "accounts": [ + { + "address": "507405661F2DB1940941FA0A6B3642015A015387", + "coins": [ + { + "denom": "iris", + "amount": 200000000 + }, + { + "denom": "steak", + "amount": 100 + } + ] + } + ], + "stake": { + "pool": { + "loose_unbonded_tokens": 100, + "unbonded_tokens": 0, + "unbonding_tokens": 0, + "bonded_tokens": 100, + "unbonded_shares": "0", + "unbonding_shares": "0", + "bonded_shares": "100", + "inflation_last_time": 0, + "inflation": "7/100", + "date_last_commission_reset": 0, + "prev_bonded_shares": "0" + }, + "params": { + "inflation_rate_change": "13/100", + "inflation_max": "1/5", + "inflation_min": "7/100", + "goal_bonded": "67/100", + "max_validators": 100, + "bond_denom": "steak" + }, + "validators": [ + { + "owner": "507405661F2DB1940941FA0A6B3642015A015387", + "pub_key": { + "type": "AC26791624DE60", + "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" + }, + "revoked": false, + "pool_shares": { + "status": 2, + "amount": "100" + }, + "delegator_shares": "0", + "description": { + "moniker": "init1", + "identity": "", + "website": "", + "details": "" + }, + "bond_height": 0, + "bond_intra_tx_counter": 0, + "proposer_reward_pool": [], + "commission": "0", + "commission_max": "0", + "commission_change_rate": "0", + "commission_change_today": "0", + "prev_bonded_shares": "0" + } + ], + "bonds": null + } + }, + "validators": [ + { + "pub_key": { + "type": "AC26791624DE60", + "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" + }, + "power": 100, + "name": "" + } + ] +} \ No newline at end of file diff --git a/testnets/develop/config/gentx/gentx-7db17b3821cf22382b7afe03e30bd04d1b4f10eb.json b/testnets/develop/config/gentx/gentx-7db17b3821cf22382b7afe03e30bd04d1b4f10eb.json new file mode 100644 index 000000000..9eb7c6484 --- /dev/null +++ b/testnets/develop/config/gentx/gentx-7db17b3821cf22382b7afe03e30bd04d1b4f10eb.json @@ -0,0 +1,20 @@ +{ + "node_id": "7db17b3821cf22382b7afe03e30bd04d1b4f10eb", + "ip": "192.168.150.125", + "validator": { + "pub_key": { + "type": "AC26791624DE60", + "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" + }, + "power": 100, + "name": "" + }, + "app_gen_tx": { + "name": "init1", + "address": "507405661F2DB1940941FA0A6B3642015A015387", + "pub_key": { + "type": "AC26791624DE60", + "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" + } + } +} \ No newline at end of file diff --git a/testnets/develop/config/node_key.json b/testnets/develop/config/node_key.json new file mode 100644 index 000000000..b1bcf6126 --- /dev/null +++ b/testnets/develop/config/node_key.json @@ -0,0 +1 @@ +{"priv_key":{"type":"954568A3288910","value":"6TWNBR3I7mIZ0IbeAVuhRU8eqEo/9QxlBxxVdO9TFodLtd05OpOiXFrI+xST4Sy4p11qV11agb33Iiv5i8GAzA=="}} \ No newline at end of file diff --git a/testnets/develop/config/priv_validator.json b/testnets/develop/config/priv_validator.json new file mode 100644 index 000000000..48a1ab5ea --- /dev/null +++ b/testnets/develop/config/priv_validator.json @@ -0,0 +1,14 @@ +{ + "address": "823E3266359570A41A6B31C7A1F738F19923A0F0", + "pub_key": { + "type": "AC26791624DE60", + "value": "CJj2r5sGJ0jn8maLpEiFYeYctyjGNskD4tW6Daz/fVk=" + }, + "last_height": 0, + "last_round": 0, + "last_step": 0, + "priv_key": { + "type": "954568A3288910", + "value": "wVB2h4AeVpuWJ/xJlfKV3cf/6WNrVfxLr+CkbWU7E/4ImPavmwYnSOfyZoukSIVh5hy3KMY2yQPi1boNrP99WQ==" + } +} \ No newline at end of file diff --git a/testnets/develop/seed_phrase b/testnets/develop/seed_phrase new file mode 100644 index 000000000..4d9127cc2 --- /dev/null +++ b/testnets/develop/seed_phrase @@ -0,0 +1 @@ +segment winner ability purse fiction robust glass find mechanic bind park attend jealous symbol artefact abandon \ No newline at end of file diff --git a/testnets/develop/start-docker.sh b/testnets/develop/start-docker.sh new file mode 100644 index 000000000..3dce2829c --- /dev/null +++ b/testnets/develop/start-docker.sh @@ -0,0 +1,5 @@ +#!/bin/bash +docker run -d -p 46656:46656 -p 46657:46657 --name irishub-sandbox -it irishub:develop sh -c ' + apk add --no-cache curl expect && \ + curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/start.sh -o start.sh && \ + sh start.sh' \ No newline at end of file diff --git a/testnets/develop/start.sh b/testnets/develop/start.sh new file mode 100644 index 000000000..53bf8fdd6 --- /dev/null +++ b/testnets/develop/start.sh @@ -0,0 +1,20 @@ +#!/bin/bash +rm -rf ~/.iris* +mkdir -p ~/.iris/config/gentx/ +curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/genesis.json -o ~/.iris/config/genesis.json +curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/node_key.json -o ~/.iris/config/node_key.json +curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/priv_validator.json -o ~/.iris/config/priv_validator.json +curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json -o ~/.iris/config/gentx/gentx-3b11af84e5cc261178eaa328978b0dd61adc561a.json +iris init --chain-id=fuxi-develop --name=init1 +SP=$(curl https://raw.githubusercontent.com/irisnet/irishub/develop/testnets/develop/seed_phrase) +command="iriscli keys add init1 --recover" +expect -c " + spawn $command; + expect { + \"override the existing name*\" {send \"y\r\"; exp_continue} + \"Enter a passphrase for your key:\" {send \"1234567890\r\"; exp_continue} + \"Repeat the passphrase:\" {send \"1234567890\r\"; exp_continue} + \"Enter your recovery seed phrase:\" {send \"$SP\r\"; exp_continue} + } +" +iris start \ No newline at end of file diff --git a/tools/context.go b/tools/context.go new file mode 100644 index 000000000..da4d0b160 --- /dev/null +++ b/tools/context.go @@ -0,0 +1,90 @@ +package tools + +import ( + "encoding/json" + "fmt" + "github.com/cosmos/cosmos-sdk/client/context" + ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/cosmos/cosmos-sdk/wire" + "io/ioutil" + "net/http" + "strings" +) + +type Context struct { + context.CoreContext + StoreName string + Cdc *wire.Codec +} + +func NewContext(storeName string,cdc *wire.Codec) Context { + ctx := context.NewCoreContextFromViper() + return Context{ + ctx,storeName,cdc, + } +} + +type JsonRpc interface { + NetInfo() *ctypes.ResultNetInfo + NumUnconfirmedTxs() *ctypes.ResultUnconfirmedTxs +} + +func (rpc Context) NetInfo() *ctypes.ResultNetInfo { + client := &http.Client{} + + reqUri := tcpToHttpUrl(rpc.NodeURI) + "/net_info" + + resp, err := client.Get(reqUri) + if err != nil { + fmt.Println(err) + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + fmt.Println(err) + } + + var res = struct { + JsonRpc string `json:"jsonrpc"` + Id string `json:"id"` + Result ctypes.ResultNetInfo `json:"result"` + }{} + if err := json.Unmarshal(body, &res); err != nil { + fmt.Println(err) + } + + return &res.Result +} + +func (rpc Context) NumUnconfirmedTxs() *ctypes.ResultUnconfirmedTxs { + client := &http.Client{} + reqUri := tcpToHttpUrl(rpc.NodeURI) + "/num_unconfirmed_txs" + + resp, err := client.Get(reqUri) + if err != nil { + fmt.Println(err) + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + fmt.Println(err) + } + + var res = struct { + JsonRpc string `json:"jsonrpc"` + Id string `json:"id"` + Result ctypes.ResultUnconfirmedTxs `json:"result"` + }{} + if err := json.Unmarshal(body, &res); err != nil { + fmt.Println(err) + } + + return &res.Result +} + +func tcpToHttpUrl(url string) string { + urls := strings.Replace(url, "tcp", "http", 1) + return urls +} diff --git a/tools/prometheus/consensus/metrics.go b/tools/prometheus/consensus/metrics.go new file mode 100644 index 000000000..696162354 --- /dev/null +++ b/tools/prometheus/consensus/metrics.go @@ -0,0 +1,215 @@ +package consensus + +import ( + cctx "context" + "encoding/hex" + "fmt" + "github.com/cosmos/cosmos-sdk/wire" // XXX fix + "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/go-kit/kit/metrics" + "github.com/go-kit/kit/metrics/prometheus" + tools "github.com/irisnet/irishub/tools" + stdprometheus "github.com/prometheus/client_golang/prometheus" + "github.com/tendermint/tendermint/types" + "log" + "strings" + "time" +) + +// Metrics contains metrics exposed by this package. +type Metrics struct { + // Height of the chain. + Height metrics.Gauge + + // Number of rounds. + Rounds metrics.Gauge + + // Number of validators. + Validators metrics.Gauge + // Number of Candidates + Candidates metrics.Gauge + // Total power of all validators. + ValidatorsPower metrics.Gauge + // Number of validators who did not sign. + MissingValidators metrics.Gauge + // Total power of the missing validators. + MissingValidatorsPower metrics.Gauge + // Number of validators who tried to double sign. + ByzantineValidators metrics.Gauge + // Total power of the byzantine validators. + ByzantineValidatorsPower metrics.Gauge + + // Time between this and the last block. + BlockIntervalSeconds metrics.Histogram + + // Number of transactions. + NumTxs metrics.Gauge + // Size of the block. + BlockSizeBytes metrics.Gauge + // Total number of transactions. + TotalTxs metrics.Gauge +} + +// PrometheusMetrics returns Metrics build using Prometheus client library. +func PrometheusMetrics() *Metrics { + return &Metrics{ + Height: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "height", + Help: "Height of the chain.", + }, []string{}), + Rounds: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "rounds", + Help: "Number of rounds.", + }, []string{}), + + Validators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "validators", + Help: "Number of validators.", + }, []string{}), + + Candidates: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "candidates", + Help: "Number of Candidates.", + }, []string{}), + + ValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "validators_power", + Help: "Total power of all validators.", + }, []string{}), + MissingValidators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "missing_validators", + Help: "Number of validators who did not sign.", + }, []string{}), + MissingValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "missing_validators_power", + Help: "Total power of the missing validators.", + }, []string{}), + ByzantineValidators: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "byzantine_validators", + Help: "Number of validators who tried to double sign.", + }, []string{}), + ByzantineValidatorsPower: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "byzantine_validators_power", + Help: "Total power of the byzantine validators.", + }, []string{}), + + BlockIntervalSeconds: prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{ + Subsystem: "consensus", + Name: "block_interval_seconds", + Help: "Time between this and the last block.", + Buckets: []float64{1, 2.5, 5, 10, 60}, + }, []string{}), + + NumTxs: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "num_txs", + Help: "Number of transactions.", + }, []string{}), + BlockSizeBytes: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "block_size_bytes", + Help: "Size of the block.", + }, []string{}), + TotalTxs: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "consensus", + Name: "total_txs", + Help: "Total number of transactions.", + }, []string{}), + } +} + +func (cs *Metrics) Start(ctx tools.Context) { + context, _ := cctx.WithTimeout(cctx.Background(), 10*time.Second) + + var client = ctx.Client + //开启监听事件 + client.Start() + + blockC := make(chan interface{}) + + err := client.Subscribe(context, "monitor", types.EventQueryNewBlock, blockC) + + if err != nil { + log.Println("got ", err) + } + + go func() { + for e := range blockC { + block := e.(types.TMEventData).(types.EventDataNewBlock) + cs.RecordMetrics(ctx, ctx.Cdc, block.Block, ctx.StoreName) + } + }() +} + +func (cs *Metrics) RecordMetrics(ctx tools.Context, cdc *wire.Codec, block *types.Block, storeName string) { + cs.Height.Set(float64(block.Height)) + cs.ByzantineValidators.Set(float64(len(block.Evidence.Evidence))) + + missingValidators := 0 + missingValidatorsPower := int64(0) + validatorsPower := int64(0) + resultValidators, err := ctx.Client.Validators(&block.Height) + if err != nil { + panic(err) + } + validators := resultValidators.Validators + valMap := make(map[string]types.Validator, len(validators)) + for i, val := range validators { + var vote *types.Vote + if i < len(block.LastCommit.Precommits) { + vote = block.LastCommit.Precommits[i] + } + if vote == nil { + missingValidators++ + missingValidatorsPower += val.VotingPower + } + + valMap[val.Address.String()] = *val + validatorsPower += val.VotingPower + } + cs.Candidates.Set(float64(getCandidatesNum(cdc, ctx, storeName))) + cs.MissingValidators.Set(float64(missingValidators)) + cs.MissingValidatorsPower.Set(float64(missingValidatorsPower)) + cs.ValidatorsPower.Set(float64(validatorsPower)) + cs.Validators.Set(float64(len(validators))) + + byzantineValidatorsPower := int64(0) + for _, ev := range block.Evidence.Evidence { + addr := strings.ToUpper(hex.EncodeToString(ev.Address())) + if val, ok := valMap[addr]; ok { + byzantineValidatorsPower += val.VotingPower + } + } + cs.ByzantineValidatorsPower.Set(float64(byzantineValidatorsPower)) + + if block.Height > 1 { + lastBlockHight := block.Height - 1 + lastBlock, _ := ctx.Client.Block(&lastBlockHight) + interval := block.Time.Sub(lastBlock.BlockMeta.Header.Time).Seconds() + cs.BlockIntervalSeconds.Observe(interval) + } + + cs.NumTxs.Set(float64(block.NumTxs)) + cs.TotalTxs.Set(float64(block.TotalTxs)) + + bz, _ := cdc.MarshalBinaryBare(block) + cs.BlockSizeBytes.Set(float64(len(bz))) +} + +func getCandidatesNum(cdc *wire.Codec, ctx tools.Context, storeName string) int { + key := stake.ValidatorsKey + resKVs, err := ctx.QuerySubspace(cdc, key, storeName) + if err != nil { + fmt.Println(err) + } + return len(resKVs) +} diff --git a/tools/prometheus/mempool/metrics.go b/tools/prometheus/mempool/metrics.go new file mode 100644 index 000000000..c7562993b --- /dev/null +++ b/tools/prometheus/mempool/metrics.go @@ -0,0 +1,38 @@ +package mempool + +import ( + "github.com/go-kit/kit/metrics" + "github.com/go-kit/kit/metrics/prometheus" + tools "github.com/irisnet/irishub/tools" + stdprometheus "github.com/prometheus/client_golang/prometheus" + "time" +) + +// Metrics contains metrics exposed by this package. +// see MetricsProvider for descriptions. +type Metrics struct { + // Size of the mempool. + Size metrics.Gauge +} + +// PrometheusMetrics returns Metrics build using Prometheus client library. +func PrometheusMetrics() *Metrics { + return &Metrics{ + Size: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "mempool", + Name: "size", + Help: "Size of the mempool (number of uncommitted transactions).", + }, []string{}), + } +} + +func (m *Metrics) Start(rpc tools.Context) { + go func() { + for { + time.Sleep(1 * time.Second) + result := rpc.NumUnconfirmedTxs() + m.Size.Set(float64(result.N)) + } + }() + +} diff --git a/tools/prometheus/p2p/metrics.go b/tools/prometheus/p2p/metrics.go new file mode 100644 index 000000000..95817918c --- /dev/null +++ b/tools/prometheus/p2p/metrics.go @@ -0,0 +1,36 @@ +package p2p + +import ( + "github.com/go-kit/kit/metrics" + "github.com/go-kit/kit/metrics/prometheus" + tools "github.com/irisnet/irishub/tools" + stdprometheus "github.com/prometheus/client_golang/prometheus" + "time" +) + +// Metrics contains metrics exposed by this package. +type Metrics struct { + // Number of peers. + Peers metrics.Gauge +} + +// PrometheusMetrics returns Metrics build using Prometheus client library. +func PrometheusMetrics() *Metrics { + return &Metrics{ + Peers: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "p2p", + Name: "peers", + Help: "Number of peers.", + }, []string{}), + } +} + +func (m *Metrics) Start(ctx tools.Context) { + go func() { + for { + time.Sleep(1 * time.Second) + result := ctx.NetInfo() + m.Peers.Set(float64(result.NPeers)) + } + }() +} diff --git a/tools/prometheus/provider.go b/tools/prometheus/provider.go new file mode 100644 index 000000000..a6ecd0a64 --- /dev/null +++ b/tools/prometheus/provider.go @@ -0,0 +1,42 @@ +package prometheus + +import ( + "github.com/irisnet/irishub/tools" + cs "github.com/irisnet/irishub/tools/prometheus/consensus" + mempl "github.com/irisnet/irishub/tools/prometheus/mempool" + "github.com/irisnet/irishub/tools/prometheus/p2p" + sys "github.com/irisnet/irishub/tools/prometheus/system" +) + +type Monitor struct { + providers []MetricsProvider + ctx tools.Context +} + +func DefaultMonitor(ctx tools.Context) *Monitor { + var providers []MetricsProvider + monitor := &Monitor{ + providers: providers, + ctx:ctx, + } + monitor.AddMetricsProvider(cs.PrometheusMetrics()). + AddMetricsProvider(p2p.PrometheusMetrics()). + AddMetricsProvider(mempl.PrometheusMetrics()). + AddMetricsProvider(sys.PrometheusMetrics()) + return monitor +} + +func (m *Monitor) AddMetricsProvider(provider MetricsProvider) *Monitor { + m.providers = append(m.providers, provider) + return m +} + +func (m *Monitor) Start() { + for _, provider := range m.providers { + provider.Start(m.ctx) + } +} + +type MetricsProvider interface { + Start(ctx tools.Context) +} diff --git a/tools/prometheus/server.go b/tools/prometheus/server.go new file mode 100644 index 000000000..b55d1934c --- /dev/null +++ b/tools/prometheus/server.go @@ -0,0 +1,55 @@ +package prometheus + +import ( + "github.com/cosmos/cosmos-sdk/wire" + "github.com/irisnet/irishub/tools" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/spf13/cobra" + cmn "github.com/tendermint/tmlibs/common" + "log" + "net/http" + "github.com/irisnet/irishub/app" +) + +func MonitorCommand(storeName string, cdc *wire.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "monitor", + Short: "irishub monitor", + RunE: func(cmd *cobra.Command, args []string) error { + + ctx := tools.NewContext(storeName,cdc) + monitor := DefaultMonitor(ctx) + monitor.Start() + + srv := &http.Server{ + Addr: ":26660", + Handler: promhttp.Handler(), + } + go func() { + if err := srv.ListenAndServe(); err != http.ErrServerClosed { + log.Println("got ", err) + } + }() + + cmn.TrapSignal(func() { + ctx.Client.Stop() + srv.Close() + }) + + return nil + }, + } + cmd.Flags().StringP("node", "n", "tcp://localhost:46657", "Node to connect to") + cmd.Flags().String("chain-id", "fuxi", "Chain ID of tendermint node") + cmd.Flags().StringP("commands", "c", "iris start", `the processes you want to monitor that started +by these commands, separated by semicolons ';'. +eg: --commands="command 0;command 1;command 2", --commands=iris by default`) + cmd.Flags().StringP("disks", "d", "/", `mounted paths of storage devices, separated by semicolons ';'. +eg: --disks="/;/mnt1;/mnt2"`) + cmd.Flags().StringP("paths", "p", app.DefaultNodeHome, `path to config and data files/directories, separated by semicolons ';'. +cannot use ~ and environment variables. eg: --paths="/etc;/home; +size of files in sub-directories is excluded. to compute the size recursively, you can use --recursively=true"`) + cmd.Flags().BoolP("recursively", "r", false, `specify whether the files in sub-directories is included, +excluded by default. If there are many files & sub-directory in given directories, this program may be very slow!`) + return cmd +} diff --git a/tools/prometheus/system/metrics.go b/tools/prometheus/system/metrics.go new file mode 100644 index 000000000..f58fe5bdc --- /dev/null +++ b/tools/prometheus/system/metrics.go @@ -0,0 +1,342 @@ +package system + +import ( + "bytes" + "container/list" + "errors" + "fmt" + "github.com/go-kit/kit/metrics" + "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" + "github.com/shirou/gopsutil/cpu" + "github.com/shirou/gopsutil/disk" + "github.com/shirou/gopsutil/mem" + "github.com/shirou/gopsutil/process" + "github.com/spf13/viper" + "io/ioutil" + "os" + "os/exec" + "strconv" + "strings" + "time" + "unicode" + "github.com/irisnet/irishub/tools" +) + +type Metrics struct { + CPUUtilization metrics.Gauge + MemoUtilization metrics.Gauge + + //processes related monitor term + ProcCPUUtilization []metrics.Gauge + ProcMemoUtilization []metrics.Gauge + ProcOpenedFilesNum []metrics.Gauge + processes []process.Process + + //storage related monitor term + DiskUsedPercentage []metrics.Gauge + DiskFreeSpace []metrics.Gauge + disks []string + + //file related monitor term + FileSize []metrics.Gauge + filePaths []string + recursively bool //whether compute directories size recursively + DirectorySize []metrics.Gauge + dirPaths []string +} + +// PrometheusMetrics returns Metrics build using Prometheus client library. +func PrometheusMetrics() *Metrics { + return &Metrics{ + CPUUtilization: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: "cpu_percent", + Help: "CPU Utilization Percantage", + }, []string{}), + MemoUtilization: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: "memo_percent", + Help: "Memo Utilization Percantage", + }, []string{}), + ProcCPUUtilization: make([]metrics.Gauge, 0), + ProcMemoUtilization: make([]metrics.Gauge, 0), + ProcOpenedFilesNum: make([]metrics.Gauge, 0), + DiskUsedPercentage: make([]metrics.Gauge, 0), + DiskFreeSpace: make([]metrics.Gauge, 0), + FileSize: make([]metrics.Gauge, 0), + DirectorySize: make([]metrics.Gauge, 0), + processes: make([]process.Process, 0), + recursively: false, + disks: make([]string, 0), + filePaths: make([]string, 0), + dirPaths: make([]string, 0), + } +} + +func (metrics *Metrics) addDisk(diskPath string) { + metrics.disks = append(metrics.disks, diskPath) + + name := fmt.Sprintf("disk_used_percentage_%s", getPathName(diskPath)) + help := fmt.Sprintf("Used Percentage of disk mount on path: %s", diskPath) + metrics.DiskUsedPercentage = append(metrics.DiskUsedPercentage, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: name, + Help: help, + }, []string{})) + + name = fmt.Sprintf("disk_free_space_%s", getPathName(diskPath)) + help = fmt.Sprintf("Free space of disk mount on path: %s", diskPath) + metrics.DiskFreeSpace = append(metrics.DiskFreeSpace, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: name, + Help: help, + }, []string{})) + +} + +func (metrics *Metrics) addPath(path string) { + if fileInfo, err := os.Stat(path); err != nil { + fmt.Println(err.Error()) + return + } else { + if fileInfo.IsDir() { + metrics.dirPaths = append(metrics.dirPaths, path) + name := fmt.Sprintf("direcotry_size_%s", getPathName(path)) + help := fmt.Sprintf("total Size of files in %s", path) + metrics.DirectorySize = append(metrics.DirectorySize, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: name, + Help: help, + }, []string{})) + } else { + metrics.filePaths = append(metrics.filePaths, path) + name := fmt.Sprintf("file_size_%s", getPathName(path)) + help := fmt.Sprintf("size of files: %s", path) + metrics.FileSize = append(metrics.FileSize, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: name, + Help: help, + }, []string{})) + } + } +} + +func (metrics *Metrics) add() { + commands := viper.GetString("commands") + for _, command := range strings.Split(commands, ";") { + if strings.TrimSpace(command) != "" { + metrics.addProcess(strings.TrimSpace(command)) + } + } + + disks := viper.GetString("disks") + for _, diskPath := range strings.Split(disks, ";") { + if strings.TrimSpace(diskPath) != "" { + metrics.addDisk(strings.TrimSpace(diskPath)) + } + } + + paths := viper.GetString("paths") + for _, path := range strings.Split(paths, ";") { + if strings.TrimSpace(path) != "" { + metrics.addPath(strings.TrimSpace(path)) + } + } + + recursively := viper.GetBool("recursively") + metrics.SetRecursively(recursively) + +} + +func (metrics *Metrics) addProcess(command string) { + + pid, err := getPid(command) + if err != nil { + return + } + process := process.Process{Pid: int32(pid)} + cmd, err := process.Cmdline() + if err != nil { + fmt.Println(err.Error()) + return + } + metrics.processes = append(metrics.processes, process) + + metrics.ProcCPUUtilization = append(metrics.ProcCPUUtilization, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: fmt.Sprintf("cpu_percent_%d", pid), + Help: fmt.Sprintf("CPU Utilization Percantage of processes with pid %d, started by command %s", pid, cmd), + }, []string{})) + + metrics.ProcMemoUtilization = append(metrics.ProcMemoUtilization, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: fmt.Sprintf("memo_percent_%d", pid), + Help: fmt.Sprintf("Memory Utilization Percantage of processes with pid %d, started by command %s", pid, cmd), + }, []string{})) + + metrics.ProcOpenedFilesNum = append(metrics.ProcOpenedFilesNum, prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{ + Subsystem: "system", + Name: fmt.Sprintf("opened_files_number_%d", pid), + Help: fmt.Sprintf("Number of Opened Files of processes with pid %d, started by command %s", pid, cmd), + }, []string{})) + +} + +func (metrics *Metrics) SetRecursively(recursively bool) { + metrics.recursively = recursively +} + +func (metrics *Metrics) Start(ctx tools.Context) { + metrics.add() + go func() { + for { + time.Sleep(1 * time.Second) + metrics.RecordMetrics() + } + }() +} + +func (metrics Metrics) RecordMetrics() { + + for i, process := range metrics.processes { + if cpuUtil, err := process.CPUPercent(); err != nil { + metrics.ProcCPUUtilization[i].Set(float64(-1)) + } else { + metrics.ProcCPUUtilization[i].Set(cpuUtil) + } + + if memoUtil, err := process.MemoryPercent(); err != nil { + metrics.ProcMemoUtilization[i].Set(float64(-1)) + } else { + metrics.ProcMemoUtilization[i].Set(float64(memoUtil)) + } + + if files, err := process.OpenFiles(); err != nil { + metrics.ProcOpenedFilesNum[i].Set(float64(-1)) + } else { + metrics.ProcOpenedFilesNum[i].Set(float64(len(files))) + } + } + + for i, diskPath := range metrics.disks { + if usage, err := disk.Usage(diskPath); err != nil { + metrics.DirectorySize[i].Set(float64(-1)) + metrics.DiskFreeSpace[i].Set(float64(-1)) + } else { + metrics.DirectorySize[i].Set(usage.UsedPercent) + metrics.DiskFreeSpace[i].Set(float64(usage.Free)) + } + } + + for i, filePath := range metrics.filePaths { + if fileInfo, err := os.Stat(filePath); err != nil { + metrics.FileSize[i].Set(float64(-1)) + } else { + metrics.FileSize[i].Set(float64(fileInfo.Size())) + } + } + + for i, dirPath := range metrics.dirPaths { + if size, err := getDirSize(dirPath, metrics.recursively); err != nil { + metrics.DirectorySize[i].Set(float64(-1)) + } else { + metrics.DirectorySize[i].Set(float64(size)) + } + } + + vMemoStat, _ := mem.VirtualMemory() + metrics.MemoUtilization.Set(vMemoStat.UsedPercent) + + CPUUsedPercent := float64(0.0) + percents, _ := cpu.Percent(time.Millisecond*100, false) + for _, percent := range percents { + CPUUsedPercent += percent + } + metrics.CPUUtilization.Set(CPUUsedPercent / float64(len(percents))) +} + +//-----------------help functions------------------------------- + +//get the pid of process that start by the given command +//the first pid return by "ps -aux|grep ", +// the process whose command contains "grep" is omitted +func getPid(command string) (pid int, err error) { + commandStr := fmt.Sprintf("ps -aux|grep '%s'", command) + cmd := exec.Command("/bin/bash", "-c", commandStr) + + stdout, err := cmd.StdoutPipe() + + if err != nil { + fmt.Printf("Error:can not obtain stdout pipe for command:%s\n", err) + return 0, err + } + + if err := cmd.Start(); err != nil { + fmt.Println("Error:Invalid command,", err) + return 0, err + } + + bytes, err := ioutil.ReadAll(stdout) + if err != nil { + fmt.Println("ReadAll Stdout:", err.Error()) + return 0, err + } + for _, item := range strings.Split(string(bytes), "\n") { + if !strings.Contains(item, "grep") { + for j, s := range strings.Split(item, " ") { + if j > 0 && s != "" { + pid, err = strconv.Atoi(s) + if err == nil { + return pid, nil + } else { + return 0, err + } + } + } + } + } + return 0, errors.New("cannot find the process") +} + +//get directory size of given path +func getDirSize(path string, recursively bool) (int64, error) { + Separator := string(os.PathSeparator) + queue := list.New() + queue.PushBack(path) + size := int64(0) + for queue.Len() > 0 { + path := fmt.Sprint(queue.Front().Value) + queue.Remove(queue.Front()) + + files, err := ioutil.ReadDir(path) + if err != nil { + return 0, err + } + for _, file := range files { + file_size := file.Size() + size += file_size + if file.IsDir() && recursively { + queue.PushBack(path + Separator + file.Name()) + } + } + } + return size, nil +} + +//conver a path to a valid Gauge monitor term name +func getPathName(path string) string { + var buffer bytes.Buffer + + for i, ch := range path { + if i == 0 && unicode.IsDigit(ch) { + buffer.WriteString("_") + } + if unicode.IsDigit(ch) || unicode.IsLetter(ch) { + buffer.WriteByte(byte(ch)) + } else { + buffer.WriteByte(byte('_')) + } + } + return buffer.String() +} diff --git a/version/version.go b/version/version.go index 720c65e4b..885bbb7fa 100644 --- a/version/version.go +++ b/version/version.go @@ -4,10 +4,11 @@ import ( "fmt" "github.com/spf13/cobra" + "net/http" ) // Version - Iris Version -const Version = "0.1.0" +const Version = "0.2.0" // VersionCmd - The version of gaia var VersionCmd = &cobra.Command{ @@ -17,3 +18,8 @@ var VersionCmd = &cobra.Command{ fmt.Printf("v%s\n", Version) }, } + +// version REST handler endpoint +func RequestHandler(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(Version)) +} From c6b3d5f24b0046d65463e28bef5c4d698d832d0b Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Wed, 18 Jul 2018 21:47:10 +0800 Subject: [PATCH 070/124] update testnets/develop/README.md --- testnets/develop/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/testnets/develop/README.md b/testnets/develop/README.md index 98725486f..4facab99b 100644 --- a/testnets/develop/README.md +++ b/testnets/develop/README.md @@ -1,5 +1,5 @@ ### Running in command line -这个命令会在宿主机后台启动一个iris进程,启动前需要确认宿主机已安装iris、iriscli,并确认`46656`和`46657`端口没有被占用, +这个命令会在宿主机后台启动一个iris进程,启动前需要确认宿主机已安装iris、iriscli,并确认`26656`和`26657`端口没有被占用, 命令会删除$HOME/.iris*目录,请注意做好备份 ``` nohup sh start.sh > iris.log 2>&1 & @@ -14,7 +14,7 @@ iriscli keys list ``` ### Running in docker -这个命令会启动一个基于最新develop分支构建的镜像的docker容器,启动前需要确认`46656`和`46657`端口没有被占用 +这个命令会启动一个基于最新develop分支构建的镜像的docker容器,启动前需要确认`26656`和`26657`端口没有被占用 ``` sh start-docker.sh ``` From c0d9522dba2d0f9a196c09b4e52abae89c05b4ca Mon Sep 17 00:00:00 2001 From: Raymond Date: Tue, 28 Aug 2018 13:25:18 +0800 Subject: [PATCH 071/124] update Gopkg.lock --- Gopkg.lock | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index aca672c2e..76c42d6bf 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -35,7 +35,7 @@ branch = "master" name = "github.com/btcsuite/btcd" packages = ["btcec"] - revision = "d81d8877b8f327112e94e814937143a71d1692a7" + revision = "79e00513b1011888b1e675157ab89f527f901cae" [[projects]] name = "github.com/btcsuite/btcutil" @@ -141,8 +141,8 @@ [[projects]] name = "github.com/go-stack/stack" packages = ["."] - revision = "259ab82a6cad3992b4e21ff5cac294ccb06474bc" - version = "v1.7.0" + revision = "2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a" + version = "v1.8.0" [[projects]] name = "github.com/gogo/protobuf" @@ -194,7 +194,6 @@ version = "v1.2.0" [[projects]] - branch = "master" name = "github.com/hashicorp/hcl" packages = [ ".", @@ -208,7 +207,8 @@ "json/scanner", "json/token" ] - revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" + revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241" + version = "v1.0.0" [[projects]] name = "github.com/inconshreveable/mousetrap" @@ -529,7 +529,7 @@ "unix", "windows" ] - revision = "11551d06cbcc94edc80a0facaccbda56473c19c1" + revision = "4910a1d54f876d7b22162a85f4d066d3ee649450" [[projects]] name = "golang.org/x/text" From cbd78170f32ed1b6f9b2881d98306881c64ff520 Mon Sep 17 00:00:00 2001 From: Raymond Date: Fri, 31 Aug 2018 10:55:47 +0800 Subject: [PATCH 072/124] IRISHUB-248: update the sdk deps to v0.23.0-iris2 --- Gopkg.lock | 14 +++++++------- Gopkg.toml | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index 76c42d6bf..ddda939e7 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -88,9 +88,9 @@ "x/stake/tags", "x/stake/types" ] - revision = "c69a00d827e16cf91b35ac533cadfff7ee454519" + revision = "bd1cb52b2d2e04230ff43d10514b5e988f2038cb" source = "https://github.com/irisnet/cosmos-sdk.git" - version = "v0.23.0-iris1" + version = "v0.23.0-iris2" [[projects]] name = "github.com/davecgh/go-spew" @@ -237,8 +237,8 @@ [[projects]] name = "github.com/mattn/go-isatty" packages = ["."] - revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" - version = "v0.0.3" + revision = "6ca4dbf54d38eea1a992b3c722a76a5d1c4cb25c" + version = "v0.0.4" [[projects]] name = "github.com/matttproud/golang_protobuf_extensions" @@ -506,7 +506,7 @@ "ripemd160", "salsa20/salsa" ] - revision = "614d502a4dac94afa3a6ce146bd1736da82514c6" + revision = "182538f80094b6a8efaade63a8fd8e0d9d5843dd" [[projects]] name = "golang.org/x/net" @@ -529,7 +529,7 @@ "unix", "windows" ] - revision = "4910a1d54f876d7b22162a85f4d066d3ee649450" + revision = "49385e6e15226593f68b26af201feec29d5bba22" [[projects]] name = "golang.org/x/text" @@ -599,6 +599,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "44386e4006f0acb8e013d69639b86f5d8c6440153a5069dbccc833739bc048e9" + inputs-digest = "eae5b968041df919006f5d21e35b282a5b20e164c2c974957b2e0d816693b6f5" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index 4ecc85193..205d71fa6 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -29,7 +29,7 @@ [[constraint]] name = "github.com/cosmos/cosmos-sdk" source = "https://github.com/irisnet/cosmos-sdk.git" - version = "=v0.23.0-iris1" + version = "=v0.23.0-iris2" [[override]] name = "github.com/golang/protobuf" From 2009e591ba8f0ac2b84273d8bd7026969d6a7c0b Mon Sep 17 00:00:00 2001 From: Raymond Date: Fri, 31 Aug 2018 11:14:40 +0800 Subject: [PATCH 073/124] IRISHUB-248: remove the upgrade related functions --- app/app.go | 189 +++++++++++++++++++++----------------------- cmd/iris/main.go | 2 +- cmd/iriscli/main.go | 36 ++++----- version/version.go | 82 +++++++++---------- 4 files changed, 151 insertions(+), 158 deletions(-) diff --git a/app/app.go b/app/app.go index 2d17754ba..ece86b96a 100644 --- a/app/app.go +++ b/app/app.go @@ -23,19 +23,11 @@ import ( "github.com/cosmos/cosmos-sdk/x/stake" "github.com/irisnet/irishub/modules/upgrade" - "errors" - "fmt" - "github.com/cosmos/cosmos-sdk/server" - "github.com/spf13/viper" - tmcli "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/node" - sm "github.com/tendermint/tendermint/state" - "strings" ) const ( appName = "IrisApp" - FlagReplay = "replay" + //FlagReplay = "replay" ) // default home directories for expected binaries @@ -58,7 +50,7 @@ type IrisApp struct { keyGov *sdk.KVStoreKey keyFeeCollection *sdk.KVStoreKey keyParams *sdk.KVStoreKey - keyUpgrade *sdk.KVStoreKey + //keyUpgrade *sdk.KVStoreKey // Manage getting and setting accounts accountMapper auth.AccountMapper @@ -69,7 +61,7 @@ type IrisApp struct { slashingKeeper slashing.Keeper govKeeper gov.Keeper paramsKeeper params.Keeper - upgradeKeeper upgrade.Keeper + //upgradeKeeper upgrade.Keeper } func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptions ...func(*bam.BaseApp)) *IrisApp { @@ -90,13 +82,13 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio keyGov: sdk.NewKVStoreKey("gov"), keyFeeCollection: sdk.NewKVStoreKey("fee"), keyParams: sdk.NewKVStoreKey("params"), - keyUpgrade: sdk.NewKVStoreKey("upgrade"), + //keyUpgrade: sdk.NewKVStoreKey("upgrade"), } - var lastHeight int64 - if viper.GetBool(FlagReplay) { - lastHeight = app.replay() - } + //var lastHeight int64 + //if viper.GetBool(FlagReplay) { + // lastHeight = app.replay() + //} // define the accountMapper app.accountMapper = auth.NewAccountMapper( @@ -112,7 +104,7 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.RegisterCodespace(slashing.DefaultCodespace)) app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection, app.paramsKeeper.Getter()) - app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper, app.paramsKeeper.Setter()) + //app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper, app.paramsKeeper.Setter()) app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) //app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) @@ -123,8 +115,8 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). AddRoute("stake", []*sdk.KVStoreKey{app.keyStake, app.keyAccount}, stake.NewHandler(app.stakeKeeper)). AddRoute("slashing", []*sdk.KVStoreKey{app.keySlashing, app.keyStake}, slashing.NewHandler(app.slashingKeeper)). - AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake, app.keyParams}, gov.NewHandler(app.govKeeper)). - AddRoute("upgrade", []*sdk.KVStoreKey{app.keyUpgrade, app.keyStake}, upgrade.NewHandler(app.upgradeKeeper)) + AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake, app.keyParams}, gov.NewHandler(app.govKeeper)) + //AddRoute("upgrade", []*sdk.KVStoreKey{app.keyUpgrade, app.keyStake}, upgrade.NewHandler(app.upgradeKeeper)) // initialize BaseApp app.SetInitChainer(app.initChainer) @@ -132,19 +124,20 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio app.SetEndBlocker(app.EndBlocker) app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) app.SetFeeRefundHandler(auth.NewFeeRefundHandler(app.accountMapper, app.feeCollectionKeeper)) - app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing, app.keyGov, app.keyFeeCollection, app.keyParams, app.keyUpgrade) - app.SetRunMsg(app.runMsgs) + app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing, app.keyGov, app.keyFeeCollection, app.keyParams/*, app.keyUpgrade*/) + //app.SetRunMsg(app.runMsgs) var err error - if viper.GetBool(FlagReplay) { - err = app.LoadVersion(lastHeight, app.keyMain) - } else { - err = app.LoadLatestVersion(app.keyMain) - } + //if viper.GetBool(FlagReplay) { + // err = app.LoadVersion(lastHeight, app.keyMain) + //} else { + // err = app.LoadLatestVersion(app.keyMain) + //} + err = app.LoadLatestVersion(app.keyMain) if err != nil { cmn.Exit(err.Error()) } - upgrade.RegisterModuleList(app.Router()) + //upgrade.RegisterModuleList(app.Router()) return app } @@ -178,7 +171,7 @@ func (app *IrisApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.R validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) tags, _ := gov.EndBlocker(ctx, app.govKeeper) - tags.AppendTags(upgrade.EndBlocker(ctx, app.upgradeKeeper)) + //tags.AppendTags(upgrade.EndBlocker(ctx, app.upgradeKeeper)) return abci.ResponseEndBlock{ ValidatorUpdates: validatorUpdates, @@ -233,7 +226,7 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci auth.InitGenesis(ctx, app.paramsKeeper.Setter(), feeTokenGensisConfig) - upgrade.InitGenesis(ctx, app.upgradeKeeper, app.Router()) + //upgrade.InitGenesis(ctx, app.upgradeKeeper, app.Router()) return abci.ResponseInitChain{} } @@ -263,72 +256,72 @@ func (app *IrisApp) ExportAppStateAndValidators() (appState json.RawMessage, val return appState, validators, nil } -// Iterates through msgs and executes them -func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) { - // accumulate results - logs := make([]string, 0, len(msgs)) - var data []byte // NOTE: we just append them all (?!) - var tags sdk.Tags // also just append them all - var code sdk.ABCICodeType - for msgIdx, msg := range msgs { - // Match route. - msgType, err := app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) - if err != nil { - return err.Result() - } - - handler := app.Router().Route(msgType) - if handler == nil { - return sdk.ErrUnknownRequest("Unrecognized Msg type: " + msgType).Result() - } - - msgResult := handler(ctx, msg) - - // NOTE: GasWanted is determined by ante handler and - // GasUsed by the GasMeter - - // Append Data and Tags - data = append(data, msgResult.Data...) - tags = append(tags, msgResult.Tags...) - - // Stop execution and return on first failed message. - if !msgResult.IsOK() { - logs = append(logs, fmt.Sprintf("Msg %d failed: %s", msgIdx, msgResult.Log)) - code = msgResult.Code - break - } - - // Construct usable logs in multi-message transactions. - logs = append(logs, fmt.Sprintf("Msg %d: %s", msgIdx, msgResult.Log)) - } - - // Set the final gas values. - result = sdk.Result{ - Code: code, - Data: data, - Log: strings.Join(logs, "\n"), - GasUsed: ctx.GasMeter().GasConsumed(), - // TODO: FeeAmount/FeeDenom - Tags: tags, - } - - return result -} - -func (app *IrisApp) replay() int64 { - ctx := server.NewDefaultContext() - ctx.Config.RootDir = viper.GetString(tmcli.HomeFlag) - dbContext := node.DBContext{"state", ctx.Config} - dbType := dbm.DBBackendType(dbContext.Config.DBBackend) - stateDB := dbm.NewDB(dbContext.ID, dbType, dbContext.Config.DBDir()) - - preState := sm.LoadPreState(stateDB) - if preState.LastBlockHeight == 0 { - panic(errors.New("can't replay the last block, last block height is 0")) - } - - sm.SaveState(stateDB, preState) - stateDB.Close() - - return preState.LastBlockHeight -} +//// Iterates through msgs and executes them +//func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) { +// // accumulate results +// logs := make([]string, 0, len(msgs)) +// var data []byte // NOTE: we just append them all (?!) +// var tags sdk.Tags // also just append them all +// var code sdk.ABCICodeType +// for msgIdx, msg := range msgs { +// // Match route. +// msgType, err := app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) +// if err != nil { +// return err.Result() +// } +// +// handler := app.Router().Route(msgType) +// if handler == nil { +// return sdk.ErrUnknownRequest("Unrecognized Msg type: " + msgType).Result() +// } +// +// msgResult := handler(ctx, msg) +// +// // NOTE: GasWanted is determined by ante handler and +// // GasUsed by the GasMeter +// +// // Append Data and Tags +// data = append(data, msgResult.Data...) +// tags = append(tags, msgResult.Tags...) +// +// // Stop execution and return on first failed message. +// if !msgResult.IsOK() { +// logs = append(logs, fmt.Sprintf("Msg %d failed: %s", msgIdx, msgResult.Log)) +// code = msgResult.Code +// break +// } +// +// // Construct usable logs in multi-message transactions. +// logs = append(logs, fmt.Sprintf("Msg %d: %s", msgIdx, msgResult.Log)) +// } +// +// // Set the final gas values. +// result = sdk.Result{ +// Code: code, +// Data: data, +// Log: strings.Join(logs, "\n"), +// GasUsed: ctx.GasMeter().GasConsumed(), +// // TODO: FeeAmount/FeeDenom +// Tags: tags, +// } +// +// return result +//} +// +//func (app *IrisApp) replay() int64 { +// ctx := server.NewDefaultContext() +// ctx.Config.RootDir = viper.GetString(tmcli.HomeFlag) +// dbContext := node.DBContext{"state", ctx.Config} +// dbType := dbm.DBBackendType(dbContext.Config.DBBackend) +// stateDB := dbm.NewDB(dbContext.ID, dbType, dbContext.Config.DBDir()) +// +// preState := sm.LoadPreState(stateDB) +// if preState.LastBlockHeight == 0 { +// panic(errors.New("can't replay the last block, last block height is 0")) +// } +// +// sm.SaveState(stateDB, preState) +// stateDB.Close() +// +// return preState.LastBlockHeight +//} diff --git a/cmd/iris/main.go b/cmd/iris/main.go index 887edfa7a..d392cf5c8 100644 --- a/cmd/iris/main.go +++ b/cmd/iris/main.go @@ -44,7 +44,7 @@ func main() { ) startCmd := server.StartCmd(ctx, server.ConstructAppCreator(newApp, "iris")) - startCmd.Flags().Bool(app.FlagReplay, false, "Replay the last block") + //startCmd.Flags().Bool(app.FlagReplay, false, "Replay the last block") rootCmd.AddCommand( server.InitCmd(ctx, cdc, app.IrisAppInit()), startCmd, diff --git a/cmd/iriscli/main.go b/cmd/iriscli/main.go index 13d5eed86..9a52dc393 100644 --- a/cmd/iriscli/main.go +++ b/cmd/iriscli/main.go @@ -18,7 +18,7 @@ import ( c "github.com/irisnet/irishub/client" govcmd "github.com/cosmos/cosmos-sdk/x/gov/client/cli" paramcmd "github.com/cosmos/cosmos-sdk/x/params/client/cli" - upgradecmd "github.com/irisnet/irishub/modules/upgrade/client/cli" + //upgradecmd "github.com/irisnet/irishub/modules/upgrade/client/cli" "github.com/irisnet/irishub/version" ) @@ -124,23 +124,23 @@ func main() { govCmd, ) - //Add upgrade commands - upgradeCmd := &cobra.Command{ - Use: "upgrade", - Short: "Software Upgrade subcommands", - } - upgradeCmd.AddCommand( - client.GetCommands( - upgradecmd.GetCmdQuerySwitch("upgrade", cdc), - upgradecmd.GetCmdInfo("upgrade", cdc), - )...) - upgradeCmd.AddCommand( - client.PostCommands( - upgradecmd.GetCmdSubmitSwitch(cdc), - )...) - rootCmd.AddCommand( - upgradeCmd, - ) + ////Add upgrade commands + //upgradeCmd := &cobra.Command{ + // Use: "upgrade", + // Short: "Software Upgrade subcommands", + //} + //upgradeCmd.AddCommand( + // client.GetCommands( + // upgradecmd.GetCmdQuerySwitch("upgrade", cdc), + // upgradecmd.GetCmdInfo("upgrade", cdc), + // )...) + //upgradeCmd.AddCommand( + // client.PostCommands( + // upgradecmd.GetCmdSubmitSwitch(cdc), + // )...) + //rootCmd.AddCommand( + // upgradeCmd, + //) //Add auth and bank commands rootCmd.AddCommand( diff --git a/version/version.go b/version/version.go index eaace5226..837e48a61 100644 --- a/version/version.go +++ b/version/version.go @@ -6,7 +6,7 @@ import ( "encoding/json" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/wire" - "github.com/irisnet/irishub/modules/upgrade" + //"github.com/irisnet/irishub/modules/upgrade" "github.com/spf13/cobra" "net/http" ) @@ -22,28 +22,28 @@ func GetCmdVersion(storeName string, cdc *wire.Codec) *cobra.Command { fmt.Printf("v%s\n", Version) - ctx := context.NewCoreContextFromViper() - - var res_versionID []byte - var err error - res_versionID, err = ctx.QueryStore(upgrade.GetCurrentVersionKey(), storeName) - if err!=nil{ - return nil - } - var versionID int64 - cdc.MustUnmarshalBinary(res_versionID, &versionID) - - var res_version []byte - res_version, err = ctx.QueryStore(upgrade.GetVersionIDKey(versionID), storeName) - if err!=nil{ - return nil - } - var version upgrade.Version - cdc.MustUnmarshalBinary(res_version, &version) - - fmt.Println(version.Id) - fmt.Println("Current version: Start Height = ", version.Start) - fmt.Println("Current version: Proposal Id = ", version.ProposalID) + //ctx := context.NewCoreContextFromViper() + // + //var res_versionID []byte + //var err error + //res_versionID, err = ctx.QueryStore(upgrade.GetCurrentVersionKey(), storeName) + //if err!=nil{ + // return nil + //} + //var versionID int64 + //cdc.MustUnmarshalBinary(res_versionID, &versionID) + // + //var res_version []byte + //res_version, err = ctx.QueryStore(upgrade.GetVersionIDKey(versionID), storeName) + //if err!=nil{ + // return nil + //} + //var version upgrade.Version + //cdc.MustUnmarshalBinary(res_version, &version) + // + //fmt.Println(version.Id) + //fmt.Println("Current version: Start Height = ", version.Start) + //fmt.Println("Current version: Proposal Id = ", version.ProposalID) return nil }, } @@ -59,24 +59,24 @@ type VersionInfo struct { func VersionHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - ctx := context.NewCoreContextFromViper() - - res_versionID, _ := ctx.QueryStore(upgrade.GetCurrentVersionKey(), "upgrade") - var versionID int64 - cdc.MustUnmarshalBinary(res_versionID, &versionID) - - res_version, _ := ctx.QueryStore(upgrade.GetVersionIDKey(versionID), "upgrade") - var version upgrade.Version - cdc.MustUnmarshalBinary(res_version, &version) - - versionInfo := VersionInfo{ - IrisVersion: Version, - UpgradeVersion: version.Id, - StartHeight: version.Start, - ProposalId: version.ProposalID, - } - - output, err := json.MarshalIndent(versionInfo, "", " ") + //ctx := context.NewCoreContextFromViper() + // + //res_versionID, _ := ctx.QueryStore(upgrade.GetCurrentVersionKey(), "upgrade") + //var versionID int64 + //cdc.MustUnmarshalBinary(res_versionID, &versionID) + // + //res_version, _ := ctx.QueryStore(upgrade.GetVersionIDKey(versionID), "upgrade") + //var version upgrade.Version + //cdc.MustUnmarshalBinary(res_version, &version) + // + //versionInfo := VersionInfo{ + // IrisVersion: Version, + // UpgradeVersion: version.Id, + // StartHeight: version.Start, + // ProposalId: version.ProposalID, + //} + + output, err := json.MarshalIndent(Version, "", " ") if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) From b8c13720213188ba3c2a520097fe5bd71a579f0d Mon Sep 17 00:00:00 2001 From: Raymond Date: Fri, 31 Aug 2018 11:18:03 +0800 Subject: [PATCH 074/124] IRISHUB-248: remove the upgrade examples --- examples/irishub-bugfix-2/app/app.go | 342 ----------------- examples/irishub-bugfix-2/app/context.go | 96 ----- examples/irishub-bugfix-2/app/genesis.go | 246 ------------- .../cmd/iris-bugfix-2/main.go | 76 ---- .../cmd/iriscli-bugfix-2/main.go | 173 --------- .../irishub-bugfix-2/ibc/client/cli/README.md | 157 -------- .../irishub-bugfix-2/ibc/client/cli/ibctx.go | 81 ---- .../irishub-bugfix-2/ibc/client/cli/relay.go | 200 ---------- .../irishub-bugfix-2/ibc/client/cli/tx.go | 66 ---- .../ibc/client/rest/transfer.go | 103 ------ examples/irishub-bugfix-2/ibc/errors.go | 50 --- examples/irishub-bugfix-2/ibc/handler.go | 84 ----- examples/irishub-bugfix-2/ibc/mapper.go | 149 -------- examples/irishub-bugfix-2/ibc/types.go | 184 ---------- examples/irishub-bugfix-2/ibc/wire.go | 13 - examples/irishub1/app/app.go | 341 ----------------- examples/irishub1/app/context.go | 96 ----- examples/irishub1/app/genesis.go | 246 ------------- examples/irishub1/cmd/iris1/main.go | 76 ---- examples/irishub1/cmd/iriscli1/main.go | 173 --------- examples/irishub1/ibc/client/cli/README.md | 157 -------- examples/irishub1/ibc/client/cli/ibctx.go | 81 ---- examples/irishub1/ibc/client/cli/relay.go | 200 ---------- examples/irishub1/ibc/client/cli/tx.go | 66 ---- examples/irishub1/ibc/client/rest/transfer.go | 103 ------ examples/irishub1/ibc/errors.go | 50 --- examples/irishub1/ibc/handler.go | 76 ---- examples/irishub1/ibc/mapper.go | 148 -------- examples/irishub1/ibc/types.go | 184 ---------- examples/irishub1/ibc/wire.go | 13 - examples/irishub2/app/app.go | 347 ------------------ examples/irishub2/app/context.go | 96 ----- examples/irishub2/app/genesis.go | 246 ------------- examples/irishub2/cmd/iris2/main.go | 76 ---- examples/irishub2/cmd/iriscli2/main.go | 173 --------- examples/irishub2/ibc/client/cli/README.md | 157 -------- examples/irishub2/ibc/client/cli/ibctx.go | 81 ---- examples/irishub2/ibc/client/cli/relay.go | 200 ---------- examples/irishub2/ibc/client/cli/tx.go | 66 ---- examples/irishub2/ibc/client/rest/transfer.go | 103 ------ examples/irishub2/ibc/errors.go | 50 --- examples/irishub2/ibc/handler.go | 76 ---- examples/irishub2/ibc/mapper.go | 149 -------- examples/irishub2/ibc/types.go | 184 ---------- examples/irishub2/ibc/wire.go | 13 - 45 files changed, 6047 deletions(-) delete mode 100644 examples/irishub-bugfix-2/app/app.go delete mode 100644 examples/irishub-bugfix-2/app/context.go delete mode 100644 examples/irishub-bugfix-2/app/genesis.go delete mode 100644 examples/irishub-bugfix-2/cmd/iris-bugfix-2/main.go delete mode 100644 examples/irishub-bugfix-2/cmd/iriscli-bugfix-2/main.go delete mode 100644 examples/irishub-bugfix-2/ibc/client/cli/README.md delete mode 100644 examples/irishub-bugfix-2/ibc/client/cli/ibctx.go delete mode 100644 examples/irishub-bugfix-2/ibc/client/cli/relay.go delete mode 100644 examples/irishub-bugfix-2/ibc/client/cli/tx.go delete mode 100644 examples/irishub-bugfix-2/ibc/client/rest/transfer.go delete mode 100644 examples/irishub-bugfix-2/ibc/errors.go delete mode 100644 examples/irishub-bugfix-2/ibc/handler.go delete mode 100644 examples/irishub-bugfix-2/ibc/mapper.go delete mode 100644 examples/irishub-bugfix-2/ibc/types.go delete mode 100644 examples/irishub-bugfix-2/ibc/wire.go delete mode 100644 examples/irishub1/app/app.go delete mode 100644 examples/irishub1/app/context.go delete mode 100644 examples/irishub1/app/genesis.go delete mode 100644 examples/irishub1/cmd/iris1/main.go delete mode 100644 examples/irishub1/cmd/iriscli1/main.go delete mode 100644 examples/irishub1/ibc/client/cli/README.md delete mode 100644 examples/irishub1/ibc/client/cli/ibctx.go delete mode 100644 examples/irishub1/ibc/client/cli/relay.go delete mode 100644 examples/irishub1/ibc/client/cli/tx.go delete mode 100644 examples/irishub1/ibc/client/rest/transfer.go delete mode 100644 examples/irishub1/ibc/errors.go delete mode 100644 examples/irishub1/ibc/handler.go delete mode 100644 examples/irishub1/ibc/mapper.go delete mode 100644 examples/irishub1/ibc/types.go delete mode 100644 examples/irishub1/ibc/wire.go delete mode 100644 examples/irishub2/app/app.go delete mode 100644 examples/irishub2/app/context.go delete mode 100644 examples/irishub2/app/genesis.go delete mode 100644 examples/irishub2/cmd/iris2/main.go delete mode 100644 examples/irishub2/cmd/iriscli2/main.go delete mode 100644 examples/irishub2/ibc/client/cli/README.md delete mode 100644 examples/irishub2/ibc/client/cli/ibctx.go delete mode 100644 examples/irishub2/ibc/client/cli/relay.go delete mode 100644 examples/irishub2/ibc/client/cli/tx.go delete mode 100644 examples/irishub2/ibc/client/rest/transfer.go delete mode 100644 examples/irishub2/ibc/errors.go delete mode 100644 examples/irishub2/ibc/handler.go delete mode 100644 examples/irishub2/ibc/mapper.go delete mode 100644 examples/irishub2/ibc/types.go delete mode 100644 examples/irishub2/ibc/wire.go diff --git a/examples/irishub-bugfix-2/app/app.go b/examples/irishub-bugfix-2/app/app.go deleted file mode 100644 index f787cb856..000000000 --- a/examples/irishub-bugfix-2/app/app.go +++ /dev/null @@ -1,342 +0,0 @@ -package app - -import ( - "encoding/json" - "io" - "os" - - bam "github.com/cosmos/cosmos-sdk/baseapp" - abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - - 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/bank" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/ibc" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/stake" - ibcbugfix "github.com/irisnet/irishub/examples/irishub-bugfix-2/ibc" - "github.com/irisnet/irishub/modules/upgrade" - - "errors" - "fmt" - "github.com/cosmos/cosmos-sdk/server" - "github.com/spf13/viper" - tmcli "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/node" - sm "github.com/tendermint/tendermint/state" - "strings" -) - -const ( - appName = "IrisApp" - FlagReplay = "replay" -) - -// default home directories for expected binaries -var ( - DefaultCLIHome = os.ExpandEnv("$HOME/.iriscli") - DefaultNodeHome = os.ExpandEnv("$HOME/.iris") -) - -// Extended ABCI application -type IrisApp struct { - *bam.BaseApp - cdc *wire.Codec - - // keys to access the substores - keyMain *sdk.KVStoreKey - keyAccount *sdk.KVStoreKey - keyIBC *sdk.KVStoreKey - keyStake *sdk.KVStoreKey - keySlashing *sdk.KVStoreKey - keyGov *sdk.KVStoreKey - keyFeeCollection *sdk.KVStoreKey - keyParams *sdk.KVStoreKey - keyUpgrade *sdk.KVStoreKey - - // Manage getting and setting accounts - accountMapper auth.AccountMapper - feeCollectionKeeper auth.FeeCollectionKeeper - coinKeeper bank.Keeper - ibcMapper ibc.Mapper - ibc1Mapper ibcbugfix.Mapper - stakeKeeper stake.Keeper - slashingKeeper slashing.Keeper - govKeeper gov.Keeper - paramsKeeper params.Keeper - upgradeKeeper upgrade.Keeper -} - -func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptions ...func(*bam.BaseApp)) *IrisApp { - cdc := MakeCodec() - - bApp := bam.NewBaseApp(appName, cdc, logger, db, baseAppOptions...) - bApp.SetCommitMultiStoreTracer(traceStore) - - // create your application object - var app = &IrisApp{ - BaseApp: bam.NewBaseApp(appName, cdc, logger, db), - cdc: cdc, - keyMain: sdk.NewKVStoreKey("main"), - keyAccount: sdk.NewKVStoreKey("acc"), - keyIBC: sdk.NewKVStoreKey("ibc"), - keyStake: sdk.NewKVStoreKey("stake"), - keySlashing: sdk.NewKVStoreKey("slashing"), - keyGov: sdk.NewKVStoreKey("gov"), - keyFeeCollection: sdk.NewKVStoreKey("fee"), - keyParams: sdk.NewKVStoreKey("params"), - keyUpgrade: sdk.NewKVStoreKey("upgrade"), - } - - var lastHeight int64 - if viper.GetBool(FlagReplay) { - lastHeight = app.replay() - } - - // define the accountMapper - app.accountMapper = auth.NewAccountMapper( - app.cdc, - app.keyAccount, // target store - auth.ProtoBaseAccount, // prototype - ) - - // add handlers - app.paramsKeeper = params.NewKeeper(app.cdc, app.keyParams) - app.coinKeeper = bank.NewKeeper(app.accountMapper) - - app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace)) - app.ibc1Mapper = ibcbugfix.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibcbugfix.DefaultCodespace)) - - app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) - app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.RegisterCodespace(slashing.DefaultCodespace)) - app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection, app.paramsKeeper.Getter()) - app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper, app.paramsKeeper.Setter()) - app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - //app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - - // register message routes - // need to update each module's msg type - app.Router(). - AddRoute("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.coinKeeper)). - AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). - AddRoute("ibc-1", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibcbugfix.NewHandler(app.ibc1Mapper, app.coinKeeper, app.upgradeKeeper)). - AddRoute("stake", []*sdk.KVStoreKey{app.keyStake, app.keyAccount}, stake.NewHandler(app.stakeKeeper)). - AddRoute("slashing", []*sdk.KVStoreKey{app.keySlashing, app.keyStake}, slashing.NewHandler(app.slashingKeeper)). - AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake, app.keyParams}, gov.NewHandler(app.govKeeper)). - AddRoute("upgrade", []*sdk.KVStoreKey{app.keyUpgrade, app.keyStake}, upgrade.NewHandler(app.upgradeKeeper)) - - // initialize BaseApp - app.SetInitChainer(app.initChainer) - app.SetBeginBlocker(app.BeginBlocker) - app.SetEndBlocker(app.EndBlocker) - app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) - app.SetFeeRefundHandler(auth.NewFeeRefundHandler(app.accountMapper, app.feeCollectionKeeper)) - app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing, app.keyGov, app.keyFeeCollection, app.keyParams, app.keyUpgrade) - app.SetRunMsg(app.runMsgs) - var err error - if viper.GetBool(FlagReplay) { - err = app.LoadVersion(lastHeight, app.keyMain) - } else { - err = app.LoadLatestVersion(app.keyMain) - } - if err != nil { - cmn.Exit(err.Error()) - } - - upgrade.RegisterModuleList(app.Router()) - - return app -} - -// custom tx codec -func MakeCodec() *wire.Codec { - var cdc = wire.NewCodec() - ibc.RegisterWire(cdc) - ibcbugfix.RegisterWire(cdc) - bank.RegisterWire(cdc) - stake.RegisterWire(cdc) - slashing.RegisterWire(cdc) - gov.RegisterWire(cdc) - auth.RegisterWire(cdc) - upgrade.RegisterWire(cdc) - sdk.RegisterWire(cdc) - wire.RegisterCrypto(cdc) - return cdc -} - -// application updates every end block -func (app *IrisApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) - - return abci.ResponseBeginBlock{ - Tags: tags.ToKVPairs(), - } -} - -// application updates every end block -func (app *IrisApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) - - tags, _ := gov.EndBlocker(ctx, app.govKeeper) - tags.AppendTags(upgrade.EndBlocker(ctx, app.upgradeKeeper)) - - return abci.ResponseEndBlock{ - ValidatorUpdates: validatorUpdates, - Tags: tags, - } -} - -// custom logic for iris initialization -func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { - stateJSON := req.AppStateBytes - - var genesisState GenesisState - err := app.cdc.UnmarshalJSON(stateJSON, &genesisState) - if err != nil { - panic(err) - } - - // load the accounts - for _, gacc := range genesisState.Accounts { - acc := gacc.ToAccount() - acc.AccountNumber = app.accountMapper.GetNextAccountNumber(ctx) - app.accountMapper.SetAccount(ctx, acc) - } - - // load the initial stake information - err = stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData) - if err != nil { - panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 - // return sdk.ErrGenesisParse("").TraceCause(err, "") - } - - gov.InitGenesis(ctx, app.govKeeper, gov.GenesisState{ - StartingProposalID: 1, - DepositProcedure: gov.DepositProcedure{ - MinDeposit: sdk.Coins{sdk.Coin{Denom: "iris", Amount: sdk.NewInt(int64(10)).Mul(gov.Pow10(18))}}, - MaxDepositPeriod: 1440, - }, - VotingProcedure: gov.VotingProcedure{ - VotingPeriod: 30, - }, - TallyingProcedure: gov.TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 100), - }, - }) - - feeTokenGensisConfig := auth.GenesisState{ - FeeTokenNative: "iris", - GasPriceThreshold: 20000000000, // 20(glue), 20*10^9, 1 glue = 10^9 lue/gas, 1 iris = 10^18 lue - } - - auth.InitGenesis(ctx, app.paramsKeeper.Setter(), feeTokenGensisConfig) - - upgrade.InitGenesis(ctx, app.upgradeKeeper, app.Router()) - - return abci.ResponseInitChain{} -} - -// export the state of iris for a genesis file -func (app *IrisApp) ExportAppStateAndValidators() (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) { - ctx := app.NewContext(true, abci.Header{}) - - // iterate to get the accounts - accounts := []GenesisAccount{} - appendAccount := func(acc auth.Account) (stop bool) { - account := NewGenesisAccountI(acc) - accounts = append(accounts, account) - return false - } - app.accountMapper.IterateAccounts(ctx, appendAccount) - - genState := GenesisState{ - Accounts: accounts, - StakeData: stake.WriteGenesis(ctx, app.stakeKeeper), - } - appState, err = wire.MarshalJSONIndent(app.cdc, genState) - if err != nil { - return nil, nil, err - } - validators = stake.WriteValidators(ctx, app.stakeKeeper) - return appState, validators, nil -} - -// Iterates through msgs and executes them -func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) { - // accumulate results - logs := make([]string, 0, len(msgs)) - var data []byte // NOTE: we just append them all (?!) - var tags sdk.Tags // also just append them all - var code sdk.ABCICodeType - for msgIdx, msg := range msgs { - // Match route. - msgType, err := app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) - fmt.Println("============ runMsgs() =========== " + msgType) - if err != nil { - return err.Result() - } - - handler := app.Router().Route(msgType) - if handler == nil { - return sdk.ErrUnknownRequest("Unrecognized Msg type: " + msgType).Result() - } - fmt.Println(msg) - msgResult := handler(ctx, msg) - - // NOTE: GasWanted is determined by ante handler and - // GasUsed by the GasMeter - - // Append Data and Tags - data = append(data, msgResult.Data...) - tags = append(tags, msgResult.Tags...) - - // Stop execution and return on first failed message. - if !msgResult.IsOK() { - logs = append(logs, fmt.Sprintf("Msg %d failed: %s", msgIdx, msgResult.Log)) - code = msgResult.Code - break - } - - // Construct usable logs in multi-message transactions. - logs = append(logs, fmt.Sprintf("Msg %d: %s", msgIdx, msgResult.Log)) - } - - // Set the final gas values. - result = sdk.Result{ - Code: code, - Data: data, - Log: strings.Join(logs, "\n"), - GasUsed: ctx.GasMeter().GasConsumed(), - // TODO: FeeAmount/FeeDenom - Tags: tags, - } - - return result -} - -func (app *IrisApp) replay() int64 { - ctx := server.NewDefaultContext() - ctx.Config.RootDir = viper.GetString(tmcli.HomeFlag) - dbContext := node.DBContext{"state", ctx.Config} - dbType := dbm.DBBackendType(dbContext.Config.DBBackend) - stateDB := dbm.NewDB(dbContext.ID, dbType, dbContext.Config.DBDir()) - - preState := sm.LoadPreState(stateDB) - if preState.LastBlockHeight == 0 { - panic(errors.New("can't replay the last block, last block height is 0")) - } - - sm.SaveState(stateDB, preState) - stateDB.Close() - - return preState.LastBlockHeight -} diff --git a/examples/irishub-bugfix-2/app/context.go b/examples/irishub-bugfix-2/app/context.go deleted file mode 100644 index 6e4b24079..000000000 --- a/examples/irishub-bugfix-2/app/context.go +++ /dev/null @@ -1,96 +0,0 @@ -package app - -import ( - "github.com/cosmos/cosmos-sdk/client/context" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - "fmt" - "io/ioutil" - "strings" - "net/http" - "github.com/cosmos/cosmos-sdk/wire" -) - -type Context struct { - Ctx context.CoreContext - Cdc *wire.Codec -} - - -func NewContext() Context { - return Context{ - Ctx:context.NewCoreContextFromViper(), - } -} - -func (c Context) WithCodeC(cdc *wire.Codec) Context{ - c.Cdc = cdc - return c -} - -func (c Context) BroadcastTxAsync(tx []byte) (*ctypes.ResultBroadcastTx, error) { - return c.Ctx.Client.BroadcastTxAsync(tx) -} - -func (c Context) BroadcastTxSync(tx []byte) (*ctypes.ResultBroadcastTx, error) { - return c.Ctx.Client.BroadcastTxSync(tx) -} - -func (c Context) NetInfo() *ctypes.ResultNetInfo { - client := &http.Client{} - - reqUri := tcpToHttpUrl(c.Ctx.NodeURI) + "/net_info" - - resp, err := client.Get(reqUri) - if err != nil { - fmt.Println(err) - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - fmt.Println(err) - } - - var res = struct { - JsonRpc string `json:"jsonrpc"` - Id string `json:"id"` - Result ctypes.ResultNetInfo `json:"result"` - }{} - if err := c.Cdc.UnmarshalJSON(body,&res); err != nil { - fmt.Println(err) - } - - return &res.Result -} - -func (c Context) NumUnconfirmedTxs() *ctypes.ResultUnconfirmedTxs { - client := &http.Client{} - reqUri := tcpToHttpUrl(c.Ctx.NodeURI) + "/num_unconfirmed_txs" - - resp, err := client.Get(reqUri) - if err != nil { - fmt.Println(err) - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - fmt.Println(err) - } - - var res = struct { - JsonRpc string `json:"jsonrpc"` - Id string `json:"id"` - Result ctypes.ResultUnconfirmedTxs `json:"result"` - }{} - if err := c.Cdc.UnmarshalJSON(body,&res); err != nil { - fmt.Println(err) - } - - return &res.Result -} - -func tcpToHttpUrl(url string) string { - urls := strings.Replace(url, "tcp", "http", 1) - return urls -} diff --git a/examples/irishub-bugfix-2/app/genesis.go b/examples/irishub-bugfix-2/app/genesis.go deleted file mode 100644 index d584c3805..000000000 --- a/examples/irishub-bugfix-2/app/genesis.go +++ /dev/null @@ -1,246 +0,0 @@ -package app - -import ( - "encoding/json" - "errors" - - "github.com/spf13/pflag" - "github.com/tendermint/tendermint/crypto" - tmtypes "github.com/tendermint/tendermint/types" - - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/server/config" - 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" - "math" -) - -// State to Unmarshal -type GenesisState struct { - Accounts []GenesisAccount `json:"accounts"` - StakeData stake.GenesisState `json:"stake"` -} - -// GenesisAccount doesn't need pubkey or sequence -type GenesisAccount struct { - Address sdk.AccAddress `json:"address"` - Coins sdk.Coins `json:"coins"` -} - -func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount { - return GenesisAccount{ - Address: acc.Address, - Coins: acc.Coins, - } -} - -func NewGenesisAccountI(acc auth.Account) GenesisAccount { - return GenesisAccount{ - Address: acc.GetAddress(), - Coins: acc.GetCoins(), - } -} - -// convert GenesisAccount to auth.BaseAccount -func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { - return &auth.BaseAccount{ - Address: ga.Address, - Coins: ga.Coins.Sort(), - } -} - -var ( - flagName = "name" - flagClientHome = "home-client" - flagOWK = "owk" - denom = "iris" - precision = 18 - // bonded tokens given to genesis validators/accounts - freeFermionVal = int64(100) - - totalTokenAmt = sdk.NewInt(200000000) -) - -const defaultUnbondingTime int64 = 60 * 10 - -// get app init parameters for server init command -func IrisAppInit() server.AppInit { - fsAppGenState := pflag.NewFlagSet("", pflag.ContinueOnError) - - fsAppGenTx := pflag.NewFlagSet("", pflag.ContinueOnError) - fsAppGenTx.String(flagName, "", "validator moniker, required") - fsAppGenTx.String(flagClientHome, DefaultCLIHome, - "home directory for the client, used for key generation") - fsAppGenTx.Bool(flagOWK, false, "overwrite the accounts created") - - return server.AppInit{ - FlagsAppGenState: fsAppGenState, - FlagsAppGenTx: fsAppGenTx, - AppGenTx: IrisAppGenTx, - AppGenState: IrisAppGenStateJSON, - } -} - -// simple genesis tx -type IrisGenTx struct { - Name string `json:"name"` - Address sdk.AccAddress `json:"address"` - PubKey string `json:"pub_key"` -} - -// Generate a gaia genesis transaction with flags -func IrisAppGenTx(cdc *wire.Codec, pk crypto.PubKey, genTxConfig config.GenTx) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - - if genTxConfig.Name == "" { - return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)") - } - - var addr sdk.AccAddress - var secret string - addr, secret, err = server.GenerateSaveCoinKey(genTxConfig.CliRoot, genTxConfig.Name, "1234567890", genTxConfig.Overwrite) - if err != nil { - return - } - mm := map[string]string{"secret": secret} - var bz []byte - bz, err = cdc.MarshalJSON(mm) - if err != nil { - return - } - cliPrint = json.RawMessage(bz) - appGenTx, _, validator, err = IrisAppGenTxNF(cdc, pk, addr, genTxConfig.Name) - return -} - -// Generate a gaia genesis transaction without flags -func IrisAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.AccAddress, name string) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - - var bz []byte - gaiaGenTx := IrisGenTx{ - Name: name, - Address: addr, - PubKey: sdk.MustBech32ifyAccPub(pk), - } - bz, err = wire.MarshalJSONIndent(cdc, gaiaGenTx) - if err != nil { - return - } - appGenTx = json.RawMessage(bz) - - validator = tmtypes.GenesisValidator{ - PubKey: pk, - Power: freeFermionVal, - } - return -} - -// Create the core parameters for genesis initialization for gaia -// note that the pubkey input is this machines pubkey -func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState GenesisState, err error) { - - if len(appGenTxs) == 0 { - err = errors.New("must provide at least genesis transaction") - return - } - - // start with the default staking genesis state - //stakeData := stake.DefaultGenesisState() - stakeData := createGenesisState() - - precisionNumber := math.Pow10(int(stakeData.Params.DenomPrecision)) - if precisionNumber > math.MaxInt64 { - panic(errors.New("precision is too high, int64 is overflow")) - } - precisionInt64 := int64(precisionNumber) - tokenPrecision := sdk.NewRat(precisionInt64) - // get genesis flag account information - genaccs := make([]GenesisAccount, len(appGenTxs)) - for i, appGenTx := range appGenTxs { - - var genTx IrisGenTx - err = cdc.UnmarshalJSON(appGenTx, &genTx) - if err != nil { - return - } - - // create the genesis account, give'm few steaks and a buncha token with there name - accAuth := auth.NewBaseAccountWithAddress(genTx.Address) - accAuth.Coins = sdk.Coins{ - {denom, totalTokenAmt.Mul(sdk.NewInt(precisionInt64))}, - } - acc := NewGenesisAccount(&accAuth) - genaccs[i] = acc - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionVal).Mul(tokenPrecision)) // increase the supply - - // add the validator - if len(genTx.Name) > 0 { - desc := stake.NewDescription(genTx.Name, "", "", "") - validator := stake.NewValidator(genTx.Address, - sdk.MustGetAccPubKeyBech32(genTx.PubKey), desc) - - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionVal).Mul(tokenPrecision)) - - // add some new shares to the validator - var issuedDelShares sdk.Rat - validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, sdk.NewInt(freeFermionVal).Mul(sdk.NewInt(precisionInt64))) - validator.TokenPrecision = stakeData.Params.DenomPrecision - stakeData.Validators = append(stakeData.Validators, validator) - - // create the self-delegation from the issuedDelShares - delegation := stake.Delegation{ - DelegatorAddr: validator.Owner, - ValidatorAddr: validator.Owner, - Shares: issuedDelShares, - Height: 0, - } - - stakeData.Bonds = append(stakeData.Bonds, delegation) - } - } - - // create the final app state - genesisState = GenesisState{ - Accounts: genaccs, - StakeData: stakeData, - } - return -} - -// IrisAppGenState but with JSON -func IrisAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) { - - // create the final app state - genesisState, err := IrisAppGenState(cdc, appGenTxs) - if err != nil { - return nil, err - } - appState, err = wire.MarshalJSONIndent(cdc, genesisState) - return -} - -func createGenesisState() stake.GenesisState { - return stake.GenesisState{ - Pool: stake.Pool{ - LooseTokens: sdk.ZeroRat(), - BondedTokens: sdk.ZeroRat(), - InflationLastTime: 0, - Inflation: sdk.NewRat(7, 100), - DateLastCommissionReset: 0, - PrevBondedShares: sdk.ZeroRat(), - }, - Params: stake.Params{ - InflationRateChange: sdk.NewRat(13, 100), - InflationMax: sdk.NewRat(20, 100), - InflationMin: sdk.NewRat(7, 100), - GoalBonded: sdk.NewRat(67, 100), - UnbondingTime: defaultUnbondingTime, - MaxValidators: 100, - BondDenom: denom, - DenomPrecision: int8(precision), - }, - } -} diff --git a/examples/irishub-bugfix-2/cmd/iris-bugfix-2/main.go b/examples/irishub-bugfix-2/cmd/iris-bugfix-2/main.go deleted file mode 100644 index f570756c2..000000000 --- a/examples/irishub-bugfix-2/cmd/iris-bugfix-2/main.go +++ /dev/null @@ -1,76 +0,0 @@ -package main - -import ( - "encoding/json" - "io" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/server" - "github.com/irisnet/irishub/examples/irishub-bugfix-2/app" - bam "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/irisnet/irishub/version" - - "github.com/spf13/viper" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/cli" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - "github.com/irisnet/irishub/tools/prometheus" -) - -func main() { - cdc := app.MakeCodec() - ctx := server.NewDefaultContext() - cobra.EnableCommandSorting = false - rootCmd := &cobra.Command{ - Use: "iris-bugfix-2", - Short: "iris-bugfix-2 Daemon (server)", - PersistentPreRunE: server.PersistentPreRunEFn(ctx), - } - - rootCmd.PersistentFlags().String("log_level", ctx.Config.LogLevel, "Log level") - - tendermintCmd := &cobra.Command{ - Use: "tendermint", - Short: "Tendermint subcommands", - } - - tendermintCmd.AddCommand( - server.ShowNodeIDCmd(ctx), - server.ShowValidatorCmd(ctx), - ) - - startCmd := server.StartCmd(ctx, server.ConstructAppCreator(newApp, "iris")) - startCmd.Flags().Bool(app.FlagReplay, false, "Replay the last block") - rootCmd.AddCommand( - server.InitCmd(ctx, cdc, app.IrisAppInit()), - startCmd, - server.TestnetFilesCmd(ctx, cdc, app.IrisAppInit()), - server.UnsafeResetAllCmd(ctx), - client.LineBreak, - tendermintCmd, - server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), - client.LineBreak, - version.GetCmdVersion("upgrade", cdc), - ) - - rootCmd.AddCommand(prometheus.MonitorCommand(cdc)) - - // prepare and add flags - executor := cli.PrepareBaseCmd(rootCmd, "IRIS", app.DefaultNodeHome) - executor.Execute() -} - -func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) abci.Application { - return app.NewIrisApp(logger, db, traceStore, bam.SetPruning(viper.GetString("pruning"))) -} - -func exportAppStateAndTMValidators( - logger log.Logger, db dbm.DB, traceStore io.Writer, -) (json.RawMessage, []tmtypes.GenesisValidator, error) { - gApp := app.NewIrisApp(logger, db, traceStore) - return gApp.ExportAppStateAndValidators() -} diff --git a/examples/irishub-bugfix-2/cmd/iriscli-bugfix-2/main.go b/examples/irishub-bugfix-2/cmd/iriscli-bugfix-2/main.go deleted file mode 100644 index 02cb3eab2..000000000 --- a/examples/irishub-bugfix-2/cmd/iriscli-bugfix-2/main.go +++ /dev/null @@ -1,173 +0,0 @@ -package main - -import ( - "github.com/spf13/cobra" - - "github.com/tendermint/tendermint/libs/cli" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/client/tx" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - ibccmd "github.com/irisnet/irishub/examples/irishub-bugfix-2/ibc/client/cli" - slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" - stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" - "github.com/irisnet/irishub/examples/irishub-bugfix-2/app" - c "github.com/irisnet/irishub/client" - govcmd "github.com/cosmos/cosmos-sdk/x/gov/client/cli" - upgradecmd "github.com/irisnet/irishub/modules/upgrade/client/cli" - "github.com/irisnet/irishub/version" -) - -// rootCmd is the entry point for this binary -var ( - rootCmd = &cobra.Command{ - Use: "iriscli-bugfix-2", - Short: "irishub2 light-client", - } -) - -func main() { - cobra.EnableCommandSorting = false - cdc := app.MakeCodec() - - // TODO: setup keybase, viper object, etc. to be passed into - // the below functions and eliminate global vars, like we do - // with the cdc - - // add standard rpc commands - rpc.AddCommands(rootCmd) - - //Add state commands - tendermintCmd := &cobra.Command{ - Use: "tendermint", - Short: "Tendermint state querying subcommands", - } - tendermintCmd.AddCommand( - rpc.BlockCommand(), - rpc.ValidatorCommand(), - ) - tx.AddCommands(tendermintCmd, cdc) - - //Add IBC commands - ibcCmd := &cobra.Command{ - Use: "ibc", - Short: "Inter-Blockchain Communication subcommands", - } - ibcCmd.AddCommand( - client.PostCommands( - ibccmd.IBCTransferCmd(cdc), - ibccmd.IBCRelayCmd(cdc), - ibccmd.IBCSetCmd(cdc), - ibccmd.IBCGetCmd(cdc), - )...) - - advancedCmd := &cobra.Command{ - Use: "advanced", - Short: "Advanced subcommands", - } - - advancedCmd.AddCommand( - tendermintCmd, - ibcCmd, - c.ServeCommand(cdc), - ) - rootCmd.AddCommand( - advancedCmd, - client.LineBreak, - ) - - //Add stake commands - stakeCmd := &cobra.Command{ - Use: "stake", - Short: "Stake and validation subcommands", - } - stakeCmd.AddCommand( - client.GetCommands( - stakecmd.GetCmdQueryValidator("stake", cdc), - stakecmd.GetCmdQueryValidators("stake", cdc), - stakecmd.GetCmdQueryDelegation("stake", cdc), - stakecmd.GetCmdQueryDelegations("stake", cdc), - slashingcmd.GetCmdQuerySigningInfo("slashing", cdc), - )...) - stakeCmd.AddCommand( - client.PostCommands( - stakecmd.GetCmdCreateValidator(cdc), - stakecmd.GetCmdEditValidator(cdc), - stakecmd.GetCmdDelegate(cdc), - stakecmd.GetCmdUnbond("stake", cdc), - stakecmd.GetCmdRedelegate("stake", cdc), - slashingcmd.GetCmdUnrevoke(cdc), - )...) - rootCmd.AddCommand( - stakeCmd, - ) - - //Add gov commands - govCmd := &cobra.Command{ - Use: "gov", - Short: "Governance and voting subcommands", - } - govCmd.AddCommand( - client.GetCommands( - govcmd.GetCmdQueryProposal("gov", cdc), - govcmd.GetCmdQueryVote("gov", cdc), - )...) - govCmd.AddCommand( - client.PostCommands( - govcmd.GetCmdSubmitProposal(cdc), - govcmd.GetCmdDeposit(cdc), - govcmd.GetCmdVote(cdc), - )...) - rootCmd.AddCommand( - govCmd, - ) - - //Add upgrade commands - upgradeCmd := &cobra.Command{ - Use: "upgrade", - Short: "Software Upgrade subcommands", - } - upgradeCmd.AddCommand( - client.GetCommands( - upgradecmd.GetCmdQuerySwitch("upgrade", cdc), - upgradecmd.GetCmdInfo("upgrade", cdc), - )...) - upgradeCmd.AddCommand( - client.PostCommands( - upgradecmd.GetCmdSubmitSwitch(cdc), - )...) - rootCmd.AddCommand( - upgradeCmd, - ) - - //Add auth and bank commands - rootCmd.AddCommand( - client.GetCommands( - authcmd.GetAccountCmd("acc", cdc, authcmd.GetAccountDecoder(cdc)), - )...) - rootCmd.AddCommand( - client.PostCommands( - bankcmd.SendTxCmd(cdc), - )...) - - // add proxy, version and key info - rootCmd.AddCommand( - keys.Commands(), - client.LineBreak, - ) - rootCmd.AddCommand( - client.GetCommands( - version.GetCmdVersion("upgrade", cdc), - )...) - - // prepare and add flags - executor := cli.PrepareMainCmd(rootCmd, "GA", app.DefaultCLIHome) - err := executor.Execute() - if err != nil { - // handle with #870 - panic(err) - } -} diff --git a/examples/irishub-bugfix-2/ibc/client/cli/README.md b/examples/irishub-bugfix-2/ibc/client/cli/README.md deleted file mode 100644 index ab9e8e555..000000000 --- a/examples/irishub-bugfix-2/ibc/client/cli/README.md +++ /dev/null @@ -1,157 +0,0 @@ -# IBC Doubble Hubble - -## Remove remaining data - -```console -> rm -r ~/.chain1 -> rm -r ~/.chain2 -> rm -r ~/.basecli -``` - -## Initialize both chains - -```console -> basecoind init --home ~/.chain1 -I[04-02|14:03:33.704] Generated private validator module=main path=/home/mossid/.chain1/config/priv_validator.json -I[04-02|14:03:33.705] Generated genesis file module=main path=/home/mossid/.chain1/config/genesis.json -{ - "secret": "crunch ignore trigger neither differ dance cheap brick situate floor luxury citizen husband decline arrow abandon", - "account": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "validator": { - "pub_key": { - "type": "ed25519", - "data": "8C9917D5E982E221F5A1450103102B44BBFC1E8768126C606246CB37B5794F4D" - }, - "power": 10, - "name": "" - }, - "node_id": "3ac8e6242315fd62143dc3e52c161edaaa6b1a64", - "chain_id": "test-chain-ZajMfr" -} -> ADDR1=C69FEB398A29AAB1B3C4F07DE22208F35E711BCC -> ID1=test-chain-ZajMfr -> NODE1=tcp://0.0.0.0:36657 -> basecli keys add key1 --recover -Enter a passphrase for your key: -Repeat the passphrase: -Enter your recovery seed phrase: -crunch ignore trigger neither differ dance cheap brick situate floor luxury citizen husband decline arrow abandon -key1 C69FEB398A29AAB1B3C4F07DE22208F35E711BCC - - -> basecoind init --home ~/.chain2 -I[04-02|14:09:14.453] Generated private validator module=main path=/home/mossid/.chain2/config/priv_validator.json -I[04-02|14:09:14.453] Generated genesis file module=main path=/home/mossid/.chain2/config/genesis.json -{ - "secret": "age guide awesome month female left oxygen soccer define high grocery work desert dinner arena abandon", - "account": "DC26002735D3AA9573707CFA6D77C12349E49868", - "validator": { - "pub_key": { - "type": "ed25519", - "data": "A94FE4B9AD763D301F4DD5A2766009812495FB7A79F1275FB8A5AF09B44FD5F3" - }, - "power": 10, - "name": "" - }, - "node_id": "ad26831330e1c72b85276d53c20f0680e6fd4cf5" - "chain_id": "test-chain-4XHTPn" -} -> ADDR2=DC26002735D3AA9573707CFA6D77C12349E49868 -> ID2=test-chain-4XHTPn -> NODE2=tcp://0.0.0.0:26657 -> basecli keys add key2 --recover -Enter a passphrase for your key: -Repeat the passphrase: -Enter your recovery seed phrase: -age guide awesome month female left oxygen soccer define high grocery work desert dinner arena abandon -key2 DC26002735D3AA9573707CFA6D77C12349E49868 - - -> basecoind start --home ~/.chain1 --address tcp://0.0.0.0:36658 --rpc.laddr tcp://0.0.0.0:36657 --p2p.laddr tcp://0.0.0.0:36656 -... - -> basecoind start --home ~/.chain2 # --address tcp://0.0.0.0:26658 --rpc.laddr tcp://0.0.0.0:26657 --p2p.laddr tcp://0.0.0.0:26656 -... -``` -## Check balance - -```console -> basecli account $ADDR1 --node $NODE1 -{ - "address": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740992 - } - ], - "public_key": null, - "sequence": 0, - "name": "" -} - -> basecli account $ADDR2 --node $NODE2 -{ - "address": "DC26002735D3AA9573707CFA6D77C12349E49868", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740992 - } - ], - "public_key": null, - "sequence": 0, - "name": "" -} - -``` - -## Transfer coins (addr1:chain1 -> addr2:chain2) - -```console -> basecli transfer --from key1 --to $ADDR2 --amount 10mycoin --chain $ID2 --chain-id $ID1 --node $NODE1 -Password to sign with 'key1': -Committed at block 1022. Hash: E16019DCC4AA08CA70AFCFBC96028ABCC51B6AD0 -> basecli account $ADDR1 --node $NODE1 -{ - "address": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740982 - } - ], - "public_key": { - "type": "ed25519", - "data": "9828FF1780A066A0D93D840737566B697035448D6C880807322BED8919348B2B" - }, - "sequence": 1, - "name": "" -} -``` - -## Relay IBC packets - -```console -> basecli relay --from key2 --from-chain-id $ID1 --from-chain-node $NODE1 --to-chain-id $ID2 --to-chain-node $NODE2 --chain-id $ID2 -Password to sign with 'key2': -I[04-03|16:18:59.984] Detected IBC packet number=0 -I[04-03|16:19:00.869] Relayed IBC packet number=0 -> basecli account $ADDR2 --node $NODE2 -{ - "address": "DC26002735D3AA9573707CFA6D77C12349E49868", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254741002 - } - ], - "public_key": { - "type": "ed25519", - "data": "F52B4FA545F4E9BFE5D7AF1DD2236899FDEF905F9B3057C38D7C01BF1B8EB52E" - }, - "sequence": 1, - "name": "" -} - -``` diff --git a/examples/irishub-bugfix-2/ibc/client/cli/ibctx.go b/examples/irishub-bugfix-2/ibc/client/cli/ibctx.go deleted file mode 100644 index f5505d9a4..000000000 --- a/examples/irishub-bugfix-2/ibc/client/cli/ibctx.go +++ /dev/null @@ -1,81 +0,0 @@ -package cli - -import ( - "encoding/hex" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" - - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - "github.com/cosmos/cosmos-sdk/x/ibc" -) - -const ( - flagTo = "to" - flagAmount = "amount" - flagChain = "chain" -) - -// IBC transfer command -func IBCTransferCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "transfer", - RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) - - // get the from address - from, err := ctx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg, err := buildMsg(from) - if err != nil { - return err - } - - // get password - err = ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, []sdk.Msg{msg}, cdc) - if err != nil { - return err - } - return nil - }, - } - - cmd.Flags().String(flagTo, "", "Address to send coins") - cmd.Flags().String(flagAmount, "", "Amount of coins to send") - cmd.Flags().String(flagChain, "", "Destination chain to send coins") - return cmd -} - -func buildMsg(from sdk.AccAddress) (sdk.Msg, error) { - amount := viper.GetString(flagAmount) - coins, err := sdk.ParseCoins(amount) - if err != nil { - return nil, err - } - - dest := viper.GetString(flagTo) - bz, err := hex.DecodeString(dest) - if err != nil { - return nil, err - } - to := sdk.AccAddress(bz) - - packet := ibc.NewIBCPacket(from, to, coins, viper.GetString(client.FlagChainID), - viper.GetString(flagChain)) - - msg := ibc.IBCTransferMsg{ - IBCPacket: packet, - } - - return msg, nil -} diff --git a/examples/irishub-bugfix-2/ibc/client/cli/relay.go b/examples/irishub-bugfix-2/ibc/client/cli/relay.go deleted file mode 100644 index 58d8f272b..000000000 --- a/examples/irishub-bugfix-2/ibc/client/cli/relay.go +++ /dev/null @@ -1,200 +0,0 @@ -package cli - -import ( - "os" - "time" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/tendermint/tendermint/libs/log" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/auth" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - "github.com/cosmos/cosmos-sdk/x/ibc" -) - -// flags -const ( - FlagFromChainID = "from-chain-id" - FlagFromChainNode = "from-chain-node" - FlagToChainID = "to-chain-id" - FlagToChainNode = "to-chain-node" -) - -type relayCommander struct { - cdc *wire.Codec - address sdk.AccAddress - decoder auth.AccountDecoder - mainStore string - ibcStore string - accStore string - - logger log.Logger -} - -// IBC relay command -func IBCRelayCmd(cdc *wire.Codec) *cobra.Command { - cmdr := relayCommander{ - cdc: cdc, - decoder: authcmd.GetAccountDecoder(cdc), - ibcStore: "ibc", - mainStore: "main", - accStore: "acc", - - logger: log.NewTMLogger(log.NewSyncWriter(os.Stdout)), - } - - cmd := &cobra.Command{ - Use: "relay", - Run: cmdr.runIBCRelay, - } - - cmd.Flags().String(FlagFromChainID, "", "Chain ID for ibc node to check outgoing packets") - cmd.Flags().String(FlagFromChainNode, "tcp://localhost:26657", ": to tendermint rpc interface for this chain") - cmd.Flags().String(FlagToChainID, "", "Chain ID for ibc node to broadcast incoming packets") - cmd.Flags().String(FlagToChainNode, "tcp://localhost:36657", ": to tendermint rpc interface for this chain") - - cmd.MarkFlagRequired(FlagFromChainID) - cmd.MarkFlagRequired(FlagFromChainNode) - cmd.MarkFlagRequired(FlagToChainID) - cmd.MarkFlagRequired(FlagToChainNode) - - viper.BindPFlag(FlagFromChainID, cmd.Flags().Lookup(FlagFromChainID)) - viper.BindPFlag(FlagFromChainNode, cmd.Flags().Lookup(FlagFromChainNode)) - viper.BindPFlag(FlagToChainID, cmd.Flags().Lookup(FlagToChainID)) - viper.BindPFlag(FlagToChainNode, cmd.Flags().Lookup(FlagToChainNode)) - - return cmd -} - -// nolint: unparam -func (c relayCommander) runIBCRelay(cmd *cobra.Command, args []string) { - fromChainID := viper.GetString(FlagFromChainID) - fromChainNode := viper.GetString(FlagFromChainNode) - toChainID := viper.GetString(FlagToChainID) - toChainNode := viper.GetString(FlagToChainNode) - address, err := context.NewCoreContextFromViper().GetFromAddress() - if err != nil { - panic(err) - } - c.address = address - - c.loop(fromChainID, fromChainNode, toChainID, toChainNode) -} - -// This is nolinted as someone is in the process of refactoring this to remove the goto -// nolint: gocyclo -func (c relayCommander) loop(fromChainID, fromChainNode, toChainID, - toChainNode string) { - - ctx := context.NewCoreContextFromViper() - // get password - passphrase, err := ctx.GetPassphraseFromStdin(ctx.FromAddressName) - if err != nil { - panic(err) - } - - ingressKey := ibc.IngressSequenceKey(fromChainID) - -OUTER: - for { - time.Sleep(5 * time.Second) - - processedbz, err := query(toChainNode, ingressKey, c.ibcStore) - if err != nil { - panic(err) - } - - var processed int64 - if processedbz == nil { - processed = 0 - } else if err = c.cdc.UnmarshalBinary(processedbz, &processed); err != nil { - panic(err) - } - - lengthKey := ibc.EgressLengthKey(toChainID) - egressLengthbz, err := query(fromChainNode, lengthKey, c.ibcStore) - if err != nil { - c.logger.Error("error querying outgoing packet list length", "err", err) - continue OUTER //TODO replace with continue (I think it should just to the correct place where OUTER is now) - } - var egressLength int64 - if egressLengthbz == nil { - egressLength = 0 - } else if err = c.cdc.UnmarshalBinary(egressLengthbz, &egressLength); err != nil { - panic(err) - } - if egressLength > processed { - c.logger.Info("Detected IBC packet", "number", egressLength-1) - } - - seq := c.getSequence(toChainNode) - - for i := processed; i < egressLength; i++ { - egressbz, err := query(fromChainNode, ibc.EgressKey(toChainID, i), c.ibcStore) - if err != nil { - c.logger.Error("error querying egress packet", "err", err) - continue OUTER // TODO replace to break, will break first loop then send back to the beginning (aka OUTER) - } - - err = c.broadcastTx(seq, toChainNode, c.refine(egressbz, i, passphrase)) - seq++ - if err != nil { - c.logger.Error("error broadcasting ingress packet", "err", err) - continue OUTER // TODO replace to break, will break first loop then send back to the beginning (aka OUTER) - } - - c.logger.Info("Relayed IBC packet", "number", i) - } - } -} - -func query(node string, key []byte, storeName string) (res []byte, err error) { - return context.NewCoreContextFromViper().WithNodeURI(node).QueryStore(key, storeName) -} - -func (c relayCommander) broadcastTx(seq int64, node string, tx []byte) error { - _, err := context.NewCoreContextFromViper().WithNodeURI(node).WithSequence(seq + 1).BroadcastTx(tx) - return err -} - -func (c relayCommander) getSequence(node string) int64 { - res, err := query(node, c.address, c.accStore) - if err != nil { - panic(err) - } - if nil != res { - account, err := c.decoder(res) - if err != nil { - panic(err) - } - - return account.GetSequence() - } - - return 0 -} - -func (c relayCommander) refine(bz []byte, sequence int64, passphrase string) []byte { - var packet ibc.IBCPacket - if err := c.cdc.UnmarshalBinary(bz, &packet); err != nil { - panic(err) - } - - msg := ibc.IBCReceiveMsg{ - IBCPacket: packet, - Relayer: c.address, - Sequence: sequence, - } - - ctx := context.NewCoreContextFromViper().WithSequence(sequence) - res, err := ctx.SignAndBuild(ctx.FromAddressName, passphrase, []sdk.Msg{msg}, c.cdc) - if err != nil { - panic(err) - } - return res -} diff --git a/examples/irishub-bugfix-2/ibc/client/cli/tx.go b/examples/irishub-bugfix-2/ibc/client/cli/tx.go deleted file mode 100644 index ddc4aa720..000000000 --- a/examples/irishub-bugfix-2/ibc/client/cli/tx.go +++ /dev/null @@ -1,66 +0,0 @@ -package cli - -import ( - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - "github.com/irisnet/irishub/examples/irishub-bugfix-2/ibc" -) - -// IBC transfer command -func IBCGetCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "get", - RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) - - // get the from address - from, err := ctx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg := ibc.NewIBCGetMsg(from) - - // get password - err = ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, []sdk.Msg{msg}, cdc) - if err != nil { - return err - } - return nil - }, - } - return cmd -} - - -// IBC transfer command -func IBCSetCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "set", - RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) - - // get the from address - from, err := ctx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg := ibc.NewIBCSetMsg(from) - - // get password - err = ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, []sdk.Msg{msg}, cdc) - if err != nil { - return err - } - return nil - }, - } - return cmd -} - diff --git a/examples/irishub-bugfix-2/ibc/client/rest/transfer.go b/examples/irishub-bugfix-2/ibc/client/rest/transfer.go deleted file mode 100644 index bee9f955f..000000000 --- a/examples/irishub-bugfix-2/ibc/client/rest/transfer.go +++ /dev/null @@ -1,103 +0,0 @@ -package rest - -import ( - "io/ioutil" - "net/http" - - "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/gorilla/mux" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/ibc" -) - -// RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { - r.HandleFunc("/ibc/{destchain}/{address}/send", TransferRequestHandlerFn(cdc, kb, ctx)).Methods("POST") -} - -type transferBody struct { - // Fees sdk.Coin `json="fees"` - Amount sdk.Coins `json:"amount"` - LocalAccountName string `json:"name"` - Password string `json:"password"` - SrcChainID string `json:"src_chain_id"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` - Gas int64 `json:"gas"` -} - -// TransferRequestHandler - http request handler to transfer coins to a address -// on a different chain via IBC -func TransferRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - // collect data - vars := mux.Vars(r) - destChainID := vars["destchain"] - bech32addr := vars["address"] - - to, err := sdk.AccAddressFromBech32(bech32addr) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - var m transferBody - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - err = cdc.UnmarshalJSON(body, &m) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - info, err := kb.Get(m.LocalAccountName) - if err != nil { - w.WriteHeader(http.StatusUnauthorized) - w.Write([]byte(err.Error())) - return - } - - // build message - packet := ibc.NewIBCPacket(sdk.AccAddress(info.GetPubKey().Address()), to, m.Amount, m.SrcChainID, destChainID) - msg := ibc.IBCTransferMsg{packet} - - // add gas to context - ctx = ctx.WithGas(m.Gas) - - // sign - ctx = ctx.WithAccountNumber(m.AccountNumber) - ctx = ctx.WithSequence(m.Sequence) - 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 - } - - // send - res, err := ctx.BroadcastTx(txBytes) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - output, err := cdc.MarshalJSON(res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - w.Write(output) - } -} diff --git a/examples/irishub-bugfix-2/ibc/errors.go b/examples/irishub-bugfix-2/ibc/errors.go deleted file mode 100644 index 7a3194baf..000000000 --- a/examples/irishub-bugfix-2/ibc/errors.go +++ /dev/null @@ -1,50 +0,0 @@ -package ibc - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// IBC errors reserve 200 ~ 299. -const ( - DefaultCodespace sdk.CodespaceType = 3 - - // IBC errors reserve 200 - 299. - CodeInvalidSequence sdk.CodeType = 200 - CodeIdenticalChains sdk.CodeType = 201 - CodeUnknownRequest sdk.CodeType = sdk.CodeUnknownRequest -) - -func codeToDefaultMsg(code sdk.CodeType) string { - switch code { - case CodeInvalidSequence: - return "invalid IBC packet sequence" - case CodeIdenticalChains: - return "source and destination chain cannot be identical" - default: - return sdk.CodeToDefaultMsg(code) - } -} - -// nolint -func ErrInvalidSequence(codespace sdk.CodespaceType) sdk.Error { - return newError(codespace, CodeInvalidSequence, "") -} -func ErrIdenticalChains(codespace sdk.CodespaceType) sdk.Error { - return newError(codespace, CodeIdenticalChains, "") -} - -// ------------------------- -// Helpers - -// nolint: unparam -func newError(codespace sdk.CodespaceType, code sdk.CodeType, msg string) sdk.Error { - msg = msgOrDefaultMsg(msg, code) - return sdk.NewError(codespace, code, msg) -} - -func msgOrDefaultMsg(msg string, code sdk.CodeType) string { - if msg != "" { - return msg - } - return codeToDefaultMsg(code) -} diff --git a/examples/irishub-bugfix-2/ibc/handler.go b/examples/irishub-bugfix-2/ibc/handler.go deleted file mode 100644 index de1ecfa27..000000000 --- a/examples/irishub-bugfix-2/ibc/handler.go +++ /dev/null @@ -1,84 +0,0 @@ -package ibc - -import ( - "reflect" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/irisnet/irishub/modules/upgrade" -) - -func NewHandler(ibcm Mapper, ck bank.Keeper, uk upgrade.Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { - switch msg := msg.(type) { - case IBCTransferMsg: - return handleIBCTransferMsg(ctx, ibcm, ck, msg) - case IBCReceiveMsg: - return handleIBCReceiveMsg(ctx, ibcm, ck, msg) - case IBCGetMsg: - return handleIBCGetMsg(ctx, ibcm, ck, uk, msg) - case IBCSetMsg: - return handleIBCSetMsg(ctx, ibcm, ck, uk, msg) - default: - errMsg := "Unrecognized IBC Msg type: " + reflect.TypeOf(msg).Name() - return sdk.ErrUnknownRequest(errMsg).Result() - } - } -} - -// IBCTransferMsg deducts coins from the account and creates an egress IBC packet. -func handleIBCTransferMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCTransferMsg) sdk.Result { - packet := msg.IBCPacket - - _, _, err := ck.SubtractCoins(ctx, packet.SrcAddr, packet.Coins) - if err != nil { - return err.Result() - } - - err = ibcm.PostIBCPacket(ctx, packet) - if err != nil { - return err.Result() - } - - return sdk.Result{} -} - -// IBCReceiveMsg adds coins to the destination address and creates an ingress IBC packet. -func handleIBCReceiveMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCReceiveMsg) sdk.Result { - packet := msg.IBCPacket - - seq := ibcm.GetIngressSequence(ctx, packet.SrcChain) - if msg.Sequence != seq { - return ErrInvalidSequence(ibcm.codespace).Result() - } - - _, _, err := ck.AddCoins(ctx, packet.DestAddr, packet.Coins) - if err != nil { - return err.Result() - } - - ibcm.SetIngressSequence(ctx, packet.SrcChain, seq+1) - - return sdk.Result{} -} - -// IBCTransferMsg deducts coins from the account and creates an egress IBC packet. -func handleIBCSetMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, uk upgrade.Keeper, msg IBCSetMsg) sdk.Result { - - if uk.OnlyRunAfterVersionId(ctx, 2) { - ibcm.Set(ctx,msg.Addr.String()+":ibc-2") - return sdk.Result{Log:"This is new module - ibc2 !!"} - } else if uk.OnlyRunAfterVersionId(ctx, 1) { - ibcm.Set(ctx,msg.Addr.String()+":ibc-1") - return sdk.Result{Log:"This is new module - ibc1 !!"} - } else { - ibcm.Set(ctx,msg.Addr.String()+":ibc-0") - return sdk.Result{Log:"This is new module - ibc0 !!"} - } -} - -// IBCReceiveMsg adds coins to the destination address and creates an ingress IBC packet. -func handleIBCGetMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, uk upgrade.Keeper, msg IBCGetMsg) sdk.Result { - AddrString,_:=ibcm.Get(ctx) - return sdk.Result{Log:AddrString} -} diff --git a/examples/irishub-bugfix-2/ibc/mapper.go b/examples/irishub-bugfix-2/ibc/mapper.go deleted file mode 100644 index 2ccc93d1a..000000000 --- a/examples/irishub-bugfix-2/ibc/mapper.go +++ /dev/null @@ -1,149 +0,0 @@ -package ibc - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" -) - -// IBC Mapper -type Mapper struct { - key sdk.StoreKey - cdc *wire.Codec - codespace sdk.CodespaceType -} - -// XXX: The Mapper should not take a CoinKeeper. Rather have the CoinKeeper -// take an Mapper. -func NewMapper(cdc *wire.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) Mapper { - // XXX: How are these codecs supposed to work? - return Mapper{ - key: key, - cdc: cdc, - codespace: codespace, - } -} - -// XXX: This is not the public API. This will change in MVP2 and will henceforth -// only be invoked from another module directly and not through a user -// transaction. -// TODO: Handle invalid IBC packets and return errors. -func (ibcm Mapper) PostIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error { - // write everything into the state - store := ctx.KVStore(ibcm.key) - index := ibcm.getEgressLength(store, packet.DestChain) - bz, err := ibcm.cdc.MarshalBinary(packet) - if err != nil { - panic(err) - } - - store.Set(EgressKey(packet.DestChain, index), bz) - bz, err = ibcm.cdc.MarshalBinary(index + 1) - if err != nil { - panic(err) - } - store.Set(EgressLengthKey(packet.DestChain), bz) - - return nil -} - -// XXX: In the future every module is able to register it's own handler for -// handling it's own IBC packets. The "ibc" handler will only route the packets -// to the appropriate callbacks. -// XXX: For now this handles all interactions with the CoinKeeper. -// XXX: This needs to do some authentication checking. -func (ibcm Mapper) ReceiveIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error { - return nil -} - -// -------------------------- -// Functions for accessing the underlying KVStore. - -func marshalBinaryPanic(cdc *wire.Codec, value interface{}) []byte { - res, err := cdc.MarshalBinary(value) - if err != nil { - panic(err) - } - return res -} - -func unmarshalBinaryPanic(cdc *wire.Codec, bz []byte, ptr interface{}) { - err := cdc.UnmarshalBinary(bz, ptr) - if err != nil { - panic(err) - } -} - -// TODO add description -func (ibcm Mapper) GetIngressSequence(ctx sdk.Context, srcChain string) int64 { - store := ctx.KVStore(ibcm.key) - key := IngressSequenceKey(srcChain) - - bz := store.Get(key) - if bz == nil { - zero := marshalBinaryPanic(ibcm.cdc, int64(0)) - store.Set(key, zero) - return 0 - } - - var res int64 - unmarshalBinaryPanic(ibcm.cdc, bz, &res) - return res -} - -// TODO add description -func (ibcm Mapper) SetIngressSequence(ctx sdk.Context, srcChain string, sequence int64) { - store := ctx.KVStore(ibcm.key) - key := IngressSequenceKey(srcChain) - - bz := marshalBinaryPanic(ibcm.cdc, sequence) - store.Set(key, bz) -} - -// Retrieves the index of the currently stored outgoing IBC packets. -func (ibcm Mapper) getEgressLength(store sdk.KVStore, destChain string) int64 { - bz := store.Get(EgressLengthKey(destChain)) - if bz == nil { - zero := marshalBinaryPanic(ibcm.cdc, int64(0)) - store.Set(EgressLengthKey(destChain), zero) - return 0 - } - var res int64 - unmarshalBinaryPanic(ibcm.cdc, bz, &res) - return res -} - -// Stores an outgoing IBC packet under "egress/chain_id/index". -func EgressKey(destChain string, index int64) []byte { - return []byte(fmt.Sprintf("egress/%s/%d", destChain, index)) -} - -// Stores the number of outgoing IBC packets under "egress/index". -func EgressLengthKey(destChain string) []byte { - return []byte(fmt.Sprintf("egress/%s", destChain)) -} - -// Stores the sequence number of incoming IBC packet under "ingress/index". -func IngressSequenceKey(srcChain string) []byte { - return []byte(fmt.Sprintf("ingress/%s", srcChain)) -} - - -// Gets the vote of a specific voter on a specific proposal -func (ibcm Mapper) Get(ctx sdk.Context) (string, bool) { - store := ctx.KVStore(ibcm.key) - bz := store.Get([]byte("ibcaddr")) - if bz == nil { - return " ", false - } - var Addr string - ibcm.cdc.MustUnmarshalBinary(bz, &Addr) - return Addr, true -} - -func (ibcm Mapper) Set(ctx sdk.Context,Addr string) { - store := ctx.KVStore(ibcm.key) - bz := ibcm.cdc.MustMarshalBinary(Addr) - store.Set([]byte("ibcaddr"), bz) -} \ No newline at end of file diff --git a/examples/irishub-bugfix-2/ibc/types.go b/examples/irishub-bugfix-2/ibc/types.go deleted file mode 100644 index 0537ff816..000000000 --- a/examples/irishub-bugfix-2/ibc/types.go +++ /dev/null @@ -1,184 +0,0 @@ -package ibc - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" -) - -var ( - msgCdc *wire.Codec -) - -func init() { - msgCdc = wire.NewCodec() -} - -// ------------------------------ -// IBCPacket - -// nolint - TODO rename to Packet as IBCPacket stutters (golint) -// IBCPacket defines a piece of data that can be send between two separate -// blockchains. -type IBCPacket struct { - SrcAddr sdk.AccAddress - DestAddr sdk.AccAddress - Coins sdk.Coins - SrcChain string - DestChain string -} - -func NewIBCPacket(srcAddr sdk.AccAddress, destAddr sdk.AccAddress, coins sdk.Coins, - srcChain string, destChain string) IBCPacket { - - return IBCPacket{ - SrcAddr: srcAddr, - DestAddr: destAddr, - Coins: coins, - SrcChain: srcChain, - DestChain: destChain, - } -} - -//nolint -func (p IBCPacket) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(p) - if err != nil { - panic(err) - } - return sdk.MustSortJSON(b) -} - -// validator the ibc packey -func (p IBCPacket) ValidateBasic() sdk.Error { - if p.SrcChain == p.DestChain { - return ErrIdenticalChains(DefaultCodespace).TraceSDK("") - } - if !p.Coins.IsValid() { - return sdk.ErrInvalidCoins("") - } - return nil -} - -// ---------------------------------- -// IBCTransferMsg - -// nolint - TODO rename to TransferMsg as folks will reference with ibc.TransferMsg -// IBCTransferMsg defines how another module can send an IBCPacket. -type IBCTransferMsg struct { - IBCPacket -} - -// nolint -func (msg IBCTransferMsg) Type() string { return "ibc-1" } - -// x/bank/tx.go MsgSend.GetSigners() -func (msg IBCTransferMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.SrcAddr} } - -// get the sign bytes for ibc transfer message -func (msg IBCTransferMsg) GetSignBytes() []byte { - return msg.IBCPacket.GetSignBytes() -} - -// validate ibc transfer message -func (msg IBCTransferMsg) ValidateBasic() sdk.Error { - return msg.IBCPacket.ValidateBasic() -} - -// ---------------------------------- -// IBCReceiveMsg - -// nolint - TODO rename to ReceiveMsg as folks will reference with ibc.ReceiveMsg -// IBCReceiveMsg defines the message that a relayer uses to post an IBCPacket -// to the destination chain. -type IBCReceiveMsg struct { - IBCPacket - Relayer sdk.AccAddress - Sequence int64 -} - -// nolint -func (msg IBCReceiveMsg) Type() string { return "ibc-1" } -func (msg IBCReceiveMsg) ValidateBasic() sdk.Error { return msg.IBCPacket.ValidateBasic() } - -// x/bank/tx.go MsgSend.GetSigners() -func (msg IBCReceiveMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Relayer} } - -// get the sign bytes for ibc receive message -func (msg IBCReceiveMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(struct { - IBCPacket json.RawMessage - Relayer sdk.AccAddress - Sequence int64 - }{ - IBCPacket: json.RawMessage(msg.IBCPacket.GetSignBytes()), - Relayer: msg.Relayer, - Sequence: msg.Sequence, - }) - if err != nil { - panic(err) - } - return sdk.MustSortJSON(b) -} - - -type IBCSetMsg struct { - Addr sdk.AccAddress -} - -func NewIBCSetMsg(addr sdk.AccAddress) IBCSetMsg { - return IBCSetMsg{ - Addr:addr, - } -} - -func (msg IBCSetMsg) Type() string { - return "ibc-1" -} - -func (msg IBCSetMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(msg) - if err != nil { - panic(err) - } - return b -} - -func (msg IBCSetMsg) ValidateBasic() sdk.Error { - return nil -} - -func (msg IBCSetMsg) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Addr} -} - -type IBCGetMsg struct { - Addr sdk.AccAddress -} - -func NewIBCGetMsg(addr sdk.AccAddress) IBCGetMsg { - return IBCGetMsg{ - Addr:addr, - } -} - -func (msg IBCGetMsg) Type() string { - return "ibc-1" -} - -func (msg IBCGetMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(msg) - if err != nil { - panic(err) - } - return b -} - -func (msg IBCGetMsg) ValidateBasic() sdk.Error { - return nil -} - -func (msg IBCGetMsg) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Addr} -} diff --git a/examples/irishub-bugfix-2/ibc/wire.go b/examples/irishub-bugfix-2/ibc/wire.go deleted file mode 100644 index 821a527ab..000000000 --- a/examples/irishub-bugfix-2/ibc/wire.go +++ /dev/null @@ -1,13 +0,0 @@ -package ibc - -import ( - "github.com/cosmos/cosmos-sdk/wire" -) - -// Register concrete types on wire codec -func RegisterWire(cdc *wire.Codec) { - cdc.RegisterConcrete(IBCTransferMsg{}, "cosmos-sdk/IBCTransferMsg/2", nil) - cdc.RegisterConcrete(IBCReceiveMsg{}, "cosmos-sdk/IBCReceiveMsg/2", nil) - cdc.RegisterConcrete(IBCSetMsg{},"cosmos-sdk/IBCSetMsg/2",nil) - cdc.RegisterConcrete(IBCGetMsg{},"cosmos-sdk/IBCGetMsg/2",nil) -} diff --git a/examples/irishub1/app/app.go b/examples/irishub1/app/app.go deleted file mode 100644 index accacdf5e..000000000 --- a/examples/irishub1/app/app.go +++ /dev/null @@ -1,341 +0,0 @@ -package app - -import ( - "encoding/json" - "io" - "os" - - bam "github.com/cosmos/cosmos-sdk/baseapp" - abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - - 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/bank" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/ibc" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/stake" - ibc1 "github.com/irisnet/irishub/examples/irishub1/ibc" - "github.com/irisnet/irishub/modules/upgrade" - - "errors" - "fmt" - "github.com/cosmos/cosmos-sdk/server" - "github.com/spf13/viper" - tmcli "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/node" - sm "github.com/tendermint/tendermint/state" - "strings" -) - -const ( - appName = "IrisApp" - FlagReplay = "replay" -) - -// default home directories for expected binaries -var ( - DefaultCLIHome = os.ExpandEnv("$HOME/.iriscli") - DefaultNodeHome = os.ExpandEnv("$HOME/.iris") -) - -// Extended ABCI application -type IrisApp struct { - *bam.BaseApp - cdc *wire.Codec - - // keys to access the substores - keyMain *sdk.KVStoreKey - keyAccount *sdk.KVStoreKey - keyIBC *sdk.KVStoreKey - keyStake *sdk.KVStoreKey - keySlashing *sdk.KVStoreKey - keyGov *sdk.KVStoreKey - keyFeeCollection *sdk.KVStoreKey - keyParams *sdk.KVStoreKey - keyUpgrade *sdk.KVStoreKey - - // Manage getting and setting accounts - accountMapper auth.AccountMapper - feeCollectionKeeper auth.FeeCollectionKeeper - coinKeeper bank.Keeper - ibcMapper ibc.Mapper - ibc1Mapper ibc1.Mapper - stakeKeeper stake.Keeper - slashingKeeper slashing.Keeper - govKeeper gov.Keeper - paramsKeeper params.Keeper - upgradeKeeper upgrade.Keeper -} - -func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptions ...func(*bam.BaseApp)) *IrisApp { - cdc := MakeCodec() - - bApp := bam.NewBaseApp(appName, cdc, logger, db, baseAppOptions...) - bApp.SetCommitMultiStoreTracer(traceStore) - - // create your application object - var app = &IrisApp{ - BaseApp: bam.NewBaseApp(appName, cdc, logger, db), - cdc: cdc, - keyMain: sdk.NewKVStoreKey("main"), - keyAccount: sdk.NewKVStoreKey("acc"), - keyIBC: sdk.NewKVStoreKey("ibc"), - keyStake: sdk.NewKVStoreKey("stake"), - keySlashing: sdk.NewKVStoreKey("slashing"), - keyGov: sdk.NewKVStoreKey("gov"), - keyFeeCollection: sdk.NewKVStoreKey("fee"), - keyParams: sdk.NewKVStoreKey("params"), - keyUpgrade: sdk.NewKVStoreKey("upgrade"), - } - - var lastHeight int64 - if viper.GetBool(FlagReplay) { - lastHeight = app.replay() - } - - // define the accountMapper - app.accountMapper = auth.NewAccountMapper( - app.cdc, - app.keyAccount, // target store - auth.ProtoBaseAccount, // prototype - ) - - // add handlers - app.paramsKeeper = params.NewKeeper(app.cdc, app.keyParams) - app.coinKeeper = bank.NewKeeper(app.accountMapper) - app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace)) - app.ibc1Mapper = ibc1.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc1.DefaultCodespace)) - app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) - app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.RegisterCodespace(slashing.DefaultCodespace)) - app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection, app.paramsKeeper.Getter()) - app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper, app.paramsKeeper.Setter()) - app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - //app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - - // register message routes - // need to update each module's msg type - app.Router(). - AddRoute("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.coinKeeper)). - AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). - AddRoute("ibc-1", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc1.NewHandler(app.ibc1Mapper, app.coinKeeper)). - AddRoute("stake", []*sdk.KVStoreKey{app.keyStake, app.keyAccount}, stake.NewHandler(app.stakeKeeper)). - AddRoute("slashing", []*sdk.KVStoreKey{app.keySlashing, app.keyStake}, slashing.NewHandler(app.slashingKeeper)). - AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake, app.keyParams}, gov.NewHandler(app.govKeeper)). - AddRoute("upgrade", []*sdk.KVStoreKey{app.keyUpgrade, app.keyStake}, upgrade.NewHandler(app.upgradeKeeper)) - - // initialize BaseApp - app.SetInitChainer(app.initChainer) - app.SetBeginBlocker(app.BeginBlocker) - app.SetEndBlocker(app.EndBlocker) - app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) - app.SetFeeRefundHandler(auth.NewFeeRefundHandler(app.accountMapper, app.feeCollectionKeeper)) - app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing, app.keyGov, app.keyFeeCollection, app.keyParams, app.keyUpgrade) - app.SetRunMsg(app.runMsgs) - var err error - if viper.GetBool(FlagReplay) { - err = app.LoadVersion(lastHeight, app.keyMain) - } else { - err = app.LoadLatestVersion(app.keyMain) - } - if err != nil { - cmn.Exit(err.Error()) - } - - upgrade.RegisterModuleList(app.Router()) - - return app -} - -// custom tx codec -func MakeCodec() *wire.Codec { - var cdc = wire.NewCodec() - ibc.RegisterWire(cdc) - ibc1.RegisterWire(cdc) - - bank.RegisterWire(cdc) - stake.RegisterWire(cdc) - slashing.RegisterWire(cdc) - gov.RegisterWire(cdc) - auth.RegisterWire(cdc) - upgrade.RegisterWire(cdc) - sdk.RegisterWire(cdc) - wire.RegisterCrypto(cdc) - return cdc -} - -// application updates every end block -func (app *IrisApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) - - return abci.ResponseBeginBlock{ - Tags: tags.ToKVPairs(), - } -} - -// application updates every end block -func (app *IrisApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) - - tags, _ := gov.EndBlocker(ctx, app.govKeeper) - tags.AppendTags(upgrade.EndBlocker(ctx, app.upgradeKeeper)) - - return abci.ResponseEndBlock{ - ValidatorUpdates: validatorUpdates, - Tags: tags, - } -} - -// custom logic for iris initialization -func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { - stateJSON := req.AppStateBytes - - var genesisState GenesisState - err := app.cdc.UnmarshalJSON(stateJSON, &genesisState) - if err != nil { - panic(err) - } - - // load the accounts - for _, gacc := range genesisState.Accounts { - acc := gacc.ToAccount() - acc.AccountNumber = app.accountMapper.GetNextAccountNumber(ctx) - app.accountMapper.SetAccount(ctx, acc) - } - - // load the initial stake information - err = stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData) - if err != nil { - panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 - // return sdk.ErrGenesisParse("").TraceCause(err, "") - } - - gov.InitGenesis(ctx, app.govKeeper, gov.GenesisState{ - StartingProposalID: 1, - DepositProcedure: gov.DepositProcedure{ - MinDeposit: sdk.Coins{sdk.Coin{Denom: "iris", Amount: sdk.NewInt(int64(10)).Mul(gov.Pow10(18))}}, - MaxDepositPeriod: 1440, - }, - VotingProcedure: gov.VotingProcedure{ - VotingPeriod: 30, - }, - TallyingProcedure: gov.TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 100), - }, - }) - - feeTokenGensisConfig := auth.GenesisState{ - FeeTokenNative: "iris", - GasPriceThreshold: 20000000000, // 20(glue), 20*10^9, 1 glue = 10^9 lue/gas, 1 iris = 10^18 lue - } - - auth.InitGenesis(ctx, app.paramsKeeper.Setter(), feeTokenGensisConfig) - - upgrade.InitGenesis(ctx, app.upgradeKeeper, app.Router()) - - return abci.ResponseInitChain{} -} - -// export the state of iris for a genesis file -func (app *IrisApp) ExportAppStateAndValidators() (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) { - ctx := app.NewContext(true, abci.Header{}) - - // iterate to get the accounts - accounts := []GenesisAccount{} - appendAccount := func(acc auth.Account) (stop bool) { - account := NewGenesisAccountI(acc) - accounts = append(accounts, account) - return false - } - app.accountMapper.IterateAccounts(ctx, appendAccount) - - genState := GenesisState{ - Accounts: accounts, - StakeData: stake.WriteGenesis(ctx, app.stakeKeeper), - } - appState, err = wire.MarshalJSONIndent(app.cdc, genState) - if err != nil { - return nil, nil, err - } - validators = stake.WriteValidators(ctx, app.stakeKeeper) - return appState, validators, nil -} - -// Iterates through msgs and executes them -func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) { - // accumulate results - logs := make([]string, 0, len(msgs)) - var data []byte // NOTE: we just append them all (?!) - var tags sdk.Tags // also just append them all - var code sdk.ABCICodeType - for msgIdx, msg := range msgs { - // Match route. - msgType, err := app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) - fmt.Println("============ runMsgs() =========== " + msgType) - if err != nil { - return err.Result() - } - - handler := app.Router().Route(msgType) - if handler == nil { - return sdk.ErrUnknownRequest("Unrecognized Msg type: " + msgType).Result() - } - fmt.Println(msg) - msgResult := handler(ctx, msg) - - // NOTE: GasWanted is determined by ante handler and - // GasUsed by the GasMeter - - // Append Data and Tags - data = append(data, msgResult.Data...) - tags = append(tags, msgResult.Tags...) - - // Stop execution and return on first failed message. - if !msgResult.IsOK() { - logs = append(logs, fmt.Sprintf("Msg %d failed: %s", msgIdx, msgResult.Log)) - code = msgResult.Code - break - } - - // Construct usable logs in multi-message transactions. - logs = append(logs, fmt.Sprintf("Msg %d: %s", msgIdx, msgResult.Log)) - } - - // Set the final gas values. - result = sdk.Result{ - Code: code, - Data: data, - Log: strings.Join(logs, "\n"), - GasUsed: ctx.GasMeter().GasConsumed(), - // TODO: FeeAmount/FeeDenom - Tags: tags, - } - - return result -} - -func (app *IrisApp) replay() int64 { - ctx := server.NewDefaultContext() - ctx.Config.RootDir = viper.GetString(tmcli.HomeFlag) - dbContext := node.DBContext{"state", ctx.Config} - dbType := dbm.DBBackendType(dbContext.Config.DBBackend) - stateDB := dbm.NewDB(dbContext.ID, dbType, dbContext.Config.DBDir()) - - preState := sm.LoadPreState(stateDB) - if preState.LastBlockHeight == 0 { - panic(errors.New("can't replay the last block, last block height is 0")) - } - - sm.SaveState(stateDB, preState) - stateDB.Close() - - return preState.LastBlockHeight -} diff --git a/examples/irishub1/app/context.go b/examples/irishub1/app/context.go deleted file mode 100644 index 6e4b24079..000000000 --- a/examples/irishub1/app/context.go +++ /dev/null @@ -1,96 +0,0 @@ -package app - -import ( - "github.com/cosmos/cosmos-sdk/client/context" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - "fmt" - "io/ioutil" - "strings" - "net/http" - "github.com/cosmos/cosmos-sdk/wire" -) - -type Context struct { - Ctx context.CoreContext - Cdc *wire.Codec -} - - -func NewContext() Context { - return Context{ - Ctx:context.NewCoreContextFromViper(), - } -} - -func (c Context) WithCodeC(cdc *wire.Codec) Context{ - c.Cdc = cdc - return c -} - -func (c Context) BroadcastTxAsync(tx []byte) (*ctypes.ResultBroadcastTx, error) { - return c.Ctx.Client.BroadcastTxAsync(tx) -} - -func (c Context) BroadcastTxSync(tx []byte) (*ctypes.ResultBroadcastTx, error) { - return c.Ctx.Client.BroadcastTxSync(tx) -} - -func (c Context) NetInfo() *ctypes.ResultNetInfo { - client := &http.Client{} - - reqUri := tcpToHttpUrl(c.Ctx.NodeURI) + "/net_info" - - resp, err := client.Get(reqUri) - if err != nil { - fmt.Println(err) - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - fmt.Println(err) - } - - var res = struct { - JsonRpc string `json:"jsonrpc"` - Id string `json:"id"` - Result ctypes.ResultNetInfo `json:"result"` - }{} - if err := c.Cdc.UnmarshalJSON(body,&res); err != nil { - fmt.Println(err) - } - - return &res.Result -} - -func (c Context) NumUnconfirmedTxs() *ctypes.ResultUnconfirmedTxs { - client := &http.Client{} - reqUri := tcpToHttpUrl(c.Ctx.NodeURI) + "/num_unconfirmed_txs" - - resp, err := client.Get(reqUri) - if err != nil { - fmt.Println(err) - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - fmt.Println(err) - } - - var res = struct { - JsonRpc string `json:"jsonrpc"` - Id string `json:"id"` - Result ctypes.ResultUnconfirmedTxs `json:"result"` - }{} - if err := c.Cdc.UnmarshalJSON(body,&res); err != nil { - fmt.Println(err) - } - - return &res.Result -} - -func tcpToHttpUrl(url string) string { - urls := strings.Replace(url, "tcp", "http", 1) - return urls -} diff --git a/examples/irishub1/app/genesis.go b/examples/irishub1/app/genesis.go deleted file mode 100644 index d584c3805..000000000 --- a/examples/irishub1/app/genesis.go +++ /dev/null @@ -1,246 +0,0 @@ -package app - -import ( - "encoding/json" - "errors" - - "github.com/spf13/pflag" - "github.com/tendermint/tendermint/crypto" - tmtypes "github.com/tendermint/tendermint/types" - - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/server/config" - 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" - "math" -) - -// State to Unmarshal -type GenesisState struct { - Accounts []GenesisAccount `json:"accounts"` - StakeData stake.GenesisState `json:"stake"` -} - -// GenesisAccount doesn't need pubkey or sequence -type GenesisAccount struct { - Address sdk.AccAddress `json:"address"` - Coins sdk.Coins `json:"coins"` -} - -func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount { - return GenesisAccount{ - Address: acc.Address, - Coins: acc.Coins, - } -} - -func NewGenesisAccountI(acc auth.Account) GenesisAccount { - return GenesisAccount{ - Address: acc.GetAddress(), - Coins: acc.GetCoins(), - } -} - -// convert GenesisAccount to auth.BaseAccount -func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { - return &auth.BaseAccount{ - Address: ga.Address, - Coins: ga.Coins.Sort(), - } -} - -var ( - flagName = "name" - flagClientHome = "home-client" - flagOWK = "owk" - denom = "iris" - precision = 18 - // bonded tokens given to genesis validators/accounts - freeFermionVal = int64(100) - - totalTokenAmt = sdk.NewInt(200000000) -) - -const defaultUnbondingTime int64 = 60 * 10 - -// get app init parameters for server init command -func IrisAppInit() server.AppInit { - fsAppGenState := pflag.NewFlagSet("", pflag.ContinueOnError) - - fsAppGenTx := pflag.NewFlagSet("", pflag.ContinueOnError) - fsAppGenTx.String(flagName, "", "validator moniker, required") - fsAppGenTx.String(flagClientHome, DefaultCLIHome, - "home directory for the client, used for key generation") - fsAppGenTx.Bool(flagOWK, false, "overwrite the accounts created") - - return server.AppInit{ - FlagsAppGenState: fsAppGenState, - FlagsAppGenTx: fsAppGenTx, - AppGenTx: IrisAppGenTx, - AppGenState: IrisAppGenStateJSON, - } -} - -// simple genesis tx -type IrisGenTx struct { - Name string `json:"name"` - Address sdk.AccAddress `json:"address"` - PubKey string `json:"pub_key"` -} - -// Generate a gaia genesis transaction with flags -func IrisAppGenTx(cdc *wire.Codec, pk crypto.PubKey, genTxConfig config.GenTx) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - - if genTxConfig.Name == "" { - return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)") - } - - var addr sdk.AccAddress - var secret string - addr, secret, err = server.GenerateSaveCoinKey(genTxConfig.CliRoot, genTxConfig.Name, "1234567890", genTxConfig.Overwrite) - if err != nil { - return - } - mm := map[string]string{"secret": secret} - var bz []byte - bz, err = cdc.MarshalJSON(mm) - if err != nil { - return - } - cliPrint = json.RawMessage(bz) - appGenTx, _, validator, err = IrisAppGenTxNF(cdc, pk, addr, genTxConfig.Name) - return -} - -// Generate a gaia genesis transaction without flags -func IrisAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.AccAddress, name string) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - - var bz []byte - gaiaGenTx := IrisGenTx{ - Name: name, - Address: addr, - PubKey: sdk.MustBech32ifyAccPub(pk), - } - bz, err = wire.MarshalJSONIndent(cdc, gaiaGenTx) - if err != nil { - return - } - appGenTx = json.RawMessage(bz) - - validator = tmtypes.GenesisValidator{ - PubKey: pk, - Power: freeFermionVal, - } - return -} - -// Create the core parameters for genesis initialization for gaia -// note that the pubkey input is this machines pubkey -func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState GenesisState, err error) { - - if len(appGenTxs) == 0 { - err = errors.New("must provide at least genesis transaction") - return - } - - // start with the default staking genesis state - //stakeData := stake.DefaultGenesisState() - stakeData := createGenesisState() - - precisionNumber := math.Pow10(int(stakeData.Params.DenomPrecision)) - if precisionNumber > math.MaxInt64 { - panic(errors.New("precision is too high, int64 is overflow")) - } - precisionInt64 := int64(precisionNumber) - tokenPrecision := sdk.NewRat(precisionInt64) - // get genesis flag account information - genaccs := make([]GenesisAccount, len(appGenTxs)) - for i, appGenTx := range appGenTxs { - - var genTx IrisGenTx - err = cdc.UnmarshalJSON(appGenTx, &genTx) - if err != nil { - return - } - - // create the genesis account, give'm few steaks and a buncha token with there name - accAuth := auth.NewBaseAccountWithAddress(genTx.Address) - accAuth.Coins = sdk.Coins{ - {denom, totalTokenAmt.Mul(sdk.NewInt(precisionInt64))}, - } - acc := NewGenesisAccount(&accAuth) - genaccs[i] = acc - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionVal).Mul(tokenPrecision)) // increase the supply - - // add the validator - if len(genTx.Name) > 0 { - desc := stake.NewDescription(genTx.Name, "", "", "") - validator := stake.NewValidator(genTx.Address, - sdk.MustGetAccPubKeyBech32(genTx.PubKey), desc) - - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionVal).Mul(tokenPrecision)) - - // add some new shares to the validator - var issuedDelShares sdk.Rat - validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, sdk.NewInt(freeFermionVal).Mul(sdk.NewInt(precisionInt64))) - validator.TokenPrecision = stakeData.Params.DenomPrecision - stakeData.Validators = append(stakeData.Validators, validator) - - // create the self-delegation from the issuedDelShares - delegation := stake.Delegation{ - DelegatorAddr: validator.Owner, - ValidatorAddr: validator.Owner, - Shares: issuedDelShares, - Height: 0, - } - - stakeData.Bonds = append(stakeData.Bonds, delegation) - } - } - - // create the final app state - genesisState = GenesisState{ - Accounts: genaccs, - StakeData: stakeData, - } - return -} - -// IrisAppGenState but with JSON -func IrisAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) { - - // create the final app state - genesisState, err := IrisAppGenState(cdc, appGenTxs) - if err != nil { - return nil, err - } - appState, err = wire.MarshalJSONIndent(cdc, genesisState) - return -} - -func createGenesisState() stake.GenesisState { - return stake.GenesisState{ - Pool: stake.Pool{ - LooseTokens: sdk.ZeroRat(), - BondedTokens: sdk.ZeroRat(), - InflationLastTime: 0, - Inflation: sdk.NewRat(7, 100), - DateLastCommissionReset: 0, - PrevBondedShares: sdk.ZeroRat(), - }, - Params: stake.Params{ - InflationRateChange: sdk.NewRat(13, 100), - InflationMax: sdk.NewRat(20, 100), - InflationMin: sdk.NewRat(7, 100), - GoalBonded: sdk.NewRat(67, 100), - UnbondingTime: defaultUnbondingTime, - MaxValidators: 100, - BondDenom: denom, - DenomPrecision: int8(precision), - }, - } -} diff --git a/examples/irishub1/cmd/iris1/main.go b/examples/irishub1/cmd/iris1/main.go deleted file mode 100644 index 1814b8aee..000000000 --- a/examples/irishub1/cmd/iris1/main.go +++ /dev/null @@ -1,76 +0,0 @@ -package main - -import ( - "encoding/json" - "io" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/server" - "github.com/irisnet/irishub/examples/irishub1/app" - bam "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/irisnet/irishub/version" - - "github.com/spf13/viper" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/cli" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - "github.com/irisnet/irishub/tools/prometheus" -) - -func main() { - cdc := app.MakeCodec() - ctx := server.NewDefaultContext() - cobra.EnableCommandSorting = false - rootCmd := &cobra.Command{ - Use: "iris1", - Short: "iris1 Daemon (server)", - PersistentPreRunE: server.PersistentPreRunEFn(ctx), - } - - rootCmd.PersistentFlags().String("log_level", ctx.Config.LogLevel, "Log level") - - tendermintCmd := &cobra.Command{ - Use: "tendermint", - Short: "Tendermint subcommands", - } - - tendermintCmd.AddCommand( - server.ShowNodeIDCmd(ctx), - server.ShowValidatorCmd(ctx), - ) - - startCmd := server.StartCmd(ctx, server.ConstructAppCreator(newApp, "iris")) - startCmd.Flags().Bool(app.FlagReplay, false, "Replay the last block") - rootCmd.AddCommand( - server.InitCmd(ctx, cdc, app.IrisAppInit()), - startCmd, - server.TestnetFilesCmd(ctx, cdc, app.IrisAppInit()), - server.UnsafeResetAllCmd(ctx), - client.LineBreak, - tendermintCmd, - server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), - client.LineBreak, - version.GetCmdVersion("upgrade", cdc), - ) - - rootCmd.AddCommand(prometheus.MonitorCommand(cdc)) - - // prepare and add flags - executor := cli.PrepareBaseCmd(rootCmd, "IRIS", app.DefaultNodeHome) - executor.Execute() -} - -func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) abci.Application { - return app.NewIrisApp(logger, db, traceStore, bam.SetPruning(viper.GetString("pruning"))) -} - -func exportAppStateAndTMValidators( - logger log.Logger, db dbm.DB, traceStore io.Writer, -) (json.RawMessage, []tmtypes.GenesisValidator, error) { - gApp := app.NewIrisApp(logger, db, traceStore) - return gApp.ExportAppStateAndValidators() -} diff --git a/examples/irishub1/cmd/iriscli1/main.go b/examples/irishub1/cmd/iriscli1/main.go deleted file mode 100644 index 95ca12985..000000000 --- a/examples/irishub1/cmd/iriscli1/main.go +++ /dev/null @@ -1,173 +0,0 @@ -package main - -import ( - "github.com/spf13/cobra" - - "github.com/tendermint/tendermint/libs/cli" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/client/tx" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - ibccmd "github.com/irisnet/irishub/examples/irishub1/ibc/client/cli" - slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" - stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" - "github.com/irisnet/irishub/examples/irishub1/app" - c "github.com/irisnet/irishub/client" - govcmd "github.com/cosmos/cosmos-sdk/x/gov/client/cli" - upgradecmd "github.com/irisnet/irishub/modules/upgrade/client/cli" - "github.com/irisnet/irishub/version" -) - -// rootCmd is the entry point for this binary -var ( - rootCmd = &cobra.Command{ - Use: "iriscli1", - Short: "irishub1 light-client", - } -) - -func main() { - cobra.EnableCommandSorting = false - cdc := app.MakeCodec() - - // TODO: setup keybase, viper object, etc. to be passed into - // the below functions and eliminate global vars, like we do - // with the cdc - - // add standard rpc commands - rpc.AddCommands(rootCmd) - - //Add state commands - tendermintCmd := &cobra.Command{ - Use: "tendermint", - Short: "Tendermint state querying subcommands", - } - tendermintCmd.AddCommand( - rpc.BlockCommand(), - rpc.ValidatorCommand(), - ) - tx.AddCommands(tendermintCmd, cdc) - - //Add IBC commands - ibcCmd := &cobra.Command{ - Use: "ibc", - Short: "Inter-Blockchain Communication subcommands", - } - ibcCmd.AddCommand( - client.PostCommands( - ibccmd.IBCTransferCmd(cdc), - ibccmd.IBCRelayCmd(cdc), - ibccmd.IBCSetCmd(cdc), - ibccmd.IBCGetCmd(cdc), - )...) - - advancedCmd := &cobra.Command{ - Use: "advanced", - Short: "Advanced subcommands", - } - - advancedCmd.AddCommand( - tendermintCmd, - ibcCmd, - c.ServeCommand(cdc), - ) - rootCmd.AddCommand( - advancedCmd, - client.LineBreak, - ) - - //Add stake commands - stakeCmd := &cobra.Command{ - Use: "stake", - Short: "Stake and validation subcommands", - } - stakeCmd.AddCommand( - client.GetCommands( - stakecmd.GetCmdQueryValidator("stake", cdc), - stakecmd.GetCmdQueryValidators("stake", cdc), - stakecmd.GetCmdQueryDelegation("stake", cdc), - stakecmd.GetCmdQueryDelegations("stake", cdc), - slashingcmd.GetCmdQuerySigningInfo("slashing", cdc), - )...) - stakeCmd.AddCommand( - client.PostCommands( - stakecmd.GetCmdCreateValidator(cdc), - stakecmd.GetCmdEditValidator(cdc), - stakecmd.GetCmdDelegate(cdc), - stakecmd.GetCmdUnbond("stake", cdc), - stakecmd.GetCmdRedelegate("stake", cdc), - slashingcmd.GetCmdUnrevoke(cdc), - )...) - rootCmd.AddCommand( - stakeCmd, - ) - - //Add gov commands - govCmd := &cobra.Command{ - Use: "gov", - Short: "Governance and voting subcommands", - } - govCmd.AddCommand( - client.GetCommands( - govcmd.GetCmdQueryProposal("gov", cdc), - govcmd.GetCmdQueryVote("gov", cdc), - )...) - govCmd.AddCommand( - client.PostCommands( - govcmd.GetCmdSubmitProposal(cdc), - govcmd.GetCmdDeposit(cdc), - govcmd.GetCmdVote(cdc), - )...) - rootCmd.AddCommand( - govCmd, - ) - - //Add upgrade commands - upgradeCmd := &cobra.Command{ - Use: "upgrade", - Short: "Software Upgrade subcommands", - } - upgradeCmd.AddCommand( - client.GetCommands( - upgradecmd.GetCmdQuerySwitch("upgrade", cdc), - upgradecmd.GetCmdInfo("upgrade", cdc), - )...) - upgradeCmd.AddCommand( - client.PostCommands( - upgradecmd.GetCmdSubmitSwitch(cdc), - )...) - rootCmd.AddCommand( - upgradeCmd, - ) - - //Add auth and bank commands - rootCmd.AddCommand( - client.GetCommands( - authcmd.GetAccountCmd("acc", cdc, authcmd.GetAccountDecoder(cdc)), - )...) - rootCmd.AddCommand( - client.PostCommands( - bankcmd.SendTxCmd(cdc), - )...) - - // add proxy, version and key info - rootCmd.AddCommand( - keys.Commands(), - client.LineBreak, - ) - rootCmd.AddCommand( - client.GetCommands( - version.GetCmdVersion("upgrade", cdc), - )...) - - // prepare and add flags - executor := cli.PrepareMainCmd(rootCmd, "GA", app.DefaultCLIHome) - err := executor.Execute() - if err != nil { - // handle with #870 - panic(err) - } -} diff --git a/examples/irishub1/ibc/client/cli/README.md b/examples/irishub1/ibc/client/cli/README.md deleted file mode 100644 index ab9e8e555..000000000 --- a/examples/irishub1/ibc/client/cli/README.md +++ /dev/null @@ -1,157 +0,0 @@ -# IBC Doubble Hubble - -## Remove remaining data - -```console -> rm -r ~/.chain1 -> rm -r ~/.chain2 -> rm -r ~/.basecli -``` - -## Initialize both chains - -```console -> basecoind init --home ~/.chain1 -I[04-02|14:03:33.704] Generated private validator module=main path=/home/mossid/.chain1/config/priv_validator.json -I[04-02|14:03:33.705] Generated genesis file module=main path=/home/mossid/.chain1/config/genesis.json -{ - "secret": "crunch ignore trigger neither differ dance cheap brick situate floor luxury citizen husband decline arrow abandon", - "account": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "validator": { - "pub_key": { - "type": "ed25519", - "data": "8C9917D5E982E221F5A1450103102B44BBFC1E8768126C606246CB37B5794F4D" - }, - "power": 10, - "name": "" - }, - "node_id": "3ac8e6242315fd62143dc3e52c161edaaa6b1a64", - "chain_id": "test-chain-ZajMfr" -} -> ADDR1=C69FEB398A29AAB1B3C4F07DE22208F35E711BCC -> ID1=test-chain-ZajMfr -> NODE1=tcp://0.0.0.0:36657 -> basecli keys add key1 --recover -Enter a passphrase for your key: -Repeat the passphrase: -Enter your recovery seed phrase: -crunch ignore trigger neither differ dance cheap brick situate floor luxury citizen husband decline arrow abandon -key1 C69FEB398A29AAB1B3C4F07DE22208F35E711BCC - - -> basecoind init --home ~/.chain2 -I[04-02|14:09:14.453] Generated private validator module=main path=/home/mossid/.chain2/config/priv_validator.json -I[04-02|14:09:14.453] Generated genesis file module=main path=/home/mossid/.chain2/config/genesis.json -{ - "secret": "age guide awesome month female left oxygen soccer define high grocery work desert dinner arena abandon", - "account": "DC26002735D3AA9573707CFA6D77C12349E49868", - "validator": { - "pub_key": { - "type": "ed25519", - "data": "A94FE4B9AD763D301F4DD5A2766009812495FB7A79F1275FB8A5AF09B44FD5F3" - }, - "power": 10, - "name": "" - }, - "node_id": "ad26831330e1c72b85276d53c20f0680e6fd4cf5" - "chain_id": "test-chain-4XHTPn" -} -> ADDR2=DC26002735D3AA9573707CFA6D77C12349E49868 -> ID2=test-chain-4XHTPn -> NODE2=tcp://0.0.0.0:26657 -> basecli keys add key2 --recover -Enter a passphrase for your key: -Repeat the passphrase: -Enter your recovery seed phrase: -age guide awesome month female left oxygen soccer define high grocery work desert dinner arena abandon -key2 DC26002735D3AA9573707CFA6D77C12349E49868 - - -> basecoind start --home ~/.chain1 --address tcp://0.0.0.0:36658 --rpc.laddr tcp://0.0.0.0:36657 --p2p.laddr tcp://0.0.0.0:36656 -... - -> basecoind start --home ~/.chain2 # --address tcp://0.0.0.0:26658 --rpc.laddr tcp://0.0.0.0:26657 --p2p.laddr tcp://0.0.0.0:26656 -... -``` -## Check balance - -```console -> basecli account $ADDR1 --node $NODE1 -{ - "address": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740992 - } - ], - "public_key": null, - "sequence": 0, - "name": "" -} - -> basecli account $ADDR2 --node $NODE2 -{ - "address": "DC26002735D3AA9573707CFA6D77C12349E49868", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740992 - } - ], - "public_key": null, - "sequence": 0, - "name": "" -} - -``` - -## Transfer coins (addr1:chain1 -> addr2:chain2) - -```console -> basecli transfer --from key1 --to $ADDR2 --amount 10mycoin --chain $ID2 --chain-id $ID1 --node $NODE1 -Password to sign with 'key1': -Committed at block 1022. Hash: E16019DCC4AA08CA70AFCFBC96028ABCC51B6AD0 -> basecli account $ADDR1 --node $NODE1 -{ - "address": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740982 - } - ], - "public_key": { - "type": "ed25519", - "data": "9828FF1780A066A0D93D840737566B697035448D6C880807322BED8919348B2B" - }, - "sequence": 1, - "name": "" -} -``` - -## Relay IBC packets - -```console -> basecli relay --from key2 --from-chain-id $ID1 --from-chain-node $NODE1 --to-chain-id $ID2 --to-chain-node $NODE2 --chain-id $ID2 -Password to sign with 'key2': -I[04-03|16:18:59.984] Detected IBC packet number=0 -I[04-03|16:19:00.869] Relayed IBC packet number=0 -> basecli account $ADDR2 --node $NODE2 -{ - "address": "DC26002735D3AA9573707CFA6D77C12349E49868", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254741002 - } - ], - "public_key": { - "type": "ed25519", - "data": "F52B4FA545F4E9BFE5D7AF1DD2236899FDEF905F9B3057C38D7C01BF1B8EB52E" - }, - "sequence": 1, - "name": "" -} - -``` diff --git a/examples/irishub1/ibc/client/cli/ibctx.go b/examples/irishub1/ibc/client/cli/ibctx.go deleted file mode 100644 index f5505d9a4..000000000 --- a/examples/irishub1/ibc/client/cli/ibctx.go +++ /dev/null @@ -1,81 +0,0 @@ -package cli - -import ( - "encoding/hex" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" - - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - "github.com/cosmos/cosmos-sdk/x/ibc" -) - -const ( - flagTo = "to" - flagAmount = "amount" - flagChain = "chain" -) - -// IBC transfer command -func IBCTransferCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "transfer", - RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) - - // get the from address - from, err := ctx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg, err := buildMsg(from) - if err != nil { - return err - } - - // get password - err = ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, []sdk.Msg{msg}, cdc) - if err != nil { - return err - } - return nil - }, - } - - cmd.Flags().String(flagTo, "", "Address to send coins") - cmd.Flags().String(flagAmount, "", "Amount of coins to send") - cmd.Flags().String(flagChain, "", "Destination chain to send coins") - return cmd -} - -func buildMsg(from sdk.AccAddress) (sdk.Msg, error) { - amount := viper.GetString(flagAmount) - coins, err := sdk.ParseCoins(amount) - if err != nil { - return nil, err - } - - dest := viper.GetString(flagTo) - bz, err := hex.DecodeString(dest) - if err != nil { - return nil, err - } - to := sdk.AccAddress(bz) - - packet := ibc.NewIBCPacket(from, to, coins, viper.GetString(client.FlagChainID), - viper.GetString(flagChain)) - - msg := ibc.IBCTransferMsg{ - IBCPacket: packet, - } - - return msg, nil -} diff --git a/examples/irishub1/ibc/client/cli/relay.go b/examples/irishub1/ibc/client/cli/relay.go deleted file mode 100644 index 58d8f272b..000000000 --- a/examples/irishub1/ibc/client/cli/relay.go +++ /dev/null @@ -1,200 +0,0 @@ -package cli - -import ( - "os" - "time" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/tendermint/tendermint/libs/log" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/auth" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - "github.com/cosmos/cosmos-sdk/x/ibc" -) - -// flags -const ( - FlagFromChainID = "from-chain-id" - FlagFromChainNode = "from-chain-node" - FlagToChainID = "to-chain-id" - FlagToChainNode = "to-chain-node" -) - -type relayCommander struct { - cdc *wire.Codec - address sdk.AccAddress - decoder auth.AccountDecoder - mainStore string - ibcStore string - accStore string - - logger log.Logger -} - -// IBC relay command -func IBCRelayCmd(cdc *wire.Codec) *cobra.Command { - cmdr := relayCommander{ - cdc: cdc, - decoder: authcmd.GetAccountDecoder(cdc), - ibcStore: "ibc", - mainStore: "main", - accStore: "acc", - - logger: log.NewTMLogger(log.NewSyncWriter(os.Stdout)), - } - - cmd := &cobra.Command{ - Use: "relay", - Run: cmdr.runIBCRelay, - } - - cmd.Flags().String(FlagFromChainID, "", "Chain ID for ibc node to check outgoing packets") - cmd.Flags().String(FlagFromChainNode, "tcp://localhost:26657", ": to tendermint rpc interface for this chain") - cmd.Flags().String(FlagToChainID, "", "Chain ID for ibc node to broadcast incoming packets") - cmd.Flags().String(FlagToChainNode, "tcp://localhost:36657", ": to tendermint rpc interface for this chain") - - cmd.MarkFlagRequired(FlagFromChainID) - cmd.MarkFlagRequired(FlagFromChainNode) - cmd.MarkFlagRequired(FlagToChainID) - cmd.MarkFlagRequired(FlagToChainNode) - - viper.BindPFlag(FlagFromChainID, cmd.Flags().Lookup(FlagFromChainID)) - viper.BindPFlag(FlagFromChainNode, cmd.Flags().Lookup(FlagFromChainNode)) - viper.BindPFlag(FlagToChainID, cmd.Flags().Lookup(FlagToChainID)) - viper.BindPFlag(FlagToChainNode, cmd.Flags().Lookup(FlagToChainNode)) - - return cmd -} - -// nolint: unparam -func (c relayCommander) runIBCRelay(cmd *cobra.Command, args []string) { - fromChainID := viper.GetString(FlagFromChainID) - fromChainNode := viper.GetString(FlagFromChainNode) - toChainID := viper.GetString(FlagToChainID) - toChainNode := viper.GetString(FlagToChainNode) - address, err := context.NewCoreContextFromViper().GetFromAddress() - if err != nil { - panic(err) - } - c.address = address - - c.loop(fromChainID, fromChainNode, toChainID, toChainNode) -} - -// This is nolinted as someone is in the process of refactoring this to remove the goto -// nolint: gocyclo -func (c relayCommander) loop(fromChainID, fromChainNode, toChainID, - toChainNode string) { - - ctx := context.NewCoreContextFromViper() - // get password - passphrase, err := ctx.GetPassphraseFromStdin(ctx.FromAddressName) - if err != nil { - panic(err) - } - - ingressKey := ibc.IngressSequenceKey(fromChainID) - -OUTER: - for { - time.Sleep(5 * time.Second) - - processedbz, err := query(toChainNode, ingressKey, c.ibcStore) - if err != nil { - panic(err) - } - - var processed int64 - if processedbz == nil { - processed = 0 - } else if err = c.cdc.UnmarshalBinary(processedbz, &processed); err != nil { - panic(err) - } - - lengthKey := ibc.EgressLengthKey(toChainID) - egressLengthbz, err := query(fromChainNode, lengthKey, c.ibcStore) - if err != nil { - c.logger.Error("error querying outgoing packet list length", "err", err) - continue OUTER //TODO replace with continue (I think it should just to the correct place where OUTER is now) - } - var egressLength int64 - if egressLengthbz == nil { - egressLength = 0 - } else if err = c.cdc.UnmarshalBinary(egressLengthbz, &egressLength); err != nil { - panic(err) - } - if egressLength > processed { - c.logger.Info("Detected IBC packet", "number", egressLength-1) - } - - seq := c.getSequence(toChainNode) - - for i := processed; i < egressLength; i++ { - egressbz, err := query(fromChainNode, ibc.EgressKey(toChainID, i), c.ibcStore) - if err != nil { - c.logger.Error("error querying egress packet", "err", err) - continue OUTER // TODO replace to break, will break first loop then send back to the beginning (aka OUTER) - } - - err = c.broadcastTx(seq, toChainNode, c.refine(egressbz, i, passphrase)) - seq++ - if err != nil { - c.logger.Error("error broadcasting ingress packet", "err", err) - continue OUTER // TODO replace to break, will break first loop then send back to the beginning (aka OUTER) - } - - c.logger.Info("Relayed IBC packet", "number", i) - } - } -} - -func query(node string, key []byte, storeName string) (res []byte, err error) { - return context.NewCoreContextFromViper().WithNodeURI(node).QueryStore(key, storeName) -} - -func (c relayCommander) broadcastTx(seq int64, node string, tx []byte) error { - _, err := context.NewCoreContextFromViper().WithNodeURI(node).WithSequence(seq + 1).BroadcastTx(tx) - return err -} - -func (c relayCommander) getSequence(node string) int64 { - res, err := query(node, c.address, c.accStore) - if err != nil { - panic(err) - } - if nil != res { - account, err := c.decoder(res) - if err != nil { - panic(err) - } - - return account.GetSequence() - } - - return 0 -} - -func (c relayCommander) refine(bz []byte, sequence int64, passphrase string) []byte { - var packet ibc.IBCPacket - if err := c.cdc.UnmarshalBinary(bz, &packet); err != nil { - panic(err) - } - - msg := ibc.IBCReceiveMsg{ - IBCPacket: packet, - Relayer: c.address, - Sequence: sequence, - } - - ctx := context.NewCoreContextFromViper().WithSequence(sequence) - res, err := ctx.SignAndBuild(ctx.FromAddressName, passphrase, []sdk.Msg{msg}, c.cdc) - if err != nil { - panic(err) - } - return res -} diff --git a/examples/irishub1/ibc/client/cli/tx.go b/examples/irishub1/ibc/client/cli/tx.go deleted file mode 100644 index 3d813e88f..000000000 --- a/examples/irishub1/ibc/client/cli/tx.go +++ /dev/null @@ -1,66 +0,0 @@ -package cli - -import ( - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - "github.com/irisnet/irishub/examples/irishub1/ibc" -) - -// IBC transfer command -func IBCGetCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "get", - RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) - - // get the from address - from, err := ctx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg := ibc.NewIBCGetMsg(from) - - // get password - err = ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, []sdk.Msg{msg}, cdc) - if err != nil { - return err - } - return nil - }, - } - return cmd -} - - -// IBC transfer command -func IBCSetCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "set", - RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) - - // get the from address - from, err := ctx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg := ibc.NewIBCSetMsg(from) - - // get password - err = ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, []sdk.Msg{msg}, cdc) - if err != nil { - return err - } - return nil - }, - } - return cmd -} - diff --git a/examples/irishub1/ibc/client/rest/transfer.go b/examples/irishub1/ibc/client/rest/transfer.go deleted file mode 100644 index bee9f955f..000000000 --- a/examples/irishub1/ibc/client/rest/transfer.go +++ /dev/null @@ -1,103 +0,0 @@ -package rest - -import ( - "io/ioutil" - "net/http" - - "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/gorilla/mux" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/ibc" -) - -// RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { - r.HandleFunc("/ibc/{destchain}/{address}/send", TransferRequestHandlerFn(cdc, kb, ctx)).Methods("POST") -} - -type transferBody struct { - // Fees sdk.Coin `json="fees"` - Amount sdk.Coins `json:"amount"` - LocalAccountName string `json:"name"` - Password string `json:"password"` - SrcChainID string `json:"src_chain_id"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` - Gas int64 `json:"gas"` -} - -// TransferRequestHandler - http request handler to transfer coins to a address -// on a different chain via IBC -func TransferRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - // collect data - vars := mux.Vars(r) - destChainID := vars["destchain"] - bech32addr := vars["address"] - - to, err := sdk.AccAddressFromBech32(bech32addr) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - var m transferBody - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - err = cdc.UnmarshalJSON(body, &m) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - info, err := kb.Get(m.LocalAccountName) - if err != nil { - w.WriteHeader(http.StatusUnauthorized) - w.Write([]byte(err.Error())) - return - } - - // build message - packet := ibc.NewIBCPacket(sdk.AccAddress(info.GetPubKey().Address()), to, m.Amount, m.SrcChainID, destChainID) - msg := ibc.IBCTransferMsg{packet} - - // add gas to context - ctx = ctx.WithGas(m.Gas) - - // sign - ctx = ctx.WithAccountNumber(m.AccountNumber) - ctx = ctx.WithSequence(m.Sequence) - 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 - } - - // send - res, err := ctx.BroadcastTx(txBytes) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - output, err := cdc.MarshalJSON(res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - w.Write(output) - } -} diff --git a/examples/irishub1/ibc/errors.go b/examples/irishub1/ibc/errors.go deleted file mode 100644 index 7a3194baf..000000000 --- a/examples/irishub1/ibc/errors.go +++ /dev/null @@ -1,50 +0,0 @@ -package ibc - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// IBC errors reserve 200 ~ 299. -const ( - DefaultCodespace sdk.CodespaceType = 3 - - // IBC errors reserve 200 - 299. - CodeInvalidSequence sdk.CodeType = 200 - CodeIdenticalChains sdk.CodeType = 201 - CodeUnknownRequest sdk.CodeType = sdk.CodeUnknownRequest -) - -func codeToDefaultMsg(code sdk.CodeType) string { - switch code { - case CodeInvalidSequence: - return "invalid IBC packet sequence" - case CodeIdenticalChains: - return "source and destination chain cannot be identical" - default: - return sdk.CodeToDefaultMsg(code) - } -} - -// nolint -func ErrInvalidSequence(codespace sdk.CodespaceType) sdk.Error { - return newError(codespace, CodeInvalidSequence, "") -} -func ErrIdenticalChains(codespace sdk.CodespaceType) sdk.Error { - return newError(codespace, CodeIdenticalChains, "") -} - -// ------------------------- -// Helpers - -// nolint: unparam -func newError(codespace sdk.CodespaceType, code sdk.CodeType, msg string) sdk.Error { - msg = msgOrDefaultMsg(msg, code) - return sdk.NewError(codespace, code, msg) -} - -func msgOrDefaultMsg(msg string, code sdk.CodeType) string { - if msg != "" { - return msg - } - return codeToDefaultMsg(code) -} diff --git a/examples/irishub1/ibc/handler.go b/examples/irishub1/ibc/handler.go deleted file mode 100644 index c277e0a4b..000000000 --- a/examples/irishub1/ibc/handler.go +++ /dev/null @@ -1,76 +0,0 @@ -package ibc - -import ( - "reflect" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" -) - -func NewHandler(ibcm Mapper, ck bank.Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { - switch msg := msg.(type) { - case IBCTransferMsg: - return handleIBCTransferMsg(ctx, ibcm, ck, msg) - case IBCReceiveMsg: - return handleIBCReceiveMsg(ctx, ibcm, ck, msg) - case IBCGetMsg: - return handleIBCGetMsg(ctx, ibcm, ck, msg) - case IBCSetMsg: - return handleIBCSetMsg(ctx, ibcm, ck, msg) - default: - errMsg := "Unrecognized IBC Msg type: " + reflect.TypeOf(msg).Name() - return sdk.ErrUnknownRequest(errMsg).Result() - } - } -} - -// IBCTransferMsg deducts coins from the account and creates an egress IBC packet. -func handleIBCTransferMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCTransferMsg) sdk.Result { - packet := msg.IBCPacket - - _, _, err := ck.SubtractCoins(ctx, packet.SrcAddr, packet.Coins) - if err != nil { - return err.Result() - } - - err = ibcm.PostIBCPacket(ctx, packet) - if err != nil { - return err.Result() - } - - return sdk.Result{} -} - -// IBCReceiveMsg adds coins to the destination address and creates an ingress IBC packet. -func handleIBCReceiveMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCReceiveMsg) sdk.Result { - packet := msg.IBCPacket - - seq := ibcm.GetIngressSequence(ctx, packet.SrcChain) - if msg.Sequence != seq { - return ErrInvalidSequence(ibcm.codespace).Result() - } - - _, _, err := ck.AddCoins(ctx, packet.DestAddr, packet.Coins) - if err != nil { - return err.Result() - } - - ibcm.SetIngressSequence(ctx, packet.SrcChain, seq+1) - - return sdk.Result{} -} - - - -// IBCTransferMsg deducts coins from the account and creates an egress IBC packet. -func handleIBCSetMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCSetMsg) sdk.Result { - ibcm.Set(ctx,msg.Addr.String()) - return sdk.Result{Log:"This is new module - ibc1 !!"} -} - -// IBCReceiveMsg adds coins to the destination address and creates an ingress IBC packet. -func handleIBCGetMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCGetMsg) sdk.Result { - AddrString,_:=ibcm.Get(ctx) - return sdk.Result{Log:AddrString} -} diff --git a/examples/irishub1/ibc/mapper.go b/examples/irishub1/ibc/mapper.go deleted file mode 100644 index 56cc10e79..000000000 --- a/examples/irishub1/ibc/mapper.go +++ /dev/null @@ -1,148 +0,0 @@ -package ibc - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" -) - -// IBC Mapper -type Mapper struct { - key sdk.StoreKey - cdc *wire.Codec - codespace sdk.CodespaceType -} - -// XXX: The Mapper should not take a CoinKeeper. Rather have the CoinKeeper -// take an Mapper. -func NewMapper(cdc *wire.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) Mapper { - // XXX: How are these codecs supposed to work? - return Mapper{ - key: key, - cdc: cdc, - codespace: codespace, - } -} - -// XXX: This is not the public API. This will change in MVP2 and will henceforth -// only be invoked from another module directly and not through a user -// transaction. -// TODO: Handle invalid IBC packets and return errors. -func (ibcm Mapper) PostIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error { - // write everything into the state - store := ctx.KVStore(ibcm.key) - index := ibcm.getEgressLength(store, packet.DestChain) - bz, err := ibcm.cdc.MarshalBinary(packet) - if err != nil { - panic(err) - } - - store.Set(EgressKey(packet.DestChain, index), bz) - bz, err = ibcm.cdc.MarshalBinary(index + 1) - if err != nil { - panic(err) - } - store.Set(EgressLengthKey(packet.DestChain), bz) - - return nil -} - -// XXX: In the future every module is able to register it's own handler for -// handling it's own IBC packets. The "ibc" handler will only route the packets -// to the appropriate callbacks. -// XXX: For now this handles all interactions with the CoinKeeper. -// XXX: This needs to do some authentication checking. -func (ibcm Mapper) ReceiveIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error { - return nil -} - -// -------------------------- -// Functions for accessing the underlying KVStore. - -func marshalBinaryPanic(cdc *wire.Codec, value interface{}) []byte { - res, err := cdc.MarshalBinary(value) - if err != nil { - panic(err) - } - return res -} - -func unmarshalBinaryPanic(cdc *wire.Codec, bz []byte, ptr interface{}) { - err := cdc.UnmarshalBinary(bz, ptr) - if err != nil { - panic(err) - } -} - -// TODO add description -func (ibcm Mapper) GetIngressSequence(ctx sdk.Context, srcChain string) int64 { - store := ctx.KVStore(ibcm.key) - key := IngressSequenceKey(srcChain) - - bz := store.Get(key) - if bz == nil { - zero := marshalBinaryPanic(ibcm.cdc, int64(0)) - store.Set(key, zero) - return 0 - } - - var res int64 - unmarshalBinaryPanic(ibcm.cdc, bz, &res) - return res -} - -// TODO add description -func (ibcm Mapper) SetIngressSequence(ctx sdk.Context, srcChain string, sequence int64) { - store := ctx.KVStore(ibcm.key) - key := IngressSequenceKey(srcChain) - - bz := marshalBinaryPanic(ibcm.cdc, sequence) - store.Set(key, bz) -} - -// Retrieves the index of the currently stored outgoing IBC packets. -func (ibcm Mapper) getEgressLength(store sdk.KVStore, destChain string) int64 { - bz := store.Get(EgressLengthKey(destChain)) - if bz == nil { - zero := marshalBinaryPanic(ibcm.cdc, int64(0)) - store.Set(EgressLengthKey(destChain), zero) - return 0 - } - var res int64 - unmarshalBinaryPanic(ibcm.cdc, bz, &res) - return res -} - -// Stores an outgoing IBC packet under "egress/chain_id/index". -func EgressKey(destChain string, index int64) []byte { - return []byte(fmt.Sprintf("egress/%s/%d", destChain, index)) -} - -// Stores the number of outgoing IBC packets under "egress/index". -func EgressLengthKey(destChain string) []byte { - return []byte(fmt.Sprintf("egress/%s", destChain)) -} - -// Stores the sequence number of incoming IBC packet under "ingress/index". -func IngressSequenceKey(srcChain string) []byte { - return []byte(fmt.Sprintf("ingress/%s", srcChain)) -} - - -func (ibcm Mapper) Get(ctx sdk.Context) (string, bool) { - store := ctx.KVStore(ibcm.key) - bz := store.Get([]byte("ibcaddr")) - if bz == nil { - return " ", false - } - var Addr string - ibcm.cdc.MustUnmarshalBinary(bz, &Addr) - return Addr, true -} - -func (ibcm Mapper) Set(ctx sdk.Context,Addr string) { - store := ctx.KVStore(ibcm.key) - bz := ibcm.cdc.MustMarshalBinary(Addr) - store.Set([]byte("ibcaddr"), bz) -} \ No newline at end of file diff --git a/examples/irishub1/ibc/types.go b/examples/irishub1/ibc/types.go deleted file mode 100644 index 0537ff816..000000000 --- a/examples/irishub1/ibc/types.go +++ /dev/null @@ -1,184 +0,0 @@ -package ibc - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" -) - -var ( - msgCdc *wire.Codec -) - -func init() { - msgCdc = wire.NewCodec() -} - -// ------------------------------ -// IBCPacket - -// nolint - TODO rename to Packet as IBCPacket stutters (golint) -// IBCPacket defines a piece of data that can be send between two separate -// blockchains. -type IBCPacket struct { - SrcAddr sdk.AccAddress - DestAddr sdk.AccAddress - Coins sdk.Coins - SrcChain string - DestChain string -} - -func NewIBCPacket(srcAddr sdk.AccAddress, destAddr sdk.AccAddress, coins sdk.Coins, - srcChain string, destChain string) IBCPacket { - - return IBCPacket{ - SrcAddr: srcAddr, - DestAddr: destAddr, - Coins: coins, - SrcChain: srcChain, - DestChain: destChain, - } -} - -//nolint -func (p IBCPacket) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(p) - if err != nil { - panic(err) - } - return sdk.MustSortJSON(b) -} - -// validator the ibc packey -func (p IBCPacket) ValidateBasic() sdk.Error { - if p.SrcChain == p.DestChain { - return ErrIdenticalChains(DefaultCodespace).TraceSDK("") - } - if !p.Coins.IsValid() { - return sdk.ErrInvalidCoins("") - } - return nil -} - -// ---------------------------------- -// IBCTransferMsg - -// nolint - TODO rename to TransferMsg as folks will reference with ibc.TransferMsg -// IBCTransferMsg defines how another module can send an IBCPacket. -type IBCTransferMsg struct { - IBCPacket -} - -// nolint -func (msg IBCTransferMsg) Type() string { return "ibc-1" } - -// x/bank/tx.go MsgSend.GetSigners() -func (msg IBCTransferMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.SrcAddr} } - -// get the sign bytes for ibc transfer message -func (msg IBCTransferMsg) GetSignBytes() []byte { - return msg.IBCPacket.GetSignBytes() -} - -// validate ibc transfer message -func (msg IBCTransferMsg) ValidateBasic() sdk.Error { - return msg.IBCPacket.ValidateBasic() -} - -// ---------------------------------- -// IBCReceiveMsg - -// nolint - TODO rename to ReceiveMsg as folks will reference with ibc.ReceiveMsg -// IBCReceiveMsg defines the message that a relayer uses to post an IBCPacket -// to the destination chain. -type IBCReceiveMsg struct { - IBCPacket - Relayer sdk.AccAddress - Sequence int64 -} - -// nolint -func (msg IBCReceiveMsg) Type() string { return "ibc-1" } -func (msg IBCReceiveMsg) ValidateBasic() sdk.Error { return msg.IBCPacket.ValidateBasic() } - -// x/bank/tx.go MsgSend.GetSigners() -func (msg IBCReceiveMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Relayer} } - -// get the sign bytes for ibc receive message -func (msg IBCReceiveMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(struct { - IBCPacket json.RawMessage - Relayer sdk.AccAddress - Sequence int64 - }{ - IBCPacket: json.RawMessage(msg.IBCPacket.GetSignBytes()), - Relayer: msg.Relayer, - Sequence: msg.Sequence, - }) - if err != nil { - panic(err) - } - return sdk.MustSortJSON(b) -} - - -type IBCSetMsg struct { - Addr sdk.AccAddress -} - -func NewIBCSetMsg(addr sdk.AccAddress) IBCSetMsg { - return IBCSetMsg{ - Addr:addr, - } -} - -func (msg IBCSetMsg) Type() string { - return "ibc-1" -} - -func (msg IBCSetMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(msg) - if err != nil { - panic(err) - } - return b -} - -func (msg IBCSetMsg) ValidateBasic() sdk.Error { - return nil -} - -func (msg IBCSetMsg) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Addr} -} - -type IBCGetMsg struct { - Addr sdk.AccAddress -} - -func NewIBCGetMsg(addr sdk.AccAddress) IBCGetMsg { - return IBCGetMsg{ - Addr:addr, - } -} - -func (msg IBCGetMsg) Type() string { - return "ibc-1" -} - -func (msg IBCGetMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(msg) - if err != nil { - panic(err) - } - return b -} - -func (msg IBCGetMsg) ValidateBasic() sdk.Error { - return nil -} - -func (msg IBCGetMsg) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Addr} -} diff --git a/examples/irishub1/ibc/wire.go b/examples/irishub1/ibc/wire.go deleted file mode 100644 index 3d4bc334e..000000000 --- a/examples/irishub1/ibc/wire.go +++ /dev/null @@ -1,13 +0,0 @@ -package ibc - -import ( - "github.com/cosmos/cosmos-sdk/wire" -) - -// Register concrete types on wire codec -func RegisterWire(cdc *wire.Codec) { - cdc.RegisterConcrete(IBCTransferMsg{}, "cosmos-sdk/IBCTransferMsg/1", nil) - cdc.RegisterConcrete(IBCReceiveMsg{}, "cosmos-sdk/IBCReceiveMsg/1", nil) - cdc.RegisterConcrete(IBCSetMsg{},"cosmos-sdk/IBCSetMsg/1",nil) - cdc.RegisterConcrete(IBCGetMsg{},"cosmos-sdk/IBCGetMsg/1",nil) -} diff --git a/examples/irishub2/app/app.go b/examples/irishub2/app/app.go deleted file mode 100644 index 81a80e64f..000000000 --- a/examples/irishub2/app/app.go +++ /dev/null @@ -1,347 +0,0 @@ -package app - -import ( - "encoding/json" - "io" - "os" - - bam "github.com/cosmos/cosmos-sdk/baseapp" - abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - - 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/bank" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/ibc" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/stake" - ibc1 "github.com/irisnet/irishub/examples/irishub1/ibc" - ibc2 "github.com/irisnet/irishub/examples/irishub2/ibc" - "github.com/irisnet/irishub/modules/upgrade" - - "errors" - "fmt" - "github.com/cosmos/cosmos-sdk/server" - "github.com/spf13/viper" - tmcli "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/node" - sm "github.com/tendermint/tendermint/state" - "strings" -) - -const ( - appName = "IrisApp" - FlagReplay = "replay" -) - -// default home directories for expected binaries -var ( - DefaultCLIHome = os.ExpandEnv("$HOME/.iriscli") - DefaultNodeHome = os.ExpandEnv("$HOME/.iris") -) - -// Extended ABCI application -type IrisApp struct { - *bam.BaseApp - cdc *wire.Codec - - // keys to access the substores - keyMain *sdk.KVStoreKey - keyAccount *sdk.KVStoreKey - keyIBC *sdk.KVStoreKey - keyStake *sdk.KVStoreKey - keySlashing *sdk.KVStoreKey - keyGov *sdk.KVStoreKey - keyFeeCollection *sdk.KVStoreKey - keyParams *sdk.KVStoreKey - keyUpgrade *sdk.KVStoreKey - - // Manage getting and setting accounts - accountMapper auth.AccountMapper - feeCollectionKeeper auth.FeeCollectionKeeper - coinKeeper bank.Keeper - ibcMapper ibc.Mapper - ibc1Mapper ibc1.Mapper - ibc2Mapper ibc2.Mapper - stakeKeeper stake.Keeper - slashingKeeper slashing.Keeper - govKeeper gov.Keeper - paramsKeeper params.Keeper - upgradeKeeper upgrade.Keeper -} - -func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptions ...func(*bam.BaseApp)) *IrisApp { - cdc := MakeCodec() - - bApp := bam.NewBaseApp(appName, cdc, logger, db, baseAppOptions...) - bApp.SetCommitMultiStoreTracer(traceStore) - - // create your application object - var app = &IrisApp{ - BaseApp: bam.NewBaseApp(appName, cdc, logger, db), - cdc: cdc, - keyMain: sdk.NewKVStoreKey("main"), - keyAccount: sdk.NewKVStoreKey("acc"), - keyIBC: sdk.NewKVStoreKey("ibc"), - keyStake: sdk.NewKVStoreKey("stake"), - keySlashing: sdk.NewKVStoreKey("slashing"), - keyGov: sdk.NewKVStoreKey("gov"), - keyFeeCollection: sdk.NewKVStoreKey("fee"), - keyParams: sdk.NewKVStoreKey("params"), - keyUpgrade: sdk.NewKVStoreKey("upgrade"), - } - - var lastHeight int64 - if viper.GetBool(FlagReplay) { - lastHeight = app.replay() - } - - // define the accountMapper - app.accountMapper = auth.NewAccountMapper( - app.cdc, - app.keyAccount, // target store - auth.ProtoBaseAccount, // prototype - ) - - // add handlers - app.paramsKeeper = params.NewKeeper(app.cdc, app.keyParams) - app.coinKeeper = bank.NewKeeper(app.accountMapper) - - app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace)) - app.ibc1Mapper = ibc1.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc1.DefaultCodespace)) - app.ibc2Mapper = ibc2.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc1.DefaultCodespace)) - - app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) - app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.RegisterCodespace(slashing.DefaultCodespace)) - app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection, app.paramsKeeper.Getter()) - app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper, app.paramsKeeper.Setter()) - app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - //app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - - // register message routes - // need to update each module's msg type - app.Router(). - AddRoute("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.coinKeeper)). - AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). - AddRoute("ibc-1", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc1.NewHandler(app.ibc1Mapper, app.coinKeeper)). - AddRoute("ibc-2", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc2.NewHandler(app.ibc2Mapper, app.coinKeeper)). - AddRoute("stake", []*sdk.KVStoreKey{app.keyStake, app.keyAccount}, stake.NewHandler(app.stakeKeeper)). - AddRoute("slashing", []*sdk.KVStoreKey{app.keySlashing, app.keyStake}, slashing.NewHandler(app.slashingKeeper)). - AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake, app.keyParams}, gov.NewHandler(app.govKeeper)). - AddRoute("upgrade", []*sdk.KVStoreKey{app.keyUpgrade, app.keyStake}, upgrade.NewHandler(app.upgradeKeeper)) - - // initialize BaseApp - app.SetInitChainer(app.initChainer) - app.SetBeginBlocker(app.BeginBlocker) - app.SetEndBlocker(app.EndBlocker) - app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) - app.SetFeeRefundHandler(auth.NewFeeRefundHandler(app.accountMapper, app.feeCollectionKeeper)) - app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing, app.keyGov, app.keyFeeCollection, app.keyParams, app.keyUpgrade) - app.SetRunMsg(app.runMsgs) - var err error - if viper.GetBool(FlagReplay) { - err = app.LoadVersion(lastHeight, app.keyMain) - } else { - err = app.LoadLatestVersion(app.keyMain) - } - if err != nil { - cmn.Exit(err.Error()) - } - - upgrade.RegisterModuleList(app.Router()) - - return app -} - -// custom tx codec -func MakeCodec() *wire.Codec { - var cdc = wire.NewCodec() - ibc.RegisterWire(cdc) - ibc1.RegisterWire(cdc) - ibc2.RegisterWire(cdc) - bank.RegisterWire(cdc) - stake.RegisterWire(cdc) - slashing.RegisterWire(cdc) - gov.RegisterWire(cdc) - auth.RegisterWire(cdc) - upgrade.RegisterWire(cdc) - sdk.RegisterWire(cdc) - wire.RegisterCrypto(cdc) - return cdc -} - -// application updates every end block -func (app *IrisApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) - - return abci.ResponseBeginBlock{ - Tags: tags.ToKVPairs(), - } -} - -// application updates every end block -func (app *IrisApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) - - tags, _ := gov.EndBlocker(ctx, app.govKeeper) - tags.AppendTags(upgrade.EndBlocker(ctx, app.upgradeKeeper)) - - return abci.ResponseEndBlock{ - ValidatorUpdates: validatorUpdates, - Tags: tags, - } -} - -// custom logic for iris initialization -func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { - stateJSON := req.AppStateBytes - - var genesisState GenesisState - err := app.cdc.UnmarshalJSON(stateJSON, &genesisState) - if err != nil { - panic(err) - } - - // load the accounts - for _, gacc := range genesisState.Accounts { - acc := gacc.ToAccount() - acc.AccountNumber = app.accountMapper.GetNextAccountNumber(ctx) - app.accountMapper.SetAccount(ctx, acc) - } - - // load the initial stake information - err = stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData) - if err != nil { - panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 - // return sdk.ErrGenesisParse("").TraceCause(err, "") - } - - gov.InitGenesis(ctx, app.govKeeper, gov.GenesisState{ - StartingProposalID: 1, - DepositProcedure: gov.DepositProcedure{ - MinDeposit: sdk.Coins{sdk.Coin{Denom: "iris", Amount: sdk.NewInt(int64(10)).Mul(gov.Pow10(18))}}, - MaxDepositPeriod: 1440, - }, - VotingProcedure: gov.VotingProcedure{ - VotingPeriod: 30, - }, - TallyingProcedure: gov.TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 100), - }, - }) - - feeTokenGensisConfig := auth.GenesisState{ - FeeTokenNative: "iris", - GasPriceThreshold: 20000000000, // 20(glue), 20*10^9, 1 glue = 10^9 lue/gas, 1 iris = 10^18 lue - } - - auth.InitGenesis(ctx, app.paramsKeeper.Setter(), feeTokenGensisConfig) - - upgrade.InitGenesis(ctx, app.upgradeKeeper, app.Router()) - - return abci.ResponseInitChain{} -} - -// export the state of iris for a genesis file -func (app *IrisApp) ExportAppStateAndValidators() (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) { - ctx := app.NewContext(true, abci.Header{}) - - // iterate to get the accounts - accounts := []GenesisAccount{} - appendAccount := func(acc auth.Account) (stop bool) { - account := NewGenesisAccountI(acc) - accounts = append(accounts, account) - return false - } - app.accountMapper.IterateAccounts(ctx, appendAccount) - - genState := GenesisState{ - Accounts: accounts, - StakeData: stake.WriteGenesis(ctx, app.stakeKeeper), - } - appState, err = wire.MarshalJSONIndent(app.cdc, genState) - if err != nil { - return nil, nil, err - } - validators = stake.WriteValidators(ctx, app.stakeKeeper) - return appState, validators, nil -} - -// Iterates through msgs and executes them -func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) { - // accumulate results - logs := make([]string, 0, len(msgs)) - var data []byte // NOTE: we just append them all (?!) - var tags sdk.Tags // also just append them all - var code sdk.ABCICodeType - for msgIdx, msg := range msgs { - // Match route. - msgType, err := app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) - fmt.Println("============ runMsgs() =========== " + msgType) - if err != nil { - return err.Result() - } - - handler := app.Router().Route(msgType) - if handler == nil { - return sdk.ErrUnknownRequest("Unrecognized Msg type: " + msgType).Result() - } - fmt.Println(msg) - msgResult := handler(ctx, msg) - - // NOTE: GasWanted is determined by ante handler and - // GasUsed by the GasMeter - - // Append Data and Tags - data = append(data, msgResult.Data...) - tags = append(tags, msgResult.Tags...) - - // Stop execution and return on first failed message. - if !msgResult.IsOK() { - logs = append(logs, fmt.Sprintf("Msg %d failed: %s", msgIdx, msgResult.Log)) - code = msgResult.Code - break - } - - // Construct usable logs in multi-message transactions. - logs = append(logs, fmt.Sprintf("Msg %d: %s", msgIdx, msgResult.Log)) - } - - // Set the final gas values. - result = sdk.Result{ - Code: code, - Data: data, - Log: strings.Join(logs, "\n"), - GasUsed: ctx.GasMeter().GasConsumed(), - // TODO: FeeAmount/FeeDenom - Tags: tags, - } - - return result -} - -func (app *IrisApp) replay() int64 { - ctx := server.NewDefaultContext() - ctx.Config.RootDir = viper.GetString(tmcli.HomeFlag) - dbContext := node.DBContext{"state", ctx.Config} - dbType := dbm.DBBackendType(dbContext.Config.DBBackend) - stateDB := dbm.NewDB(dbContext.ID, dbType, dbContext.Config.DBDir()) - - preState := sm.LoadPreState(stateDB) - if preState.LastBlockHeight == 0 { - panic(errors.New("can't replay the last block, last block height is 0")) - } - - sm.SaveState(stateDB, preState) - stateDB.Close() - - return preState.LastBlockHeight -} diff --git a/examples/irishub2/app/context.go b/examples/irishub2/app/context.go deleted file mode 100644 index 6e4b24079..000000000 --- a/examples/irishub2/app/context.go +++ /dev/null @@ -1,96 +0,0 @@ -package app - -import ( - "github.com/cosmos/cosmos-sdk/client/context" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - "fmt" - "io/ioutil" - "strings" - "net/http" - "github.com/cosmos/cosmos-sdk/wire" -) - -type Context struct { - Ctx context.CoreContext - Cdc *wire.Codec -} - - -func NewContext() Context { - return Context{ - Ctx:context.NewCoreContextFromViper(), - } -} - -func (c Context) WithCodeC(cdc *wire.Codec) Context{ - c.Cdc = cdc - return c -} - -func (c Context) BroadcastTxAsync(tx []byte) (*ctypes.ResultBroadcastTx, error) { - return c.Ctx.Client.BroadcastTxAsync(tx) -} - -func (c Context) BroadcastTxSync(tx []byte) (*ctypes.ResultBroadcastTx, error) { - return c.Ctx.Client.BroadcastTxSync(tx) -} - -func (c Context) NetInfo() *ctypes.ResultNetInfo { - client := &http.Client{} - - reqUri := tcpToHttpUrl(c.Ctx.NodeURI) + "/net_info" - - resp, err := client.Get(reqUri) - if err != nil { - fmt.Println(err) - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - fmt.Println(err) - } - - var res = struct { - JsonRpc string `json:"jsonrpc"` - Id string `json:"id"` - Result ctypes.ResultNetInfo `json:"result"` - }{} - if err := c.Cdc.UnmarshalJSON(body,&res); err != nil { - fmt.Println(err) - } - - return &res.Result -} - -func (c Context) NumUnconfirmedTxs() *ctypes.ResultUnconfirmedTxs { - client := &http.Client{} - reqUri := tcpToHttpUrl(c.Ctx.NodeURI) + "/num_unconfirmed_txs" - - resp, err := client.Get(reqUri) - if err != nil { - fmt.Println(err) - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - fmt.Println(err) - } - - var res = struct { - JsonRpc string `json:"jsonrpc"` - Id string `json:"id"` - Result ctypes.ResultUnconfirmedTxs `json:"result"` - }{} - if err := c.Cdc.UnmarshalJSON(body,&res); err != nil { - fmt.Println(err) - } - - return &res.Result -} - -func tcpToHttpUrl(url string) string { - urls := strings.Replace(url, "tcp", "http", 1) - return urls -} diff --git a/examples/irishub2/app/genesis.go b/examples/irishub2/app/genesis.go deleted file mode 100644 index d584c3805..000000000 --- a/examples/irishub2/app/genesis.go +++ /dev/null @@ -1,246 +0,0 @@ -package app - -import ( - "encoding/json" - "errors" - - "github.com/spf13/pflag" - "github.com/tendermint/tendermint/crypto" - tmtypes "github.com/tendermint/tendermint/types" - - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/server/config" - 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" - "math" -) - -// State to Unmarshal -type GenesisState struct { - Accounts []GenesisAccount `json:"accounts"` - StakeData stake.GenesisState `json:"stake"` -} - -// GenesisAccount doesn't need pubkey or sequence -type GenesisAccount struct { - Address sdk.AccAddress `json:"address"` - Coins sdk.Coins `json:"coins"` -} - -func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount { - return GenesisAccount{ - Address: acc.Address, - Coins: acc.Coins, - } -} - -func NewGenesisAccountI(acc auth.Account) GenesisAccount { - return GenesisAccount{ - Address: acc.GetAddress(), - Coins: acc.GetCoins(), - } -} - -// convert GenesisAccount to auth.BaseAccount -func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { - return &auth.BaseAccount{ - Address: ga.Address, - Coins: ga.Coins.Sort(), - } -} - -var ( - flagName = "name" - flagClientHome = "home-client" - flagOWK = "owk" - denom = "iris" - precision = 18 - // bonded tokens given to genesis validators/accounts - freeFermionVal = int64(100) - - totalTokenAmt = sdk.NewInt(200000000) -) - -const defaultUnbondingTime int64 = 60 * 10 - -// get app init parameters for server init command -func IrisAppInit() server.AppInit { - fsAppGenState := pflag.NewFlagSet("", pflag.ContinueOnError) - - fsAppGenTx := pflag.NewFlagSet("", pflag.ContinueOnError) - fsAppGenTx.String(flagName, "", "validator moniker, required") - fsAppGenTx.String(flagClientHome, DefaultCLIHome, - "home directory for the client, used for key generation") - fsAppGenTx.Bool(flagOWK, false, "overwrite the accounts created") - - return server.AppInit{ - FlagsAppGenState: fsAppGenState, - FlagsAppGenTx: fsAppGenTx, - AppGenTx: IrisAppGenTx, - AppGenState: IrisAppGenStateJSON, - } -} - -// simple genesis tx -type IrisGenTx struct { - Name string `json:"name"` - Address sdk.AccAddress `json:"address"` - PubKey string `json:"pub_key"` -} - -// Generate a gaia genesis transaction with flags -func IrisAppGenTx(cdc *wire.Codec, pk crypto.PubKey, genTxConfig config.GenTx) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - - if genTxConfig.Name == "" { - return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)") - } - - var addr sdk.AccAddress - var secret string - addr, secret, err = server.GenerateSaveCoinKey(genTxConfig.CliRoot, genTxConfig.Name, "1234567890", genTxConfig.Overwrite) - if err != nil { - return - } - mm := map[string]string{"secret": secret} - var bz []byte - bz, err = cdc.MarshalJSON(mm) - if err != nil { - return - } - cliPrint = json.RawMessage(bz) - appGenTx, _, validator, err = IrisAppGenTxNF(cdc, pk, addr, genTxConfig.Name) - return -} - -// Generate a gaia genesis transaction without flags -func IrisAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.AccAddress, name string) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - - var bz []byte - gaiaGenTx := IrisGenTx{ - Name: name, - Address: addr, - PubKey: sdk.MustBech32ifyAccPub(pk), - } - bz, err = wire.MarshalJSONIndent(cdc, gaiaGenTx) - if err != nil { - return - } - appGenTx = json.RawMessage(bz) - - validator = tmtypes.GenesisValidator{ - PubKey: pk, - Power: freeFermionVal, - } - return -} - -// Create the core parameters for genesis initialization for gaia -// note that the pubkey input is this machines pubkey -func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState GenesisState, err error) { - - if len(appGenTxs) == 0 { - err = errors.New("must provide at least genesis transaction") - return - } - - // start with the default staking genesis state - //stakeData := stake.DefaultGenesisState() - stakeData := createGenesisState() - - precisionNumber := math.Pow10(int(stakeData.Params.DenomPrecision)) - if precisionNumber > math.MaxInt64 { - panic(errors.New("precision is too high, int64 is overflow")) - } - precisionInt64 := int64(precisionNumber) - tokenPrecision := sdk.NewRat(precisionInt64) - // get genesis flag account information - genaccs := make([]GenesisAccount, len(appGenTxs)) - for i, appGenTx := range appGenTxs { - - var genTx IrisGenTx - err = cdc.UnmarshalJSON(appGenTx, &genTx) - if err != nil { - return - } - - // create the genesis account, give'm few steaks and a buncha token with there name - accAuth := auth.NewBaseAccountWithAddress(genTx.Address) - accAuth.Coins = sdk.Coins{ - {denom, totalTokenAmt.Mul(sdk.NewInt(precisionInt64))}, - } - acc := NewGenesisAccount(&accAuth) - genaccs[i] = acc - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionVal).Mul(tokenPrecision)) // increase the supply - - // add the validator - if len(genTx.Name) > 0 { - desc := stake.NewDescription(genTx.Name, "", "", "") - validator := stake.NewValidator(genTx.Address, - sdk.MustGetAccPubKeyBech32(genTx.PubKey), desc) - - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRat(freeFermionVal).Mul(tokenPrecision)) - - // add some new shares to the validator - var issuedDelShares sdk.Rat - validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, sdk.NewInt(freeFermionVal).Mul(sdk.NewInt(precisionInt64))) - validator.TokenPrecision = stakeData.Params.DenomPrecision - stakeData.Validators = append(stakeData.Validators, validator) - - // create the self-delegation from the issuedDelShares - delegation := stake.Delegation{ - DelegatorAddr: validator.Owner, - ValidatorAddr: validator.Owner, - Shares: issuedDelShares, - Height: 0, - } - - stakeData.Bonds = append(stakeData.Bonds, delegation) - } - } - - // create the final app state - genesisState = GenesisState{ - Accounts: genaccs, - StakeData: stakeData, - } - return -} - -// IrisAppGenState but with JSON -func IrisAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) { - - // create the final app state - genesisState, err := IrisAppGenState(cdc, appGenTxs) - if err != nil { - return nil, err - } - appState, err = wire.MarshalJSONIndent(cdc, genesisState) - return -} - -func createGenesisState() stake.GenesisState { - return stake.GenesisState{ - Pool: stake.Pool{ - LooseTokens: sdk.ZeroRat(), - BondedTokens: sdk.ZeroRat(), - InflationLastTime: 0, - Inflation: sdk.NewRat(7, 100), - DateLastCommissionReset: 0, - PrevBondedShares: sdk.ZeroRat(), - }, - Params: stake.Params{ - InflationRateChange: sdk.NewRat(13, 100), - InflationMax: sdk.NewRat(20, 100), - InflationMin: sdk.NewRat(7, 100), - GoalBonded: sdk.NewRat(67, 100), - UnbondingTime: defaultUnbondingTime, - MaxValidators: 100, - BondDenom: denom, - DenomPrecision: int8(precision), - }, - } -} diff --git a/examples/irishub2/cmd/iris2/main.go b/examples/irishub2/cmd/iris2/main.go deleted file mode 100644 index 87c78a4bd..000000000 --- a/examples/irishub2/cmd/iris2/main.go +++ /dev/null @@ -1,76 +0,0 @@ -package main - -import ( - "encoding/json" - "io" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/server" - "github.com/irisnet/irishub/examples/irishub2/app" - bam "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/irisnet/irishub/version" - - "github.com/spf13/viper" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/cli" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - "github.com/irisnet/irishub/tools/prometheus" -) - -func main() { - cdc := app.MakeCodec() - ctx := server.NewDefaultContext() - cobra.EnableCommandSorting = false - rootCmd := &cobra.Command{ - Use: "iris-bugfix-2", - Short: "iris-bugfix-2 Daemon (server)", - PersistentPreRunE: server.PersistentPreRunEFn(ctx), - } - - rootCmd.PersistentFlags().String("log_level", ctx.Config.LogLevel, "Log level") - - tendermintCmd := &cobra.Command{ - Use: "tendermint", - Short: "Tendermint subcommands", - } - - tendermintCmd.AddCommand( - server.ShowNodeIDCmd(ctx), - server.ShowValidatorCmd(ctx), - ) - - startCmd := server.StartCmd(ctx, server.ConstructAppCreator(newApp, "iris")) - startCmd.Flags().Bool(app.FlagReplay, false, "Replay the last block") - rootCmd.AddCommand( - server.InitCmd(ctx, cdc, app.IrisAppInit()), - startCmd, - server.TestnetFilesCmd(ctx, cdc, app.IrisAppInit()), - server.UnsafeResetAllCmd(ctx), - client.LineBreak, - tendermintCmd, - server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), - client.LineBreak, - version.GetCmdVersion("upgrade", cdc), - ) - - rootCmd.AddCommand(prometheus.MonitorCommand(cdc)) - - // prepare and add flags - executor := cli.PrepareBaseCmd(rootCmd, "IRIS", app.DefaultNodeHome) - executor.Execute() -} - -func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) abci.Application { - return app.NewIrisApp(logger, db, traceStore, bam.SetPruning(viper.GetString("pruning"))) -} - -func exportAppStateAndTMValidators( - logger log.Logger, db dbm.DB, traceStore io.Writer, -) (json.RawMessage, []tmtypes.GenesisValidator, error) { - gApp := app.NewIrisApp(logger, db, traceStore) - return gApp.ExportAppStateAndValidators() -} diff --git a/examples/irishub2/cmd/iriscli2/main.go b/examples/irishub2/cmd/iriscli2/main.go deleted file mode 100644 index 0d71c4ab2..000000000 --- a/examples/irishub2/cmd/iriscli2/main.go +++ /dev/null @@ -1,173 +0,0 @@ -package main - -import ( - "github.com/spf13/cobra" - - "github.com/tendermint/tendermint/libs/cli" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/client/tx" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - ibccmd "github.com/irisnet/irishub/examples/irishub2/ibc/client/cli" - slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" - stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" - "github.com/irisnet/irishub/examples/irishub2/app" - c "github.com/irisnet/irishub/client" - govcmd "github.com/cosmos/cosmos-sdk/x/gov/client/cli" - upgradecmd "github.com/irisnet/irishub/modules/upgrade/client/cli" - "github.com/irisnet/irishub/version" -) - -// rootCmd is the entry point for this binary -var ( - rootCmd = &cobra.Command{ - Use: "iriscli-bugfix-2", - Short: "irishub2 light-client", - } -) - -func main() { - cobra.EnableCommandSorting = false - cdc := app.MakeCodec() - - // TODO: setup keybase, viper object, etc. to be passed into - // the below functions and eliminate global vars, like we do - // with the cdc - - // add standard rpc commands - rpc.AddCommands(rootCmd) - - //Add state commands - tendermintCmd := &cobra.Command{ - Use: "tendermint", - Short: "Tendermint state querying subcommands", - } - tendermintCmd.AddCommand( - rpc.BlockCommand(), - rpc.ValidatorCommand(), - ) - tx.AddCommands(tendermintCmd, cdc) - - //Add IBC commands - ibcCmd := &cobra.Command{ - Use: "ibc", - Short: "Inter-Blockchain Communication subcommands", - } - ibcCmd.AddCommand( - client.PostCommands( - ibccmd.IBCTransferCmd(cdc), - ibccmd.IBCRelayCmd(cdc), - ibccmd.IBCSetCmd(cdc), - ibccmd.IBCGetCmd(cdc), - )...) - - advancedCmd := &cobra.Command{ - Use: "advanced", - Short: "Advanced subcommands", - } - - advancedCmd.AddCommand( - tendermintCmd, - ibcCmd, - c.ServeCommand(cdc), - ) - rootCmd.AddCommand( - advancedCmd, - client.LineBreak, - ) - - //Add stake commands - stakeCmd := &cobra.Command{ - Use: "stake", - Short: "Stake and validation subcommands", - } - stakeCmd.AddCommand( - client.GetCommands( - stakecmd.GetCmdQueryValidator("stake", cdc), - stakecmd.GetCmdQueryValidators("stake", cdc), - stakecmd.GetCmdQueryDelegation("stake", cdc), - stakecmd.GetCmdQueryDelegations("stake", cdc), - slashingcmd.GetCmdQuerySigningInfo("slashing", cdc), - )...) - stakeCmd.AddCommand( - client.PostCommands( - stakecmd.GetCmdCreateValidator(cdc), - stakecmd.GetCmdEditValidator(cdc), - stakecmd.GetCmdDelegate(cdc), - stakecmd.GetCmdUnbond("stake", cdc), - stakecmd.GetCmdRedelegate("stake", cdc), - slashingcmd.GetCmdUnrevoke(cdc), - )...) - rootCmd.AddCommand( - stakeCmd, - ) - - //Add gov commands - govCmd := &cobra.Command{ - Use: "gov", - Short: "Governance and voting subcommands", - } - govCmd.AddCommand( - client.GetCommands( - govcmd.GetCmdQueryProposal("gov", cdc), - govcmd.GetCmdQueryVote("gov", cdc), - )...) - govCmd.AddCommand( - client.PostCommands( - govcmd.GetCmdSubmitProposal(cdc), - govcmd.GetCmdDeposit(cdc), - govcmd.GetCmdVote(cdc), - )...) - rootCmd.AddCommand( - govCmd, - ) - - //Add upgrade commands - upgradeCmd := &cobra.Command{ - Use: "upgrade", - Short: "Software Upgrade subcommands", - } - upgradeCmd.AddCommand( - client.GetCommands( - upgradecmd.GetCmdQuerySwitch("upgrade", cdc), - upgradecmd.GetCmdInfo("upgrade", cdc), - )...) - upgradeCmd.AddCommand( - client.PostCommands( - upgradecmd.GetCmdSubmitSwitch(cdc), - )...) - rootCmd.AddCommand( - upgradeCmd, - ) - - //Add auth and bank commands - rootCmd.AddCommand( - client.GetCommands( - authcmd.GetAccountCmd("acc", cdc, authcmd.GetAccountDecoder(cdc)), - )...) - rootCmd.AddCommand( - client.PostCommands( - bankcmd.SendTxCmd(cdc), - )...) - - // add proxy, version and key info - rootCmd.AddCommand( - keys.Commands(), - client.LineBreak, - ) - rootCmd.AddCommand( - client.GetCommands( - version.GetCmdVersion("upgrade", cdc), - )...) - - // prepare and add flags - executor := cli.PrepareMainCmd(rootCmd, "GA", app.DefaultCLIHome) - err := executor.Execute() - if err != nil { - // handle with #870 - panic(err) - } -} diff --git a/examples/irishub2/ibc/client/cli/README.md b/examples/irishub2/ibc/client/cli/README.md deleted file mode 100644 index ab9e8e555..000000000 --- a/examples/irishub2/ibc/client/cli/README.md +++ /dev/null @@ -1,157 +0,0 @@ -# IBC Doubble Hubble - -## Remove remaining data - -```console -> rm -r ~/.chain1 -> rm -r ~/.chain2 -> rm -r ~/.basecli -``` - -## Initialize both chains - -```console -> basecoind init --home ~/.chain1 -I[04-02|14:03:33.704] Generated private validator module=main path=/home/mossid/.chain1/config/priv_validator.json -I[04-02|14:03:33.705] Generated genesis file module=main path=/home/mossid/.chain1/config/genesis.json -{ - "secret": "crunch ignore trigger neither differ dance cheap brick situate floor luxury citizen husband decline arrow abandon", - "account": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "validator": { - "pub_key": { - "type": "ed25519", - "data": "8C9917D5E982E221F5A1450103102B44BBFC1E8768126C606246CB37B5794F4D" - }, - "power": 10, - "name": "" - }, - "node_id": "3ac8e6242315fd62143dc3e52c161edaaa6b1a64", - "chain_id": "test-chain-ZajMfr" -} -> ADDR1=C69FEB398A29AAB1B3C4F07DE22208F35E711BCC -> ID1=test-chain-ZajMfr -> NODE1=tcp://0.0.0.0:36657 -> basecli keys add key1 --recover -Enter a passphrase for your key: -Repeat the passphrase: -Enter your recovery seed phrase: -crunch ignore trigger neither differ dance cheap brick situate floor luxury citizen husband decline arrow abandon -key1 C69FEB398A29AAB1B3C4F07DE22208F35E711BCC - - -> basecoind init --home ~/.chain2 -I[04-02|14:09:14.453] Generated private validator module=main path=/home/mossid/.chain2/config/priv_validator.json -I[04-02|14:09:14.453] Generated genesis file module=main path=/home/mossid/.chain2/config/genesis.json -{ - "secret": "age guide awesome month female left oxygen soccer define high grocery work desert dinner arena abandon", - "account": "DC26002735D3AA9573707CFA6D77C12349E49868", - "validator": { - "pub_key": { - "type": "ed25519", - "data": "A94FE4B9AD763D301F4DD5A2766009812495FB7A79F1275FB8A5AF09B44FD5F3" - }, - "power": 10, - "name": "" - }, - "node_id": "ad26831330e1c72b85276d53c20f0680e6fd4cf5" - "chain_id": "test-chain-4XHTPn" -} -> ADDR2=DC26002735D3AA9573707CFA6D77C12349E49868 -> ID2=test-chain-4XHTPn -> NODE2=tcp://0.0.0.0:26657 -> basecli keys add key2 --recover -Enter a passphrase for your key: -Repeat the passphrase: -Enter your recovery seed phrase: -age guide awesome month female left oxygen soccer define high grocery work desert dinner arena abandon -key2 DC26002735D3AA9573707CFA6D77C12349E49868 - - -> basecoind start --home ~/.chain1 --address tcp://0.0.0.0:36658 --rpc.laddr tcp://0.0.0.0:36657 --p2p.laddr tcp://0.0.0.0:36656 -... - -> basecoind start --home ~/.chain2 # --address tcp://0.0.0.0:26658 --rpc.laddr tcp://0.0.0.0:26657 --p2p.laddr tcp://0.0.0.0:26656 -... -``` -## Check balance - -```console -> basecli account $ADDR1 --node $NODE1 -{ - "address": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740992 - } - ], - "public_key": null, - "sequence": 0, - "name": "" -} - -> basecli account $ADDR2 --node $NODE2 -{ - "address": "DC26002735D3AA9573707CFA6D77C12349E49868", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740992 - } - ], - "public_key": null, - "sequence": 0, - "name": "" -} - -``` - -## Transfer coins (addr1:chain1 -> addr2:chain2) - -```console -> basecli transfer --from key1 --to $ADDR2 --amount 10mycoin --chain $ID2 --chain-id $ID1 --node $NODE1 -Password to sign with 'key1': -Committed at block 1022. Hash: E16019DCC4AA08CA70AFCFBC96028ABCC51B6AD0 -> basecli account $ADDR1 --node $NODE1 -{ - "address": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740982 - } - ], - "public_key": { - "type": "ed25519", - "data": "9828FF1780A066A0D93D840737566B697035448D6C880807322BED8919348B2B" - }, - "sequence": 1, - "name": "" -} -``` - -## Relay IBC packets - -```console -> basecli relay --from key2 --from-chain-id $ID1 --from-chain-node $NODE1 --to-chain-id $ID2 --to-chain-node $NODE2 --chain-id $ID2 -Password to sign with 'key2': -I[04-03|16:18:59.984] Detected IBC packet number=0 -I[04-03|16:19:00.869] Relayed IBC packet number=0 -> basecli account $ADDR2 --node $NODE2 -{ - "address": "DC26002735D3AA9573707CFA6D77C12349E49868", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254741002 - } - ], - "public_key": { - "type": "ed25519", - "data": "F52B4FA545F4E9BFE5D7AF1DD2236899FDEF905F9B3057C38D7C01BF1B8EB52E" - }, - "sequence": 1, - "name": "" -} - -``` diff --git a/examples/irishub2/ibc/client/cli/ibctx.go b/examples/irishub2/ibc/client/cli/ibctx.go deleted file mode 100644 index f5505d9a4..000000000 --- a/examples/irishub2/ibc/client/cli/ibctx.go +++ /dev/null @@ -1,81 +0,0 @@ -package cli - -import ( - "encoding/hex" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" - - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - "github.com/cosmos/cosmos-sdk/x/ibc" -) - -const ( - flagTo = "to" - flagAmount = "amount" - flagChain = "chain" -) - -// IBC transfer command -func IBCTransferCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "transfer", - RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) - - // get the from address - from, err := ctx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg, err := buildMsg(from) - if err != nil { - return err - } - - // get password - err = ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, []sdk.Msg{msg}, cdc) - if err != nil { - return err - } - return nil - }, - } - - cmd.Flags().String(flagTo, "", "Address to send coins") - cmd.Flags().String(flagAmount, "", "Amount of coins to send") - cmd.Flags().String(flagChain, "", "Destination chain to send coins") - return cmd -} - -func buildMsg(from sdk.AccAddress) (sdk.Msg, error) { - amount := viper.GetString(flagAmount) - coins, err := sdk.ParseCoins(amount) - if err != nil { - return nil, err - } - - dest := viper.GetString(flagTo) - bz, err := hex.DecodeString(dest) - if err != nil { - return nil, err - } - to := sdk.AccAddress(bz) - - packet := ibc.NewIBCPacket(from, to, coins, viper.GetString(client.FlagChainID), - viper.GetString(flagChain)) - - msg := ibc.IBCTransferMsg{ - IBCPacket: packet, - } - - return msg, nil -} diff --git a/examples/irishub2/ibc/client/cli/relay.go b/examples/irishub2/ibc/client/cli/relay.go deleted file mode 100644 index 58d8f272b..000000000 --- a/examples/irishub2/ibc/client/cli/relay.go +++ /dev/null @@ -1,200 +0,0 @@ -package cli - -import ( - "os" - "time" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/tendermint/tendermint/libs/log" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/auth" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - "github.com/cosmos/cosmos-sdk/x/ibc" -) - -// flags -const ( - FlagFromChainID = "from-chain-id" - FlagFromChainNode = "from-chain-node" - FlagToChainID = "to-chain-id" - FlagToChainNode = "to-chain-node" -) - -type relayCommander struct { - cdc *wire.Codec - address sdk.AccAddress - decoder auth.AccountDecoder - mainStore string - ibcStore string - accStore string - - logger log.Logger -} - -// IBC relay command -func IBCRelayCmd(cdc *wire.Codec) *cobra.Command { - cmdr := relayCommander{ - cdc: cdc, - decoder: authcmd.GetAccountDecoder(cdc), - ibcStore: "ibc", - mainStore: "main", - accStore: "acc", - - logger: log.NewTMLogger(log.NewSyncWriter(os.Stdout)), - } - - cmd := &cobra.Command{ - Use: "relay", - Run: cmdr.runIBCRelay, - } - - cmd.Flags().String(FlagFromChainID, "", "Chain ID for ibc node to check outgoing packets") - cmd.Flags().String(FlagFromChainNode, "tcp://localhost:26657", ": to tendermint rpc interface for this chain") - cmd.Flags().String(FlagToChainID, "", "Chain ID for ibc node to broadcast incoming packets") - cmd.Flags().String(FlagToChainNode, "tcp://localhost:36657", ": to tendermint rpc interface for this chain") - - cmd.MarkFlagRequired(FlagFromChainID) - cmd.MarkFlagRequired(FlagFromChainNode) - cmd.MarkFlagRequired(FlagToChainID) - cmd.MarkFlagRequired(FlagToChainNode) - - viper.BindPFlag(FlagFromChainID, cmd.Flags().Lookup(FlagFromChainID)) - viper.BindPFlag(FlagFromChainNode, cmd.Flags().Lookup(FlagFromChainNode)) - viper.BindPFlag(FlagToChainID, cmd.Flags().Lookup(FlagToChainID)) - viper.BindPFlag(FlagToChainNode, cmd.Flags().Lookup(FlagToChainNode)) - - return cmd -} - -// nolint: unparam -func (c relayCommander) runIBCRelay(cmd *cobra.Command, args []string) { - fromChainID := viper.GetString(FlagFromChainID) - fromChainNode := viper.GetString(FlagFromChainNode) - toChainID := viper.GetString(FlagToChainID) - toChainNode := viper.GetString(FlagToChainNode) - address, err := context.NewCoreContextFromViper().GetFromAddress() - if err != nil { - panic(err) - } - c.address = address - - c.loop(fromChainID, fromChainNode, toChainID, toChainNode) -} - -// This is nolinted as someone is in the process of refactoring this to remove the goto -// nolint: gocyclo -func (c relayCommander) loop(fromChainID, fromChainNode, toChainID, - toChainNode string) { - - ctx := context.NewCoreContextFromViper() - // get password - passphrase, err := ctx.GetPassphraseFromStdin(ctx.FromAddressName) - if err != nil { - panic(err) - } - - ingressKey := ibc.IngressSequenceKey(fromChainID) - -OUTER: - for { - time.Sleep(5 * time.Second) - - processedbz, err := query(toChainNode, ingressKey, c.ibcStore) - if err != nil { - panic(err) - } - - var processed int64 - if processedbz == nil { - processed = 0 - } else if err = c.cdc.UnmarshalBinary(processedbz, &processed); err != nil { - panic(err) - } - - lengthKey := ibc.EgressLengthKey(toChainID) - egressLengthbz, err := query(fromChainNode, lengthKey, c.ibcStore) - if err != nil { - c.logger.Error("error querying outgoing packet list length", "err", err) - continue OUTER //TODO replace with continue (I think it should just to the correct place where OUTER is now) - } - var egressLength int64 - if egressLengthbz == nil { - egressLength = 0 - } else if err = c.cdc.UnmarshalBinary(egressLengthbz, &egressLength); err != nil { - panic(err) - } - if egressLength > processed { - c.logger.Info("Detected IBC packet", "number", egressLength-1) - } - - seq := c.getSequence(toChainNode) - - for i := processed; i < egressLength; i++ { - egressbz, err := query(fromChainNode, ibc.EgressKey(toChainID, i), c.ibcStore) - if err != nil { - c.logger.Error("error querying egress packet", "err", err) - continue OUTER // TODO replace to break, will break first loop then send back to the beginning (aka OUTER) - } - - err = c.broadcastTx(seq, toChainNode, c.refine(egressbz, i, passphrase)) - seq++ - if err != nil { - c.logger.Error("error broadcasting ingress packet", "err", err) - continue OUTER // TODO replace to break, will break first loop then send back to the beginning (aka OUTER) - } - - c.logger.Info("Relayed IBC packet", "number", i) - } - } -} - -func query(node string, key []byte, storeName string) (res []byte, err error) { - return context.NewCoreContextFromViper().WithNodeURI(node).QueryStore(key, storeName) -} - -func (c relayCommander) broadcastTx(seq int64, node string, tx []byte) error { - _, err := context.NewCoreContextFromViper().WithNodeURI(node).WithSequence(seq + 1).BroadcastTx(tx) - return err -} - -func (c relayCommander) getSequence(node string) int64 { - res, err := query(node, c.address, c.accStore) - if err != nil { - panic(err) - } - if nil != res { - account, err := c.decoder(res) - if err != nil { - panic(err) - } - - return account.GetSequence() - } - - return 0 -} - -func (c relayCommander) refine(bz []byte, sequence int64, passphrase string) []byte { - var packet ibc.IBCPacket - if err := c.cdc.UnmarshalBinary(bz, &packet); err != nil { - panic(err) - } - - msg := ibc.IBCReceiveMsg{ - IBCPacket: packet, - Relayer: c.address, - Sequence: sequence, - } - - ctx := context.NewCoreContextFromViper().WithSequence(sequence) - res, err := ctx.SignAndBuild(ctx.FromAddressName, passphrase, []sdk.Msg{msg}, c.cdc) - if err != nil { - panic(err) - } - return res -} diff --git a/examples/irishub2/ibc/client/cli/tx.go b/examples/irishub2/ibc/client/cli/tx.go deleted file mode 100644 index eb73cc0bf..000000000 --- a/examples/irishub2/ibc/client/cli/tx.go +++ /dev/null @@ -1,66 +0,0 @@ -package cli - -import ( - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - "github.com/irisnet/irishub/examples/irishub2/ibc" -) - -// IBC transfer command -func IBCGetCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "get", - RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) - - // get the from address - from, err := ctx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg := ibc.NewIBCGetMsg(from) - - // get password - err = ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, []sdk.Msg{msg}, cdc) - if err != nil { - return err - } - return nil - }, - } - return cmd -} - - -// IBC transfer command -func IBCSetCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "set", - RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) - - // get the from address - from, err := ctx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg := ibc.NewIBCSetMsg(from) - - // get password - err = ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, []sdk.Msg{msg}, cdc) - if err != nil { - return err - } - return nil - }, - } - return cmd -} - diff --git a/examples/irishub2/ibc/client/rest/transfer.go b/examples/irishub2/ibc/client/rest/transfer.go deleted file mode 100644 index bee9f955f..000000000 --- a/examples/irishub2/ibc/client/rest/transfer.go +++ /dev/null @@ -1,103 +0,0 @@ -package rest - -import ( - "io/ioutil" - "net/http" - - "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/gorilla/mux" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/ibc" -) - -// RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { - r.HandleFunc("/ibc/{destchain}/{address}/send", TransferRequestHandlerFn(cdc, kb, ctx)).Methods("POST") -} - -type transferBody struct { - // Fees sdk.Coin `json="fees"` - Amount sdk.Coins `json:"amount"` - LocalAccountName string `json:"name"` - Password string `json:"password"` - SrcChainID string `json:"src_chain_id"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` - Gas int64 `json:"gas"` -} - -// TransferRequestHandler - http request handler to transfer coins to a address -// on a different chain via IBC -func TransferRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - // collect data - vars := mux.Vars(r) - destChainID := vars["destchain"] - bech32addr := vars["address"] - - to, err := sdk.AccAddressFromBech32(bech32addr) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - var m transferBody - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - err = cdc.UnmarshalJSON(body, &m) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - info, err := kb.Get(m.LocalAccountName) - if err != nil { - w.WriteHeader(http.StatusUnauthorized) - w.Write([]byte(err.Error())) - return - } - - // build message - packet := ibc.NewIBCPacket(sdk.AccAddress(info.GetPubKey().Address()), to, m.Amount, m.SrcChainID, destChainID) - msg := ibc.IBCTransferMsg{packet} - - // add gas to context - ctx = ctx.WithGas(m.Gas) - - // sign - ctx = ctx.WithAccountNumber(m.AccountNumber) - ctx = ctx.WithSequence(m.Sequence) - 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 - } - - // send - res, err := ctx.BroadcastTx(txBytes) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - output, err := cdc.MarshalJSON(res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - w.Write(output) - } -} diff --git a/examples/irishub2/ibc/errors.go b/examples/irishub2/ibc/errors.go deleted file mode 100644 index 7a3194baf..000000000 --- a/examples/irishub2/ibc/errors.go +++ /dev/null @@ -1,50 +0,0 @@ -package ibc - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// IBC errors reserve 200 ~ 299. -const ( - DefaultCodespace sdk.CodespaceType = 3 - - // IBC errors reserve 200 - 299. - CodeInvalidSequence sdk.CodeType = 200 - CodeIdenticalChains sdk.CodeType = 201 - CodeUnknownRequest sdk.CodeType = sdk.CodeUnknownRequest -) - -func codeToDefaultMsg(code sdk.CodeType) string { - switch code { - case CodeInvalidSequence: - return "invalid IBC packet sequence" - case CodeIdenticalChains: - return "source and destination chain cannot be identical" - default: - return sdk.CodeToDefaultMsg(code) - } -} - -// nolint -func ErrInvalidSequence(codespace sdk.CodespaceType) sdk.Error { - return newError(codespace, CodeInvalidSequence, "") -} -func ErrIdenticalChains(codespace sdk.CodespaceType) sdk.Error { - return newError(codespace, CodeIdenticalChains, "") -} - -// ------------------------- -// Helpers - -// nolint: unparam -func newError(codespace sdk.CodespaceType, code sdk.CodeType, msg string) sdk.Error { - msg = msgOrDefaultMsg(msg, code) - return sdk.NewError(codespace, code, msg) -} - -func msgOrDefaultMsg(msg string, code sdk.CodeType) string { - if msg != "" { - return msg - } - return codeToDefaultMsg(code) -} diff --git a/examples/irishub2/ibc/handler.go b/examples/irishub2/ibc/handler.go deleted file mode 100644 index 99addf31a..000000000 --- a/examples/irishub2/ibc/handler.go +++ /dev/null @@ -1,76 +0,0 @@ -package ibc - -import ( - "reflect" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" -) - -func NewHandler(ibcm Mapper, ck bank.Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { - switch msg := msg.(type) { - case IBCTransferMsg: - return handleIBCTransferMsg(ctx, ibcm, ck, msg) - case IBCReceiveMsg: - return handleIBCReceiveMsg(ctx, ibcm, ck, msg) - case IBCGetMsg: - return handleIBCGetMsg(ctx, ibcm, ck, msg) - case IBCSetMsg: - return handleIBCSetMsg(ctx, ibcm, ck, msg) - default: - errMsg := "Unrecognized IBC Msg type: " + reflect.TypeOf(msg).Name() - return sdk.ErrUnknownRequest(errMsg).Result() - } - } -} - -// IBCTransferMsg deducts coins from the account and creates an egress IBC packet. -func handleIBCTransferMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCTransferMsg) sdk.Result { - packet := msg.IBCPacket - - _, _, err := ck.SubtractCoins(ctx, packet.SrcAddr, packet.Coins) - if err != nil { - return err.Result() - } - - err = ibcm.PostIBCPacket(ctx, packet) - if err != nil { - return err.Result() - } - - return sdk.Result{} -} - -// IBCReceiveMsg adds coins to the destination address and creates an ingress IBC packet. -func handleIBCReceiveMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCReceiveMsg) sdk.Result { - packet := msg.IBCPacket - - seq := ibcm.GetIngressSequence(ctx, packet.SrcChain) - if msg.Sequence != seq { - return ErrInvalidSequence(ibcm.codespace).Result() - } - - _, _, err := ck.AddCoins(ctx, packet.DestAddr, packet.Coins) - if err != nil { - return err.Result() - } - - ibcm.SetIngressSequence(ctx, packet.SrcChain, seq+1) - - return sdk.Result{} -} - - - -// IBCTransferMsg deducts coins from the account and creates an egress IBC packet. -func handleIBCSetMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCSetMsg) sdk.Result { - ibcm.Set(ctx,msg.Addr.String()+":ibc-2") - return sdk.Result{Log:"This is new module - ibc2 !!"} -} - -// IBCReceiveMsg adds coins to the destination address and creates an ingress IBC packet. -func handleIBCGetMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCGetMsg) sdk.Result { - AddrString,_:=ibcm.Get(ctx) - return sdk.Result{Log:AddrString} -} diff --git a/examples/irishub2/ibc/mapper.go b/examples/irishub2/ibc/mapper.go deleted file mode 100644 index 2ccc93d1a..000000000 --- a/examples/irishub2/ibc/mapper.go +++ /dev/null @@ -1,149 +0,0 @@ -package ibc - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" -) - -// IBC Mapper -type Mapper struct { - key sdk.StoreKey - cdc *wire.Codec - codespace sdk.CodespaceType -} - -// XXX: The Mapper should not take a CoinKeeper. Rather have the CoinKeeper -// take an Mapper. -func NewMapper(cdc *wire.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) Mapper { - // XXX: How are these codecs supposed to work? - return Mapper{ - key: key, - cdc: cdc, - codespace: codespace, - } -} - -// XXX: This is not the public API. This will change in MVP2 and will henceforth -// only be invoked from another module directly and not through a user -// transaction. -// TODO: Handle invalid IBC packets and return errors. -func (ibcm Mapper) PostIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error { - // write everything into the state - store := ctx.KVStore(ibcm.key) - index := ibcm.getEgressLength(store, packet.DestChain) - bz, err := ibcm.cdc.MarshalBinary(packet) - if err != nil { - panic(err) - } - - store.Set(EgressKey(packet.DestChain, index), bz) - bz, err = ibcm.cdc.MarshalBinary(index + 1) - if err != nil { - panic(err) - } - store.Set(EgressLengthKey(packet.DestChain), bz) - - return nil -} - -// XXX: In the future every module is able to register it's own handler for -// handling it's own IBC packets. The "ibc" handler will only route the packets -// to the appropriate callbacks. -// XXX: For now this handles all interactions with the CoinKeeper. -// XXX: This needs to do some authentication checking. -func (ibcm Mapper) ReceiveIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error { - return nil -} - -// -------------------------- -// Functions for accessing the underlying KVStore. - -func marshalBinaryPanic(cdc *wire.Codec, value interface{}) []byte { - res, err := cdc.MarshalBinary(value) - if err != nil { - panic(err) - } - return res -} - -func unmarshalBinaryPanic(cdc *wire.Codec, bz []byte, ptr interface{}) { - err := cdc.UnmarshalBinary(bz, ptr) - if err != nil { - panic(err) - } -} - -// TODO add description -func (ibcm Mapper) GetIngressSequence(ctx sdk.Context, srcChain string) int64 { - store := ctx.KVStore(ibcm.key) - key := IngressSequenceKey(srcChain) - - bz := store.Get(key) - if bz == nil { - zero := marshalBinaryPanic(ibcm.cdc, int64(0)) - store.Set(key, zero) - return 0 - } - - var res int64 - unmarshalBinaryPanic(ibcm.cdc, bz, &res) - return res -} - -// TODO add description -func (ibcm Mapper) SetIngressSequence(ctx sdk.Context, srcChain string, sequence int64) { - store := ctx.KVStore(ibcm.key) - key := IngressSequenceKey(srcChain) - - bz := marshalBinaryPanic(ibcm.cdc, sequence) - store.Set(key, bz) -} - -// Retrieves the index of the currently stored outgoing IBC packets. -func (ibcm Mapper) getEgressLength(store sdk.KVStore, destChain string) int64 { - bz := store.Get(EgressLengthKey(destChain)) - if bz == nil { - zero := marshalBinaryPanic(ibcm.cdc, int64(0)) - store.Set(EgressLengthKey(destChain), zero) - return 0 - } - var res int64 - unmarshalBinaryPanic(ibcm.cdc, bz, &res) - return res -} - -// Stores an outgoing IBC packet under "egress/chain_id/index". -func EgressKey(destChain string, index int64) []byte { - return []byte(fmt.Sprintf("egress/%s/%d", destChain, index)) -} - -// Stores the number of outgoing IBC packets under "egress/index". -func EgressLengthKey(destChain string) []byte { - return []byte(fmt.Sprintf("egress/%s", destChain)) -} - -// Stores the sequence number of incoming IBC packet under "ingress/index". -func IngressSequenceKey(srcChain string) []byte { - return []byte(fmt.Sprintf("ingress/%s", srcChain)) -} - - -// Gets the vote of a specific voter on a specific proposal -func (ibcm Mapper) Get(ctx sdk.Context) (string, bool) { - store := ctx.KVStore(ibcm.key) - bz := store.Get([]byte("ibcaddr")) - if bz == nil { - return " ", false - } - var Addr string - ibcm.cdc.MustUnmarshalBinary(bz, &Addr) - return Addr, true -} - -func (ibcm Mapper) Set(ctx sdk.Context,Addr string) { - store := ctx.KVStore(ibcm.key) - bz := ibcm.cdc.MustMarshalBinary(Addr) - store.Set([]byte("ibcaddr"), bz) -} \ No newline at end of file diff --git a/examples/irishub2/ibc/types.go b/examples/irishub2/ibc/types.go deleted file mode 100644 index b60b423cc..000000000 --- a/examples/irishub2/ibc/types.go +++ /dev/null @@ -1,184 +0,0 @@ -package ibc - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" -) - -var ( - msgCdc *wire.Codec -) - -func init() { - msgCdc = wire.NewCodec() -} - -// ------------------------------ -// IBCPacket - -// nolint - TODO rename to Packet as IBCPacket stutters (golint) -// IBCPacket defines a piece of data that can be send between two separate -// blockchains. -type IBCPacket struct { - SrcAddr sdk.AccAddress - DestAddr sdk.AccAddress - Coins sdk.Coins - SrcChain string - DestChain string -} - -func NewIBCPacket(srcAddr sdk.AccAddress, destAddr sdk.AccAddress, coins sdk.Coins, - srcChain string, destChain string) IBCPacket { - - return IBCPacket{ - SrcAddr: srcAddr, - DestAddr: destAddr, - Coins: coins, - SrcChain: srcChain, - DestChain: destChain, - } -} - -//nolint -func (p IBCPacket) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(p) - if err != nil { - panic(err) - } - return sdk.MustSortJSON(b) -} - -// validator the ibc packey -func (p IBCPacket) ValidateBasic() sdk.Error { - if p.SrcChain == p.DestChain { - return ErrIdenticalChains(DefaultCodespace).TraceSDK("") - } - if !p.Coins.IsValid() { - return sdk.ErrInvalidCoins("") - } - return nil -} - -// ---------------------------------- -// IBCTransferMsg - -// nolint - TODO rename to TransferMsg as folks will reference with ibc.TransferMsg -// IBCTransferMsg defines how another module can send an IBCPacket. -type IBCTransferMsg struct { - IBCPacket -} - -// nolint -func (msg IBCTransferMsg) Type() string { return "ibc-2" } - -// x/bank/tx.go MsgSend.GetSigners() -func (msg IBCTransferMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.SrcAddr} } - -// get the sign bytes for ibc transfer message -func (msg IBCTransferMsg) GetSignBytes() []byte { - return msg.IBCPacket.GetSignBytes() -} - -// validate ibc transfer message -func (msg IBCTransferMsg) ValidateBasic() sdk.Error { - return msg.IBCPacket.ValidateBasic() -} - -// ---------------------------------- -// IBCReceiveMsg - -// nolint - TODO rename to ReceiveMsg as folks will reference with ibc.ReceiveMsg -// IBCReceiveMsg defines the message that a relayer uses to post an IBCPacket -// to the destination chain. -type IBCReceiveMsg struct { - IBCPacket - Relayer sdk.AccAddress - Sequence int64 -} - -// nolint -func (msg IBCReceiveMsg) Type() string { return "ibc-2" } -func (msg IBCReceiveMsg) ValidateBasic() sdk.Error { return msg.IBCPacket.ValidateBasic() } - -// x/bank/tx.go MsgSend.GetSigners() -func (msg IBCReceiveMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Relayer} } - -// get the sign bytes for ibc receive message -func (msg IBCReceiveMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(struct { - IBCPacket json.RawMessage - Relayer sdk.AccAddress - Sequence int64 - }{ - IBCPacket: json.RawMessage(msg.IBCPacket.GetSignBytes()), - Relayer: msg.Relayer, - Sequence: msg.Sequence, - }) - if err != nil { - panic(err) - } - return sdk.MustSortJSON(b) -} - - -type IBCSetMsg struct { - Addr sdk.AccAddress -} - -func NewIBCSetMsg(addr sdk.AccAddress) IBCSetMsg { - return IBCSetMsg{ - Addr:addr, - } -} - -func (msg IBCSetMsg) Type() string { - return "ibc-2" -} - -func (msg IBCSetMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(msg) - if err != nil { - panic(err) - } - return b -} - -func (msg IBCSetMsg) ValidateBasic() sdk.Error { - return nil -} - -func (msg IBCSetMsg) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Addr} -} - -type IBCGetMsg struct { - Addr sdk.AccAddress -} - -func NewIBCGetMsg(addr sdk.AccAddress) IBCGetMsg { - return IBCGetMsg{ - Addr:addr, - } -} - -func (msg IBCGetMsg) Type() string { - return "ibc-2" -} - -func (msg IBCGetMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(msg) - if err != nil { - panic(err) - } - return b -} - -func (msg IBCGetMsg) ValidateBasic() sdk.Error { - return nil -} - -func (msg IBCGetMsg) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Addr} -} diff --git a/examples/irishub2/ibc/wire.go b/examples/irishub2/ibc/wire.go deleted file mode 100644 index 821a527ab..000000000 --- a/examples/irishub2/ibc/wire.go +++ /dev/null @@ -1,13 +0,0 @@ -package ibc - -import ( - "github.com/cosmos/cosmos-sdk/wire" -) - -// Register concrete types on wire codec -func RegisterWire(cdc *wire.Codec) { - cdc.RegisterConcrete(IBCTransferMsg{}, "cosmos-sdk/IBCTransferMsg/2", nil) - cdc.RegisterConcrete(IBCReceiveMsg{}, "cosmos-sdk/IBCReceiveMsg/2", nil) - cdc.RegisterConcrete(IBCSetMsg{},"cosmos-sdk/IBCSetMsg/2",nil) - cdc.RegisterConcrete(IBCGetMsg{},"cosmos-sdk/IBCGetMsg/2",nil) -} From 2663852f7210b653a96cf7276bfa45bb971ba21a Mon Sep 17 00:00:00 2001 From: programokey <872127164@qq.com> Date: Sun, 2 Sep 2018 23:08:51 -0700 Subject: [PATCH 075/124] IRISHUB-272: fix the bug that the monitor didn't correctly close opened processes. --- tools/prometheus/system/metrics.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/prometheus/system/metrics.go b/tools/prometheus/system/metrics.go index 20ca055c5..9a73a7716 100644 --- a/tools/prometheus/system/metrics.go +++ b/tools/prometheus/system/metrics.go @@ -237,6 +237,7 @@ func getProcessNum(command string) (num int, err error) { fmt.Println("Error:Invalid command,", err) return 0, err } + defer cmd.Wait() bytes, err := ioutil.ReadAll(stdout) if err != nil { @@ -276,6 +277,7 @@ func getPid(command string) (pid int, err error) { fmt.Println("Error:Invalid command,", err) return 0, err } + defer cmd.Wait() bytes, err := ioutil.ReadAll(stdout) if err != nil { From 7133ad6939f9838c85c151e30577c7c839c1550c Mon Sep 17 00:00:00 2001 From: Raymond Date: Wed, 5 Sep 2018 17:09:48 +0800 Subject: [PATCH 076/124] update cosmos-sdk deps to v0.23.0-iris3 --- Gopkg.lock | 14 +++++++------- Gopkg.toml | 4 ++-- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index ddda939e7..4020ec69f 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -35,7 +35,7 @@ branch = "master" name = "github.com/btcsuite/btcd" packages = ["btcec"] - revision = "79e00513b1011888b1e675157ab89f527f901cae" + revision = "cff30e1d23fc9e800b2b5b4b41ef1817dda07e9f" [[projects]] name = "github.com/btcsuite/btcutil" @@ -88,9 +88,9 @@ "x/stake/tags", "x/stake/types" ] - revision = "bd1cb52b2d2e04230ff43d10514b5e988f2038cb" + revision = "ee0aed6ca28dbf3e4b90a6ea4c420172b8f2d85d" source = "https://github.com/irisnet/cosmos-sdk.git" - version = "v0.23.0-iris2" + version = "v0.23.0-iris3" [[projects]] name = "github.com/davecgh/go-spew" @@ -506,7 +506,7 @@ "ripemd160", "salsa20/salsa" ] - revision = "182538f80094b6a8efaade63a8fd8e0d9d5843dd" + revision = "0709b304e793a5edb4a2c0145f281ecdc20838a4" [[projects]] name = "golang.org/x/net" @@ -529,7 +529,7 @@ "unix", "windows" ] - revision = "49385e6e15226593f68b26af201feec29d5bba22" + revision = "ebe1bf3edb3325c393447059974de898d5133eb8" [[projects]] name = "golang.org/x/text" @@ -556,7 +556,7 @@ branch = "master" name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] - revision = "c66870c02cf823ceb633bcd05be3c7cda29976f4" + revision = "11092d34479b07829b72e10713b159248caf5dad" [[projects]] name = "google.golang.org/grpc" @@ -599,6 +599,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "eae5b968041df919006f5d21e35b282a5b20e164c2c974957b2e0d816693b6f5" + inputs-digest = "229f9905857cf4f1f368b1dea33748c0765e9437b728db927dbf3a6daf69c5f2" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index 205d71fa6..8679d7bb9 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -29,7 +29,7 @@ [[constraint]] name = "github.com/cosmos/cosmos-sdk" source = "https://github.com/irisnet/cosmos-sdk.git" - version = "=v0.23.0-iris2" + version = "=v0.23.0-iris3" [[override]] name = "github.com/golang/protobuf" @@ -55,7 +55,7 @@ [[override]] name = "github.com/tendermint/tendermint" source = "https://github.com/irisnet/tendermint.git" - version = "=v0.22.6-iris1" + version = "=v0.22.6-iris2" [prune] From e64b870e66e6e741432bfee0fc8101275f6f534f Mon Sep 17 00:00:00 2001 From: Raymond Date: Thu, 6 Sep 2018 11:25:22 +0800 Subject: [PATCH 077/124] Release version v0.4.0 --- CHANGELOG.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b4a85ea62..be11c7b8b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,14 +2,14 @@ ## 0.4.0 -*August 16th, 2018* +*September 6th, 2018* BREAKING CHANGES: - [cosmos-sdk] Upgrade to cosmos-sdk v0.23.0 - Change the address prefix format: - cosmosaccaddr --> faa - - cosmosaccaddr --> fap + - cosmosaccpub --> fap - cosmosvaladdr --> fva - cosmosvalpub --> fvp - Adjust the Route & rootMultiStore Commit for software upgrade @@ -19,12 +19,19 @@ BREAKING CHANGES: FEATURES: - [tendermint] Upgrade to Tendermint v0.22.6 - - Store the pre-state to support the replay function in software upgrade + - Store the pre-state to support the replay function - [cosmos-sdk] Upgrade to cosmos-sdk v0.23.0 - Add the paramProposal and softwareUpgradeProposal in gov module - Improve fee token mechanism to more reasonably deduct transaction fee and achieve more ability to defent DDOS attack. - Introduce the global parameter module -- [irishub] Add the upgrade module and example apps for the async software upgrade + +BUG FIXES + +- Default account balance in genesis +- Fix iris version issue +- Fix the unit conflict issue in slashing +- Check the voting power when create validator +- Fix evidence amimo register issue ## 0.3.0 From 5b3e952c0547d2915087cfe1f1396cb5a1caf203 Mon Sep 17 00:00:00 2001 From: Raymond Date: Thu, 6 Sep 2018 16:01:28 +0800 Subject: [PATCH 078/124] IRISHUB-312: update gov votingPeriod params --- Gopkg.lock | 7 +++---- app/app.go | 4 ++-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index 4020ec69f..185c8f3e9 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -199,7 +199,6 @@ ".", "hcl/ast", "hcl/parser", - "hcl/printer", "hcl/scanner", "hcl/strconv", "hcl/token", @@ -481,9 +480,9 @@ "types", "version" ] - revision = "fb697db81e3f0b04fb9c6f393ce9a09b984a4687" + revision = "bc9a42a60837b5c23c18c921e7d6e2c71a0ff170" source = "https://github.com/irisnet/tendermint.git" - version = "v0.22.6-iris1" + version = "v0.22.6-iris2" [[projects]] name = "github.com/zondax/ledger-goclient" @@ -599,6 +598,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "229f9905857cf4f1f368b1dea33748c0765e9437b728db927dbf3a6daf69c5f2" + inputs-digest = "421bec49dc49069d936902c452298cd1e8deb627a6d783149d3babb176a432aa" solver-name = "gps-cdcl" solver-version = 1 diff --git a/app/app.go b/app/app.go index ece86b96a..60f1413e7 100644 --- a/app/app.go +++ b/app/app.go @@ -206,11 +206,11 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci gov.InitGenesis(ctx, app.govKeeper, gov.GenesisState{ StartingProposalID: 1, DepositProcedure: gov.DepositProcedure{ - MinDeposit: sdk.Coins{sdk.Coin{Denom: "iris", Amount: sdk.NewInt(int64(10)).Mul(gov.Pow10(18))}}, + MinDeposit: sdk.Coins{sdk.Coin{Denom: "iris", Amount: sdk.NewInt(int64(1000)).Mul(gov.Pow10(18))}}, MaxDepositPeriod: 1440, }, VotingProcedure: gov.VotingProcedure{ - VotingPeriod: 30, + VotingPeriod: 20000, }, TallyingProcedure: gov.TallyingProcedure{ Threshold: sdk.NewRat(1, 2), From f6166e3b760344639105f1facbf58a8637df815d Mon Sep 17 00:00:00 2001 From: Raymond Date: Thu, 13 Sep 2018 11:24:01 +0800 Subject: [PATCH 079/124] IRISHUB-396: update sdk deps version and release 0.4.1 --- Gopkg.lock | 225 ++++++++++++++++++++++++++++++++++++++++----- Gopkg.toml | 2 +- version/version.go | 2 +- 3 files changed, 204 insertions(+), 25 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index 185c8f3e9..15fb8d60c 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -2,47 +2,62 @@ [[projects]] + digest = "1:e92f5581902c345eb4ceffdcd4a854fb8f73cf436d47d837d1ec98ef1fe0a214" name = "github.com/StackExchange/wmi" packages = ["."] + pruneopts = "UT" revision = "5d049714c4a64225c3c79a7cf7d02f7fb5b96338" version = "1.0.0" [[projects]] branch = "master" + 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 = "cff30e1d23fc9e800b2b5b4b41ef1817dda07e9f" [[projects]] + digest = "1:386de157f7d19259a7f9c81f26ce011223ce0f090353c1152ffdf730d7d10ac2" name = "github.com/btcsuite/btcutil" packages = ["bech32"] + pruneopts = "UT" revision = "d4cc87b860166d00d6b5b9e0d3b3d71d6088d4d4" [[projects]] + digest = "1:67c389e6e950ca4ef969adcb4063ddce7b2c3b5bd82e7bc5275786e39516d246" name = "github.com/cosmos/cosmos-sdk" packages = [ "baseapp", @@ -86,30 +101,38 @@ "x/stake/client/rest", "x/stake/keeper", "x/stake/tags", - "x/stake/types" + "x/stake/types", ] - revision = "ee0aed6ca28dbf3e4b90a6ea4c420172b8f2d85d" + pruneopts = "UT" + revision = "1a50123d7199e2182a0b5684447515e239882aa6" source = "https://github.com/irisnet/cosmos-sdk.git" - version = "v0.23.0-iris3" + version = "v0.23.0-iris4" [[projects]] + digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec" name = "github.com/davecgh/go-spew" packages = ["spew"] + pruneopts = "UT" revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73" version = "v1.1.1" [[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", @@ -118,33 +141,41 @@ "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:64a5a67c69b70c2420e607a8545d674a23778ed9c3e80607bfd17b77c6c87f6a" name = "github.com/go-ole/go-ole" packages = [ ".", - "oleutil" + "oleutil", ] + pruneopts = "UT" revision = "a41e3c4b706f6ae8dfbff342b06e40fa4d2d0506" version = "v1.2.1" [[projects]] + digest = "1:586ea76dbd0374d6fb649a91d70d652b7fe0ccffb8910a77468e7702e7901f3d" name = "github.com/go-stack/stack" packages = ["."] + pruneopts = "UT" revision = "2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a" version = "v1.8.0" [[projects]] + digest = "1:35621fe20f140f05a0c4ef662c26c0ab4ee50bca78aa30fe87d33120bd28165e" name = "github.com/gogo/protobuf" packages = [ "gogoproto", @@ -152,48 +183,60 @@ "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]] + digest = "1:ea40c24cdbacd054a6ae9de03e62c5f252479b96c716375aace5c120d68647c8" name = "github.com/hashicorp/hcl" packages = [ ".", @@ -204,112 +247,144 @@ "hcl/token", "json/parser", "json/scanner", - "json/token" + "json/token", ] + pruneopts = "UT" revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241" version = "v1.0.0" [[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:0981502f9816113c9c8c4ac301583841855c8cf4da8c72f696b3ebedf6d0e4e5" name = "github.com/mattn/go-isatty" packages = ["."] + pruneopts = "UT" revision = "6ca4dbf54d38eea1a992b3c722a76a5d1c4cb25c" version = "v0.0.4" [[projects]] + digest = "1:ff5ebae34cfbf047d505ee150de27e60570e8c394b3b8fdbb720ff6ac71985fc" name = "github.com/matttproud/golang_protobuf_extensions" packages = ["pbutil"] + pruneopts = "UT" revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" version = "v1.0.1" [[projects]] + digest = "1:645110e089152bd0f4a011a2648fbb0e4df5977be73ca605781157ac297f50c4" name = "github.com/mitchellh/mapstructure" packages = ["."] + pruneopts = "UT" revision = "fa473d140ef3c6adf42d6b391fe76707f1f243c8" version = "v1.0.0" [[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:2d5cd61daa5565187e1d96bae64dbbc6080dacf741448e9629c64fd93203b0d4" name = "github.com/prometheus/client_model" packages = ["go"] + pruneopts = "UT" revision = "5c3871d89910bfb32f5fcab2aa4b9ec68e65a99f" [[projects]] branch = "master" + digest = "1:63b68062b8968092eb86bedc4e68894bd096ea6b24920faca8b9dcf451f54bb5" name = "github.com/prometheus/common" packages = [ "expfmt", "internal/bitbucket.org/ww/goautoneg", - "model" + "model", ] + pruneopts = "UT" revision = "c7de2306084e37d54b8be01f3541a8464345e9a5" [[projects]] branch = "master" + digest = "1:8c49953a1414305f2ff5465147ee576dd705487c35b15918fcd4efdc0cb7a290" name = "github.com/prometheus/procfs" packages = [ ".", "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:22e4289b3741da96aceecc4d1dcbf682ae167c759d010fd88c63c65c9a2e8c72" name = "github.com/shirou/gopsutil" packages = [ "cpu", @@ -318,67 +393,85 @@ "internal/common", "mem", "net", - "process" + "process", ] + pruneopts = "UT" revision = "8048a2e9c5773235122027dd585cf821b2af1249" version = "v2.18.07" [[projects]] branch = "master" + digest = "1:99c6a6dab47067c9b898e8c8b13d130c6ab4ffbcc4b7cc6236c2cd0b1e344f5b" name = "github.com/shirou/w32" packages = ["."] + pruneopts = "UT" revision = "bb4de0191aa41b5507caa14b0650cdbddcd9280b" [[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:8a020f916b23ff574845789daee6818daf8d25a4852419aae3f0b12378ba432a" name = "github.com/spf13/jwalterweatherman" packages = ["."] + pruneopts = "UT" revision = "14d3d4c518341bea657dd8a226f5121c0ff8c9f2" [[projects]] + digest = "1:dab83a1bbc7ad3d7a6ba1a1cc1760f25ac38cdf7d96a5cdd55cd915a4f5ceaf9" name = "github.com/spf13/pflag" packages = ["."] + pruneopts = "UT" revision = "9a97c102cda95a86cec2345a6f09f55a939babf5" version = "v1.0.2" [[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:f2ffd421680b0a3f7887501b3c6974bcf19217ecd301d0e2c9b681940ec363d5" name = "github.com/syndtr/goleveldb" packages = [ "leveldb", @@ -392,33 +485,41 @@ "leveldb/opt", "leveldb/storage", "leveldb/table", - "leveldb/util" + "leveldb/util", ] + pruneopts = "UT" revision = "ae2bd5eed72d46b28834ec3f60db3a3ebedd8dbd" [[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:d3c1bd7382f0798d9479edcd9b683727c490187e6853fc9d1a6a205f05f47475" name = "github.com/tendermint/tendermint" packages = [ "abci/client", @@ -478,19 +579,23 @@ "state/txindex/kv", "state/txindex/null", "types", - "version" + "version", ] + pruneopts = "UT" revision = "bc9a42a60837b5c23c18c921e7d6e2c71a0ff170" source = "https://github.com/irisnet/tendermint.git" version = "v0.22.6-iris2" [[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", @@ -503,11 +608,13 @@ "pbkdf2", "poly1305", "ripemd160", - "salsa20/salsa" + "salsa20/salsa", ] + pruneopts = "UT" revision = "0709b304e793a5edb4a2c0145f281ecdc20838a4" [[projects]] + digest = "1:d36f55a999540d29b6ea3c2ea29d71c76b1d9853fdcd3e5c5cb4836f2ba118f1" name = "golang.org/x/net" packages = [ "context", @@ -517,20 +624,24 @@ "idna", "internal/timeseries", "netutil", - "trace" + "trace", ] + pruneopts = "UT" revision = "292b43bbf7cb8d35ddf40f8d5100ef3837cced3f" [[projects]] branch = "master" + digest = "1:7f4a61b989d94774dc61016b660cf8347f59eb0bed91a10b2f23fc72a38d45d4" name = "golang.org/x/sys" packages = [ "unix", - "windows" + "windows", ] + pruneopts = "UT" revision = "ebe1bf3edb3325c393447059974de898d5133eb8" [[projects]] + digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" name = "golang.org/x/text" packages = [ "collate", @@ -546,18 +657,22 @@ "unicode/bidi", "unicode/cldr", "unicode/norm", - "unicode/rangetable" + "unicode/rangetable", ] + pruneopts = "UT" revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" version = "v0.3.0" [[projects]] branch = "master" + digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c" name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] + pruneopts = "UT" revision = "11092d34479b07829b72e10713b159248caf5dad" [[projects]] + digest = "1:2dab32a43451e320e49608ff4542fdfc653c95dcc35d0065ec9c6c3dd540ed74" name = "google.golang.org/grpc" packages = [ ".", @@ -584,20 +699,84 @@ "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 = "421bec49dc49069d936902c452298cd1e8deb627a6d783149d3babb176a432aa" + input-imports = [ + "github.com/cosmos/cosmos-sdk/baseapp", + "github.com/cosmos/cosmos-sdk/client", + "github.com/cosmos/cosmos-sdk/client/context", + "github.com/cosmos/cosmos-sdk/client/keys", + "github.com/cosmos/cosmos-sdk/client/rpc", + "github.com/cosmos/cosmos-sdk/client/tx", + "github.com/cosmos/cosmos-sdk/crypto/keys", + "github.com/cosmos/cosmos-sdk/server", + "github.com/cosmos/cosmos-sdk/server/config", + "github.com/cosmos/cosmos-sdk/store", + "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/auth/client/cli", + "github.com/cosmos/cosmos-sdk/x/auth/client/rest", + "github.com/cosmos/cosmos-sdk/x/bank", + "github.com/cosmos/cosmos-sdk/x/bank/client/cli", + "github.com/cosmos/cosmos-sdk/x/bank/client/rest", + "github.com/cosmos/cosmos-sdk/x/gov", + "github.com/cosmos/cosmos-sdk/x/gov/client/cli", + "github.com/cosmos/cosmos-sdk/x/gov/client/rest", + "github.com/cosmos/cosmos-sdk/x/ibc", + "github.com/cosmos/cosmos-sdk/x/ibc/client/cli", + "github.com/cosmos/cosmos-sdk/x/ibc/client/rest", + "github.com/cosmos/cosmos-sdk/x/params", + "github.com/cosmos/cosmos-sdk/x/params/client/cli", + "github.com/cosmos/cosmos-sdk/x/slashing", + "github.com/cosmos/cosmos-sdk/x/slashing/client/cli", + "github.com/cosmos/cosmos-sdk/x/slashing/client/rest", + "github.com/cosmos/cosmos-sdk/x/stake", + "github.com/cosmos/cosmos-sdk/x/stake/client/cli", + "github.com/cosmos/cosmos-sdk/x/stake/client/rest", + "github.com/cosmos/cosmos-sdk/x/stake/types", + "github.com/go-kit/kit/metrics", + "github.com/go-kit/kit/metrics/prometheus", + "github.com/gorilla/mux", + "github.com/pelletier/go-toml", + "github.com/pkg/errors", + "github.com/prometheus/client_golang/prometheus", + "github.com/prometheus/client_golang/prometheus/promhttp", + "github.com/shirou/gopsutil/cpu", + "github.com/shirou/gopsutil/disk", + "github.com/shirou/gopsutil/mem", + "github.com/shirou/gopsutil/process", + "github.com/spf13/cobra", + "github.com/spf13/pflag", + "github.com/spf13/viper", + "github.com/stretchr/testify/require", + "github.com/tendermint/tendermint/abci/types", + "github.com/tendermint/tendermint/consensus", + "github.com/tendermint/tendermint/crypto", + "github.com/tendermint/tendermint/crypto/ed25519", + "github.com/tendermint/tendermint/libs/cli", + "github.com/tendermint/tendermint/libs/common", + "github.com/tendermint/tendermint/libs/db", + "github.com/tendermint/tendermint/libs/log", + "github.com/tendermint/tendermint/mempool", + "github.com/tendermint/tendermint/rpc/core/types", + "github.com/tendermint/tendermint/rpc/lib/server", + "github.com/tendermint/tendermint/types", + ] solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index 8679d7bb9..2f006a850 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -29,7 +29,7 @@ [[constraint]] name = "github.com/cosmos/cosmos-sdk" source = "https://github.com/irisnet/cosmos-sdk.git" - version = "=v0.23.0-iris3" + version = "=v0.23.0-iris4" [[override]] name = "github.com/golang/protobuf" diff --git a/version/version.go b/version/version.go index 837e48a61..4ee9b66e2 100644 --- a/version/version.go +++ b/version/version.go @@ -12,7 +12,7 @@ import ( ) // Version - Iris Version -const Version = "0.4.0" +const Version = "0.4.1" func GetCmdVersion(storeName string, cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ From 9a5c8337099f6ae5b10ee97914c5db3e98672493 Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Mon, 17 Sep 2018 17:08:13 +0800 Subject: [PATCH 080/124] IRISHUB-420 hotfix docs --- README.md | 101 +- docs/.vuepress/config.js | 44 + docs/README.md | 6 + docs/get-started/Full-Node.md | 85 ++ .../get-started/Genesis-Generation-Process.md | 75 ++ docs/get-started/Install-Iris.md | 120 ++ docs/get-started/README.md | 41 + docs/get-started/Validator-Node.md | 132 +++ docs/get-started/tools/Bech32-on-IRISnet.md | 36 + docs/get-started/tools/Deploy-IRIS-Monitor.md | 55 + docs/get-started/tools/Setup-Sentry-Node.md | 59 + docs/introduction/Whitepaper.md | 1032 +++++++++++++++++ docs/introduction/Whitepaper_CN.md | 616 ++++++++++ docs/modules/fee-token/Fee.md | 23 + .../fee-token/{feeToken.md => README.md} | 8 +- docs/modules/gov/gov_spec.md | 143 --- docs/pics/iris.jpg | Bin 0 -> 44414 bytes docs/validators/FAQ.md | 58 + ...ow-to-participate-in-onchain-governance.md | 76 ++ docs/validators/Setup A Sentry Node.md | 59 + docs/validators/overview.md | 15 + docs/zh/README.md | 5 + docs/zh/get-started/Full-Node.md | 89 ++ .../get-started/Genesis-Generation-Process.md | 77 ++ docs/zh/get-started/README.md | 213 ++++ docs/zh/get-started/Validator-Node.md | 127 ++ docs/zh/get-started/install-Iris.md | 118 ++ .../get-started/tools/Deploy-IRIS-Monitor.md | 46 + .../zh/get-started/tools/Setup-Sentry-Node.md | 54 + docs/zh/modules/coin/README.md | 51 + .../gov_test.md => zh/modules/gov/README.md} | 6 +- ...ow-to-participate-in-onchain-governance.md | 68 ++ 32 files changed, 3402 insertions(+), 236 deletions(-) create mode 100644 docs/.vuepress/config.js create mode 100644 docs/README.md create mode 100644 docs/get-started/Full-Node.md create mode 100644 docs/get-started/Genesis-Generation-Process.md create mode 100644 docs/get-started/Install-Iris.md create mode 100644 docs/get-started/README.md create mode 100644 docs/get-started/Validator-Node.md create mode 100644 docs/get-started/tools/Bech32-on-IRISnet.md create mode 100644 docs/get-started/tools/Deploy-IRIS-Monitor.md create mode 100644 docs/get-started/tools/Setup-Sentry-Node.md create mode 100644 docs/introduction/Whitepaper.md create mode 100644 docs/introduction/Whitepaper_CN.md create mode 100644 docs/modules/fee-token/Fee.md rename docs/modules/fee-token/{feeToken.md => README.md} (93%) delete mode 100644 docs/modules/gov/gov_spec.md create mode 100644 docs/pics/iris.jpg create mode 100644 docs/validators/FAQ.md create mode 100644 docs/validators/How-to-participate-in-onchain-governance.md create mode 100644 docs/validators/Setup A Sentry Node.md create mode 100644 docs/validators/overview.md create mode 100644 docs/zh/README.md create mode 100644 docs/zh/get-started/Full-Node.md create mode 100644 docs/zh/get-started/Genesis-Generation-Process.md create mode 100644 docs/zh/get-started/README.md create mode 100644 docs/zh/get-started/Validator-Node.md create mode 100644 docs/zh/get-started/install-Iris.md create mode 100644 docs/zh/get-started/tools/Deploy-IRIS-Monitor.md create mode 100644 docs/zh/get-started/tools/Setup-Sentry-Node.md create mode 100644 docs/zh/modules/coin/README.md rename docs/{modules/gov/gov_test.md => zh/modules/gov/README.md} (98%) create mode 100644 docs/zh/validators/How-to-participate-in-onchain-governance.md diff --git a/README.md b/README.md index 697088432..16d7a2d7b 100644 --- a/README.md +++ b/README.md @@ -1,99 +1,28 @@ -## IRIShub 简介 +# IRISHub +![banner](./docs/pics/iris.jpg) -IRIS Hub是在Cosmos生态中的区域性枢纽,提供iService服务 -## 现有资源 +IRIS network (a.k.a. IRISnet) aims to establish a technology foundation to facilitate construction of next-generation distributed applications. By incorpo- rating a comprehensive service infrastructure and an enhanced IBC protocol into the Tendermint & Cosmos stack, IRISnet enables service interoperability as well as token transfers across an internet of blockchains. +As the centerpiece of IRISnet, IRIS Hub (a.k.a. IRIShub) will be the first regional hub connecting to the main Cosmos Hub, thus making IRISnet an inseparable part of the whole Cosmos network. -* 源码:https://github.com/irisnet/irishub -* 浏览器:http://testnet.irisplorer.io -* 水龙头:http://testnet.irisplorer.io/#/faucet -* 文档:https://github.com/irisnet/testnets/tree/master/testnets +## Fuxi Testnet +To join the Fuxi testnet, follow +[this guide](https://github.com/irisnet/irishub/blob/feature/docs/docs/get-started/README.md). -## 安装IRIShub +For status updates and genesis files, see the +[testnets repo](https://github.com/irisnet/testnets). -### 方法1:下载发行版安装 +## Install -进入下载页: https://github.com/irisnet/irishub/releases/ -下载对应版本的可执行文件 -解压缩tar -C /usr/local/bin -xzf 、irishub_0.2.0_linux_amd64.zip -拷贝到/usr/local/bin/目录下 -执行以下命令,若出现对应的版本号则说明安装成功。 -``` -$ iris version -v0.2.0 - -$ iriscli version -v0.2.0 -``` -### 方法2:源码编译安装 +See the +[install instructions](https://github.com/irisnet/irishub/blob/feature/docs/docs/get-started/install-iris.md). -### 安装Go版本 1.10+ +## Resources +* Explorer:http://testnet.irisplorer.io +* Faucet:http://testnet.irisplorer.io/#/faucet -系统要求: -Ubuntu LTS 16.04 - - -安装IRISHub需要保证Go的版本在1.10以上, - -通过执行以下命令安装1.10版本的Go。 - -``` - $ sudo add-apt-repository ppa:gophers/archive - $ sudo apt-get update - $ sudo apt-get install golang-1.10-go -``` - -以上命令将安装 golang-1.10-go在 /usr/lib/go-1.10/bin. 需要将它加入到PATH中 - -``` - echo "export PATH=$PATH:/usr/lib/go-1.10/bin" >> ~/.bash_profile - source ~/.bash_profile -``` - -同时,你需要指定相关的 $GOPATH, $GOBIN, 和 $PATH 变量, 例如: - -``` - mkdir -p $HOME/go/bin - echo "export GOPATH=$HOME/go" >> ~/.bash_profile - echo "export GOBIN=$GOPATH/bin" >> ~/.bash_profile - echo "export PATH=$PATH:$GOBIN" >> ~/.bash_profile - source ~/.bash_profile -``` - -参考链接: - -1. https://golang.org/doc/install -2. https://github.com/golang/go/wiki/Ubuntu - - - -### 下载源码并安装 - - -在完成Go的安装后,通过以下命令下载并安装IRIS hub相关程序. - -``` - mkdir -p $GOPATH/src/github.com/irisnet - cd $GOPATH/src/github.com/irisnet - git clone https://github.com/irisnet/irishub - cd irishub && git checkout v0.2.0 - - curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh - - make get_vendor_deps && make install -``` - -以上命令将完成 iris 和 iriscli的安装. 若出现对应的版本号则说明安装成功。 - -``` - $ iris version - v0.2.0 - - $ iriscli version - v0.2.0 -``` diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js new file mode 100644 index 000000000..375eff556 --- /dev/null +++ b/docs/.vuepress/config.js @@ -0,0 +1,44 @@ +module.exports = { + title: 'IRISnet Document', + description: '', + base: "/docs/", + themeConfig: { + displayAllHeaders: false, + nav: [ + { text: 'Back to IRISnet', link: 'https://www.irisnet.org' } + ], + sidebar: [ + { + title: 'Introduction', + collapsable: false, + children: [ + ['/introduction/Whitepaper.md', 'Whitepaper - English'], + ['/introduction/Whitepaper_CN.md', 'Whitepaper - 中文'] + ] + },{ + title: 'Getting Started', + collapsable: false, + children: [ + ['/get-started/Install-Iris.md', 'Install'], + ['/get-started/Full-Node.md', 'Run a Full Node'], + ['/get-started/Validator-Node.md', 'Run a Validator Node'] + ] + },{ + title: 'Modules', + collapsable: false, + children: [ + ['/modules/coin/README.md', 'Coin Type'], + ['/modules/fee-token/README.md', 'Fee Token'], + ['/modules/gov/README.md', 'Governance'] + ] + },{ + title: 'Validators', + collapsable: false, + children: [ + ['/validators/overview.md', 'Overview'], + ['/validators/Setup A Sentry Node.md', 'Setup a Sentry Node'] + ] + } + ] + } +} diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 000000000..26b6c0021 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,6 @@ +# Welcome to the IRISnet Docs! +![irisnet](./pics/iris.jpg) + +IRIS network (a.k.a. IRISnet) aims to establish a technology foundation to fa- cilitate construction of next-generation distributed applications. By incorpo- rating a comprehensive service infrastructure and an enhanced IBC protocol into the Tendermint & Cosmos stack, IRISnet enables service interoperability as well as token transfers across an internet of blockchains. +As the centerpiece of IRISnet, IRIS Hub (a.k.a. IRIShub) will be the first re- gional hub connecting to the main Cosmos Hub, thus making IRISnet an inseparable part of the whole Cosmos network. + diff --git a/docs/get-started/Full-Node.md b/docs/get-started/Full-Node.md new file mode 100644 index 000000000..78acc8bcb --- /dev/null +++ b/docs/get-started/Full-Node.md @@ -0,0 +1,85 @@ +# Setup A Full-node + +Before setting up your validator node, make sure you already had **Iris** installed by following this [guide](install-iris.md) + +### Step 1: Init Your Node + +These instructions are for setting up a brand new full node from scratch. + +First, initialize the node and create the necessary config files: + +``` +iris init --name= --home=$IRISHOME +``` + +> Note: Only ASCII characters are supported for the `--name`. Using Unicode characters will render your node unreachable. + +The default \$IRISHOME is `~/.iris` , You can edit this `name` later, in the `~/.iris/config/config.toml` file: + +Your full node has been initialized! + +### Get Configuration Files + + +After intializing your node, please download the genesis file and the config file to join in the testnet. + +``` +cd $IRISHOME/config/ +rm genesis.json +rm config.toml +wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-3000/config/config.toml +wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-3000/config/genesis.json +``` +## Edit your Config File + +You could customized the `moniker` and `external_address` fields. + +``` +# A custom human readable name for this node +moniker = "" +external_address = "your-public-IP:26656" +``` + + +Optional: +Set `addr_book_strict` to `false` to make peering more easily. + +``` +addr_book_strict = false +``` + + +### Add Seed Nodes + +Your node needs to know how to find more peers. You'll need to add healthy seed nodes to `$IRISHOME/config/config.toml`. Here are some seed nodes you can use: + +``` +c16700520a810b270206d59f0f02ea9abd85a4fe@35.165.232.141:26656 +a12cfb2f535210ea12731f94a76b691832056156@120.79.226.163:26656 +``` + +Meanwhile, you could add some known full node as `Persistent Peer`. Your node could connect to `sentry node` as `persistent peers`. + + +### Enable Port + +You will need to set `26656` port to get connected with other peers and `26657` to query information of Tendermint. + +## Run a Full Node + +Start the full node with this command: + +``` +iris start --home=$IRISHOME > iris.log +``` + +Check that everything is running smoothly: + +``` +iriscli status +``` +You could see the following +``` +{"node_info":{"id":"1c40d19d695721fc3e3ce44cbc3f446f038b36e4","listen_addr":"172.31.0.190:46656","network":"iris-stage-4","version":"0.22.6","channels":"4020212223303800","moniker":"name","other":["amino_version=0.10.1","p2p_version=0.5.0","consensus_version=v1/0.2.2","rpc_version=0.7.0/3","tx_index=on","rpc_addr=tcp://0.0.0.0:46657"]},"sync_info":{"latest_block_hash":"41117D8CB54FA54EFD8DEAD81D6D83BDCE0E63AC","latest_app_hash":"95D82B8AC8B64C4CD6F85C1D91F999C2D1DA4F0A","latest_block_height":"1517","latest_block_time":"2018-09-07T05:44:27.810641328Z","catching_up":false},"validator_info":{"address":"3FCCECF1A27A9CEBD394F3A0C5253ADAA8392EB7","pub_key":{"type":"tendermint/PubKeyEd25519","value":"wZp1blOEwJu4UuqbEmivzjUMO1UwUK4C0jRH96HhV90="},"voting_power":"100"}} +``` +If you see the `catching_up` is `false`, it means your node is fully synced with the network, otherwise your node is still downloading blocks. Once fully synced, you could upgrade your node to a validator node. The instructions is in [here](validator-node.md). diff --git a/docs/get-started/Genesis-Generation-Process.md b/docs/get-started/Genesis-Generation-Process.md new file mode 100644 index 000000000..0008d1896 --- /dev/null +++ b/docs/get-started/Genesis-Generation-Process.md @@ -0,0 +1,75 @@ +# How To Participate in Genesis Process + +## Requirement + +You must have follow this [guide](install-iris.md) to install the correct version of **Iris**. + +## Step 1: + +Please run the `gen-tx` command to generate files. + + +``` +iris init gen-tx --name=your_name --home=path_to_home --ip=Your_public_IP +``` + +You could see the following output: + +``` +{ + "app_message": { + "secret": "artist green between expand license credit dinner link confirm web tell trip north web crouch february item level crop bullet fancy mixed behind anxiety" + }, + "gen_tx_file": { + "node_id": "b272ea8a29f5b21dfb4587968f22a5612c6b120a", + "ip": "192.168.1.7", + "validator": { + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "0CtwpyEviDneH7uQUL5a+e+cTqJC0sciZSJk21moH8Y=" + }, + "power": "100", + "name": "" + }, + "app_gen_tx": { + "name": "name", + "address": "faa1nnlmkvfmdvn7efwqz7eyur9rszdw723adx2mcx", + "pub_key": "fap1zcjduepq6q4hpfep97yrnhslhwg9p0j6l8hecn4zgtfvwgn9yfjdkkdgrlrqftg82c" + } + } +} +``` + +The `app_message` contains the seed phrase to recover the account of `address` field you just created. +There will be a gentx-node-ID.json a file. + +The content of the file will be: + +``` +{ + "node_id": "b272ea8a29f5b21dfb4587968f22a5612c6b120a", + "ip": "192.168.1.7", + "validator": { + "pub_key": { + "type": "tendermint/PubKeyEd25519", + "value": "0CtwpyEviDneH7uQUL5a+e+cTqJC0sciZSJk21moH8Y=" + }, + "power": "100", + "name": "" + }, + "app_gen_tx": { + "name": "name", + "address": "faa1nnlmkvfmdvn7efwqz7eyur9rszdw723adx2mcx", + "pub_key": "fap1zcjduepq6q4hpfep97yrnhslhwg9p0j6l8hecn4zgtfvwgn9yfjdkkdgrlrqftg82c" + } +``` +validator is generated by \$IRISHOME/config/priv_validator.json + +## Step 2: + +Submit your gentx-node-ID.json to `https://github.com/irisnet/testnets/tree/master/testnets/fuxi-3000/config/gentx` by createing a pull request. + +After the team has collected all the gen-tx transactions, we will publish the genesis file in the following folder: `https://github.com/irisnet/testnets/tree/master/testnets/fuxi-3000/config/` + +You could then download the final genesis file and start a node. + diff --git a/docs/get-started/Install-Iris.md b/docs/get-started/Install-Iris.md new file mode 100644 index 000000000..64c44a2c4 --- /dev/null +++ b/docs/get-started/Install-Iris.md @@ -0,0 +1,120 @@ +# Install Iris + +### Step 1: Configure Your Server + +All the blockchains in IRISnet is based on Cosmos-SDK, which is a framework for building blockchain applications in Golang. It is being used to build [Cosmos Hub](https://cosmos.network/). It's recommended to run a validator node on Linux server. + +**Recommanded Configurations:** + +1. 2 CPU +2. Memory: 4GB +3. Disk: 60GB SSD +4. OS: Ubuntu 16.04 LTS +5. Allow all incoming connections on TCP port 26656 and 26657 + +### Step 2: Install Iris + +There are two ways to get Iris running on your server. You can download the binary files from our release pages, or you can download the source code and compile it locally. + +#### Download Binary Directly + +Go to the download page: https://github.com/irisnet/irishub/releases/ then get the release v0.4.1 on your computer. +`unzip -C /usr/local/bin iris$VERSION.$OS-$ARCH.zip` to `/usr/local/bin/ ` + +You can verify you have the right version installed by running the following commands: + +``` +$ iris version +v0.4.1 + +$ iriscli version +v0.4.1 +``` + +#### Compile Source Code + +- Install Go 1.10+ + +``` +$ sudo add-apt-repository ppa:gophers/archive +$ sudo apt-get update +$ sudo apt-get install golang-1.10-go +``` + +> Note that golang-1.10-go puts binaries in /usr/lib/go-1.10/bin. If you want them on your PATH, you need to make that change yourself. + +Using snaps also works quite well: + +``` +This will give you the latest version of go +$ sudo snap install --classic go +``` + +> A restart is required for the command to be recognized. + +Then you need to verify the versions of Go: + +``` +$ go version +go version go1.10.3 darwin/amd64 +``` + +Then, you need to add `GOPATH` to system `PATH` , then your system could correctly compile the code. + +Open your `.profile` in your home directory. Add the following lines at the end of file: + +``` +GOPATH=$HOME/go +PATH=$GOPATH/bin:$PATH +``` + +Save the file and exit the editor. Then run the following to make your bash reload your profile configurations. + +``` +$ source $HOME/.profile +``` + +Now you should see something like this if you echo your\$GOPATH and \$PATH variables + +``` +$ echo $GOPATH +/home/iris/go +$ echo $PATH +/home/isir/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin +``` + +- Get the code and compile Iris + +After setup Go correctly, you should be able to compile and run **Iris**. +Make sure that you can access to google.com for that our project used some libraries provided by google. +``` +mkdir -p $GOPATH/src/github.com/irisnet +cd $GOPATH/src/github.com/irisnet +git clone https://github.com/irisnet/irishub +cd irishub && git checkout v0.4.1 +curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh +make get_vendor_deps && make install +``` + +If your environment variables have set up correctly, you should not get any errors by running the above commands. +Now check your **Iris** version. + +``` +$ iris version +v0.4.1 +$ iriscli version +v0.4.1 +``` + +### How to Update + +Get latest code (you can also `git fetch` only the version desired), ensure the dependencies are up to date, then recompile. + +``` +cd $GOPATH/src/github.com/irisnet/irishub +git fetch -a origin +rm Gopkg.lock +git checkout v0.4.1 +make get_vendor_deps +make install +``` diff --git a/docs/get-started/README.md b/docs/get-started/README.md new file mode 100644 index 000000000..366db482b --- /dev/null +++ b/docs/get-started/README.md @@ -0,0 +1,41 @@ +# IRISnet Testnet,Codename Fuxi + +## What is IRISnet + +IRIS network (a.k.a. IRISnet) is named after Greek goddess **Iris**, said to be the personification of the rainbow and the faithful messenger between heaven and humanity. IRIS network aims to build the foundation which facilitates construction of distributed business applications. IRIS hub will provide iServices, which allow resources such as data service and computing services being invoked across blockchains. To know more about IRISnet, please read this blog. + +## How to Join Fuxi Testnet + +### Step 1: Install Iris on Your Server + +Please follow this [instruction](Install-Iris.md) to get **Iris** installed locally. + +### Step 2: Run a Full Node + +Please follow this [instruction](Full-Node.md) to get your full node running. + + +### Step 3: Upgrade to Validator Node + +Please follow this [instruction](Validator-Node.md) to upgrade your full node to validator node. + +### Deploy IRISHub Monitor + +Please follow this [guide](tools/Deploy-IRIS-Monitor.md) to get IRIHub monitor running on your side. + + +### Upgrade to Validator Node + +You now have an active full node. What's the next step? + +If you have participated in the genesis file generation process, you should be a validator once you are fully synced. + +If you miss the genesis file generation process, you can still upgrade your full node to become a IRISnet Validator. The top 100 validators have the ability to propose new blocks to the IRIS Hub. Continue onto [the Validator Setup](). + +### Setup a sentry node + +A validator is under the risk of being attacked. You could follow this [guide](tools/Setup-Sentry-Node.md) to setup a sentry node to protect yourself. + +## Useful Links + +* Riot chat: #irisvalidators:matrix.org diff --git a/docs/get-started/Validator-Node.md b/docs/get-started/Validator-Node.md new file mode 100644 index 000000000..c2eef030d --- /dev/null +++ b/docs/get-started/Validator-Node.md @@ -0,0 +1,132 @@ +# Running a Validator Node + +Before setting up your validator node, make sure you've already installed **Iris** by this [guide](Full-Node.md) + +Validators are responsible for committing new blocks to the blockchain through consensus. A validator's stake will be slashed if they become unavailable, double sign a transaction, or don't cast their votes. Please read about Sentry Node Architecture to protect your node from DDOS attacks and to ensure high-availability. + +## Create A Validator + +### Get IRIS Token + +#### Create Account + +You need to get `iris` and `iriscli` installed first. Then, follow the instructions below to create a new account: + +``` +iriscli keys add +``` + +Then, you should set a password of at least 8 characters. + +The output will look like the following: +``` +NAME: TYPE: ADDRESS: PUBKEY: +tom local faa1arlugktm7p64uylcmh6w0g5m09ptvklxm5k69x fap1addwnpepqvlmtpv7tke2k93vlyfpy2sxup93jfulll6r3jty695dkh09tekrzagazek +**Important** write this seed phrase in a safe place. +It is the only way to recover your account if you ever forget your password. + +blast change tumble toddler rival ordinary chicken dirt physical club few language noise oak moment consider enemy claim elephant cruel people adult peanut garden +``` + +You could see the address and public key of this account. Please node that account address in IRISnet will start with `faa` and public key of account will start with `fap`. + +The seed phrase of this account will also be displayed. You could use these 24 phrases to recover this account in another server. The recover command is: +``` +iriscli keys add --recover +``` + + +### Claim tokens + +You can always get some `IRIS` by using the [Faucet](https://testnet.irisplorer.io/#/faucet). The faucet will send you 10IRIS every request, Please don't abuse it. + +Once you have created your own address, please then you could use this account to stake as a validatord. The following command is used to check the balance of your account: +``` +iriscli account --node=http://localhost:26657 +``` + +## Create-Validator + +### Confirm Your Validator is Synced + +Your validator is active if the following command returns anything: + +``` +iriscli status --node=tcp://localhost:26657 +``` + +You should also be able to see `catching_up` is `false`. + +You need to get the public key of your node before upgrade your node to a validator node. The public key of your node starts with `fvp`, it can be used to create a new validator by staking tokens. To understand more about the address encoding in IRISHub, please read this [doc](./tools/Bech32%20on%20IRISnet.md) + +You can find your validator's pubkey by running: + +``` +iris tendermint show_validator --home= +``` +Example output: +``` +fvp1zcjduepqv7z2kgussh7ufe8e0prupwcm7l9jcn2fp90yeupaszmqjk73rjxq8yzw85 +``` +Next, use the output as `` field for `iriscli stake create-validator` command: + + +``` +iriscli stake create-validator --amount=iris --pubkey= --address-validator= --moniker= --chain-id=game-of-genesis --name= --node=http://localhost:26657 +``` +Please note the **amount** needs to be the **minimium unit** of IRIS. + +1 IRIS=10^18iris + +In this way, to stake 1IRIS, you need to do: + +``` +iriscli stake create-validator --pubkey=pubkey --address-validator=account --fee=40000000000000000iris --gas=2000000 --from= --chain-id=fuxi-3000 --node=tcp://localhost:26657 --amount=1000000000000000000iris +``` +Don't forget the `fee` and `gas` field. To read more about fees in IRISHub, you should read [this](/modules/fee-token/feeToken.md) + +### View Validator Info + +View the validator's information with this command: + +``` +iriscli stake validator --address-validator=account --chain-id=fuxi-3000 --node=tcp://localhost:26657 +``` + +The `` is your account address that starts with 'faa' + +To read more about fee mechanism in IRISHub, go to this [doc](../modules/fee-token/Fee.md) + +### Confirm Your Validator is Running + +Your validator is active if the following command returns anything: + +``` +iriscli status --node=tcp://localhost:26657 +``` + +You should also be able to see your power is above 0. Also, you should see validator on the [Explorer](https://testnet.irisplorer.io). + + +### Edit Validator Description + +You can edit your validator's public description. This info is to identify your validator, and will be relied on by delegators to decide which validators to stake to. Make sure to provide input for every flag below, otherwise the field will default to empty (`--moniker`defaults to the machine name). + +You should put your name of your team in `details`. + +``` +iriscli stake edit-validator --address-validator=account --moniker="choose a moniker" --website="https://irisnet.org" --details="team" --chain-id=fuxi-3000 + --name=key_name --node=tcp://localhost:26657 --fee=40000000000000000iris --gas=2000000 +``` +### View Validator Description + +View the validator's information with this command: + +``` +iriscli stake validator --address-validator= --chain-id=fuxi-3000 +``` + +### Use IRISPlorer + +You should also be able to see your validator on the [Explorer](https://testnet.irisplorer.io). You are looking for the `bech32` encoded `address` in the `~/.iris/config/priv_validator.json` file. + diff --git a/docs/get-started/tools/Bech32-on-IRISnet.md b/docs/get-started/tools/Bech32-on-IRISnet.md new file mode 100644 index 000000000..a62927bb4 --- /dev/null +++ b/docs/get-started/tools/Bech32-on-IRISnet.md @@ -0,0 +1,36 @@ +# Bech32 on IRISnet + +Bech32 is a new Bitcoin address format proposed by Pieter Wuille and Greg Maxwell. Besides Bitcoin addresses, Bech32 can encode any short binary data. In the IRIS network, keys and addresses may refer to a number of different roles in the network like accounts, validators etc. The IRIS network is designed to use the Bech32 address format to provide robust integrity checks on data. The human readable part(HRP) makes it more efficient to read and the users could see error messages. + + +## Human Readable Part Table + + +| HRP | Definition | +| ------------- |:-------------:| +|faa |IRISnet Account Address| +|fap| IRISnet Account Public Key| +|fva |IRISnet Consensus Address| +|fvp| IRISnet Consensus Public Key| + +## Separator + +Why include a separator in addresses? That way the human-readable part is unambiguously separated from the data part, avoiding potential collisions with other human-readable parts that share a prefix. It also allows us to avoid having character-set restrictions on the human-readable part. The separator is 1 because using a non-alphanumeric character would complicate copy-pasting of addresses (with no double-click selection in several applications). Therefore an alphanumeric character outside the normal character set was chosen. + +## Encoding + +Not all interfaces to users IRISnet should be exposed as bech32 interfaces. Many address are still in hex or base64 encoded form. + +To covert between other binary reprsentation of addresses and keys, it is important to first apply the Amino enocoding process before bech32 encoding. + + +## Example + +Once you create a new address, you should see the following: + +` +NAME: TYPE: ADDRESS: PUBKEY: +test1 local faa18ekc4dswwrh2a6lfyev4tr25h5y76jkpqsz7kl fap1addwnpepqgxa40ww28uy9q46gg48g6ulqdzwupyjcwfumgfjpvz7krmg5mrnw6zv8uv +` + +This means you have created a new address `faa18ekc4dswwrh2a6lfyev4tr25h5y76jkpqsz7kl`, its hrp is `faa`. And its public key could be encoded into `fap1addwnpepqgxa40ww28uy9q46gg48g6ulqdzwupyjcwfumgfjpvz7krmg5mrnw6zv8uv`, its hrp is `fap`. \ No newline at end of file diff --git a/docs/get-started/tools/Deploy-IRIS-Monitor.md b/docs/get-started/tools/Deploy-IRIS-Monitor.md new file mode 100644 index 000000000..a5104ae52 --- /dev/null +++ b/docs/get-started/tools/Deploy-IRIS-Monitor.md @@ -0,0 +1,55 @@ +# How to deploy IRISHUB monitor + +Please make sure that iris is installed in your computer and added to $PATH.You can see this page for insturcion https://github.com/irisnet/irishub. You also need /bin/bash, wc, ps to ensure the monitor work properly. + +1. Download the monitoring tools +``` +wget https://raw.githubusercontent.com/programokey/monitor/master/monitor.tar.gz +``` + +2. Uncompress the monitoring tools: +``` +tar -xzvf monitor.tar.gz +``` + +3. Edit the running parameters + +``` +cd monitor +vim start.sh +``` + +4. Edit the third command in `start.sh` + +You could get hex encoded validator address by running: +``` +iriscli status +``` + +It corresponds to `validator_info.address` field. + +modify +-a=378E63271D5BE927443E17CBAAFE68DEFF383DA7 +to +-a= +modify +--chain-id=fuxi-3000 +to +--chain-id= +modify +--node="tcp://localhost:26657" +to +--node= + +5. start the monitoring tools +``` +./start.sh +``` + +then, you can visit http://localhost:3000/ to see the grafana monitoring page. The default username and password are both admin. We strongly recommend immediately changing your username & password after login. +Click the Home button, and open the IRIS HUB. Then you can see all the monitoring parameters. + +6. stop the monitor +``` +./stop.sh +``` \ No newline at end of file diff --git a/docs/get-started/tools/Setup-Sentry-Node.md b/docs/get-started/tools/Setup-Sentry-Node.md new file mode 100644 index 000000000..328867153 --- /dev/null +++ b/docs/get-started/tools/Setup-Sentry-Node.md @@ -0,0 +1,59 @@ +# Setup A Sentry Node + +## Why do we need a sentry node? + +A validator node is under the risk of distributed denial-of-service (DDoS)attack. It occures when an attacker tries to disrupt normal traffic of a node. In this way, this node will be isolated from other nodes in the network. One way to mitigate this risk is for validators to carefully structure their network topology in a so-called sentry node architecture. + +## What is a sentry node? + +In IRISnet, a sentry node is just a normal full node. The validator node will only connect to its sentry node. In this way, the sentry nodes will be protect the validator node from DDoS attack. + +## How to setup a sentry node? + + +### Sentry Node + +On the sentry node's side, you need to get fully initialized first. + +Then, you should edit its `config.tmol` file, and change `private_peers_id` field: + +``` +private_peers_ids="validator_node_id" +``` + +`validator node id` is the `node-id` of validator node. + +Then you could start your sentry node, + +``` +iris start --home=sentry_home +``` + +If you have multiple sentry node, you could make them as `persistent-peers` to each other. + +### Validator Node + +On the validator node's side, you also need to get fully initialized first, and make sure you have the `priv_validator.json` file backuped. + +Then, you should edit its `config.tmol` file, + +``` +persistent_peers="sentry_node_id@sentry_listen_address" +``` + +If you want to put multiple sentry info, you need to separate the information with `,` + +Set +``` +pex=false +``` +In this way, the validator node will diable its peer reactor, so it will not respond to any peer exchange request other than its sentry nodes. + +Then you could start your validator node, + +``` +iris start --home=sentry_home +``` + +It's also recommanded to enable the firewall of validator node. + diff --git a/docs/introduction/Whitepaper.md b/docs/introduction/Whitepaper.md new file mode 100644 index 000000000..a1916bd21 --- /dev/null +++ b/docs/introduction/Whitepaper.md @@ -0,0 +1,1032 @@ +# The IRIS Network +**Inter-chain service infrastructure and protocol for building trustworthy and distributed business applications** + +Harriet Cao harriet@bianjie.ai
+Haifeng Xi haifeng@bianjie.ai + +_NOTE: If you can read this on GitHub, then we're still actively developing this +document. Please check regularly for updates!_ +
+ +## Table of Contents ########################################################### + +* [Disclaimer](#disclaimer) +* [IRIS Overview](#iris-overview) + * [Cosmos and Tendermint](#cosmos-and-tendermint) + * [IRIS Innovations](#iris-innovations) +* [IRIS Network Design](#iris-network-design) + * [Network Actors](#network-actors) + * [IRIS Services](#iris-services) + * [IBC Enhancement](#ibc-enhancement) +* [Use Cases](#use-cases) +* [Token Economics](#token-economics) +* [Initial Token Distribution](#initial-token-distribution) +* [Roadmap](#roadmap) +* [The Team](#the-team) + * [Core Members](#core-members) + * [Advisors](#advisors) +* [References](#references) + +
+ +## Disclaimer + +This whitepaper and any other documents published in association with this whitepaper relate to the intended development and use of the IRIS network. They are information purposes only and may be subject to change. + +### This whitepaper describes a developing project + +This whitepaper contains forward-looking statements that are based on the beliefs of IRIS Foundation Limited, as well as certain assumptions made by and information available to IRIS Foundation Limited. + +The IRIS network as envisaged in this whitepaper is under development and is being constantly updated, including but not limited to key governance and technical features. The IRIS token involves and relates to the development and use of experimental platforms (software) and technologies that may not come to fruition or achieve the objectives specified in this whitepaper. + +If and when the IRIS network is completed, it may differ significantly from the network set out in this whitepaper. No representation or warranty is given as to the achievement or reasonableness of any plans, future projections or prospects and nothing in this document is or should be relied upon as a promise or representation as to the future. + +### No offer of regulated products + +The IRIS tokens are not intended to represent a security or any other regulated product in any jurisdiction. + +This document does not constitute an offer or solicitation of securities or any other regulated product, nor a promotion, invitation or solicitation for investment purposes. The terms of the purchase are not intended to be a financial service offering document or a prospectus of any sort. + +The IRIS tokens do not represent equity, shares, units, royalties or rights to capital, profit, returns or income in the platform or software or in IRIS Foundation Limited or any other company or intellectual property associated with the platform or any other public or private enterprise, corporation, foundation or other entity in any jurisdiction. + +### This whitepaper is not advice + +This whitepaper does not constitute advice to purchase any IRIS tokens. It must not be relied upon in connection with any contract or purchasing decision. + +### Risk warning + +The purchase of IRIS tokens and participation in the IRIS network carries with it significant risks. + +Prior to purchasing IRIS tokens, you should carefully assess and take into account the risks, including those listed on and in any other documentation. + +### Views of IRIS Foundation Limited only + +The views and opinions expressed in this whitepaper are those of IRIS Foundation Limited and do not necessarily reflect the official policy or position of any government, quasi-government, authority or public body (including but not limited to any regulatory body of any jurisdiction) in any jurisdiction. + +Information contained in this whitepaper is based on sources considered reliable by IRIS Foundation Limited but there is no assurance as to their accuracy or completeness. + +### English is the authorised language of this whitepaper + +This whitepaper and related materials are issued in English only. Any translation is for reference purposes only and is not certified by IRIS Foundation Limited or any other person. No assurance can be made as to the accuracy and completeness of any translations. If there is any inconsistency between a translation and the English version of this whitepaper, the English version prevails. + +### No third party affiliation or endorsements + +References in this whitepaper to specific companies and platforms are for illustrative purposes only. The use of any company and/or platform names and trademarks does not imply any affiliation with, or endorsement by, any of those parties. + +### You must obtain all necessary professional advice + +You must consult a lawyer, accountant and/or tax professional, as well as any other professional advisors, as necessary prior to determining whether to purchase IRIS tokens or otherwise participate in the IRIS network. + +
+ +## IRIS OVERVIEW ################################################################ + +> The IRIS network is named after the Greek goddess Iris, said to be the personification of the rainbow and the faithful messenger between heaven and humanity. + +Contractual relationships are a fundamental building block of human society and the +importance of blockchain technology lies in providing a very efficient +and cost effective way of realizing reliable contractual +relationships: for the first time, trust (which is also very +costly to establish) is not needed when multiple parties participate in sophisticated +business interactions. It has been said that blockchain technology provides +the most important elements for distributed business to take place: lifting network effect +and very low transaction cost. More and more people see the potential of +blockchains as the new internet of value and will gradually transform the +current business models into more efficient distributed ones. Especially +the token mechanism embedded in most modern blockchain emphasizes each network +participant's right and will disrupt business in its current form [\[1\]][1]. + +However, blockchain technology is still in its early stages. As with any new technology, there are drawbacks. These include limited performance and undeveloped governance mechanisms. Presently, these drawbacks make it difficult for blockchains to support real-world distributed business collaboration. Consortium chains, such as Hyperledger Fabric and R3 Corda, and organisations such as the Ethereum Enterprise Alliance, have tried to address those performance and governance issues to make blockchain technology more suitable for enterprises. However, today consortium chains are dominated by huge +enterprise companies. Furthermore their close-form off on-chain governance model +is very inefficient. Without a token economics model and the +openness and the excitement in public chains, consortium chains may be viewed as lacking vitality. + +We would like to enhance the current blockchain technology and +make it possible to enable thousands and millions of Small Medium Businesses ("SMBs") and even individual freelance business service providers to provide their services and enjoy the rewards in an open network. To achieve this, we have identified the following challenges and consequent opportunities for technology innovations: + +**Not all computation could or should be implemented as on-chain computations such as smart contracts** + +The [Turing-complete](https://en.wikipedia.org/wiki/Turing_completeness) virtual +machine provided by Ethereum [\[2\]][2] runs Smart Contracts gives people a lot of hope of developing +decentralized applications. However Smart contracts can only handle deterministic logic (so +every node can reach an identical state after processing every +transaction and block) while huge amount of existing business logic that +is not deterministic and might vary at different time and under +different environmental parameters. Especially these days, business systems have placed an increasing amount of reliance on computer algorithms, including Natural Language Processing ("NLP"), machine learning, and operation research algorithms, for decision optimization. In those +algorithms, very often we purposely add some randomness to make the +decision not to get stuck at local optimal states while trying to find a +better sub-optimal result. + +On the other hand, some of the real world business logics are meant to +be run once off-chain and shouldn't be implemented as smart contracts +this type of replicated computing. Integration and collaboration of off-chain services and resources with +a distributed ledger is key to further advance the adoption of +blockchain technology for more real-world use scenarios. + +**How to reuse the existing blockchain resources, including both public chains and consortium chains** + +It is infeasible to use one public chain to address all use cases. +Every day there are different chains going live which focus on one aspect +of problem solving such as distributed storage, asset ownership or predict market etc. +According to the coinmarketcap.com, there are more than 1000 +cryptocurrencies currently active on various exchanges. + +While building business applications involve handling storage and also +different source of data feeds. Another motivation of our work involves +how to support building distributed business applications by reusing +some of the existing work like storage (IPFS, SIA, Storj.io etc.), data feed +(Augur, Gnosis, Oraclize etc.) and IoT (IOTA etc.) provided by those +dedicated blockchains and not reinventing the wheel. + +Besides, there are many (near) real-time business transactions do need +more close form consortium/permission/private chains to address +performance, security and business governance requirements. Our vision of distributed business infrastructure needs to have the Interoperability of many heterogeneous chains including public/consortium/permission/private chains. + +Inter-chain technology is a very nature answer to the requirement. +However, till today, the existing Inter-chain technologies are mainly +designed to provide interoperability among existing blockchains and +focus on token value transfer. The question of how to consume the +resource provided in different chains still remains unanswered. + +Comparing the proposed inter-chain technologies like Cosmos [\[3\]][3] and +Polkadot [\[4\]][4], we find out that Cosmos provides more mature base for +interoperability and scalability. Especially, we found the design of +"`many hubs and many zones`" and "`each zones are independent blockchains +having independent governance models`" from Cosmos provides a very +suitable architecture for modeling the real world complexity in a SOC +way. To best reuse the existing framework, we present the IRIS Network, a +decentralized inter-chain network composing hub and zones with +implementing a layer of service infrastructure based on +Cosmos/Tendermint [\[5\]][5], with enhanced usage of token . + +Since the IRIS network is designed on top of Cosmos/Tendermint, we will first discuss Cosmos/Tendermint, summarize the features we inherit from Cosmos/Tendermint and summarize the innovations we have created. + +### Cosmos and Tendermint ################################################################ + +Cosmos [\[3\]][3] intends to build the 'internet of blockchains'. It is a network of many independent blockchains, called "zones". Each zone is powered by classical Byzantine fault-tolerant ("BFT") +consensus protocols like [Tendermint](https://tendermint.com/). + +Tendermint provides a high-performance, consistent, secure BFT consensus +engine, where strict fork-accountability guarantees hold over the +behavior of malicious actors. Tendermint is well suited for scaling +heterogeneous blockchains including public blockchains such as Ethermint +[\[6\]][6], which is a blazing fast Proof-of-Stake implementation of +Ethereum, as well as performance critical permission/consortium chains. +The successful stories on using Tendermint in the permission/consortium +chain domain including Oracle [\[7\]][7], CITA [\[8\]][8] and +Hyperledger Burrow [\[9\]][9]. + +Tendermint is used as the consensus protocol for building the first zone +on the Cosmos Hub. Hub can connect to many different +kinds of zones, and the communication is achieved via an +inter-blockchain communication ("IBC") protocol, a kind of virtual UDP or +TCP for blockchains. Tokens can be transferred from one zone to another +securely through the Cosmos Hub, without the need for an exchange +or a trusted third party between zones. + +To develop robust interoperable blockchains and blockchain applications +with Cosmos Hub, Cosmos SDK provides blockchain development +\'starter-kit\' of common blockchain modules while not enforcing +user stories thus giving maximum flexibility for application customization. + +### IRIS Innovations ################################################################ + +IRIS network aims to build technology foundation which facilitate +construction of distributed business applications. It goes beyond today's +blockchain systems which are mainly for digitalized assets. + +The key challenges that we aim to address via the IRIS network are two-fold: +* Integration and collaboration of off-chain computing and resources on + a distributed ledger; +* interoperability of the services across + heterogeneous chains. + +We address those challenges through incorporation +of a service oriented infrastructure into Cosmos/Tendermint. + +Our design inherits the thinking pattern from +many years of service-oriented architecture ("SOA") practices. SOA is an architectural approach to create +systems built from autonomous services which have explicit boundaries, +share schemas and contracts [\[13\]][13]. Earlier practice of SOA focused +on the implementation of Enterprise Service Bus ("ESB") which enables +communication among services via a common communication bus which +consists of a variety of point-to-point connections between providers +and consumers. However, centralized management of services through ESB could +trigger a single point of failure, also adds dependency of service +deployment. The recent surge of micro-services architectural style can be +seen as a development of SOA without focusing on the ESB rather using +light message queues for inter service communication. In IRIS network, +the inter service communication is intended to be implemented over blockchain to +leverage blockchain as a trusted machine for mediating business +collaborations. It runs without prerequisite of existing trust among service +provider and service consumer which is very hard to establish. + +The IRIS network uses Tendermint protocol as a high-performance consensus +engine. Leveraging the flexibility provided by tendermint's Application +BlockChain Interface ("ABCI"), we define a set of service infrastructure +transaction types including service provisioning, service consumption +and service governance. As explained earlier, most business logic is not +suitable for implementation as deterministic smart contracts on +blockchain, we are using this service layer to move the business +application specific logics and transaction processing off the +blockchain itself and use the blockchain only to get consensus on the +results generated through those services. This idea is also inspired by +existing work from blockchain community when address performance issues +of moving some complicated computation off the main chain, such as Lightning +Network's off-chain state channels [\[10\]][10] as well as Plasma's fraud +proof side chains [\[11\]][11]. Although we are not implementing side chains, +we rip traditional business logic computation off the blockchain + and use it as a trustworthy mediation bus for +complicated business collaboration. + +For interchain communication, Cosmos IBC [\[12\]][12] defines a protocol for +transferring values from an account on one chain to an account on another +chain. The IRIS network designs new semantics to allow cross-chain computation to be invoked by leveraging IBC. We believe this capability is very important when building scalable business applications. Further details of potential use cases are set out below. + +The IRIS network is intended to provide the service infrastructure for handing and coordinating on-chain transaction processing with off-chain data processing and business logic execution. Enhanced IBC capability +allows those off-chain processing to be invoked cross chain, if required. The IRIS network, as presently envisaged, will also include client-side tools, including a smart wallet enabling cross-chain multi-asset storage, as well as consume and provide iServices. We plan to provide SDKs for easy construction of iServices. For example, for a specific service definition, the Client SDK would generate the provider side skeleton as well as consumer side stub for major programming languages. + +
+ +## IRIS Network Design ################################################################ + +![Figure of IRIS Network](https://github.com/irisnet/irisnet/blob/master/images/chap2-1.png?raw=true) + +As illustrated in the figure above, the IRIS network is intended to have the +same topology as the Cosmos network. We plan to connect the IRIS Hub to +the Cosmos Hub as one of its zones and regional hubs. IRIS full nodes, +developed with the IRIS SDK (which is itself a planned extension of the +Cosmos SDK), are proposed to provide a service infrastructure as well as +offer integration with an embedded InterPlanetary File System ("IPFS") node. + +IRIS Services (a.k.a. "iServices") intend to bridge the gap between the blockchain +world and the conventional business application world, by mediating a +complete lifecycle of off-chain services -- from their definition, +binding (provider registration), invocation, to their governance +(profiling and dispute resolution). By enhancing the IBC processing +logic to support service semantics, the IRIS SDK is intended to allow +distributed business services to be available across the internet of blockchains. + +While the IRIS network focuses on providing an innovative solution +for distributed business applications, it is still part of +the broader Cosmos network. All zones connected to our proposed IRIS hub would be able to interact with any other zone in the Cosmos network over +the standard IBC protocol. Furthermore, by introducing a layer of service +semantics, which we believe could enable a whole new set of business scenarios, +the planned IRIS network would represent an increase in scale and diversity +of the Cosmos network. + +### Network Actors + +1. **Consumers** are those users who may consume off-chain services by sending + requests to the network and receiving responses from the network. + +2. **Providers** are those users who may offer the implementation of one or more +iService definitions and often act as *adaptors* of off-chain services and resources located + in other public and consortium chains, as well as in enterprise legacy + systems. Providers monitor and process incoming requests and send responses + back to the network. A provider could at the same time act as a consumer + by sending requests to other providers. As planned, providers would be required to + charge a fee for any services they might offer, and the service fee, by default, would be + priced in the IRIS network's native fee token known as "IRIS"; providers + could also price their services in other whitelisted Cosmos fee tokens, to be + considered in due course. + +3. **Profiler** is the special user who works on behalf of the IRIS Foundation +Limited ("Foundation"), a Hong Kong incorporated company limited by guarantee. +The Foundation will take the lead in building the IRIS network. The profiler +is the sole user authorized to invoke iServices in the profiling mode, which +is intended to help create and maintain objective *provider profiles* that +consumers use to select suitable providers. + +### IRIS Services + +In this section, we set out the intended technical parameters for deploying iServices on the IRIS network. + +**Service Definition** + +A `Method` is composed of: + +* `ID (int)`: The unique ID of this method in the encompassing iService + +* `Name (string)`: The unique name of this method in the iService + +* `Description (string)`: A description of this method + +* `Input (string)`: A structured definition of the input parameters + +* `Output (string)`: A structured definition of the output result + +* `Error (string)`: A structured definition of all possible error conditions + +* `OutputPrivacy (enum)`: Can be one of `NoPrivacy` or `PubKeyEncryption` + +A `ServiceDefinition` is composed of: + +* `Name (string)`: The name of this iService + +* `Description (string)`: A description of this iService + +* `Tags (string)`: Comma separated keywords about this iService + +* `Creator (string)`: A self-description of the iService creator. *Optional* + +* `ChainID (string)`: The ID of the blockchain where this iService was + originally defined + +* `Messaging (enum)`: Can be one of `Unicast` or `Multicast` + +* `Methods ([]Method)`: The definition of methods available in this iService + +A `CreateServiceDefinitionTx` transaction is composed of: + +* `Definition (ServiceDefinition)`: The service definition to be created + +**Service Binding**: + +A `CreateServiceBindingTx` transaction is composed of: + +* `DefinitionHash ([]byte)`: The hash of the service definition that the provider is binding to + +* `ChainID (string)`: The ID of the blockchain where the provider is connected + +* `ProviderAddress ([]byte)`: The provider's blockchain address + +* `BindingType (enum)`: Can be one of `Local` or `Global`; choose `Global` if a + provider wants the binding to be exposed to the rest of the world; + otherwise, use `Local` + +* `ProviderDeposit (int64)`: To create an effective binding, the provider + must put down a deposit (in terms of IRIS token amount) that is greater than + the value of the system parameter `MinProviderDeposit`; a larger deposit + may imply more trustworthiness of the provider + +* `ServicePricing (string)`: A structured definition of the service pricing + model on a per method basis, including cost per call, volume discount, + promotional terms etc.; service fee is by default listed in IRIS token but + could also be quoted in other whitelisted fee tokens. + +* `ServiceLevel (string)`: A structured definition of service level the + provider agrees to bind himself to, in terms of response time, + availability etc. + +* `BindingExpiration (int64)`: The blockchain height where this binding + expires; a negative number means "never expire" + +An `UpdateServiceBindingTx` transaction is composed of: + +* `DefinitionHash ([]byte)`: The hash of the service definition the + provider has bound to + +* `ChainID (string)`: The ID of the blockchain where the provider is + connected + +* `ProviderAddress ([]byte)`: The provider's blockchain address + +* `ChangeSet (string)`: A structured definition of desired changes to an + existing binding identified by the preceding three fields + +![Figure of iService Definition and Bindings](https://github.com/irisnet/irisnet/blob/master/images/chap2-2.png?raw=true) + +A provider can update `ServicePricing`, `ServiceLevel` and `BindingExpiration` +at any time, but a small amount of their deposit will be slashed for +changing the latter two (specified by `ServiceLevelUpdateSlash` and +`BindingExpirationUpdateSlash` respectively). Setting `BindingExpiration` to +a height that is lower than the current height will be interpreted as +invalidating the binding immediately. + +Updates to `ProviderDeposit` will always be treated as *adding to* the +current deposit balance. Whenever the balance drops below +`MinProviderDeposit`, the binding will be disabled until the provider +increases the balance above the threshold. Upon expiration or +invalidation of a binding, the provider will automatically get back the +remaining balance of its deposit. + +`BindingType` can be changed from `Local` to `Global`, but not the other way +around. To downgrade a binding from `Global` to `Local`, a provider must +first invalidate the binding in question and then create a new `Local` +binding. + +If a provider somehow needs to move the binding to a new address, it is +not allowed to update `ProviderAddress` directly; instead, the provider +should invalidate the current binding and create another one with the +desired new `ProviderAddress`. + +Upon successful execution of these two transactions by the application +(i.e., iService business logic in the IRIS SDK), a `ServiceBinding` object +will be created or updated accordingly. + +A `ServiceBinding` is composed of: + +* `DefinitionHash ([]byte)` + +* `ChainID (string)` + +* `ProviderAddress ([]byte)` + +* `ServiceLevel (string)` + +* `ServicePricing (string)` + +* `BindingExpiration (int64)` + +* `IsValid (enum)`: Can be one of `True` or `False` + +**Service Invocation** + +![Figure of Service Invocation](https://github.com/irisnet/irisnet/blob/master/images/chap2-3.png?raw=true) + +Consumers and providers are proposed to interact with each other through *endpoints*. +There are two kinds of endpoints -- *request table* and *response table* +(see Figure above). Service requests are posted to request tables monitored +by interested provider(s) which pick up and process requests addressed +to them; service results (or errors) are posted back to response tables +monitored in turn by matched consumers. + +For a `Multicast` service, all of its bindings share one request table; +for a `Unicast` service, however, a separate request table is created and +maintained for each of its bindings. As for the other direction, a dedicated response table would be created and managed for each consumer. + +A `ServiceRequest` is composed of: + +* `ChainID (string)`: The ID of the blockchain where the consumer is + connected + +* `ConsumerAddress ([]byte)`: The blockchain address of the consumer + +* `DefinitionHash ([]byte)`: The hash of the service definition + +* `MethodID (int)`: The ID of the method to be invoked + +* `InputValue (string)`: A structured representation of input values + +* `BindingHash ([]byte)`: The hash of the target binding, in case of a + `Unicast` service. *Optional* + +* `MaxServiceFee (int64)`: The max amount of service fee the consumer is + willing to pay for a `Multicast` request. *Optional* + +* `Timeout (int)`: The max number of blocks the consumer is willing to wait + for response(s) to come back + +A `PostServiceRequestTx` transaction is composed of: + +* `Requests ([]ServiceRequest)`: The service requests to be posted + +* `RequestDeposits ([]int64)`: The consumer must put down for each request + a deposit (in terms of IRIS amount) that is greater than the value of + `MinRequestDeposit`; this deposit is meant to incentivize the consumer to acknowledge receipt of service responses in a timely manner (see `ConfirmServiceResponseTx`). + +The application will verify that each request is coming from a consumer +with matching `ChainID` and `ConsumerAddress`, the targeted binding is +valid, the request deposit is sufficient, the consumer's account balance is +enough to cover the request deposits and service fees, and that the total +number of requests in the transaction is less than `MaxRequestPostBatch`. + +When a verified request is appended to the request table, the related +service fee (`MaxServiceFee` in case of a `Multicast` request) will be +deducted from the consumer's account and locked up in escrow. + +A `GetServiceRequest` query is composed of: + +* `DefinitionHash ([]byte)`: The hash of the service definition + +* `BindingHash ([]byte)`: The hash of this provider's binding to the + service in question; the application will verify that the binding is + valid and the caller matches the binding's `ChainID` and `ProviderAddress` + +* `BeginHeight (uint64)`: The blockchain height from where the application + should start to retrieve requests for the provider, up to a total number + that is the lesser of `BatchSize` and `MaxRequestGetBatch` + +* `BatchSize (int)`: The max number of requests to be returned + +A `ServiceResponse` is composed of: + +* `RequestHash ([]byte)`: The hash of the matched request + +* `BindingHash ([]byte)`: The hash of this provider's service binding + +* `OutputValue ([]byte)`: A structured (potentially encrypted) + representation of output result. *Optional* + +* `ErrorMsg (string)`: A structured representation of error messages. + *Optional* + +A `PostServiceResponseTx` transaction is composed of: + +* `Responses ([]ServiceResponse)`: The service responses to be posted + +The application will verify that each response is coming from a +provider with matching `ChainID` and `ProviderAddress`, and that the number +of responses in the transaction is less than `MaxResponsePostBatch`. A +verified request will be appended to the response table for the intended +consumer. + +A `GetServiceResponse` query is composed of: + +* `RequestHash ([]byte)`: The hash of the original request; the + application will verify that the caller matches the request's `ChainID` + and `ConsumerAddress` + +* `BeginHeight (uint64)`: The blockchain height from where the application + should start to retrieve responses for the consumer, up to a total + number that is the lesser of `BatchSize` and `MaxResponseGetBatch` + +* `BatchSize (int)`: The max number of responses to be returned + +A `ConfirmServiceResponseTx` transaction is composed of: + +* `ResponseHash ([][]byte)`: The hash of responses to be confirmed + +The application will verify that the each response to be confirmed is +indeed for a request originated by the caller, and that the number of +responses in the transaction is less than `MaxResponseConfirmBatch`. + +Responses that fall out of the `Timeout` window (and, in case of `Multicast` +responses, when `MaxServiceFee` runs out as more responses come back) will +not be accepted by the application. A consumer starts processing a +`Unicast` response immediately upon receiving it. However, for `Multicast` +responses, a consumer will need to wait until the `Timeout` window elapses before +starting to process all responses received, if any. + +When a `Unicast` response is confirmed by the consumer, the associated +service fee will be released from escrow to the matched provider account +-- after a small tax (defined by `ServiceFeeTaxRate`) is deducted and +added to the *system reserve*; and the associated request deposit will +be returned to the consumer as well. + +In the case of a `Multicast` request, the situation is a bit more complex: +when a response is confirmed, only part of the request deposit is +returned to the consumer, in proportion to the response related service +fee vs `MaxServiceFee`; and after all responses are confirmed, the +remaining escrow balance for the request will be returned to the +consumer. + +If a request timeouts without seeing any response come back, the +application will refund the associated balance held in escrow plus the request +deposit, in full, back to the consumer. However, if the consumer does +not confirm a response in time (before `ResponseConfirmTimeout` + +blockchain height of the response), a small penalty (defined by +`ResponseConfirmDelayPenaltyRate`) will be applied before the request +deposit is refunded to the consumer, while the associated service fee +will be released to the provider as usual. + +**Dispute Resolution** + +In any case where a consumer is unsatisfied with a service response, a mechanism should exist allowing the consumer to issue a complaint and consequently, to receive an acceptable solution to that complaint, without having to resort to a centralized authority such as the legal system. Also, this mechanism should avoid +introducing subjective evaluation, which could be abused by either side. + +The process to resolve a dispute that arises on the IRIS network resembles that of service invocation, except that a consumer sends a `Complaint` to the provider, and the provider responds with a `Resolution`. These interactions are intended to happen through a pair of global endpoints known as *complaint table* and *resolution table*. + +Under the present design for the IRIS network, a consumer deposit is required for filing a complaint. Where a consumer does not confirm a resolution in a timely manner, a penalty will be deducted from this deposit. Similarly, a provider's deposit will be partially slashed if he fails to respond to a complaint in a timely manner. + +A `Complaint` is composed of: + +* `ResponseHash ([]byte)`: The hash of the response in dispute + +* `Problem (string)`: A description of the problem with the service response + +* `PreferredDisposal (enum)`: Can be one of `Refund` or `Redo` + +A Resolution is composed of: + +* `ComplaintHash ([]byte)`: The hash of the matched complaint + +* `Disposal (enum)`: Can be one of `Refund` or `Redo` + +* `Refund (uint64)`: Service fee refund. *Optional* + +* `OutputValue ([]byte)`: A structured (potentially encrypted) + representation of output result. *Optional* + +Our intended dispute resolution process, as outlined above, may not be legally binding. Nonetheless, we believe that it will provide an efficient means of resolving common disputes on the IRIS network. + +**Service Profiling** + +Bootstrapping the iService ecosystem presents a few challenges. A major challenge is finding a way to make it easy for consumers to discover suitable providers - consumers need performance metrics to evaluate and select a provider, yet without consumer usage no performance metrics will be available. + +With the intention to solve this circular issue, we plan to introduce a profiling mechanism where a privileged system user, the profiler, invokes all the active services on a regular schedule. This would leave objective performance data in the network (such as response time, availability, complaint handling etc.) that are useful for real consumers. + +Service profiling calls would be exempt from service fees and consumer +deposits, but they would incur network transaction fees. These calls +would originate from a few reserved addresses that are intended to be recognized and honored by the application. + +Profiling activities would stay at a relatively stable level for new services +and gradually decline for individual services as they start to +attract real consumer calls, which is expected to generate more performance data on their own. + +Transaction fees incurred during profiling would be paid out from the system reserve by default, and the Foundation reserve would step in if necessary. + +**Query** + +All the service related lifecycle objects described above can be queried +using the ABCI Query interface [\[3\]][3]. These queries would be executed over +the Query connection and do not participate in the consensus process. We +have already seen how `GetServiceRequest` and `GetServiceResponse` queries +work as part of the service invocation process. + +Below is a non-exhaustive summary of our currently planned queries: + +**Service Objects** + +| Object | Commonly Used Filters | Authorization | +| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| Service Definition | Name, keywords, source (chain ID), messaging type, with active bindings... | Anyone can query | +| Service Binding (for a given definition) | Location (local or remote), pricing, service level, expiration... | Anyone can query | +| Service Request | Service definition and binding, blockchain height, batch size | Only matched provider(s) | +| Service Response | Service request, blockchain height, batch size | Only matched consumer | + + +**Performance Metrics** + +| Area | Metrics | Authorization | +| --------------------------- | ---------------------------------------- | ----------------- | +| Provider (address) | Number of services provided (ever and active), response time (min, max and average), requests served (local and remote), requests missed, complaints received, complaints ignored, ... | Anyone can query | +| Provider (binding) | Active time, response time (min, max and average), requests served (local and remote), requests missed, complaints received, complaints ignored, ... | Anyone can query | +| Consumer | Number of services ever used, requests made, requests confirmed (in time and missed), complaints made, resolutions confirmed, ... | Anyone can query | +| Consumer (service, binding) | Requests made, requests confirmed (in time and missed), complaints made, resolutions confirmed, ... | Anyone can query | + + +### IBC Enhancement + +One unique advantage of establishing our service infrastructure on top of Cosmos is the potential for services to be *deployed once and invoked +everywhere*, over an internet of blockchains. Specifically, our plan is to +accomplish the following: + +1. Service definitions are broadcast to every zone in the IRIS network; + +2. Global service bindings are broadcast to every zone in the IRIS network; + +3. Service requests or complaints targeting a remote provider are routed to + the blockchain to which the provider is connected; + +4. Service responses or resolution meant for a remote consumer are routed + back to the blockchain to which the consumer is connected. + +When processing a `CreateServiceDefinitionTx` transaction, the application +is designed to first validate and store the `ServiceDefinition` object locally, before creating an `IBCPacket` containing the definition for each neighboring chain. + +Each neighbor eventually receives -- from the corresponding relay process -- +an `IBCPacketTx` containing the packet; if the definition does not already +exist in the receiving chain, the latter will pass on the definition by +creating an `IBCPacket` for each of *its* neighbors -- except the source +chain from which it received the packet in the first place; if the +definition already exists, the receiving chain stops passing on the +definition. + +Similarly, when a `ServiceBinding` is created or updated with its +`BindingType` set or updated to `Global`, an `IBCPacket` containing the +binding is created for each neighboring chain, and gets propagated across +the entire IRIS network. + +An `IBCPacket` described above is composed of: + +* `Header (IBCPacketHeader)`: The packet header + +* `Payload (ServiceDefinition or ServiceBinding)`: The bytes of the service + definition or binding + +The `IBCPacketHeader` above is composed of: + +* `SrcChainID (string)`: The ID of the blockchain creating this packet + +* `DstChainID (string)`: The ID of the neighboring blockchain this packet is + destined for + +* `Number (int)`: A unique number for all packets + +* `Status (enum)`: `NoAck` + +* `Type (string)`: "iris-service-definition" or "iris-service-binding" + +Now let's take a look at how interchain service invocation happens through IBC. +When a request is made for a `Unicast` service, the application checks if +the target binding is `Local`; where this is true, the `ServiceRequest` is appended to the corresponding request table as explained in 2.2; otherwise, an +`IBCPacket` containing the `ServiceRequest` will be created instead. + +An `IBCPacket` containing a `ServiceRequest` is composed of: + +* `Header (IBCPacketHeader)`: The packet header + +* `Payload (ServiceRequest)`: The bytes of the service request + +The `IBCPacketHeader` above is composed of: + +* `SrcChainID (string)`: The ID of the blockchain creating this packet + +* `DstChainID (string)`: The ID of the blockchain where the remote provider + is located, i.e., `ServiceRequest.ServiceBinding.ChainID` + +* `Number (int)`: A unique number for all packets + +* `Status (enum)`: `AckPending` + +* `Type (string)`: "iris-service-request" + +* `MaxHeight (int)`: Current height + `ServiceRequest.Timeout` + +As a remote request finally arrives at the destination chain, the +application would append it to the corresponding endpoint (the request table) +for the targeted binding. A response to this remote request would be +wrapped in a receipt `IBCPacket` that is routed all the way back to the +source chain and appended to the remote endpoint (the response table) for +the originating consumer. + +Request for a remote `Multicast` service is treated in the same way except +that more than one `IBCPacket` could be generated in the source chain. + +Remote complaints and resolutions are expected to work in the same manner as requests and responses, and therefore will not be elaborated here. + +Below is a complete list of application-dependent `IBCPacket` types: + +| **Type** | **iService Object** | +| ------------------------- | ------------------- | +| "iris-service-definition" | ServiceDefinition | +| "iris-service-binding" | ServiceBinding | +| "iris-service-request" | ServiceRequest | +| "iris-service-response" | ServiceResponse | +| "iris-complaint" | Complaint | +| "iris-resolution" | Resolution | + +
+ +## Use Cases ################################################################ + +In this section, we have set out some potential use cases for the IRIS network. + +### Distributed AI for privacy preserving data analysis + +The proposed service infrastructure has been prototyped by Bianjie AI, a +Shanghai based startup, into its permission product `BEAN (Blockchain +Edge Analytics Network)` to solve the longstanding challenge of getting +data for running analytics models. Although homomorphic encryption is +one of the key methods allowing computing to be achieved over encrypted data, it is said to be unable to practically solve real world machine learning problems due to its slow performance. As a result, BEAN was created to take a different approach. This approach uses the idea of model parallelism taken from the traditional distributed AI study [\[14\]][14] and +utilizing SOA design patterns to develop distributed analytics services as an additional layer to the blockchain. + +To protect data access, the (partial) model that runs on the data side needs to be open sourced to the client and specified in the service definition. Since only the partial model is released to the client, the model developers do not have to worry about someone stealing their idea; equally, the data owners never need to worry about losing control of data usage as their data will not be leaving its origin. + +Other potential benefits could include the following: +1. Only a small amount of parametric data being exchanged on-chain, which can help enhance performance. + + . A more practical way for data usage auditing, which is often needed in the healthcare domain. + +Healthcare data is highly private, involving numerous security requirements. This puts forward the challenge for healthcare data to be used for the purposes of cross-organization collaboration (such as a cross-hospital clinic records search for diagnosis assistance, new drug clinic test patient identification, health insurance automatic claim processing etc.). This minimum viable product ("MVP") service layer implementation is built on top of `Ethermint` in attempt to connect hospitals, insurance companies and analytics service providers to provide privacy preserving healthcare data analytics capability. + +Smart contracts have been implemented to support on-chain service registration and invocation. One example of the off-chain data processing could be to support a Diagnosis Related Group ("DRG") grouping analytics service. More specifically, when a hospital user invokes the DRG service, the raw medical record is processed off-chain using service provider provided client side NLP (implemented as SQL and Python) code stub to exact structured data inputs for receiving DRGs service over blockchain without passing the highly confidential raw medical records. + +The `BEAN` +scenario demonstrates a more complicated service use case including +implementing distributed analytics, and connecting service providers as +well as service consumers, utilizing blockchain to provide audible +transaction ledge as well as trustworthy distributed computing +foundation. + +### Data and analytics e-marketplace + +From studying several proposed AI+Blockchain projects, it seems that most of the projects aim to provide data exchange markets and analytics API markets. With proposed `IRIS` infrastructure, those +networks could potentially be built with ease through publishing data as data services and wrapping analytics API as analytics services utilizing the `IRIS` service provider SDK. + +### Distributed e-commerce + +With the proposed `IRIS` infrastructure, integration with traditional systems +like `ERP` to obtain inventory information, or inter-chain query on trusted data sources to obtain information such as transportation and weather data, will be quite similar to the approach with which many enterprise application developers are already familiar. With those services integrated to support +distributed e-commerce applications, it could be possible for distributed e-commerce applications to provide a similar user experience as centralized systems, such as Amazon or Alibaba. + +### Combining public chains & consortium chains + +For many business scenarios, taking a hybrid architecture of combining the good features of a public chain and a consortium chain can provide beneficial results, particularly with regards to performance, security and economic incentives. + +For example, hospitals and insurance companies could form a consortium blockchain to support high performance medical insurance transactions, whilst identifying other information such as statistics regarding certain diseases as a global service, which can be invoked from other public chains. The tokens received from public chains can be awarded back to +those information providers in the consortium chain, which motivate the +system participants to improve and promote services. With this infrastructure provided by `IRIS`, large-scale spontaneous collaboration could be made possible while still supporting stringent performance and security requirements. + +There are many use cases that could be supported by the `IRIS` service +infrastructure, such as more efficient asset based security systems, +distributed regulation technology such as due diligence, mutual aid +marketplace etc. One of `IRIS` project plans is also working closely with +such application project teams to support and enable them with needed +blockchain infrastructure and allow them to focus on delivering the +envisioned business value more efficiently. + +
+ +## Token Economics ################################################################ + +Similar to the Cosmos Network, the IRIS network, as presently designed, is intended to support a multi-token model. The tokens will be held on the various zones, and can be moved from one zone to another via the IRIS Hub. There are two types of tokens that are expected to support IRIS network's operation: + +* staking token +* fee token + +### Staking token + +Adopting the same staking mechanism design used in the Cosmos network [\[15\]][15], the IRIS Hub will have its own special native token for staking. This token will be called "IRIS". We have a number of ideas in mind regarding the specific functionality of the IRIS token, including: + +* integration of the IRIS token in the IRIS network's consensus engine validators, through a system of validators and delegators; + +* voting power to participate in the IRIS network's governance + + +### Fee token + +There are two types of fee tokens in IRIS network: +* **Network fee** token is for spam-prevention and payment to validators in maintaining the + ledger; +* **Service fee** token is used for payment to service providers + who deploy iServices and the default payment service token is IRIS token. + +The IRIS network is intended to support all whitelisted fee tokens from the Cosmos network, e.g [Photon](https://blog.cosmos.network/cosmos-fee-token-introducing-the-photon-8a62b2f51aa), plus the IRIS token. + +Supporting a variety of whitelisted fee tokens is a feature that we plan to adopt from Cosmos. It can provide an enhanced experience for network participants. In Cosmos, for `network fee token`, each validator has a config +file defines his personal weighting of how much they value each fee +token. Validator can run a separate cron job to update the config file +based on validator preferred live market data or maybe just use a +default config value. + +For the `service fee token` design, similarly a multi-token model is planned to be supported. A service provider on the IRIS network should therefore have the freedom to charge for their services in their preferred tokens, provided that it appears on the whitelist. + +To help IRIS network participants mitigate cryptocurrency price volatility, the Foundation intends to facilitate the deployment of global iServices for retrieving market data from different exchanges, or through the potential introduction of oracles. + +Both staking and fee tokens are subject to further refinement to ensure compliance with legal and regulatory obligations. + +
+ +## Initial Token Distribution ################################################################ + +On Genesis, the initial token supply will be 2,000,000,000 IRIS tokens. The distribution of IRIS tokens is planned to be as follows: + +* **Private Sale**: 20% + +* **Core Developer Team**: 20% (4-year vesting period starting from IRIS Hub launch, during which the team will vest 1/48th of its IRIS tokens each month) + +* **IRIS Foundation**: 15% (reserved to support the operations of the Foundation) + +* **Ecosystem Development**: 45% (swap with zones connecting to IRIS Hub; grant to potential users; awards to outstanding partners; potential public sale) + +If and when the IRIS network is fully deployed, the annual inflation rate of IRIS tokens will be adjusted to account for the fact that a substantial portion of IRIS tokens in circulation may be voluntarily staked by participants to participate in the consensus engine. + +Proceeds from the private sale of IRIS tokens will be used, first and foremost, for the development of the IRIS network. The planned usage distribution is as follows: + +* **Foundation Operations**: 10% (including service providers and contractors fees, for example, auditing, consulting, legal and other third party fees, and other overheads) + +* **Software Development**: 50% (including costs, fees and expenses directly attributable to the development of launch) + +* **Developer Enablement**: 10% (including funding hackathons, awards to volunteers and training programs) + +* **Research and Development Sponsorships**: 10% (including conference, research programs and university outreach) + +* **Marketing and Promotion**: 20% (including business development, community programs and outreach, together with related travel, communication, publication, distribution and other expenses) + + +
+ +## Roadmap ################################################################ + +The expected IRIS project is set out below. We reiterate that the roadmap is indicative only, and subject to change. + +* **PANGU** (January 2018 \~ July 2018) The first stage of the IRIS project will focus on having the IRIS Hub up and running and connected to the Cosmos Hub. We also intend to release an initial version of the mobile client for the IRIS network. + + +* **NUWA** (July 2018 \~ November 2018) +The second stage will focus on building the fundamental IRIS Service Layer. This will involve enabling service definition, binding, invocation and query. +In this stage we are also aiming to have a beta version of the IRIS SDK ready for developers. + +* **KUAFU** (December 2018 \~ May 2019) The third stage will focus on incremental upgrades to the IRIS network in order to support our planned advanced IRIS Service governance features. + + +* **HOUYI** (Beyond June 2019) +The fourth stage will focus on further technology innovations to the IRIS network, IRIS SDK and mobile client, as well as developer engagement. + +
+ +## The Team ################################################################ + +**Tendermint** (the team that developed the [Tendermint](https://www.tendermint.com) consensus engine and is currently building Cosmos), **Wancloud** (a subsidiary of [Wanxiang +Blockchain](http://www.wxblockchain.com) and **Bianjie AI** will work together to build the IRIS network's infrastructure. + +Tendermint's intended role to give technical advice and development support to the IRIS project team in extending the Tendermint ABCI and the Cosmos IBC technologies. +[Wancloud](https://www.wancloud.io) is envisaged as the key strategy partner to both the Cosmos and IRIS ecosystems, and we understand that it intends to participate in Cosmos and IRIS development across Asia. + +**Bianjie AI** +will be the core development team for the IRIS network, leveraging the team's experience established from building distributed AI analytics services for healthcare data analysis and exchange. [Bianjie AI](https://www.bianjie.ai) is a Shanghai-based start-up established in 2016. It focuses on developing innovative products and solutions for healthcare and financial industries, using advanced Blockchain and AI technologies. One of Bianjie's core products, `BEAN (Blockchain Edge Analytics Network)` BEAN (Blockchain Edge Analytics Network), is a permission chain which delivers distributed data analytics services for privacy preserving healthcare data analysis and exchange using NLP and machine learning technologies. Bianjie AI is +currently extending `BEAN` capabilities to build the IRIS network. +**Bianjie AI** +is also the operation and service partner of Cosmos Network in China. + + +### Core Members + +**Harriet Cao** + +[Harriet](https://www.linkedin.com/in/harrietcao/) is the founder of Bianjie AI, which a Shanghai-based start-up focusing on building smart services for blockchain that enable trustworthy and efficient business collaborations using distributed AI technology. Harriet is an award-winning practitioner of data analytics and artificial intelligence technologies, and was the recipient of 2010 INFORMS Daniel H. Wagner Prize. Prior to establishing Bianjie AI, Harriet worked for IBM Research for more than 16 years in various capacities including Director of IBM Research Shanghai Lab and Big Data Analytics Leader for IBM Global Labs. +Harriet has an M.S degree in Robotics from Carnegie Mellon University and an M.S. degree in Automation Control from Tsinghua University. + + +**Haifeng Xi** + +[Haifeng](https://www.linkedin.com/in/haifengxi/) is a senior technologist and entrepreneur. Since returning to China from the United States in 2009, he had worked in the capacity of Chief Technology Officer for three companies, one of which is NASDAQ listed. He also co-founded two start-ups in Shanghai, where he plays an active role of technical leader and engineering champion. +Haifeng has a Master's degree in Electrical and Computer Engineering from the University of Maryland, and a Master's and Bachelor's degree in Automatic Control from Tsinghua University. + + +**Jae Kwon** + +After graduating from Cornell in 2005 with an undergraduate degree in computer science, [Jae](https://www.linkedin.com/in/yjkwon/) worked as a software developer in Silicon Valley, first at Amazon (where he worked on the Alexa digital assistant), then later at Yelp, where he led their mobile app development team. +After getting the blockchain bug, Jae created the Tendermint BFT consensus algorithm and the Tendermint Core blockchain engine, with the intent of creating a provably secure proof-of-stake algorithm. +In addition to Tendermint, Jae is also the creator of Cosmos. + + +**Tom Tao** + +Since joining Wanxiang in August 2016, [Tom](https://www.linkedin.com/in/tom-tao-14763a45/) is responsible for Wanxiang Blockhain Group's consulting service, Wancloud BaaS Platform as well as the ChainBase accelerator and incubator service. Before Wanxiang, Tom worked in service management and business management for over 18 years in a number of global leading companies. +Tom has spearheaded the introduction of cloud services, IoT data service platforms, and creative accelerator technologies into the Chinese market. +Tom has been tracking trends in the blockchain, cloud computing, IoT and smart manufacturing industries since 2013. Tom has a Master's degree in Physics from Fudan University and a Bachelor's degree in Electrical Engineering from Nankai University. + + +### Advisors + +**Jim Yang** + +[Jim Yang](https://www.linkedin.com/in/jimyang/) runs Strategy for Tendermint. He was the founder and CEO at ChatX, mobile messaging studio. ChatX developed various mobile messaging/social apps. He also co-founded Identyx, where he served as CEO until its acquisition by Red Hat. Identyx developed an open source enterprise identity management software. + +**Zaki Manian** + +[Zaki Manian](https://zaki.manian.org), Executive Director of Trusted IoT Alliance, is a prolific contributor to the development of blockchain and cryptocurrency technology. Zaki has deep expertise in cryptography and distributed consensus system. He is also an advisor to the Cosmos project, and several other investment funds and startup in the space. + +**Adrian Brink** + +[Adrian Brink](https://adrianbrink.com), Core Developer & Head of Community of Tendermint / Cosmos Network. + +**Michael Yuan** + +[Dr. Michael Yuan](http://www.michaelyuan.com) is the Director of the [CyberMiles Foundation](https://cm.5miles.com). Michael received a PhD in Astrophysics from University of Texas at Austin. He is the author of 5 books on software development, published by Prentice Hall, Addison-Wesley, and O'Reilly. Michael was an active code committer in large Open Source projects such as Firefox, Fedora, JBoss, and others. He is an expert on enterprise and mobile software, and was a Principle Investigator on multiple research projects funded by the US government. + +
+ +## References ################################################################ + +[1]: https://drive.google.com/file/d/1bI7JIOe-CfJ5fPHKxYlFub2Kg-KCGU6r/view?usp=sharing +[2]: http://ethdocs.org/en/latest/ +[3]: https://cosmos.network/whitepaper +[4]: https://polkadot.io/ +[5]: https://tendermint.readthedocs.io/en/master/ +[6]: https://ethermint.zone/ +[7]: http://www.freepatentsonline.com/y2017/0236120.html +[8]: https://github.com/cryptape/cita-whitepaper/blob/master/en/technical-whitepaper.md +[9]: https://github.com/hyperledger/burrow +[10]: https://lightning.network/lightning-network-paper.pdf +[11]: https://www.plasma.io/plasma.pdf +[12]: https://github.com/cosmos/ibc/blob/master/README.md +[13]: https://www.amazon.com/SOA-Principles-Service-Thomas-Erl/dp/0132344823 +[14]: http://www.cs.toronto.edu/~ranzato/publications/DistBeliefNIPS2012_withAppendix.pdf +[15]: https://medium.com/@tendermint/b5b2c682a292 +[16]: https://drive.google.com/file/d/1jtyYtx7t1xy9gxEi2T5lXFNd8xUY7bhJ/view + + +* [1] Wanxiang Blochchain Inc., Distributed Business Value Research Institute, + "Blockchain and Distributed Business Whitepaper", September 2017. + +* [2] Ethereum Foundation, "Ethereum Homestead Documentation", + http://ethdocs.org/en/latest/ + +* [3] Jae Kwon, Ethan Buchman,"Cosmos, A Network of Distributed + Ledgers", https://cosmos.network/whitepaper + +* [4] Gavin Wood, "Polkadot: Vision For a Heterogeneous Muilti-chain + Framework", https://polkadot.io/ + +* [5] Tendermint, https://tendermint.readthedocs.io/en/master/ + +* [6] Ethermint, https://ethermint.zone/ + +* [7] Oracle International Corporation, "Accountability and Trust in + Distributed Ledger Systems", USA Patent Application 20170236120, August + 17, 2017, http://www.freepatentsonline.com/y2017/0236120.html + +* [8] Jan Xie, "CITA Technical Whitepaper", + https://github.com/cryptape/cita-whitepaper/blob/master/en/technical-whitepaper.md + +* [9] Hyperledger Burrow, https://github.com/hyperledger/burrow + +* [10] Joseph Poon, Thaddeus Dryja, "The Bitcoin Lightning Network: + Scalable Off-Chain Instant Payments", January 14, 2016, + https://lightning.network/lightning-network-paper.pdf + +* [11] Joseph Poon, Vitalik Buterin, "Plasma: Scalable Autonomous Smart + Contracts", August 11, 2017, https://www.plasma.io/plasma.pdf + +* [12] Ethan Frey, "Cosmos IBC Specification", Sep. 29, 2017, + https://github.com/cosmos/ibc/blob/master/README.md + +* [13] Thomas Erl,  "SOA: Principles of Service Design", Prentice Hall; + 1st edition (July 28, 2007) + +* [14] Dean, J., Corrado, G.S., Monga, R., et al, Ng, A. Y. "Large Scale + Distributed Deep Networks". In Proceedings of the Neural Information + Processing Systems (NIPS'12) (Lake Tahoe, Nevada, United States, + December 3--6, 2012). Curran Associates, Inc, 57 Morehouse Lane, Red + Hook, NY, 2013, 1223-1232. + +* [15] Tendermint Blog, "Cosmos Validator Economics -- Revenue Streams", + January 2018, https://medium.com/@tendermint/b5b2c682a292 + +* [16] Sunny Aggarwal, "Cosmos Token Model", December 2017, + https://drive.google.com/file/d/1jtyYtx7t1xy9gxEi2T5lXFNd8xUY7bhJ/view diff --git a/docs/introduction/Whitepaper_CN.md b/docs/introduction/Whitepaper_CN.md new file mode 100644 index 000000000..cfb8d494d --- /dev/null +++ b/docs/introduction/Whitepaper_CN.md @@ -0,0 +1,616 @@ +# IRIS 网络白皮书 + +**用于构建可信分布式商业应用的跨链服务基础设施及协议** + +Harriet Cao harriet@bianjie.ai
Haifeng Xi haifeng@bianjie.ai + +_NOTE:如果你可以在GitHub上阅读,那么我们仍然在积极完善这个文档。 请定期检查更新!_
+ +## 目录 + +- [免责声明](#disclaimer) +- [IRIS 概览](#iris-概览) + - [Cosmos 和 Tendermint](#cosmos-和-tendermint) + - [IRIS 技术创新](#iris-技术创新) +- [IRIS网络设计](#iris-网络设计) + - [网络参与者](#网络参与者) + - [IRIS服务](#iris-服务) + - [IBC 改进](#ibc-改进) +- [用例](#用例) +- [通证经济](#通证经济) +- [初始通证分配](#初始通证分配) +- [路线图](#路线图) +- [团队](#团队) + - [核心成员](#核心成员) + - [顾问](#顾问) +- [参考文献](#参考文献) + +
+ +## 免责声明 + +本白皮书及其相关文档用于接下来对IRIS网络的开发和应用。仅做信息传播之用并可能更改。 + +### 本文介绍了一个开发中的项目 + +本文基于IRIS 基金会有限公司(IRIS Foundation Limited)提供的已知信息及假设,包含了符合该基金会理念的前瞻性声明。 + +本文所设想的IRIS网络尚在开发中,并将不断更新,这些更新包括但不限于关键治理和关键技术。 开发使用IRIS通证或与之相关的测试平台(软件)以及技术,可能无法实现或无法完全实现本白皮书所述的目标。 + +如果IRIS网络得以完成,可能与本文所述有所不同。本文不对未来的任何计划、预测或前景的成功性或者合理性做出陈述或保证,本文的任何内容都不应被视为对未来的承诺或陈述。 + +### 并非监管类产品的要约 + +IRIS通证不代表任何一种有价证券或者任何其它司法监管下的产品。 + +本文不构成对任何有价证券或其他受监管产品的出价要约或询价邀请,也不构成以投资为目的的促销、邀请或询价。其购买条款并非提供金融服务的文件或任何类型的招股说明书。 + +IRIS通证不代表任何平台或软件系统、或IRIS 基金会有限公司以及其他任何公司的股权、股份、单位、资本权益或版权使用费、利润、回报或收入,不代表任何与平台有关的公有或私有企业、公司、基金会以及其他受监管实体的知识产权。 + +### 并非建议 + +本白皮书不构成任何对IRIS通证的购买建议。请不要依赖本白皮书去达成任何合同或购买的决策。 + +### 风险警告 + +购买IRIS通证并参与IRIS网络伴随着极大的风险。 + +在购买IRIS通证之前,您应该仔细评估并考虑风险,包括在上和其他任何文档中列出的风险。 + +### 仅代表IRIS基金会有限公司的意见 + +本白皮书所表达的观点为IRIS 基金会有限公司的观点,并不一定反映任何政府、准政府、当局或公共机构(包括但不限于任何管辖范围内的任何管辖机构)的官方政策或立场。 + +本白皮书中的信息基于IRIS 基金会认为可靠的来源,但并不能保证其准确性或完整性。 + +### 英文是本白皮书的授权语言 + +本白皮书和相关材料仅以英文发行。任何翻译并未经IRIS 基金会有限公司或其他人员认证,其准确性和完整性无法保证,仅供参考。如果翻译与本白皮书的英文版本之间有任何不一致之处,则以英文版本为准。 + +### 非第三方从属关联或背书 + +本白皮书中提及的特定公司和平台仅供参考。使用任何公司和/或平台名称和商标并不意味着与其有任何的从属关联或背书。 + +### 您必须获得所有必要的专业建议 + +您有必要在决定是否购买IRIS通证或参与IRIS网络项目之前,必须咨询律师、会计师和/或税务专业人员,以及其他专业顾问。 + +
+ +## IRIS 概览 + +> IRIS网络是以希腊女神Iris的名字命名的,她是彩虹的化身,是在天堂和人类之间忠诚传递消息的信使。 + +契约关系是人类社会的基本组成部分,区块链技术的重要性在于提供一种非常有效和低成本的方式来实现可靠的契约关系:第一次出现了多方参与复杂的业务交互时不再需要(本来非常昂贵的)信任。 也就是说区块链技术为分布式商业提供了最重要的元素:以极低的交易成本提升网络效益。越来越多的人认识到区块链作为新的价值互联网的影响力,并将逐步把当前的商业模式转变为更高效的分布式网络。 特别是内置于大多数现代区块链中的通证机制,强调每个网络参与者的权利,并将革新商业的现有模式[[1]]。 + +不过,区块链技术仍处于早期阶段。与其它新技术一样也存在缺点,包括有限的性能和还没有发展起来的治理机制。目前,这些缺点使区块链难以支持真实的分布式商业协作。 诸如Hyperledger Fabric和R3 Corda,以及以太坊企业联盟(Ethereum Enterprise Alliance)等组织都在试图通过联盟链(consortium chains)解决这些性能和治理的问题,使区块链技术更适用于企业。然而,如今的联盟链由大型企业公司主导的,他们封闭式的链上链下治理模式非常低效。联盟链可能因为缺乏公有链的通证经济模型及其开放性和激励性而缺乏活力。 + +我们希望发展当前的区块链技术,让成千上万的中小企业(Small Medium Businesses,SMBs),甚至是个体自由职业者,可以在一个开放的网络中提供他们的服务并享受回报。为了实现这一目标,我们确定了以下挑战以及随之而来的技术创新机会: + +**并非所有的运算都可以或应该以诸如智能合约这样的形式在区块链上实现** + +以太坊提供了[图灵完备](https://en.wikipedia.org/wiki/Turing_completeness)的虚拟机 [[2]]运行智能合约,带给人们开发分布式应用的诸多希望。 然而,智能合约只能处理确定性逻辑(因此每个节点在处理完同一交易和块后都能达到相同的状态),而大量现存的业务逻辑是不确定的,在不同时间和不同环境参数下可能会发生变化。 特别是现在,业务系统越来越依赖于计算机的算法进行决策优化,包括自然语言处理(Natural Language Processing,NLP),机器学习和操作研究算法。我们经常会故意在这些算法中添加一些随机性,以使决策不仅仅是局部最优状态,同时试图找到一个更好的次优结果。 + +另一方面,一些真实世界的业务逻辑应该在链下运行,不应该作为诸如可重复运算的智能合约这种类型来执行。 利用分布式账本集成和协同链下的服务和资源,是进一步推动区块链技术在更多真实场景中应用的关键。 + +**如何利用现有的区块链资源,包括公有链和联盟链** + +使用一个公有链来处理所有用例是不可行的。每天都有不同的区块链上线,各自专注于解决问题的一个方面,比如分布式存储、资产所有权或市场预测等。据coinmarketcap.com显示,目前有超过1000种加密货币在不同的交易平台上活跃。 + +构建业务应用程序时涉及处理存储以及不同数据源的来源,我们的另一个工作动机是如何通过重用一些现有的工作,比如存储(IPFS, SIA, Storj.io等等)、数据发送(Augur,Gnosis,Oraclize等)和物联网(IOTA等)提供的这些专用的区块链,而不是“重新发明轮子”。 + +此外,有很多(近)实时业务交易确实需要更密切的联盟链/许可链/私有链来处理性能问题、安全问题和业务治理要求。因此,我们对分布式商业基础设施的愿景是要具备在多种异构链,包括公共链/联盟链/许可链/私有链之间具备互操作的能力。 + +跨链技术是满足这一需求非常自然的解决方案。 然而目前为止,现有的跨链技术主要是为了在已有区块链中提供互操作性,并专注于通证的价值转移。 如何使用不同区块链提供的资源,这一问题仍然没有答案。 + +比较现有的跨链技术如Cosmos [[3]] 和 Polkadot[[4]],提出的跨链技术,我们发现Cosmos为互操作性和可扩展性提供了更成熟的基础。 尤其我们发现Cosmos的多枢纽多分区( "many hubs and many zones" )和每个分区都是独立的区块链,拥有独立的治理模型( "each zones are independent blockchains having independent governance models" 的设计,提供了一种非常合适的体系架构,可以用SOC(Seperation of Concern,SOC)的方式对现实世界的复杂性进行建模。 为了最好地重用现有框架,我们提出了IRIS网络(IRIS Network),它是由一个枢纽和众多分区构成的去中心化的跨链网络,基于Cosmos/Tendermint [[5]]实现,具有更为完善的通证使用。 + +鉴于IRIS网络是基于Cosmos/Tendermint设计的,我们将首先讨论Cosmos/Tendermint,总结我们从Cosmos/Tendermint继承的特性和独特的创新。 + +### Cosmos 和 Tendermint + +Cosmos[[3]]想要建立“区块链的互联网”。 这是由许多被称为分区“Zone”的独立区块链构成的互联网络,每个分区都由经典的拜占庭容错(Byzantine fault-tolerant,BFT)共识协议(如Tendermint)提供支持。 + +Tendermint提供了一个高性能、一致的、安全的BFT共识引擎,严格的分叉问责保证能够控制作恶者的行为。Tendermint非常适合用于扩展异构区块链,包括公有链以及注重的性能的许可链/联盟链,像Ethermint [[6]]就是一次对Ethereum以太坊POS机制的快速实现。 使用Tendermint在许可/联盟链域中的成功案例包括Oracle [[7]],CITA [[8]] 和Hyperledger Burrow [[9]]。 + +Tendermint作为共识协议用于在Cosmos Hub上构建第一个分区。Cosmos Hub可以连接到许多不同类型的分区,并且通过一种相当于区块链之间的虚拟UDP或TCP的IBC协议( Inter-blockchain Communication,IBC)实现跨链通信。 通证可以安全地通过Cosmos Hub从一个分区转移到另一个分区,而不需要在分区之间的交易所或受信任的第三方。 + +为了使用Cosmos Hub开发强大的可互操作区块链和区块链应用,Cosmos SDK提供了区块链常用模块的开发“入门套件”,而不是限制可实现的用户故事,从而为应用定制提供了最大的灵活性。 + +### IRIS 技术创新 + +IRIS网络的目标是为构建分布式商业应用提供技术基础设施,它超越了主要用于数字资产的现有区块链系统。 + +我们打算通过IRIS网络解决的关键挑战在于两个方面: +- 利用分布式账本支持链下运算资源的集成和协同 +- 服务跨异构区块链的互操作性 + +我们通过将面向服务的基础架构融入Cosmos / Tendermint来应对这些挑战。 + +我们的设计继承了多年来面向服务架构(Service-oriented Architecture,SOA)实践的思维模式。 SOA是一种架构方法,用于创建由自治服务构建的系统,这些系统具有明确的边界、共享模式和契约[[13]]。早期的SOA实践侧重于实施企业服务总线(Enterprise Service Bus,ESB),通过服务提供者和服务消费者之间的各种点对点连接组成公用总线,实现服务间的通信。但是,通过ESB集中管理服务可能会触发单点故障,也会增加服务部署的依赖性。最近大量的微服务架构可以看作是SOA的发展,不再关注ESB而是使用轻量级的消息队列进行服务间通信。在IRIS网络中,服务之间的通信旨在通过实施区块链作为信任机器来协同实现商业协作,使它在服务提供者和服务消费者之间很难建立信任的前提下也能运行。 + +IRIS网络使用Tendermint协议作为高性能的共识引擎。利用Tendermint的区块链应用接口(Application BlockChain Interface,ABCI)提供的灵活性,我们定义了一组服务的基础交易类型,包括:服务提供,服务消费和服务治理。如前所述,大多数业务逻辑不适合作为区块链上确定的智能合约来实施,我们正在使用这个服务层将业务应用的特定逻辑和事务处理移出区块链,仅使用区块链对这些服务产生的结果达成共识。这一想法也受到区块链社区已有成果的启发,将一些复杂计算从主链上移除以解决性能问题,例如Lightning Network的离线状态通道[[10]]以及Plasma的防欺诈侧链[[11]]。尽管我们没有实施侧链,但是我们将传统业务逻辑计算从区块链中剥离出来,并将其用作复杂业务协作的可信中介总线。 + +对于跨链通信,Cosmos IBC [[12]]定义了一个协议用于将价值从一条链上的某个帐户转移到另一条链上的某个帐户的协议。而IRIS网络设计了新的语义,以允许利用IBC调用跨链计算资源。我们认为这种能力在构建可扩展的业务应用程序时非常重要。更详细的潜在用例将会在后面描述。 + +IRIS网络旨在提供服务基础设施,以处理和协同链上的交易处理与链下的数据处理和业务逻辑执行。必要时,扩展的IBC功能允许那些链下的处理被跨链调用。 按目前的设想,IRIS网络还将包含客户端工具,一个支持跨链多资产存储的智能钱包以及服务消费方和提供方使用的iServices。 我们计划提供SDK以轻松构建iServices。 例如,对于特定的服务定义,客户端Client SDK将生成服务提供方的框架以及服务消费方的模块。 + +
+ +## IRIS 网络设计 + +![img](https://github.com/irisnet/irisnet/blob/master/images/chap2-1.png?raw=true) + +如上图所示,IRIS网络在设计上与Cosmos网络具有相同的拓扑结构。 我们计划将IRIS Hub作为Cosmos众多分区和区域型Hub之一与Cosmos Hub连接起来。IRIS SDK本身就是计划对Cosmos SDK的扩展,由IRIS SDK开发的IRIS全节点旨在提供一个服务的基础设施,并在内部集成了分布式文件系统IPFS(InterPlanetary File System,IPFS)。 + +IRIS Services(又名“iServices”)旨在对链下服务从定义、绑定(服务提供方注册)、调用到治理(分析和争端解决)的全生命周期传递,来跨越区块链世界和传统业务应用世界之间的鸿沟。 IRIS SDK通过增强的IBC处理逻辑来支持服务语义,以允许分布式商业服务在区块链互联网上可用。 + +尽管IRIS网络专注于为分布式业务应用提供创新解决方案,但它仍是Cosmos网络的一部分。 连接到IRIS Hub的所有分区都可以通过标准IBC协议与Cosmos网络中的任何其他分区进行交互。此外,我们相信通过引入服务语义层可以实现全新的业务场景,创新的IRIS网络将增加Cosmos网络的规模和多样性。 + +### 网络参与者 + +1. **服务消费者** 服务消费者是通过向网络发送请求并接收响应来使用链下服务的用户。 + +2. **服务提供者** 服务提供者是那些可能提供一个或多个iService定义的用户,并且通常是其它公有链和联盟链甚至传统企业应用系统中链下服务和资源之间的适配器。服务提供者监听和处理传入的请求,并将结果发送回网络。一个服务提供者可以向其它服务提供者发送请求而同时成为服务消费者。服务提提供者可以按计划为他们提供的任何服务收取费用,默认情况下服务费使用IRIS网络的原生费用通证“IRIS”定价;也可以在适当的时候考虑使用Cosmos白名单中的其他费用通证对服务定价。 + +3. **分析员** 分析员是一种特殊用户,代表了发起建立IRIS网络的IRIS基金会有限公司(IRIS Foundation Limited),这是一家注册在香港的股份有限公司。分析员是在分析模式中调用iServices的唯一授权用户,旨在帮助创建和维护服务提供者的概要文件,通过这些客观的概要文件服务消费者可以选择合适的服务提供者。 + +### IRIS 服务 + +在本节中,我们列出了在IRS网络上部署iService时预计使用的技术参数。 + +**服务定义** + +`Method`包括 : + +* `ID (int)`: iService中该方法的唯一标识 +* `Name (string)`: iService中该方法的唯一名称 +* `Description (string)`: 对该方法的描述 +* `Input (string)`: 对输入参数的结构化定义 +* `Output (string)`: 对输出结果的机构化定义 +* `Error (string)`: 对可能出现的错误条件的结构化定义 +* `OutputPrivacy (enum)`: 设置此方法是非隐私的还是公钥加密的,可选值`NoPrivacy`/`PubKeyEncryption` + +`ServiceDefinition`包括: + +* `Name (string)`: 该iService服务的名称 +* `Description (string)`: 对此iService服务的描述 +* `Tags (string)`: 此iService服务以逗号分隔的关键字 +* `Creator (string)`: 对此iService服务创建者的描述. *可选* +* `ChainID (string)`: 最初定义此iService服务的区块链标识 +* `Messaging (enum)`: 设置此服务消息是单播还是多播,可选值`Unicast`/`Multicast` +* `Methods ([]Method)`: 定义此iService服务中可用的方法 + +`CreateServiceDefinitionTx` 交易包括: + +* `Definition (ServiceDefinition)`: 创建的服务定义 + +**服务绑定**: + +`CreateServiceBindingTx` 交易包括: + +* `DefinitionHash ([]byte)`: 服务定义的哈希值,由服务提供者绑定 +* `ChainID (string)`: 服务提供者所接入的区块链标识 +* `ProviderAddress ([]byte)`: 服务提供者的区块链地址 +* `BindingType (enum)`: 对服务是本地还是全局的设置,可选值`Local`/`Global`;其中`Global`选项将绑定暴露到全局,反之则使用`Local` +* `ProviderDeposit (int64)`: 服务提供者的保证金。服务提供者必须提供大于系统参数`MinProviderDeposit`所设(以IRIS通证计数)的保证金,才能创建有效的绑定,押金越高意味着更值得信任 +* `ServicePricing (string)`: 服务定价。基于每个方法对服务价格模型的结构化定义,包括每次的调用成本、批量折扣、促销条款等;服务费默认使用IRIS通证也可以是白名单列出的其它费用通证 +* `ServiceLevel (string)`: 服务水平。对服务提供者自己认可所绑定服务水平的结构化定义,包括响应时间、可用性等。 +* `BindingExpiration (int64)`: 此绑定过期的区块高度,采用负数即表示“永不过期” + +`UpdateServiceBindingTx` 交易包括: + +* `DefinitionHash ([]byte)`: 服务定义的哈希值,由服务提供者绑定 +* `ChainID (string)`: 服务提供者接入区块链标识 +* `ProviderAddress ([]byte)`: 服务提供者的区块链地址 +* `ChangeSet (string)`: 更改集,由前面三个字段确定的现有绑定所需更改内容的结构化定义 + +![img](https://github.com/irisnet/irisnet/blob/master/images/chap2-2.png?raw=true) + + +服务提供者可以在任何时间更新`ServicePricing`,`ServiceLevel`和`BindingExpiration`,但他们的少量保证金将随后续(分别由`ServiceLevelUpdateSlash`和 `BindingExpirationUpdateSlash`规定的)两种情况减少。当`BindingExpiration`设置的高度低于当前区块高度,将立即被解释为无效的绑定。 + +更新 `ProviderDeposit`将始终被视为*adding to*,即增加当前保证金余额。当保证金低于`MinProviderDeposit`时,绑定将失效,直到服务提供者增加余额高于阈值方可恢复。绑定过期或者失效的时候,保证金余额将自动返还给服务提供者。 + +`BindingType`可用从`Local`更改为`Global`,但反之不行。要把一个绑定从`Global` 降到 `Local`,服务提供者只能先使绑定的问题失效,然后重新创建一个 `Local`型的绑定。 + +如果服务提供者出于某种原因需要将绑定移到一个新地址,是不允许直接更新`ProviderAddress`的;必须先使当前绑定失效,再使用所需的 `ProviderAddress`创建另一个绑定. + +一个 `ServiceBinding` 的对象将在应用程序成功的执行这两个交易时(例如,在IRIS SDK种的iService业务逻辑)被创建或更新. + +`ServiceBinding`包括: + +* `DefinitionHash ([]byte)` +* `ChainID (string)` +* `ProviderAddress ([]byte)` +* `ServiceLevel (string)` +* `ServicePricing (string)` +* `BindingExpiration (int64)` +* `IsValid (enum)`: 可选项`True`/`False` + +**服务调用** + +![img](https://github.com/irisnet/irisnet/blob/master/images/chap2-3.png?raw=true) + +服务消费者和服务提供者被建议通过 *端点(endpoints)* 交互。有两种服务端点 —— *请求表(request table)* 和 *响应表(response table)* (见上图)。服务请求被添加到请求表,感兴趣的服务提供者监控这些请求表并接收和处理发送给他们的请求; 服务结果(或错误)被返回由相应的服务消费者反过来监控的响应表中。 + +`Multicast`多播服务的所有绑定共享一个请求表;而`Unicast`单播服务为每个绑定创建和维护单独的请求表。 至于另一个方向(的服务)将为每个服务消费者创建和管理专用的响应表。 + +`ServiceRequest`交易包括: + +- `ChainID (string)`: 服务消费者所接入的区块链标识ID +- `ConsumerAddress ([]byte)`: 服务消费者所的区块链地址 +- `DefinitionHash ([]byte)`: 服务定义的哈希值 +- `MethodID (int)`: 被调用的方法ID +- `InputValue (string)`: 输入值的结构化表示 +- `BindingHash ([]byte)`:在'Unicast'单播服务情况下目标绑定的哈希值。 *可选* +- `MaxServiceFee (int64)`: 服务消费者愿意为一个'Multicast'多播请求支付的最大服务费金额 。*可选* +- `Timeout (int)`: 服务消费者愿意等待响应返回的最大区块数 + +`PostServiceRequestTx` 交易包括: + +- `Requests ([]ServiceRequest)`: 被发送的服务请求 +- `RequestDeposits ([]int64)`: 服务消费者必须为每个请求者(使用IRIS计数)支付大于`MinRequestDeposit`的押金。此押金目的是为了激励消费者及时确认收到的服务响应(参考 `ConfirmServiceResponseTx`). + +应用程序将验证用户与'ChainID'和'ConsumerAddress'一致的每一个请求、目标绑定的有效性、请求押金充足,服务消费者帐户余额足够支付请求押金和服务费用,并且请求的总数小于`MaxRequestPostBatch`。 + +当一个已验证请求被追加到请求表中时,相关服务费用(对'Multicast'多播方式是'MaxServiceFee')将从服务消费者的账户中扣除并锁定到第三方托管。 + + `GetServiceRequest` 查询包括: + +- `DefinitionHash ([]byte)`: 服务定义的哈希值 +- `BindingHash ([]byte)`: 服务提供者对此问题绑定服务的哈希值; 应用程序将验证绑定有效,并且调用者具有匹配绑定的区块链标识`ChainID`和服务提供者地址`ProviderAddress` +- `BeginHeight (uint64)`: 应用程序应当从此区块高度开始检索对服务提供者的请求,一般是最大请求数'BatchSize'和'MaxRequestGetBatch'中较小的一个 +- `BatchSize (int)`: 返回的最大请求数 + + `ServiceResponse` 查询包括: + +- `RequestHash ([]byte)`: 所匹配请求的哈希值 +- `BindingHash ([]byte)`: 服务提供者绑定服务的哈希值 +- `OutputValue ([]byte)`: 输出结果的结构化(可能加密)表示。*可选* +- `ErrorMsg (string)`: 错误信息的结构化表示。*可选* + + `PostServiceResponseTx` 交易包含: + +- `Responses ([]ServiceResponse)`: 服务回复内容 + +应用程序将验证服务提供者的每个响应是否带有匹配的区块链标识`ChainID`和地址`ProviderAddress`,并且该交易中的响应数少于`MaxResponsePostBatch`。经过验证的请求将附加到目标消费者的响应表中。 + +`GetServiceResponse` 查询包括: + +- `RequestHash ([]byte)`: 原始请求的哈希值,应用程序将校验调用者是否有匹配的区块链标识'ChainID'和服务消费者地址'ConsumerAddress' +- `BeginHeight (uint64)`: 应用程序应当从此区块高度开始检索服务提供者的响应,一般是最大响应数`BatchSize`和`MaxResponseGetBatch`中的较小的一个 +- `BatchSize (int)`: 返回的最大响应数 + +`ConfirmServiceResponseTx` 交易包含: + +- `ResponseHash ([][]byte)`: 待确认响应的哈希值 + +应用程序将验证每个待确认响应是否确实是由调用者发起的请求,并且此交易中的响应数量小于`MaxResponseConfirmBatch`。 + +从`Timeout`超时窗口中退出的响应(对于'Multicast'多播服务,当`MaxServiceFee`随响应返回增加而消耗光时)将不会被应用程序接受。服务消费者一收到'Unicast'单播响应就立即开始处理。然而,对于`Multicast`多播响应,必须等待`Timeout`超时窗口结束,然后才开始处理可能收到的全部响应。 + +当一个`Unicast`单播响应被用户确认,相关服务费用将从托管账户中释放到匹配的服务提供者账户 ——其中扣除少量(由'ServiceFeeTaxRate'定义的)税金并添加到*系统准备金(system reserve)* 中; 同时,相关请求的押金也将退还给服务消费者。 + +在`Multicast`多播请求的情况有点复杂:每个响应确认时,只有部分请求押金被退还给服务消费者,即此响应相关服务费用占`MaxServiceFee`的比例; 在所有的响应被确认之后,此请求剩余的托管余额将会退还给服务消费者。 + +如果请求超时而没有看到任何响应,则应用程序将托管中的相关余额以及请求押金全额退还给用户。但是,如果用户没有(在`ResponseConfirmTimeout`+响应区块数的高度之前)及时确认回复,请求押金将被执行一个(由`ResponseConfirmDelayPenaltyRate`定义的)小惩罚再退还给消费者,与此同时,相关服务费将照常释放给服务提供者。 + +**争议解决** + +在任何情况下如果服务消费者对服务响应不满意,就应该存在一种机制允许服务消费者发出投诉,从而获得可接受的解决方案,而不必求助于诸如法律系统等集中的权威。同时,这种机制应避免引入可能会被任一方滥用的主观评价。 + +解决出现在IRIS网络上的争议,其过程类似于服务调用,不仅服务消费者向服务提供者发送`Complaint`(服务),而且服务提供者以一个`Resolution`(服务)进行响应。这些交互是通过一对称为 *投诉表(complaint table)* 和 *解决方案表(resolution table)* 的全局端点来实现的。 + +在IRIS网络目前的设计中,提交投诉时需要一份消费押金。如果服务消费者不及时确认某个解决方案,将从该押金中扣除罚款。同样地,如果服务提供者不及时响应投诉,他的保证金将被部分削减。 + +`Complaint` 包含: + +- `ResponseHash ([]byte)`: 对争议响应的哈希 +- `Problem (string)`: 对服务响应的问题描述 +- `PreferredDisposal (enum)`: 可以是`Refund`或`Redo`选项 + +`Resolution`包括: + +- `ComplaintHash ([]byte)`: 对所匹配投诉的哈希 +- `Disposal (enum)`: 可以是`Refund`或`Redo`选项 +- `Refund (uint64)`: 服务费退款. *可选* +- `OutputValue ([]byte)`:输出结果的结构化(可能加密)表示。 *可选* + +如上所述,我们预期的争议解决流程可能不具有法律约束力。尽管如此,我们认为这将为解决IRIS网络上的常见争议提供有效手段。 + +**服务分析** + +引入iService生态系统带来一些挑战。一个主要的挑战是找到一种方法,让服务消费者更容易发现合适的服务提供者——服务消费者需要性能指标来评估和选择服务提供商,但如果没有服务消费者的使用,性能指标也就不可用。 + +为了试图解决这个循环问题,我们计划引入一种分析机制,在这个机制中,一个享有特权的系统用户即分析员,在常规的调度下调用所有活动的服务。这将使网络中的客观性能数据(例如响应时间、可用性、投诉处理等)对实际消费者有用。 + +服务分析调用将免除服务费用和消费押金,但会产生网络交易费用。这些调用来自那些被应用程序识别和认可的保留地址。 + +对于新服务,分析活动将保持相对稳定的水平,随着它们开始吸引真正的服务消费者调用并预计生成更多的性能数据,分析活动将逐渐减少单个服务的使用。 + +分析过程中发生的交易费用默认情况下从系统准备金(system reserve)中支付,必要时基金会准备金(Foundation reserve)将会介入。 + +**查询** + +上述所有与服务生命周期相关的对象都可以使用ABCI 'Query'接口[\[3\]]查询到。这些查询将通过'Query'连接执行,并不参与共识过程。我们已经看到了如何得到的`GetServiceRequest`和得到`GetServiceResponse`查询作为服务调用过程的一部分。 +上面描述的所有与服务相关的生命周期对象都可以使用ABCI查询接口3来查询。 + +以下是我们目前计划的查询的一个非详尽的摘要: + +**服务对象** + +| Object | Commonly Used Filters | Authorization | +| ---------------------------------------- | ------------------------------------------------------------ | ------------------------ | +| Service Definition | Name, keywords, source (chain ID), messaging type, with active bindings... | Anyone can query | +| Service Binding (for a given definition) | Location (local or remote), pricing, service level, expiration... | Anyone can query | +| Service Request | Service definition and binding, blockchain height, batch size | Only matched provider(s) | +| Service Response | Service request, blockchain height, batch size | Only matched consumer | + + +**性能指标** + + +| Area | Metrics | Authorization | +| --------------------------- | ------------------------------------------------------------ | ---------------- | +| Provider (address) | Number of services provided (ever and active), response time (min, max and average), requests served (local and remote), requests missed, complaints received, complaints ignored, ... | Anyone can query | +| Provider (binding) | Active time, response time (min, max and average), requests served (local and remote), requests missed, complaints received, complaints ignored, ... | Anyone can query | +| Consumer | Number of services ever used, requests made, requests confirmed (in time and missed), complaints made, resolutions confirmed, ... | Anyone can query | +| Consumer (service, binding) | Requests made, requests confirmed (in time and missed), complaints made, resolutions confirmed, ... | Anyone can query | + +### IBC 改进 + +在Cosmos上建立自己的服务基础架构有一个独特优势:*服务可以部署一次,并通过区块链互联网随时随地进行调用*。具体来说,我们的计划是完成以下内容: +1. 服务定义广播到IRIS网络中的每个分区; +2. 全局服务绑定广播到IRIS网络中的每个分区; +3. 针对远程提供者的服务请求或投诉被路由到提供者所连接的区块链; +4. 针对远程消费者的服务响应或决议被路由回消费者所连接的区块链。 + +在处理一个`CreateServiceDefinitionTx`交易时,应用程序被设计为首先在本地验证和存储`ServiceDefinition`对象,然后创建一个包含了对每个相邻链定义的`IBCPacket`。 + +每个相邻链最终从相应的中继过程中接收包含该数据包的`IBCPacketTx`;如果此定义在接收链中尚不存在,则后者将通过为他的每个相邻链(除了最初接收数据包的源链之外)创建一个`IBCPacket`来传递此定义;如果该定义已经存在,接收链将停止传递此定义。 + +同样,当`ServiceBinding`创建或更新它的`BindingType`集合或更新为`Global`时,将为每个相邻链创建一个包含绑定的`IBCPacket`数据包,并在整个IRIS网络中进行广播。 + +上述`IBCPacket`由以下部分组成: + + +- `Header (IBCPacketHeader)` :数据包的头部 + + +- `Payload(ServiceDefinition或ServiceBinding)`:服务定义或绑定的字节数 + +前面提到的`IBCPacketHeader`由以下部分组成: + +- `SrcChainID(string)`:创建此数据包的区块链标识ID +- `DstChainID(string)`:此数据包将派往的相邻区块链标识ID +- `Number(int)`:数据包对应的唯一编号 +- `Status(enum)`:'NoAck' +- `Type (string)`:“iris-service-definition”或者是“iris-service-binding” + +现在让我们来看看如何通过IBC发生跨链服务调用。当请求一个`Unicast`单播服务时,应用程序检查目标绑定是否是`Local`本地的,如果是`Local`则将`ServiceRequest`追加到相应的请求表中,如2.2所述;否则,将会创建一个包含`ServiceRequest`的`IBCPacket`。 + + +包含一个'ServiceRequest'的`IBCPacket`由以下部分组成: + +- `Header(IBCPacketHeader)`:数据包的头部 +- `Payload(ServiceRequest)`:服务请求的字节数 + +前面提到的`IBCPacketHeader`由以下部分组成: + +- `SrcChainID(string)`:创建此数据包的区块链标识ID +- `DstChainID(string)`:远程服务提供者所在的区块链标识ID,例如'ServiceRequest'、'ServiceBinding'、'ChainID' +- `Number(int)`:数据包对应的唯一编号 +- `Status(enum)`:'AckPending' +- `Type(string)`:“iris-service-request” +- `MaxHeight(int)`:当前高度加上'ServiceRequest.Timeout' + +当远程请求最终到达目标链时,应用程序将其追加到相应的端点(请求表)中,以便进行目标绑定。对此远程请求的响应将被包装在一个收据IBCPacket中,该收据被一直路由回到源链,并将其追加到原始消费者的远程端点(响应表)中。 + +对远程的`Multicast`多播服务的请求以相同的方式处理,只不过可以在源链中生成多个`IBCPacket`。 + +远程投诉和解决的工作方式与请求和响应的方式相同,因此在此不做详细阐述。 + +下面是应用程序依赖`IBCPacket`类型的完整列表: + +| **类型** | **iService 对象** | +| ------------------------- | ------------------- | +| "iris-service-definition" | ServiceDefinition | +| "iris-service-binding" | ServiceBinding | +| "iris-service-request" | ServiceRequest | +| "iris-service-response" | ServiceResponse | +| "iris-complaint" | Complaint | +| "iris-resolution" | Resolution | + +
+ +## 用例 + +在本节中,我们为IRIS网络列出了一些可能的用例。 + +### 分布式人工智能用于隐私保护下的数据分析 + +这个用例的服务基础架构已由位于上海的初创公司`边界智能`进行了原型设计,并将其应用到联盟链产品`BEAN (BlockchainEdge Analytics Network)`中,用于解决长期已来为运行分析模型获取数据的挑战。尽管同态加密是允许通过加密数据实现计算的关键方法之一,但由于性能低下,实际上无法解决现实世界的机器学习问题。因此,BEAN的创建提供了另一种解决方案--利用传统的分布式人工智能研究[[14]]中的模型并行性和SOA设计模式,作为区块链的附加层开发分布式分析服务。 + +为了保护数据存取,运行在数据端的(部分)模型需要开放给客户端,并在服务定义中说明。由于只有部分模型开放给客户端,模型开发人员不必担心有人窃取他们的想法;同样,数据拥有者永远不需要担心失去对其数据使用的控制,因为数据不会离开他们的数据源。 + +其他潜在的好处可能包括以下几点: + +1. 仅在链上交换少量参数数据,这可以帮助提高性能。 + +2. 一种更实用的数据使用审计方法,这在医疗保健领域经常被用到。 + +医疗健康数据隐私度高,涉及众多安全需求。这就为医疗健康数据用于跨组织协作的目的提出了挑战(例如用于辅助诊断的跨医院会诊记录搜索,新药临床试验的患者身份,健康保险自动理赔等)。最小化可行产品(Minimum Viable Product,MVP)服务层的实现是建立在`Ethermint`的基础之上,试图连接众多医院、保险公司和分析服务提供者,以提供具有隐私保护的医疗健康数据分析能力。 + +支持链上服务注册和调用的智能合约已经实现。链下数据处理的一个例子是支持相关诊断组(Diagnosis Related Group,DRG)的分组分析服务。更具体地说,当一个医院用户调用DRG服务时,原始医疗记录将在链下进行处理,使用服务提供者提供的客户端NLP(由SQL和Python实现)代码存根来提取通过区块链接收DRGS服务传来的结构化数据,而不传递高度机密的原始医疗记录。 + +`BEAN`场景阐述了一个更复杂的服务使用案例,包括实现分布式分析、连接服务提供者和服务消费者、利用区块链提供可审计交易平台以及可信任的分布式计算基础。 + +### 数据和分析电子市场 + +通过对几个AI+区块链项目的研究,发现似乎大部分项目都旨在提供数据交换市场和分析API市场。在建议的`IRIS`基础架构中,通过使用`IRIS`服务提供者SDK来发布数据作为数据服务和包装分析API作为分析服务,从而轻松地构建这些网络。 + +### 分布式电子商务 + +将建议的`IRIS`基础架构与传统系统(例如`ERP`)集成以获取库存信息,或对可信数据源进行链间查询以获取交通和天气数据等信息,此方法与许多企业应用程序开发人员已经熟悉的方法非常相似。通过集成这些服务来支持分布式电子商务应用程序,就有可能提供与中心化系统(例如Amazon亚马逊或Alibaba阿里巴巴)相近的用户体验。 + +### 公有链和联盟链的结合 + +对于许多业务场景而言,采用混合了公有链和联盟链优良特性的混合架构,从而可以提供有益的结果,特别是在性能、安全性和经济激励方面。 + +例如,医院和保险公司可以组成联盟链以支持高性能的医疗保险交易,同时识别其他信息,例如关于某些疾病的全球服务的统计数据,这些信息可以从其他公有链中调用。从公有链接收到的通证可以返回给联盟链中的信息提供者,从而激励系统参与者改善和提高服务质量。利用`IRIS`提供的这种基础架构,可以在满足严格的性能和安全要求的前提下实现大规模的自发协作。 + +`IRIS`服务基础架构可以支持许多用例,例如更高效的基于资产的安全系统、分布式监管技术(如严格评估,互助市场等)。IRIS项目计划之一还包括与此类应用程序项目团队展开密切合作,以支持并使他们能够拥有所需的区块链基础架构,让他们专注于更高效地交付预期的业务价值。 + +
+ +## 通证经济 + +与Cosmos网络相似,IRIS网络也被设计为支持多通证模型。这些通证被不同的分区所拥有,同时可以通过IRIS枢纽从一个分区转移到另一个分区。我们构建了两种通证类型来支持IRIS网络上的操作: + +- 权益通证 +- 费用通证 + +### 权益通证 + +与Cosmos网络 [[15]][15]采用同样的权益机制设计,IRIS枢纽也拥有自己特殊的原生通证来表示权益。通证命名为`IRIS`。关于IRIS通证,我们设计了一些具体功能,其包括: + +- 通过验证人和代理人系统,将IRIS通证整合到IRIS网络的共识引擎验证人中; +- 代表投票权,参与IRIS网络的治理 + +### 费用通证 + +在IRIS网络中有两种费用通证: + +- **网络费用** 用来进行垃圾请求防范和支付验证人进行账本维护的报酬; +- **服务费用** 用来支付部署iServices的服务提供者的报酬。默认支付服务的通证为IRIS通证 + +IRIS网络旨在支持所有来自Cosmos网络白名单中的费用通证,例如 [Photon光子](https://blog.cosmos.network/cosmos-fee-token-introducing-the-photon-8a62b2f51aa), 以及IRIS通证。 + +支持各种白名单的中的费用通证是我们计划从Cosmos中采用的一个特性。它可以为网络的参与者提供增强的体验。在Cosmos中,对于网络费用通证`network fee token`,每一个验证人都拥有配置文件来定义他自己对每一个费用通证的价值评估。验证人可以运行一个独立的定时器,根据实时市场数据更新配置信息,或者使用默认的配置数据。 + +对于服务费用通证`service fee token`的设计,同样支持多通证模型。因此,在IRIS网络上的服务提供者,可以自由选择白名单中出现的通证为其服务收费。 + +为了帮助IRIS网络的参与者降低通证价格的波动性,基金会希望发展全球性的iService以从不同的交易所、或者从oracle预言机的潜在信息中获取市场价格数据。 + +权益通证和费用通证都会进一步细化以确保符合法律和监管规定的义务。 + +
+ +## 初始通证分配 + +最开始,系统预计发放2000000000个IRIS通证。IRIS通证的分布计划如下: + +- **私募**: 20% +- **核心开发团队**: 20% (自IRIS Hub主网上线起的4年成熟期,每月释放1/48。) +- **IRIS 基金会**: 15% (保留用作基金会的日常建设和运营) +- **生态建设**: 45% (在链接到IRIS Hub的分区中进行通证交换;激励潜在用户;奖励的合作伙伴) + +如果IRIS网络完全开发完毕,IRIS通证每年的通胀速率会根据账户进行调整,因为事实上,很大一部分流通中的IRIS通证都将被参与者作为权益证明主动投入到共识引擎中。 + +首要说明的是,私募的IRIS通证将用于开发IRIS网络。这部分通证的使用计划如下: + +- **运营**: 10% (包括服务提供者和承建商的费用,例如,审计、顾问、法律和其他第三方费用,以及其它管理费)) +- **软件开发**: 50% (包括直接用于开发上线所需的成本、费用和开支) +- **开发者支持**: 10% (包括黑客马拉松、志愿者奖励和培训项目) +- **研发赞助**: 10% (包括会议、研究项目和大学合作) +- **市场拓展**: 20% (包括业务发展,社区发展和推广,以及出差、交流、出版、发行和其他费用等) + +
+ +## 路线图 + +预期的IRIS项目路线图如下。这里我们重申一下,路线图只是一个大概方向,将来根据项目实施会有变化。 + +- **盘古**(2018年1月~2018年7月):IRIS项目的第一阶段,将集中在构建和运行IRIS Hub以及与Cosmos Hub的交互。同时,我们将发布一个初始版本的IRIS网络移动客户端。 + +- **女娲**   (2018年7月~2018年11月):第二阶段主要集中在构建IRIS Service Layer。这将涉及启用服务定义、绑定、调用和查询。在这个阶段,我们也打算为开发者准备一个beta版的IRIS SDK。 + +- **夸父** (2018年12月~2019年5月):第三阶段主要专注于IRIS网络的增量升级,以支持我们计划中先进的IRIS Service治理特性。 + +- **后裔** (2019年6月之后):第四阶段专注在IRIS网络、IRIS SDK和移动客户端的技术创新,以及开发者的参与。 + +
+ +## 团队 + +**Tendermint** (该团队开发了 [Tendermint](https://www.tendermint.com)共识引擎,当前正在开发Cosmos), **Wancloud万云** ( [万向区块链](http://www.wxblockchain.com) 子公司)和 **边界智能** 将共同构建IRIS网络的基础设施。 + +Tendermint将在扩展Tendermint ABCI和Cosmos IBC技术方面,为IRIS项目团队提供技术咨询和开发支持。[Wancloud万云](https://www.wancloud.io) 将是Cosmos和IRIS生态系统的关键战略合作伙伴,它将积极参与Cosmos和IRIS在亚太地区的开发和发展。 + +边界智能将是IRIS网络的核心开发团队,IRIS充分借助团队创建分布式智能分析服务的经验,实现医疗数据分析与交换。边界智能是一家于2016年在上海成立的初创公司,专注于利用先进的区块链技术和人工智能技术为医疗和金融行业开发创新产品和提供解决方案。边界智能中的一个核心产品`BEAN`(区块链智能信息边缘分析网络Blockchain Edge Analytics Network)是一条许可链,它利用自然语言分析及机器学习技术为隐私保护、医疗健康数据的分析和交换提供分布式智能分析服务。边界智能正不断扩展`BEAN`功能来构建IRIS网络,同时,**边界智能**也是Cosmos网络在中国的运营和服务合作伙伴。 + +### 核心成员 + +**曹恒** + +[曹恒](https://www.linkedin.com/in/harrietcao/) 是边界智能的创始人,该公司是一家成立于上海的初创公司。边界智能专注于利用分布式AI技术为区块链提供智能化服务,支持可信高效的行业协作。曹恒是曾获得过2010年美国运筹学和管理学研究协会(INFORMS)颁发的数据分析和人工智能技术领域的“Daniel H. Wagner”大奖。在创立边界智能之前,曹恒在IBM 研究院工作16年,曾担任IBM研究院上海研究院院长,是前IBM全球研究院大数据分析技术带头人。曹恒拥有卡耐基梅隆大学机器人硕士学位和清华大学自动化控制学士学位。 + +**奚海峰** + +[奚海峰](https://www.linkedin.com/in/haifengxi/) 是高级技术专家和企业家。自2009年从美国归国以来,他曾在三家公司担任首席技术官,其中一家是纳斯达克上市公司。他还在上海联合创立过两家初创公司,并在那里担当技术和工程学的领导角色。奚海峰拥有马里兰大学电子与计算机工程硕士学位,以及清华大学自动化控制硕士和学士学位。 + +**Jae Kwon** + +2005年,[Jae](https://www.linkedin.com/in/yjkwon/)毕业于康奈尔大学计算机科学学士学位后,曾在硅谷担任软件开发工程师,起先在亚马逊从事Alexa开发工作,后来在Yelp带领移动应用开发团队。Jae在认识到区块链问题后,开发了Tendermint BFT共识算法和Tendermint Core共识引擎。Tendermint是第一个可信的PoS算法。 除了开发Tendermint之外,Jae还是Cosmos的创始人之一。 + +**陶曲明** + +[陶曲明](https://www.linkedin.com/in/tom-tao-14763a45/)自2016年8月加入万向以来,便负责万向区块链集团的咨询服务,万云BaaS平台,以及ChainBase加速器和孵化器服务。在加入万向前,他曾在多家全球领先企业里积累了超过18年的丰富服务管理和业务管理的实践经验。Tom率先将云服务,物联网数据服务平台和加速器技术引入中国市场。自2013年起,Tom一直在跟踪区块链,云计算,物联网和智能制造行业的发展趋势。Tom拥有复旦大学物理学硕士学位和南开大学电气工程学士学位。 + + +### 顾问 + +**Jim Yang** + +[Jim Yang](https://www.linkedin.com/in/jimyang/) 是Tendermint首席运营官。 他是ChatX移动信息工作室的创始人兼首席执行官。 ChatX开发了各种移动消息/社交应用程序。 他还共同创立了Identyx并一直担任CEO至被Red Hat收购。 Identyx开发一个开源企业身份管理软件。 + +**Zaki Manian** + +[Zaki Manian](https://zaki.manian.org)是可信物联网联盟执行董事,也是区块链和加密货币技术发展的丰富贡献者。 Zaki在密码学和分布式共识系统方面拥有深厚的专业积累。 他还是Cosmos项目以及其创业项目的顾问。 + +**Adrian Brink** + +[Adrian Brink](https://adrianbrink.com), 是Tendermint / Cosmos 网络的核心开发者和社区负责人。 + +**Michael Yuan** + +[Dr. Michael Yuan](http://www.michaelyuan.com) 博士是 [CyberMiles Foundation](https://cm.5miles.com)基金会的负责人。Michael在德克萨斯大学奥斯汀分校获得了天体物理学博士学位。 他编写的5本关于软件开发的书已由Prentice Hall,Addison-Wesley和O'Reilly出版。 Michael是Firefox,Fedora,JBoss等大型开源项目中的活跃代码提交者。 他是企业应用软件和移动软件方面的专家,也是参与了多个由美国政府资助的研究项目。 + +
+ +## 参考文献################################################################### + +[1]: https://drive.google.com/file/d/1bI7JIOe-CfJ5fPHKxYlFub2Kg-KCGU6r/view?usp=sharing +[2]: http://ethdocs.org/en/latest/ +[3]: https://cosmos.network/whitepaper +[4]: https://polkadot.io/ +[5]: https://tendermint.readthedocs.io/en/master/ +[6]: https://ethermint.zone/ +[7]: http://www.freepatentsonline.com/y2017/0236120.html +[8]: https://github.com/cryptape/cita-whitepaper/blob/master/en/technical-whitepaper.md +[9]: https://github.com/hyperledger/burrow +[10]: https://lightning.network/lightning-network-paper.pdf +[11]: https://www.plasma.io/plasma.pdf +[12]: https://github.com/cosmos/ibc/blob/master/README.md +[13]: https://www.amazon.com/SOA-Principles-Service-Thomas-Erl/dp/0132344823 +[14]: http://www.cs.toronto.edu/~ranzato/publications/DistBeliefNIPS2012_withAppendix.pdf +[15]: https://medium.com/@tendermint/b5b2c682a292 +[16]: https://drive.google.com/file/d/1jtyYtx7t1xy9gxEi2T5lXFNd8xUY7bhJ/view + +* [1] Wanxiang Blochchain Inc., Distributed Business Value Research Institute,"Blockchain and Distributed Business Whitepaper", September 2017. +* [2] Ethereum Foundation, "Ethereum Homestead Documentation", +* [3] Jae Kwon, Ethan Buchman,"Cosmos, A Network of DistributedLedgers", +* [4] Gavin Wood, "Polkadot: Vision For a Heterogeneous Muilti-chainFramework", +* [5] Tendermint, +* [6] Ethermint, +* [7] Oracle International Corporation, "Accountability and Trust inDistributed Ledger Systems", USA Patent Application 20170236120, August17, 2017, +* [8] Jan Xie, "CITA Technical Whitepaper", +* [9] Hyperledger Burrow, +* [10] Joseph Poon, Thaddeus Dryja, "The Bitcoin Lightning Network:Scalable Off-Chain Instant Payments", January 14, 2016, +* [11] Joseph Poon, Vitalik Buterin, "Plasma: Scalable Autonomous SmartContracts", August 11, 2017, +* [12] Ethan Frey, "Cosmos IBC Specification", Sep. 29, 2017, +* [13] Thomas Erl, "SOA: Principles of Service Design", Prentice Hall;1st edition (July 28, 2007) +* [14] Dean, J., Corrado, G.S., Monga, R., et al, Ng, A. Y. "Large ScaleDistributed Deep Networks". In Proceedings of the Neural InformationProcessing Systems (NIPS'12) (Lake Tahoe, Nevada, United States,December 3--6, 2012). Curran Associates, Inc, 57 Morehouse Lane, RedHook, NY, 2013, 1223-1232. +* [15] Tendermint Blog, "Cosmos Validator Economics -- Revenue Streams",January 2018, @tendermint/b5b2c682a292 +* [16] Sunny Aggarwal, "Cosmos Token Model", December 2017, diff --git a/docs/modules/fee-token/Fee.md b/docs/modules/fee-token/Fee.md new file mode 100644 index 000000000..64b2587f2 --- /dev/null +++ b/docs/modules/fee-token/Fee.md @@ -0,0 +1,23 @@ +# Introduction + +Specify the maximum fee you want to pay by `--fee`. Gas is the unit used to measure how much resource needed to execute the transaction. Specify the maximum gas limit by --gas. If maximum gas is too small, it won't be enough for executing the transaction. If the fee is too low, fee paid for each unit of gas will be low & validator won't execute the transaction too. The fee(minimum unit)/gas must be large than 2*10^10. We recommend that you set your maximum gas to 20000 and set your maximum fee to 400000000000000iris. Fee will be deduct according to the gas used and lefted fee will be returned to user. + +## Fee + +To secure their own validator node and maintain the avalibility of blockchain network, validators in IRISnet need a lot of equipments and works. Thus, every transactions in IRISnet should pay some fee to validators. The parameter in commands is used to specify the maximum fee the user want to pay for their transaction. + +## Gas + +The resource needed for every transactions are varied for different type of transactions. For example, only a few computations, queries & modifies is needed for sending some token to other peolpe. But a lot of computations, queries & modifies is needed for creating a validator. Gas is the unit used to measure how much resource needed to execute the transaction. We list the gas needed for some typical operactions in the below: + +- gas needed for reading some data from database: 10 + data length(in bytes) +- gas needed for writing some data to database: 10 + 10 * data length(in bytes) +- sign or verify a signature + +The total gas needed for executing the transaction is the sum of gas needed for every operations performed during executing the transaction. User should specify the maximum gas by --gas parameter. If maximum gas is not enough for executing the transcation, the transaction won't be executed successfully and all the fee will be returned to user's account. After the transaction being executed successfully, fee will deduct according to gas used, deducted fee will be maximum fee * gas used / maximum gas and left fee will be returned to user. Gas price is equal to maximum fee / maximum gas and stands for fee that user want to pay for each unit of gas. To keep the fee is set in a resonable range, we set a minimum limit for gas price, 2^(-8) iris/gas, transaction won't be executed if the gas price is less than this value. + +Example +``` + iriscli stake unbond complete --from=test --address-validator=faa1mahw6ymzvt2q3lu4pjj5pau2e8krntklgarrxy --address-delegator=faa1mahw6ymzvt2q3lu4pjj5pau2e8krntklgarrxy --fee=2000000000000000iris --gas=20000 --chain-id=test +``` +This example is a transaction to complete the unbond operation. The maximum fee(--fee) is set to be 2000000000000000iris(2*10^15) and the maximum(--gas) gas is set to be 20000. Therefore, the gas price here is 10^11iris/gas. Suppose that 1500 gas is used to execute the transaction, then 1500000000000000 iris will be paid to validators and lefted 500000000000000 iris will be returned to user. diff --git a/docs/modules/fee-token/feeToken.md b/docs/modules/fee-token/README.md similarity index 93% rename from docs/modules/fee-token/feeToken.md rename to docs/modules/fee-token/README.md index fbc8cccfc..d5b1c6c4b 100644 --- a/docs/modules/fee-token/feeToken.md +++ b/docs/modules/fee-token/README.md @@ -18,22 +18,22 @@ Now we must specify fee for each transaction properly. Otherwise, your transacti For command Line: ``` -iriscli send --to=faa1ze87hkku6vgnqp7gqkn528d60ttr06xuudx0k9 --name=moniker --chain-id=test-chain-UieBV2 --amount=100000000000000000iris --node=tcp://localhost:26657 \ ---gas=10000 --fee=2000000000000000iris +iriscli send --to=faa1ze87hkku6vgnqp7gqkn528d60ttr06xuudx0k9 --name=moniker --chain-id=test-chain-UieBV2 --amount=10iris --node=tcp://localhost:26657 \ +--gas=10000 --fee=0.0005iris ``` In command line, we specify gas and fee token by two option: "--gas" and "--fee". The "--gas" option can be omitted. Because gas has default value: 200000. However, the "--fee" option can't be omitted. Because its default value is empty. For rest API: ``` { - "amount":[{"denom":"monikerToken","amount":"100000000000000000"}], + "amount":[{"denom":"iris","amount":"10"}], "name":"moniker", "password":"1234567890", "chain_id":"test-chain-UieBV2", "sequence":"9", "account_number":"0", "gas":"10000", - "fee":"200000000000000iris" + "fee":"0.0005iris" } ``` In rest API, the gas and fee token are specified by gas field and fee field in json body. Both of them can't be omitted. diff --git a/docs/modules/gov/gov_spec.md b/docs/modules/gov/gov_spec.md deleted file mode 100644 index 7a517b89a..000000000 --- a/docs/modules/gov/gov_spec.md +++ /dev/null @@ -1,143 +0,0 @@ -# Governance Module - -本模块的主要作用是增加区块链的链上治理能力,通过该某块可以实现链上配置数据的动态修改,软件升级等功能,主要分为以下几个步骤: - -* 提交提议:当某个需求需要大多数人达成一致时,可以由提议者提交提议,将需求以交易的形式广播到区块链上。当然这个提议不是可以随便提交的,除了需要扣除部分手续费之外,还需要抵押你的一部分代币,为了防止提交恶意请求。但是这部分抵押的代币在提议通过之后,会等额的返还到你的账户。如果抵押的金额没有达到系统预设的最小抵押金额,这个提议将进入抵押代币阶段;如果大于了最小抵押金额,该提议将自动进入投票阶段。该阶段的相关数据模型如下: - -```golang -//提议交易数据结构 -type MsgSubmitProposal struct { - Title string // Title of the proposal - Description string // Description of the proposal - ProposalType ProposalKind // Type of proposal. Initial set {PlainTextProposal, SoftwareUpgradeProposal} - Proposer sdk.AccAddress // Address of the proposer - InitialDeposit sdk.Coins // Initial deposit paid by sender. Must be strictly positive. - Params Params -} - -``` - -* 抵押代币:在提交提议的时候,需要抵押部分代币,这个最小的抵押金额可能会很大,造成单方的代币不够,所以,这个时候你可以邀请别人来帮你抵押一部分代币,当然在提议通过之后,双方抵押的代币也都会等额的返还。 -抵押过程中,如果当前的抵押金额大于最小抵押金额,该提议进入投票阶段。当提议进入投票阶段之后,这个提议就不能再被抵押金额。在抵押阶段也有时间限制。当到达规定时间,抵押的金额还没能够大于等于最小抵押金额,系统会丢弃该提议,并且会被系统认为是垃圾提议,不会退还任何抵押者的代币。该阶段的相关数据模型如下: - -```golang -//抵押交易数据结构 -type MsgDeposit struct { - ProposalID int64 `json:"proposalID"` // ID of the proposal - Depositer sdk.AccAddress `json:"depositer"` // Address of the depositer - Amount sdk.Coins `json:"amount"` // Coins to add to the proposal's deposit -} -//抵押期的系统预设参数 -type DepositProcedure struct { - MinDeposit sdk.Coins `json:"min_deposit"` // Minimum deposit for a proposal to enter voting period. - MaxDepositPeriod int64 `json:"max_deposit_period"` // Maximum period for Atom holders to deposit on a proposal. Initial value: 2 months -} - -``` - - -* 投票:当提议进入投票阶段之后,验证人需要在规定时间(系统预设)内,对提议投票。投票有以下几种可选项:Yes(同意),Abstain(弃权),No(反对),NoWithVeto(强烈反对)。当然你也可以不参与投票,但是你和你的委托人要承担失去部分绑定金额(比例由系统预设)的风险。当达到规定时间,系统开始自动统计投票信息,根据投票结果,会出现以下行为: -投票通过:退回所有抵押者的全部金额,如果存在未投票的验证人,会受到相应的惩罚(具体由slash模块处理)。投票未通过:不退还抵押者的代币,同时对未参与投票的验证人进行slash机制。该阶段的相关数据模型如下: - -```golang - -//投票交易数据结构 -type MsgVote struct { - ProposalID int64 // proposalID of the proposal - Voter sdk.AccAddress // address of the voter - Option VoteOption // option from OptionSet chosen by the voter -} -//投票期的系统预设参数 -// Procedure around Voting in governance -type VotingProcedure struct { - VotingPeriod int64 `json:"voting_period"` // Length of the voting period. -} - -// Procedure around Tallying votes in governance -type TallyingProcedure struct { - Threshold sdk.Rat `json:"threshold"` // Minimum propotion of Yes votes for proposal to pass. Initial value: 0.5 - Veto sdk.Rat `json:"veto"` // Minimum value of Veto votes to Total votes ratio for proposal to be vetoed. Initial value: 1/3 - GovernancePenalty sdk.Rat `json:"governance_penalty"` // Penalty if validator does not vote -} - -``` - -* 提议执行:该阶段是新增的功能,是投票通过的后续动作,根据用户提出的提议的不同类型,会触发不同的后续操作,目前有以下几种提议: - * 文本提议:一种只读的提议,提议的执行不会对系统产生任何实际的影响 - * 参数变更提议:提议执行的时候,根据提议者参入的修改内容,可以修改系统里预设的一些配置参数。例如提议的最小抵押金额,由原来的1000iris,修改为2000iris - * 软件升级提议:当提议被通过后,软件升级提议会变更当前软件运行的版本,触发软件升级模块执行升级动作 - 提议被设计为借口类型,具体实现数据模型如下: - -```golang - -// 提议接口定义 -type Proposal interface { - GetProposalID() int64 - SetProposalID(int64) - - GetTitle() string - SetTitle(string) - - GetDescription() string - SetDescription(string) - - GetProposalType() ProposalKind - SetProposalType(ProposalKind) - - GetStatus() ProposalStatus - SetStatus(ProposalStatus) - - GetSubmitBlock() int64 - SetSubmitBlock(int64) - - GetTotalDeposit() sdk.Coins - SetTotalDeposit(sdk.Coins) - - GetVotingStartBlock() int64 - SetVotingStartBlock(int64) - - Execute(ctx sdk.Context, k Keeper) error -} - -//文本提议 -type TextProposal struct { - ProposalID int64 `json:"proposal_id"` // ID of the proposal - Title string `json:"title"` // Title of the proposal - Description string `json:"description"` // Description of the proposal - ProposalType ProposalKind `json:"proposal_type"` // Type of proposal. Initial set {PlainTextProposal, SoftwareUpgradeProposal} - - Status ProposalStatus `json:"proposal_status"` // Status of the Proposal {Pending, Active, Passed, Rejected} - - SubmitBlock int64 `json:"submit_block"` // Height of the block where TxGovSubmitProposal was included - TotalDeposit sdk.Coins `json:"total_deposit"` // Current deposit on this proposal. Initial value is set at InitialDeposit - - VotingStartBlock int64 `json:"voting_start_block"` // Height of the block where MinDeposit was reached. -1 if MinDeposit is not reached -} - -//参数变更提议 -type ParameterProposal struct { - TextProposal - Params Params `json:"params"` -} - -type Op string - -const ( - Add Op = "add" - Update Op = "update" -) - -type Param struct { - Key string `json:"key"` - Value string `json:"value"` - Op Op `json:"op"` -} - -type Params []Param - -//软件升级提议 -type SoftwareUpgradeProposal struct { - TextProposal -} - -``` \ No newline at end of file diff --git a/docs/pics/iris.jpg b/docs/pics/iris.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8d9686a458df0049ef7542addfdc4897f6d6ee98 GIT binary patch literal 44414 zcmbSzby!s0yY|q6grqbo9fCASjEJPt4ZA{*Z0SFeG446%-);*to7vm+-q*8Z*LjlJmB; z0)bRiKwKaY=ne=Y+!lll908|*Xn}tq5Y}f55Ek$gC=7fSbw;rbpUiNM$WL$^W6scvDM$+~s|(aCO{8LWV<_LTy#Y0a zUl(0--A`B(H`g*{6(}RBjO#ip!Dm?;)sQt+t+sGTc4Vp`B9`BZUA`QrShvzj5i1T@ z5{ayC6_;nBmae5w5b`@?toefV6*|S#d7({dWnrBaO0$hB!Q=?|Gq4a+C{l|lwqm{c z`AnESBf;g)=J>c8H+(_TN824Xjbo<2-YCp9(B|OM=)XhD`T8y{B{YLP$9(ehgOHGC zEcCHlP+=D8G`AhjAd@ezp(LYeh$^Dalru_}e*HWcJEf8hj@?JGY*huU@zYXFh5G`> z{y6d{5~vou&!zRwEc5gbw+$!5p!BTuSlb#6XI3QxX|4WC+IJBw8{|W|Wv5uNa`!P5 zxt!-{l`C0Ej&J8Q0}(IEKEP3LN~LzDgdC@Q)6U<6*Mi9sw~>a%%zXADp*j4nmK6u| zx6`l|qt%-lzw#|ET0M+IW<}SYti&c~alCIOC3#B*GxT%a?WZL)2E>!pLbH|Cm?8tB zB$I*M6G=B9#*pj7Z510=(Jn8N$()dLb?_`Yc@M|XHDA0Vdc5OaRI7Q=_Cm%9naJna znu0BJffwqQ>w_(suVLG-^qocfJ>w=n1xDy(?Q0}y?Zq-$ zu3c&hwGmau6|=K^l_U^TyaADw zYYQumyVgQe6tN_2yhr1{$5wbCJwA%r!hsWeKS{HIC1&V2(j}Sw=bc`-kM05Jk>W+# z$rfiEH@II6BBMc`twQk{k6VDgv|Fu7Jm3b@zffx!$%|d};^_DtV}7BWX2Gu&jb%xDg;FiUJnqe8oG>%> zd$%1sOeJy2@gVM3T@Es}{$;GJs(K+xa@;}IgG%0jMsbNhve+y+qoh|B9wK?Sj&c7p^mn=9IYe*W>FcK z#js4Qx3V_Zc5GJWAH|Et;HDI0#B!>vdURGyA9i)N3ew0Wd2rVyQpdH0P7_wewX_0u zoX(9-^V$?hE=N?7uFd^bloM*)K;vO-iSoU#vh6B9-_zd3@7b2tP@SijWFJ^4{#-(H zYyAcI(e1d?@={mhG~z=(${cU+Vmd7H%*C0U#{6TUk-=GCf4CM?yv7|{1$+x!L(4G| z(sEo6v$KgdkQvf6|&l1UR2j?9UHR(2x$JuCK<{Za~^O zF~V#XbZXq&I_&;!k&%^VO1N(%FKGjViAg9QgOWAm9uRQ;h}=1p?X0fe!a~6Uq_*xW6JzdoZ=wBe~0U%xS=#2^YD1E*v5un z&87D5O3IQ#OG~jgAxesvk(@dPu@n}=nA+bIm>K$dTNKS>87(B@3Kdu?*ztn4IDa?X zuP;&Q+Qg&zQ|4NbzM#6itIBk=1zkX=5GWpHRcQIQSyEc?X!(!Twn)$hjjW2fM1Bl( zpwIyBt&T57Kfb~eZDl_6xhS5rCw6mfe*uP1@sQBVVaG0M;Fn13{n1ZMm&GWqy!}ez zbQbdsYv=Q_@qcvQin9q-aj6|-80p({l#`|fESDSyb`}9h*@s!YBQp6#iRdereZb}M z(`l_kWK`$d8e)QKGhHaL`;Uosyht3!e?nI-wYdhuxt#5O595yLdUf+%4kcekMy$B6 zot~9cl8(qx1ajmR16HYW95_yptb3Pla%QNTk@5iXJa+RJRJtLPR4(NseaDS;y z+s9|4U$=fK{IN@?UK$P7UUSiv>`ILYBPl631FT&rzR7LeCo-(4jY2~XMDdx-S-kWk zdCVw7Uh-g#!+TSoKgEtq`ceGL^lRC{nY@-iVwyY*D*%gDT#L|;)6(+?y}_nurR4nn>2^=GFPLUAAZTWe7|q>_GhR3UoZ4l@4|-5HQ#5@{PGIv_8xNj4 zwjAl$wt#$p9Md-zX~-#(#9f@@BGQ38mriE{}YjJ5c;PP@2h>D3s$L$m`W4u$4h%r7~} zQ>H_xa)quM%7+99oOcMuZ*Ol)=0-O@pvnufF@C~Ttnyc2}Uqds@1eH#j$5at@e9n8{R{4hHOW;`n@MsMz;%FA*S-OT%4qeXOK(5~ z_wH!`I-ma6-)z}#+y>#3ZJkn?2WwglWM7EiL6dzlToRa9NQWvO_elf-#<&p3$&!_= z!b+hXWVVQGO)>dmbOX9ST0S8akE5LQl&D2-cwAe%2q%YEJisQFB)5o1fc%7zL`!`l zeI~Mmy`*dydyyWp)3dr`hilf$<7&%MFpZ=3k4b$l-G@(+^j@gfW8NwW84HYQetTPU zKT_iuRk1x=uAzDjN|WIf>yg^N$_qd68{D1Nl=v3(ZZ`v_W=enX%e7Z%mZKC?A37QN zHfNV^#}=5l3W^!ELnrIMgt#NbQX8 zjA=3hlNOK|P@b}CdXB!&`2Up*o2{#57=7zKE<0UszyZ7{{_@rh=pZAwI6NOny#XBs z0&D?>E-yHITOFj-w((_-8C1+r_Hlrq26zS>{kp5oZJnL&`bDsEi6f2=M_vKo)3L4mYnQ-cex)Q*aY8p}3ta*pmLia=?*W5C5d5d_}|C9%Z!#Hxmp}8*QxyC z;JNx~rYw2-Rt(Idh8xgpJKBuZYnS5TJ2rWd&nP9KJ2{9Fu5rZ;_O{(&JvNp5L!?;4dvg})9Rit`+1BwEKn`q)EbeS!`C)2)Cx)-Q?D`IhG9<+&zAloql zy;by2&Y<-h`jsgTa5&vnIYOdua@JKPf=nWHb+y8%g^~fU9|=mo0gV@r-++|EilAql zXW-G?qBh|7&tCo~$x_1n7JpBSqEF|2ICE*)7PkA}DZT-vI`x!K#9erz?DGDZ;+(&3 z(o%^m=|QjgGp3s{H2+7ZRErSjYui^6VOy%p+jBZTI=7{e@DxM7VlO3GW{fT7d?wjiKbH@y4U1?+AbGE?_NzjVWm8pA!9LDkaSNRyp@_kT0 zcb`K`p(W@V7HlEy2y!@camC9fu?DsD78NRta(pazILEcE;aj5knEa`h=L3L|v1Q6# zVQ{_bYhUxBP5K$DY9=NfR<76R_vHGMG!IIj+ikgmf2E2&^JmVyY)`i{lhD_35Act~>2i?42GM>Qof;}xuw^V#(M{mz}ZiEu+S(+#Ly3dL_jw!32WjW_>M ze87-}WExU3EFnY!lmE|i(p`v_x7WGjbvBCZTc5-7)#H(ayR6eE5ks%jqpXj%A*Jim z1RD(>N~c_kn&%hizQW0mv#xsls&VIRdUTi)tFGpAmY~v=r_etta1R6jo25}j~T0VXQV%5ae}7UpF+-EkkJ7+ ze$QL4KLtEBlHpAfZjT9=pl#OuLnuFk;S$GY+0GJoP>6~?s z?yDZC!K706x%Y-UhspKY$(L9D5uFG**{m(~)$1jD#hxIn6y5TeTSFJm+{T1}b=+wuwSQe%?Y{m&s z9$@*I&nNReu*l}#L?(57`NJJmY7*rPv6DVV2}6Y9ikIRF!1&fNFYxYA;5v-u&b36yMB=cDaHLji9Xo zDH?`=k^jvPv+jHbiw-P&Dtn8qboa@eH$+R5hK%>&+GR$>n%7ltoN{c`Ii^mAoLSr1 zu3DGo>4nj$ut_8@);tX{wHB8}T3ia+^0b&b1#Ls@|9!-q zk)-g9PP0Jm!H+G8@gU}?YwH1jF42_5khasj`L-lK7ijrK=J@z?11u-JjMzwCoUCq9 zNJ@*ZHXj}P0%|)&;8nj!wnA>+lB}j2`ddIPX9NpfE|B%dKGD^|i?uB*!RNc|xg7W4 z39R{oCpjL>672{S!W{PM4;5$7hnoPL-~)ui*|ZZuqWqv+H~~|ZC$v6k@a1hf0C z_!V8nRp%`C^CM7Fkk*G3-0fJY5`iz~Z<&v7 zk+5MPU41eO=ei`&Nn5o5o}EI&6MN&{syjRLSj#hcF`=@7VxTB#OB9!9rIyYM@yUw?%K#K5V42xs znSuLZ*eV5LG*SvJTDFxU&!2z|j7MGrV&l`2$YP5FBFj()^3Tje# z;K?8c!ic>3O0m>vt~cqTxt3S&f6aFhS;NKQCdX)mfSijV?srbay*?@$bklkLV4rcZ$Wd7A_6dO`gHO7|jyfv3Lg=*4BSza%&O6d=I@jT6&IgkwO z*9|BJUJH+vX0K^t4_i>VFDK5ZtrAgWqHt*Jd+(jh@#VoP6DyfgAFR9w858!iw3$s- zg%vgEgbsimNK24*MBUe#HMdwyJ-cMG@RPl62oUt{j)8@<#&u4nJ*fCRFNhV_A{Z=# zO;6q7@nAFZ!rJJ_DH5gO?C2+3GPn3+03z5w>NhyP90AJcRD4PF%d>*}RcT5fP+Y&Y+n}gY5Yi=yx-Q>cD$XwAt$r zK31)=*TDf)@K9;SIX~G63jgXZLdk?!&B;g4Hy^k$uYZrpC3zi*tUez`*5!~&^9>f- zYT~;O;so@PGBBD{*STEZfZ{!{c@+$=H^Zx$&dkH9gjx5?g+~3GAU{7I_WeM=TS0|f zzg+>Bj5|$hM5%neHayv=I?({j+<@M~XZpcWt>ibL_lq4aR7b=Kq+AhkrzLm;BMI|U zNsJ`o+`r_(6sKTv@1%|?h&^Key8C@wupvGGOp4RY$~*hpp9`L|T^HbWNnr%gcsH%p z)fc|NsqPDOd>n7;Dt(#|h(&(#q?1f_6(Sxmw^$vHdX!O(GDld5jX42$O~iZBBAn*^ zQ4_Hl&Z{{>@Ye%zKiNK;jRvtJd5!!lTgQqi)pF}~TL(`UZ=-CzK9{kjxfA`xKMs3` zFy0o%qrF3hy*P2C?bSP!7lNhK31-~8B0&kFhNb@bY>}wz-nn)1F1 zMrmY7-8W2VmMZP*==4@ddU&eTb6Cec|C5=f!f>kNy&*w7s}hS-y=XT#lFS=Y-= z6k1l;N4(x6gUM1W&nY3li*0r{nL;nNGSL>$XK?x(kQq1>Or7iR*7>8AX)?{xC{u^= zRo5z`yDWi!x=6j`M-Tx@9|=c@uJE-J`Pc9<7*J2d9XRIyG#cQ~>V1eMy%g9ME9Wb^ zcXnmzCy!+2F=Q;*ukeNj7>-)8uHZ>T6T8*3td;gBZ7H#zL**yYgy;!4VY-N1`S$%t z$=!FY2K#G!)L2d86q|&_*P{x;m(9nj468l@(j#whodbVow4*L;I&M9wJUrxo3GKs zW3r3hjz>rK-tTOt*DeG>xb(!~2bF7X@zP3x9}}Wno$W7RPk($fu;SI{u@JXrnA-VX zJd(43V(1a~gr;f@x|Wp{a+VjtDW>G>YOUzt}paH zZ#-SM;~e->OvtZN3RLhMph6(`p3MI1yvM(SsV)FN!CVH<%(PN%oSmQ}W_?Ox<_5t8F3= zfQbg_AI-E^$}^um005K8#4m@jjw}~yB_-Kxsy=asnHUUzK|ap@FTDhU&xp#M)9KAr zwH7j~#2S+}oRlNhZJ(Z=memHfJZPH>r22BsqiR&4CeHmRWob!cqoDcK6Ms4F`oFMQ z@_K;f86}bIZ5a(zKwWV$Yur612K^Hd9Shqj|^qupEVzqjKk1ZCrZSoMPne@)OZv~NF) zFyAmo64y+nf0%`HoC6Qoq#+U*XyMLyCa)V`$AT&~x>ojAJ1qpTn^ypK;}C>HDbd;U zx0^*t^>=;qA}b%xioWuUQ$5|odSi?AM*O_|x0d4*aFJco&~0F*fFJK8C%UlH3)xB9 zPWRQdw?%OKaF>E>E&Bf!o{BiSTwa{*<%|}t(aOLq>gFYyDkGYR<`qf`6hB=s zNZAhm=wDWN{*I#hyA$WMXR&1i@ghBV2W@p$!Z7n|L%e82d5KcsZxL8a^eSfuvIDNT zbH{!PjgNXXiRMR+@{!p7&aH_fGkG1_-+BLdZvLK^1-NoL1Y)syq!DUh{*c)R)=5b+JjnlJ1pH%Il@+d#!t6U%HX z>?P|%MI_5+C3~P43W|gu*>~qq`@Qg(_jz77;z(6j($$U0zlJd%i@VYGIA|Iq9W({D zhRoKlgeQ5dHe$oCS0=K;_??gr$ByUVRSesee?EuIGyQCr`vzy zUBo~&M=wcuKF6rB2pm@Y!k4C%oZJxdJ#UqAULP4Cwjdiy$!iu~Jg`_85Mvn7HYlX= zNw%Ag4$DW*HX(b7KRLh>N^p8bGW~LCk2uc5x9rz5x|E_&?Q9g!!@wI*kX~jOVpF*E zob1g0wDCj-F~M0r$dpLD|8Q<%7A1m^x&d{?F>D9i8OyZDh~A}1qB$NbZxs-%#dvFB zO%0n?5j>YgVigMN3uXEaUy+(wrl&o=b(cxZqTu*tAx?X$RdQ zwHTj^f$xtP6z=|+-jvWzNQ%Azfvbmv#}D0HyVnw;1R0ggT$L^}t}(8^2XL^ptXw&T zWtbm?D8&70e1LFdrMWwXB&XjjCk@nvOWXfEGWtNp_e9@LZLXkE4+c5DV1!^=aN~!i z*!p=eEEcPsTx7P=9I<^{x&hrYK<0Oz(E0wR(Y1N)X(_%r&iLMoUhnWvJ3InSc3s#? zUUOM+uYZb^PDQturA&gC+U*3#<>cXx1euI5>R9i4zz~$~3>p+58P%nWwzzah#-b7&OpnRf*-*|D=zZVn4&c4<@b5%959QJ!PWcK!``+xr&4!dISI6~?`dFL;VWL9 zHy|AJ=nV)z^iyqHB6maRLZ&Y%b}#Q-zPq^A9}5$F8XDbprXWT^#AM47l++mcvI|I& ze{&MLJv?J*KPWH_7JCpZR(>QJ^id~5KU$=Q%l`iF{u@x_K?@BdnRgJ+;vGc8AU{P- z;z6C}HS5e}erA^jN#=&rXbaymdk>h-@BUG=v>@W`6{}2@4TOzmg@v3x^3D&j)vS=< zJCB;bMxu7{Vk^SSX_4>5`gyl2#=x%zUB8G(5J@r$WPB1YDx~_F;ZF-LbP8J}3!n;^ z0I=dsB5Xa+RF@CJk40Q*mg1xL9Wj<-Mt<=Bm}@Y7hElsOhFU*1I`=&~nU-nYlo=OQ zDmH$y2E)m76+2;O$Ghqz3d$nBza-kLMv1~aY7XE4(= zy4su*At21tcWiEpdMwxKl%cD1?xavQrhqbNlO}cnV;sHz_^jotmhpm1@=6xp1lz$n zV+^0qQ>A%hKMXmO@tPJj`DO>OUj4_(<>%ibEo|oS)OVCCv2iu2eS%43we2q!G+g|u z40GlvcH~{OLYjO9JTjRr;7cq2#sTEp|S;} zuV!#Rw<`v@RM*E{vK|?{cc#s;_Uk{PXC3fKFEl~O4TwVmnQ#NLIAFRa#d-Jcqv@8I z9QO(Mn2Wy={hA3MY!NqGy?P$xvH}lcBJ?v@b>JOcnpJ!Ed8>XlrCE<4>S5@5ZP*I~ z%%}X%WgRTV+G)-JDoOBL0DhBi1Aw7w!1aVd)R1x>P_!KEfE`T;VBpEVezG^9stB(e zP|+uWIBy z$|Sa_r5RI5F(1^0hD!4W^n+^-_s$9pb{Cn@bjad%5ySUIcMZ<=8ULt6zSHrdUiB@> z*E7v$)lQ1F?{;@!e|;ohZMzI3G8lqFp#ny;vxYsRgF;nLv}47Fsl2QnaFwtm1qwp8 zNP!27zXA1?pdJ9vTD5xvQZ#A30M-i}(3w-Mh9XNv<2Tx0>H9q&tAH=_H6aQX9v?Y< zXwG@MBf(yOopF}_(lH_1AMMb^gPy++i*J(gkQGit?lhJJ@m9`+t|vXbO4 zx-DY$=WrF|u>~rz@5#`>4tki7lD%!=E8uhE-nOU-M9yzo{*tdPH1I376)LB1bfot) z^su|nD?T4>FczPRqVI}c@u7Pb5n4G&w(Q(1bHAs?%xH23zK#*(P-oMIS=~76x7cwL zC2Mz?6MEsg^ffTuQCYd^u=XuDS9xggwegUzg*~DoCe1iBNY; zLt|A0lzBU$@1y{lZgr&A@p~xB(7G*-f-Tc><9^uAf`p37dsC|8n)2{C^-S>#$#T!d zUvo=S8>w-U7^{n+Xs%|2XxBa!fWI_tWN&a+fVJyBjvnA?1y{8T6ntolzSn=JG}On{ zGvt+n;Kz3nKs((q3|DE2v^k9`LN0wMBoF^U}4yI57f4?B`IK!OpeT_$u$&I04@5nG=hqp%xL z<*=H$9W`4%j}`8``$5jG+Mz&5LgY$e`q(FHImfV-p)SMQPEm>7Elk^y znxn+d8i3Psw63{m-{LV>G4#7=9mYDH<#78<*l{$FNvdXLXV;Y8ZI}m8L3iTc9iCF9 zYzgW8*?|bo8AmMCj}__<7MB@c2lNljla%Dx+PMDdPky;=R;oVGE5t7Sv62Y1?<2@e z*p@EGo$hkXi8JQqmA>)R1G%$(YP*^IPrviO*#paR6zc!G0s)$kr5Hej0J@~bD(IRq z^S{&~)y!*Kpi8EG+a>$AtdP}xB=4QBZISp{>zPk#2$}-9+a--Rj^^|>6SWbdStT?l z+OVceAC9|N6R9?jzaxbKn`D}aTPDY(51M2g9jQ3`bxcr2i3%pA5p!-nQ-? zy%FJs6+ZqvKB3Y2th0a;HYV{i;ZvFb(H+<5v5|wg1^#r%Wib!SP9NN!X+fcSVR!WW zr24RUH?9{JcRvSfa&~3)Sq6G^k1}?fRVTudM%pNvte8ITkZ?7(w|6#f|6-*tm%GS2 zV3bBesH*SL>h!!aQT`X-`+q%KbK$1QBRXQri=foIto{HS9sFK=@ z;LYdXWU|J0ni_vzLb951eAhuxV^a9Vm{1x^V`ExqEJt$nw;pFupQPU0BGC=#O$=10 z+E{Bv=g+yROG-^WrcyZgcx32DBSWf}Mk0_`&QY<853p^Il(OG|oP^*n0^TTpvW`ujdjmE&8H| zc$ddh`WTyirjl%csF%|gBUbdil=2Cw=tO zHUn~=DgGBY$_OtH2K%#LxXaCsm>&Gp>BXGfkB#ap&2d)^@$N01M~ zBxF1LO&e$f_V|;SUrKF#>{y@swsjs$O03*P$_>WEbd6+-Dv(#9O-Ui&>zd$gPWbwL z4AHYxIoJl)iYiqg-^9{bC_z5^J}Uz6MU^dimo7KGUvdZ!6#JPH3de7tS+MiOZRKc0 zW#<&~C1Gi$I%7QbF&EIhHVI!94sVA<%~mvgAM@icQzPB#v*!dlzYG;HO7swzx|w9z z>L@3w#;S5GzAT+J1Js_itniUVz~Tn<9Rf7aiKRKcMOTWFcpI0ZQk!bS)Hn-l3O+c2 z$net2)bL7vz<$Ay9C+Pq<7d|r%O+{7KgOo^y}YHY;z?;4!9fDvViFfLhErg~AFejb z#NI0}37F?(wUc9<>i4~RX(xCXCU!`BcK`;ac9>Q$_aDAR=$+`F^m;>nnm|78_V1dXklaVUBu||JJkIeuF*V!YL#j^ML%)Xn zUm!M7yR|3x$(}j0^NcK{$M7-VmSaU)jvz*}4?W;T< zZaXD!4uTR|!9@XF8Ft^#3h8u|=*>OgX-^D)zuF zIw$l%QfI}t&(OC;c}LIuqjmapqHm(AeYLpA>rOIEb@jCL8Vh zNimx72o&u&>-c0V7j0}gJ9~@4e1XI<#!uT zVdfywfE2HrJSy`O)syu09-Wurg;|_K?29dCP%~X)m2oon+VnEb`@w z&#{rwAxqrgW8Y5rJ;`^u_7Fy4vDuZuGk(hXc5x@^UBC1;>N|G`)Id}^SlNydnEllY5OwGPLTky*K zthl+ePQvhVO3>Op`8&d>zTP=fJ?_HL?(tO7x^O|?tKYRy`4$gwgCG5oZumVjLHed- z3M#5%7IXW6eO~?V?vnyzc~w%Xnb9R!BfVd5wU|&_&GQC9z|EbQdt)WXL z;NuW@1k<@H(5f1_r+2{*kYg$+(baH-Hq(X7VprT1yYmfb>x2D9L&$3WE?Pc$XaI~9 z>_uzr11<7?)47LcU{m$5|;?JV(^Yh9JJLxg!%4*Q(@82I`WSK|jtgoI2T$iCp zt^kMJK9a$=kAY~lYDDxDuDq)d$_$f_o-@?9O*CX}Q_%4+K;?6Bmo?=F?oi(Ye`P{) zS+`*T`Kk&q8(Q`vOx5Sr-d0D%an>t~M71#kl?tU4?~U8-UE}$UJ~%#d&0{AHhVVWU z?TH2t4WWU^6SD$b*o2~vl&MYCYs6;kGI(vF_49sBsNG4xSq9x!+|FGz$-^5^k_Hm! z37K0?q2pWpQ*S`n0NX9N1^ok3SG;Gv44cVZP5t2BBDiut{8SEsuFbV?)oFfOSlIjs z!{x2TU7RjKnb5=seqE-^V{epLkcViJ`>~vGOL$29oYJ~Hny--%`D^$sgq;B)4(mUR z%|Y0S_K;wq`k<l3Q_;p^_}0_f5h36kBZ=dtEtcMhh<5UC%3LkoYir>9nL z={7&HXpOT8XVXAdmVdQb((wazDtOu=lCu{@7jvZxtcGMWhVRjzj;7k2E=c&SeO zf&Ap3SwGcvO`}Xb9$H>)p#+J2tBVwEN7w+#%)^1I@J9M#WXhI$T>f`8B&^{enJ z&Wu!adX3$M^?C9QC?ug3C~@0Gz&0>)bPv1=)^231*0De`>9{;0OjFBL_48fnPl=Z$ zYP8*i9V(;M7%Wvzt^)1y6#jrZ;XzqUoL&5Q&-}!`Jzwpo${sqLpx@O zo{w5i>miTY6Y&9a=8byj6f)b3qF`RZO?CR>U3aLRDUVpI$H=nv zoQ%X7sO)i}&R$+4uzdK5IqvP-pmma~s4FpOKc*iY0M`f%0nPDs7$Eb~B-4i`J^)Nz zN~RSJb3cD?jD(m>yyeZ0s9NgdXq1n)Ubj*TdusVic%3UTjJDv>=|=sAkzr06Kw!kK#`n!D6)hbkOMG#HVNCU!U(5u@}8$2^K&XVE88xz=M^ti8+e(`$Vh}I zjMWbF)C2L%pq$czz#2_L>lgPfj=&~J{v)p?XqdYb8Pf66So-ppQRb+oO{s8YM?-AROr!FEPy zbVA>g>g-ds%@1n>&O#>U(&KmZL#2lB#gwy_DVd}l`Wi1?0E;F8Zj_5mLK7Gvu)4^+ zqdKS-faY(g6I*(2_qlz2)0JkX*45-9g)hkgdTYp}7Ig(}?}H)?`0jh>cR{J3OG!!I zRKFPbUXBY{K}e&vi8?P_W_Ge>FC=gcQ1G))xChO8Q%ne}dQ|3O4*-N|Q31@rf<(O& zTL6ZkwtZRzxD}j4fBdhfqS|NOPP59w|5+1#8Koj6)6^y^UNMO6f-TPoaf36n&#;a9; z-B^6fqXf!TfV&P*oSje*WtjH)UxF#lzl0Y`$K&w$Z@Gl9)?%y_3*#o^>GV;Gv z*dndfzZD)pZJhdFC1L@-k^){Fe)t4nfYJJ_PnE0PWp@vDPGwN_u!^ zji@!bNNk9ZV zuv(md)PIc&1_(E{;9y-ST{B^-&;8`t?nIimZ1bThbl5%m7L?8c1qeF&KqX)g!}}+H zxja)lfA$2A6uP8&5EF-;*H)bDakAPrynR3P3;GKPpRRj;lTAwb(Kai1`c9f(N%FC= z*)JyI6Cdw>*B>rrN1rbIviAc@PXmf`(ZApzA?SNXMn=}jRU(+lbJ`69{wQ~5HkLh5 z?=QDL#z2fECOWW#o9#Q%aB0#bWM);1_3aPX~=wy?TgTmp9=@yalg9>{-0Xp-#G|?JWWh${`3=fJ?MJ6 zt#sePNUJfne?%$U>P{p$B5eudOgIOkkM4yKL6@H*VN~@2pQmlO&l@plNO(OvJ}Dge zZ3aI{lalkWr13lQPJ5Hv{0TmY`dH-Zsi&~R)LDTgi^M?~E(~c~#!7Jw&n+qz_?=KL z@@qcde0*Hw>{6q*42zY7lzCru&&Ea9X5IZH@0p(B!@GK1a;_0dvx${)Epy#~=HLtW zBeg}Gx8Hz9Yf~4cB@DaAofUYISS1hj87D5p%#;L%bK1^eBhBiA5BE7O)BGPQJ(k=r zo`Z{c(})=DZA!jCb5iaeK&JU1sY=Mr>ts>tGpVQEks+b;GzPMy!}0e5eI2E15i`I} zlsvdRcqvDk8-bn&Ew_{ESa_%0Q~%*qm*DmU@mrma+$<$w=^Qt1i4+S==z%ABI+$4n~u9TB@Jn z=tsLjKBSzs3RzQZeUX+8MRKw%R(yeNe1xALT}%bO=GXLa@l%POtavAs^T+9(U)GoA zMz!AnY|1Vg#{@wt_%2`B#M!*PFI8{I| zniSy`vxky}dFx6M-~Im6Som$?GIPw`@4Y3Gd6Kzn@@lHw$gsSIBYiH9EKBK3BIVvQ zHy~92wk8Dc2K;0~yyTm4>IP#6NO+rf`)m|{MV2|Z;-Av_(o{??7;#IO#!l(g{bE^k z>jG|{(d6`J~5`%=PR#{6Z;@~5hDfo_&> z;S3$$N!%b03ch9$XNML3reEAa>z?L)#LeRB|Kjz=p9c!mjR=67iWHk#2BXLq&tE}j ztj`M(0C!AM!7_J8aA>))=B}@}N=xBtZP)n;UHNzOAlGBX_qgC@Q&r3$1Q2Z76@gi2 z!iKin*8pihq#bq_S=8C4M_V&{4$Gf2njuoSQa;B2c(kA3#E6-s#{Mbnlk>n52s085 zz1=^&QVc%Y0t1`$vRs>#-7*%8P`v|CbuhwY2>JNW9 z-0Y`;jO&(Ueo0Lup@-%o^{G7i{C#s}{EM~jIS3^_q&RE^Z%-DnDSMp`w^JijS%rpY z5aLd~f{$j1)qZ+9PdO|0!i^&MnAPE1S#zb3jnWB|4Uq0~eTaG3F}~Ooe(1MQ}jUfmAsev;dT9wU(!xzEmBC>rYxEO z=zZZmMBSEl!ANG!>r6C;cK`&#PY`ZeKjiTwRd*s!fjG)#Jz!^+C#dPptZ|p$XyrqN zlLyC=IX>z7%g3*zINiF9FG4cGU!cf`qNw}D=eIXALH7kPBk_)YcQSHM);gGXPx+t( zw?xhbepl3-Q&E-0PKg3qLSnZT80wjF5y3*Tad=*V%+E!+Ul;oM9+h`gsyP)R%T3@D z4rWaR)xDJChg>|lG~;4KVY35*!xkG(er2^cWobleiIFZ zFQpse?HQDNi}oBNGnJ7pcp-(~Bd1hE9{W;#b6^rvki5{D&ZR$L8wk;k z$)?Da9f|TBQO$|jSuGyiJ=qU$LiH6M)aj<-n-g2TeE`|mgZAd$fP62t3BGLFo#+qu zacCuG=-Jx?i{lJmiUdr@kc1MLBQ})R%H7B2oerx^nBHB#KWV9kEjxUz*bGcD`fhFE z?xjDI+;OF=iiOp` zeJKZm78cO&1T+QilO`kz1`R@Kugw3F&{N3!58Jo5xa}H^X>@cl{=_#nksZeJKBAE> zO8RyC;Ry#%Cw#bv8zM5uaMvV4WmWY6zIbE~ze+o>b>K6>#NX{qMM?l0eH{5W!+(zX zFPH7hJKOt$^f@xmfsX=^%yD-wx~UF$s0#P`wc8Hs z{LMuGer6^uGux(04xSC~eCuij;+x#z0_J-v-%*}QEC_MIa+RcqfTQ>Q^4HA-S)d{s zzQ@>gDsP?k2^9$l9fjcOz>ZZs{Vsx~jIB>4HLR@60(;)qJ~<0n{s1Xgc3MWFZv9bi zBZ}3Es7v*7bkjJ32y4H9Yq;&$xVkCws1+hBAWQIsx}EWaD#p@UFT&;51N?6^crEWQ zh|9b0;4+RLgu{A4ubZ!eF@`#Y&;%}%LRdw9_mzE}rlvuntoWKcwGwNwwT2U8M)C$8 zt38j6d__6wc6`6EbQt4&{t#!1_W|`F!qa7;z123mvC@ZG9BwO8wzQre4Qd|!H~oj? z|5_2`iPB&e4XK?>x{cR*s=frfg{r~34>WH#soi5W2t4eA=fmg0Opu<{@N<>m_r*kcG~1{$Bs);{dmui>V3uvKSX1{Q;> z6CZ@cAX$7MY+J$2A^bC%LS|GQCIW)%eo}$7)k>TQ?nKqH`E(j@N8T}31}4bF&HDO$ z=M=nGui3(qyQUA$k?kSfPiG0)D>K&IfX)j1xeKuZ`j8`nVed`41_+(I*&47~BlQJ3 zXaQ^zfeZii#R=6|QXQSs`5z=Y}l61_iI`6j{EXXA3 zYm9qvPwIZjrVKfA7}mkL^&{^i?N`GMVJw*V1;IJ$fFK`LeYx$3D;zhXWp%sX=a$MJ zCn5+T%Of{{3y8m?Kq@}|{93pC^s8M3KWv94?(t5=A>--?9B6p;ggv^s8jS(pE-PY@(3#-T;} z;+*5Q;~W>Hq~ESF9LB2^zQaim@ob3lob=Y%A3-w zG9=E!`Wq%-h{t?agAMh4&Hc>lt5qGGg@`C4?01};kYu~3`}&ohJh_C7&@cGTp=F8C znR;+^gPXnl#?RRv)qI7WMmj3O~o==or@FuQ@y z?Y0Pt`)!GzCDt#ATO0_znL0>BNFAc52|iP6JXzT=Li;Pbrgv}7+1A@tV~>1{n&Raw z=-?ifRf7q}glzuBz3*o(lc3Qvq+t=WVU$;}pf$yHb)+$me6nLe5apz7rqB^=R-&f- zBL8A}87Wx@ski{;co=9j*oGCQ8bwKD>EdeYk-Si6AFvqMnLd^dtGzB&5bPq83YiL- zc-PrKk<8p4NjCPEM!~>9m&OyIfWZAMktho5G4B3l z7SE)&5gbIgF^DBiw%mGf-@)z5fCnz%CO!HJq8z+doc?PhAFpwGi7#%~JoWjIdr4+K z46Q1v_z8U3B2(3<#u{+vo;vqYCY?j6+lqHVM&i2=ylBL6W$GH?=CNLo$R(zV{xS#Y zirTRX_4r}sg&51-4N>s0VI1kBZ7EkYStX^KpMr(E2KdVhTS>ZFM_c+j28x5evBq~b z8yJ(|XLv5{GtO7&XW_m&HZz8sZ~tnOPZrwSC2&I2Cb*QF+yHN%F(9-r^#7s)uqAfM z?o=S?@FAvH`{;LS;(1y^9n*)e>lz<)J=DAR;qg-MmGoP0K2in}8cs;mAq1O6|CIAC zwhPyo05lD~yxpWEOtVn`yIX{wnxjL;TSp->4=z#9Kyq^q-Tknwtv=Sb$74s3*7RvZ#Km_k_0m$k2@1&l$!|%<4kEH?&rB_V<2)Y>71>T4(KhkZ= z_}3yBGxcXz{jqS%dsfz>{Oya9==wMa{kFUM%)#le#l;?uks*n4Mn-MVpZEFB4xu-Z zZ{1>$j2Z&|C8#HbTnf!=2a3<9>s5nwhL|78-6>2zrq$+&8s{_SFTLW2`B{*ut3WyK z{jY7{Uxv}Era-PoF{^(7?{sh(<^;!t|FsSw-}#4(vEF%>Q^AZbbJfgN z$no{X3SUa=WUTudbhaXc9Ot}^yVNAG`pikKg092v_tm(LZ;R<3|5QF>(W_$JF3n*x zYz}}LKAZI=%kLP&4D2%#9{QJcWl|u;2-iqDbRlM;g zVNQZn+aK6SBzG|s#uo-J-!SXbgjASTHH#!E(3V~>UG z{z3#MD+-@HI~b%}_$JAtCjE1z{k!?wg!v>j(_54o_CpMd#NBG;jhXj%JsMu+!cUW^ z`|)Ea-EX)4?GE2T6vJ=A2mc}CB&py94Dm^8{&j=i`eHaq74(VmjD+{^zUg0e)xE{X z4vqKt@6k1{as9$3?b~8kQAbHI-Zg2?c}q(WpLL&ofz#cUuHfP&wc3hi{=>dQ0S%Kx zwV4+!fv9f8-eEEh?e+QX!`IFR-zszsCTl^JNS_CuiFa6vvXbA10=PHQC8+{QbXk1k`z zfi8VU)nb?e+livvx~nom-o#$XFw=!>BYA>Yf+_R3=F9YbL3`7nww9gU!=gYsOZ_V8;M@3rpqx%87nz`lPf22(6c!6e`Xc|9=-QOhfY}p zDUw~%8rLb{COT%!O;XRlZk!eimLGrLR=;-pOWHg{JhiK=BlP~*f9#RkO~J2Sa}zV3 zR7z?la##O_WZcOI;8)kk#AMF+|MsPYdrwm_RXQ-Dz~7+wIral7w&5<8p7s9! zA@%43b}@thpkA`bm&zko?f!k!fFddE2=XQPu_i>94A>s`{Mz>F~duw98!pUncj-=pE$%;3&_}R=k+f|34s~-241xSKlS1#3$LD z*~IF;SAE!z2LOF@OGpeP!F^|yTS_ioN}gB4WQ2#Of8-YV^jEkk=0_{A3iBG+HEb`4 zzC#)x(r<2M#BDV=iTZr+TG+cjaTnthGlkdcoolC+w3BhAkzWPczg#GOPLv+ro5>UOYeDFt-|H9-a5miPi$GGe7NiuolP@}V zGW##CDHQm;Zmsk-*MCe#F051|%&ATm^98?=M$U>a!t`{`tul4oa@3%l>T#QPWm6E7 zHIq5fxujpd|NQGqTaj2S-s)~V#@r1BsEF>JLyA_fzW(m9m%yQbeUcTGHJP1}z22C4 z2rnabh0tn8lDNmQ*Dvn6$^QlW_QFP7sKvhV8E~F6Pbt|nv0~W|va#}{TQJ+^$qFI+ zs);K#5wgB9CZx;IF-7*jx}AfMDU0A$uy@$XER6VC+Mm(_iUwzHlj^Agjw^4(H@jIF zG=E>;e~Ib%g4n9w2zW6fD)G}(cOxY*)h5zB#;5tmsj5cujU>8_-+Z*)$biQN1=hf5 zd$MFy+`C4w8So8+&~HL@;XgxoD@k z!Fx$4;*T4+Jj3o6zrZQSu!RmvW?CEG1w%jR<~Gj$u;hReg~;>pXkcoeT2BhBdb}Ipi-O1Qz%N z|C^+>@puu{PLZcM=7S60LJGXb?hhs9L-r%Vw{cRvx(2|jxgf9cfvZ>MI*M$FewdrdUAVf9Lf)DD=tjcVZ8 zqacC_+eJL>6)h>M<+=@)Pvl)3W9DDqkX%TUtK^3rjQF~ho#^qrT?xw>j806;=jSKG zXD@Qhmv{o~yH{hl=DKq^7w|og{w_$TIKF9($P|4^szvJD5M* zG0&hoDxnrP-joSOYl`*hh;1+Nh1_*ME9Z3zz)|j=S(iPuUnP<6ZIzy}Ob!^<;@5${ zvxcZ&Cd0Y=Fh{7TD#hP&tVxY=Bayb}wgZRe4P+0S2-U!4el%o34{c0*hA$1SxKAi| zNt%Dxxe*}4r07dH$iR)sx{IG8aXI)@Kp@wH68fp4`P{AkHjew*^{e9XI>T2uMEQKz zFpCCM6z1rI0nDX1m_cTu2laj9l<%W1a_Y=&1|%Qb*`M}yWor&v139=N(v4tAx`9u5 z=fG8f8exnJNTRtTlAn__4#{c+=jGNbb_FHH!>>?kODt3-cLeFY|ND07IzC#E4Cu?) zPQ<%YBYLCw@(PZK&Yz}p!`!sKZ!~702M^Y-pMgoqO$yLLsQD^BZtkHST$D#K;zAzxxwJi zUkc!U5R>$awrdoDFGjJcU6}nyGn&#zp~M=Q?lF~6j*k@+_LR+tvF}Uz$HTJP%7`(1 z(yg+L*P9V#Q})Z=A#=t%HEsPIKg7y4;E?JIPGDMqns61yMCI_x zj8tDz-Gt{?gmh`O8J*jx0bTou4z0xQe!cfeZG3<9%ehJ9HSGQriNrHr+FxIo&=bk#($b(f+$b?xs8E(ZV3Wd9F^6dIO`WF8`wg1N#< z{%5?RKv61wYjK*dKNpz50MO8X(Iu2s@bMq!>qqZ<+(S^erog8^R4(!ORA43QZNNOm6O_&X?G6ObI!Niq6G&_=JM%2%CH-Zmk#s5xYAhBok z*YU_FSoqiE5uZXE&7iA4sUHfp#qmeoFi8`-uXJm@X%CvWA`J8(3jDWh@DX0vq^Ecb z%#jYZzHbW`jlI^9<|n`J7ZmGY&m6SrpoyXVnW z_+*X-egp-j!Ox*ZqSTzfE!5A}mOT8v(B~B*RXLZc$@Be(?bmNE@p)9gEy(#@jz^`t zNX+;nf*f9;FK{I}f4ikIzC+fD%XD)&tx$on&rTt?u&Uu96FF-+L@tTv;l_iX_lM-M zaimEQlbZ$~ehYQjEU1!6d^l5g>1>W{xjC2MS0Xov z#1#0`8#Gl-8yht&VCHoOAfYe1JY!$K%`vmHZDZ<9UV}D>9JqLi^h$rYIO zLUqJ5xdiDnI&;fU3%2E;zSTB5yzHx!X?aAMUfq(eU!-v!4SRaoM0CNDcdH;Hyg^j{ z#$74+G_`gwL(IX4hQ@_VcBU4HU|>2dop6GKX2UFi+rZN*O7{~BSL`J zP8W|2sl>ZIunM8s&SjDyjo7_Tm)X6$AcS3p&vv{>9aZ9f`?V^q#$f*h8rs2z6-KPB zGViQNPY5zXcg&xySSdg2di%aNx!R0^M>ag{ZqVF(%j&@ameLyERRMEu#FRvOw|n(2 z@KxkH9lUb(VezY|(3bGam@KdcUs(P9+4Zqpvzm~9{igS>XNot-s?C=1&JISUzmH7} z$^D0nj`$9%9S)F1TG!sDxi~C9;t_IXBlCq8bU!^EuWxkTwo5iN?U*LLeBcee=dE&q_?;W2yhj#S1mZi6?JXM7nMu1XHlj4->+2KcE1KUfUa8a`b{~RAKK-h zwbHfKEtXPxFLg(QYuAnzd-@m5L*?9}KrBQ~6gVc`hAV2nMQ%mBwxzjw>fl~(O^XWJ_drfcKHs@4(!Ex{1BmOI!I*f@ryl#C+3V#|jVjqIFLJPNhU|LRWFeaHA1;zi6 zb+=D}Ybz@>7QgqrQd4x}O{+6rtTA{3J7(m+PD!zKvI1Q!!^OBIUDzL}+kaoQ#3wzB zws8E|og z7-WxI)arFLP*CBn4c~-3osIbA^~r#Gk(RngA1!pAWw{T_bX?PR&XxIHO%BRJHqLb( zQIf`1>(3K4ZsHlUy%VI4Mc=J|+RTeQUJ+q4h-w6x5&=8OzC44{U=((;yT9`_NZS& z8Y|LE&+e3?hD}&p-MyGunwx8swS~>G-+Ys<)qmaMcWRJ*R*7m2HPS6YVt{LMOP++1wza9%k}dapr+za%(phcJ?a zRxS6ybmb%_5If$6`z&V|v_HyrJ#1y%Ow6^|kY)GST20GMMp?7It%&$@0_?U&07vDp z;QiL!A~XPVGn{S;u;rc-4qQhJGci`wn@v;)Hw$R(nVxREmYHqRhv2p@^WWkR@<Rc)*mOwB|(^R9mM?1)-i!v(0heKu7eJ6*P zR}WGNraQj5>`40|I6q#xTNdxT+Py-9*FaPM)I2Y=W&LtFS(8U| z97|ls*AndT2()=9qJz`lzMGE?!^IX(u?DP(rp%+B`AD2OVSB#`hs_#>2sNj|cXT))&V=1cG}c zS+6I2Us(RVtdCxfWc*{3ZA<``Ow?&XFK*6V>Yw_}0l zWtL8o&wVOcIl#kE&e-^6i^e?dwRM=IWacyF)h1DD(^y*%^}WtO0Ho1z9T=Y~NOauY z>9_&dYhb2|z0U2N^7?K%jnh%{>;_B>`6vx26C<3BRyP=U^11B^o2ox_y{0DPLR5)i|g?bLe9tD`9$zK0CjEZ30g(9J zL%CL9UT<}hSh0wxvuuM^i}cmr^z+oee!de!6mFn-H%X7^O^=i7dj{CtgI`#`zRZ#j z=K520(3^O_F0Nk7KdGp8u3r`2h3zpjy)`A7Q)2_JlgDGn6mLy^C|L_iS<1VAUS7wZ zm3&aUh84#lFH6p(X?OU<=7<7VGRHvuhGwS>9H3!XSg6dGk`k)RIQQ&W^wEinG!;r* zT1(RS1?Pl`Usl7pVC?t`guk;sCb1q3jh%q0&Vf-}4RHo_Z8bTnoavh`{F)T(j742Z zGT+T_wT2BOCBVQ0H=^kTNeX|CE;{^D;DkdmyH!dPAEOQ)ELfa659FW@)1GR0{>-O- zV@p$xHlawm8~N@egySDF=kZu1yB%gTt=x={;g=dnv}poZ@nfO1$XxeBp`d8f!gOO* zC0e@_bC3Az9%>`p?jhA1;VX_OL+ZRqd=?snwqgjis zea_zUA0qX>6eWC;3wybDckm@Ot;RIo76U~k#UfuFeaPh@Lg|q4^5an}bXdO9LOjD3 z{Kspo`cbx@=MB_;`Alz0=a+!ccL$GL{vpd*I480=11_29cRs;d<2^ZSzlc!8g1&v3 zKhj`oh1U}&{y}EE!&X(3`DdH1P#dGp(q@PKGWvr3AQ+p~EsE)Pqgd+6Um*&|9`dr` ze!Vc*3kp&{U3FYJOu2ea&o}ePn0>e_@p-+GxO?^4Ku<+T58u_xc%m`k-8cYip>xi; zH%ANxMc#@tnye6+^j_4SDnuq%c#lh17RGnp5|(AWzi?$pBad*E_!h(7?}op#+C9$h zsBwL&O`uHkRmJ0S?Sg}FePo(<7R~}ym3U|N=jTCPCS^{J&|!uxFbCcZw~IZGRMSNh z;@ocd+pKqYD7IT`8)JO>z8*VV-H|o33JR%GK_^0!B#Xb@n zKs2#MCUBj{v{9nK^iH6g2X*Rt585!e)azLupoKFf3E{|qysLVj7br!}_YeNOI%kI3 z!-qns_`}g|J-PF(>#LC@CVyW#n}sfUIvV4t(WBUUDg=s&I$=HxZKc;dQ6>R(2z~s~ zl!3t+=qsSM26EYf^9Z_*{LsQ$|8>EwSKNwQUrX;pa&e4=v_O0GV$I<9@<}c7BkgOR zWR%Hgq-3C=0OQ9C@Nqq0#v?V+wM*lE5~tO36juN6^Rd%Zmm?^Z#hgiEhvv0}$k(bu zykU$cr=Xa&RxetA9TZ_hi9ryVQ+q9UcN$Wh1MU0o8oy&8Vp&^^Uo!cq+?MZ z@kVUT)Jc-XT7*Z}+z0s+5?B5q8=o!xu3zS4&Q;NAn)1gyEo|eCR9`fw;JQen^L7w) zAp;!-A4wp9v|LiVQ~ck-h8rYbb)e(o${vb&?swX=$5Hwb^!SGhm+~oC0U!Syl*CA=X;{OOS0vz#bQeFpvkL_&5Fz+1l-qAa z50Zw&)c+pTa$Q%Kv^@9(rD>PG$Xk)pGr*RahpdhDN$|K?adpcw0dwRctd*~XrRMEyh7 zXrH9UyOzM-#V3Y|`T%q7VEfR8B8)TcMD89vN%|QO_E6CHflz{7h|KF23$&5a{fb*b zK89)~+crg*#kGw6Wi)ibwl~xKeO-3oT#p6_li2*tk#wuUYGz7kuF`vFR$`Dwsexdh z-uY3ANj;@h+Z%ivkLWkgWes^H&FMdOVlY`}ArFbw07<$O%mWxP%)!JNAanI`xmxZa zy4c*1_`H@+7mi^$Fi|nbG^rlPK{7@_^{97;^)P2I>!*UZ%J;OEm{#pF{a@H zl|LhHxc7wB;D^vb^zYCAAtTERo8G>NY<5Ib3*P}YA-jU_99wmM!)1=4UWNp%UEH-3B<^DUiDnTou zqMl);O8kB-4Y+c?(nSadY&=h!|9#8;_QQJ&GAR%_(@dv9Lv60No%0NxXGf;n`OS+G z>7f5xJLe7Fd#nICOE?2i?h`u7tV;i78LYOO1B5t(2?oWyrTS~?g8pOA(B=OQk;H%@ zlHtHwxfB#|KSA1O`3-51eBA{~L+_{}&Mf;p7()_%3iU{l6@_x(QI@ z3eV-YQ}LwVzexPfQW=U0>5|2eE4R|y$Oj+2BK>~z@tkV0+UDQh?LOWzQr#H+r-({2 z_0^lv@Wh0B(rTcV<^laqK7F{0gC9v`=71mXQv?uO?WWycf3(`#aE|9ljwbsWx?z5L z1p}b!R55X=*^ITa5C%t&uA;?qgYI4FOoN){E43M(KmB(DZxF|o@-DNryd8FTpImq+ zxgjABFBLI*u~3k`zr>cZM}$O8Si;8S7D7__Y-fa3`fx~Onn=7vs#&3-Z2rRosIhQo z5B128IWW=_Re`0S*A-m`g_TH09_{VUXaXd3mFpJL$k$P zrSrBMV@TIy;x&iu4sOiZ<(4(@qNRw#0&QRA0;lkIyg0!b@cJPVktn)ZfRFUh`Cv|}`Zix@_YfIL@CkwBe+fMtb&?uvj7070q z#%Zb8wbITlK9T6|KOm2S*57QzhIEI}+hL*I&Y$z0CF;>~S1n+b-~dLKK?U1Cv{7QZ z6s%pu_ZaBFYIFxHKAEz&Z1HcsUcHdL)fdj*s%Gx>jqC#Q&Bf3{T3TB3_RxVlWd#MX z_ufT?RmX|uefVUuzbU?~bl~H=*ic#~&~aG;C%1v|V&fYxOzi4-pVp<zasoRmSQd(!`qFSqm(~V1vXG%7^Sv z^0V)#B7_464t%ic8n<9iUBvZ1=@xI7;{2a{96nZ*9i-Yzjo?X+ps*G0ux=uOih}8E z2|`5p^ewCCI;PkjrF4G**I?5^3b^UcGk7&o`_pT)byiXJtqmT6M*V%( z9NxELFR7|8LyJzPclm^`YoJw)xG};;;3ucN(zqLVAG-cah&i$;iSR=po)n}X_#8@q zFFYMw;uoEK?TfA54W@|0xi@RN8UP;rS2vBWq&vNj!NEl(~&E2$jpsflm0?W=6ttML}yV{pUJs z`!8J5zwiWlN#7c(d(7}s%a5|ted&-wQ5n%?A(-OGW%0aLMli)wS6x?rJ4a-e=!j|; z+gdxj{D&;N*aFI(B&=Y;e^2ZalR!MNyzt|d1+SEQ@d15s`2iklwMmn2sKL_yS<<;x zfJ4UMslQd^s|VySPr+zEMk7`C$$3j00ch!_2W+FYs52@ILEU z?MS0PE|x31{*te%BPZTER!Z3?-%1psc&+tO+|D;OIdy)dsxm3lY3P3wQxLzBfU9ry z5|T3Hr6WnspP*Og#<=2t1erX&H0v>rd)64NU@dzQuy%b6ZDo!2w|%>$Hq*&@FP@${@_^yxX7t+EtCv~r zVOzuA<~!pNZ5F@>5sm+a4$xrS)wte_H!WV)maw#sUo~%=c72)6@EK}S=Q%shQhv3m zA(21gJuM3}RD!5@nF_y0w469Ya`^&~haq?Ew@_IDSU0sS|kH=IU zrGDb(M8!2_seQ?}?N41}SDag;Q#`+gS@Q2*q4>(E+qDY(yEE1^zX_Ydp+&-g#TN)Ec3?tnYz8!MG9XN;Xh+5XuZ!3sz3BP zWHy@@2oP3{F>7G0H~tF)at5%5Q6W|K2hv#WN0>kDC>LpiM_9N)+%;Tv@$+Tqdx1w> zG|pw8i`^&1`58X@UNcFNF|SJsTj8#|OzsfDAN5@r_W=D5YJB7UU->DzLfQ?9yS$Kt zk9C?K-aSqKwb7Dp^w~&uzDR%ZSu@s-_3V8AHU@z@?@wCr)51{psVe)>-LM9~Xm4(a zeA^gckX^6>eUxwV_Y>#Kr^$=_9Ut({m{pwNWr+qKOlw+AX06>AwF%HW6&0GVSNS+f zpZ2IR^;a)g3u0WEtldPZbv2ie?#HHD*)v_W$GHDeE?JlGaVWn8qR1NbCQ)~;yjMjr zmNY9j1Pt@C_GKl^IUm2?sa~SbHuv?E6`zNx6L{bgBz}ChVpsdUhYu@z3VP7gvwE%1 zD-KTQ519T+*|(&aHpbp_6O&oxPm^FlH5GpA-WoA6pXcMb%pgg_RPZI33jokyu8;M} zh?UoQHRW=9MzT`w!01gHxrJVUt@{v-!sg8iF_nTc9&vJ0xsZ89z&}0W#zK67_d*3p zg1Rr>wkl+MgNz!&#`V7RrWVygg55#G3G5@fZ#;P$N_~?%MQVe?wgyei0ZJBdfN0>! z(b`cROuHA1ZF4XS3Plw;F6&;d6lkA^z+-N!QG3B^9U4HJ3@duBaM$@8z`|jJPe7?) zGG+Llz6+lZ4H|qcdg>-S3zfOwhivavJ!Y4&Skf1~-%Q;+Ep^PUnkee2(d7+m^g17y zESsCp1nqMY^!;m}U=GWQ9N9!gV)t(r75rY>ZSiTy3wBPY5o9xdA=DFdBlix~i3sL; zB{^z!zX)4`c8gf;Z(+?&NdE-T9OmPE%683EOgxw4T_c%;)ij)iH%}B?shj;6o8E3w zLtnONc;>e=qX)W^qCw;x{JX2vB+(s2;ob$$pOxd8`40nYCke zOQMy9uRh1{V6JK(fAYs+CsSo#nu3%3{{p%I1TF_m3Y#|9h5S%fh`&ywn#7?{oM}^G z?|H7+aVtgj#K}w#D&H&Vc8d-BV}K8%_$rP~70CpC1zIpiC5Bh*tq4z+3qfe|8>+A8 zmN_m&%*4JCSMRGY`dQl_{j*F!_FBSc@ial;+enkkV+e)fMQ{K&nsm!ia!b z>@7u=$Ju|%N-S2P53ZZ8)iyUJq913FEEsaz2j^SmcR*J{ULLU$U*j3E^yrA?(c-L9 zf0KniJA1#<-xi8FuEe;)w!~eBjmF>K_GKvmR=L=r+OtyKQ%XTN%mlZ(7qw0-+XHbD z<*??&d*j`I_dEC&eh;CY4-6#1y=)n7UO|;3ymRvloRY9DMjAgFmRGOuec=zm@m}V)*{!uxqJ?uyb{Z^2V)6s(T1O$zr@Xf-A9>Z+eo*w2;oakB7)j`4 z=)Gnq(hV1fiQ?a59-`SwF$i>emT)q{VTwcQ;Eh-xk0;d|iNta$vEe6Gx56|_-JQ+Y z)o`%{`+*P&7acpVIQ~6Bg8X!#}E#8(qeQI9!UaQ$}`NTiTXEM#Jp5^z$VY(^D;1wT0IZ*EWph z%PI{&B}=isr@S6BnTDe&*o+lFv&HFNMifQiS}{l6^a};rHEmO8!6G&-E*f)Yk&Z^z z;HNog8IQ{>&$o@8(qTn_5T2k)C3gp*^;NoF->63~ zQZJu1UPk^D^S3f@y6WixEsZUI$$V9dhR6TGv2 zz%^5(=m{tk9*G%j=o~T&X^-$Rwr`jX8mg))AW15ej-;Lr%EAwUVw$oj)C0Qf65N6=b zMeKJnks@WXPn-YwJwJ$rdk^sSR0#akS>*UHXPRD&5At*MTY=2z+@{+kkl47UzV1Kv zZ-UmBjLm;@>C}2th!Z4}ir+V8{x@=f5nxNuJ^8<52j1V>09cbX=lf-A;G_kXiDi+xR}qd81Vf^zW3PBXu@m*CwdF{XEVZ`jJ5bv6ak+Z5Jid{jLmIUa##5vD zJ9PuTS+@qqo`(AG@@Mf#g!*;ThneTmoT!QP*{oisvKKwyK|ldi?$#-E(rbH$Hd8!K z$@sk4?oDB{4-U5IcMh5lu_M&f)`ln^CfX8!7~9Dn$(39W-p#@Umg>9y8xJ0eiw@q3 z2h@^Wr9cYyS0BE}j)T_25SD&@)q-;{;O4w^!IpJ}%(rZOSJN!MrPp+<2;t~tzY@${ zupYYdJ`^#A1lUbMsVMq5FiHTk!3|UWp?vp1nc+!*gU&9c_uc^KAc6w#h$Vl4w_8^Q zbNk!qXRuYA^c%1}A74#qA(kttdCYxBEL$m)K%^-URojrQ>`q|YV{2}=EQ*5g@RMsP z3LBt5^cpXY9{3R?NHeH5J9@?@Ukd|SU0cj9CY7M)jIDia+ZC z3hNp1m6JI437hEGGh_eW$Yaw*N!MCr&LCH~GUQ<{JzT_J1YMaXT)P&BtnZ_5qVrn=59L#WyJpJ9* zK&JcP;`BYtBF-J}WG-%3{5zrdE2pc_tHj^Z;_G~!zJ>!EihaN(Ec2)z%mqQ~8=sqP z)B2`&ZoZ1I-YQ}6{NnsM_ zaHjbo`JFOwYu07@r5Jm{y3(tM_X7tyA@q3iz7Q^=I0_NllIlR>M$Slnn?{(t>3Vm3 zMPN(7mC{V)hKB15;Rtm^<c4~BT^SxaVpM}YIfu{yq8jI5%TttIu??pG3Wuo4cbkW4O_Q*dMV^pUJPk7G(*|&gH zFM}czOXF76ZT5HnC={}1mD_6fA|l}!;^^%68v+skB!F4frn&-Z|-)5k6q5g`sP0hq3l8;YOkTw&u!?j5ZGxHbS4z zZFwiFh4_2yJ^Htu185iGK3#TT#{1|g=ixtbpho?MMrZb32(7=t5$Y#f-Y>V;(`f|_ zRnzO&HD%uXIxKvYDNoJ3$e*(K`DVddM_B>P`!WK~MpVQ@F(=)ttS|`X!a9)7UT03a zvK+Dhx}zg#`|zM35;yv`?r!d?UdHkKeN}A{%v&fhuF6-+fwU-{l^kT_ZW^CYLK7v| zL2*!?0&Ecw^0t3im-Jo{&Iug!ADj-+&g>~GyIuM9dS!F=t<4G4F*(XYX2&FL_rkf} z9Ew?QKu{89fhTld6fHNkLqXda4e2#10eAx4w2>amn zwEzM_)a)AbIeD*&W#d5x;Vyi_w{ZbR`oC&B%dn`sc5e?zODHAM2uez)#E3{s53Mv3 zN{4hw4qXZo1Cm3FAR#Rwp)@GcDI(3tkiKiseLwep_x`%SavU(hf35Xf*Sgku64yIL z+<9WJHT$i)-MgU6lIo{WPVzul`P8j_sV>btoJ{`D)D3wL14aN=v4tbxGZUT&o!zOq z!>*0iE{~CNV+h{lQ^zII;bBhgEN)Gb z6ma=0#bcB80VqO;=Xnz|O)-(83~rx(rSe-h)*ofCjCY}%4&$M;N+9gPYr&hNZ&GbX z70=$1&CVOs{NW+n7bt7`HliawY>otF`W!*whdU3w?3K}>Ef!JfvCXj2xQygYEtM)2 zS!w*%GZ=_y6ZH_5_W zjos@vbfI^!H(oppuD9AZjrS1gIbKqmIDDGmipUAvQN0~tN*wU*oM!U2)9X=Q^HD#A z+Z8r1#I<-$Wyi?p4wF*lZ|TWD>cNd<*f_Y{(IS0T=BF_~M`<^=qculuYc%*F!=D27 zf}6zRH$`AZM~`Dl<6rqFRy+gdf%4uY3AqP@!<*RBb6>&=W?&G1b> zs{ibYKWrkg3xyvbzS(rXV8Zc}o8R=2kYVz2Q+Yq?QQGxLtn)>G-ulo(gQ;E?xR4~( zEfH^)6tmFIoZA5;P4O)KwAOqM%k)KC{(~TtgqjkaOM;7aEd@F22;x%@wCeRXRD&+UjjCxCYKenL^;~cIO$TP zejmnQ!ZS9tVf|z0!2#D#p^fOtoKu;RK)YD{b`t@#TcPc*JARl5m-XZXG@1TNW3{BJ z9hG_$Uo+Lf-dq3nSqkDdjgvl;bilwAUuQh6A3maOmS(3eR7MaDRhdLxPCFn`*!l9L z@viNXp$Ap!&Dtc%Cuym&=4?YztawW8_bWg8V$2Ujc@iBlLqEPoa2{-LM$d0Qm$?MS zTbY;5ylCz((ACoRVr`|-7`?e=L@6dZY?4Fxj9$p`e!V93T|qnvs2k|og<6BcQQa@5 zoxlzc~{|+==|ms>WT@U2NbFdS;Gkq*C+@K@;bLVL)ab$$UX(I zAB2z(DF6)Z`EO;Xa(Oy@@r34}PqlV3mRdJ^fD2_ZkYICZL?hb6pIc#4Sijl$TPcIw zy@t5Yw_ZI|__X%*_Is8q3I#BM{9{9VJi z6kqYTAD(YaxSQX9db)VuP){tjk6gyAqKJW@g3Mst(WBX7!?=;CdS+n1{y`WCE46qp z`*kU+S9Oo1jm91p{nY4;|GKsqxOwe_CSXv89xdlf`nGi4$fSX%h0eFs_ep5Dzx?30 z@{wn9g7v`@{-H;zL;?_*CsU3x%wD8DOShWmukG?8%1qE=zg#DpIE(FvX5?=-ZL4@A=`-$k&?x&@ysT!da3@#i)um<{v_Qo zy^!bU_0FU!TwS~&ESx<*WG=H~{HhUyZX;M)C>Bh+5n-m6n{J;_c)jlt(|buR!;su% zsm*Bde!bkI{Nc^!<;Y9b&2N=nx`gDsi7|`WV&e09`%4krntZ9cJJ%KK);(nt?kDY1 zG;_Nm*P*Oqt&3m7Iq2(GMH?aM5f#r~4(q+-$5!pwts*5Ca*%@Y#JXwS(UZBM`B{~llBI$&Weycks5*9UKSnjYm z`NCr4erVNzS#^kv`KX8!a6O$Y#(xF18k85c2uW4;;ml`}W zGL|dsxl}VrvO3*85)!q-^~S%z#WXTrsFeXfr?^3PZ-`B|x-j%7taFZAupaN)Ci zoS=QZM%tmEHcsBsN%*)Xe_PWv=6j^`m%bn$eGueu2_|ahuJ~E+tQHl{bost-o4u-B z0GCe|DvY*$i*L<-2%nF@UnM4xn(U|*&tQF;2jCS9s-+~XsEu>NuyQ|E&=?E2G5br8 zYt8f4vng6f&RLCkbFwW=RDo5qD^kyz&e0-;I}}f0s-C3o(r}=eX{-s!?s@VO6P@3a z$xZi9mJ5}UkI|(Cbdy5L{>~G10uR4*R`ZL$`uU|-05{(w1|qayxp+w~v5^(H$Z=uz zwGN^bQO8|7aw-j=i_lEk7x2gIJZ!`|tM2P@c_`<08uYTCa=-!c)0#F`H`!PzaKSpf$SL#)@0>Ze_5wZLI(NGv>?1xYb$^MFDa_wT^v-Q-Epj#hU%RAkD>HYJa_?$V z=AXAW0Ms`**chzYO$pt!1qEAdbFTVt{DZANDRL+8h}y#22S@V0(o6OB`{+#A?0t=( z>E@bDBc7vws37RCb{FI87LgE81I4nTF+RYG>nI4`XvLEe^%|THgfH##g<0RGxWene z5E;HG^JCr}I^$U4y_OK@-a_YRfK~%XAGd6uc8b~Ez-bxf4YIqzbLS3IQxW=+mpJeT z;_qiXVhTNdv}lUGF>%hm6Z`YswO$ z%bd5aH9|{d;t?u5{UP7_T@sGFv7Kh~4`UCVTi|CFXJ5U=2K-L|OYIlIE`B&|AjK)| zzKEK%Y~sNo^K>WVW>dAxYH`oy^S3!47&X?UX9{M*`oGTIANq8i>-&5uCqtyvbJI%G zOVIfoAH3!jFSn)pPYNH=bJ_DFMYp_|nq`x(v$H$*Syl{593vL-+qOfXHKfUmZ%U2Y zy+%0qJh-o2<}(>7lnZhdtv4g}!hf~1lc^EY)~or6`82<^6gt>&(nEemTdx>btRcBG zd7VaWgNtHV9;G({JFQ7!`fA7Yxk`Lle*#+la+6T3Jsz}<*=+0~(26KM*n67W%kP}u zmQ-l;4+r6-{!}tLVYcD~yI*MC&mCvvd=oD8f-1o2<(wzNsI@;Qc=rcf&pudF(-SIlE zm*{Yx8B20|zLlBhRWlL$NKz)^C(|bTj-)DjcOFY7ayamb5qnnAjEBA+U5r(QYZ9^9 z{`2P>hykas8Ve+Iu>m6O)}?p*9TpD7^gHBP$tcWkd{DxbcoxUU(VTxPa%a=4mk+5x6luvHdQ;PbW7xXOVg&d&Q?grqxt z^^;%x*3;aSQ7Q_#ltWa4T?|m$ruuS{AFQifI(Y34&s*7SGAybGO87{E0!E4q9b16E z#BXNsF1ly;eP=68)BUNq^0XRs6!kl^(?mYxdc(I;fn#C_t~b3vp=!4)LD#(-FuFqV zU)$PUoR7KiAXK~P7+n<W^`@13A;O;|;gw=`43Ax~ zT6UF|cYQ0!#qm1-Vs0!{PFI*XipVXtcOf0V5V92py`ov-VT(EVX)m4F;l@7T&$+9b zj?LUwNcckbojLljbci5ZFQ8eP>rVQDHQmcqQ={-)40jRGRN#=*n^yCC(j@B96!l(c z)?yKIx$Yy<;p4F=t_Z>_ZG!=|T3C-P6#3ZM4zP2)4bk*uvN}>F5A*X_r5neb$mo^; zRQ`TY2oRQCxSNsWdg@u27y4slGqT118E1*n$!V+6o5v(EHis!ZHt7DMxHOC4sZYp@ zfj2|KRv**puP}z>A_pYHFYKQ=#TVunj7*ym*t@yxpDK!Jq_)aw<@20o<0Fy8iCvv? z>|^81H(v>V^d^PS6f?RieCZzE)KTTsBT|s1x*GNHg1-rC3aXUn#G$8E`LnKMR(y0V zqMUjmZlaz^W@Jk!L^kR3VZxr{^NN@J%QcO?b^~Q071w~@;m=1^A zy1j$90B4k4fDwQ)WObfvx2bTvPQYjYNcF5SoKk=gWo}1N5h;w&b0CA^j0lWA99xcT zYfK1ojU8$f*;g#uA+SB0Z-?mDlUkD~d>ZFy3Hreh2~@po%Og7Jh5*-}p@{`-a9ApY z_^fah*NZI`&bhskXrBa%N-X)LJR@8v^8_XiXEa`QQXgl}JXik>@fr3GW=cyWmhVN0 zJWT3gTP?G=(45nTB_=F{bI}mLhI3*85jH;nnd*jxX*y;u4L!@vH>ggG^G((TuRZzm z4*l{cNvbc;?N4BoS}ODZ?Wn667L@h)A~NVj8T^5o0?%FFuF6>(0pNG)g8L-W0*v>V(%BN(VFg>%=d)`Mj#Ypo2uRjQBGja&Z?8XNT)&SX7BD z!P{Y}cM``{Zg*8GlnozS&qL81hmlW>B>5tb>3u>Cu_~U<^`^qwM#nLoXSpT!$0zExKm?C;Fu(0T0lK4!} zYYt0It8*gm2KRY@!Zz@+#q%J_GHky0Y?|BbWOTX}^_V_4VXitK3Auk_b>#tT)-sOw zv#Z^m0v_UIwcZPj;q1ee(5EwECTD5e+Z8JYO~!BBdm@5YmHC;cnXey7VLsrPhG?CuMMTgD6s9t-55ip9rbocceHnv8Is3QnBV z`qufbAN!tMn>%GkTh2=Y_yKy!c(lBhM9-A-#tVZfubjw(y>>y~!(P@);yRyk{aF|J zzCq_n!x^UHG|s(k7TRs#HScJHSxjJB#zGea9%{P(UX;`hd{Xp@!Ji|k(OWCFFJ zt1TQegr`qR)I1|q74bapg|2ON*FW5k?YSLCSSf8-NAi~B1F9$$PL{Dv@$r*~TW_hU z+`c;7?j`Y08OJEk(eE|!(`7AtY+-4RPO1KClAn~$4HOsc*%Oyfy3@4+db;7t?6->E zovZ-^NLSq)RKudsel@C!ckO7jL1w@o9)5r z0b{L%0W0HU!oj=t_^ETxM@O=PlKor)OO}sc1*g54o_?jmDT*`k8?q55r(^sZQb9$+ z0P#`U%|s$w-T2p*orW-WNiwflp>WE+^jp?+#;c}s+CM}2vO*Le_zs&fD`kTz)Be%0 z{Gkj`$j|Dz)a8H?aey`ObB)JMJsPA$`#VW|sAyEKBNoQUI;xAI2`E-u^9b z*HU!uqSiOG#xBq$K3YF;U;VyEwuZvS~5U<@`>-olBeV3$@bSJY<1K-p8p4cHhT z0~`?N7ov|bYXm|%n{h1rr=QlRUX8i{rXP$lC`s8!Zr}Z&`1|VwYTf|!F$|L6%5_mG zGAZ#5w)~_lV;Hf>SqTi8t%Aq!a16)WeWca-y1K57B+P0&;f=<=|A>Tmq3}0_FABrQ z!)9c>7&x&^NIF|N`^C=p^*oi-48_^7CT!nb<4~S}01L1s37^Nlb-j>?)>G8rkPM&p zYyM#im+`%Hc2<}`Q5q1nkvns_&?*k}>`-1$#rvWlJ!lk^q^<^0+7}|p3j^OgI7dkT z4H+vM`wdYEFZ|moQP`ICxbJ6*BU3pEDaKKK{4ans2TmqYHLb+wNgB&(ZJ~S#C9uuO zY7B}dFP;(Tsq;}tOME9#Yfr99UniUbrojtesO}GpJXClQ*C)%y>^;4ssZR(zBiK4u zpDsrN#qgs6ELvF1%erBS)*VU`Kjoz%{|E9=9rojw$MG9#SR|BMN|Wp)5eQv( zRsTcg{^xd4MUWuo1xlIrHqqlgZ+=5~=VD=ZE9HSY=&v5=LD2w2dHY9B4SFJl0z1}j!e#RsqF z<>d`I>3a@MIS)iGakG3N)*QObbli0ecc0r(6TN6`S#O;H)NnXl^D;eYt(hYI!%u+Y zmxRq0wR}=5zDM=IYE4@0-oB8txT&m`mh;WOTyuE7G9&c;=t#k3%DHEtbtNmPTwY=r zBofYAW(~J2l@ALVn{6%uhq_Sy+??xrywC{D6c5N;oaJd$-(Qyz zc>Y1Evjv4|WiBY#_YurPC3>Y?rt*NsxKk7!68aNolZwT9ZTa^>E3lxgg#GWF#r=@*IgxNvp599X4Cd!7QG|(`r3o?H$@NL1OD0)Ax zZzvJ`@Q8@r%gRF)Il-A4_QjCJ*S~%?SWTmTs3>tnO0blTGQ?z4&e}Vl65nanYtFQV zz^lxs#qK>LQ%9ME2mQB!x84k5Hdx4@9LTrCtnum1zS>H7`8cs#p7B13O~|{t;;g~1 zD)yuzc-$Vmo|guXSeRg;VH!#KKAD{Q-V02oEOKnqM{c%GlJy+H*seI+Kl#Jle=#pB zPq~a~yvo014-3n5l;T4oiMq&Uk1`I5vlWxK-49BtC=e_u3Zw!u7)SZ|6?Pye8%7s^ycvaXGQ$_4x%#1>;nR06J1e=c1ZM@eb-j1kOoHO|f1TVb z4It}oJcdb2x5O$e5>$COP{KnLT@<&r=Hs}aoUC*}ih+Ech^Hsec73q? z-hDUMq9;DIbydXP>EYu?`a>|`RXv?>n!+)D@W~T!IoRmqIDwiE`(n<5Cvm|0Xk452 z(J(>^G4|je_5-(R0(oW5)QtAAuM)^MTE;sb#0#)KwX`id-*P*fIOD=skPD|oB!JB= zz$Akz#zpu`1#SxelX0IH;^{~9nEibcLp8o!gB>kXR<=%XGODO^I4@LP`G;MFWolnt z--noArQdNJMDf0agL(%QYxgiBW54(Z-G83%Pu*Yf7LG?JSem31S#RVheLde^)6?vt zfV2uR3VqS#aSi#R{$Vv@HtUlZJtW-I!4c%sILsbNhDhW{L=w$+1#j z&4wM1XwY`g@%h{yBjEA~U2>1GJ+p`D#_%&n`-o*RddBtB|UR&{^InNWh#VW7)gI`V31G_*a;eBjR7)nH>$+quN zxKc4&>hj5qw4|0}j`Av-+*M*=kR%5<=zQ=+{IgEiv(dw={)x84mv87MuVeyxZ7lbzm+pQ4ZZD)2bH14iYb{sqMsJhCgej1lu%W0dtDA3Ssm!z_# zk_}nH&dvRPDLox5#$X}QIj8!YgPEC;6Pj~8A6O@wW#tKjCGWX33Skc3Bn%U_Ot?l% zdau3maTFl=ZZ$(8rQD9NySZL6}-$1ECu%Sf!x^>1K%$k=GjHEZi*r(PT>*;#6SraVNhSYF**n)f-(Paq%{ zZ%AI133=`P2rUh2m*7A7;k-u23Me_}bkzUpAV=J#PZlHr)hZE|ShiJ)=ilvXAxnuW z^PJj6B<=a7Rp+Nv$(fcQ+awT*dVc1x#lz)sZhDn@KQVTcDThjU-Z=J+OE&60psRc# X%*G6FX --from= --chain-id=fuxi-3000 --fee=400000000000000iris --gas=20000 --node=http://localhost:36657 +``` + +> Please Note the `deposit` is in minimum unit. + +The `` for `proposer` field should start with `faa` which corresponds to ``. + + +## How to add deposit to a proposal? + +To add deposit to some proposal, you could execute this command to add `10IRIS` to the proposal's deposit: + +``` +iriscli gov deposit --proposalID=1 --depositer= --deposit=1000000000000000000iris --from= --chain-id=fuxi-3000 --fee=400000000000000iris --gas=20000 --node=http://localhost:36657 +``` + +## How to vote a proposal? + +In the current version of governance module, you have the following choices for each proposal: +* Yes +* No +* NoWithVeto +* Abstien + +You could put one of the choices in the `--option` field. + +To vote for a proposal, you need to get the correct ``.You could execute the following command to vote on proposal with ID = 1: +``` +iriscli vote --from=jerry --voter= --proposalID=1 --option=Yes --chain-id=fuxi-3000 + --fee=2000000000000000iris --gas=20000 --node=http://localhost:36657 +``` + +## How to get more information about a proposal? + +You could use the following command to get the first proposal: +``` +iriscli gov query-proposal --proposalID=1 --chain-id=fuxi-3000 --node=http://localhost:26657 + +``` + diff --git a/docs/validators/Setup A Sentry Node.md b/docs/validators/Setup A Sentry Node.md new file mode 100644 index 000000000..184150087 --- /dev/null +++ b/docs/validators/Setup A Sentry Node.md @@ -0,0 +1,59 @@ +# Setup A Sentry Node + +## Why do we need a sentry node? + +A validator node is under the risk of distributed denial-of-service (DDoS)attack. It occures when an attacker tries to disrupt normal traffic of a node. In this way, this node will be isolated from other nodes in the network. One way to mitigate this risk is for validators to carefully structure their network topology in a so-called sentry node architecture. + +## What is a sentry node? + +In IRISnet, a sentry node is just a normal full node. The validator node will only connect to its sentry node. In this way, the sentry nodes will be protect the validator node from DDoS attack. + +## How to setup a sentry node? + + +### Sentry Node + +On the sentry node's side, you need to get fully initialized first. + +Then, you should edit its `config.tmol` file, and change `private_peers_id` field: + +``` +private_peers_id="" +``` + +`validator node id` is the `node-id` of validator node. + +Then you could start your sentry node, + +``` +iris start --home= +``` + +If you have multiple sentry node, you could make them as `persistent-peers` to each other. + +### Validator Node + +On the validator node's side, you also need to get fully initialized first, and make sure you have the `priv_validator.json` file backuped. + +Then, you should edit its `config.tmol` file, + +``` +persistent_peers="@" +``` + +If you want to put multiple sentry info, you need to separate the information with `,` + +Set +``` +pex=false +``` +In this way, the validator node will diable its peer reactor, so it will not respond to any peer exchange request other than its sentry nodes. + +Then you could start your validator node, + +``` +iris start --home= +``` + +It's also recommanded to enable the firewall of validator node. + diff --git a/docs/validators/overview.md b/docs/validators/overview.md new file mode 100644 index 000000000..4d292ab8a --- /dev/null +++ b/docs/validators/overview.md @@ -0,0 +1,15 @@ +## Tendermint & Cosmos-SDK + +Tendermint is software for securely and consistently replicating an application on many machines. Tendermint is designed to be easy-to-use, simple-to-understand, highly performant, and useful for a wide variety of distributed applications. + + + +## What is a validator + +In IRIS network , a validator is responsible for for creating new blocks and verifying transactions. The IRIS network will keep generating value when its validators could keep the whole network secure. +Validator candidates can bond their own IRIS to become a validator. + + +## What is a delegator + +People that cannot, or do not want to run validator operations, can still participate in the staking process as delegators. Indeed, validators are not chosen based on their own stake but based on their total stake, which is the sum of their own stake and of the stake that is delegated to them. This is an important property, as it makes delegators a safeguard against validators that exhibit bad behavior. If a validator misbehaves, its delegators will move their Atoms away from it, thereby reducing its stake. Eventually, if a validator's stake falls under the top 100 addresses with highest stake, it will exit the validator set. \ No newline at end of file diff --git a/docs/zh/README.md b/docs/zh/README.md new file mode 100644 index 000000000..29b46317a --- /dev/null +++ b/docs/zh/README.md @@ -0,0 +1,5 @@ +# IRISnet文档目录 +![irisnet](../pics/iris.jpg) + +IRIS网络是上海边界智能和Tendermint团队合作打造的跨链区块链网络,将是Cos- mos网络生态中的第一个区域性枢纽(Hub),并专注于为分布式商业应用提供基础 设施和协议。 +IRISnet将面向服务的基础设施融入到Cosmos网络中,支持对包括公链、联盟链以及 现有传统商业系统的集成从而实现互联互通。通过对Cosmos网络的跨链协议进行创新 扩展,IRISnet允许数据及复杂计算跨异构网络被调用。就像忠实地在人间和天堂传递 信息的希腊彩虹女神 Iris, IRISnet的目标是成为链接数字经济和实体经济,支持构建复 杂分布式商业应用的下一代公链。 diff --git a/docs/zh/get-started/Full-Node.md b/docs/zh/get-started/Full-Node.md new file mode 100644 index 000000000..dfc69a0de --- /dev/null +++ b/docs/zh/get-started/Full-Node.md @@ -0,0 +1,89 @@ +# 如何运行一个全节点 + +## 配置 + +### 设置软件运行的目录 + +iris在运行过程中所依赖的配置文件和数据会存放在\$IRISHOME下,所以在运行iris前,需要指定一个目录作为\$IRISHOME。\$IRISHOME默认为:/Users/$user/.iris。 + +在\$IRISHOME需要设置两个文件夹:/config 和 /data + +### 下载配置文件文件 +iris运行中需要用到两个重要的文件:genesis.json 和config.toml + +genesis文件中定义了区块链网络的初始状态,而config.toml指定了iris软件模块的重要组成部分。 + +下载这两个文件到/$IRISHOME/config目录下: + +``` +cd $IRISHOME/config/ +wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-3000/config/config.toml +wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-3000/config/genesis.json +``` +### 修改配置文件 +在config.tmol文件中可以配置以下信息: +* 将`moniker`字段配置称为自定义的名称,这样便于区分不同的节点 +* `seed`字段用语设置种子节点,在fuxi-2000中的官方中字节点为:3fb472c641078eaaee4a4acbe32841f18967672c@35.165.232.141:26657 + +## 启动一个全节点 + +通过以下命令启动全节点,并将日志输出到文件中: +``` +iris start --home {path_to_your_home} > log文件地址 & +``` +通过执行以下操作确认节点的运行状态: +``` +iriscli status +``` +示例输出: +```json +{"node_info":{"id":"3fb472c641078eaaee4a4acbe32841f18967672c","listen_addr":"172.31.0.190:26656","network":"fuxi-2000","version":"0.22.6","channels":"4020212223303800","moniker":"name","other":["amino_version=0.10.1","p2p_version=0.5.0","consensus_version=v1/0.2.2","rpc_version=0.7.0/3","tx_index=on","rpc_addr=tcp://0.0.0.0:26657"]},"sync_info":{"latest_block_hash":"7B1168B2055B19F811773EEE56BB3C9ECB6F3B37","latest_app_hash":"B8F7F8BF18E3F1829CCDE26897DB905A51AF4372","latest_block_height":12567,"latest_block_time":"2018-08-25T11:33:13.164432273Z","catching_up":false},"validator_info":{"address":"CAF80DAEC0F4A7036DD2116B56F89B07F43A133E","pub_key":{"type":"AC26791624DE60","value":"Cl6Yq+gqZZY14QxrguOaZqAswPhluv7bDfcyQx2uSRc="},"voting_power":0}} +``` +通过以上命令可以查看状态: + +* `"catching_up":false`: 表示节点与网络保持同步 + +* `"catching_up":true`: 表示节点正在同步区块 + +* `"latest_block_height"`: 表示最新的区块高度 + + +之后你就应该可以在浏览器中看到 + +## 重置一个全节点 + +若需要将一个节点重启,则可以通过以下命令让节点再次通过与网络保持同步。 + +### 重置IRIShub节点流程如下: + +1. 关闭iris进程 +``` +kill -9 +``` + +若Genesis文件有变动,则需要下载新的文件到$IRISHOME/config目录下。 + +2. 重置iris +``` +iris unsafe_reset_all --home= +``` + +3. 重新启动 + +通过以下命令启动全节点,并将日志输出到文件中: +``` +iris start --home > log文件地址 & +``` +通过执行以下操作确认节点的运行状态: +``` +iriscli status +``` +示例输出: +```json +{"node_info":{"id":"3fb472c641078eaaee4a4acbe32841f18967672c","listen_addr":"172.31.0.190:26656","network":"fuxi-2000","version":"0.22.6","channels":"4020212223303800","moniker":"name","other":["amino_version=0.10.1","p2p_version=0.5.0","consensus_version=v1/0.2.2","rpc_version=0.7.0/3","tx_index=on","rpc_addr=tcp://0.0.0.0:26657"]},"sync_info":{"latest_block_hash":"7B1168B2055B19F811773EEE56BB3C9ECB6F3B37","latest_app_hash":"B8F7F8BF18E3F1829CCDE26897DB905A51AF4372","latest_block_height":12567,"latest_block_time":"2018-08-25T11:33:13.164432273Z","catching_up":false},"validator_info":{"address":"CAF80DAEC0F4A7036DD2116B56F89B07F43A133E","pub_key":{"type":"AC26791624DE60","value":"Cl6Yq+gqZZY14QxrguOaZqAswPhluv7bDfcyQx2uSRc="},"voting_power":100}} +``` +通过以上命令可以查看状态: + +* `"catching_up":false`: 表示节点与网络保持同步 + +* `"latest_block_height"`: 表示最新的区块高度 \ No newline at end of file diff --git a/docs/zh/get-started/Genesis-Generation-Process.md b/docs/zh/get-started/Genesis-Generation-Process.md new file mode 100644 index 000000000..6c4bf6b6a --- /dev/null +++ b/docs/zh/get-started/Genesis-Generation-Process.md @@ -0,0 +1,77 @@ +# 参与到Genesis文件生成流程中 + + +1. 每个希望成为验证人的参与者确保安装了对应版本的软件:iris v0.4.1 + +2. 执行gentx命令,获得一个node-id.json的文件。这个操作将默认生成一个余额为200IRIS的账户,该账户默认绑定100IRIS成为一个验证人候选人。 + +``` + iris init gen-tx --name=your_name --home=path_to_home --ip=Your_public_IP +``` + 代码示例: +``` + iris init gen-tx --name=alice +``` + +``` + { + "app_message": { + "secret": "similar spread grace kite security age pig easy always prize salon clip exhibit electric art abandon" + }, + "gen_tx_file": { + "node_id": "3385a8e3895b169eab3024079d987602b4d2b383", + "ip": "192.168.1.7", + "validator": { + "pub_key": { + "type": "AC26791624DE60", + "value": "RDxXckkpTc35q9xlLNXjzUAov6xMkGJlwtWg2IqAkD8=" + }, + "power": 100, + "name": "" + }, + "app_gen_tx": { + "name": "alice", + "address": "8D3B5761BC2B9048E2A7745B14E62D51C82E0B7C", + "pub_key": { + "type": "AC26791624DE60", + "value": "RDxXckkpTc35q9xlLNXjzUAov6xMkGJlwtWg2IqAkD8=" + } + } + } + } + ``` +然后你可以发现在$IRISHOME/config目录下生成了一个gentx文件夹。里面存在一个gentx-node-ID.json文件。这个文件包含了如下信息: + + ``` + { + "node_id": "3385a8e3895b169eab3024079d987602b4d2b383", + "ip": "192.168.1.7", + "validator": { + "pub_key": { + "type": "AC26791624DE60", + "value": "RDxXckkpTc35q9xlLNXjzUAov6xMkGJlwtWg2IqAkD8=" + }, + "power": 100, + "name": "" + }, + "app_gen_tx": { + "name": "alice", + "address": "8D3B5761BC2B9048E2A7745B14E62D51C82E0B7C", + "pub_key": { + "type": "AC26791624DE60", + "value": "RDxXckkpTc35q9xlLNXjzUAov6xMkGJlwtWg2IqAkD8=" + } + } + } + ``` + validator字段对应了home/config下的节点信息 + + `app_gen_tx`中说明了拥有这个节点的账户信息。这个账户的助记词就是刚刚的secret + +3. 将上述提到的json文件以提交Pull Request的形式上传到`https://github.com/irisnet/testnets/tree/master/testnets/fuxi-3000/config/gentx`目录下: + + 注意⚠️:json文中的IP改成公网IP + + + + diff --git a/docs/zh/get-started/README.md b/docs/zh/get-started/README.md new file mode 100644 index 000000000..d1720d36a --- /dev/null +++ b/docs/zh/get-started/README.md @@ -0,0 +1,213 @@ +# IRISnet测试网 + + +## IRIShub 简介 + +IRIS Hub是在Cosmos生态中的区域性枢纽,提供iService服务 + +## 如何加入fuxi-3000测试网 + +### 安装IRIShub + +#### 服务器配置要求 + + +首先,你需要配置一台服务器。你的验证人节点应该能够一直运行,使用你可能需要在一台数据中心的服务器。任何像AWS、GCP、DigitalOcean中的云服务器都是适合的。 + +IRIS Hub是用Go语言编写的。它可以在任何能够编译并运行Go语言程序的平台上工作。然而,我强烈建议在Linux服务器上运行验证人节点。我曾经尝试在Windows上运行验证人节点。我能够顺利的编译但是在运行的时候会有一些问题。接下来的说明和指导都是基于Linux服务器的。 +这是我们的服务器的配置: + +* CPU核数:2 +* 内存容量:2GB +* 磁盘空间:40GB +* 操作系统:Ubuntu 18.04 LTS/16.04 LTS +* 允许的入方向的链接:TCP端口 26656 和 26657 + + +#### 方法1:下载发行版安装 + +进入下载页: https://github.com/irisnet/irishub/releases/ +下载对应版本的可执行文件 +解压缩tar -C /usr/local/bin -xzf iris$VERSION.$OS-$ARCH.zip +拷贝到/usr/local/bin/目录下 +执行以下命令,若出现对应的版本号则说明安装成功。 +``` +$ iris version +v0.4.1 + +$ iriscli version +v0.4.1 +``` +#### 方法2:源码编译安装 + +#### 安装Go版本 1.10+ + + +系统要求: + +Ubuntu LTS 16.04 + + +安装IRISHub需要保证Go的版本在1.10以上, + +通过执行以下命令安装1.10版本的Go。 + +``` + $ sudo add-apt-repository ppa:gophers/archive + $ sudo apt-get update + $ sudo apt-get install golang-1.10-go +``` + +以上命令将安装 golang-1.10-go在 /usr/lib/go-1.10/bin. 需要将它加入到PATH中 + +``` + echo "export PATH=$PATH:/usr/lib/go-1.10/bin" >> ~/.bash_profile + source ~/.bash_profile +``` + +同时,你需要指定相关的 $GOPATH, $GOBIN, 和 $PATH 变量, 例如: + +``` + mkdir -p $HOME/go/bin + echo "export GOPATH=$HOME/go" >> ~/.bash_profile + source ~/.bash_profile + echo "export GOBIN=$GOPATH/bin" >> ~/.bash_profile + source ~/.bash_profile + echo "export PATH=$PATH:$GOBIN" >> ~/.bash_profile + source ~/.bash_profile +``` + +参考链接: + +1. https://golang.org/doc/install +2. https://github.com/golang/go/wiki/Ubuntu + + + +#### 下载源码并安装 + + +在完成Go的安装后,通过以下命令下载并安装IRIS hub相关程序. + +``` +mkdir -p $GOPATH/src/github.com/irisnet +cd $GOPATH/src/github.com/irisnet +git clone https://github.com/irisnet/irishub +cd irishub && git checkout v0.4.1 + +curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh + +make get_vendor_deps && make install +``` + +以上命令将完成 iris 和 iriscli的安装. 若出现对应的版本号则说明安装成功。 + +``` +$ iris version +v0.4.1 + +$ iriscli version +v0.4.1 +``` + +### 部署一个全节点 + +* **配置软件运行的目录** + +iris在运行过程中所依赖的配置文件和数据会存放在\$IRISHOME下,所以在运行iris前,需要指定一个目录作为$IRISHOME。若不配置目录,则\$IRISHOME默认为:/\$HOME/.iris。 + +* **初始化** + 执行以下操作, + ``` + iris init --home=iris-home + ``` + +会在$IRISHOME下创建两个文件夹:/config 和 /data。/config终会包含两个重要文件:genesis.json 和config.toml。genesis文件中定义了区块链网络的初始状态,而config.toml指定了iris软件模块的重要组成部分。 + +* **下载配置文件文件** + +下载配置文件,并替换原有的/$IRISHOME/config目录下的文件: + + cd $IRISHOME/config/ + rm genesis.json + rm config.toml + wget https://raw.githubusercontent.com/irisnet/testnets/master/fuxi/fuxi-3000/config/config.toml + wget https://raw.githubusercontent.com/irisnet/testnets/master/fuxi/fuxi-3000/config/genesis.json + +* **修改配置文件** + +在config.tmol文件中可以配置以下信息: + +1. 将moniker字段配置称为自定义的名称,这样便于区分不同的节点 +2. seed字段用语设置种子节点,在fuxi-2000中的官方种子节点为: +``` +c16700520a810b270206d59f0f02ea9abd85a4fe@35.165.232.141:26656 +``` + +3. 将`external_address` 改为`本地IP:26656` + +* **启动一个全节点** + +通过以下命令启动全节点,并将日志输出到文件中: + + iris start --home $IRISHOME > log & + +通过执行以下操作确认节点的运行状态: + + iriscli status + +示例输出: + +```json +{"node_info":{"id":"1c40d19d695721fc3e3ce44cbc3f446f038b36e4","listen_addr":"172.31.0.190:46656","network":"iris-stage-4","version":"0.22.6","channels":"4020212223303800","moniker":"name","other":["amino_version=0.10.1","p2p_version=0.5.0","consensus_version=v1/0.2.2","rpc_version=0.7.0/3","tx_index=on","rpc_addr=tcp://0.0.0.0:46657"]},"sync_info":{"latest_block_hash":"41117D8CB54FA54EFD8DEAD81D6D83BDCE0E63AC","latest_app_hash":"95D82B8AC8B64C4CD6F85C1D91F999C2D1DA4F0A","latest_block_height":"1517","latest_block_time":"2018-09-07T05:44:27.810641328Z","catching_up":false},"validator_info":{"address":"3FCCECF1A27A9CEBD394F3A0C5253ADAA8392EB7","pub_key":{"type":"tendermint/PubKeyEd25519","value":"wZp1blOEwJu4UuqbEmivzjUMO1UwUK4C0jRH96HhV90="},"voting_power":"100"}} +``` +通过以上命令可以查看状态: + +* `"catching_up":false`: 表示节点与网络保持同步 + +* `"catching_up":true`: 表示节点正在同步区块 + +* `"latest_block_height"`: 表示最新的区块高度 + + ​ + +* **重置一个全节点** + +若需要将一个节点重启,则可以通过以下命令让节点再次通过与网络保持同步。 + +重置IRIShub节点流程如下: + +1. 关闭iris进程 +``` +kill -9 PID +``` + + +若Genesis文件有变动,则需要下载新的文件到$IRISHOME/config目录下。 + +2. 重置iris + +iris unsafe_reset_all --home=$IRIShome + +3. 重新启动 + +通过以下命令启动全节点,并将日志输出到文件中: + + iris start --home path_to_your_home > log文件地址 & + +通过执行以下操作确认节点的运行状态: + + iriscli status + +示例输出: + +```json +{"node_info":{"id":"1c40d19d695721fc3e3ce44cbc3f446f038b36e4","listen_addr":"172.31.0.190:46656","network":"iris-stage-4","version":"0.22.6","channels":"4020212223303800","moniker":"name","other":["amino_version=0.10.1","p2p_version=0.5.0","consensus_version=v1/0.2.2","rpc_version=0.7.0/3","tx_index=on","rpc_addr=tcp://0.0.0.0:46657"]},"sync_info":{"latest_block_hash":"41117D8CB54FA54EFD8DEAD81D6D83BDCE0E63AC","latest_app_hash":"95D82B8AC8B64C4CD6F85C1D91F999C2D1DA4F0A","latest_block_height":"1517","latest_block_time":"2018-09-07T05:44:27.810641328Z","catching_up":false},"validator_info":{"address":"3FCCECF1A27A9CEBD394F3A0C5253ADAA8392EB7","pub_key":{"type":"tendermint/PubKeyEd25519","value":"wZp1blOEwJu4UuqbEmivzjUMO1UwUK4C0jRH96HhV90="},"voting_power":"100"}} +``` + +通过以上命令可以查看状态: + +* `"catching_up":false`: 表示节点与网络保持同步 + +* `"latest_block_height"`: 表示最新的区块高度 + diff --git a/docs/zh/get-started/Validator-Node.md b/docs/zh/get-started/Validator-Node.md new file mode 100644 index 000000000..138f2fcdf --- /dev/null +++ b/docs/zh/get-started/Validator-Node.md @@ -0,0 +1,127 @@ +# 运行一个验证人节点 + +在配置验证人节点之前,请保证已经按照此[文档](安装IRISHub.md)正确安装了**Iris** + +在IRISHub枢纽中,验证人负责将交易打包并提交区块。成为一个验证人需要满足很多条件,不仅仅是技术和硬件上的投资。同时,因为只有在有限验证人的条件下,Tendermint才能发挥最大的作用。目前,我们将IRISHub枢纽的验证人上限定为100。也就是说只有前100个验证人能够获得奖励,而大部分IRIS持有者不会成为验证人而是通过委托的方式决定谁会成为验证人。 + +## 如何升级成一个验证人节点 + +### 获取IRIS Token + +#### 创建一个账户 +你首先需要安装`iris` 和 `iriscli`。然后执行以下操作创建一个新的账户: + +``` +iriscli keys add +``` + +然后你需要输入至少8位的密码。 + +示例输出如下: +``` +NAME: TYPE: ADDRESS: PUBKEY: +tom local faa1arlugktm7p64uylcmh6w0g5m09ptvklxm5k69x fap1addwnpepqvlmtpv7tke2k93vlyfpy2sxup93jfulll6r3jty695dkh09tekrzagazek +**Important** write this seed phrase in a safe place. +It is the only way to recover your account if you ever forget your password. + +blast change tumble toddler rival ordinary chicken dirt physical club few language noise oak moment consider enemy claim elephant cruel people adult peanut garden +``` + +你可以查看到该账户的地址和公钥。在IRISHub中,地址经过bech32编码后将以`faa`为首字节 ,另外公钥将以 `fap`为首字节. + +账户的助记词(seed phrase)也将被显示出来。你可以使用该长度为24个单词的助记词在任意的机器上恢复你的账户。恢复账户的命令是: + +``` +iriscli keys add --recover +``` +### Claim tokens + + +一旦你完成了账户的创建,你可以通过[水龙头](https://testnet.irisplorer.io/#/faucet)获得用于测试网的IRIS token。ese tokens to stake as a validator. +水龙头每次将发送10IRIS,请按需使用! + +以下命令将查询你的账户的余额: + +``` +iriscli account --node=http://localhost:26657 +``` + +## 执行成为验证人操作 + +### 确认你的全节点与网络保持同步 + +通过以下命令确认节点的状况: +``` +iriscli status --node=tcp://localhost:26657 +``` +若 `catching_up` 字段为 `false`那么你的节点就是同步的。 + +你需要获取当前节点的公钥信息来执行以下操作,公钥信息以 `fvp`为首字节,想要了解更多的编码信息,请参考以下 [文档](../get-started/tools/Bech32%20on%20IRISnet.md) + +通过执行以下命令获得节点的公钥信息: + +``` +iris tendermint show_validator --home= +``` +示例输出: +``` +fvp1zcjduepqv7z2kgussh7ufe8e0prupwcm7l9jcn2fp90yeupaszmqjk73rjxq8yzw85 +``` +然后,使用以上输出作为`iriscli stake create-validator`命令的 `` 字段: + +``` +iriscli stake create-validator --amount=iris --pubkey= --address-validator= --moniker= --chain-id=game-of-genesis --name= --node=http://localhost:26657 +``` +> 注意:**amount**字段需要使用最小单位iris。准化比例为: + +1 IRIS=10^18iris + +也就是说,如果你想要抵押1IRIS,你可以执行以下操作: + +``` +iriscli stake create-validator --pubkey=pubkey --address-validator=account --fee=40000000000000000iris --gas=2000000 --from= --chain-id=fuxi-3000 --node=tcp://localhost:26657 --amount=1000000000000000000iris +``` + +请记得在命令中注明`fee` 和 `gas`字段。请在以下[文档](/modules/fee-token/feeToken.md) 了解更多。 + +### 查询验证人信息 + +你可以通过以下命令查询验证人的信息: + +``` +iriscli stake validator --address-validator= --chain-id=fuxi-3000 --node=tcp://localhost:26657 +``` + +请注意 `` 字段是以`faa`为首字母。 + + +### 确认验证人是否在线 + +你可以通过以下命令查询验证人节点的运行状况, + +``` +iriscli status --node=tcp://localhost:26657 +``` + +你应该可以看到节点的`power`字段返回值大于0。 + +### 编辑验证人信息 + +你可以通过以下命令修改验证人的描述信息,验证人的名称默认为`--moniker`字段。 +你应该在`details`字段注明自定义的信息。 + +``` +iriscli stake edit-validator --address-validator=account --moniker="choose a moniker" --website="https://irisnet.org" --details="team" --chain-id=fuxi-3000 + --name=key_name --node=tcp://localhost:26657 --fee=40000000000000000iris --gas=2000000 +``` +### 查询验证人信息 + +你可以通过以下命令查询验证人的信息: + +``` +iriscli stake validator --address-validator= --chain-id=fuxi-3000 +``` + +### 使用浏览器:IRISPlorer + +你可以通过[浏览器](https://testnet.irisplorer.io)确认验证人节点的运行状况。 \ No newline at end of file diff --git a/docs/zh/get-started/install-Iris.md b/docs/zh/get-started/install-Iris.md new file mode 100644 index 000000000..05e1d25bc --- /dev/null +++ b/docs/zh/get-started/install-Iris.md @@ -0,0 +1,118 @@ +### 安装IRIShub + +#### 服务器配置要求 + + +首先,你需要配置一台服务器。你的验证人节点应该能够一直运行,使用你可能需要在一台数据中心的服务器。任何像AWS、GCP、DigitalOcean中的云服务器都是适合的。 + +IRIS Hub是用Go语言编写的。它可以在任何能够编译并运行Go语言程序的平台上工作。然而,我强烈建议在Linux服务器上运行验证人节点。我曾经尝试在Windows上运行验证人节点。我能够顺利的编译但是在运行的时候会有一些问题。接下来的说明和指导都是基于Linux服务器的。 +这是我们推荐的服务器的配置: + +* CPU核数:2 +* 内存容量:2GB +* 磁盘空间:40GB +* 操作系统:Ubuntu 18.04 LTS/16.04 LTS +* 允许的入方向的链接:TCP端口 26656 和 26657 + + +#### 方法1:下载发行版安装 + +进入下载页: https://github.com/irisnet/irishub/releases/ +下载对应版本的可执行文件 +解压缩 +``` +tar -C /usr/local/bin -xzf iris$VERSION.$OS-$ARCH.zip +``` +拷贝到/usr/local/bin/目录下 +执行以下命令,若出现对应的版本号则说明安装成功。 + +``` +$ iris version +v0.4.0 + +$ iriscli version +v0.4.0 +``` +#### 方法2:源码编译安装 + +#### 安装Go版本 1.10+ + + +系统要求: + +Ubuntu LTS 16.04 + + +安装IRISHub需要保证Go的版本在1.10以上, + +通过执行以下命令安装1.10版本的Go。 + +``` + $ sudo add-apt-repository ppa:gophers/archive + $ sudo apt-get update + $ sudo apt-get install golang-1.10-go +``` + +以上命令将安装 golang-1.10-go在 /usr/lib/go-1.10/bin. 需要将它加入到PATH中 + +``` + echo "export PATH=$PATH:/usr/lib/go-1.10/bin" >> ~/.bash_profile + source ~/.bash_profile +``` + +同时,你需要指定相关的 $GOPATH, $GOBIN, 和 $PATH 变量, 例如: + +``` + mkdir -p $HOME/go/bin + echo "export GOPATH=$HOME/go" >> ~/.bash_profile + source ~/.bash_profile + echo "export GOBIN=$GOPATH/bin" >> ~/.bash_profile + source ~/.bash_profile + echo "export PATH=$PATH:$GOBIN" >> ~/.bash_profile + source ~/.bash_profile +``` + +参考链接: + +1. https://golang.org/doc/install +2. https://github.com/golang/go/wiki/Ubuntu + + + +#### 下载源码并安装 + + +在完成Go的安装后,通过以下命令下载并安装IRIS hub相关程序. + +``` +mkdir -p $GOPATH/src/github.com/irisnet +cd $GOPATH/src/github.com/irisnet +git clone https://github.com/irisnet/irishub +cd irishub && git checkout v0.4.1 + +curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh + +make get_vendor_deps && make install +``` + +以上命令将完成 iris 和 iriscli的安装. 若出现对应的版本号则说明安装成功。 + +``` +$ iris version +v0.4.1 + +$ iriscli version +v0.4.1 +``` +### 如何升级IRISHub + +通过执行一下命令可以完成IRISHub从v0.3.4到v0.4.1的升级 + +``` +cd $GOPATH/src/github.com/irisnet/irishub +git fetch -a origin +rm Gopkg.lock +git checkout v0.4.1 +make get_vendor_deps +make install +``` \ No newline at end of file diff --git a/docs/zh/get-started/tools/Deploy-IRIS-Monitor.md b/docs/zh/get-started/tools/Deploy-IRIS-Monitor.md new file mode 100644 index 000000000..19918cb12 --- /dev/null +++ b/docs/zh/get-started/tools/Deploy-IRIS-Monitor.md @@ -0,0 +1,46 @@ +# 如何部署monitor + +确保已经安装了iris等工具,系统中需要有/bin/bash、wc、ps等命令。 你可以参考这个页面来安装iris工具:https://github.com/irisnet/irishub + +1. 下载打包好的监控工具。 +``` +wget https://raw.githubusercontent.com/programokey/monitor/master/monitor.tar.gz +``` + +2. 解压监控工具包 + +``` +tar -xzvf monitor.tar.gz +``` + +3. 修改运行参数 + +``` +cd monitor +vim start.sh +``` + +将第三条命令中的 + +-a=378E63271D5BE927443E17CBAAFE68DEFF383DA7 +修改为 +-a=<你的验证人地址的hex编码> +--chain-id=fuxi-test +修改为 +--chain-id=<你要监控的网络的ID> +--node="tcp://localhost:26657" +修改为 +--node=<你要监控的节点监听的rpc端口(默认为26657)> + + +4. 启动监控工具 +``` +./start.sh +``` +接下来就可以访问localhost:3000来查看grafana监控。打开网页后使用默认用户名admin,默认密码admin登录。建议登录之后立即修改密码。 +点击Home按钮,然后在general栏中打开IRIS HUB即可看到监控项。 + +5. 关闭监控 +``` +./stop.sh +``` diff --git a/docs/zh/get-started/tools/Setup-Sentry-Node.md b/docs/zh/get-started/tools/Setup-Sentry-Node.md new file mode 100644 index 000000000..52495dc2f --- /dev/null +++ b/docs/zh/get-started/tools/Setup-Sentry-Node.md @@ -0,0 +1,54 @@ +# 哨兵节点及其搭建 + +为了保证验证人节点的安全性和可用性,我们建议为验证人节点配置2个以上的哨兵节点。使用哨兵节点的好处在于可以有效地防止DoS攻击等其他针对验证人节点的攻击。 + +## 初始化一个全节点 + +为了搭建哨兵节点,首先我们需要初始化一些全节点。执行以下命令创建一个全节点(建议在多台不同的服务器上创建多个哨兵节点以提高可用性和安全性) +``` +iris init --name= --home= +``` +< sentry home>是你指定的哨兵节点的地址。示例: +``` +iris init --name="sentry" --home=sentry --home-client=sentry +{ + "chain_id": "test-chain-hfuDmL", + "node_id": "937efdf8526e3d9e8b5e887fa953ff1645cc096d", + "app_message": { + "secret": "issue envelope dose rail busy glass treat crop royal resemble city deer hungry govern cable angle cousin during mountain december spare stick unveil great" + } +} +``` + + +## 修改哨兵节点的配置 + +然后将验证人节点中的genesis.json文件复制到 < sentry home>/config/目录下。接下来对< sentry home>/config/目录下的config.tmol进行编辑。需要进行如下修改: +``` +private_peers_ids="validator_node_id" +``` + +这里的< validator node id>可以在验证人节点上使用iriscli status命令获得。经过这样设置之后然后使用 + +``` +iris init --home=sentry_home +``` + +启动哨兵节点。对每个哨兵节点都需要进行这些操作。 + +## 修改验证人节点的配置 + +接下来需要对验证人节点的< validator home>/config/目录下的config.tmol进行修改: + +``` +persistent_peers="sentry node id@sentry listen address" +``` + +这里只写sentry节点的node id和地址,多个哨兵节点的信息使用逗号分开。 + +设置`pex=false` 不与其他节点进行peers交换,这样验证人节点就不会连接除persistent_peers之外的节点。 +这里的< sentry node id>可以在哨兵节点上使用iriscli status命令获得。修改完成后需要重启验证人节点使修改生效。 + +``` +iris init --home=validator node home +``` diff --git a/docs/zh/modules/coin/README.md b/docs/zh/modules/coin/README.md new file mode 100644 index 000000000..dc13225f7 --- /dev/null +++ b/docs/zh/modules/coin/README.md @@ -0,0 +1,51 @@ +# Coin_Type + +## 定义 + +coin_type 定义了iris-hub系统中代币的可用单位,只要是系统中已注册的coin_type类型,都可以使用该单位来进行交易。iris-hub中系统默认的代币为iris,iris存在以下几种可用单位:iris-milli,iris-micro,iris-nano,iris-pico,iris-femto,iris-atto。他们之间存在以下换算关系 + +``` +1 iris = 10^3 iris-milli +1 iris = 10^6 iris-micro +1 iris = 10^9 iris-nano +1 iris = 10^12 iris-pico +1 iris = 10^15 iris-femto +1 iris = 10^18 iris-atto +``` + +## coin_type的数据模型 + +```golang +type CoinType struct { + Name string `json:"name"` + MinUnit Unit `json:"min_unit"` + Units Units `json:"units"` + Origin Origin `json:"origin"` + Desc string `json:"desc"` +} +``` + +* Name : 代币名称,也是coin的主单位,例如iris +* MinUnit: coin_type的最小单位,系统中存在的代币都是以最小单位的形式存在,例如iris代币,在iris-hub中存储的单位是iris-atto。当用户发送交易到iris-hub中,使用的必须是该代币的最小单位。但是如果你使用的是iris-hub提供的命令行工具,你可以使用任何系统识别的单位,系统将自动转化为该代币对应的最小单位形式。比如如果你使用send命令转移1iris,命令行将在后端处理为10^18 iris-atto,使用交易hash查询到的交易详情,你也只会看到10^18 iris-atto。 + +## Unit结构定义 + +```golang +type Unit struct { + Denom string `json:"denom"` + Decimal int `json:"decimal"` +} +``` + +其中Denom定义为该单位的名称,Decimal定义为该单位支持的最大精度,例如iris-atto支持的最大精度为18 +* Units:定义了coin_type下可用的一组单位 +* Origin:定义了该coin_type的来源,取值:Native(系统内部,iris),External(系统外部,例如eth等),UserIssued(用户自定义) +* Desc:对该代币coin_type的描述 + +## 查询代币coin_type + +如果想查询某种代币的coin_type配置,可以使用如下命令 + +```golang +iriscli coin types [coin_name] +``` \ No newline at end of file diff --git a/docs/modules/gov/gov_test.md b/docs/zh/modules/gov/README.md similarity index 98% rename from docs/modules/gov/gov_test.md rename to docs/zh/modules/gov/README.md index d71afb72d..b84170062 100644 --- a/docs/modules/gov/gov_test.md +++ b/docs/zh/modules/gov/README.md @@ -1,6 +1,6 @@ -# Governance Module Test Flow +# Governance -#####1:初始化区块链运行环境 +## 初始化区块链运行环境 ``` rm -rf .iris @@ -11,7 +11,7 @@ iris start ``` -#####2:提议流程 +## 提议流程 这里以"参数修改提议"为例,其他提议不需要--params参数。比如,当某一个时间点我们发现,系统产生了很多无用的提议,原因可能是当前最小抵押金额太小了,造成很多人都可以提交一个无意义的提议。 这个时候我们可以使用"参数修改提议"来修改系统预设的最小抵押金额这个参数。我们首先需要知道该参数对应的key值,才能修改。可以使用以下命令查看: diff --git a/docs/zh/validators/How-to-participate-in-onchain-governance.md b/docs/zh/validators/How-to-participate-in-onchain-governance.md new file mode 100644 index 000000000..ec822457e --- /dev/null +++ b/docs/zh/validators/How-to-participate-in-onchain-governance.md @@ -0,0 +1,68 @@ +# IRISHub重的链上治理过程 + +## 什么是链上治理? + +链上治理是让验证人对区块链网络的运行达成共识的一种投票机制。 + +### 线上治理提案的类型 + +* Text +* System Parameter Change +* Protocol Upgrade [未实现] + +## 线上治理流程 + +链上治理投票分为以下三步骤: + + +* Mininimum Depost: `1000IRIS` or `1000000000000000000000iris` +* Deposit Period: 1440 blocks +* Penalty for non-voting validtors: 1% +* Pass Threshold: 50% +* Voting Period: 20000 blocks + +## 如何提交一个提案? + +任何人都可以提交链上治理提案,但你需要为此提案存入超过最低要求的押金。 + +如下的命令将执行提交一个 `Text`类型的提案: + +``` +iriscli gov submit-proposal --title="Text" --description="name of the proposal" --type="Text" --deposit="1000000000000000000000iris" --proposer= --from= --chain-id=fuxi-3000 --fee=400000000000000iris --gas=20000 --node=http://localhost:36657 +``` + +The `` for `proposer` field should start with `faa` which corresponds to ``. + + +## 如何增加投票的抵押金额? + +To add deposit to some proposal, you could execute this command to add `10IRIS` to the proposal's deposit: + +``` +iriscli gov deposit --proposalID=1 --depositer= --deposit=1000000000000000000iris --from= --chain-id=fuxi-3000 --fee=400000000000000iris --gas=20000 --node=http://localhost:36657 +``` + +##如何投票? + +In the current version of governance module, you have the following choices for each proposal: +* Yes +* No +* NoWithVeto +* Abstien + +You could put one of the choices in the `--option` field. + +To vote for a proposal, you need to get the correct ``.You could execute the following command to vote on proposal with ID = 1: +``` +iriscli vote --from=jerry --voter= --proposalID=1 --option=Yes --chain-id=fuxi-3000 --fee=2000000000000000iris --gas=20000 --node=http://localhost:36657 +``` + +## 如何查询投票信息? + +例如,查询第一个提案的信息: + +``` +iriscli gov query-proposal --proposalID=1 --chain-id=fuxi-3000 --node=http://localhost:26657 + +`````` +也可以在浏览器上查询。 From e92991291497ac602e629e97c272e93020f0b8f3 Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Mon, 17 Sep 2018 17:16:19 +0800 Subject: [PATCH 081/124] IRISHUB-420 hotfix docs --- docs/.vuepress/config.js | 9 +++++---- docs/validators/{overview.md => README.md} | 0 .../{Setup A Sentry Node.md => Setup-A-Sentry-Node.md} | 0 3 files changed, 5 insertions(+), 4 deletions(-) rename docs/validators/{overview.md => README.md} (100%) rename docs/validators/{Setup A Sentry Node.md => Setup-A-Sentry-Node.md} (100%) diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 375eff556..8d9fe37c7 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -27,16 +27,17 @@ module.exports = { title: 'Modules', collapsable: false, children: [ - ['/modules/coin/README.md', 'Coin Type'], + // ['/modules/coin/README.md', 'Coin Type'], ['/modules/fee-token/README.md', 'Fee Token'], - ['/modules/gov/README.md', 'Governance'] + // ['/modules/gov/README.md', 'Governance'] ] },{ title: 'Validators', collapsable: false, children: [ - ['/validators/overview.md', 'Overview'], - ['/validators/Setup A Sentry Node.md', 'Setup a Sentry Node'] + ['/validators/README.md', 'Overview'], + ['/validators/Setup-A-Sentry-Node.md', 'Setup a Sentry Node'], + ['/validators/FAQ.md', 'FAQ'] ] } ] diff --git a/docs/validators/overview.md b/docs/validators/README.md similarity index 100% rename from docs/validators/overview.md rename to docs/validators/README.md diff --git a/docs/validators/Setup A Sentry Node.md b/docs/validators/Setup-A-Sentry-Node.md similarity index 100% rename from docs/validators/Setup A Sentry Node.md rename to docs/validators/Setup-A-Sentry-Node.md From 7606d4ff3c4a7efa72d5416b78d42f5b663c1a3f Mon Sep 17 00:00:00 2001 From: kidinamoto01 Date: Mon, 17 Sep 2018 17:34:18 +0800 Subject: [PATCH 082/124] IRISHUB-423:Edit README --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 16d7a2d7b..e64aee329 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # IRISHub -![banner](./docs/pics/iris.jpg) +![banner](https://github.com/irisnet/irishub/blob/master/docs/pics/iris.jpg) IRIS network (a.k.a. IRISnet) aims to establish a technology foundation to facilitate construction of next-generation distributed applications. By incorpo- rating a comprehensive service infrastructure and an enhanced IBC protocol into the Tendermint & Cosmos stack, IRISnet enables service interoperability as well as token transfers across an internet of blockchains. @@ -9,7 +9,7 @@ As the centerpiece of IRISnet, IRIS Hub (a.k.a. IRIShub) will be the first regio ## Fuxi Testnet To join the Fuxi testnet, follow -[this guide](https://github.com/irisnet/irishub/blob/feature/docs/docs/get-started/README.md). +[this guide](https://github.com/irisnet/irishub/blob/master/docs/get-started/README.md). For status updates and genesis files, see the [testnets repo](https://github.com/irisnet/testnets). @@ -17,12 +17,12 @@ For status updates and genesis files, see the ## Install See the -[install instructions](https://github.com/irisnet/irishub/blob/feature/docs/docs/get-started/install-iris.md). +[install instructions](https://github.com/irisnet/irishub/blob/master/docs/get-started/Install-Iris.md). ## Resources -* Explorer:http://testnet.irisplorer.io -* Faucet:http://testnet.irisplorer.io/#/faucet +* Explorer:https://testnet.irisplorer.io +* Faucet:https://testnet.irisplorer.io/#/faucet From 9a4f622a76ffc903d25a3b084a7a1d52bbf95528 Mon Sep 17 00:00:00 2001 From: kidinamoto01 Date: Mon, 17 Sep 2018 17:36:02 +0800 Subject: [PATCH 083/124] IRISHUB-423:Edit README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e64aee329..6de93f6bf 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # IRISHub -![banner](https://github.com/irisnet/irishub/blob/master/docs/pics/iris.jpg) +![banner](./docs/pics/iris.jpg) IRIS network (a.k.a. IRISnet) aims to establish a technology foundation to facilitate construction of next-generation distributed applications. By incorpo- rating a comprehensive service infrastructure and an enhanced IBC protocol into the Tendermint & Cosmos stack, IRISnet enables service interoperability as well as token transfers across an internet of blockchains. From fd67a1288e5ac6d2d0d6896920bc8134ea208e38 Mon Sep 17 00:00:00 2001 From: kidinamoto01 Date: Mon, 17 Sep 2018 17:43:31 +0800 Subject: [PATCH 084/124] IRISHUB-423:Edit README --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6de93f6bf..8fec5a5de 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ As the centerpiece of IRISnet, IRIS Hub (a.k.a. IRIShub) will be the first regio ## Fuxi Testnet To join the Fuxi testnet, follow -[this guide](https://github.com/irisnet/irishub/blob/master/docs/get-started/README.md). +[this guide](./docs/get-started/README.md). For status updates and genesis files, see the [testnets repo](https://github.com/irisnet/testnets). @@ -17,7 +17,7 @@ For status updates and genesis files, see the ## Install See the -[install instructions](https://github.com/irisnet/irishub/blob/master/docs/get-started/Install-Iris.md). +[install instructions](./docs/get-started/Install-Iris.md). ## Resources From 082a45e67339d1091711809ace7ee765aa0ceba2 Mon Sep 17 00:00:00 2001 From: kidinamoto01 Date: Mon, 17 Sep 2018 17:44:34 +0800 Subject: [PATCH 085/124] IRISHUB-423:Edit README --- docs/get-started/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/get-started/README.md b/docs/get-started/README.md index 366db482b..30bdb1b2c 100644 --- a/docs/get-started/README.md +++ b/docs/get-started/README.md @@ -1,4 +1,4 @@ -# IRISnet Testnet,Codename Fuxi +# IRISnet Testnet Codename Fuxi ## What is IRISnet From f540779e4d2ea9a4756542c07bef2fa72f783cf0 Mon Sep 17 00:00:00 2001 From: kidinamoto01 Date: Mon, 17 Sep 2018 17:51:53 +0800 Subject: [PATCH 086/124] IRISHUB-423:Edit README --- docs/get-started/Genesis-Generation-Process.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/get-started/Genesis-Generation-Process.md b/docs/get-started/Genesis-Generation-Process.md index 0008d1896..84c957293 100644 --- a/docs/get-started/Genesis-Generation-Process.md +++ b/docs/get-started/Genesis-Generation-Process.md @@ -41,7 +41,7 @@ You could see the following output: ``` The `app_message` contains the seed phrase to recover the account of `address` field you just created. -There will be a gentx-node-ID.json a file. +There will be a gentx-node-ID.json a file at `$IRISHOME/config/gentx/`. The content of the file will be: From a74448d0bce4bbbe818bf6e14f4b9a94ed403d88 Mon Sep 17 00:00:00 2001 From: kidinamoto01 Date: Mon, 17 Sep 2018 18:17:20 +0800 Subject: [PATCH 087/124] IRISHUB-423:Edit README --- docs/zh/get-started/install-Iris.md | 4 +-- .../zh/get-started/tools/Bech32-on-IRISnet.md | 36 +++++++++++++++++++ docs/zh/modules/fee-token/Fee.md | 29 +++++++++++++++ 3 files changed, 67 insertions(+), 2 deletions(-) create mode 100644 docs/zh/get-started/tools/Bech32-on-IRISnet.md create mode 100644 docs/zh/modules/fee-token/Fee.md diff --git a/docs/zh/get-started/install-Iris.md b/docs/zh/get-started/install-Iris.md index 05e1d25bc..06bf23a52 100644 --- a/docs/zh/get-started/install-Iris.md +++ b/docs/zh/get-started/install-Iris.md @@ -28,10 +28,10 @@ tar -C /usr/local/bin -xzf iris$VERSION.$OS-$ARCH.zip ``` $ iris version -v0.4.0 +v0.4.1 $ iriscli version -v0.4.0 +v0.4.1 ``` #### 方法2:源码编译安装 diff --git a/docs/zh/get-started/tools/Bech32-on-IRISnet.md b/docs/zh/get-started/tools/Bech32-on-IRISnet.md new file mode 100644 index 000000000..a62927bb4 --- /dev/null +++ b/docs/zh/get-started/tools/Bech32-on-IRISnet.md @@ -0,0 +1,36 @@ +# Bech32 on IRISnet + +Bech32 is a new Bitcoin address format proposed by Pieter Wuille and Greg Maxwell. Besides Bitcoin addresses, Bech32 can encode any short binary data. In the IRIS network, keys and addresses may refer to a number of different roles in the network like accounts, validators etc. The IRIS network is designed to use the Bech32 address format to provide robust integrity checks on data. The human readable part(HRP) makes it more efficient to read and the users could see error messages. + + +## Human Readable Part Table + + +| HRP | Definition | +| ------------- |:-------------:| +|faa |IRISnet Account Address| +|fap| IRISnet Account Public Key| +|fva |IRISnet Consensus Address| +|fvp| IRISnet Consensus Public Key| + +## Separator + +Why include a separator in addresses? That way the human-readable part is unambiguously separated from the data part, avoiding potential collisions with other human-readable parts that share a prefix. It also allows us to avoid having character-set restrictions on the human-readable part. The separator is 1 because using a non-alphanumeric character would complicate copy-pasting of addresses (with no double-click selection in several applications). Therefore an alphanumeric character outside the normal character set was chosen. + +## Encoding + +Not all interfaces to users IRISnet should be exposed as bech32 interfaces. Many address are still in hex or base64 encoded form. + +To covert between other binary reprsentation of addresses and keys, it is important to first apply the Amino enocoding process before bech32 encoding. + + +## Example + +Once you create a new address, you should see the following: + +` +NAME: TYPE: ADDRESS: PUBKEY: +test1 local faa18ekc4dswwrh2a6lfyev4tr25h5y76jkpqsz7kl fap1addwnpepqgxa40ww28uy9q46gg48g6ulqdzwupyjcwfumgfjpvz7krmg5mrnw6zv8uv +` + +This means you have created a new address `faa18ekc4dswwrh2a6lfyev4tr25h5y76jkpqsz7kl`, its hrp is `faa`. And its public key could be encoded into `fap1addwnpepqgxa40ww28uy9q46gg48g6ulqdzwupyjcwfumgfjpvz7krmg5mrnw6zv8uv`, its hrp is `fap`. \ No newline at end of file diff --git a/docs/zh/modules/fee-token/Fee.md b/docs/zh/modules/fee-token/Fee.md new file mode 100644 index 000000000..ee3107434 --- /dev/null +++ b/docs/zh/modules/fee-token/Fee.md @@ -0,0 +1,29 @@ +# 简介 + +手续费上限使用 --fee指定。gas是衡量交易需要消耗多少资源的单位。gas上限用--gas指定。gas上限太小时,不够交易需要的gas;手续费太低时,每一单位gas支付的手续费太低,验证人节点也不会执行这笔交易。手续费(最小单位)/gas应该大于等于2*10^10。推荐将gas上限设置为20000,手续费上限设置为400000000000000iris。需要多少gas就会花多少手续费,剩余的手续费会被退还。 + +## Fee + +IRIS网络中的验证人为了维护自己节点的安全性和网络的正常运行,付出了不小的成本。因此,在IRIS网络中的各种交易都需要支付一定的手续费。各种交易中的--fee选项就是用来指定交易中支付的手续费的上限的参数。 + +## Gas + +验证人节点处理不同的交易时需要的资源也不同,例如转账交易只需要进行的计算、查询和修改,而创建验证人需要进行的计算、查询和修改较多。Gas是用来衡量每个交易需要的资源多少的,下面给出部分操作需要的gas数量: + +- 进行一次从数据库中读取数据的操作需要的gas数量为:10 + 读取数据长度(以bytes为单位) +- 进行一次往数据库中写入数据的操作需要的gas数量为:10 + 10*写入数据长度(以bytes为单位) +- 进行一次签名验证:100 +- .... + +一笔交易中各种操作需要的gas加起来就是这个交易需要的总共的gas。用户可以使用--gas参数给自己发起的交易设置这笔交易的gas上限,如果一笔交易使用的gas超过了用户设定的gas上限则交易就无法成功执行,用户的手续费不会被扣除。如果一笔交易使用的gas未超过用户设定的gas上限,则交易可能被成功的执行(还需要检查交易是否符合要求)。当交易被成功执行的时候,用户支付的手续费为: 手续费上限 * 实际消耗的gas/gas上限。 + +gas价格 = 手续费上限 / gas上限,代表用户为每个单位的资源消耗支付的手续费价格。 + +为了使用户支付的手续费维持在一个合理的水平,我们给gas价格设定了一个下限,2^(-8) iris/gas,gas价格低于此限制的交易不会被执行。 + +例子 +``` + iriscli stake unbond complete --from=test --address-validator=faa1mahw6ymzvt2q3lu4pjj5pau2e8krntklgarrxy --address-delegator=faa1mahw6ymzvt2q3lu4pjj5pau2e8krntklgarrxy --fee=2000000000000000iris --gas=20000 --chain-id=test +``` + +在这个例子中执行的是完成解绑操作,这里设定的手续费上限(--fee)为2000000000000000iris(2*10^15),gas上限(--gas)为20000,gas价格就是10^11iris/gas。假设执行交易总共需要1500个gas,那么会有1500000000000000iris的手续费被支付给验证人节点;剩余的500000000000000iris会被退还给用户。 From 4cd98993a03c97880b03e6048d1b7038a17690d6 Mon Sep 17 00:00:00 2001 From: kidinamoto01 Date: Mon, 17 Sep 2018 18:18:22 +0800 Subject: [PATCH 088/124] IRISHUB-423:Edit README --- docs/zh/get-started/Validator-Node.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/zh/get-started/Validator-Node.md b/docs/zh/get-started/Validator-Node.md index 138f2fcdf..f89905d06 100644 --- a/docs/zh/get-started/Validator-Node.md +++ b/docs/zh/get-started/Validator-Node.md @@ -1,6 +1,6 @@ # 运行一个验证人节点 -在配置验证人节点之前,请保证已经按照此[文档](安装IRISHub.md)正确安装了**Iris** +在配置验证人节点之前,请保证已经按照此[文档](install-Iris.md)正确安装了**Iris** 在IRISHub枢纽中,验证人负责将交易打包并提交区块。成为一个验证人需要满足很多条件,不仅仅是技术和硬件上的投资。同时,因为只有在有限验证人的条件下,Tendermint才能发挥最大的作用。目前,我们将IRISHub枢纽的验证人上限定为100。也就是说只有前100个验证人能够获得奖励,而大部分IRIS持有者不会成为验证人而是通过委托的方式决定谁会成为验证人。 @@ -56,7 +56,7 @@ iriscli status --node=tcp://localhost:26657 ``` 若 `catching_up` 字段为 `false`那么你的节点就是同步的。 -你需要获取当前节点的公钥信息来执行以下操作,公钥信息以 `fvp`为首字节,想要了解更多的编码信息,请参考以下 [文档](../get-started/tools/Bech32%20on%20IRISnet.md) +你需要获取当前节点的公钥信息来执行以下操作,公钥信息以 `fvp`为首字节,想要了解更多的编码信息,请参考以下 [文档](../get-started/tools/Bech32-on-IRISnet.md) 通过执行以下命令获得节点的公钥信息: @@ -82,7 +82,7 @@ iriscli stake create-validator --amount=iris --pubkey= --address iriscli stake create-validator --pubkey=pubkey --address-validator=account --fee=40000000000000000iris --gas=2000000 --from= --chain-id=fuxi-3000 --node=tcp://localhost:26657 --amount=1000000000000000000iris ``` -请记得在命令中注明`fee` 和 `gas`字段。请在以下[文档](/modules/fee-token/feeToken.md) 了解更多。 +请记得在命令中注明`fee` 和 `gas`字段。请在以下[文档](../modules/fee-token/Fee.md) 了解更多。 ### 查询验证人信息 From 85c4853bfeb35d887fed2f895b9cee56db4d0fd7 Mon Sep 17 00:00:00 2001 From: Yelong Zhang Date: Mon, 17 Sep 2018 18:51:35 +0800 Subject: [PATCH 089/124] Typo fix --- docs/zh/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/zh/README.md b/docs/zh/README.md index 29b46317a..0d04c7b6c 100644 --- a/docs/zh/README.md +++ b/docs/zh/README.md @@ -1,5 +1,5 @@ # IRISnet文档目录 ![irisnet](../pics/iris.jpg) -IRIS网络是上海边界智能和Tendermint团队合作打造的跨链区块链网络,将是Cos- mos网络生态中的第一个区域性枢纽(Hub),并专注于为分布式商业应用提供基础 设施和协议。 +IRIS网络是上海边界智能和Tendermint团队合作打造的跨链区块链网络,将是Cosmos网络生态中的第一个区域性枢纽(Hub),并专注于为分布式商业应用提供基础 设施和协议。 IRISnet将面向服务的基础设施融入到Cosmos网络中,支持对包括公链、联盟链以及 现有传统商业系统的集成从而实现互联互通。通过对Cosmos网络的跨链协议进行创新 扩展,IRISnet允许数据及复杂计算跨异构网络被调用。就像忠实地在人间和天堂传递 信息的希腊彩虹女神 Iris, IRISnet的目标是成为链接数字经济和实体经济,支持构建复 杂分布式商业应用的下一代公链。 From 1dc1c10e40826b5161fcb2ba403688590de62597 Mon Sep 17 00:00:00 2001 From: kidinamoto01 Date: Tue, 18 Sep 2018 10:35:28 +0800 Subject: [PATCH 090/124] IRISTNET-126:add iris-atto --- docs/get-started/Validator-Node.md | 6 +++--- docs/zh/get-started/Validator-Node.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/get-started/Validator-Node.md b/docs/get-started/Validator-Node.md index c2eef030d..a839459f8 100644 --- a/docs/get-started/Validator-Node.md +++ b/docs/get-started/Validator-Node.md @@ -74,16 +74,16 @@ Next, use the output as `` field for `iriscli stake create-validator` c ``` iriscli stake create-validator --amount=iris --pubkey= --address-validator= --moniker= --chain-id=game-of-genesis --name= --node=http://localhost:26657 ``` -Please note the **amount** needs to be the **minimium unit** of IRIS. +Please note the **amount** needs to be the **minimium unit** of IRIS token: `iris-atto`. -1 IRIS=10^18iris +1 IRIS=10^18 iris-atto In this way, to stake 1IRIS, you need to do: ``` iriscli stake create-validator --pubkey=pubkey --address-validator=account --fee=40000000000000000iris --gas=2000000 --from= --chain-id=fuxi-3000 --node=tcp://localhost:26657 --amount=1000000000000000000iris ``` -Don't forget the `fee` and `gas` field. To read more about fees in IRISHub, you should read [this](/modules/fee-token/feeToken.md) +Don't forget the `fee` and `gas` field. In this version of IRIHub, all the `unit` for `amount` and `field` correspond to `iris-atto`. To read more about coin-type in IRISHub, you should read [this](../zh/modules/coin/README.md) ### View Validator Info diff --git a/docs/zh/get-started/Validator-Node.md b/docs/zh/get-started/Validator-Node.md index f89905d06..ac76345e4 100644 --- a/docs/zh/get-started/Validator-Node.md +++ b/docs/zh/get-started/Validator-Node.md @@ -72,9 +72,9 @@ fvp1zcjduepqv7z2kgussh7ufe8e0prupwcm7l9jcn2fp90yeupaszmqjk73rjxq8yzw85 ``` iriscli stake create-validator --amount=iris --pubkey= --address-validator= --moniker= --chain-id=game-of-genesis --name= --node=http://localhost:26657 ``` -> 注意:**amount**字段需要使用最小单位iris。准化比例为: +> 注意:**amount** 和 **Fee** 字段需要使用最小单位 `iris-atto` 。准化比例为: -1 IRIS=10^18iris +1 IRIS=10^18 iris-atto 也就是说,如果你想要抵押1IRIS,你可以执行以下操作: @@ -82,7 +82,7 @@ iriscli stake create-validator --amount=iris --pubkey= --address iriscli stake create-validator --pubkey=pubkey --address-validator=account --fee=40000000000000000iris --gas=2000000 --from= --chain-id=fuxi-3000 --node=tcp://localhost:26657 --amount=1000000000000000000iris ``` -请记得在命令中注明`fee` 和 `gas`字段。请在以下[文档](../modules/fee-token/Fee.md) 了解更多。 +请记得在命令中注明`fee` 和 `gas`字段。请在以下[文档](../modules/coin/README.md) 了解更多有关代币单位的内容。 ### 查询验证人信息 From 7af6637d765006197126fdeb0304c111366ac6e0 Mon Sep 17 00:00:00 2001 From: Raymond Date: Tue, 18 Sep 2018 09:33:44 +0800 Subject: [PATCH 091/124] IRISHUB-406: fix misspellings --- docs/introduction/Whitepaper_CN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/introduction/Whitepaper_CN.md b/docs/introduction/Whitepaper_CN.md index cfb8d494d..ab918696e 100644 --- a/docs/introduction/Whitepaper_CN.md +++ b/docs/introduction/Whitepaper_CN.md @@ -167,7 +167,7 @@ IRIS Services(又名“iServices”)旨在对链下服务从定义、绑定 * `Name (string)`: iService中该方法的唯一名称 * `Description (string)`: 对该方法的描述 * `Input (string)`: 对输入参数的结构化定义 -* `Output (string)`: 对输出结果的机构化定义 +* `Output (string)`: 对输出结果的结构化定义 * `Error (string)`: 对可能出现的错误条件的结构化定义 * `OutputPrivacy (enum)`: 设置此方法是非隐私的还是公钥加密的,可选值`NoPrivacy`/`PubKeyEncryption` From d1cb15d3a872f87a642a491bd01aaa8459faa252 Mon Sep 17 00:00:00 2001 From: kidinamoto01 Date: Tue, 18 Sep 2018 11:57:39 +0800 Subject: [PATCH 092/124] IRISTNET-126:add iris-atto --- docs/get-started/Validator-Node.md | 2 +- docs/zh/get-started/Validator-Node.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/get-started/Validator-Node.md b/docs/get-started/Validator-Node.md index a839459f8..f54dce382 100644 --- a/docs/get-started/Validator-Node.md +++ b/docs/get-started/Validator-Node.md @@ -83,7 +83,7 @@ In this way, to stake 1IRIS, you need to do: ``` iriscli stake create-validator --pubkey=pubkey --address-validator=account --fee=40000000000000000iris --gas=2000000 --from= --chain-id=fuxi-3000 --node=tcp://localhost:26657 --amount=1000000000000000000iris ``` -Don't forget the `fee` and `gas` field. In this version of IRIHub, all the `unit` for `amount` and `field` correspond to `iris-atto`. To read more about coin-type in IRISHub, you should read [this](../zh/modules/coin/README.md) +Don't forget the `fee` and `gas` field. In this version of IRIHub, all the `unit` for `amount` and `field` correspond to `iris-atto`,but it's shown as `iris`. To read more about coin-type in IRISHub, you should read [this](../zh/modules/coin/README.md) ### View Validator Info diff --git a/docs/zh/get-started/Validator-Node.md b/docs/zh/get-started/Validator-Node.md index ac76345e4..05877557c 100644 --- a/docs/zh/get-started/Validator-Node.md +++ b/docs/zh/get-started/Validator-Node.md @@ -82,7 +82,7 @@ iriscli stake create-validator --amount=iris --pubkey= --address iriscli stake create-validator --pubkey=pubkey --address-validator=account --fee=40000000000000000iris --gas=2000000 --from= --chain-id=fuxi-3000 --node=tcp://localhost:26657 --amount=1000000000000000000iris ``` -请记得在命令中注明`fee` 和 `gas`字段。请在以下[文档](../modules/coin/README.md) 了解更多有关代币单位的内容。 +请记得在命令中注明`fee` 和 `gas`字段。`fee`和`amount`的单位为`iris-atto`,但是在命令中为了方便写成`iris`。请在以下[文档](../modules/coin/README.md) 了解更多有关代币单位的内容。 ### 查询验证人信息 From d283dec76282297c4040529be16461ea168d999f Mon Sep 17 00:00:00 2001 From: Yelong Zhang Date: Tue, 18 Sep 2018 18:49:25 +0800 Subject: [PATCH 093/124] fix link --- docs/get-started/Genesis-Generation-Process.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/get-started/Genesis-Generation-Process.md b/docs/get-started/Genesis-Generation-Process.md index 84c957293..080c76ba7 100644 --- a/docs/get-started/Genesis-Generation-Process.md +++ b/docs/get-started/Genesis-Generation-Process.md @@ -69,7 +69,7 @@ validator is generated by \$IRISHOME/config/priv_validator.json Submit your gentx-node-ID.json to `https://github.com/irisnet/testnets/tree/master/testnets/fuxi-3000/config/gentx` by createing a pull request. -After the team has collected all the gen-tx transactions, we will publish the genesis file in the following folder: `https://github.com/irisnet/testnets/tree/master/testnets/fuxi-3000/config/` +After the team has collected all the gen-tx transactions, we will publish the genesis file in the following folder: `https://github.com/irisnet/testnets/tree/master/fuxi/fuxi-3000/config/gen-tx/` You could then download the final genesis file and start a node. From 94415cdc0fb7a9178858802d6cb0d016d10f1a8c Mon Sep 17 00:00:00 2001 From: shirleypyj <43328538+shirleypyj@users.noreply.github.com> Date: Thu, 20 Sep 2018 11:36:30 +0800 Subject: [PATCH 094/124] Create README.md --- docs/modules/coin/README.md | 51 +++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 docs/modules/coin/README.md diff --git a/docs/modules/coin/README.md b/docs/modules/coin/README.md new file mode 100644 index 000000000..263383c51 --- /dev/null +++ b/docs/modules/coin/README.md @@ -0,0 +1,51 @@ +# Coin_Type + +## Definition + +Coin_type defines the available units of tokens in the iris-hub system. All the registered coin_type in the system can be used to transfer. The system default token in iris-hub is iris, which has following available units: iris-milli, iris-micro, iris-nano, iris-pico, iris-femto and iris-atto. The conversion relationship between them are as follows: + +``` +1 iris = 10^3 iris-milli +1 iris = 10^6 iris-micro +1 iris = 10^9 iris-nano +1 iris = 10^12 iris-pico +1 iris = 10^15 iris-femto +1 iris = 10^18 iris-atto +``` + +## Data model of coin_type + +```golang +type CoinType struct { + Name string `json:"name"` + MinUnit Unit `json:"min_unit"` + Units Units `json:"units"` + Origin Origin `json:"origin"` + Desc string `json:"desc"` +} +``` + +* Name : The name of tokens, which is also the main unit of coin;for instance, iris. +* MinUnit:The minimum unit of coin_type. The tokens present in the system are all in the form of minimum unit, such as iris. The unit stored in iris-hub is iris-atto. You must use the minimum unit of the tokens when sending a transaction to the iris-hub. But if you use the command line tool provided by iris-hub, you can use any system-recognized unit and the system will automatically convert to the minimum unit of corresponding token. For example, if you use the "send" command to transfer 1iris, the command line will be processed as 10^18 iris-attos in the backend, and you will only see 10^18 iris-attos when enquiring the transaction details by the transaction hash. + +## Structure definition of Unit + +```golang +type Unit struct { + Denom string `json:"denom"` + Decimal int `json:"decimal"` +} +``` + +Denom is defined as the name of the unit, and Decimal is defined as the maximum precision of the unit. For example, the maximum precision of iris-atto is 18. +* Units dfines a set of units available under coin_type. +* Origin defines the source of the coin_type, with the value Native (inner system, iris), External (external system, such as eth, etc.), and UserIssued (user-defined). +* Desc:Description of the coin_type. + +## Inquery of coin_type + +If you want to query the coin_type configuration of a certain token, you can use the following command: + +```golang +iriscli coin types [coin_name] +``` From 9b2018c975454bfc96a4299648470ca69958977a Mon Sep 17 00:00:00 2001 From: shirleypyj <43328538+shirleypyj@users.noreply.github.com> Date: Thu, 20 Sep 2018 11:38:18 +0800 Subject: [PATCH 095/124] Create README.md --- docs/modules/gov/README.md | 99 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 docs/modules/gov/README.md diff --git a/docs/modules/gov/README.md b/docs/modules/gov/README.md new file mode 100644 index 000000000..da3e46ddf --- /dev/null +++ b/docs/modules/gov/README.md @@ -0,0 +1,99 @@ +# Governance + +## Initialize the runtime environment of blockchain + +``` +rm -rf .iris +rm -rf .iriscli +iris init gen-tx --name=iris +iris init --gen-txs --chain-id=gov-test +iris start + +``` + +## Proposal process + +Here is an example of "parameter modification proposal". Other proposals do not need parameter "--params". For instance, sometimes we find there are a lot of useless proposals in the system, probably because the current minimum delegating amount is too small, so that many people submit meaningless ones. Here we can use "parameter modification proposal" to modify the system default minimum parameter of “delegating amount”. Firstly we need to know the value of key of this parameter before modification. The following command can be used to view: +``` +iriscli params export gov +``` +This command will export all the parameters that can be modified with the "parameter modification proposal". For instance, we get the following results: + +``` +[ + { + "key": "gov/depositprocedure/deposit", + "value": "10000000000000000000iris" + }, + { + "key": "gov/depositprocedure/maxDepositPeriod", + "value": "10" + }, + { + "key": "gov/feeToken/gasPriceThreshold", + "value": "20000000000" + }, + { + "key": "gov/tallyingprocedure/penalty", + "value": "1/100" + }, + { + "key": "gov/tallyingprocedure/threshold", + "value": "1/2" + }, + { + "key": "gov/tallyingprocedure/veto", + "value": "1/3" + }, + { + "key": "gov/votingprocedure/votingPeriod", + "value": "20" + } +] + +``` +Each (key, value) is corresponding to a set of system-preset modifiable parameters, the specific meaning of which will be updated in future documents. The key of minimum delegating amount here is gov/depositprocedure/deposit. At present, value=10000000000000000000iris(This is the value after the decimal-binary conversion, refering to the “fee-token” module for details.). To raise the threshold of proposals, it will be doubled to 20000000000000000000iris. The following command can be used: + +``` +iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" + --deposit="9000000000000000000iris" + --params='[{"key":"gov/depositprocedure/deposit","value":"20000000000000000001iris","op":"update"}]' + --proposer=faa1pkunlumfyglqd9dgup0mwp66kjrp6y09twmuvd + --from=iris + --chain-id=gov-test + --fee=400000000000000iris + --gas=20000 + +``` + +Here I delegate 9000000000000000000iris, which is 1000000000000000000iris less than the minimum delegating amount, so the proposal has not been activated can not be voted. 10000000000000000000 more iris should be delegated in 10 (key:gov/depositprocedure/maxDepositPeriod) blocks (If it needs 5s to produce a block, it means you need to complete the delegation in 5 * 10s). The delegating command is as follows: + +``` +iriscli gov deposit --proposalID=1 + --depositer=faa1pkunlumfyglqd9dgup0mwp66kjrp6y09twmuvd + --deposit=1000000000000000000iris + --from=iris + --chain-id=gov-test + --fee=200000000000000iris + --gas=20000 + +``` +The above proposalID is the result from the first step. At this stage, we delegate 1000000000000000000iris tokens, which is exactly equal to the minimum delegating amount, so the proposal can be voted. And the proposer can send a voting request to each validators (currently only off-chain notification is available, but on-chain or monitoring notification will be implemented later). Then each validators can view the proposal first with the following command: +``` +iriscli gov query-proposal --proposalID=1 +``` +Later proposers can vote as they wish, here I vote Yes (option=Yes): +``` +iriscli gov vote --proposalID=1 + --voter=faa1pkunlumfyglqd9dgup0mwp66kjrp6y09twmuvd + --option=Yes + --from=iris + --chain-id=gov-test + --fee=400000000000000iris + --gas=20000 +``` +Notice that the maximum of waiting time is in 20 blocks during the voting period (key: gov/votingprocedure/votingPeriod). If the percentage of affirmative vote is still less than 50% during this period (key: gov/tallyingprocedure/threshold), the proposal will not be passed and the tokens delegated will also not be refunded (the validators haven't voted will be slashed, and 1/100 of the total tokens delegated currently will be deducted (key: gov/tallyingprocedure/penalty). This mechanism has not been implemented in current version ). Suppose there is only one validator. If I voted yes, the ratio of affirmative vote is 1>1/2 and the strong negative vote is 0<1/3 (key:gov/tallyingprocedure/veto), the proposal will be passed. After voting, the proposal is automatically executed: (key: gov/depositprocedure/deposit, value: 10000000000000000000iris) is modified to (key: gov/depositprocedure/deposit, value: 20000000000000000000iris). Then we can verify this result and query the minimum delegating amount in current system: +``` +iriscli iriscli params export gov/depositprocedure/deposit +``` +This is the end of the governance process. From b289808351310d08517918b81117c8b4f35be48e Mon Sep 17 00:00:00 2001 From: Yelong Zhang Date: Sat, 22 Sep 2018 10:13:46 +0800 Subject: [PATCH 096/124] Update README.md --- docs/get-started/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/get-started/README.md b/docs/get-started/README.md index 30bdb1b2c..7b2f12b3b 100644 --- a/docs/get-started/README.md +++ b/docs/get-started/README.md @@ -30,7 +30,7 @@ You now have an active full node. What's the next step? If you have participated in the genesis file generation process, you should be a validator once you are fully synced. -If you miss the genesis file generation process, you can still upgrade your full node to become a IRISnet Validator. The top 100 validators have the ability to propose new blocks to the IRIS Hub. Continue onto [the Validator Setup](). +If you miss the genesis file generation process, you can still upgrade your full node to become a IRISnet Validator. The top 100 validators have the ability to propose new blocks to the IRIS Hub. Continue onto [the Validator Setup](Validator-Node.md). ### Setup a sentry node From 98bdb79d91efcfe0fb596114720305f06172ebf6 Mon Sep 17 00:00:00 2001 From: Raymond Date: Sat, 22 Sep 2018 23:57:49 +0800 Subject: [PATCH 097/124] Update SDK deps to v0.23.0-iris5 due to the consensus failure issue --- CHANGELOG.md | 17 +++++++++++++++++ Gopkg.lock | 6 +++--- Gopkg.toml | 2 +- version/version.go | 2 +- 4 files changed, 22 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index be11c7b8b..0ef4317b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## 0.4.2 + +*September 22th, 2018* + +BUG FIXES + +- Fix consensus failure due to the double sign evidence be broadcasted before the genesis block + +## 0.4.1 + +*September 12th, 2018* + +BUG FIXES + +- Missing to set validator intraTxCount in stake genesis init + + ## 0.4.0 *September 6th, 2018* diff --git a/Gopkg.lock b/Gopkg.lock index 15fb8d60c..bb9547a8e 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -57,7 +57,7 @@ revision = "d4cc87b860166d00d6b5b9e0d3b3d71d6088d4d4" [[projects]] - digest = "1:67c389e6e950ca4ef969adcb4063ddce7b2c3b5bd82e7bc5275786e39516d246" + digest = "1:a434ef9c43a2e5540a92d5cf86624cddd85753ff020c2627833631597549fc57" name = "github.com/cosmos/cosmos-sdk" packages = [ "baseapp", @@ -104,9 +104,9 @@ "x/stake/types", ] pruneopts = "UT" - revision = "1a50123d7199e2182a0b5684447515e239882aa6" + revision = "66cf80ee66e443c71e0fa6afd794780b78ccc412" source = "https://github.com/irisnet/cosmos-sdk.git" - version = "v0.23.0-iris4" + version = "v0.23.0-iris5" [[projects]] digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec" diff --git a/Gopkg.toml b/Gopkg.toml index 2f006a850..e5099c33b 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -29,7 +29,7 @@ [[constraint]] name = "github.com/cosmos/cosmos-sdk" source = "https://github.com/irisnet/cosmos-sdk.git" - version = "=v0.23.0-iris4" + version = "=v0.23.0-iris5" [[override]] name = "github.com/golang/protobuf" diff --git a/version/version.go b/version/version.go index 4ee9b66e2..a802a6990 100644 --- a/version/version.go +++ b/version/version.go @@ -12,7 +12,7 @@ import ( ) // Version - Iris Version -const Version = "0.4.1" +const Version = "0.4.2" func GetCmdVersion(storeName string, cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ From ca6d7f272933662128d02437ab21a3abe5e9dfbf Mon Sep 17 00:00:00 2001 From: kidinamoto01 Date: Sun, 23 Sep 2018 21:12:25 +0800 Subject: [PATCH 098/124] upgrade to 3001 --- docs/get-started/Full-Node.md | 4 ++-- docs/get-started/Install-Iris.md | 9 +++++---- docs/zh/get-started/install-Iris.md | 10 +++++----- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/docs/get-started/Full-Node.md b/docs/get-started/Full-Node.md index 78acc8bcb..9fa82520d 100644 --- a/docs/get-started/Full-Node.md +++ b/docs/get-started/Full-Node.md @@ -27,8 +27,8 @@ After intializing your node, please download the genesis file and the config fil cd $IRISHOME/config/ rm genesis.json rm config.toml -wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-3000/config/config.toml -wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-3000/config/genesis.json +wget https://raw.githubusercontent.com/irisnet/testnets/master/fuxi/fuxi-3000/config/genesis.json +wget https://raw.githubusercontent.com/irisnet/testnets/master/fuxi/fuxi-3000/config/config.toml ``` ## Edit your Config File diff --git a/docs/get-started/Install-Iris.md b/docs/get-started/Install-Iris.md index 64c44a2c4..8c4cb89a0 100644 --- a/docs/get-started/Install-Iris.md +++ b/docs/get-started/Install-Iris.md @@ -91,7 +91,7 @@ Make sure that you can access to google.com for that our project used some libra mkdir -p $GOPATH/src/github.com/irisnet cd $GOPATH/src/github.com/irisnet git clone https://github.com/irisnet/irishub -cd irishub && git checkout v0.4.1 +cd irishub && git checkout v0.4.2 curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh make get_vendor_deps && make install ``` @@ -101,9 +101,10 @@ Now check your **Iris** version. ``` $ iris version -v0.4.1 +v0.4.2 $ iriscli version -v0.4.1 +v0.4.2 +v0.4.2 ``` ### How to Update @@ -114,7 +115,7 @@ Get latest code (you can also `git fetch` only the version desired), ensure the cd $GOPATH/src/github.com/irisnet/irishub git fetch -a origin rm Gopkg.lock -git checkout v0.4.1 +git checkout v0.4.2 make get_vendor_deps make install ``` diff --git a/docs/zh/get-started/install-Iris.md b/docs/zh/get-started/install-Iris.md index 06bf23a52..8c91b1adf 100644 --- a/docs/zh/get-started/install-Iris.md +++ b/docs/zh/get-started/install-Iris.md @@ -28,10 +28,10 @@ tar -C /usr/local/bin -xzf iris$VERSION.$OS-$ARCH.zip ``` $ iris version -v0.4.1 +v0.4.2 $ iriscli version -v0.4.1 +v0.4.2 ``` #### 方法2:源码编译安装 @@ -99,10 +99,10 @@ make get_vendor_deps && make install ``` $ iris version -v0.4.1 +v0.4.2 $ iriscli version -v0.4.1 +v0.4.2 ``` ### 如何升级IRISHub @@ -112,7 +112,7 @@ v0.4.1 cd $GOPATH/src/github.com/irisnet/irishub git fetch -a origin rm Gopkg.lock -git checkout v0.4.1 +git checkout v0.4.2 make get_vendor_deps make install ``` \ No newline at end of file From 1512f73fcf52e4e3edf89c0ce046284065a7373e Mon Sep 17 00:00:00 2001 From: kidinamoto01 Date: Sun, 23 Sep 2018 21:38:42 +0800 Subject: [PATCH 099/124] upgrade to 3001 --- docs/get-started/Install-Iris.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/get-started/Install-Iris.md b/docs/get-started/Install-Iris.md index 8c4cb89a0..b0ba15903 100644 --- a/docs/get-started/Install-Iris.md +++ b/docs/get-started/Install-Iris.md @@ -104,7 +104,6 @@ $ iris version v0.4.2 $ iriscli version v0.4.2 -v0.4.2 ``` ### How to Update From a90ae378358ed6fbb5a982e00ac66bed8f5f625f Mon Sep 17 00:00:00 2001 From: kidinamoto01 Date: Sun, 23 Sep 2018 21:44:30 +0800 Subject: [PATCH 100/124] upgrade to 3001 --- docs/get-started/Install-Iris.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/get-started/Install-Iris.md b/docs/get-started/Install-Iris.md index b0ba15903..2008093ad 100644 --- a/docs/get-started/Install-Iris.md +++ b/docs/get-started/Install-Iris.md @@ -25,10 +25,10 @@ You can verify you have the right version installed by running the following com ``` $ iris version -v0.4.1 +v0.4.2 $ iriscli version -v0.4.1 +v0.4.2 ``` #### Compile Source Code From c776397209b0d803a211b9785baf2554e05c72ce Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Wed, 26 Sep 2018 14:06:16 +0800 Subject: [PATCH 101/124] IRISHUB-466: write the gov/iparam user guide --- docs/modules/gov/README.md | 6 + docs/zh/modules/gov/README.md | 301 +++++++++++++++++++++++++--------- 2 files changed, 234 insertions(+), 73 deletions(-) diff --git a/docs/modules/gov/README.md b/docs/modules/gov/README.md index da3e46ddf..30507e2da 100644 --- a/docs/modules/gov/README.md +++ b/docs/modules/gov/README.md @@ -79,10 +79,13 @@ iriscli gov deposit --proposalID=1 ``` The above proposalID is the result from the first step. At this stage, we delegate 1000000000000000000iris tokens, which is exactly equal to the minimum delegating amount, so the proposal can be voted. And the proposer can send a voting request to each validators (currently only off-chain notification is available, but on-chain or monitoring notification will be implemented later). Then each validators can view the proposal first with the following command: + ``` iriscli gov query-proposal --proposalID=1 ``` + Later proposers can vote as they wish, here I vote Yes (option=Yes): + ``` iriscli gov vote --proposalID=1 --voter=faa1pkunlumfyglqd9dgup0mwp66kjrp6y09twmuvd @@ -92,8 +95,11 @@ iriscli gov vote --proposalID=1 --fee=400000000000000iris --gas=20000 ``` + Notice that the maximum of waiting time is in 20 blocks during the voting period (key: gov/votingprocedure/votingPeriod). If the percentage of affirmative vote is still less than 50% during this period (key: gov/tallyingprocedure/threshold), the proposal will not be passed and the tokens delegated will also not be refunded (the validators haven't voted will be slashed, and 1/100 of the total tokens delegated currently will be deducted (key: gov/tallyingprocedure/penalty). This mechanism has not been implemented in current version ). Suppose there is only one validator. If I voted yes, the ratio of affirmative vote is 1>1/2 and the strong negative vote is 0<1/3 (key:gov/tallyingprocedure/veto), the proposal will be passed. After voting, the proposal is automatically executed: (key: gov/depositprocedure/deposit, value: 10000000000000000000iris) is modified to (key: gov/depositprocedure/deposit, value: 20000000000000000000iris). Then we can verify this result and query the minimum delegating amount in current system: + ``` iriscli iriscli params export gov/depositprocedure/deposit ``` + This is the end of the governance process. diff --git a/docs/zh/modules/gov/README.md b/docs/zh/modules/gov/README.md index b84170062..2763a4621 100644 --- a/docs/zh/modules/gov/README.md +++ b/docs/zh/modules/gov/README.md @@ -1,102 +1,257 @@ -# Governance +# Gov/Iparam User Guide -## 初始化区块链运行环境 +## 基本功能描述 + +1. 文本提议的链上治理 +2. 参数修改提议的链上治理 +3. 软件升级提议的链上治理(不可用) + +## 交互流程 + +### 治理流程 + +1. 任何用户可以发起提议,并抵押一部分资金,如果超过`min_deposit`,提议进入投票,否则留在抵押期。其他人可以对在抵押期的提议进行抵押资金,如果提议的抵押资金总和超过`min_deposit`,则进入投票期。但是提议在抵押期停留的区块数目超过`max_deposit_period`,则提议被关闭。 +2. 进入投票期的提议,只有验证人和委托人可以进行投票,委托人如果没投票,则他继承他委托的验证人的投票选项,如果委托人投票了,则覆盖他委托的验证人的投票选项,当提议到达`voting_perid`,统计投票结果。 +3. 具体提议投票逻辑细节见[CosmosSDK-Gov-spec](https://github.com/cosmos/cosmos-sdk/blob/develop/docs/spec/governance/overview.md) + +## 使用场景 +### 创建使用环境 ``` -rm -rf .iris +rm -rf iris rm -rf .iriscli -iris init gen-tx --name=iris -iris init --gen-txs --chain-id=gov-test -iris start - +iris init gen-tx --name=x --home=iris +iris init --gen-txs --chain-id=gov-test -o --home=iris +iris start --home=iris ``` -## 提议流程 +### 参数修改的使用场景 + +场景一:通过命令行带入参数修改信息进行参数修改 -这里以"参数修改提议"为例,其他提议不需要--params参数。比如,当某一个时间点我们发现,系统产生了很多无用的提议,原因可能是当前最小抵押金额太小了,造成很多人都可以提交一个无意义的提议。 -这个时候我们可以使用"参数修改提议"来修改系统预设的最小抵押金额这个参数。我们首先需要知道该参数对应的key值,才能修改。可以使用以下命令查看: ``` -iriscli params export gov +# 根据gov模块名查询的可修改的参数 +iriscli gov query-params --module=gov --trust-node + +# 结果 +[ + "Gov/gov/DepositProcedure", + "Gov/gov/TallyingProcedure", + "Gov/gov/VotingProcedure" +] + +# 根据Key查询可修改参数的内容 +iriscli gov query-params --key=Gov/gov/DepositProcedure --trust-node + +# 结果 +{"key":"Gov/gov/DepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":10}","op":""} + +# 发送提议,返回参数修改的内容 +echo 1234567890 | iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --param='{"key":"Gov/gov/DepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":20}","op":"update"}' --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# 对提议进行抵押 +echo 1234567890 | iriscli gov deposit --proposal-id=1 --deposit=1iris --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# 对提议投票 +echo 1234567890 | iriscli gov vote --proposal-id=1 --option=Yes --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# 查询提议情况 +iriscli gov query-proposal --proposal-id=1 --trust-node + ``` -这个命令会导出所有可以使用"参数修改提议"来修改的参数,比如我们得到如下结果: + +场景二,通过文件修改参数 ``` -[ - { - "key": "gov/depositprocedure/deposit", - "value": "10000000000000000000iris" - }, - { - "key": "gov/depositprocedure/maxDepositPeriod", - "value": "10" - }, - { - "key": "gov/feeToken/gasPriceThreshold", - "value": "20000000000" - }, - { - "key": "gov/tallyingprocedure/penalty", - "value": "1/100" - }, - { - "key": "gov/tallyingprocedure/threshold", - "value": "1/2" - }, - { - "key": "gov/tallyingprocedure/veto", - "value": "1/3" - }, - { - "key": "gov/votingprocedure/votingPeriod", - "value": "20" +# 导出配置文件 +iriscli gov pull-params --path=iris --trust-node + +# 查询配置文件信息 +cat iris/config/params.json +{ + "gov": { + "Gov/gov/DepositProcedure": { + "min_deposit": [ + { + "denom": "iris-atto", + "amount": "10000000000000000000" + } + ], + "max_deposit_period": "10" + }, + "Gov/gov/VotingProcedure": { + "voting_period": "10" + }, + "Gov/gov/TallyingProcedure": { + "threshold": "1/2", + "veto": "1/3", + "governance_penalty": "1/100" + } } -] +} +# 修改配置文件(TallyingProcedure的governance_penalty) +vi iris/config/params.json +{ + "gov": { + "Gov/gov/DepositProcedure": { + "min_deposit": [ + { + "denom": "iris-atto", + "amount": "10000000000000000000" + } + ], + "max_deposit_period": "10" + }, + "Gov/gov/VotingProcedure": { + "voting_period": "10" + }, + "Gov/gov/TallyingProcedure": { + "threshold": "1/2", + "veto": "1/3", + "governance_penalty": "20/100" + } + } +} +# 通过文件修改参数的命令,返回参数修改的内容 +echo 1234567890 | iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --path=iris --key=Gov/gov/TallyingProcedure --op=update --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# 对提议进行抵押 +echo 1234567890 | iriscli gov deposit --proposal-id=1 --deposit=1iris --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# 对提议投票 +echo 1234567890 | iriscli gov vote --proposal-id=1 --option=Yes --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# 查询提议情况 +iriscli gov query-proposal --proposal-id=1 --trust-node ``` -每一个(key,value)对应一组系统预设的可修改参数,具体的意义会在以后的文档中来完善。这里最小抵押金额的key为gov/depositprocedure/deposit -目前value:10000000000000000000iris(该值是经过进度换算以后的值,具体参考fee-token模块)。我们准备将该值修改为:20000000000000000000iris -提高一倍,来限制提交提议的门槛。可以使用以下命令: +## CLI命令详情 + +### 治理模块基础方法 + +``` +# 文本类提议 +iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="Text" --deposit="10iris" --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 ``` -iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" - --deposit="9000000000000000000iris" - --params='[{"key":"gov/depositprocedure/deposit","value":"20000000000000000001iris","op":"update"}]' - --proposer=faa1pkunlumfyglqd9dgup0mwp66kjrp6y09twmuvd - --from=iris - --chain-id=gov-test - --fee=400000000000000iris - --gas=20000 +* `--title` 提议的标题 +* `--description` 提议的描述 +* `--type` 提议的类型 {'Text','ParameterChange','SoftwareUpgrade'} +* `--deposit` 抵押贷币的数量 +* 上面就是典型的文本类提议 + +``` +iriscli gov deposit --proposal-id=1 --deposit=1iris --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 ``` -这里我抵押的金额为9000000000000000000iris,比最小抵押金额少1000000000000000000iris,所以该提议还未被激活,不能进入投票阶段,需要在10(key:gov/depositprocedure/maxDepositPeriod)个区块之前筹齐10000000000000000000iris的抵押金额(如果当前出块时间为5s,意味着你需要在 5 * 10s之前完成抵押任务),抵押操作命令如下: +* `--propsal-id` 抵押提议ID +* `--deposit` 抵押的贷币数目 ``` -iriscli gov deposit --proposalID=1 - --depositer=faa1pkunlumfyglqd9dgup0mwp66kjrp6y09twmuvd - --deposit=1000000000000000000iris - --from=iris - --chain-id=gov-test - --fee=200000000000000iris - --gas=20000 +iriscli gov vote --proposal-id=1 --option=Yes --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 +``` + +* `--proposal-id` 投票提议ID +* `--option` 投票的选项{'Yes'赞同,'Abstain'弃权,'No'不同意,'nowithVeto'强烈不同意} + ``` -以上的proposalID是由第一步返回结果得到的,这个阶段我们抵押了1000000000000000000iris个代币,正好等于最小抵押金额,所以该提议将进入投票阶段,提议者可以向各个validator发起投票请求(目前只能靠链下通知,以后可以考虑采用链上通知或者监控通知)。然后各个validator可以先查看该提议内容,使用以下命令: +# 查询提议情况 +iriscli gov query-proposal --proposal-id=1 --trust-node ``` -iriscli gov query-proposal --proposalID=1 + +* `--proposal-id` 查询提议ID + + + +### 参数修改提议部分 + ``` -之后投票者可以根据自己的意愿发起投票,这里我投赞成票(option=Yes): +# 根据gov模块名查询的可修改的参数 +iriscli gov query-params --module=gov --trust-node ``` -iriscli gov vote --proposalID=1 - --voter=faa1pkunlumfyglqd9dgup0mwp66kjrp6y09twmuvd - --option=Yes - --from=iris - --chain-id=gov-test - --fee=400000000000000iris - --gas=20000 + +* `--module` 查询module可修改参数的key的列表 + + ``` -注意投票期有最大等待时间20个区块高度(key:gov/votingprocedure/votingPeriod)。如果超过这个高度选票的赞成票比例还未达到1/2(key:gov/tallyingprocedure/threshold)。那么系统认为该提议未被通过。不会退还之前抵押的代币(如果有validator未投票,还会被slash,惩罚的比例为当前stake代币总量的1/100(key:gov/tallyingprocedure/penalty),当前版本还没有这个机制)。假设当前我们只有一个validator,因为我们投的是赞成票,所以赞成的比例为1>1/2 并且 强烈反对票为0<1/3(key:gov/tallyingprocedure/veto),所以提议通过。等投票期结束,开始自动执行提议内容:将(key:gov/depositprocedure/deposit,value:10000000000000000000iris)修改为(key:gov/depositprocedure/deposit,value:20000000000000000000iris)。接下来我们可以验证这个结果,查询当前系统的最小抵押金额: +# 根据Key查询可修改参数的内容 +iriscli gov query-params --key=Gov/gov/DepositProcedure --trust-node ``` -iriscli iriscli params export gov/depositprocedure/deposit + +* `--key` 查询key对应的参数值 + ``` -到此,gov治理流程结束。 \ No newline at end of file +# 导出配置文件 +iriscli gov pull-params --path=iris --trust-node +``` + +* `--path` 节点初始化的文件夹 + + + +``` +# 通过命令行带入参数修改信息进行参数修改 +iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --param='{"key":"Gov/gov/DepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":20}","op":"update"}' --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 +``` + +* `--param` 参数修改的具体内容(通过query-params得到参数内容,然后直接对其修改,并在"op"上添上update,具体可见使用场景) +* 其他字段与文本提议类似 + +``` +# 通过文件修改参数的命令,返回参数修改的内容 +echo 1234567890 | iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --path=iris --key=Gov/gov/TallyingProcedure --op=update --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 +``` + +* `--path` 节点初始化的文件夹 +* `--key` 要修改参数的key +* `--op` 参数修改类型,目前只实现了'update' +* 其他字段与文本提议类似 + +### 软件升级提议部分 + +## 基本参数 + +``` +# DepositProcedure(抵押阶段的参数) +"Gov/gov/DepositProcedure": { + "min_deposit": [ + { + "denom": "iris-atto", + "amount": "10000000000000000000" + } + ], + "max_deposit_period": "10" +} +``` + +* 可修改参数 +* 参数的key:"Gov/gov/DepositProcedure" +* `min_deposit[0].denom` 最小抵押贷币的token只能是单位是iris-atto的iris通证。 +* `min_deposit[0].amount` 最小抵押贷币的数量,默认范围:10iris(1iris,200iris) +* `max_deposit_period` 补交抵押的窗口期,默认:10 范围(0,1) + +``` +# VotingProcedure(投票阶段的参数) +"Gov/gov/VotingProcedure": { + "voting_period": "10" +}, +``` + +* `voting_perid` 投票的窗口期,默认10,范围(20,20000) + +``` +# TallyingProcedure (统计阶段段参数) +"Gov/gov/TallyingProcedure": { + "threshold": "1/2", + "veto": "1/3", + "governance_penalty": "1/100" +} +``` +* `veto` 默认1/3,范围(0,1) +* `threshold` 默认1/2,范围(0,1) +* `governance_penalty` 未投票的验证人惩罚贷币的比例 默认1/100,范围(0,1) +* 投票统计逻辑:如果强烈反对的voting_power占总的voting_power 超过 veto,提议不通过。然后再看赞同的voting_power占总的投票的voting_power 是否超过 veto,超过则提议不通过,不超过则不通过。 + + From cf2cd172f0d431fae17faa322ec794db1bf745f8 Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Thu, 27 Sep 2018 10:46:08 +0800 Subject: [PATCH 102/124] IRISHUB-473 Update titles --- docs/get-started/Full-Node.md | 10 +++++----- docs/get-started/Genesis-Generation-Process.md | 8 ++++---- docs/get-started/Validator-Node.md | 16 +++++++--------- docs/tools/Deploy-IRIS-Monitor.md | 2 +- .../How-to-participate-in-onchain-governance.md | 8 ++++---- docs/zh/get-started/Full-Node.md | 10 +++++----- .../zh/get-started/Genesis-Generation-Process.md | 2 +- docs/zh/get-started/README.md | 8 ++++---- docs/zh/get-started/Validator-Node.md | 8 ++++---- .../How-to-participate-in-onchain-governance.md | 8 ++++---- 10 files changed, 39 insertions(+), 41 deletions(-) diff --git a/docs/get-started/Full-Node.md b/docs/get-started/Full-Node.md index a50d82e98..8f69a5489 100644 --- a/docs/get-started/Full-Node.md +++ b/docs/get-started/Full-Node.md @@ -2,7 +2,7 @@ Before setting up your validator node, make sure you already had **Iris** installed by following this [guide](Install-Iris.md) -### Step 1: Init Your Node +## Init Your Node These instructions are for setting up a brand new full node from scratch. @@ -18,7 +18,7 @@ The default \$IRISHOME is `~/.iris` , You can edit this `name` later, in the `~/ Your full node has been initialized! -### Get Configuration Files +## Get Configuration Files After intializing your node, please download the genesis file and the config file to join in the testnet. @@ -27,10 +27,10 @@ After intializing your node, please download the genesis file and the config fil cd $IRISHOME/config/ rm genesis.json rm config.toml -wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-3000/config/config.toml -wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-3000/config/genesis.json +wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-3001/config/config.toml +wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-3001/config/genesis.json ``` -## Edit your Config File +## Edit Your Config File You could customized the `moniker` and `external_address` fields. diff --git a/docs/get-started/Genesis-Generation-Process.md b/docs/get-started/Genesis-Generation-Process.md index 5b5769e5a..64590df82 100644 --- a/docs/get-started/Genesis-Generation-Process.md +++ b/docs/get-started/Genesis-Generation-Process.md @@ -1,10 +1,10 @@ # How To Participate in Genesis Process -## Requirement +## Requirements You must have follow this [guide](Install-Iris.md) to install the correct version of **Iris**. -## Step 1: +## Gentx Please run the `gen-tx` command to generate files. @@ -67,9 +67,9 @@ validator is generated by \$IRISHOME/config/priv_validator.json ## Step 2: -Submit your gentx-node-ID.json to `https://github.com/irisnet/testnets/tree/master/fuxi/fuxi-3000/config/gen-tx/` by createing a pull request. +Submit your `gentx-.json` to `https://github.com/irisnet/testnets/tree/master/fuxi/fuxi-3001/config/gen-tx/` by createing a pull request. -After the team has collected all the gen-tx transactions, we will publish the genesis file in the following folder: `https://github.com/irisnet/testnets/tree/master/testnets/fuxi-3000/config/` +After the team has collected all the gen-tx transactions, we will publish the genesis file in the following folder: `https://github.com/irisnet/testnets/tree/master/testnets/fuxi-3001/config/` You could then download the final genesis file and start a node. diff --git a/docs/get-started/Validator-Node.md b/docs/get-started/Validator-Node.md index da849d9e2..8b9e90975 100644 --- a/docs/get-started/Validator-Node.md +++ b/docs/get-started/Validator-Node.md @@ -4,11 +4,9 @@ Before setting up your validator node, make sure you've already installed **Iri Validators are responsible for committing new blocks to the blockchain through consensus. A validator's stake will be slashed if they become unavailable, double sign a transaction, or don't cast their votes. Please read about Sentry Node Architecture to protect your node from DDOS attacks and to ensure high-availability. -## Create A Validator +## Get IRIS Token -### Get IRIS Token - -#### Create Account +### Create Account You need to get `iris` and `iriscli` installed first. Then, follow the instructions below to create a new account: @@ -45,7 +43,7 @@ Once you have created your own address, please then you could use this accoun iriscli account --node=http://localhost:26657 ``` -## Create-Validator +## Create Validator ### Confirm Your Validator is Synced @@ -81,7 +79,7 @@ Please note the **amount** needs to be the **minimium unit** of IRIS token: `iri In this way, to stake 1IRIS, you need to do: ``` -iriscli stake create-validator --pubkey=pubkey --address-validator=account --fee=40000000000000000iris --gas=2000000 --from= --chain-id=fuxi-3000 --node=tcp://localhost:26657 --amount=1000000000000000000iris +iriscli stake create-validator --pubkey=pubkey --address-validator=account --fee=40000000000000000iris --gas=2000000 --from= --chain-id=fuxi-3001 --node=tcp://localhost:26657 --amount=1000000000000000000iris ``` Don't forget the `fee` and `gas` field. In this version of IRIHub, all the `unit` for `amount` and `field` correspond to `iris-atto`,but it's shown as `iris`. To read more about coin-type in IRISHub, you should read [this](../zh/modules/coin/README.md) @@ -90,7 +88,7 @@ Don't forget the `fee` and `gas` field. In this version of IRIHub, all the `unit View the validator's information with this command: ``` -iriscli stake validator --address-validator=account --chain-id=fuxi-3000 --node=tcp://localhost:26657 +iriscli stake validator --address-validator=account --chain-id=fuxi-3001 --node=tcp://localhost:26657 ``` The `` is your account address that starts with 'faa' @@ -115,7 +113,7 @@ You can edit your validator's public description. This info is to identify your You should put your name of your team in `details`. ``` -iriscli stake edit-validator --address-validator=account --moniker="choose a moniker" --website="https://irisnet.org" --details="team" --chain-id=fuxi-3000 +iriscli stake edit-validator --address-validator=account --moniker="choose a moniker" --website="https://irisnet.org" --details="team" --chain-id=fuxi-3001 --name=key_name --node=tcp://localhost:26657 --fee=40000000000000000iris --gas=2000000 ``` ### View Validator Description @@ -123,7 +121,7 @@ iriscli stake edit-validator --address-validator=account --moniker="choose a mo View the validator's information with this command: ``` -iriscli stake validator --address-validator= --chain-id=fuxi-3000 +iriscli stake validator --address-validator= --chain-id=fuxi-3001 ``` ### Use IRISPlorer diff --git a/docs/tools/Deploy-IRIS-Monitor.md b/docs/tools/Deploy-IRIS-Monitor.md index 216059643..939a69f89 100644 --- a/docs/tools/Deploy-IRIS-Monitor.md +++ b/docs/tools/Deploy-IRIS-Monitor.md @@ -40,7 +40,7 @@ to modify ``` ---chain-id=fuxi-3000 +--chain-id=fuxi-3001 ``` to ``` diff --git a/docs/validators/How-to-participate-in-onchain-governance.md b/docs/validators/How-to-participate-in-onchain-governance.md index 763e14f55..785ccfdda 100644 --- a/docs/validators/How-to-participate-in-onchain-governance.md +++ b/docs/validators/How-to-participate-in-onchain-governance.md @@ -34,7 +34,7 @@ Anyone could submit a governance proposal, but you need to make the deposit for The following command is for submitting a `Text` proposal: ``` -iriscli gov submit-proposal --title="Text" --description="name of the proposal" --type="Text" --deposit="1000000000000000000000iris" --proposer= --from= --chain-id=fuxi-3000 --fee=400000000000000iris --gas=20000 --node=http://localhost:36657 +iriscli gov submit-proposal --title="Text" --description="name of the proposal" --type="Text" --deposit="1000000000000000000000iris" --proposer= --from= --chain-id=fuxi-3001 --fee=400000000000000iris --gas=20000 --node=http://localhost:36657 ``` > Please Note the `deposit` is in minimum unit. @@ -47,7 +47,7 @@ The `` for `proposer` field should start with `faa` which corresponds t To add deposit to some proposal, you could execute this command to add `10IRIS` to the proposal's deposit: ``` -iriscli gov deposit --proposalID=1 --depositer= --deposit=1000000000000000000iris --from= --chain-id=fuxi-3000 --fee=400000000000000iris --gas=20000 --node=http://localhost:36657 +iriscli gov deposit --proposalID=1 --depositer= --deposit=1000000000000000000iris --from= --chain-id=fuxi-3001 --fee=400000000000000iris --gas=20000 --node=http://localhost:36657 ``` ## How to vote a proposal? @@ -62,7 +62,7 @@ You could put one of the choices in the `--option` field. To vote for a proposal, you need to get the correct ``.You could execute the following command to vote on proposal with ID = 1: ``` -iriscli vote --from=jerry --voter= --proposalID=1 --option=Yes --chain-id=fuxi-3000 +iriscli vote --from=jerry --voter= --proposalID=1 --option=Yes --chain-id=fuxi-3001 --fee=2000000000000000iris --gas=20000 --node=http://localhost:36657 ``` @@ -70,7 +70,7 @@ iriscli vote --from=jerry --voter= --proposalID=1 --option=Yes --chain You could use the following command to get the first proposal: ``` -iriscli gov query-proposal --proposalID=1 --chain-id=fuxi-3000 --node=http://localhost:26657 +iriscli gov query-proposal --proposalID=1 --chain-id=fuxi-3001 --node=http://localhost:26657 ``` diff --git a/docs/zh/get-started/Full-Node.md b/docs/zh/get-started/Full-Node.md index 0c3b5ec02..8764b6149 100644 --- a/docs/zh/get-started/Full-Node.md +++ b/docs/zh/get-started/Full-Node.md @@ -17,13 +17,13 @@ genesis文件中定义了区块链网络的初始状态,而config.toml指定 ``` cd $IRISHOME/config/ -wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-3000/config/config.toml -wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-3000/config/genesis.json +wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-3001/config/config.toml +wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-3001/config/genesis.json ``` ### 修改配置文件 在config.toml文件中可以配置以下信息: * 将`moniker`字段配置称为自定义的名称,这样便于区分不同的节点 -* `seed`字段用语设置种子节点,在fuxi-3000中的官方中字节点为:3fb472c641078eaaee4a4acbe32841f18967672c@35.165.232.141:26657 +* `seed`字段用语设置种子节点,在fuxi-3001中的官方中字节点为:3fb472c641078eaaee4a4acbe32841f18967672c@35.165.232.141:26657 ## 启动一个全节点 @@ -37,7 +37,7 @@ iriscli status ``` 示例输出: ```json -{"node_info":{"id":"3fb472c641078eaaee4a4acbe32841f18967672c","listen_addr":"172.31.0.190:26656","network":"fuxi-3000","version":"0.22.6","channels":"4020212223303800","moniker":"name","other":["amino_version=0.10.1","p2p_version=0.5.0","consensus_version=v1/0.2.2","rpc_version=0.7.0/3","tx_index=on","rpc_addr=tcp://0.0.0.0:26657"]},"sync_info":{"latest_block_hash":"7B1168B2055B19F811773EEE56BB3C9ECB6F3B37","latest_app_hash":"B8F7F8BF18E3F1829CCDE26897DB905A51AF4372","latest_block_height":12567,"latest_block_time":"2018-08-25T11:33:13.164432273Z","catching_up":false},"validator_info":{"address":"CAF80DAEC0F4A7036DD2116B56F89B07F43A133E","pub_key":{"type":"AC26791624DE60","value":"Cl6Yq+gqZZY14QxrguOaZqAswPhluv7bDfcyQx2uSRc="},"voting_power":0}} +{"node_info":{"id":"3fb472c641078eaaee4a4acbe32841f18967672c","listen_addr":"172.31.0.190:26656","network":"fuxi-3001","version":"0.22.6","channels":"4020212223303800","moniker":"name","other":["amino_version=0.10.1","p2p_version=0.5.0","consensus_version=v1/0.2.2","rpc_version=0.7.0/3","tx_index=on","rpc_addr=tcp://0.0.0.0:26657"]},"sync_info":{"latest_block_hash":"7B1168B2055B19F811773EEE56BB3C9ECB6F3B37","latest_app_hash":"B8F7F8BF18E3F1829CCDE26897DB905A51AF4372","latest_block_height":12567,"latest_block_time":"2018-08-25T11:33:13.164432273Z","catching_up":false},"validator_info":{"address":"CAF80DAEC0F4A7036DD2116B56F89B07F43A133E","pub_key":{"type":"AC26791624DE60","value":"Cl6Yq+gqZZY14QxrguOaZqAswPhluv7bDfcyQx2uSRc="},"voting_power":0}} ``` 通过以上命令可以查看状态: @@ -80,7 +80,7 @@ iriscli status ``` 示例输出: ```json -{"node_info":{"id":"3fb472c641078eaaee4a4acbe32841f18967672c","listen_addr":"172.31.0.190:26656","network":"fuxi-3000","version":"0.22.6","channels":"4020212223303800","moniker":"name","other":["amino_version=0.10.1","p2p_version=0.5.0","consensus_version=v1/0.2.2","rpc_version=0.7.0/3","tx_index=on","rpc_addr=tcp://0.0.0.0:26657"]},"sync_info":{"latest_block_hash":"7B1168B2055B19F811773EEE56BB3C9ECB6F3B37","latest_app_hash":"B8F7F8BF18E3F1829CCDE26897DB905A51AF4372","latest_block_height":12567,"latest_block_time":"2018-08-25T11:33:13.164432273Z","catching_up":false},"validator_info":{"address":"CAF80DAEC0F4A7036DD2116B56F89B07F43A133E","pub_key":{"type":"AC26791624DE60","value":"Cl6Yq+gqZZY14QxrguOaZqAswPhluv7bDfcyQx2uSRc="},"voting_power":100}} +{"node_info":{"id":"3fb472c641078eaaee4a4acbe32841f18967672c","listen_addr":"172.31.0.190:26656","network":"fuxi-3001","version":"0.22.6","channels":"4020212223303800","moniker":"name","other":["amino_version=0.10.1","p2p_version=0.5.0","consensus_version=v1/0.2.2","rpc_version=0.7.0/3","tx_index=on","rpc_addr=tcp://0.0.0.0:26657"]},"sync_info":{"latest_block_hash":"7B1168B2055B19F811773EEE56BB3C9ECB6F3B37","latest_app_hash":"B8F7F8BF18E3F1829CCDE26897DB905A51AF4372","latest_block_height":12567,"latest_block_time":"2018-08-25T11:33:13.164432273Z","catching_up":false},"validator_info":{"address":"CAF80DAEC0F4A7036DD2116B56F89B07F43A133E","pub_key":{"type":"AC26791624DE60","value":"Cl6Yq+gqZZY14QxrguOaZqAswPhluv7bDfcyQx2uSRc="},"voting_power":100}} ``` 通过以上命令可以查看状态: diff --git a/docs/zh/get-started/Genesis-Generation-Process.md b/docs/zh/get-started/Genesis-Generation-Process.md index 6c4bf6b6a..5fa286081 100644 --- a/docs/zh/get-started/Genesis-Generation-Process.md +++ b/docs/zh/get-started/Genesis-Generation-Process.md @@ -68,7 +68,7 @@ `app_gen_tx`中说明了拥有这个节点的账户信息。这个账户的助记词就是刚刚的secret -3. 将上述提到的json文件以提交Pull Request的形式上传到`https://github.com/irisnet/testnets/tree/master/testnets/fuxi-3000/config/gentx`目录下: +3. 将上述提到的json文件以提交Pull Request的形式上传到`https://github.com/irisnet/testnets/tree/master/testnets/fuxi-3001/config/gentx`目录下: 注意⚠️:json文中的IP改成公网IP diff --git a/docs/zh/get-started/README.md b/docs/zh/get-started/README.md index 872e8fdad..c5dd468d1 100644 --- a/docs/zh/get-started/README.md +++ b/docs/zh/get-started/README.md @@ -5,7 +5,7 @@ IRIS Hub是在Cosmos生态中的区域性枢纽,提供iService服务 -## 如何加入fuxi-3000测试网 +## 如何加入fuxi-3001测试网 ### 安装IRIShub @@ -131,15 +131,15 @@ iris在运行过程中所依赖的配置文件和数据会存放在\$IRISHOME下 cd $IRISHOME/config/ rm genesis.json rm config.toml - wget https://raw.githubusercontent.com/irisnet/testnets/master/fuxi/fuxi-3000/config/config.toml - wget https://raw.githubusercontent.com/irisnet/testnets/master/fuxi/fuxi-3000/config/genesis.json + wget https://raw.githubusercontent.com/irisnet/testnets/master/fuxi/fuxi-3001/config/config.toml + wget https://raw.githubusercontent.com/irisnet/testnets/master/fuxi/fuxi-3001/config/genesis.json * **修改配置文件** 在config.toml文件中可以配置以下信息: 1. 将moniker字段配置称为自定义的名称,这样便于区分不同的节点 -2. seed字段用语设置种子节点,在fuxi-3000中的官方种子节点为: +2. seed字段用语设置种子节点,在fuxi-3001中的官方种子节点为: ``` c16700520a810b270206d59f0f02ea9abd85a4fe@35.165.232.141:26656 ``` diff --git a/docs/zh/get-started/Validator-Node.md b/docs/zh/get-started/Validator-Node.md index b5458e948..4f0582291 100644 --- a/docs/zh/get-started/Validator-Node.md +++ b/docs/zh/get-started/Validator-Node.md @@ -79,7 +79,7 @@ iriscli stake create-validator --amount=iris --pubkey= --address 也就是说,如果你想要抵押1IRIS,你可以执行以下操作: ``` -iriscli stake create-validator --pubkey=pubkey --address-validator=account --fee=40000000000000000iris --gas=2000000 --from= --chain-id=fuxi-3000 --node=tcp://localhost:26657 --amount=1000000000000000000iris +iriscli stake create-validator --pubkey=pubkey --address-validator=account --fee=40000000000000000iris --gas=2000000 --from= --chain-id=fuxi-3001 --node=tcp://localhost:26657 --amount=1000000000000000000iris ``` 请记得在命令中注明`fee` 和 `gas`字段。`fee`和`amount`的单位为`iris-atto`,但是在命令中为了方便写成`iris`。请在以下[文档](../modules/coin/README.md) 了解更多有关代币单位的内容。 @@ -89,7 +89,7 @@ iriscli stake create-validator --pubkey=pubkey --address-validator=account --fee 你可以通过以下命令查询验证人的信息: ``` -iriscli stake validator --address-validator= --chain-id=fuxi-3000 --node=tcp://localhost:26657 +iriscli stake validator --address-validator= --chain-id=fuxi-3001 --node=tcp://localhost:26657 ``` 请注意 `` 字段是以`faa`为首字母。 @@ -111,7 +111,7 @@ iriscli status --node=tcp://localhost:26657 你应该在`details`字段注明自定义的信息。 ``` -iriscli stake edit-validator --address-validator=account --moniker="choose a moniker" --website="https://irisnet.org" --details="team" --chain-id=fuxi-3000 +iriscli stake edit-validator --address-validator=account --moniker="choose a moniker" --website="https://irisnet.org" --details="team" --chain-id=fuxi-3001 --name=key_name --node=tcp://localhost:26657 --fee=40000000000000000iris --gas=2000000 ``` ### 查询验证人信息 @@ -119,7 +119,7 @@ iriscli stake edit-validator --address-validator=account --moniker="choose a mo 你可以通过以下命令查询验证人的信息: ``` -iriscli stake validator --address-validator= --chain-id=fuxi-3000 +iriscli stake validator --address-validator= --chain-id=fuxi-3001 ``` ### 使用浏览器:IRISPlorer diff --git a/docs/zh/validators/How-to-participate-in-onchain-governance.md b/docs/zh/validators/How-to-participate-in-onchain-governance.md index ec822457e..72d9a1ab8 100644 --- a/docs/zh/validators/How-to-participate-in-onchain-governance.md +++ b/docs/zh/validators/How-to-participate-in-onchain-governance.md @@ -28,7 +28,7 @@ 如下的命令将执行提交一个 `Text`类型的提案: ``` -iriscli gov submit-proposal --title="Text" --description="name of the proposal" --type="Text" --deposit="1000000000000000000000iris" --proposer= --from= --chain-id=fuxi-3000 --fee=400000000000000iris --gas=20000 --node=http://localhost:36657 +iriscli gov submit-proposal --title="Text" --description="name of the proposal" --type="Text" --deposit="1000000000000000000000iris" --proposer= --from= --chain-id=fuxi-3001 --fee=400000000000000iris --gas=20000 --node=http://localhost:36657 ``` The `` for `proposer` field should start with `faa` which corresponds to ``. @@ -39,7 +39,7 @@ The `` for `proposer` field should start with `faa` which corresponds t To add deposit to some proposal, you could execute this command to add `10IRIS` to the proposal's deposit: ``` -iriscli gov deposit --proposalID=1 --depositer= --deposit=1000000000000000000iris --from= --chain-id=fuxi-3000 --fee=400000000000000iris --gas=20000 --node=http://localhost:36657 +iriscli gov deposit --proposalID=1 --depositer= --deposit=1000000000000000000iris --from= --chain-id=fuxi-3001 --fee=400000000000000iris --gas=20000 --node=http://localhost:36657 ``` ##如何投票? @@ -54,7 +54,7 @@ You could put one of the choices in the `--option` field. To vote for a proposal, you need to get the correct ``.You could execute the following command to vote on proposal with ID = 1: ``` -iriscli vote --from=jerry --voter= --proposalID=1 --option=Yes --chain-id=fuxi-3000 --fee=2000000000000000iris --gas=20000 --node=http://localhost:36657 +iriscli vote --from=jerry --voter= --proposalID=1 --option=Yes --chain-id=fuxi-3001 --fee=2000000000000000iris --gas=20000 --node=http://localhost:36657 ``` ## 如何查询投票信息? @@ -62,7 +62,7 @@ iriscli vote --from=jerry --voter= --proposalID=1 --option=Yes --chain 例如,查询第一个提案的信息: ``` -iriscli gov query-proposal --proposalID=1 --chain-id=fuxi-3000 --node=http://localhost:26657 +iriscli gov query-proposal --proposalID=1 --chain-id=fuxi-3001 --node=http://localhost:26657 `````` 也可以在浏览器上查询。 From c040e71e5ae4cd2f30791d7b973c034c7c703711 Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Thu, 27 Sep 2018 10:51:04 +0800 Subject: [PATCH 103/124] IRISHUB-473 Update titles --- docs/get-started/Genesis-Generation-Process.md | 2 +- docs/get-started/irislcd.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/get-started/Genesis-Generation-Process.md b/docs/get-started/Genesis-Generation-Process.md index 64590df82..ab98410aa 100644 --- a/docs/get-started/Genesis-Generation-Process.md +++ b/docs/get-started/Genesis-Generation-Process.md @@ -65,7 +65,7 @@ The content of the file will be: ``` validator is generated by \$IRISHOME/config/priv_validator.json -## Step 2: +## Submit Gentx Submit your `gentx-.json` to `https://github.com/irisnet/testnets/tree/master/fuxi/fuxi-3001/config/gen-tx/` by createing a pull request. diff --git a/docs/get-started/irislcd.md b/docs/get-started/irislcd.md index 9dd2e5d35..557fd2fd4 100644 --- a/docs/get-started/irislcd.md +++ b/docs/get-started/irislcd.md @@ -1,6 +1,6 @@ # What is Irislcd -An irislcd node is a REST server which can connect to any full nodes and provide a set of rest APIs. By these APIs, users can send transactions and query blockchain data. Irislcd can verify the proof of query result. So it can provide the same security as a full node with the minimal requirements on bandwidth, computing and storage resource. Besides, it also provides swagger-ui which presents detailed description about what APIs it provides and how to use the them. +An irislcd node is a REST server which can connect to any full nodes and provide a set of rest APIs. By these APIs, users can send transactions and query blockchain data. Irislcd can verify the proof of query result. So it can provide the same security as a full node with the minimal requirements on bandwidth, computing and storage resource. Besides, it also provides swagger-ui which presents detailed description about what APIs it provides and how to use them. ## Irislcd options From 0cb331a70d873cdf530424a310ad6c07a095e3e1 Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Thu, 27 Sep 2018 10:57:19 +0800 Subject: [PATCH 104/124] IRISHUB-473 Fix Links --- docs/validators/FAQ.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/validators/FAQ.md b/docs/validators/FAQ.md index 5fe6bd105..50576ac7f 100644 --- a/docs/validators/FAQ.md +++ b/docs/validators/FAQ.md @@ -53,6 +53,6 @@ Please read this [doc](https://github.com/irisnet/testnets/blob/master/fuxi/docs 7. How to understand the notion of gas&fee in IRISHub? -This is the tech spec for fee&gas is [here](https://github.com/irisnet/irishub/blob/d1d20826da2112a53c6a0ce45e0263237c549089/docs/modules/fee-token/feeToken.md) +This is the tech spec for fee&gas is [here](../modules/fee-token/README.md) From 2605521371d7d898e465f16e6285faee4534fd32 Mon Sep 17 00:00:00 2001 From: Raymond Date: Thu, 27 Sep 2018 11:13:50 +0800 Subject: [PATCH 105/124] IRISHUB-474: add the cli cmd for software-upgrade --- client/upgrade/cli/query.go | 45 +++++++++++++++++++++++++++ client/upgrade/cli/sendtx.go | 59 ++++++++++++++++++++++++++++++++++++ cmd/iriscli/main.go | 11 +++++-- 3 files changed, 112 insertions(+), 3 deletions(-) create mode 100644 client/upgrade/cli/sendtx.go diff --git a/client/upgrade/cli/query.go b/client/upgrade/cli/query.go index adfe924ca..8975d60ec 100644 --- a/client/upgrade/cli/query.go +++ b/client/upgrade/cli/query.go @@ -2,12 +2,15 @@ package cli import ( "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/modules/upgrade" "github.com/irisnet/irishub/modules/upgrade/params" + "github.com/pkg/errors" "github.com/spf13/cobra" + "github.com/spf13/viper" "os" ) @@ -49,3 +52,45 @@ func GetInfoCmd(storeName string, cdc *wire.Codec) *cobra.Command { } return cmd } + +// Command to Get a Switch Information +func GetCmdQuerySwitch(storeName string, cdc *wire.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "query-switch", + Short: "query switch details", + RunE: func(cmd *cobra.Command, args []string) error { + proposalID := viper.GetInt64(flagProposalID) + voterStr := viper.GetString(flagVoter) + + voter, err := sdk.AccAddressFromBech32(voterStr) + if err != nil { + return err + } + + cliCtx := context.NewCLIContext(). + WithCodec(cdc). + WithLogger(os.Stdout). + WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + + res, err := cliCtx.QueryStore(upgrade.GetSwitchKey(proposalID, voter), storeName) + if len(res) == 0 || err != nil { + return errors.Errorf("proposalID [%d] is not existed", proposalID) + } + + var switchMsg upgrade.MsgSwitch + cdc.MustUnmarshalBinary(res, &switchMsg) + output, err := wire.MarshalJSONIndent(cdc, switchMsg) + if err != nil { + return err + } + + fmt.Println(string(output)) + return nil + }, + } + + cmd.Flags().String(flagProposalID, "", "proposalID of upgrade swtich being queried") + cmd.Flags().String(flagVoter, "", "Address sign the switch msg") + + return cmd +} diff --git a/client/upgrade/cli/sendtx.go b/client/upgrade/cli/sendtx.go new file mode 100644 index 000000000..97c8725ef --- /dev/null +++ b/client/upgrade/cli/sendtx.go @@ -0,0 +1,59 @@ +package cli + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/wire" + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + "github.com/irisnet/irishub/client/context" + "github.com/irisnet/irishub/client/utils" + "github.com/irisnet/irishub/modules/upgrade" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "os" +) + +const ( + flagProposalID = "proposalID" + flagTitle = "title" + flagVoter = "voter" +) + +// submit switch msg +func GetCmdSubmitSwitch(cdc *wire.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "submit-switch", + Short: "Submit a switch msg for a upgrade propsal", + RunE: func(cmd *cobra.Command, args []string) error { + title := viper.GetString(flagTitle) + proposalID := viper.GetInt64(flagProposalID) + + cliCtx := context.NewCLIContext(). + WithCodec(cdc). + WithLogger(os.Stdout). + WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc). + WithCliCtx(cliCtx) + + // get the from/to address + from, err := cliCtx.GetFromAddress() + if err != nil { + return err + } + + msg := upgrade.NewMsgSwitch(title, proposalID, from) + if err = msg.ValidateBasic(); err != nil { + return err + } + + // Build and sign the transaction, then broadcast to a Tendermint + // node. + cliCtx.PrintResponse = true + return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) + }, + } + + cmd.Flags().String(flagTitle, "", "title of switch") + cmd.Flags().String(flagProposalID, "", "proposalID of upgrade proposal") + + return cmd +} diff --git a/cmd/iriscli/main.go b/cmd/iriscli/main.go index 69cc3f5e5..48e6ee229 100644 --- a/cmd/iriscli/main.go +++ b/cmd/iriscli/main.go @@ -1,8 +1,6 @@ package main import ( - "github.com/spf13/cobra" - "github.com/tendermint/tendermint/libs/cli" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/irisnet/irishub/app" "github.com/irisnet/irishub/client" @@ -15,6 +13,8 @@ import ( tenderminttxcmd "github.com/irisnet/irishub/client/tendermint/tx" upgradecmd "github.com/irisnet/irishub/client/upgrade/cli" "github.com/irisnet/irishub/version" + "github.com/spf13/cobra" + "github.com/tendermint/tendermint/libs/cli" ) // rootCmd is the entry point for this binary @@ -73,7 +73,7 @@ func main() { govcmd.GetCmdQueryVote("gov", cdc), govcmd.GetCmdQueryVotes("gov", cdc), govcmd.GetCmdQueryGovConfig("params", cdc), - govcmd.GetCmdPullGovConfig("params", cdc), + govcmd.GetCmdPullGovConfig("params", cdc), )...) govCmd.AddCommand( client.PostCommands( @@ -123,6 +123,11 @@ func main() { upgradeCmd.AddCommand( client.GetCommands( upgradecmd.GetInfoCmd("upgrade", cdc), + upgradecmd.GetCmdQuerySwitch("upgrade", cdc), + )...) + upgradeCmd.AddCommand( + client.PostCommands( + upgradecmd.GetCmdSubmitSwitch(cdc), )...) rootCmd.AddCommand( upgradeCmd, From a0fcef503c63b4490f8b93e0a06439b443d43294 Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Thu, 27 Sep 2018 14:29:29 +0800 Subject: [PATCH 106/124] update the gov docs --- docs/zh/modules/gov/README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/zh/modules/gov/README.md b/docs/zh/modules/gov/README.md index 2763a4621..ae35da1d4 100644 --- a/docs/zh/modules/gov/README.md +++ b/docs/zh/modules/gov/README.md @@ -10,8 +10,8 @@ ### 治理流程 -1. 任何用户可以发起提议,并抵押一部分资金,如果超过`min_deposit`,提议进入投票,否则留在抵押期。其他人可以对在抵押期的提议进行抵押资金,如果提议的抵押资金总和超过`min_deposit`,则进入投票期。但是提议在抵押期停留的区块数目超过`max_deposit_period`,则提议被关闭。 -2. 进入投票期的提议,只有验证人和委托人可以进行投票,委托人如果没投票,则他继承他委托的验证人的投票选项,如果委托人投票了,则覆盖他委托的验证人的投票选项,当提议到达`voting_perid`,统计投票结果。 +1. 任何用户可以发起提议,并抵押一部分token,如果超过`min_deposit`,提议进入投票,否则留在抵押期。其他人可以对在抵押期的提议进行抵押token,如果提议的抵押token总和超过`min_deposit`,则进入投票期。但若提议在抵押期停留的出块数目超过`max_deposit_period`,则提议被关闭。 +2. 进入投票期的提议,只有验证人和委托人可以进行投票。如果委托人没投票,则他继承他委托的验证人的投票选项。如果委托人投票了,则覆盖他委托的验证人的投票选项。当提议到达`voting_perid`,统计投票结果。 3. 具体提议投票逻辑细节见[CosmosSDK-Gov-spec](https://github.com/cosmos/cosmos-sdk/blob/develop/docs/spec/governance/overview.md) ## 使用场景 @@ -138,7 +138,7 @@ iriscli gov submit-proposal --title="update MinDeposit" --description="test" --t * `--title` 提议的标题 * `--description` 提议的描述 * `--type` 提议的类型 {'Text','ParameterChange','SoftwareUpgrade'} -* `--deposit` 抵押贷币的数量 +* `--deposit` 抵押token的数量 * 上面就是典型的文本类提议 ``` @@ -146,7 +146,7 @@ iriscli gov deposit --proposal-id=1 --deposit=1iris --from=x --chain-id=gov-test ``` * `--propsal-id` 抵押提议ID -* `--deposit` 抵押的贷币数目 +* `--deposit` 抵押的token数目 ``` iriscli gov vote --proposal-id=1 --option=Yes --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 @@ -228,9 +228,9 @@ echo 1234567890 | iriscli gov submit-proposal --title="update MinDeposit" --desc * 可修改参数 * 参数的key:"Gov/gov/DepositProcedure" -* `min_deposit[0].denom` 最小抵押贷币的token只能是单位是iris-atto的iris通证。 -* `min_deposit[0].amount` 最小抵押贷币的数量,默认范围:10iris(1iris,200iris) -* `max_deposit_period` 补交抵押的窗口期,默认:10 范围(0,1) +* `min_deposit[0].denom` 最小抵押token只能是单位是iris-atto的iris通证。 +* `min_deposit[0].amount` 最小抵押token数量,默认:10iris,范围(1iris,200iris) +* `max_deposit_period` 补交抵押token的窗口期,默认:10,范围(0,1) ``` # VotingProcedure(投票阶段的参数) @@ -239,7 +239,7 @@ echo 1234567890 | iriscli gov submit-proposal --title="update MinDeposit" --desc }, ``` -* `voting_perid` 投票的窗口期,默认10,范围(20,20000) +* `voting_perid` 投票的窗口期,默认:10,范围(20,20000) ``` # TallyingProcedure (统计阶段段参数) @@ -249,9 +249,9 @@ echo 1234567890 | iriscli gov submit-proposal --title="update MinDeposit" --desc "governance_penalty": "1/100" } ``` -* `veto` 默认1/3,范围(0,1) -* `threshold` 默认1/2,范围(0,1) -* `governance_penalty` 未投票的验证人惩罚贷币的比例 默认1/100,范围(0,1) +* `veto` 默认:1/3,范围(0,1) +* `threshold` 默认:1/2,范围(0,1) +* `governance_penalty` 未投票的验证人惩罚token的比例 默认:1/100,范围(0,1) * 投票统计逻辑:如果强烈反对的voting_power占总的voting_power 超过 veto,提议不通过。然后再看赞同的voting_power占总的投票的voting_power 是否超过 veto,超过则提议不通过,不超过则不通过。 From 215e99deaf0be87b80ee10124007e359b655f2b7 Mon Sep 17 00:00:00 2001 From: shirleypyj <43328538+shirleypyj@users.noreply.github.com> Date: Thu, 27 Sep 2018 15:03:21 +0800 Subject: [PATCH 107/124] Update README.md --- docs/modules/gov/README.md | 292 ++++++++++++++++++++++++++++--------- 1 file changed, 222 insertions(+), 70 deletions(-) diff --git a/docs/modules/gov/README.md b/docs/modules/gov/README.md index 30507e2da..40f0f6242 100644 --- a/docs/modules/gov/README.md +++ b/docs/modules/gov/README.md @@ -1,105 +1,257 @@ -# Governance +# Gov/Iparam User Guide -## Initialize the runtime environment of blockchain +## Basic Function Description + +1. On-chain governance proposals on text +2. On-chain governance proposals on parameter modification +3. On-chain governance proposals on software upgrade (unavailable) + +## interactive process + +### governance process + +1. Any users can deposit some tokens to initiate a proposal. Once deposit reaches a certain value 'min_deposit`, enter voting period, otherwise it will remain in the deposit period. Others can deposit the proposals on the deposit period. Once the sum of the deposit reaches 'min_deposit`, enter voting period. However, if the block-time exceeds `max_deposit_period` in the deposit period, the proposal will be closed. +2. The proposals which enter voting period only can be voted by validators and delegators. The vote of a delegator who hasn't vote will be the same as his validator's vote, and the vote of a delegator who has voted will be remained. The votes wil be counted when reach `voting_period'. +3. More details about voting for proposals: +[CosmosSDK-Gov-spec](https://github.com/cosmos/cosmos-sdk/blob/develop/docs/spec/governance/overview.md) + +## Usage Scenario +### Create an environment ``` -rm -rf .iris +rm -rf iris rm -rf .iriscli -iris init gen-tx --name=iris -iris init --gen-txs --chain-id=gov-test -iris start - +iris init gen-tx --name=x --home=iris +iris init --gen-txs --chain-id=gov-test -o --home=iris +iris start --home=iris ``` -## Proposal process +### Usage scenario of parameter modification + +Scenario 1:Modify the parameters through the command lines -Here is an example of "parameter modification proposal". Other proposals do not need parameter "--params". For instance, sometimes we find there are a lot of useless proposals in the system, probably because the current minimum delegating amount is too small, so that many people submit meaningless ones. Here we can use "parameter modification proposal" to modify the system default minimum parameter of “delegating amount”. Firstly we need to know the value of key of this parameter before modification. The following command can be used to view: ``` -iriscli params export gov +# Query parameters can be modified by the modules'name in gov +iriscli gov query-params --module=gov --trust-node + +# Results +[ + "Gov/gov/DepositProcedure", + "Gov/gov/TallyingProcedure", + "Gov/gov/VotingProcedure" +] + +# Query parameters can be modified by "key” +iriscli gov query-params --key=Gov/gov/DepositProcedure --trust-node + +# Results +{"key":"Gov/gov/DepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":10}","op":""} + +# Send proposals, return modified parameters +echo 1234567890 | iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --param='{"key":"Gov/gov/DepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":20}","op":"update"}' --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# Deposit for a proposal +echo 1234567890 | iriscli gov deposit --proposal-id=1 --deposit=1iris --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# Vote for a proposal +echo 1234567890 | iriscli gov vote --proposal-id=1 --option=Yes --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# Query the state of a proposal +iriscli gov query-proposal --proposal-id=1 --trust-node + ``` -This command will export all the parameters that can be modified with the "parameter modification proposal". For instance, we get the following results: + +Scenario 2: Modify the parameters by the files ``` -[ - { - "key": "gov/depositprocedure/deposit", - "value": "10000000000000000000iris" - }, - { - "key": "gov/depositprocedure/maxDepositPeriod", - "value": "10" - }, - { - "key": "gov/feeToken/gasPriceThreshold", - "value": "20000000000" - }, - { - "key": "gov/tallyingprocedure/penalty", - "value": "1/100" - }, - { - "key": "gov/tallyingprocedure/threshold", - "value": "1/2" - }, - { - "key": "gov/tallyingprocedure/veto", - "value": "1/3" - }, - { - "key": "gov/votingprocedure/votingPeriod", - "value": "20" +# Export profiles +iriscli gov pull-params --path=iris --trust-node + +# Query profiles' info +cat iris/config/params.json +{ + "gov": { + "Gov/gov/DepositProcedure": { + "min_deposit": [ + { + "denom": "iris-atto", + "amount": "10000000000000000000" + } + ], + "max_deposit_period": "10" + }, + "Gov/gov/VotingProcedure": { + "voting_period": "10" + }, + "Gov/gov/TallyingProcedure": { + "threshold": "1/2", + "veto": "1/3", + "governance_penalty": "1/100" + } } -] +} +# Modify profiles (TallyingProcedure的governance_penalty) +vi iris/config/params.json +{ + "gov": { + "Gov/gov/DepositProcedure": { + "min_deposit": [ + { + "denom": "iris-atto", + "amount": "10000000000000000000" + } + ], + "max_deposit_period": "10" + }, + "Gov/gov/VotingProcedure": { + "voting_period": "10" + }, + "Gov/gov/TallyingProcedure": { + "threshold": "1/2", + "veto": "1/3", + "governance_penalty": "20/100" + } + } +} + +# Modify the parameters through files, return modified parameters +echo 1234567890 | iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --path=iris --key=Gov/gov/TallyingProcedure --op=update --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# Deposit for a proposal +echo 1234567890 | iriscli gov deposit --proposal-id=1 --deposit=1iris --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# Vote for a proposal +echo 1234567890 | iriscli gov vote --proposal-id=1 --option=Yes --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# Query the state of a proposal +iriscli gov query-proposal --proposal-id=1 --trust-node +``` + +## CLI Command Details + +### Basic method of gov modules + +``` +# Text proposals +iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="Text" --deposit="10iris" --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 +``` + +* `--title` The title of a proposal +* `--description` The description of a proposal +* `--type` The type of a proposal {'Text','ParameterChange','SoftwareUpgrade'} +* `--deposit` The number of the tokens deposited +* The basic text proposals are as below + +``` +iriscli gov deposit --proposal-id=1 --deposit=1iris --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 +``` +* `--propsal-id` The ID of the proposal deposited +* `--deposit` The number of the tokens deposited + +``` +iriscli gov vote --proposal-id=1 --option=Yes --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 ``` -Each (key, value) is corresponding to a set of system-preset modifiable parameters, the specific meaning of which will be updated in future documents. The key of minimum delegating amount here is gov/depositprocedure/deposit. At present, value=10000000000000000000iris(This is the value after the decimal-binary conversion, refering to the “fee-token” module for details.). To raise the threshold of proposals, it will be doubled to 20000000000000000000iris. The following command can be used: + +* `--proposal-id` The ID of the proposal deposited +* `--option` Vote option{'Yes'-agree,'Abstain'-abstain,'No'-disagree,'nowithVeto'-strongly disagree } + + +``` +# Query the state of a proposal +iriscli gov query-proposal --proposal-id=1 --trust-node +``` + +* `--proposal-id` Query the ID of a proposal + + + +### The proposals on parameters modification ``` -iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" - --deposit="9000000000000000000iris" - --params='[{"key":"gov/depositprocedure/deposit","value":"20000000000000000001iris","op":"update"}]' - --proposer=faa1pkunlumfyglqd9dgup0mwp66kjrp6y09twmuvd - --from=iris - --chain-id=gov-test - --fee=400000000000000iris - --gas=20000 +# Query parameters can be modified by the modules'name in gov +iriscli gov query-params --module=gov --trust-node +``` + +* `--module` Query the list of "key" of the parameters can be modified in the module + +``` +# Query the parameters can be modified by "key" +iriscli gov query-params --key=Gov/gov/DepositProcedure --trust-node ``` -Here I delegate 9000000000000000000iris, which is 1000000000000000000iris less than the minimum delegating amount, so the proposal has not been activated can not be voted. 10000000000000000000 more iris should be delegated in 10 (key:gov/depositprocedure/maxDepositPeriod) blocks (If it needs 5s to produce a block, it means you need to complete the delegation in 5 * 10s). The delegating command is as follows: +* `--key` Query the parameter corresponding to the "key" ``` -iriscli gov deposit --proposalID=1 - --depositer=faa1pkunlumfyglqd9dgup0mwp66kjrp6y09twmuvd - --deposit=1000000000000000000iris - --from=iris - --chain-id=gov-test - --fee=200000000000000iris - --gas=20000 +# Export profiles +iriscli gov pull-params --path=iris --trust-node +``` + +* `--path` The folder of node initialization + + ``` -The above proposalID is the result from the first step. At this stage, we delegate 1000000000000000000iris tokens, which is exactly equal to the minimum delegating amount, so the proposal can be voted. And the proposer can send a voting request to each validators (currently only off-chain notification is available, but on-chain or monitoring notification will be implemented later). Then each validators can view the proposal first with the following command: +# Modify the parameters through the command lines +iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --param='{"key":"Gov/gov/DepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":20}","op":"update"}' --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 +``` + +* `--param` The details of modified parameters (get parameters through query-params, modify it and then add "update" on the "op", more details in usage scenarios) +* Other fields' proposals are similar with text proposal ``` -iriscli gov query-proposal --proposalID=1 +# Modify the parameters through files, return modified parameters +echo 1234567890 | iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --path=iris --key=Gov/gov/TallyingProcedure --op=update --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 ``` -Later proposers can vote as they wish, here I vote Yes (option=Yes): +* `--path` The folder of node initialization +* `--key` The key of the parameter to be modified +* `--op` The type of modified parameters; only 'update' is implemented at present +* Other fields' proposals are similar with text proposal + +### Proposals on software upgrade + +## Basic parameters ``` -iriscli gov vote --proposalID=1 - --voter=faa1pkunlumfyglqd9dgup0mwp66kjrp6y09twmuvd - --option=Yes - --from=iris - --chain-id=gov-test - --fee=400000000000000iris - --gas=20000 +# DepositProcedure(The parameters in deposit period) +"Gov/gov/DepositProcedure": { + "min_deposit": [ + { + "denom": "iris-atto", + "amount": "10000000000000000000" + } + ], + "max_deposit_period": "10" +} ``` -Notice that the maximum of waiting time is in 20 blocks during the voting period (key: gov/votingprocedure/votingPeriod). If the percentage of affirmative vote is still less than 50% during this period (key: gov/tallyingprocedure/threshold), the proposal will not be passed and the tokens delegated will also not be refunded (the validators haven't voted will be slashed, and 1/100 of the total tokens delegated currently will be deducted (key: gov/tallyingprocedure/penalty). This mechanism has not been implemented in current version ). Suppose there is only one validator. If I voted yes, the ratio of affirmative vote is 1>1/2 and the strong negative vote is 0<1/3 (key:gov/tallyingprocedure/veto), the proposal will be passed. After voting, the proposal is automatically executed: (key: gov/depositprocedure/deposit, value: 10000000000000000000iris) is modified to (key: gov/depositprocedure/deposit, value: 20000000000000000000iris). Then we can verify this result and query the minimum delegating amount in current system: +* Parameters can be modified +* The key of parameters:"Gov/gov/DepositProcedure" +* `min_deposit[0].denom` The minimum tokens deposited are counted by iris-atto. +* `min_deposit[0].amount` The number of minimum tokens and the default scope:10iris,(1iris,200iris) +* `max_deposit_period` Window period for repaying deposit, default :10, scope(0,1) ``` -iriscli iriscli params export gov/depositprocedure/deposit +# VotingProcedure(The parameters in voting period) +"Gov/gov/VotingProcedure": { + "voting_period": "10" +}, +``` + +* `voting_perid` Window period for vote, default:10, scope(20,20000) + ``` +# TallyingProcedure (The parameters in counting period) +"Gov/gov/TallyingProcedure": { + "threshold": "1/2", + "veto": "1/3", + "governance_penalty": "1/100" +} +``` +* `veto` default: 1/3, scope(0,1) +* `threshold` default 1/2, scope(0,1) +* `governance_penalty` The default ratio of slashing tokens of validators who didn't vote: 1/100, scope(0,1) +* Vote rules: If the ratio of voting_power of "strongly disagree" over "veto", the proposal won't be passed. If the ratio of voting_power of "agree" over "veto", the proposal won't be passed. Otherwise, it will be passed. -This is the end of the governance process. From 769e9348a264de7d82f3f20e22c3ebfc69cbc686 Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Thu, 27 Sep 2018 15:44:29 +0800 Subject: [PATCH 108/124] add gov docs (English ver.) --- docs/modules/gov/README.md | 43 +++++++++++++++++-------------- docs/zh/modules/upgrade/README.md | 22 ++++++++++++++++ 2 files changed, 45 insertions(+), 20 deletions(-) create mode 100644 docs/zh/modules/upgrade/README.md diff --git a/docs/modules/gov/README.md b/docs/modules/gov/README.md index 40f0f6242..3fc2c3e47 100644 --- a/docs/modules/gov/README.md +++ b/docs/modules/gov/README.md @@ -3,15 +3,15 @@ ## Basic Function Description 1. On-chain governance proposals on text -2. On-chain governance proposals on parameter modification +2. On-chain governance proposals on parameter change 3. On-chain governance proposals on software upgrade (unavailable) -## interactive process +## Interactive process ### governance process -1. Any users can deposit some tokens to initiate a proposal. Once deposit reaches a certain value 'min_deposit`, enter voting period, otherwise it will remain in the deposit period. Others can deposit the proposals on the deposit period. Once the sum of the deposit reaches 'min_deposit`, enter voting period. However, if the block-time exceeds `max_deposit_period` in the deposit period, the proposal will be closed. -2. The proposals which enter voting period only can be voted by validators and delegators. The vote of a delegator who hasn't vote will be the same as his validator's vote, and the vote of a delegator who has voted will be remained. The votes wil be counted when reach `voting_period'. +1. Any users can deposit some tokens to initiate a proposal. Once deposit reaches a certain value `min_deposit`, enter voting period, otherwise it will remain in the deposit period. Others can deposit the proposals on the deposit period. Once the sum of the deposit reaches `min_deposit`, enter voting period. However, if the block-time exceeds `max_deposit_period` in the deposit period, the proposal will be closed. +2. The proposals which enter voting period only can be voted by validators and delegators. The vote of a delegator who hasn't vote will be the same as his validator's vote, and the vote of a delegator who has voted will be remained. The votes wil be tallyed when reach `voting_period'. 3. More details about voting for proposals: [CosmosSDK-Gov-spec](https://github.com/cosmos/cosmos-sdk/blob/develop/docs/spec/governance/overview.md) @@ -26,12 +26,12 @@ iris init --gen-txs --chain-id=gov-test -o --home=iris iris start --home=iris ``` -### Usage scenario of parameter modification +### Usage scenario of parameter change -Scenario 1:Modify the parameters through the command lines +Scenario 1:Change the parameters through the command lines ``` -# Query parameters can be modified by the modules'name in gov +# Query parameters can be changed by the modules'name in gov iriscli gov query-params --module=gov --trust-node # Results @@ -47,7 +47,7 @@ iriscli gov query-params --key=Gov/gov/DepositProcedure --trust-node # Results {"key":"Gov/gov/DepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":10}","op":""} -# Send proposals, return modified parameters +# Send proposals, return changed parameters echo 1234567890 | iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --param='{"key":"Gov/gov/DepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":20}","op":"update"}' --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 # Deposit for a proposal @@ -61,7 +61,7 @@ iriscli gov query-proposal --proposal-id=1 --trust-node ``` -Scenario 2: Modify the parameters by the files +Scenario 2: Change the parameters by the files ``` # Export profiles @@ -114,7 +114,7 @@ vi iris/config/params.json } } -# Modify the parameters through files, return modified parameters +# Change the parameters through files, return changed parameters echo 1234567890 | iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --path=iris --key=Gov/gov/TallyingProcedure --op=update --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 # Deposit for a proposal @@ -153,7 +153,7 @@ iriscli gov deposit --proposal-id=1 --deposit=1iris --from=x --chain-id=gov-test iriscli gov vote --proposal-id=1 --option=Yes --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 ``` -* `--proposal-id` The ID of the proposal deposited +* `--proposal-id` The ID of the proposal in voting period * `--option` Vote option{'Yes'-agree,'Abstain'-abstain,'No'-disagree,'nowithVeto'-strongly disagree } @@ -173,7 +173,7 @@ iriscli gov query-proposal --proposal-id=1 --trust-node iriscli gov query-params --module=gov --trust-node ``` -* `--module` Query the list of "key" of the parameters can be modified in the module +* `--module` Query the list of "key" of the parameters can be changed in the module ``` @@ -197,17 +197,17 @@ iriscli gov pull-params --path=iris --trust-node iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --param='{"key":"Gov/gov/DepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":20}","op":"update"}' --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 ``` -* `--param` The details of modified parameters (get parameters through query-params, modify it and then add "update" on the "op", more details in usage scenarios) +* `--param` The details of changed parameters (get parameters through query-params, modify it and then add "update" on the "op", more details in usage scenarios) * Other fields' proposals are similar with text proposal ``` -# Modify the parameters through files, return modified parameters +# Change the parameters through files, return modified parameters echo 1234567890 | iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --path=iris --key=Gov/gov/TallyingProcedure --op=update --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 ``` * `--path` The folder of node initialization * `--key` The key of the parameter to be modified -* `--op` The type of modified parameters; only 'update' is implemented at present +* `--op` The type of changed parameters; only 'update' is implemented at present * Other fields' proposals are similar with text proposal ### Proposals on software upgrade @@ -227,7 +227,7 @@ echo 1234567890 | iriscli gov submit-proposal --title="update MinDeposit" --desc } ``` -* Parameters can be modified +* Parameters can be changed * The key of parameters:"Gov/gov/DepositProcedure" * `min_deposit[0].denom` The minimum tokens deposited are counted by iris-atto. * `min_deposit[0].amount` The number of minimum tokens and the default scope:10iris,(1iris,200iris) @@ -239,19 +239,22 @@ echo 1234567890 | iriscli gov submit-proposal --title="update MinDeposit" --desc "voting_period": "10" }, ``` - + +* Parameters can be changed * `voting_perid` Window period for vote, default:10, scope(20,20000) ``` -# TallyingProcedure (The parameters in counting period) +# TallyingProcedure (The parameters in Tallying period) "Gov/gov/TallyingProcedure": { "threshold": "1/2", "veto": "1/3", "governance_penalty": "1/100" } -``` +``` + +* Parameters can be changed * `veto` default: 1/3, scope(0,1) * `threshold` default 1/2, scope(0,1) * `governance_penalty` The default ratio of slashing tokens of validators who didn't vote: 1/100, scope(0,1) -* Vote rules: If the ratio of voting_power of "strongly disagree" over "veto", the proposal won't be passed. If the ratio of voting_power of "agree" over "veto", the proposal won't be passed. Otherwise, it will be passed. +* Vote rules: If the ratio of voting power of "strongly disagree" over "veto", the proposal won't be passed. If the ratio of voting_power of "agree" over "veto", the proposal won't be passed. Otherwise, it will be passed. diff --git a/docs/zh/modules/upgrade/README.md b/docs/zh/modules/upgrade/README.md new file mode 100644 index 000000000..fb5f2d399 --- /dev/null +++ b/docs/zh/modules/upgrade/README.md @@ -0,0 +1,22 @@ +# Upgrade User Guide + +## 基本功能描述 + +该模块支持区块链软件平滑升级的基础设施,通过UpgradeProposal和switch两阶段的投票来在约定高度切换到新版的代码,并对历史版本的链上数据完全兼容。 +## 交互流程 + +### 软件升级提议治理流程 +1. 用户提交升级软件提议 +2. 治理流程详细见[]() +3. +### 升级软件流程 +1. 用户安装新软件,并发送switch消息,广播全网自己已经安装新软件。 +2. + +## 使用场景 + +iriscli upgrade submit-switch --name=x --from=$VADDR --proposalID=1 --chain-id=upgrade-test --fee=20000000000000000iris + +iris start --replay + +## 命令详情 \ No newline at end of file From bde0e4af2520a0270ab14d4e69d473c6842ed7e7 Mon Sep 17 00:00:00 2001 From: Raymond Date: Thu, 27 Sep 2018 15:55:18 +0800 Subject: [PATCH 109/124] IRISHUB-474: refactor upgrade examples --- examples/irishub-bugfix-2/app/app.go | 10 +- examples/irishub-bugfix-2/app/context.go | 3 +- examples/irishub-bugfix-2/app/genesis.go | 22 ++-- .../cmd/iris-bugfix-2/main.go | 2 +- .../cmd/iriscli-bugfix-2/main.go | 8 +- .../ibc/client/rest/transfer.go | 103 ------------------ examples/irishub-bugfix-3/app/app.go | 17 ++- examples/irishub-bugfix-3/app/context.go | 3 +- examples/irishub-bugfix-3/app/genesis.go | 22 ++-- .../cmd/iris-bugfix-3/main.go | 2 +- .../cmd/iriscli-bugfix-3/main.go | 8 +- .../ibc/client/rest/transfer.go | 103 ------------------ examples/irishub1/app/app.go | 36 +++--- examples/irishub1/app/context.go | 3 +- examples/irishub1/app/genesis.go | 22 ++-- examples/irishub1/cmd/iris1/main.go | 2 +- examples/irishub1/cmd/iriscli1/main.go | 8 +- examples/irishub1/ibc/client/rest/transfer.go | 103 ------------------ examples/irishub2/app/app.go | 10 +- examples/irishub2/app/context.go | 3 +- examples/irishub2/app/genesis.go | 22 ++-- examples/irishub2/cmd/iris2/main.go | 2 +- examples/irishub2/cmd/iriscli2/main.go | 8 +- examples/irishub2/ibc/client/rest/transfer.go | 103 ------------------ 24 files changed, 95 insertions(+), 530 deletions(-) delete mode 100644 examples/irishub-bugfix-2/ibc/client/rest/transfer.go delete mode 100644 examples/irishub-bugfix-3/ibc/client/rest/transfer.go delete mode 100644 examples/irishub1/ibc/client/rest/transfer.go delete mode 100644 examples/irishub2/ibc/client/rest/transfer.go diff --git a/examples/irishub-bugfix-2/app/app.go b/examples/irishub-bugfix-2/app/app.go index bef4cac0e..cbcae978c 100644 --- a/examples/irishub-bugfix-2/app/app.go +++ b/examples/irishub-bugfix-2/app/app.go @@ -33,7 +33,6 @@ import ( sm "github.com/tendermint/tendermint/state" bc "github.com/tendermint/tendermint/blockchain" "strings" - "github.com/irisnet/irishub/modules/iparams" ) const ( @@ -74,7 +73,6 @@ type IrisApp struct { govKeeper gov.Keeper paramsKeeper params.Keeper upgradeKeeper upgrade.Keeper - iparamsKeeper iparams.Keeper // fee manager @@ -124,7 +122,7 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.paramsKeeper.Getter(), app.RegisterCodespace(slashing.DefaultCodespace)) app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection) - app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper, app.iparamsKeeper.Setter()) + app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper) app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) //app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) @@ -139,7 +137,7 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake, app.keyParams}, gov.NewHandler(app.govKeeper)). AddRoute("upgrade", []*sdk.KVStoreKey{app.keyUpgrade, app.keyStake}, upgrade.NewHandler(app.upgradeKeeper)) - app.feeManager = bam.NewFeeManager(app.iparamsKeeper.Getter()) + app.feeManager = bam.NewFeeManager(app.paramsKeeper.Setter()) // initialize BaseApp app.SetInitChainer(app.initChainer) @@ -226,7 +224,7 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci panic(err) } - minDeposit,err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s",10,denom)) + minDeposit,err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s",10,Denom)) if err != nil { panic(err) } @@ -252,7 +250,7 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci GasPriceThreshold: 20000000000, // 20(glue), 20*10^9, 1 glue = 10^9 lue/gas, 1 iris = 10^18 lue } - bam.InitGenesis(ctx, app.iparamsKeeper.Setter(), feeTokenGensisConfig) + bam.InitGenesis(ctx, app.paramsKeeper.Setter(), feeTokenGensisConfig) // load the address to pubkey map slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.StakeData) diff --git a/examples/irishub-bugfix-2/app/context.go b/examples/irishub-bugfix-2/app/context.go index 4e882be76..adc073942 100644 --- a/examples/irishub-bugfix-2/app/context.go +++ b/examples/irishub-bugfix-2/app/context.go @@ -16,7 +16,6 @@ import ( "strings" ) -//TODO 以后需要重构,现在有点乱 type Context struct { context.CLIContext txCtx txcxt.TxContext @@ -88,7 +87,7 @@ func (c Context) NumUnconfirmedTxs() (*ctypes.ResultUnconfirmedTxs, error) { func (c Context) GetCoinType(coinName string) (types.CoinType, error) { var coinType types.CoinType coinName = strings.ToLower(coinName) - if coinName == denom { + if coinName == Denom { coinType = IrisCt } else { key := types.CoinTypeKey(coinName) diff --git a/examples/irishub-bugfix-2/app/genesis.go b/examples/irishub-bugfix-2/app/genesis.go index 30a7a2b52..db61f2009 100644 --- a/examples/irishub-bugfix-2/app/genesis.go +++ b/examples/irishub-bugfix-2/app/genesis.go @@ -8,15 +8,15 @@ import ( "github.com/tendermint/tendermint/crypto" tmtypes "github.com/tendermint/tendermint/types" + "fmt" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/config" 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" - "time" "github.com/irisnet/irishub/types" - "fmt" + "time" ) // State to Unmarshal @@ -54,13 +54,13 @@ func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { } var ( - flagName = "name" - flagClientHome = "home-client" - flagOWK = "owk" - denom = "iris" - feeAmt = int64(100) - IrisCt = types.NewDefaultCoinType(denom) - freeFermionVal ,_ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s",feeAmt,denom)) + flagName = "name" + flagClientHome = "home-client" + flagOWK = "owk" + Denom = "iris" + feeAmt = int64(100) + IrisCt = types.NewDefaultCoinType(Denom) + freeFermionVal, _ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", feeAmt, Denom)) ) const defaultUnbondingTime time.Duration = 60 * 10 * time.Second @@ -176,7 +176,7 @@ func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState // add some new shares to the validator var issuedDelShares sdk.Rat - validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, feeAmt) + validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, freeFermionVal.Amount) //validator.TokenPrecision = stakeData.Params.DenomPrecision stakeData.Validators = append(stakeData.Validators, validator) @@ -229,7 +229,7 @@ func createGenesisState() stake.GenesisState { GoalBonded: sdk.NewRat(67, 100), UnbondingTime: defaultUnbondingTime, MaxValidators: 100, - BondDenom: denom, + BondDenom: Denom + "-" + types.Atto, }, } } diff --git a/examples/irishub-bugfix-2/cmd/iris-bugfix-2/main.go b/examples/irishub-bugfix-2/cmd/iris-bugfix-2/main.go index 9f1a15370..0a199f50c 100644 --- a/examples/irishub-bugfix-2/cmd/iris-bugfix-2/main.go +++ b/examples/irishub-bugfix-2/cmd/iris-bugfix-2/main.go @@ -54,7 +54,7 @@ func main() { tendermintCmd, server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), client.LineBreak, - version.GetCmdVersion("upgrade", cdc), + version.ServeVersionCommand(cdc), ) rootCmd.AddCommand(prometheus.MonitorCommand(cdc)) diff --git a/examples/irishub-bugfix-2/cmd/iriscli-bugfix-2/main.go b/examples/irishub-bugfix-2/cmd/iriscli-bugfix-2/main.go index 270936088..49b94f6a1 100644 --- a/examples/irishub-bugfix-2/cmd/iriscli-bugfix-2/main.go +++ b/examples/irishub-bugfix-2/cmd/iriscli-bugfix-2/main.go @@ -15,9 +15,8 @@ import ( slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" "github.com/irisnet/irishub/examples/irishub-bugfix-2/app" - c "github.com/irisnet/irishub/client/lcd" govcmd "github.com/cosmos/cosmos-sdk/x/gov/client/cli" - upgradecmd "github.com/irisnet/irishub/client/cli/upgrade" + upgradecmd "github.com/irisnet/irishub/client/upgrade/cli" "github.com/irisnet/irishub/version" ) @@ -71,7 +70,6 @@ func main() { advancedCmd.AddCommand( tendermintCmd, ibcCmd, - c.ServeCommand(cdc), ) rootCmd.AddCommand( advancedCmd, @@ -132,7 +130,7 @@ func main() { upgradeCmd.AddCommand( client.GetCommands( upgradecmd.GetCmdQuerySwitch("upgrade", cdc), - upgradecmd.GetCmdInfo("upgrade", cdc), + upgradecmd.GetInfoCmd("upgrade", cdc), )...) upgradeCmd.AddCommand( client.PostCommands( @@ -159,7 +157,7 @@ func main() { ) rootCmd.AddCommand( client.GetCommands( - version.GetCmdVersion("upgrade", cdc), + version.ServeVersionCommand(cdc), )...) // prepare and add flags diff --git a/examples/irishub-bugfix-2/ibc/client/rest/transfer.go b/examples/irishub-bugfix-2/ibc/client/rest/transfer.go deleted file mode 100644 index bee9f955f..000000000 --- a/examples/irishub-bugfix-2/ibc/client/rest/transfer.go +++ /dev/null @@ -1,103 +0,0 @@ -package rest - -import ( - "io/ioutil" - "net/http" - - "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/gorilla/mux" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/ibc" -) - -// RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { - r.HandleFunc("/ibc/{destchain}/{address}/send", TransferRequestHandlerFn(cdc, kb, ctx)).Methods("POST") -} - -type transferBody struct { - // Fees sdk.Coin `json="fees"` - Amount sdk.Coins `json:"amount"` - LocalAccountName string `json:"name"` - Password string `json:"password"` - SrcChainID string `json:"src_chain_id"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` - Gas int64 `json:"gas"` -} - -// TransferRequestHandler - http request handler to transfer coins to a address -// on a different chain via IBC -func TransferRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - // collect data - vars := mux.Vars(r) - destChainID := vars["destchain"] - bech32addr := vars["address"] - - to, err := sdk.AccAddressFromBech32(bech32addr) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - var m transferBody - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - err = cdc.UnmarshalJSON(body, &m) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - info, err := kb.Get(m.LocalAccountName) - if err != nil { - w.WriteHeader(http.StatusUnauthorized) - w.Write([]byte(err.Error())) - return - } - - // build message - packet := ibc.NewIBCPacket(sdk.AccAddress(info.GetPubKey().Address()), to, m.Amount, m.SrcChainID, destChainID) - msg := ibc.IBCTransferMsg{packet} - - // add gas to context - ctx = ctx.WithGas(m.Gas) - - // sign - ctx = ctx.WithAccountNumber(m.AccountNumber) - ctx = ctx.WithSequence(m.Sequence) - 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 - } - - // send - res, err := ctx.BroadcastTx(txBytes) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - output, err := cdc.MarshalJSON(res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - w.Write(output) - } -} diff --git a/examples/irishub-bugfix-3/app/app.go b/examples/irishub-bugfix-3/app/app.go index 7c8b0857c..1c434c2bf 100644 --- a/examples/irishub-bugfix-3/app/app.go +++ b/examples/irishub-bugfix-3/app/app.go @@ -28,12 +28,11 @@ import ( "fmt" "github.com/cosmos/cosmos-sdk/server" "github.com/spf13/viper" + bc "github.com/tendermint/tendermint/blockchain" tmcli "github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/node" sm "github.com/tendermint/tendermint/state" - bc "github.com/tendermint/tendermint/blockchain" "strings" - "github.com/irisnet/irishub/modules/iparams" ) const ( @@ -74,11 +73,9 @@ type IrisApp struct { govKeeper gov.Keeper paramsKeeper params.Keeper upgradeKeeper upgrade.Keeper - iparamsKeeper iparams.Keeper - // fee manager - feeManager bam.FeeManager + feeManager bam.FeeManager } func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptions ...func(*bam.BaseApp)) *IrisApp { @@ -124,7 +121,7 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.paramsKeeper.Getter(), app.RegisterCodespace(slashing.DefaultCodespace)) app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection) - app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper, app.iparamsKeeper.Setter()) + app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper) app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) //app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) @@ -139,7 +136,7 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake, app.keyParams}, gov.NewHandler(app.govKeeper)). AddRoute("upgrade", []*sdk.KVStoreKey{app.keyUpgrade, app.keyStake}, upgrade.NewHandler(app.upgradeKeeper)) - app.feeManager = bam.NewFeeManager(app.iparamsKeeper.Getter()) + app.feeManager = bam.NewFeeManager(app.paramsKeeper.Setter()) // initialize BaseApp app.SetInitChainer(app.initChainer) @@ -226,7 +223,7 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci panic(err) } - minDeposit,err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s",10,denom)) + minDeposit, err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", 10, Denom)) if err != nil { panic(err) } @@ -252,7 +249,7 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci GasPriceThreshold: 20000000000, // 20(glue), 20*10^9, 1 glue = 10^9 lue/gas, 1 iris = 10^18 lue } - bam.InitGenesis(ctx, app.iparamsKeeper.Setter(), feeTokenGensisConfig) + bam.InitGenesis(ctx, app.paramsKeeper.Setter(), feeTokenGensisConfig) // load the address to pubkey map slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.StakeData) @@ -356,7 +353,7 @@ func (app *IrisApp) replay() int64 { defer func() { stateDB.Close() blockStoreDB.Close() - } () + }() curState := sm.LoadState(stateDB) preState := sm.LoadPreState(stateDB) diff --git a/examples/irishub-bugfix-3/app/context.go b/examples/irishub-bugfix-3/app/context.go index 4e882be76..adc073942 100644 --- a/examples/irishub-bugfix-3/app/context.go +++ b/examples/irishub-bugfix-3/app/context.go @@ -16,7 +16,6 @@ import ( "strings" ) -//TODO 以后需要重构,现在有点乱 type Context struct { context.CLIContext txCtx txcxt.TxContext @@ -88,7 +87,7 @@ func (c Context) NumUnconfirmedTxs() (*ctypes.ResultUnconfirmedTxs, error) { func (c Context) GetCoinType(coinName string) (types.CoinType, error) { var coinType types.CoinType coinName = strings.ToLower(coinName) - if coinName == denom { + if coinName == Denom { coinType = IrisCt } else { key := types.CoinTypeKey(coinName) diff --git a/examples/irishub-bugfix-3/app/genesis.go b/examples/irishub-bugfix-3/app/genesis.go index 30a7a2b52..db61f2009 100644 --- a/examples/irishub-bugfix-3/app/genesis.go +++ b/examples/irishub-bugfix-3/app/genesis.go @@ -8,15 +8,15 @@ import ( "github.com/tendermint/tendermint/crypto" tmtypes "github.com/tendermint/tendermint/types" + "fmt" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/config" 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" - "time" "github.com/irisnet/irishub/types" - "fmt" + "time" ) // State to Unmarshal @@ -54,13 +54,13 @@ func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { } var ( - flagName = "name" - flagClientHome = "home-client" - flagOWK = "owk" - denom = "iris" - feeAmt = int64(100) - IrisCt = types.NewDefaultCoinType(denom) - freeFermionVal ,_ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s",feeAmt,denom)) + flagName = "name" + flagClientHome = "home-client" + flagOWK = "owk" + Denom = "iris" + feeAmt = int64(100) + IrisCt = types.NewDefaultCoinType(Denom) + freeFermionVal, _ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", feeAmt, Denom)) ) const defaultUnbondingTime time.Duration = 60 * 10 * time.Second @@ -176,7 +176,7 @@ func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState // add some new shares to the validator var issuedDelShares sdk.Rat - validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, feeAmt) + validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, freeFermionVal.Amount) //validator.TokenPrecision = stakeData.Params.DenomPrecision stakeData.Validators = append(stakeData.Validators, validator) @@ -229,7 +229,7 @@ func createGenesisState() stake.GenesisState { GoalBonded: sdk.NewRat(67, 100), UnbondingTime: defaultUnbondingTime, MaxValidators: 100, - BondDenom: denom, + BondDenom: Denom + "-" + types.Atto, }, } } diff --git a/examples/irishub-bugfix-3/cmd/iris-bugfix-3/main.go b/examples/irishub-bugfix-3/cmd/iris-bugfix-3/main.go index 866aab121..9755d3b11 100644 --- a/examples/irishub-bugfix-3/cmd/iris-bugfix-3/main.go +++ b/examples/irishub-bugfix-3/cmd/iris-bugfix-3/main.go @@ -54,7 +54,7 @@ func main() { tendermintCmd, server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), client.LineBreak, - version.GetCmdVersion("upgrade", cdc), + version.ServeVersionCommand(cdc), ) rootCmd.AddCommand(prometheus.MonitorCommand(cdc)) diff --git a/examples/irishub-bugfix-3/cmd/iriscli-bugfix-3/main.go b/examples/irishub-bugfix-3/cmd/iriscli-bugfix-3/main.go index 99a1eb582..a080f4edc 100644 --- a/examples/irishub-bugfix-3/cmd/iriscli-bugfix-3/main.go +++ b/examples/irishub-bugfix-3/cmd/iriscli-bugfix-3/main.go @@ -15,9 +15,8 @@ import ( slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" "github.com/irisnet/irishub/examples/irishub-bugfix-3/app" - c "github.com/irisnet/irishub/client/lcd" govcmd "github.com/cosmos/cosmos-sdk/x/gov/client/cli" - upgradecmd "github.com/irisnet/irishub/client/cli/upgrade" + upgradecmd "github.com/irisnet/irishub/client/upgrade/cli" "github.com/irisnet/irishub/version" ) @@ -71,7 +70,6 @@ func main() { advancedCmd.AddCommand( tendermintCmd, ibcCmd, - c.ServeCommand(cdc), ) rootCmd.AddCommand( advancedCmd, @@ -132,7 +130,7 @@ func main() { upgradeCmd.AddCommand( client.GetCommands( upgradecmd.GetCmdQuerySwitch("upgrade", cdc), - upgradecmd.GetCmdInfo("upgrade", cdc), + upgradecmd.GetInfoCmd("upgrade", cdc), )...) upgradeCmd.AddCommand( client.PostCommands( @@ -159,7 +157,7 @@ func main() { ) rootCmd.AddCommand( client.GetCommands( - version.GetCmdVersion("upgrade", cdc), + version.ServeVersionCommand(cdc), )...) // prepare and add flags diff --git a/examples/irishub-bugfix-3/ibc/client/rest/transfer.go b/examples/irishub-bugfix-3/ibc/client/rest/transfer.go deleted file mode 100644 index bee9f955f..000000000 --- a/examples/irishub-bugfix-3/ibc/client/rest/transfer.go +++ /dev/null @@ -1,103 +0,0 @@ -package rest - -import ( - "io/ioutil" - "net/http" - - "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/gorilla/mux" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/ibc" -) - -// RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { - r.HandleFunc("/ibc/{destchain}/{address}/send", TransferRequestHandlerFn(cdc, kb, ctx)).Methods("POST") -} - -type transferBody struct { - // Fees sdk.Coin `json="fees"` - Amount sdk.Coins `json:"amount"` - LocalAccountName string `json:"name"` - Password string `json:"password"` - SrcChainID string `json:"src_chain_id"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` - Gas int64 `json:"gas"` -} - -// TransferRequestHandler - http request handler to transfer coins to a address -// on a different chain via IBC -func TransferRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - // collect data - vars := mux.Vars(r) - destChainID := vars["destchain"] - bech32addr := vars["address"] - - to, err := sdk.AccAddressFromBech32(bech32addr) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - var m transferBody - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - err = cdc.UnmarshalJSON(body, &m) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - info, err := kb.Get(m.LocalAccountName) - if err != nil { - w.WriteHeader(http.StatusUnauthorized) - w.Write([]byte(err.Error())) - return - } - - // build message - packet := ibc.NewIBCPacket(sdk.AccAddress(info.GetPubKey().Address()), to, m.Amount, m.SrcChainID, destChainID) - msg := ibc.IBCTransferMsg{packet} - - // add gas to context - ctx = ctx.WithGas(m.Gas) - - // sign - ctx = ctx.WithAccountNumber(m.AccountNumber) - ctx = ctx.WithSequence(m.Sequence) - 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 - } - - // send - res, err := ctx.BroadcastTx(txBytes) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - output, err := cdc.MarshalJSON(res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - w.Write(output) - } -} diff --git a/examples/irishub1/app/app.go b/examples/irishub1/app/app.go index 80d8f08ef..76073eb37 100644 --- a/examples/irishub1/app/app.go +++ b/examples/irishub1/app/app.go @@ -5,13 +5,9 @@ import ( "io" "os" - bam "github.com/irisnet/irishub/baseapp" - abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - + "errors" + "fmt" + "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/auth" @@ -21,19 +17,20 @@ import ( "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/stake" + bam "github.com/irisnet/irishub/baseapp" ibc1 "github.com/irisnet/irishub/examples/irishub1/ibc" "github.com/irisnet/irishub/modules/upgrade" - - "errors" - "fmt" - "github.com/cosmos/cosmos-sdk/server" "github.com/spf13/viper" + abci "github.com/tendermint/tendermint/abci/types" + bc "github.com/tendermint/tendermint/blockchain" tmcli "github.com/tendermint/tendermint/libs/cli" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/node" sm "github.com/tendermint/tendermint/state" - bc "github.com/tendermint/tendermint/blockchain" + tmtypes "github.com/tendermint/tendermint/types" "strings" - "github.com/irisnet/irishub/modules/iparams" ) const ( @@ -74,10 +71,9 @@ type IrisApp struct { govKeeper gov.Keeper paramsKeeper params.Keeper upgradeKeeper upgrade.Keeper - iparamsKeeper iparams.Keeper // fee manager - feeManager bam.FeeManager + feeManager bam.FeeManager } func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptions ...func(*bam.BaseApp)) *IrisApp { @@ -121,7 +117,7 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.paramsKeeper.Getter(), app.RegisterCodespace(slashing.DefaultCodespace)) app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection) - app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper, app.iparamsKeeper.Setter()) + app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper) app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) //app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) @@ -136,7 +132,7 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake, app.keyParams}, gov.NewHandler(app.govKeeper)). AddRoute("upgrade", []*sdk.KVStoreKey{app.keyUpgrade, app.keyStake}, upgrade.NewHandler(app.upgradeKeeper)) - app.feeManager = bam.NewFeeManager(app.iparamsKeeper.Getter()) + app.feeManager = bam.NewFeeManager(app.paramsKeeper.Setter()) // initialize BaseApp app.SetInitChainer(app.initChainer) @@ -224,7 +220,7 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci panic(err) } - minDeposit,err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s",10,denom)) + minDeposit, err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", 10, Denom)) if err != nil { panic(err) } @@ -250,7 +246,7 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci GasPriceThreshold: 20000000000, // 20(glue), 20*10^9, 1 glue = 10^9 lue/gas, 1 iris = 10^18 lue } - bam.InitGenesis(ctx, app.iparamsKeeper.Setter(), feeTokenGensisConfig) + bam.InitGenesis(ctx, app.paramsKeeper.Setter(), feeTokenGensisConfig) // load the address to pubkey map slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.StakeData) @@ -354,7 +350,7 @@ func (app *IrisApp) replay() int64 { defer func() { stateDB.Close() blockStoreDB.Close() - } () + }() curState := sm.LoadState(stateDB) preState := sm.LoadPreState(stateDB) diff --git a/examples/irishub1/app/context.go b/examples/irishub1/app/context.go index 4e882be76..adc073942 100644 --- a/examples/irishub1/app/context.go +++ b/examples/irishub1/app/context.go @@ -16,7 +16,6 @@ import ( "strings" ) -//TODO 以后需要重构,现在有点乱 type Context struct { context.CLIContext txCtx txcxt.TxContext @@ -88,7 +87,7 @@ func (c Context) NumUnconfirmedTxs() (*ctypes.ResultUnconfirmedTxs, error) { func (c Context) GetCoinType(coinName string) (types.CoinType, error) { var coinType types.CoinType coinName = strings.ToLower(coinName) - if coinName == denom { + if coinName == Denom { coinType = IrisCt } else { key := types.CoinTypeKey(coinName) diff --git a/examples/irishub1/app/genesis.go b/examples/irishub1/app/genesis.go index 30a7a2b52..db61f2009 100644 --- a/examples/irishub1/app/genesis.go +++ b/examples/irishub1/app/genesis.go @@ -8,15 +8,15 @@ import ( "github.com/tendermint/tendermint/crypto" tmtypes "github.com/tendermint/tendermint/types" + "fmt" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/config" 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" - "time" "github.com/irisnet/irishub/types" - "fmt" + "time" ) // State to Unmarshal @@ -54,13 +54,13 @@ func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { } var ( - flagName = "name" - flagClientHome = "home-client" - flagOWK = "owk" - denom = "iris" - feeAmt = int64(100) - IrisCt = types.NewDefaultCoinType(denom) - freeFermionVal ,_ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s",feeAmt,denom)) + flagName = "name" + flagClientHome = "home-client" + flagOWK = "owk" + Denom = "iris" + feeAmt = int64(100) + IrisCt = types.NewDefaultCoinType(Denom) + freeFermionVal, _ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", feeAmt, Denom)) ) const defaultUnbondingTime time.Duration = 60 * 10 * time.Second @@ -176,7 +176,7 @@ func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState // add some new shares to the validator var issuedDelShares sdk.Rat - validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, feeAmt) + validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, freeFermionVal.Amount) //validator.TokenPrecision = stakeData.Params.DenomPrecision stakeData.Validators = append(stakeData.Validators, validator) @@ -229,7 +229,7 @@ func createGenesisState() stake.GenesisState { GoalBonded: sdk.NewRat(67, 100), UnbondingTime: defaultUnbondingTime, MaxValidators: 100, - BondDenom: denom, + BondDenom: Denom + "-" + types.Atto, }, } } diff --git a/examples/irishub1/cmd/iris1/main.go b/examples/irishub1/cmd/iris1/main.go index 3374ffdee..6b1618d69 100644 --- a/examples/irishub1/cmd/iris1/main.go +++ b/examples/irishub1/cmd/iris1/main.go @@ -54,7 +54,7 @@ func main() { tendermintCmd, server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), client.LineBreak, - version.GetCmdVersion("upgrade", cdc), + version.ServeVersionCommand(cdc), ) rootCmd.AddCommand(prometheus.MonitorCommand(cdc)) diff --git a/examples/irishub1/cmd/iriscli1/main.go b/examples/irishub1/cmd/iriscli1/main.go index 704521d9b..9a381673f 100644 --- a/examples/irishub1/cmd/iriscli1/main.go +++ b/examples/irishub1/cmd/iriscli1/main.go @@ -15,9 +15,8 @@ import ( slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" "github.com/irisnet/irishub/examples/irishub1/app" - c "github.com/irisnet/irishub/client/lcd" govcmd "github.com/cosmos/cosmos-sdk/x/gov/client/cli" - upgradecmd "github.com/irisnet/irishub/client/cli/upgrade" + upgradecmd "github.com/irisnet/irishub/client/upgrade/cli" "github.com/irisnet/irishub/version" ) @@ -71,7 +70,6 @@ func main() { advancedCmd.AddCommand( tendermintCmd, ibcCmd, - c.ServeCommand(cdc), ) rootCmd.AddCommand( advancedCmd, @@ -132,7 +130,7 @@ func main() { upgradeCmd.AddCommand( client.GetCommands( upgradecmd.GetCmdQuerySwitch("upgrade", cdc), - upgradecmd.GetCmdInfo("upgrade", cdc), + upgradecmd.GetInfoCmd("upgrade", cdc), )...) upgradeCmd.AddCommand( client.PostCommands( @@ -159,7 +157,7 @@ func main() { ) rootCmd.AddCommand( client.GetCommands( - version.GetCmdVersion("upgrade", cdc), + version.ServeVersionCommand(cdc), )...) // prepare and add flags diff --git a/examples/irishub1/ibc/client/rest/transfer.go b/examples/irishub1/ibc/client/rest/transfer.go deleted file mode 100644 index bee9f955f..000000000 --- a/examples/irishub1/ibc/client/rest/transfer.go +++ /dev/null @@ -1,103 +0,0 @@ -package rest - -import ( - "io/ioutil" - "net/http" - - "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/gorilla/mux" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/ibc" -) - -// RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { - r.HandleFunc("/ibc/{destchain}/{address}/send", TransferRequestHandlerFn(cdc, kb, ctx)).Methods("POST") -} - -type transferBody struct { - // Fees sdk.Coin `json="fees"` - Amount sdk.Coins `json:"amount"` - LocalAccountName string `json:"name"` - Password string `json:"password"` - SrcChainID string `json:"src_chain_id"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` - Gas int64 `json:"gas"` -} - -// TransferRequestHandler - http request handler to transfer coins to a address -// on a different chain via IBC -func TransferRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - // collect data - vars := mux.Vars(r) - destChainID := vars["destchain"] - bech32addr := vars["address"] - - to, err := sdk.AccAddressFromBech32(bech32addr) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - var m transferBody - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - err = cdc.UnmarshalJSON(body, &m) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - info, err := kb.Get(m.LocalAccountName) - if err != nil { - w.WriteHeader(http.StatusUnauthorized) - w.Write([]byte(err.Error())) - return - } - - // build message - packet := ibc.NewIBCPacket(sdk.AccAddress(info.GetPubKey().Address()), to, m.Amount, m.SrcChainID, destChainID) - msg := ibc.IBCTransferMsg{packet} - - // add gas to context - ctx = ctx.WithGas(m.Gas) - - // sign - ctx = ctx.WithAccountNumber(m.AccountNumber) - ctx = ctx.WithSequence(m.Sequence) - 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 - } - - // send - res, err := ctx.BroadcastTx(txBytes) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - output, err := cdc.MarshalJSON(res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - w.Write(output) - } -} diff --git a/examples/irishub2/app/app.go b/examples/irishub2/app/app.go index 3aed32f3d..3cb0bfc8e 100644 --- a/examples/irishub2/app/app.go +++ b/examples/irishub2/app/app.go @@ -34,7 +34,6 @@ import ( sm "github.com/tendermint/tendermint/state" bc "github.com/tendermint/tendermint/blockchain" "strings" - "github.com/irisnet/irishub/modules/iparams" ) const ( @@ -76,7 +75,6 @@ type IrisApp struct { govKeeper gov.Keeper paramsKeeper params.Keeper upgradeKeeper upgrade.Keeper - iparamsKeeper iparams.Keeper // fee manager feeManager bam.FeeManager @@ -126,7 +124,7 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.paramsKeeper.Getter(), app.RegisterCodespace(slashing.DefaultCodespace)) app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection) - app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper, app.iparamsKeeper.Setter()) + app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper) app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) //app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) @@ -142,7 +140,7 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake, app.keyParams}, gov.NewHandler(app.govKeeper)). AddRoute("upgrade", []*sdk.KVStoreKey{app.keyUpgrade, app.keyStake}, upgrade.NewHandler(app.upgradeKeeper)) - app.feeManager = bam.NewFeeManager(app.iparamsKeeper.Getter()) + app.feeManager = bam.NewFeeManager(app.paramsKeeper.Setter()) // initialize BaseApp app.SetInitChainer(app.initChainer) @@ -230,7 +228,7 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci panic(err) } - minDeposit,err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s",10,denom)) + minDeposit,err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s",10,Denom)) if err != nil { panic(err) } @@ -256,7 +254,7 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci GasPriceThreshold: 20000000000, // 20(glue), 20*10^9, 1 glue = 10^9 lue/gas, 1 iris = 10^18 lue } - bam.InitGenesis(ctx, app.iparamsKeeper.Setter(), feeTokenGensisConfig) + bam.InitGenesis(ctx, app.paramsKeeper.Setter(), feeTokenGensisConfig) // load the address to pubkey map slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.StakeData) diff --git a/examples/irishub2/app/context.go b/examples/irishub2/app/context.go index 4e882be76..adc073942 100644 --- a/examples/irishub2/app/context.go +++ b/examples/irishub2/app/context.go @@ -16,7 +16,6 @@ import ( "strings" ) -//TODO 以后需要重构,现在有点乱 type Context struct { context.CLIContext txCtx txcxt.TxContext @@ -88,7 +87,7 @@ func (c Context) NumUnconfirmedTxs() (*ctypes.ResultUnconfirmedTxs, error) { func (c Context) GetCoinType(coinName string) (types.CoinType, error) { var coinType types.CoinType coinName = strings.ToLower(coinName) - if coinName == denom { + if coinName == Denom { coinType = IrisCt } else { key := types.CoinTypeKey(coinName) diff --git a/examples/irishub2/app/genesis.go b/examples/irishub2/app/genesis.go index 30a7a2b52..db61f2009 100644 --- a/examples/irishub2/app/genesis.go +++ b/examples/irishub2/app/genesis.go @@ -8,15 +8,15 @@ import ( "github.com/tendermint/tendermint/crypto" tmtypes "github.com/tendermint/tendermint/types" + "fmt" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/config" 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" - "time" "github.com/irisnet/irishub/types" - "fmt" + "time" ) // State to Unmarshal @@ -54,13 +54,13 @@ func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { } var ( - flagName = "name" - flagClientHome = "home-client" - flagOWK = "owk" - denom = "iris" - feeAmt = int64(100) - IrisCt = types.NewDefaultCoinType(denom) - freeFermionVal ,_ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s",feeAmt,denom)) + flagName = "name" + flagClientHome = "home-client" + flagOWK = "owk" + Denom = "iris" + feeAmt = int64(100) + IrisCt = types.NewDefaultCoinType(Denom) + freeFermionVal, _ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", feeAmt, Denom)) ) const defaultUnbondingTime time.Duration = 60 * 10 * time.Second @@ -176,7 +176,7 @@ func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState // add some new shares to the validator var issuedDelShares sdk.Rat - validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, feeAmt) + validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, freeFermionVal.Amount) //validator.TokenPrecision = stakeData.Params.DenomPrecision stakeData.Validators = append(stakeData.Validators, validator) @@ -229,7 +229,7 @@ func createGenesisState() stake.GenesisState { GoalBonded: sdk.NewRat(67, 100), UnbondingTime: defaultUnbondingTime, MaxValidators: 100, - BondDenom: denom, + BondDenom: Denom + "-" + types.Atto, }, } } diff --git a/examples/irishub2/cmd/iris2/main.go b/examples/irishub2/cmd/iris2/main.go index feb6df7a7..7663fc800 100644 --- a/examples/irishub2/cmd/iris2/main.go +++ b/examples/irishub2/cmd/iris2/main.go @@ -54,7 +54,7 @@ func main() { tendermintCmd, server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), client.LineBreak, - version.GetCmdVersion("upgrade", cdc), + version.ServeVersionCommand(cdc), ) rootCmd.AddCommand(prometheus.MonitorCommand(cdc)) diff --git a/examples/irishub2/cmd/iriscli2/main.go b/examples/irishub2/cmd/iriscli2/main.go index dad93851f..8ab273815 100644 --- a/examples/irishub2/cmd/iriscli2/main.go +++ b/examples/irishub2/cmd/iriscli2/main.go @@ -15,9 +15,8 @@ import ( slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" "github.com/irisnet/irishub/examples/irishub2/app" - c "github.com/irisnet/irishub/client/lcd" govcmd "github.com/cosmos/cosmos-sdk/x/gov/client/cli" - upgradecmd "github.com/irisnet/irishub/client/cli/upgrade" + upgradecmd "github.com/irisnet/irishub/client/upgrade/cli" "github.com/irisnet/irishub/version" ) @@ -71,7 +70,6 @@ func main() { advancedCmd.AddCommand( tendermintCmd, ibcCmd, - c.ServeCommand(cdc), ) rootCmd.AddCommand( advancedCmd, @@ -132,7 +130,7 @@ func main() { upgradeCmd.AddCommand( client.GetCommands( upgradecmd.GetCmdQuerySwitch("upgrade", cdc), - upgradecmd.GetCmdInfo("upgrade", cdc), + upgradecmd.GetInfoCmd("upgrade", cdc), )...) upgradeCmd.AddCommand( client.PostCommands( @@ -159,7 +157,7 @@ func main() { ) rootCmd.AddCommand( client.GetCommands( - version.GetCmdVersion("upgrade", cdc), + version.ServeVersionCommand(cdc), )...) // prepare and add flags diff --git a/examples/irishub2/ibc/client/rest/transfer.go b/examples/irishub2/ibc/client/rest/transfer.go deleted file mode 100644 index bee9f955f..000000000 --- a/examples/irishub2/ibc/client/rest/transfer.go +++ /dev/null @@ -1,103 +0,0 @@ -package rest - -import ( - "io/ioutil" - "net/http" - - "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/gorilla/mux" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/ibc" -) - -// RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { - r.HandleFunc("/ibc/{destchain}/{address}/send", TransferRequestHandlerFn(cdc, kb, ctx)).Methods("POST") -} - -type transferBody struct { - // Fees sdk.Coin `json="fees"` - Amount sdk.Coins `json:"amount"` - LocalAccountName string `json:"name"` - Password string `json:"password"` - SrcChainID string `json:"src_chain_id"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` - Gas int64 `json:"gas"` -} - -// TransferRequestHandler - http request handler to transfer coins to a address -// on a different chain via IBC -func TransferRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - // collect data - vars := mux.Vars(r) - destChainID := vars["destchain"] - bech32addr := vars["address"] - - to, err := sdk.AccAddressFromBech32(bech32addr) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - var m transferBody - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - err = cdc.UnmarshalJSON(body, &m) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - info, err := kb.Get(m.LocalAccountName) - if err != nil { - w.WriteHeader(http.StatusUnauthorized) - w.Write([]byte(err.Error())) - return - } - - // build message - packet := ibc.NewIBCPacket(sdk.AccAddress(info.GetPubKey().Address()), to, m.Amount, m.SrcChainID, destChainID) - msg := ibc.IBCTransferMsg{packet} - - // add gas to context - ctx = ctx.WithGas(m.Gas) - - // sign - ctx = ctx.WithAccountNumber(m.AccountNumber) - ctx = ctx.WithSequence(m.Sequence) - 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 - } - - // send - res, err := ctx.BroadcastTx(txBytes) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - output, err := cdc.MarshalJSON(res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - w.Write(output) - } -} From 8763d314929eb71816f74674e9858b6b2ebe5ec9 Mon Sep 17 00:00:00 2001 From: Yelong Zhang Date: Thu, 27 Sep 2018 16:14:24 +0800 Subject: [PATCH 110/124] Update README.md --- docs/zh/modules/gov/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/zh/modules/gov/README.md b/docs/zh/modules/gov/README.md index ae35da1d4..a2f99bfe3 100644 --- a/docs/zh/modules/gov/README.md +++ b/docs/zh/modules/gov/README.md @@ -138,7 +138,7 @@ iriscli gov submit-proposal --title="update MinDeposit" --description="test" --t * `--title` 提议的标题 * `--description` 提议的描述 * `--type` 提议的类型 {'Text','ParameterChange','SoftwareUpgrade'} -* `--deposit` 抵押token的数量 +* `--deposit` 抵押的token数量 * 上面就是典型的文本类提议 ``` @@ -146,7 +146,7 @@ iriscli gov deposit --proposal-id=1 --deposit=1iris --from=x --chain-id=gov-test ``` * `--propsal-id` 抵押提议ID -* `--deposit` 抵押的token数目 +* `--deposit` 抵押的token数量 ``` iriscli gov vote --proposal-id=1 --option=Yes --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 From 6bd6bdd5f99699445f15bd014a52f6eaaca46587 Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Thu, 27 Sep 2018 17:29:25 +0800 Subject: [PATCH 111/124] set SwitchPeriod for Testnet and complete the makefile --- Makefile | 10 +++++++++- modules/gov/msgs.go | 8 +++++--- modules/upgrade/keeper.go | 4 ++-- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 01ef065a5..37480db56 100644 --- a/Makefile +++ b/Makefile @@ -64,17 +64,25 @@ build_cur: update_irislcd_swagger_docs go build -o build/iriscli ./cmd/iriscli && \ go build -o build/irislcd ./cmd/irislcd -build_example: update_irislcd_swagger_docs +build_examples: update_irislcd_swagger_docs go build -o build/iris1 ./examples/irishub1/cmd/iris1 go build -o build/iriscli1 ./examples/irishub1/cmd/iriscli1 go build -o build/iris2 ./examples/irishub2/cmd/iris2 go build -o build/iriscli2 ./examples/irishub2/cmd/iriscli2 + go build -o build/iris-bugfix-2 ./examples/irishub-bugfix-2/cmd/iris-bugfix-2 + go build -o build/iriscli-bugfix-2 ./examples/irishub-bugfix-2/cmd/iriscli-bugfix-2 + go build -o build/iris-bugfix-3 ./examples/irishub-bugfix-3/cmd/iris-bugfix-3 + go build -o build/iriscli-bugfix-3 ./examples/irishub-bugfix-3/cmd/iriscli-bugfix-3 install_examples: update_irislcd_swagger_docs go install ./examples/irishub1/cmd/iris1 go install ./examples/irishub1/cmd/iriscli1 go install ./examples/irishub2/cmd/iris2 go install ./examples/irishub2/cmd/iriscli2 + go install ./examples/irishub-bugfix-2/cmd/iris-bugfix-2 + go install ./examples/irishub-bugfix-2/cmd/iriscli-bugfix-2 + go install ./examples/irishub-bugfix-3/cmd/iris-bugfix-3 + go install ./examples/irishub-bugfix-3/cmd/iriscli-bugfix-3 build_example_linux: update_irislcd_swagger_docs CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iris1 ./examples/irishub1/cmd/iris1 diff --git a/modules/gov/msgs.go b/modules/gov/msgs.go index ea3048af6..ddf1e7bef 100644 --- a/modules/gov/msgs.go +++ b/modules/gov/msgs.go @@ -64,12 +64,14 @@ func (msg MsgSubmitProposal) ValidateBasic() sdk.Error { return ErrInvalidParam(DefaultCodespace) } - } + if msg.Param.Op != Update && msg.Param.Op != Insert { + return ErrInvalidParamOp(DefaultCodespace, msg.Param.Op) + } - if msg.Param.Op != Update && msg.Param.Op != Insert { - return ErrInvalidParamOp(DefaultCodespace, msg.Param.Op) } + + return nil } diff --git a/modules/upgrade/keeper.go b/modules/upgrade/keeper.go index 642caf9de..c11358caa 100644 --- a/modules/upgrade/keeper.go +++ b/modules/upgrade/keeper.go @@ -8,8 +8,8 @@ import ( ) const ( - //defaultSwitchPeriod int64 = 57600 // 2 days - defaultSwitchPeriod int64 = 30 // for test (4 minutes) + defaultSwitchPeriod int64 = 57600 // 2 days + //defaultSwitchPeriod int64 = 30 // for test (4 minutes) ) type Keeper struct { From 21abaccb3b57b6aa222667412f9caa863d67120a Mon Sep 17 00:00:00 2001 From: zhangyelong Date: Thu, 27 Sep 2018 17:37:39 +0800 Subject: [PATCH 112/124] IRISHUB-473 Update iris version --- docs/get-started/Install-Iris.md | 14 +++++++------- docs/zh/get-started/Genesis-Generation-Process.md | 2 +- docs/zh/get-started/Install-Iris.md | 14 +++++++------- docs/zh/get-started/README.md | 10 +++++----- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/docs/get-started/Install-Iris.md b/docs/get-started/Install-Iris.md index 64c44a2c4..7e9287fe7 100644 --- a/docs/get-started/Install-Iris.md +++ b/docs/get-started/Install-Iris.md @@ -18,17 +18,17 @@ There are two ways to get Iris running on your server. You can download the bina #### Download Binary Directly -Go to the download page: https://github.com/irisnet/irishub/releases/ then get the release v0.4.1 on your computer. +Go to the download page: https://github.com/irisnet/irishub/releases/ then get the release v0.4.2 on your computer. `unzip -C /usr/local/bin iris$VERSION.$OS-$ARCH.zip` to `/usr/local/bin/ ` You can verify you have the right version installed by running the following commands: ``` $ iris version -v0.4.1 +v0.4.2 $ iriscli version -v0.4.1 +v0.4.2 ``` #### Compile Source Code @@ -91,7 +91,7 @@ Make sure that you can access to google.com for that our project used some libra mkdir -p $GOPATH/src/github.com/irisnet cd $GOPATH/src/github.com/irisnet git clone https://github.com/irisnet/irishub -cd irishub && git checkout v0.4.1 +cd irishub && git checkout v0.4.2 curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh make get_vendor_deps && make install ``` @@ -101,9 +101,9 @@ Now check your **Iris** version. ``` $ iris version -v0.4.1 +v0.4.2 $ iriscli version -v0.4.1 +v0.4.2 ``` ### How to Update @@ -114,7 +114,7 @@ Get latest code (you can also `git fetch` only the version desired), ensure the cd $GOPATH/src/github.com/irisnet/irishub git fetch -a origin rm Gopkg.lock -git checkout v0.4.1 +git checkout v0.4.2 make get_vendor_deps make install ``` diff --git a/docs/zh/get-started/Genesis-Generation-Process.md b/docs/zh/get-started/Genesis-Generation-Process.md index 5fa286081..759c77a75 100644 --- a/docs/zh/get-started/Genesis-Generation-Process.md +++ b/docs/zh/get-started/Genesis-Generation-Process.md @@ -1,7 +1,7 @@ # 参与到Genesis文件生成流程中 -1. 每个希望成为验证人的参与者确保安装了对应版本的软件:iris v0.4.1 +1. 每个希望成为验证人的参与者确保安装了对应版本的软件:iris v0.4.2 2. 执行gentx命令,获得一个node-id.json的文件。这个操作将默认生成一个余额为200IRIS的账户,该账户默认绑定100IRIS成为一个验证人候选人。 diff --git a/docs/zh/get-started/Install-Iris.md b/docs/zh/get-started/Install-Iris.md index 06bf23a52..868b85250 100644 --- a/docs/zh/get-started/Install-Iris.md +++ b/docs/zh/get-started/Install-Iris.md @@ -28,10 +28,10 @@ tar -C /usr/local/bin -xzf iris$VERSION.$OS-$ARCH.zip ``` $ iris version -v0.4.1 +v0.4.2 $ iriscli version -v0.4.1 +v0.4.2 ``` #### 方法2:源码编译安装 @@ -88,7 +88,7 @@ Ubuntu LTS 16.04 mkdir -p $GOPATH/src/github.com/irisnet cd $GOPATH/src/github.com/irisnet git clone https://github.com/irisnet/irishub -cd irishub && git checkout v0.4.1 +cd irishub && git checkout v0.4.2 curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh @@ -99,20 +99,20 @@ make get_vendor_deps && make install ``` $ iris version -v0.4.1 +v0.4.2 $ iriscli version -v0.4.1 +v0.4.2 ``` ### 如何升级IRISHub -通过执行一下命令可以完成IRISHub从v0.3.4到v0.4.1的升级 +通过执行一下命令可以完成IRISHub从v0.3.4到v0.4.2的升级 ``` cd $GOPATH/src/github.com/irisnet/irishub git fetch -a origin rm Gopkg.lock -git checkout v0.4.1 +git checkout v0.4.2 make get_vendor_deps make install ``` \ No newline at end of file diff --git a/docs/zh/get-started/README.md b/docs/zh/get-started/README.md index c5dd468d1..7036aa4ed 100644 --- a/docs/zh/get-started/README.md +++ b/docs/zh/get-started/README.md @@ -33,10 +33,10 @@ IRIS Hub是用Go语言编写的。它可以在任何能够编译并运行Go语 执行以下命令,若出现对应的版本号则说明安装成功。 ``` $ iris version -v0.4.1 +v0.4.2 $ iriscli version -v0.4.1 +v0.4.2 ``` #### 方法2:源码编译安装 @@ -93,7 +93,7 @@ Ubuntu LTS 16.04 mkdir -p $GOPATH/src/github.com/irisnet cd $GOPATH/src/github.com/irisnet git clone https://github.com/irisnet/irishub -cd irishub && git checkout v0.4.1 +cd irishub && git checkout v0.4.2 curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh @@ -104,10 +104,10 @@ make get_vendor_deps && make install ``` $ iris version -v0.4.1 +v0.4.2 $ iriscli version -v0.4.1 +v0.4.2 ``` ### 部署一个全节点 From 49aabd67be1475d530698735b30a25423a89d208 Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Thu, 27 Sep 2018 18:02:30 +0800 Subject: [PATCH 113/124] delete two example and fix the upgrade cli --- examples/irishub-bugfix-3/app/app.go | 374 ----------------- examples/irishub-bugfix-3/app/context.go | 165 -------- examples/irishub-bugfix-3/app/genesis.go | 235 ----------- .../cmd/iris-bugfix-3/main.go | 76 ---- .../cmd/iriscli-bugfix-3/main.go | 170 -------- .../irishub-bugfix-3/ibc/client/cli/README.md | 157 -------- .../irishub-bugfix-3/ibc/client/cli/ibctx.go | 84 ---- .../irishub-bugfix-3/ibc/client/cli/tx.go | 66 --- examples/irishub-bugfix-3/ibc/errors.go | 50 --- examples/irishub-bugfix-3/ibc/handler.go | 87 ---- examples/irishub-bugfix-3/ibc/mapper.go | 149 ------- examples/irishub-bugfix-3/ibc/types.go | 184 --------- examples/irishub-bugfix-3/ibc/wire.go | 13 - examples/irishub2/app/app.go | 379 ------------------ examples/irishub2/app/context.go | 165 -------- examples/irishub2/app/genesis.go | 235 ----------- examples/irishub2/cmd/iris2/main.go | 76 ---- examples/irishub2/cmd/iriscli2/main.go | 170 -------- examples/irishub2/ibc/client/cli/README.md | 157 -------- examples/irishub2/ibc/client/cli/ibctx.go | 84 ---- examples/irishub2/ibc/client/cli/tx.go | 66 --- examples/irishub2/ibc/errors.go | 50 --- examples/irishub2/ibc/handler.go | 76 ---- examples/irishub2/ibc/mapper.go | 149 ------- examples/irishub2/ibc/types.go | 184 --------- examples/irishub2/ibc/wire.go | 13 - 26 files changed, 3614 deletions(-) delete mode 100644 examples/irishub-bugfix-3/app/app.go delete mode 100644 examples/irishub-bugfix-3/app/context.go delete mode 100644 examples/irishub-bugfix-3/app/genesis.go delete mode 100644 examples/irishub-bugfix-3/cmd/iris-bugfix-3/main.go delete mode 100644 examples/irishub-bugfix-3/cmd/iriscli-bugfix-3/main.go delete mode 100644 examples/irishub-bugfix-3/ibc/client/cli/README.md delete mode 100644 examples/irishub-bugfix-3/ibc/client/cli/ibctx.go delete mode 100644 examples/irishub-bugfix-3/ibc/client/cli/tx.go delete mode 100644 examples/irishub-bugfix-3/ibc/errors.go delete mode 100644 examples/irishub-bugfix-3/ibc/handler.go delete mode 100644 examples/irishub-bugfix-3/ibc/mapper.go delete mode 100644 examples/irishub-bugfix-3/ibc/types.go delete mode 100644 examples/irishub-bugfix-3/ibc/wire.go delete mode 100644 examples/irishub2/app/app.go delete mode 100644 examples/irishub2/app/context.go delete mode 100644 examples/irishub2/app/genesis.go delete mode 100644 examples/irishub2/cmd/iris2/main.go delete mode 100644 examples/irishub2/cmd/iriscli2/main.go delete mode 100644 examples/irishub2/ibc/client/cli/README.md delete mode 100644 examples/irishub2/ibc/client/cli/ibctx.go delete mode 100644 examples/irishub2/ibc/client/cli/tx.go delete mode 100644 examples/irishub2/ibc/errors.go delete mode 100644 examples/irishub2/ibc/handler.go delete mode 100644 examples/irishub2/ibc/mapper.go delete mode 100644 examples/irishub2/ibc/types.go delete mode 100644 examples/irishub2/ibc/wire.go diff --git a/examples/irishub-bugfix-3/app/app.go b/examples/irishub-bugfix-3/app/app.go deleted file mode 100644 index 1c434c2bf..000000000 --- a/examples/irishub-bugfix-3/app/app.go +++ /dev/null @@ -1,374 +0,0 @@ -package app - -import ( - "encoding/json" - "io" - "os" - - bam "github.com/irisnet/irishub/baseapp" - abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - - 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/bank" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/ibc" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/stake" - ibcbugfix "github.com/irisnet/irishub/examples/irishub-bugfix-3/ibc" - "github.com/irisnet/irishub/modules/upgrade" - - "errors" - "fmt" - "github.com/cosmos/cosmos-sdk/server" - "github.com/spf13/viper" - bc "github.com/tendermint/tendermint/blockchain" - tmcli "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/node" - sm "github.com/tendermint/tendermint/state" - "strings" -) - -const ( - appName = "IrisApp" - FlagReplay = "replay" -) - -// default home directories for expected binaries -var ( - DefaultCLIHome = os.ExpandEnv("$HOME/.iriscli") - DefaultNodeHome = os.ExpandEnv("$HOME/.iris") -) - -// Extended ABCI application -type IrisApp struct { - *bam.BaseApp - cdc *wire.Codec - - // keys to access the substores - keyMain *sdk.KVStoreKey - keyAccount *sdk.KVStoreKey - keyIBC *sdk.KVStoreKey - keyStake *sdk.KVStoreKey - keySlashing *sdk.KVStoreKey - keyGov *sdk.KVStoreKey - keyFeeCollection *sdk.KVStoreKey - keyParams *sdk.KVStoreKey - keyUpgrade *sdk.KVStoreKey - - // Manage getting and setting accounts - accountMapper auth.AccountMapper - feeCollectionKeeper auth.FeeCollectionKeeper - coinKeeper bank.Keeper - ibcMapper ibc.Mapper - ibc1Mapper ibcbugfix.Mapper - stakeKeeper stake.Keeper - slashingKeeper slashing.Keeper - govKeeper gov.Keeper - paramsKeeper params.Keeper - upgradeKeeper upgrade.Keeper - - // fee manager - feeManager bam.FeeManager -} - -func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptions ...func(*bam.BaseApp)) *IrisApp { - cdc := MakeCodec() - - bApp := bam.NewBaseApp(appName, cdc, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...) - bApp.SetCommitMultiStoreTracer(traceStore) - - // create your application object - var app = &IrisApp{ - BaseApp: bApp, - cdc: cdc, - keyMain: sdk.NewKVStoreKey("main"), - keyAccount: sdk.NewKVStoreKey("acc"), - keyIBC: sdk.NewKVStoreKey("ibc"), - keyStake: sdk.NewKVStoreKey("stake"), - keySlashing: sdk.NewKVStoreKey("slashing"), - keyGov: sdk.NewKVStoreKey("gov"), - keyFeeCollection: sdk.NewKVStoreKey("fee"), - keyParams: sdk.NewKVStoreKey("params"), - keyUpgrade: sdk.NewKVStoreKey("upgrade"), - } - - var lastHeight int64 - if viper.GetBool(FlagReplay) { - lastHeight = app.replay() - } - - // define the accountMapper - app.accountMapper = auth.NewAccountMapper( - app.cdc, - app.keyAccount, // target store - auth.ProtoBaseAccount, // prototype - ) - - // add handlers - app.paramsKeeper = params.NewKeeper(app.cdc, app.keyParams) - app.coinKeeper = bank.NewKeeper(app.accountMapper) - - app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace)) - app.ibc1Mapper = ibcbugfix.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibcbugfix.DefaultCodespace)) - - app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) - app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.paramsKeeper.Getter(), app.RegisterCodespace(slashing.DefaultCodespace)) - app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection) - app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper) - app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - //app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - - // register message routes - // need to update each module's msg type - app.Router(). - AddRoute("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.coinKeeper)). - AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). - AddRoute("ibc-1", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibcbugfix.NewHandler(app.ibc1Mapper, app.coinKeeper, app.upgradeKeeper)). - AddRoute("stake", []*sdk.KVStoreKey{app.keyStake, app.keyAccount}, stake.NewHandler(app.stakeKeeper)). - AddRoute("slashing", []*sdk.KVStoreKey{app.keySlashing, app.keyStake}, slashing.NewHandler(app.slashingKeeper)). - AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake, app.keyParams}, gov.NewHandler(app.govKeeper)). - AddRoute("upgrade", []*sdk.KVStoreKey{app.keyUpgrade, app.keyStake}, upgrade.NewHandler(app.upgradeKeeper)) - - app.feeManager = bam.NewFeeManager(app.paramsKeeper.Setter()) - - // initialize BaseApp - app.SetInitChainer(app.initChainer) - app.SetBeginBlocker(app.BeginBlocker) - app.SetEndBlocker(app.EndBlocker) - app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) - app.SetFeeRefundHandler(bam.NewFeeRefundHandler(app.accountMapper, app.feeCollectionKeeper, app.feeManager)) - app.SetFeePreprocessHandler(bam.NewFeePreprocessHandler(app.feeManager)) - app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing, app.keyGov, app.keyFeeCollection, app.keyParams, app.keyUpgrade) - app.SetRunMsg(app.runMsgs) - var err error - if viper.GetBool(FlagReplay) { - err = app.LoadVersion(lastHeight, app.keyMain) - } else { - err = app.LoadLatestVersion(app.keyMain) - } - if err != nil { - cmn.Exit(err.Error()) - } - - upgrade.RegisterModuleList(app.Router()) - - return app -} - -// custom tx codec -func MakeCodec() *wire.Codec { - var cdc = wire.NewCodec() - ibc.RegisterWire(cdc) - ibcbugfix.RegisterWire(cdc) - bank.RegisterWire(cdc) - stake.RegisterWire(cdc) - slashing.RegisterWire(cdc) - gov.RegisterWire(cdc) - auth.RegisterWire(cdc) - upgrade.RegisterWire(cdc) - sdk.RegisterWire(cdc) - wire.RegisterCrypto(cdc) - return cdc -} - -// application updates every end block -func (app *IrisApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) - - return abci.ResponseBeginBlock{ - Tags: tags.ToKVPairs(), - } -} - -// application updates every end block -func (app *IrisApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) - - tags := gov.EndBlocker(ctx, app.govKeeper) - tags.AppendTags(upgrade.EndBlocker(ctx, app.upgradeKeeper)) - - return abci.ResponseEndBlock{ - ValidatorUpdates: validatorUpdates, - Tags: tags, - } -} - -// custom logic for iris initialization -func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { - stateJSON := req.AppStateBytes - - var genesisState GenesisState - err := app.cdc.UnmarshalJSON(stateJSON, &genesisState) - if err != nil { - panic(err) - } - - // load the accounts - for _, gacc := range genesisState.Accounts { - acc := gacc.ToAccount() - acc.AccountNumber = app.accountMapper.GetNextAccountNumber(ctx) - app.accountMapper.SetAccount(ctx, acc) - } - - // load the initial stake information - validators, err := stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData) - if err != nil { - panic(err) - } - - minDeposit, err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", 10, Denom)) - if err != nil { - panic(err) - } - - gov.InitGenesis(ctx, app.govKeeper, gov.GenesisState{ - StartingProposalID: 1, - DepositProcedure: gov.DepositProcedure{ - MinDeposit: sdk.Coins{minDeposit}, - MaxDepositPeriod: 1440, - }, - VotingProcedure: gov.VotingProcedure{ - VotingPeriod: 30, - }, - TallyingProcedure: gov.TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 100), - }, - }) - - feeTokenGensisConfig := bam.FeeGenesisStateConfig{ - FeeTokenNative: IrisCt.MinUnit.Denom, - GasPriceThreshold: 20000000000, // 20(glue), 20*10^9, 1 glue = 10^9 lue/gas, 1 iris = 10^18 lue - } - - bam.InitGenesis(ctx, app.paramsKeeper.Setter(), feeTokenGensisConfig) - - // load the address to pubkey map - slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.StakeData) - - upgrade.InitGenesis(ctx, app.upgradeKeeper, app.Router()) - - return abci.ResponseInitChain{ - Validators: validators, - } -} - -// export the state of iris for a genesis file -func (app *IrisApp) ExportAppStateAndValidators() (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) { - ctx := app.NewContext(true, abci.Header{}) - - // iterate to get the accounts - accounts := []GenesisAccount{} - appendAccount := func(acc auth.Account) (stop bool) { - account := NewGenesisAccountI(acc) - accounts = append(accounts, account) - return false - } - app.accountMapper.IterateAccounts(ctx, appendAccount) - - genState := GenesisState{ - Accounts: accounts, - StakeData: stake.WriteGenesis(ctx, app.stakeKeeper), - } - appState, err = wire.MarshalJSONIndent(app.cdc, genState) - if err != nil { - return nil, nil, err - } - validators = stake.WriteValidators(ctx, app.stakeKeeper) - return appState, validators, nil -} - -// Iterates through msgs and executes them -func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) { - // accumulate results - logs := make([]string, 0, len(msgs)) - var data []byte // NOTE: we just append them all (?!) - var tags sdk.Tags // also just append them all - var code sdk.ABCICodeType - for msgIdx, msg := range msgs { - // Match route. - msgType, err := app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) - fmt.Println("============ runMsgs() =========== " + msgType) - if err != nil { - return err.Result() - } - - handler := app.Router().Route(msgType) - if handler == nil { - return sdk.ErrUnknownRequest("Unrecognized Msg type: " + msgType).Result() - } - fmt.Println(msg) - msgResult := handler(ctx, msg) - - // NOTE: GasWanted is determined by ante handler and - // GasUsed by the GasMeter - - // Append Data and Tags - data = append(data, msgResult.Data...) - tags = append(tags, msgResult.Tags...) - - // Stop execution and return on first failed message. - if !msgResult.IsOK() { - logs = append(logs, fmt.Sprintf("Msg %d failed: %s", msgIdx, msgResult.Log)) - code = msgResult.Code - break - } - - // Construct usable logs in multi-message transactions. - logs = append(logs, fmt.Sprintf("Msg %d: %s", msgIdx, msgResult.Log)) - } - - // Set the final gas values. - result = sdk.Result{ - Code: code, - Data: data, - Log: strings.Join(logs, "\n"), - GasUsed: ctx.GasMeter().GasConsumed(), - // TODO: FeeAmount/FeeDenom - Tags: tags, - } - - return result -} - -func (app *IrisApp) replay() int64 { - ctx := server.NewDefaultContext() - ctx.Config.RootDir = viper.GetString(tmcli.HomeFlag) - dbContext := node.DBContext{"state", ctx.Config} - dbType := dbm.DBBackendType(dbContext.Config.DBBackend) - stateDB := dbm.NewDB(dbContext.ID, dbType, dbContext.Config.DBDir()) - - blockDBContext := node.DBContext{"blockstore", ctx.Config} - blockStoreDB := dbm.NewDB(blockDBContext.ID, dbType, dbContext.Config.DBDir()) - blockStore := bc.NewBlockStore(blockStoreDB) - - defer func() { - stateDB.Close() - blockStoreDB.Close() - }() - - curState := sm.LoadState(stateDB) - preState := sm.LoadPreState(stateDB) - if curState.LastBlockHeight == preState.LastBlockHeight { - panic(errors.New("there is no block now, can't replay")) - } - var loadHeight int64 - if blockStore.Height() == curState.LastBlockHeight { - sm.SaveState(stateDB, preState) - loadHeight = preState.LastBlockHeight - } else if blockStore.Height() == curState.LastBlockHeight+1 { - loadHeight = curState.LastBlockHeight - } else { - panic(errors.New("tendermint block store height should be at most one ahead of the its state height")) - } - - return loadHeight -} diff --git a/examples/irishub-bugfix-3/app/context.go b/examples/irishub-bugfix-3/app/context.go deleted file mode 100644 index adc073942..000000000 --- a/examples/irishub-bugfix-3/app/context.go +++ /dev/null @@ -1,165 +0,0 @@ -package app - -import ( - "fmt" - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/auth" - txcxt "github.com/cosmos/cosmos-sdk/x/auth/client/context" - "github.com/irisnet/irishub/types" - "github.com/pkg/errors" - client2 "github.com/tendermint/tendermint/rpc/client" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - "io/ioutil" - "net/http" - "strings" -) - -type Context struct { - context.CLIContext - txCtx txcxt.TxContext - Cdc *wire.Codec -} - -func NewContext() Context { - return Context{ - CLIContext: context.NewCLIContext(), - txCtx: txcxt.NewTxContextFromCLI(), - } -} -func (c Context) Get() context.CLIContext { - return c.CLIContext.WithCodec(c.Cdc) -} - -func (c Context) GetTxCxt() txcxt.TxContext { - return c.txCtx.WithCodec(c.Cdc) -} - -func (c Context) WithCodeC(cdc *wire.Codec) Context { - c.Cdc = cdc - c.CLIContext = c.CLIContext.WithCodec(cdc) - return c -} -func (c Context) WithCLIContext(ctx context.CLIContext) Context { - c.CLIContext = ctx - return c -} -func (c Context) WithTxContext(ctx txcxt.TxContext) Context { - c.txCtx = ctx - return c -} - -func (c Context) NetInfo() (*ctypes.ResultNetInfo, error) { - client := c.Client.(*client2.HTTP) - return client.NetInfo() -} - -func (c Context) NumUnconfirmedTxs() (*ctypes.ResultUnconfirmedTxs, error) { - client := &http.Client{} - url := strings.Replace(c.NodeURI, "tcp", "http", 1) - reqUri := fmt.Sprintf("%s/%s", url, "num_unconfirmed_txs") - - resp, err := client.Get(reqUri) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - var res = struct { - JsonRpc string `json:"jsonrpc"` - Id string `json:"id"` - Result ctypes.ResultUnconfirmedTxs `json:"result"` - }{} - - if err := c.Cdc.UnmarshalJSON(body, &res); err != nil { - return nil, err - } - - return &res.Result, nil -} - -func (c Context) GetCoinType(coinName string) (types.CoinType, error) { - var coinType types.CoinType - coinName = strings.ToLower(coinName) - if coinName == Denom { - coinType = IrisCt - } else { - key := types.CoinTypeKey(coinName) - bz, err := c.QueryStore([]byte(key), "iparams") - if err != nil { - return coinType, err - } - - if err = c.Cdc.UnmarshalBinary(bz, &coinType); err != nil { - return coinType, err - } - } - - return coinType, nil -} - -func (c Context) ParseCoin(coinStr string) (sdk.Coin, error) { - mainUnit, err := types.GetCoinName(coinStr) - coinType, err := c.GetCoinType(mainUnit) - if err != nil { - return sdk.Coin{}, err - } - - coin, err := coinType.ConvertToMinCoin(coinStr) - if err != nil { - return sdk.Coin{}, err - } - return coin, nil -} - -func (c Context) ParseCoins(coinsStr string) (coins sdk.Coins, err error) { - coinsStr = strings.TrimSpace(coinsStr) - if len(coinsStr) == 0 { - return coins, nil - } - - coinStrs := strings.Split(coinsStr, ",") - for _, coinStr := range coinStrs { - coin, err := c.ParseCoin(coinStr) - if err != nil { - return coins, err - } - coins = append(coins, coin) - } - return coins, nil -} - -// Build builds a single message to be signed from a TxContext given a set of -// messages. It returns an error if a fee is supplied but cannot be parsed. -func (c Context) Build(msgs []sdk.Msg) (auth.StdSignMsg, error) { - ctx := c.txCtx - chainID := ctx.ChainID - if chainID == "" { - return auth.StdSignMsg{}, errors.Errorf("chain ID required but not specified") - } - - fee := sdk.Coin{} - if ctx.Fee != "" { - parsedFee, err := c.ParseCoin(ctx.Fee) - if err != nil { - return auth.StdSignMsg{}, err - } - - fee = parsedFee - } - - return auth.StdSignMsg{ - ChainID: ctx.ChainID, - AccountNumber: ctx.AccountNumber, - Sequence: ctx.Sequence, - Memo: ctx.Memo, - Msgs: msgs, - Fee: auth.NewStdFee(ctx.Gas, fee), - }, nil -} diff --git a/examples/irishub-bugfix-3/app/genesis.go b/examples/irishub-bugfix-3/app/genesis.go deleted file mode 100644 index db61f2009..000000000 --- a/examples/irishub-bugfix-3/app/genesis.go +++ /dev/null @@ -1,235 +0,0 @@ -package app - -import ( - "encoding/json" - "errors" - - "github.com/spf13/pflag" - "github.com/tendermint/tendermint/crypto" - tmtypes "github.com/tendermint/tendermint/types" - - "fmt" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/server/config" - 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" - "github.com/irisnet/irishub/types" - "time" -) - -// State to Unmarshal -type GenesisState struct { - Accounts []GenesisAccount `json:"accounts"` - StakeData stake.GenesisState `json:"stake"` -} - -// GenesisAccount doesn't need pubkey or sequence -type GenesisAccount struct { - Address sdk.AccAddress `json:"address"` - Coins sdk.Coins `json:"coins"` -} - -func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount { - return GenesisAccount{ - Address: acc.Address, - Coins: acc.Coins, - } -} - -func NewGenesisAccountI(acc auth.Account) GenesisAccount { - return GenesisAccount{ - Address: acc.GetAddress(), - Coins: acc.GetCoins(), - } -} - -// convert GenesisAccount to auth.BaseAccount -func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { - return &auth.BaseAccount{ - Address: ga.Address, - Coins: ga.Coins.Sort(), - } -} - -var ( - flagName = "name" - flagClientHome = "home-client" - flagOWK = "owk" - Denom = "iris" - feeAmt = int64(100) - IrisCt = types.NewDefaultCoinType(Denom) - freeFermionVal, _ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", feeAmt, Denom)) -) - -const defaultUnbondingTime time.Duration = 60 * 10 * time.Second - -// get app init parameters for server init command -func IrisAppInit() server.AppInit { - fsAppGenState := pflag.NewFlagSet("", pflag.ContinueOnError) - - fsAppGenTx := pflag.NewFlagSet("", pflag.ContinueOnError) - fsAppGenTx.String(flagName, "", "validator moniker, required") - fsAppGenTx.String(flagClientHome, DefaultCLIHome, - "home directory for the client, used for key generation") - fsAppGenTx.Bool(flagOWK, false, "overwrite the accounts created") - - return server.AppInit{ - FlagsAppGenState: fsAppGenState, - FlagsAppGenTx: fsAppGenTx, - AppGenTx: IrisAppGenTx, - AppGenState: IrisAppGenStateJSON, - } -} - -// simple genesis tx -type IrisGenTx struct { - Name string `json:"name"` - Address sdk.AccAddress `json:"address"` - PubKey string `json:"pub_key"` -} - -// Generate a gaia genesis transaction with flags -func IrisAppGenTx(cdc *wire.Codec, pk crypto.PubKey, genTxConfig config.GenTx) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - - if genTxConfig.Name == "" { - return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)") - } - - var addr sdk.AccAddress - var secret string - addr, secret, err = server.GenerateSaveCoinKey(genTxConfig.CliRoot, genTxConfig.Name, "1234567890", genTxConfig.Overwrite) - if err != nil { - return - } - mm := map[string]string{"secret": secret} - var bz []byte - bz, err = cdc.MarshalJSON(mm) - if err != nil { - return - } - cliPrint = json.RawMessage(bz) - appGenTx, _, validator, err = IrisAppGenTxNF(cdc, pk, addr, genTxConfig.Name) - return -} - -// Generate a gaia genesis transaction without flags -func IrisAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.AccAddress, name string) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - - var bz []byte - gaiaGenTx := IrisGenTx{ - Name: name, - Address: addr, - PubKey: sdk.MustBech32ifyAccPub(pk), - } - bz, err = wire.MarshalJSONIndent(cdc, gaiaGenTx) - if err != nil { - return - } - appGenTx = json.RawMessage(bz) - - validator = tmtypes.GenesisValidator{ - PubKey: pk, - Power: feeAmt, - } - return -} - -// Create the core parameters for genesis initialization for gaia -// note that the pubkey input is this machines pubkey -func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState GenesisState, err error) { - - if len(appGenTxs) == 0 { - err = errors.New("must provide at least genesis transaction") - return - } - - stakeData := createGenesisState() - genaccs := make([]GenesisAccount, len(appGenTxs)) - for i, appGenTx := range appGenTxs { - - var genTx IrisGenTx - err = cdc.UnmarshalJSON(appGenTx, &genTx) - if err != nil { - return - } - - // create the genesis account, give'm few steaks and a buncha token with there name - accAuth := auth.NewBaseAccountWithAddress(genTx.Address) - accAuth.Coins = sdk.Coins{ - freeFermionVal, - } - acc := NewGenesisAccount(&accAuth) - genaccs[i] = acc - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRatFromInt(freeFermionVal.Amount)) // increase the supply - - // add the validator - if len(genTx.Name) > 0 { - desc := stake.NewDescription(genTx.Name, "", "", "") - validator := stake.NewValidator(genTx.Address, - sdk.MustGetAccPubKeyBech32(genTx.PubKey), desc) - - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRatFromInt(freeFermionVal.Amount)) - - // add some new shares to the validator - var issuedDelShares sdk.Rat - validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, freeFermionVal.Amount) - //validator.TokenPrecision = stakeData.Params.DenomPrecision - stakeData.Validators = append(stakeData.Validators, validator) - - // create the self-delegation from the issuedDelShares - delegation := stake.Delegation{ - DelegatorAddr: validator.Owner, - ValidatorAddr: validator.Owner, - Shares: issuedDelShares, - Height: 0, - } - - stakeData.Bonds = append(stakeData.Bonds, delegation) - } - } - - // create the final app state - genesisState = GenesisState{ - Accounts: genaccs, - StakeData: stakeData, - } - return -} - -// IrisAppGenState but with JSON -func IrisAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) { - - // create the final app state - genesisState, err := IrisAppGenState(cdc, appGenTxs) - if err != nil { - return nil, err - } - appState, err = wire.MarshalJSONIndent(cdc, genesisState) - return -} - -func createGenesisState() stake.GenesisState { - return stake.GenesisState{ - Pool: stake.Pool{ - LooseTokens: sdk.ZeroRat(), - BondedTokens: sdk.ZeroRat(), - InflationLastTime: time.Unix(0, 0), - Inflation: sdk.NewRat(7, 100), - DateLastCommissionReset: 0, - PrevBondedShares: sdk.ZeroRat(), - }, - Params: stake.Params{ - InflationRateChange: sdk.NewRat(13, 100), - InflationMax: sdk.NewRat(20, 100), - InflationMin: sdk.NewRat(7, 100), - GoalBonded: sdk.NewRat(67, 100), - UnbondingTime: defaultUnbondingTime, - MaxValidators: 100, - BondDenom: Denom + "-" + types.Atto, - }, - } -} diff --git a/examples/irishub-bugfix-3/cmd/iris-bugfix-3/main.go b/examples/irishub-bugfix-3/cmd/iris-bugfix-3/main.go deleted file mode 100644 index 9755d3b11..000000000 --- a/examples/irishub-bugfix-3/cmd/iris-bugfix-3/main.go +++ /dev/null @@ -1,76 +0,0 @@ -package main - -import ( - "encoding/json" - "io" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/server" - "github.com/irisnet/irishub/examples/irishub-bugfix-3/app" - bam "github.com/irisnet/irishub/baseapp" - "github.com/irisnet/irishub/version" - - "github.com/spf13/viper" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/cli" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - "github.com/irisnet/irishub/tools/prometheus" -) - -func main() { - cdc := app.MakeCodec() - ctx := server.NewDefaultContext() - cobra.EnableCommandSorting = false - rootCmd := &cobra.Command{ - Use: "iris-bugfix-3", - Short: "iris-bugfix-3 Daemon (server)", - PersistentPreRunE: server.PersistentPreRunEFn(ctx), - } - - rootCmd.PersistentFlags().String("log_level", ctx.Config.LogLevel, "Log level") - - tendermintCmd := &cobra.Command{ - Use: "tendermint", - Short: "Tendermint subcommands", - } - - tendermintCmd.AddCommand( - server.ShowNodeIDCmd(ctx), - server.ShowValidatorCmd(ctx), - ) - - startCmd := server.StartCmd(ctx, server.ConstructAppCreator(newApp, "iris")) - startCmd.Flags().Bool(app.FlagReplay, false, "Replay the last block") - rootCmd.AddCommand( - server.InitCmd(ctx, cdc, app.IrisAppInit()), - startCmd, - server.TestnetFilesCmd(ctx, cdc, app.IrisAppInit()), - server.UnsafeResetAllCmd(ctx), - client.LineBreak, - tendermintCmd, - server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), - client.LineBreak, - version.ServeVersionCommand(cdc), - ) - - rootCmd.AddCommand(prometheus.MonitorCommand(cdc)) - - // prepare and add flags - executor := cli.PrepareBaseCmd(rootCmd, "IRIS", app.DefaultNodeHome) - executor.Execute() -} - -func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) abci.Application { - return app.NewIrisApp(logger, db, traceStore, bam.SetPruning(viper.GetString("pruning"))) -} - -func exportAppStateAndTMValidators( - logger log.Logger, db dbm.DB, traceStore io.Writer, -) (json.RawMessage, []tmtypes.GenesisValidator, error) { - gApp := app.NewIrisApp(logger, db, traceStore) - return gApp.ExportAppStateAndValidators() -} diff --git a/examples/irishub-bugfix-3/cmd/iriscli-bugfix-3/main.go b/examples/irishub-bugfix-3/cmd/iriscli-bugfix-3/main.go deleted file mode 100644 index a080f4edc..000000000 --- a/examples/irishub-bugfix-3/cmd/iriscli-bugfix-3/main.go +++ /dev/null @@ -1,170 +0,0 @@ -package main - -import ( - "github.com/spf13/cobra" - - "github.com/tendermint/tendermint/libs/cli" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/client/tx" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - ibccmd "github.com/irisnet/irishub/examples/irishub-bugfix-3/ibc/client/cli" - slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" - stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" - "github.com/irisnet/irishub/examples/irishub-bugfix-3/app" - govcmd "github.com/cosmos/cosmos-sdk/x/gov/client/cli" - upgradecmd "github.com/irisnet/irishub/client/upgrade/cli" - "github.com/irisnet/irishub/version" -) - -// rootCmd is the entry point for this binary -var ( - rootCmd = &cobra.Command{ - Use: "iriscli-bugfix-3", - Short: "irishub2 light-client", - } -) - -func main() { - cobra.EnableCommandSorting = false - cdc := app.MakeCodec() - - // TODO: setup keybase, viper object, etc. to be passed into - // the below functions and eliminate global vars, like we do - // with the cdc - - // add standard rpc commands - rpc.AddCommands(rootCmd) - - //Add state commands - tendermintCmd := &cobra.Command{ - Use: "tendermint", - Short: "Tendermint state querying subcommands", - } - tendermintCmd.AddCommand( - rpc.BlockCommand(), - rpc.ValidatorCommand(), - ) - tx.AddCommands(tendermintCmd, cdc) - - //Add IBC commands - ibcCmd := &cobra.Command{ - Use: "ibc", - Short: "Inter-Blockchain Communication subcommands", - } - ibcCmd.AddCommand( - client.PostCommands( - ibccmd.IBCTransferCmd(cdc), - ibccmd.IBCSetCmd(cdc), - ibccmd.IBCGetCmd(cdc), - )...) - - advancedCmd := &cobra.Command{ - Use: "advanced", - Short: "Advanced subcommands", - } - - advancedCmd.AddCommand( - tendermintCmd, - ibcCmd, - ) - rootCmd.AddCommand( - advancedCmd, - client.LineBreak, - ) - - //Add stake commands - stakeCmd := &cobra.Command{ - Use: "stake", - Short: "Stake and validation subcommands", - } - stakeCmd.AddCommand( - client.GetCommands( - stakecmd.GetCmdQueryValidator("stake", cdc), - stakecmd.GetCmdQueryValidators("stake", cdc), - stakecmd.GetCmdQueryDelegation("stake", cdc), - stakecmd.GetCmdQueryDelegations("stake", cdc), - slashingcmd.GetCmdQuerySigningInfo("slashing", cdc), - )...) - stakeCmd.AddCommand( - client.PostCommands( - stakecmd.GetCmdCreateValidator(cdc), - stakecmd.GetCmdEditValidator(cdc), - stakecmd.GetCmdDelegate(cdc), - stakecmd.GetCmdUnbond("stake", cdc), - stakecmd.GetCmdRedelegate("stake", cdc), - slashingcmd.GetCmdUnrevoke(cdc), - )...) - rootCmd.AddCommand( - stakeCmd, - ) - - //Add gov commands - govCmd := &cobra.Command{ - Use: "gov", - Short: "Governance and voting subcommands", - } - govCmd.AddCommand( - client.GetCommands( - govcmd.GetCmdQueryProposal("gov", cdc), - govcmd.GetCmdQueryVote("gov", cdc), - )...) - govCmd.AddCommand( - client.PostCommands( - govcmd.GetCmdSubmitProposal(cdc), - govcmd.GetCmdDeposit(cdc), - govcmd.GetCmdVote(cdc), - )...) - rootCmd.AddCommand( - govCmd, - ) - - //Add upgrade commands - upgradeCmd := &cobra.Command{ - Use: "upgrade", - Short: "Software Upgrade subcommands", - } - upgradeCmd.AddCommand( - client.GetCommands( - upgradecmd.GetCmdQuerySwitch("upgrade", cdc), - upgradecmd.GetInfoCmd("upgrade", cdc), - )...) - upgradeCmd.AddCommand( - client.PostCommands( - upgradecmd.GetCmdSubmitSwitch(cdc), - )...) - rootCmd.AddCommand( - upgradeCmd, - ) - - //Add auth and bank commands - rootCmd.AddCommand( - client.GetCommands( - authcmd.GetAccountCmd("acc", cdc, authcmd.GetAccountDecoder(cdc)), - )...) - rootCmd.AddCommand( - client.PostCommands( - bankcmd.SendTxCmd(cdc), - )...) - - // add proxy, version and key info - rootCmd.AddCommand( - keys.Commands(), - client.LineBreak, - ) - rootCmd.AddCommand( - client.GetCommands( - version.ServeVersionCommand(cdc), - )...) - - // prepare and add flags - executor := cli.PrepareMainCmd(rootCmd, "GA", app.DefaultCLIHome) - err := executor.Execute() - if err != nil { - // handle with #870 - panic(err) - } -} diff --git a/examples/irishub-bugfix-3/ibc/client/cli/README.md b/examples/irishub-bugfix-3/ibc/client/cli/README.md deleted file mode 100644 index ab9e8e555..000000000 --- a/examples/irishub-bugfix-3/ibc/client/cli/README.md +++ /dev/null @@ -1,157 +0,0 @@ -# IBC Doubble Hubble - -## Remove remaining data - -```console -> rm -r ~/.chain1 -> rm -r ~/.chain2 -> rm -r ~/.basecli -``` - -## Initialize both chains - -```console -> basecoind init --home ~/.chain1 -I[04-02|14:03:33.704] Generated private validator module=main path=/home/mossid/.chain1/config/priv_validator.json -I[04-02|14:03:33.705] Generated genesis file module=main path=/home/mossid/.chain1/config/genesis.json -{ - "secret": "crunch ignore trigger neither differ dance cheap brick situate floor luxury citizen husband decline arrow abandon", - "account": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "validator": { - "pub_key": { - "type": "ed25519", - "data": "8C9917D5E982E221F5A1450103102B44BBFC1E8768126C606246CB37B5794F4D" - }, - "power": 10, - "name": "" - }, - "node_id": "3ac8e6242315fd62143dc3e52c161edaaa6b1a64", - "chain_id": "test-chain-ZajMfr" -} -> ADDR1=C69FEB398A29AAB1B3C4F07DE22208F35E711BCC -> ID1=test-chain-ZajMfr -> NODE1=tcp://0.0.0.0:36657 -> basecli keys add key1 --recover -Enter a passphrase for your key: -Repeat the passphrase: -Enter your recovery seed phrase: -crunch ignore trigger neither differ dance cheap brick situate floor luxury citizen husband decline arrow abandon -key1 C69FEB398A29AAB1B3C4F07DE22208F35E711BCC - - -> basecoind init --home ~/.chain2 -I[04-02|14:09:14.453] Generated private validator module=main path=/home/mossid/.chain2/config/priv_validator.json -I[04-02|14:09:14.453] Generated genesis file module=main path=/home/mossid/.chain2/config/genesis.json -{ - "secret": "age guide awesome month female left oxygen soccer define high grocery work desert dinner arena abandon", - "account": "DC26002735D3AA9573707CFA6D77C12349E49868", - "validator": { - "pub_key": { - "type": "ed25519", - "data": "A94FE4B9AD763D301F4DD5A2766009812495FB7A79F1275FB8A5AF09B44FD5F3" - }, - "power": 10, - "name": "" - }, - "node_id": "ad26831330e1c72b85276d53c20f0680e6fd4cf5" - "chain_id": "test-chain-4XHTPn" -} -> ADDR2=DC26002735D3AA9573707CFA6D77C12349E49868 -> ID2=test-chain-4XHTPn -> NODE2=tcp://0.0.0.0:26657 -> basecli keys add key2 --recover -Enter a passphrase for your key: -Repeat the passphrase: -Enter your recovery seed phrase: -age guide awesome month female left oxygen soccer define high grocery work desert dinner arena abandon -key2 DC26002735D3AA9573707CFA6D77C12349E49868 - - -> basecoind start --home ~/.chain1 --address tcp://0.0.0.0:36658 --rpc.laddr tcp://0.0.0.0:36657 --p2p.laddr tcp://0.0.0.0:36656 -... - -> basecoind start --home ~/.chain2 # --address tcp://0.0.0.0:26658 --rpc.laddr tcp://0.0.0.0:26657 --p2p.laddr tcp://0.0.0.0:26656 -... -``` -## Check balance - -```console -> basecli account $ADDR1 --node $NODE1 -{ - "address": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740992 - } - ], - "public_key": null, - "sequence": 0, - "name": "" -} - -> basecli account $ADDR2 --node $NODE2 -{ - "address": "DC26002735D3AA9573707CFA6D77C12349E49868", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740992 - } - ], - "public_key": null, - "sequence": 0, - "name": "" -} - -``` - -## Transfer coins (addr1:chain1 -> addr2:chain2) - -```console -> basecli transfer --from key1 --to $ADDR2 --amount 10mycoin --chain $ID2 --chain-id $ID1 --node $NODE1 -Password to sign with 'key1': -Committed at block 1022. Hash: E16019DCC4AA08CA70AFCFBC96028ABCC51B6AD0 -> basecli account $ADDR1 --node $NODE1 -{ - "address": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740982 - } - ], - "public_key": { - "type": "ed25519", - "data": "9828FF1780A066A0D93D840737566B697035448D6C880807322BED8919348B2B" - }, - "sequence": 1, - "name": "" -} -``` - -## Relay IBC packets - -```console -> basecli relay --from key2 --from-chain-id $ID1 --from-chain-node $NODE1 --to-chain-id $ID2 --to-chain-node $NODE2 --chain-id $ID2 -Password to sign with 'key2': -I[04-03|16:18:59.984] Detected IBC packet number=0 -I[04-03|16:19:00.869] Relayed IBC packet number=0 -> basecli account $ADDR2 --node $NODE2 -{ - "address": "DC26002735D3AA9573707CFA6D77C12349E49868", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254741002 - } - ], - "public_key": { - "type": "ed25519", - "data": "F52B4FA545F4E9BFE5D7AF1DD2236899FDEF905F9B3057C38D7C01BF1B8EB52E" - }, - "sequence": 1, - "name": "" -} - -``` diff --git a/examples/irishub-bugfix-3/ibc/client/cli/ibctx.go b/examples/irishub-bugfix-3/ibc/client/cli/ibctx.go deleted file mode 100644 index 8a729b697..000000000 --- a/examples/irishub-bugfix-3/ibc/client/cli/ibctx.go +++ /dev/null @@ -1,84 +0,0 @@ -package cli - -import ( - "encoding/hex" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" - - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - authctx "github.com/cosmos/cosmos-sdk/x/auth/client/context" - "github.com/cosmos/cosmos-sdk/x/ibc" - "os" - "github.com/cosmos/cosmos-sdk/client/utils" -) - -const ( - flagTo = "to" - flagAmount = "amount" - flagChain = "chain" -) - -// IBC transfer command -func IBCTransferCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "transfer", - RunE: func(cmd *cobra.Command, args []string) error { - txCtx := authctx.NewTxContextFromCLI().WithCodec(cdc) - cliCtx := context.NewCLIContext(). - WithCodec(cdc). - WithLogger(os.Stdout). - WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - - // get the from address - from, err := cliCtx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg, err := buildMsg(from) - if err != nil { - return err - } - - cliCtx.PrintResponse = true - return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) - }, - } - - cmd.Flags().String(flagTo, "", "Address to send coins") - cmd.Flags().String(flagAmount, "", "Amount of coins to send") - cmd.Flags().String(flagChain, "", "Destination chain to send coins") - return cmd -} - -func buildMsg(from sdk.AccAddress) (sdk.Msg, error) { - amount := viper.GetString(flagAmount) - coins, err := sdk.ParseCoins(amount) - if err != nil { - return nil, err - } - - dest := viper.GetString(flagTo) - bz, err := hex.DecodeString(dest) - if err != nil { - return nil, err - } - to := sdk.AccAddress(bz) - - packet := ibc.NewIBCPacket(from, to, coins, viper.GetString(client.FlagChainID), - viper.GetString(flagChain)) - - msg := ibc.IBCTransferMsg{ - IBCPacket: packet, - } - - return msg, nil -} diff --git a/examples/irishub-bugfix-3/ibc/client/cli/tx.go b/examples/irishub-bugfix-3/ibc/client/cli/tx.go deleted file mode 100644 index db7ac5d02..000000000 --- a/examples/irishub-bugfix-3/ibc/client/cli/tx.go +++ /dev/null @@ -1,66 +0,0 @@ -package cli - -import ( - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - authctx "github.com/cosmos/cosmos-sdk/x/auth/client/context" - "github.com/irisnet/irishub/examples/irishub-bugfix-3/ibc" - "os" - "github.com/cosmos/cosmos-sdk/client/utils" -) - -// IBC transfer command -func IBCGetCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "get", - RunE: func(cmd *cobra.Command, args []string) error { - txCtx := authctx.NewTxContextFromCLI().WithCodec(cdc) - cliCtx := context.NewCLIContext(). - WithCodec(cdc). - WithLogger(os.Stdout). - WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - - from, err := cliCtx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg := ibc.NewIBCGetMsg(from) - - cliCtx.PrintResponse = true - return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) - }, - } - return cmd -} - - -// IBC transfer command -func IBCSetCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "set", - RunE: func(cmd *cobra.Command, args []string) error { - txCtx := authctx.NewTxContextFromCLI().WithCodec(cdc) - cliCtx := context.NewCLIContext(). - WithCodec(cdc). - WithLogger(os.Stdout). - WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - - from, err := cliCtx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg := ibc.NewIBCSetMsg(from) - - cliCtx.PrintResponse = true - return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) - }, - } - return cmd -} diff --git a/examples/irishub-bugfix-3/ibc/errors.go b/examples/irishub-bugfix-3/ibc/errors.go deleted file mode 100644 index 7a3194baf..000000000 --- a/examples/irishub-bugfix-3/ibc/errors.go +++ /dev/null @@ -1,50 +0,0 @@ -package ibc - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// IBC errors reserve 200 ~ 299. -const ( - DefaultCodespace sdk.CodespaceType = 3 - - // IBC errors reserve 200 - 299. - CodeInvalidSequence sdk.CodeType = 200 - CodeIdenticalChains sdk.CodeType = 201 - CodeUnknownRequest sdk.CodeType = sdk.CodeUnknownRequest -) - -func codeToDefaultMsg(code sdk.CodeType) string { - switch code { - case CodeInvalidSequence: - return "invalid IBC packet sequence" - case CodeIdenticalChains: - return "source and destination chain cannot be identical" - default: - return sdk.CodeToDefaultMsg(code) - } -} - -// nolint -func ErrInvalidSequence(codespace sdk.CodespaceType) sdk.Error { - return newError(codespace, CodeInvalidSequence, "") -} -func ErrIdenticalChains(codespace sdk.CodespaceType) sdk.Error { - return newError(codespace, CodeIdenticalChains, "") -} - -// ------------------------- -// Helpers - -// nolint: unparam -func newError(codespace sdk.CodespaceType, code sdk.CodeType, msg string) sdk.Error { - msg = msgOrDefaultMsg(msg, code) - return sdk.NewError(codespace, code, msg) -} - -func msgOrDefaultMsg(msg string, code sdk.CodeType) string { - if msg != "" { - return msg - } - return codeToDefaultMsg(code) -} diff --git a/examples/irishub-bugfix-3/ibc/handler.go b/examples/irishub-bugfix-3/ibc/handler.go deleted file mode 100644 index 3d742fd03..000000000 --- a/examples/irishub-bugfix-3/ibc/handler.go +++ /dev/null @@ -1,87 +0,0 @@ -package ibc - -import ( - "reflect" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/irisnet/irishub/modules/upgrade" -) - -func NewHandler(ibcm Mapper, ck bank.Keeper, uk upgrade.Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { - switch msg := msg.(type) { - case IBCTransferMsg: - return handleIBCTransferMsg(ctx, ibcm, ck, msg) - case IBCReceiveMsg: - return handleIBCReceiveMsg(ctx, ibcm, ck, msg) - case IBCGetMsg: - return handleIBCGetMsg(ctx, ibcm, ck, uk, msg) - case IBCSetMsg: - return handleIBCSetMsg(ctx, ibcm, ck, uk, msg) - default: - errMsg := "Unrecognized IBC Msg type: " + reflect.TypeOf(msg).Name() - return sdk.ErrUnknownRequest(errMsg).Result() - } - } -} - -// IBCTransferMsg deducts coins from the account and creates an egress IBC packet. -func handleIBCTransferMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCTransferMsg) sdk.Result { - packet := msg.IBCPacket - - _, _, err := ck.SubtractCoins(ctx, packet.SrcAddr, packet.Coins) - if err != nil { - return err.Result() - } - - err = ibcm.PostIBCPacket(ctx, packet) - if err != nil { - return err.Result() - } - - return sdk.Result{} -} - -// IBCReceiveMsg adds coins to the destination address and creates an ingress IBC packet. -func handleIBCReceiveMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCReceiveMsg) sdk.Result { - packet := msg.IBCPacket - - seq := ibcm.GetIngressSequence(ctx, packet.SrcChain) - if msg.Sequence != seq { - return ErrInvalidSequence(ibcm.codespace).Result() - } - - _, _, err := ck.AddCoins(ctx, packet.DestAddr, packet.Coins) - if err != nil { - return err.Result() - } - - ibcm.SetIngressSequence(ctx, packet.SrcChain, seq+1) - - return sdk.Result{} -} - -// IBCTransferMsg deducts coins from the account and creates an egress IBC packet. -func handleIBCSetMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, uk upgrade.Keeper, msg IBCSetMsg) sdk.Result { - - if uk.OnlyRunAfterVersionId(ctx, 3) { - ibcm.Set(ctx,msg.Addr.String()+":ibc-3") - return sdk.Result{Log:"This is new module - ibc3 !!"} - } else if uk.OnlyRunAfterVersionId(ctx, 2) { - ibcm.Set(ctx,msg.Addr.String()+":ibc-2") - return sdk.Result{Log:"This is new module - ibc2 !!"} - } else if uk.OnlyRunAfterVersionId(ctx, 1) { - ibcm.Set(ctx,msg.Addr.String()+":ibc-1") - return sdk.Result{Log:"This is new module - ibc1 !!"} - } else { - ibcm.Set(ctx,msg.Addr.String()+":ibc-0") - return sdk.Result{Log:"This is new module - ibc0 !!"} - } -} - -// IBCReceiveMsg adds coins to the destination address and creates an ingress IBC packet. -func handleIBCGetMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, uk upgrade.Keeper, msg IBCGetMsg) sdk.Result { - AddrString,_:=ibcm.Get(ctx) - return sdk.Result{Log:AddrString} -} diff --git a/examples/irishub-bugfix-3/ibc/mapper.go b/examples/irishub-bugfix-3/ibc/mapper.go deleted file mode 100644 index 2ccc93d1a..000000000 --- a/examples/irishub-bugfix-3/ibc/mapper.go +++ /dev/null @@ -1,149 +0,0 @@ -package ibc - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" -) - -// IBC Mapper -type Mapper struct { - key sdk.StoreKey - cdc *wire.Codec - codespace sdk.CodespaceType -} - -// XXX: The Mapper should not take a CoinKeeper. Rather have the CoinKeeper -// take an Mapper. -func NewMapper(cdc *wire.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) Mapper { - // XXX: How are these codecs supposed to work? - return Mapper{ - key: key, - cdc: cdc, - codespace: codespace, - } -} - -// XXX: This is not the public API. This will change in MVP2 and will henceforth -// only be invoked from another module directly and not through a user -// transaction. -// TODO: Handle invalid IBC packets and return errors. -func (ibcm Mapper) PostIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error { - // write everything into the state - store := ctx.KVStore(ibcm.key) - index := ibcm.getEgressLength(store, packet.DestChain) - bz, err := ibcm.cdc.MarshalBinary(packet) - if err != nil { - panic(err) - } - - store.Set(EgressKey(packet.DestChain, index), bz) - bz, err = ibcm.cdc.MarshalBinary(index + 1) - if err != nil { - panic(err) - } - store.Set(EgressLengthKey(packet.DestChain), bz) - - return nil -} - -// XXX: In the future every module is able to register it's own handler for -// handling it's own IBC packets. The "ibc" handler will only route the packets -// to the appropriate callbacks. -// XXX: For now this handles all interactions with the CoinKeeper. -// XXX: This needs to do some authentication checking. -func (ibcm Mapper) ReceiveIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error { - return nil -} - -// -------------------------- -// Functions for accessing the underlying KVStore. - -func marshalBinaryPanic(cdc *wire.Codec, value interface{}) []byte { - res, err := cdc.MarshalBinary(value) - if err != nil { - panic(err) - } - return res -} - -func unmarshalBinaryPanic(cdc *wire.Codec, bz []byte, ptr interface{}) { - err := cdc.UnmarshalBinary(bz, ptr) - if err != nil { - panic(err) - } -} - -// TODO add description -func (ibcm Mapper) GetIngressSequence(ctx sdk.Context, srcChain string) int64 { - store := ctx.KVStore(ibcm.key) - key := IngressSequenceKey(srcChain) - - bz := store.Get(key) - if bz == nil { - zero := marshalBinaryPanic(ibcm.cdc, int64(0)) - store.Set(key, zero) - return 0 - } - - var res int64 - unmarshalBinaryPanic(ibcm.cdc, bz, &res) - return res -} - -// TODO add description -func (ibcm Mapper) SetIngressSequence(ctx sdk.Context, srcChain string, sequence int64) { - store := ctx.KVStore(ibcm.key) - key := IngressSequenceKey(srcChain) - - bz := marshalBinaryPanic(ibcm.cdc, sequence) - store.Set(key, bz) -} - -// Retrieves the index of the currently stored outgoing IBC packets. -func (ibcm Mapper) getEgressLength(store sdk.KVStore, destChain string) int64 { - bz := store.Get(EgressLengthKey(destChain)) - if bz == nil { - zero := marshalBinaryPanic(ibcm.cdc, int64(0)) - store.Set(EgressLengthKey(destChain), zero) - return 0 - } - var res int64 - unmarshalBinaryPanic(ibcm.cdc, bz, &res) - return res -} - -// Stores an outgoing IBC packet under "egress/chain_id/index". -func EgressKey(destChain string, index int64) []byte { - return []byte(fmt.Sprintf("egress/%s/%d", destChain, index)) -} - -// Stores the number of outgoing IBC packets under "egress/index". -func EgressLengthKey(destChain string) []byte { - return []byte(fmt.Sprintf("egress/%s", destChain)) -} - -// Stores the sequence number of incoming IBC packet under "ingress/index". -func IngressSequenceKey(srcChain string) []byte { - return []byte(fmt.Sprintf("ingress/%s", srcChain)) -} - - -// Gets the vote of a specific voter on a specific proposal -func (ibcm Mapper) Get(ctx sdk.Context) (string, bool) { - store := ctx.KVStore(ibcm.key) - bz := store.Get([]byte("ibcaddr")) - if bz == nil { - return " ", false - } - var Addr string - ibcm.cdc.MustUnmarshalBinary(bz, &Addr) - return Addr, true -} - -func (ibcm Mapper) Set(ctx sdk.Context,Addr string) { - store := ctx.KVStore(ibcm.key) - bz := ibcm.cdc.MustMarshalBinary(Addr) - store.Set([]byte("ibcaddr"), bz) -} \ No newline at end of file diff --git a/examples/irishub-bugfix-3/ibc/types.go b/examples/irishub-bugfix-3/ibc/types.go deleted file mode 100644 index 0537ff816..000000000 --- a/examples/irishub-bugfix-3/ibc/types.go +++ /dev/null @@ -1,184 +0,0 @@ -package ibc - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" -) - -var ( - msgCdc *wire.Codec -) - -func init() { - msgCdc = wire.NewCodec() -} - -// ------------------------------ -// IBCPacket - -// nolint - TODO rename to Packet as IBCPacket stutters (golint) -// IBCPacket defines a piece of data that can be send between two separate -// blockchains. -type IBCPacket struct { - SrcAddr sdk.AccAddress - DestAddr sdk.AccAddress - Coins sdk.Coins - SrcChain string - DestChain string -} - -func NewIBCPacket(srcAddr sdk.AccAddress, destAddr sdk.AccAddress, coins sdk.Coins, - srcChain string, destChain string) IBCPacket { - - return IBCPacket{ - SrcAddr: srcAddr, - DestAddr: destAddr, - Coins: coins, - SrcChain: srcChain, - DestChain: destChain, - } -} - -//nolint -func (p IBCPacket) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(p) - if err != nil { - panic(err) - } - return sdk.MustSortJSON(b) -} - -// validator the ibc packey -func (p IBCPacket) ValidateBasic() sdk.Error { - if p.SrcChain == p.DestChain { - return ErrIdenticalChains(DefaultCodespace).TraceSDK("") - } - if !p.Coins.IsValid() { - return sdk.ErrInvalidCoins("") - } - return nil -} - -// ---------------------------------- -// IBCTransferMsg - -// nolint - TODO rename to TransferMsg as folks will reference with ibc.TransferMsg -// IBCTransferMsg defines how another module can send an IBCPacket. -type IBCTransferMsg struct { - IBCPacket -} - -// nolint -func (msg IBCTransferMsg) Type() string { return "ibc-1" } - -// x/bank/tx.go MsgSend.GetSigners() -func (msg IBCTransferMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.SrcAddr} } - -// get the sign bytes for ibc transfer message -func (msg IBCTransferMsg) GetSignBytes() []byte { - return msg.IBCPacket.GetSignBytes() -} - -// validate ibc transfer message -func (msg IBCTransferMsg) ValidateBasic() sdk.Error { - return msg.IBCPacket.ValidateBasic() -} - -// ---------------------------------- -// IBCReceiveMsg - -// nolint - TODO rename to ReceiveMsg as folks will reference with ibc.ReceiveMsg -// IBCReceiveMsg defines the message that a relayer uses to post an IBCPacket -// to the destination chain. -type IBCReceiveMsg struct { - IBCPacket - Relayer sdk.AccAddress - Sequence int64 -} - -// nolint -func (msg IBCReceiveMsg) Type() string { return "ibc-1" } -func (msg IBCReceiveMsg) ValidateBasic() sdk.Error { return msg.IBCPacket.ValidateBasic() } - -// x/bank/tx.go MsgSend.GetSigners() -func (msg IBCReceiveMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Relayer} } - -// get the sign bytes for ibc receive message -func (msg IBCReceiveMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(struct { - IBCPacket json.RawMessage - Relayer sdk.AccAddress - Sequence int64 - }{ - IBCPacket: json.RawMessage(msg.IBCPacket.GetSignBytes()), - Relayer: msg.Relayer, - Sequence: msg.Sequence, - }) - if err != nil { - panic(err) - } - return sdk.MustSortJSON(b) -} - - -type IBCSetMsg struct { - Addr sdk.AccAddress -} - -func NewIBCSetMsg(addr sdk.AccAddress) IBCSetMsg { - return IBCSetMsg{ - Addr:addr, - } -} - -func (msg IBCSetMsg) Type() string { - return "ibc-1" -} - -func (msg IBCSetMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(msg) - if err != nil { - panic(err) - } - return b -} - -func (msg IBCSetMsg) ValidateBasic() sdk.Error { - return nil -} - -func (msg IBCSetMsg) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Addr} -} - -type IBCGetMsg struct { - Addr sdk.AccAddress -} - -func NewIBCGetMsg(addr sdk.AccAddress) IBCGetMsg { - return IBCGetMsg{ - Addr:addr, - } -} - -func (msg IBCGetMsg) Type() string { - return "ibc-1" -} - -func (msg IBCGetMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(msg) - if err != nil { - panic(err) - } - return b -} - -func (msg IBCGetMsg) ValidateBasic() sdk.Error { - return nil -} - -func (msg IBCGetMsg) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Addr} -} diff --git a/examples/irishub-bugfix-3/ibc/wire.go b/examples/irishub-bugfix-3/ibc/wire.go deleted file mode 100644 index 821a527ab..000000000 --- a/examples/irishub-bugfix-3/ibc/wire.go +++ /dev/null @@ -1,13 +0,0 @@ -package ibc - -import ( - "github.com/cosmos/cosmos-sdk/wire" -) - -// Register concrete types on wire codec -func RegisterWire(cdc *wire.Codec) { - cdc.RegisterConcrete(IBCTransferMsg{}, "cosmos-sdk/IBCTransferMsg/2", nil) - cdc.RegisterConcrete(IBCReceiveMsg{}, "cosmos-sdk/IBCReceiveMsg/2", nil) - cdc.RegisterConcrete(IBCSetMsg{},"cosmos-sdk/IBCSetMsg/2",nil) - cdc.RegisterConcrete(IBCGetMsg{},"cosmos-sdk/IBCGetMsg/2",nil) -} diff --git a/examples/irishub2/app/app.go b/examples/irishub2/app/app.go deleted file mode 100644 index 3cb0bfc8e..000000000 --- a/examples/irishub2/app/app.go +++ /dev/null @@ -1,379 +0,0 @@ -package app - -import ( - "encoding/json" - "io" - "os" - - bam "github.com/irisnet/irishub/baseapp" - abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - - 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/bank" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/ibc" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/stake" - ibc1 "github.com/irisnet/irishub/examples/irishub1/ibc" - ibc2 "github.com/irisnet/irishub/examples/irishub2/ibc" - "github.com/irisnet/irishub/modules/upgrade" - - "errors" - "fmt" - "github.com/cosmos/cosmos-sdk/server" - "github.com/spf13/viper" - tmcli "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/node" - sm "github.com/tendermint/tendermint/state" - bc "github.com/tendermint/tendermint/blockchain" - "strings" -) - -const ( - appName = "IrisApp" - FlagReplay = "replay" -) - -// default home directories for expected binaries -var ( - DefaultCLIHome = os.ExpandEnv("$HOME/.iriscli") - DefaultNodeHome = os.ExpandEnv("$HOME/.iris") -) - -// Extended ABCI application -type IrisApp struct { - *bam.BaseApp - cdc *wire.Codec - - // keys to access the substores - keyMain *sdk.KVStoreKey - keyAccount *sdk.KVStoreKey - keyIBC *sdk.KVStoreKey - keyStake *sdk.KVStoreKey - keySlashing *sdk.KVStoreKey - keyGov *sdk.KVStoreKey - keyFeeCollection *sdk.KVStoreKey - keyParams *sdk.KVStoreKey - keyUpgrade *sdk.KVStoreKey - - // Manage getting and setting accounts - accountMapper auth.AccountMapper - feeCollectionKeeper auth.FeeCollectionKeeper - coinKeeper bank.Keeper - ibcMapper ibc.Mapper - ibc1Mapper ibc1.Mapper - ibc2Mapper ibc2.Mapper - stakeKeeper stake.Keeper - slashingKeeper slashing.Keeper - govKeeper gov.Keeper - paramsKeeper params.Keeper - upgradeKeeper upgrade.Keeper - - // fee manager - feeManager bam.FeeManager -} - -func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptions ...func(*bam.BaseApp)) *IrisApp { - cdc := MakeCodec() - - bApp := bam.NewBaseApp(appName, cdc, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...) - bApp.SetCommitMultiStoreTracer(traceStore) - - // create your application object - var app = &IrisApp{ - BaseApp: bApp, - cdc: cdc, - keyMain: sdk.NewKVStoreKey("main"), - keyAccount: sdk.NewKVStoreKey("acc"), - keyIBC: sdk.NewKVStoreKey("ibc"), - keyStake: sdk.NewKVStoreKey("stake"), - keySlashing: sdk.NewKVStoreKey("slashing"), - keyGov: sdk.NewKVStoreKey("gov"), - keyFeeCollection: sdk.NewKVStoreKey("fee"), - keyParams: sdk.NewKVStoreKey("params"), - keyUpgrade: sdk.NewKVStoreKey("upgrade"), - } - - var lastHeight int64 - if viper.GetBool(FlagReplay) { - lastHeight = app.replay() - } - - // define the accountMapper - app.accountMapper = auth.NewAccountMapper( - app.cdc, - app.keyAccount, // target store - auth.ProtoBaseAccount, // prototype - ) - - // add handlers - app.paramsKeeper = params.NewKeeper(app.cdc, app.keyParams) - app.coinKeeper = bank.NewKeeper(app.accountMapper) - - app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace)) - app.ibc1Mapper = ibc1.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc1.DefaultCodespace)) - app.ibc2Mapper = ibc2.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc1.DefaultCodespace)) - - app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) - app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.paramsKeeper.Getter(), app.RegisterCodespace(slashing.DefaultCodespace)) - app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection) - app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper) - app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - //app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - - // register message routes - // need to update each module's msg type - app.Router(). - AddRoute("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.coinKeeper)). - AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). - AddRoute("ibc-1", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc1.NewHandler(app.ibc1Mapper, app.coinKeeper)). - AddRoute("ibc-2", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc2.NewHandler(app.ibc2Mapper, app.coinKeeper)). - AddRoute("stake", []*sdk.KVStoreKey{app.keyStake, app.keyAccount}, stake.NewHandler(app.stakeKeeper)). - AddRoute("slashing", []*sdk.KVStoreKey{app.keySlashing, app.keyStake}, slashing.NewHandler(app.slashingKeeper)). - AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake, app.keyParams}, gov.NewHandler(app.govKeeper)). - AddRoute("upgrade", []*sdk.KVStoreKey{app.keyUpgrade, app.keyStake}, upgrade.NewHandler(app.upgradeKeeper)) - - app.feeManager = bam.NewFeeManager(app.paramsKeeper.Setter()) - - // initialize BaseApp - app.SetInitChainer(app.initChainer) - app.SetBeginBlocker(app.BeginBlocker) - app.SetEndBlocker(app.EndBlocker) - app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) - app.SetFeeRefundHandler(bam.NewFeeRefundHandler(app.accountMapper, app.feeCollectionKeeper, app.feeManager)) - app.SetFeePreprocessHandler(bam.NewFeePreprocessHandler(app.feeManager)) - app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing, app.keyGov, app.keyFeeCollection, app.keyParams, app.keyUpgrade) - app.SetRunMsg(app.runMsgs) - var err error - if viper.GetBool(FlagReplay) { - err = app.LoadVersion(lastHeight, app.keyMain) - } else { - err = app.LoadLatestVersion(app.keyMain) - } - if err != nil { - cmn.Exit(err.Error()) - } - - upgrade.RegisterModuleList(app.Router()) - - return app -} - -// custom tx codec -func MakeCodec() *wire.Codec { - var cdc = wire.NewCodec() - ibc.RegisterWire(cdc) - ibc1.RegisterWire(cdc) - ibc2.RegisterWire(cdc) - bank.RegisterWire(cdc) - stake.RegisterWire(cdc) - slashing.RegisterWire(cdc) - gov.RegisterWire(cdc) - auth.RegisterWire(cdc) - upgrade.RegisterWire(cdc) - sdk.RegisterWire(cdc) - wire.RegisterCrypto(cdc) - return cdc -} - -// application updates every end block -func (app *IrisApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) - - return abci.ResponseBeginBlock{ - Tags: tags.ToKVPairs(), - } -} - -// application updates every end block -func (app *IrisApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) - - tags := gov.EndBlocker(ctx, app.govKeeper) - tags.AppendTags(upgrade.EndBlocker(ctx, app.upgradeKeeper)) - - return abci.ResponseEndBlock{ - ValidatorUpdates: validatorUpdates, - Tags: tags, - } -} - -// custom logic for iris initialization -func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { - stateJSON := req.AppStateBytes - - var genesisState GenesisState - err := app.cdc.UnmarshalJSON(stateJSON, &genesisState) - if err != nil { - panic(err) - } - - // load the accounts - for _, gacc := range genesisState.Accounts { - acc := gacc.ToAccount() - acc.AccountNumber = app.accountMapper.GetNextAccountNumber(ctx) - app.accountMapper.SetAccount(ctx, acc) - } - - // load the initial stake information - validators, err := stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData) - if err != nil { - panic(err) - } - - minDeposit,err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s",10,Denom)) - if err != nil { - panic(err) - } - - gov.InitGenesis(ctx, app.govKeeper, gov.GenesisState{ - StartingProposalID: 1, - DepositProcedure: gov.DepositProcedure{ - MinDeposit: sdk.Coins{minDeposit}, - MaxDepositPeriod: 1440, - }, - VotingProcedure: gov.VotingProcedure{ - VotingPeriod: 30, - }, - TallyingProcedure: gov.TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 100), - }, - }) - - feeTokenGensisConfig := bam.FeeGenesisStateConfig{ - FeeTokenNative: IrisCt.MinUnit.Denom, - GasPriceThreshold: 20000000000, // 20(glue), 20*10^9, 1 glue = 10^9 lue/gas, 1 iris = 10^18 lue - } - - bam.InitGenesis(ctx, app.paramsKeeper.Setter(), feeTokenGensisConfig) - - // load the address to pubkey map - slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.StakeData) - - upgrade.InitGenesis(ctx, app.upgradeKeeper, app.Router()) - - return abci.ResponseInitChain{ - Validators: validators, - } -} - -// export the state of iris for a genesis file -func (app *IrisApp) ExportAppStateAndValidators() (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) { - ctx := app.NewContext(true, abci.Header{}) - - // iterate to get the accounts - accounts := []GenesisAccount{} - appendAccount := func(acc auth.Account) (stop bool) { - account := NewGenesisAccountI(acc) - accounts = append(accounts, account) - return false - } - app.accountMapper.IterateAccounts(ctx, appendAccount) - - genState := GenesisState{ - Accounts: accounts, - StakeData: stake.WriteGenesis(ctx, app.stakeKeeper), - } - appState, err = wire.MarshalJSONIndent(app.cdc, genState) - if err != nil { - return nil, nil, err - } - validators = stake.WriteValidators(ctx, app.stakeKeeper) - return appState, validators, nil -} - -// Iterates through msgs and executes them -func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) { - // accumulate results - logs := make([]string, 0, len(msgs)) - var data []byte // NOTE: we just append them all (?!) - var tags sdk.Tags // also just append them all - var code sdk.ABCICodeType - for msgIdx, msg := range msgs { - // Match route. - msgType, err := app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) - fmt.Println("============ runMsgs() =========== " + msgType) - if err != nil { - return err.Result() - } - - handler := app.Router().Route(msgType) - if handler == nil { - return sdk.ErrUnknownRequest("Unrecognized Msg type: " + msgType).Result() - } - fmt.Println(msg) - msgResult := handler(ctx, msg) - - // NOTE: GasWanted is determined by ante handler and - // GasUsed by the GasMeter - - // Append Data and Tags - data = append(data, msgResult.Data...) - tags = append(tags, msgResult.Tags...) - - // Stop execution and return on first failed message. - if !msgResult.IsOK() { - logs = append(logs, fmt.Sprintf("Msg %d failed: %s", msgIdx, msgResult.Log)) - code = msgResult.Code - break - } - - // Construct usable logs in multi-message transactions. - logs = append(logs, fmt.Sprintf("Msg %d: %s", msgIdx, msgResult.Log)) - } - - // Set the final gas values. - result = sdk.Result{ - Code: code, - Data: data, - Log: strings.Join(logs, "\n"), - GasUsed: ctx.GasMeter().GasConsumed(), - // TODO: FeeAmount/FeeDenom - Tags: tags, - } - - return result -} - -func (app *IrisApp) replay() int64 { - ctx := server.NewDefaultContext() - ctx.Config.RootDir = viper.GetString(tmcli.HomeFlag) - dbContext := node.DBContext{"state", ctx.Config} - dbType := dbm.DBBackendType(dbContext.Config.DBBackend) - stateDB := dbm.NewDB(dbContext.ID, dbType, dbContext.Config.DBDir()) - - blockDBContext := node.DBContext{"blockstore", ctx.Config} - blockStoreDB := dbm.NewDB(blockDBContext.ID, dbType, dbContext.Config.DBDir()) - blockStore := bc.NewBlockStore(blockStoreDB) - - defer func() { - stateDB.Close() - blockStoreDB.Close() - } () - - curState := sm.LoadState(stateDB) - preState := sm.LoadPreState(stateDB) - if curState.LastBlockHeight == preState.LastBlockHeight { - panic(errors.New("there is no block now, can't replay")) - } - var loadHeight int64 - if blockStore.Height() == curState.LastBlockHeight { - sm.SaveState(stateDB, preState) - loadHeight = preState.LastBlockHeight - } else if blockStore.Height() == curState.LastBlockHeight+1 { - loadHeight = curState.LastBlockHeight - } else { - panic(errors.New("tendermint block store height should be at most one ahead of the its state height")) - } - - return loadHeight -} diff --git a/examples/irishub2/app/context.go b/examples/irishub2/app/context.go deleted file mode 100644 index adc073942..000000000 --- a/examples/irishub2/app/context.go +++ /dev/null @@ -1,165 +0,0 @@ -package app - -import ( - "fmt" - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/auth" - txcxt "github.com/cosmos/cosmos-sdk/x/auth/client/context" - "github.com/irisnet/irishub/types" - "github.com/pkg/errors" - client2 "github.com/tendermint/tendermint/rpc/client" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - "io/ioutil" - "net/http" - "strings" -) - -type Context struct { - context.CLIContext - txCtx txcxt.TxContext - Cdc *wire.Codec -} - -func NewContext() Context { - return Context{ - CLIContext: context.NewCLIContext(), - txCtx: txcxt.NewTxContextFromCLI(), - } -} -func (c Context) Get() context.CLIContext { - return c.CLIContext.WithCodec(c.Cdc) -} - -func (c Context) GetTxCxt() txcxt.TxContext { - return c.txCtx.WithCodec(c.Cdc) -} - -func (c Context) WithCodeC(cdc *wire.Codec) Context { - c.Cdc = cdc - c.CLIContext = c.CLIContext.WithCodec(cdc) - return c -} -func (c Context) WithCLIContext(ctx context.CLIContext) Context { - c.CLIContext = ctx - return c -} -func (c Context) WithTxContext(ctx txcxt.TxContext) Context { - c.txCtx = ctx - return c -} - -func (c Context) NetInfo() (*ctypes.ResultNetInfo, error) { - client := c.Client.(*client2.HTTP) - return client.NetInfo() -} - -func (c Context) NumUnconfirmedTxs() (*ctypes.ResultUnconfirmedTxs, error) { - client := &http.Client{} - url := strings.Replace(c.NodeURI, "tcp", "http", 1) - reqUri := fmt.Sprintf("%s/%s", url, "num_unconfirmed_txs") - - resp, err := client.Get(reqUri) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - var res = struct { - JsonRpc string `json:"jsonrpc"` - Id string `json:"id"` - Result ctypes.ResultUnconfirmedTxs `json:"result"` - }{} - - if err := c.Cdc.UnmarshalJSON(body, &res); err != nil { - return nil, err - } - - return &res.Result, nil -} - -func (c Context) GetCoinType(coinName string) (types.CoinType, error) { - var coinType types.CoinType - coinName = strings.ToLower(coinName) - if coinName == Denom { - coinType = IrisCt - } else { - key := types.CoinTypeKey(coinName) - bz, err := c.QueryStore([]byte(key), "iparams") - if err != nil { - return coinType, err - } - - if err = c.Cdc.UnmarshalBinary(bz, &coinType); err != nil { - return coinType, err - } - } - - return coinType, nil -} - -func (c Context) ParseCoin(coinStr string) (sdk.Coin, error) { - mainUnit, err := types.GetCoinName(coinStr) - coinType, err := c.GetCoinType(mainUnit) - if err != nil { - return sdk.Coin{}, err - } - - coin, err := coinType.ConvertToMinCoin(coinStr) - if err != nil { - return sdk.Coin{}, err - } - return coin, nil -} - -func (c Context) ParseCoins(coinsStr string) (coins sdk.Coins, err error) { - coinsStr = strings.TrimSpace(coinsStr) - if len(coinsStr) == 0 { - return coins, nil - } - - coinStrs := strings.Split(coinsStr, ",") - for _, coinStr := range coinStrs { - coin, err := c.ParseCoin(coinStr) - if err != nil { - return coins, err - } - coins = append(coins, coin) - } - return coins, nil -} - -// Build builds a single message to be signed from a TxContext given a set of -// messages. It returns an error if a fee is supplied but cannot be parsed. -func (c Context) Build(msgs []sdk.Msg) (auth.StdSignMsg, error) { - ctx := c.txCtx - chainID := ctx.ChainID - if chainID == "" { - return auth.StdSignMsg{}, errors.Errorf("chain ID required but not specified") - } - - fee := sdk.Coin{} - if ctx.Fee != "" { - parsedFee, err := c.ParseCoin(ctx.Fee) - if err != nil { - return auth.StdSignMsg{}, err - } - - fee = parsedFee - } - - return auth.StdSignMsg{ - ChainID: ctx.ChainID, - AccountNumber: ctx.AccountNumber, - Sequence: ctx.Sequence, - Memo: ctx.Memo, - Msgs: msgs, - Fee: auth.NewStdFee(ctx.Gas, fee), - }, nil -} diff --git a/examples/irishub2/app/genesis.go b/examples/irishub2/app/genesis.go deleted file mode 100644 index db61f2009..000000000 --- a/examples/irishub2/app/genesis.go +++ /dev/null @@ -1,235 +0,0 @@ -package app - -import ( - "encoding/json" - "errors" - - "github.com/spf13/pflag" - "github.com/tendermint/tendermint/crypto" - tmtypes "github.com/tendermint/tendermint/types" - - "fmt" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/server/config" - 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" - "github.com/irisnet/irishub/types" - "time" -) - -// State to Unmarshal -type GenesisState struct { - Accounts []GenesisAccount `json:"accounts"` - StakeData stake.GenesisState `json:"stake"` -} - -// GenesisAccount doesn't need pubkey or sequence -type GenesisAccount struct { - Address sdk.AccAddress `json:"address"` - Coins sdk.Coins `json:"coins"` -} - -func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount { - return GenesisAccount{ - Address: acc.Address, - Coins: acc.Coins, - } -} - -func NewGenesisAccountI(acc auth.Account) GenesisAccount { - return GenesisAccount{ - Address: acc.GetAddress(), - Coins: acc.GetCoins(), - } -} - -// convert GenesisAccount to auth.BaseAccount -func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { - return &auth.BaseAccount{ - Address: ga.Address, - Coins: ga.Coins.Sort(), - } -} - -var ( - flagName = "name" - flagClientHome = "home-client" - flagOWK = "owk" - Denom = "iris" - feeAmt = int64(100) - IrisCt = types.NewDefaultCoinType(Denom) - freeFermionVal, _ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", feeAmt, Denom)) -) - -const defaultUnbondingTime time.Duration = 60 * 10 * time.Second - -// get app init parameters for server init command -func IrisAppInit() server.AppInit { - fsAppGenState := pflag.NewFlagSet("", pflag.ContinueOnError) - - fsAppGenTx := pflag.NewFlagSet("", pflag.ContinueOnError) - fsAppGenTx.String(flagName, "", "validator moniker, required") - fsAppGenTx.String(flagClientHome, DefaultCLIHome, - "home directory for the client, used for key generation") - fsAppGenTx.Bool(flagOWK, false, "overwrite the accounts created") - - return server.AppInit{ - FlagsAppGenState: fsAppGenState, - FlagsAppGenTx: fsAppGenTx, - AppGenTx: IrisAppGenTx, - AppGenState: IrisAppGenStateJSON, - } -} - -// simple genesis tx -type IrisGenTx struct { - Name string `json:"name"` - Address sdk.AccAddress `json:"address"` - PubKey string `json:"pub_key"` -} - -// Generate a gaia genesis transaction with flags -func IrisAppGenTx(cdc *wire.Codec, pk crypto.PubKey, genTxConfig config.GenTx) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - - if genTxConfig.Name == "" { - return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)") - } - - var addr sdk.AccAddress - var secret string - addr, secret, err = server.GenerateSaveCoinKey(genTxConfig.CliRoot, genTxConfig.Name, "1234567890", genTxConfig.Overwrite) - if err != nil { - return - } - mm := map[string]string{"secret": secret} - var bz []byte - bz, err = cdc.MarshalJSON(mm) - if err != nil { - return - } - cliPrint = json.RawMessage(bz) - appGenTx, _, validator, err = IrisAppGenTxNF(cdc, pk, addr, genTxConfig.Name) - return -} - -// Generate a gaia genesis transaction without flags -func IrisAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.AccAddress, name string) ( - appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { - - var bz []byte - gaiaGenTx := IrisGenTx{ - Name: name, - Address: addr, - PubKey: sdk.MustBech32ifyAccPub(pk), - } - bz, err = wire.MarshalJSONIndent(cdc, gaiaGenTx) - if err != nil { - return - } - appGenTx = json.RawMessage(bz) - - validator = tmtypes.GenesisValidator{ - PubKey: pk, - Power: feeAmt, - } - return -} - -// Create the core parameters for genesis initialization for gaia -// note that the pubkey input is this machines pubkey -func IrisAppGenState(cdc *wire.Codec, appGenTxs []json.RawMessage) (genesisState GenesisState, err error) { - - if len(appGenTxs) == 0 { - err = errors.New("must provide at least genesis transaction") - return - } - - stakeData := createGenesisState() - genaccs := make([]GenesisAccount, len(appGenTxs)) - for i, appGenTx := range appGenTxs { - - var genTx IrisGenTx - err = cdc.UnmarshalJSON(appGenTx, &genTx) - if err != nil { - return - } - - // create the genesis account, give'm few steaks and a buncha token with there name - accAuth := auth.NewBaseAccountWithAddress(genTx.Address) - accAuth.Coins = sdk.Coins{ - freeFermionVal, - } - acc := NewGenesisAccount(&accAuth) - genaccs[i] = acc - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRatFromInt(freeFermionVal.Amount)) // increase the supply - - // add the validator - if len(genTx.Name) > 0 { - desc := stake.NewDescription(genTx.Name, "", "", "") - validator := stake.NewValidator(genTx.Address, - sdk.MustGetAccPubKeyBech32(genTx.PubKey), desc) - - stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens.Add(sdk.NewRatFromInt(freeFermionVal.Amount)) - - // add some new shares to the validator - var issuedDelShares sdk.Rat - validator, stakeData.Pool, issuedDelShares = validator.AddTokensFromDel(stakeData.Pool, freeFermionVal.Amount) - //validator.TokenPrecision = stakeData.Params.DenomPrecision - stakeData.Validators = append(stakeData.Validators, validator) - - // create the self-delegation from the issuedDelShares - delegation := stake.Delegation{ - DelegatorAddr: validator.Owner, - ValidatorAddr: validator.Owner, - Shares: issuedDelShares, - Height: 0, - } - - stakeData.Bonds = append(stakeData.Bonds, delegation) - } - } - - // create the final app state - genesisState = GenesisState{ - Accounts: genaccs, - StakeData: stakeData, - } - return -} - -// IrisAppGenState but with JSON -func IrisAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) { - - // create the final app state - genesisState, err := IrisAppGenState(cdc, appGenTxs) - if err != nil { - return nil, err - } - appState, err = wire.MarshalJSONIndent(cdc, genesisState) - return -} - -func createGenesisState() stake.GenesisState { - return stake.GenesisState{ - Pool: stake.Pool{ - LooseTokens: sdk.ZeroRat(), - BondedTokens: sdk.ZeroRat(), - InflationLastTime: time.Unix(0, 0), - Inflation: sdk.NewRat(7, 100), - DateLastCommissionReset: 0, - PrevBondedShares: sdk.ZeroRat(), - }, - Params: stake.Params{ - InflationRateChange: sdk.NewRat(13, 100), - InflationMax: sdk.NewRat(20, 100), - InflationMin: sdk.NewRat(7, 100), - GoalBonded: sdk.NewRat(67, 100), - UnbondingTime: defaultUnbondingTime, - MaxValidators: 100, - BondDenom: Denom + "-" + types.Atto, - }, - } -} diff --git a/examples/irishub2/cmd/iris2/main.go b/examples/irishub2/cmd/iris2/main.go deleted file mode 100644 index 7663fc800..000000000 --- a/examples/irishub2/cmd/iris2/main.go +++ /dev/null @@ -1,76 +0,0 @@ -package main - -import ( - "encoding/json" - "io" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/server" - "github.com/irisnet/irishub/examples/irishub2/app" - bam "github.com/irisnet/irishub/baseapp" - "github.com/irisnet/irishub/version" - - "github.com/spf13/viper" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/cli" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - "github.com/irisnet/irishub/tools/prometheus" -) - -func main() { - cdc := app.MakeCodec() - ctx := server.NewDefaultContext() - cobra.EnableCommandSorting = false - rootCmd := &cobra.Command{ - Use: "iris-bugfix-3", - Short: "iris-bugfix-3 Daemon (server)", - PersistentPreRunE: server.PersistentPreRunEFn(ctx), - } - - rootCmd.PersistentFlags().String("log_level", ctx.Config.LogLevel, "Log level") - - tendermintCmd := &cobra.Command{ - Use: "tendermint", - Short: "Tendermint subcommands", - } - - tendermintCmd.AddCommand( - server.ShowNodeIDCmd(ctx), - server.ShowValidatorCmd(ctx), - ) - - startCmd := server.StartCmd(ctx, server.ConstructAppCreator(newApp, "iris")) - startCmd.Flags().Bool(app.FlagReplay, false, "Replay the last block") - rootCmd.AddCommand( - server.InitCmd(ctx, cdc, app.IrisAppInit()), - startCmd, - server.TestnetFilesCmd(ctx, cdc, app.IrisAppInit()), - server.UnsafeResetAllCmd(ctx), - client.LineBreak, - tendermintCmd, - server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), - client.LineBreak, - version.ServeVersionCommand(cdc), - ) - - rootCmd.AddCommand(prometheus.MonitorCommand(cdc)) - - // prepare and add flags - executor := cli.PrepareBaseCmd(rootCmd, "IRIS", app.DefaultNodeHome) - executor.Execute() -} - -func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) abci.Application { - return app.NewIrisApp(logger, db, traceStore, bam.SetPruning(viper.GetString("pruning"))) -} - -func exportAppStateAndTMValidators( - logger log.Logger, db dbm.DB, traceStore io.Writer, -) (json.RawMessage, []tmtypes.GenesisValidator, error) { - gApp := app.NewIrisApp(logger, db, traceStore) - return gApp.ExportAppStateAndValidators() -} diff --git a/examples/irishub2/cmd/iriscli2/main.go b/examples/irishub2/cmd/iriscli2/main.go deleted file mode 100644 index 8ab273815..000000000 --- a/examples/irishub2/cmd/iriscli2/main.go +++ /dev/null @@ -1,170 +0,0 @@ -package main - -import ( - "github.com/spf13/cobra" - - "github.com/tendermint/tendermint/libs/cli" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/client/tx" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - ibccmd "github.com/irisnet/irishub/examples/irishub2/ibc/client/cli" - slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" - stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" - "github.com/irisnet/irishub/examples/irishub2/app" - govcmd "github.com/cosmos/cosmos-sdk/x/gov/client/cli" - upgradecmd "github.com/irisnet/irishub/client/upgrade/cli" - "github.com/irisnet/irishub/version" -) - -// rootCmd is the entry point for this binary -var ( - rootCmd = &cobra.Command{ - Use: "iriscli-bugfix-3", - Short: "irishub2 light-client", - } -) - -func main() { - cobra.EnableCommandSorting = false - cdc := app.MakeCodec() - - // TODO: setup keybase, viper object, etc. to be passed into - // the below functions and eliminate global vars, like we do - // with the cdc - - // add standard rpc commands - rpc.AddCommands(rootCmd) - - //Add state commands - tendermintCmd := &cobra.Command{ - Use: "tendermint", - Short: "Tendermint state querying subcommands", - } - tendermintCmd.AddCommand( - rpc.BlockCommand(), - rpc.ValidatorCommand(), - ) - tx.AddCommands(tendermintCmd, cdc) - - //Add IBC commands - ibcCmd := &cobra.Command{ - Use: "ibc", - Short: "Inter-Blockchain Communication subcommands", - } - ibcCmd.AddCommand( - client.PostCommands( - ibccmd.IBCTransferCmd(cdc), - ibccmd.IBCSetCmd(cdc), - ibccmd.IBCGetCmd(cdc), - )...) - - advancedCmd := &cobra.Command{ - Use: "advanced", - Short: "Advanced subcommands", - } - - advancedCmd.AddCommand( - tendermintCmd, - ibcCmd, - ) - rootCmd.AddCommand( - advancedCmd, - client.LineBreak, - ) - - //Add stake commands - stakeCmd := &cobra.Command{ - Use: "stake", - Short: "Stake and validation subcommands", - } - stakeCmd.AddCommand( - client.GetCommands( - stakecmd.GetCmdQueryValidator("stake", cdc), - stakecmd.GetCmdQueryValidators("stake", cdc), - stakecmd.GetCmdQueryDelegation("stake", cdc), - stakecmd.GetCmdQueryDelegations("stake", cdc), - slashingcmd.GetCmdQuerySigningInfo("slashing", cdc), - )...) - stakeCmd.AddCommand( - client.PostCommands( - stakecmd.GetCmdCreateValidator(cdc), - stakecmd.GetCmdEditValidator(cdc), - stakecmd.GetCmdDelegate(cdc), - stakecmd.GetCmdUnbond("stake", cdc), - stakecmd.GetCmdRedelegate("stake", cdc), - slashingcmd.GetCmdUnrevoke(cdc), - )...) - rootCmd.AddCommand( - stakeCmd, - ) - - //Add gov commands - govCmd := &cobra.Command{ - Use: "gov", - Short: "Governance and voting subcommands", - } - govCmd.AddCommand( - client.GetCommands( - govcmd.GetCmdQueryProposal("gov", cdc), - govcmd.GetCmdQueryVote("gov", cdc), - )...) - govCmd.AddCommand( - client.PostCommands( - govcmd.GetCmdSubmitProposal(cdc), - govcmd.GetCmdDeposit(cdc), - govcmd.GetCmdVote(cdc), - )...) - rootCmd.AddCommand( - govCmd, - ) - - //Add upgrade commands - upgradeCmd := &cobra.Command{ - Use: "upgrade", - Short: "Software Upgrade subcommands", - } - upgradeCmd.AddCommand( - client.GetCommands( - upgradecmd.GetCmdQuerySwitch("upgrade", cdc), - upgradecmd.GetInfoCmd("upgrade", cdc), - )...) - upgradeCmd.AddCommand( - client.PostCommands( - upgradecmd.GetCmdSubmitSwitch(cdc), - )...) - rootCmd.AddCommand( - upgradeCmd, - ) - - //Add auth and bank commands - rootCmd.AddCommand( - client.GetCommands( - authcmd.GetAccountCmd("acc", cdc, authcmd.GetAccountDecoder(cdc)), - )...) - rootCmd.AddCommand( - client.PostCommands( - bankcmd.SendTxCmd(cdc), - )...) - - // add proxy, version and key info - rootCmd.AddCommand( - keys.Commands(), - client.LineBreak, - ) - rootCmd.AddCommand( - client.GetCommands( - version.ServeVersionCommand(cdc), - )...) - - // prepare and add flags - executor := cli.PrepareMainCmd(rootCmd, "GA", app.DefaultCLIHome) - err := executor.Execute() - if err != nil { - // handle with #870 - panic(err) - } -} diff --git a/examples/irishub2/ibc/client/cli/README.md b/examples/irishub2/ibc/client/cli/README.md deleted file mode 100644 index ab9e8e555..000000000 --- a/examples/irishub2/ibc/client/cli/README.md +++ /dev/null @@ -1,157 +0,0 @@ -# IBC Doubble Hubble - -## Remove remaining data - -```console -> rm -r ~/.chain1 -> rm -r ~/.chain2 -> rm -r ~/.basecli -``` - -## Initialize both chains - -```console -> basecoind init --home ~/.chain1 -I[04-02|14:03:33.704] Generated private validator module=main path=/home/mossid/.chain1/config/priv_validator.json -I[04-02|14:03:33.705] Generated genesis file module=main path=/home/mossid/.chain1/config/genesis.json -{ - "secret": "crunch ignore trigger neither differ dance cheap brick situate floor luxury citizen husband decline arrow abandon", - "account": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "validator": { - "pub_key": { - "type": "ed25519", - "data": "8C9917D5E982E221F5A1450103102B44BBFC1E8768126C606246CB37B5794F4D" - }, - "power": 10, - "name": "" - }, - "node_id": "3ac8e6242315fd62143dc3e52c161edaaa6b1a64", - "chain_id": "test-chain-ZajMfr" -} -> ADDR1=C69FEB398A29AAB1B3C4F07DE22208F35E711BCC -> ID1=test-chain-ZajMfr -> NODE1=tcp://0.0.0.0:36657 -> basecli keys add key1 --recover -Enter a passphrase for your key: -Repeat the passphrase: -Enter your recovery seed phrase: -crunch ignore trigger neither differ dance cheap brick situate floor luxury citizen husband decline arrow abandon -key1 C69FEB398A29AAB1B3C4F07DE22208F35E711BCC - - -> basecoind init --home ~/.chain2 -I[04-02|14:09:14.453] Generated private validator module=main path=/home/mossid/.chain2/config/priv_validator.json -I[04-02|14:09:14.453] Generated genesis file module=main path=/home/mossid/.chain2/config/genesis.json -{ - "secret": "age guide awesome month female left oxygen soccer define high grocery work desert dinner arena abandon", - "account": "DC26002735D3AA9573707CFA6D77C12349E49868", - "validator": { - "pub_key": { - "type": "ed25519", - "data": "A94FE4B9AD763D301F4DD5A2766009812495FB7A79F1275FB8A5AF09B44FD5F3" - }, - "power": 10, - "name": "" - }, - "node_id": "ad26831330e1c72b85276d53c20f0680e6fd4cf5" - "chain_id": "test-chain-4XHTPn" -} -> ADDR2=DC26002735D3AA9573707CFA6D77C12349E49868 -> ID2=test-chain-4XHTPn -> NODE2=tcp://0.0.0.0:26657 -> basecli keys add key2 --recover -Enter a passphrase for your key: -Repeat the passphrase: -Enter your recovery seed phrase: -age guide awesome month female left oxygen soccer define high grocery work desert dinner arena abandon -key2 DC26002735D3AA9573707CFA6D77C12349E49868 - - -> basecoind start --home ~/.chain1 --address tcp://0.0.0.0:36658 --rpc.laddr tcp://0.0.0.0:36657 --p2p.laddr tcp://0.0.0.0:36656 -... - -> basecoind start --home ~/.chain2 # --address tcp://0.0.0.0:26658 --rpc.laddr tcp://0.0.0.0:26657 --p2p.laddr tcp://0.0.0.0:26656 -... -``` -## Check balance - -```console -> basecli account $ADDR1 --node $NODE1 -{ - "address": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740992 - } - ], - "public_key": null, - "sequence": 0, - "name": "" -} - -> basecli account $ADDR2 --node $NODE2 -{ - "address": "DC26002735D3AA9573707CFA6D77C12349E49868", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740992 - } - ], - "public_key": null, - "sequence": 0, - "name": "" -} - -``` - -## Transfer coins (addr1:chain1 -> addr2:chain2) - -```console -> basecli transfer --from key1 --to $ADDR2 --amount 10mycoin --chain $ID2 --chain-id $ID1 --node $NODE1 -Password to sign with 'key1': -Committed at block 1022. Hash: E16019DCC4AA08CA70AFCFBC96028ABCC51B6AD0 -> basecli account $ADDR1 --node $NODE1 -{ - "address": "C69FEB398A29AAB1B3C4F07DE22208F35E711BCC", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254740982 - } - ], - "public_key": { - "type": "ed25519", - "data": "9828FF1780A066A0D93D840737566B697035448D6C880807322BED8919348B2B" - }, - "sequence": 1, - "name": "" -} -``` - -## Relay IBC packets - -```console -> basecli relay --from key2 --from-chain-id $ID1 --from-chain-node $NODE1 --to-chain-id $ID2 --to-chain-node $NODE2 --chain-id $ID2 -Password to sign with 'key2': -I[04-03|16:18:59.984] Detected IBC packet number=0 -I[04-03|16:19:00.869] Relayed IBC packet number=0 -> basecli account $ADDR2 --node $NODE2 -{ - "address": "DC26002735D3AA9573707CFA6D77C12349E49868", - "coins": [ - { - "denom": "mycoin", - "amount": 9007199254741002 - } - ], - "public_key": { - "type": "ed25519", - "data": "F52B4FA545F4E9BFE5D7AF1DD2236899FDEF905F9B3057C38D7C01BF1B8EB52E" - }, - "sequence": 1, - "name": "" -} - -``` diff --git a/examples/irishub2/ibc/client/cli/ibctx.go b/examples/irishub2/ibc/client/cli/ibctx.go deleted file mode 100644 index 8a729b697..000000000 --- a/examples/irishub2/ibc/client/cli/ibctx.go +++ /dev/null @@ -1,84 +0,0 @@ -package cli - -import ( - "encoding/hex" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" - - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - authctx "github.com/cosmos/cosmos-sdk/x/auth/client/context" - "github.com/cosmos/cosmos-sdk/x/ibc" - "os" - "github.com/cosmos/cosmos-sdk/client/utils" -) - -const ( - flagTo = "to" - flagAmount = "amount" - flagChain = "chain" -) - -// IBC transfer command -func IBCTransferCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "transfer", - RunE: func(cmd *cobra.Command, args []string) error { - txCtx := authctx.NewTxContextFromCLI().WithCodec(cdc) - cliCtx := context.NewCLIContext(). - WithCodec(cdc). - WithLogger(os.Stdout). - WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - - // get the from address - from, err := cliCtx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg, err := buildMsg(from) - if err != nil { - return err - } - - cliCtx.PrintResponse = true - return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) - }, - } - - cmd.Flags().String(flagTo, "", "Address to send coins") - cmd.Flags().String(flagAmount, "", "Amount of coins to send") - cmd.Flags().String(flagChain, "", "Destination chain to send coins") - return cmd -} - -func buildMsg(from sdk.AccAddress) (sdk.Msg, error) { - amount := viper.GetString(flagAmount) - coins, err := sdk.ParseCoins(amount) - if err != nil { - return nil, err - } - - dest := viper.GetString(flagTo) - bz, err := hex.DecodeString(dest) - if err != nil { - return nil, err - } - to := sdk.AccAddress(bz) - - packet := ibc.NewIBCPacket(from, to, coins, viper.GetString(client.FlagChainID), - viper.GetString(flagChain)) - - msg := ibc.IBCTransferMsg{ - IBCPacket: packet, - } - - return msg, nil -} diff --git a/examples/irishub2/ibc/client/cli/tx.go b/examples/irishub2/ibc/client/cli/tx.go deleted file mode 100644 index 6d67f063c..000000000 --- a/examples/irishub2/ibc/client/cli/tx.go +++ /dev/null @@ -1,66 +0,0 @@ -package cli - -import ( - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - authctx "github.com/cosmos/cosmos-sdk/x/auth/client/context" - "github.com/irisnet/irishub/examples/irishub2/ibc" - "os" - "github.com/cosmos/cosmos-sdk/client/utils" -) - -// IBC transfer command -func IBCGetCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "get", - RunE: func(cmd *cobra.Command, args []string) error { - txCtx := authctx.NewTxContextFromCLI().WithCodec(cdc) - cliCtx := context.NewCLIContext(). - WithCodec(cdc). - WithLogger(os.Stdout). - WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - - from, err := cliCtx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg := ibc.NewIBCGetMsg(from) - - cliCtx.PrintResponse = true - return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) - }, - } - return cmd -} - - -// IBC transfer command -func IBCSetCmd(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "set", - RunE: func(cmd *cobra.Command, args []string) error { - txCtx := authctx.NewTxContextFromCLI().WithCodec(cdc) - cliCtx := context.NewCLIContext(). - WithCodec(cdc). - WithLogger(os.Stdout). - WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - - from, err := cliCtx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg := ibc.NewIBCSetMsg(from) - - cliCtx.PrintResponse = true - return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) - }, - } - return cmd -} diff --git a/examples/irishub2/ibc/errors.go b/examples/irishub2/ibc/errors.go deleted file mode 100644 index 7a3194baf..000000000 --- a/examples/irishub2/ibc/errors.go +++ /dev/null @@ -1,50 +0,0 @@ -package ibc - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// IBC errors reserve 200 ~ 299. -const ( - DefaultCodespace sdk.CodespaceType = 3 - - // IBC errors reserve 200 - 299. - CodeInvalidSequence sdk.CodeType = 200 - CodeIdenticalChains sdk.CodeType = 201 - CodeUnknownRequest sdk.CodeType = sdk.CodeUnknownRequest -) - -func codeToDefaultMsg(code sdk.CodeType) string { - switch code { - case CodeInvalidSequence: - return "invalid IBC packet sequence" - case CodeIdenticalChains: - return "source and destination chain cannot be identical" - default: - return sdk.CodeToDefaultMsg(code) - } -} - -// nolint -func ErrInvalidSequence(codespace sdk.CodespaceType) sdk.Error { - return newError(codespace, CodeInvalidSequence, "") -} -func ErrIdenticalChains(codespace sdk.CodespaceType) sdk.Error { - return newError(codespace, CodeIdenticalChains, "") -} - -// ------------------------- -// Helpers - -// nolint: unparam -func newError(codespace sdk.CodespaceType, code sdk.CodeType, msg string) sdk.Error { - msg = msgOrDefaultMsg(msg, code) - return sdk.NewError(codespace, code, msg) -} - -func msgOrDefaultMsg(msg string, code sdk.CodeType) string { - if msg != "" { - return msg - } - return codeToDefaultMsg(code) -} diff --git a/examples/irishub2/ibc/handler.go b/examples/irishub2/ibc/handler.go deleted file mode 100644 index 99addf31a..000000000 --- a/examples/irishub2/ibc/handler.go +++ /dev/null @@ -1,76 +0,0 @@ -package ibc - -import ( - "reflect" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" -) - -func NewHandler(ibcm Mapper, ck bank.Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { - switch msg := msg.(type) { - case IBCTransferMsg: - return handleIBCTransferMsg(ctx, ibcm, ck, msg) - case IBCReceiveMsg: - return handleIBCReceiveMsg(ctx, ibcm, ck, msg) - case IBCGetMsg: - return handleIBCGetMsg(ctx, ibcm, ck, msg) - case IBCSetMsg: - return handleIBCSetMsg(ctx, ibcm, ck, msg) - default: - errMsg := "Unrecognized IBC Msg type: " + reflect.TypeOf(msg).Name() - return sdk.ErrUnknownRequest(errMsg).Result() - } - } -} - -// IBCTransferMsg deducts coins from the account and creates an egress IBC packet. -func handleIBCTransferMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCTransferMsg) sdk.Result { - packet := msg.IBCPacket - - _, _, err := ck.SubtractCoins(ctx, packet.SrcAddr, packet.Coins) - if err != nil { - return err.Result() - } - - err = ibcm.PostIBCPacket(ctx, packet) - if err != nil { - return err.Result() - } - - return sdk.Result{} -} - -// IBCReceiveMsg adds coins to the destination address and creates an ingress IBC packet. -func handleIBCReceiveMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCReceiveMsg) sdk.Result { - packet := msg.IBCPacket - - seq := ibcm.GetIngressSequence(ctx, packet.SrcChain) - if msg.Sequence != seq { - return ErrInvalidSequence(ibcm.codespace).Result() - } - - _, _, err := ck.AddCoins(ctx, packet.DestAddr, packet.Coins) - if err != nil { - return err.Result() - } - - ibcm.SetIngressSequence(ctx, packet.SrcChain, seq+1) - - return sdk.Result{} -} - - - -// IBCTransferMsg deducts coins from the account and creates an egress IBC packet. -func handleIBCSetMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCSetMsg) sdk.Result { - ibcm.Set(ctx,msg.Addr.String()+":ibc-2") - return sdk.Result{Log:"This is new module - ibc2 !!"} -} - -// IBCReceiveMsg adds coins to the destination address and creates an ingress IBC packet. -func handleIBCGetMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCGetMsg) sdk.Result { - AddrString,_:=ibcm.Get(ctx) - return sdk.Result{Log:AddrString} -} diff --git a/examples/irishub2/ibc/mapper.go b/examples/irishub2/ibc/mapper.go deleted file mode 100644 index 2ccc93d1a..000000000 --- a/examples/irishub2/ibc/mapper.go +++ /dev/null @@ -1,149 +0,0 @@ -package ibc - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" -) - -// IBC Mapper -type Mapper struct { - key sdk.StoreKey - cdc *wire.Codec - codespace sdk.CodespaceType -} - -// XXX: The Mapper should not take a CoinKeeper. Rather have the CoinKeeper -// take an Mapper. -func NewMapper(cdc *wire.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) Mapper { - // XXX: How are these codecs supposed to work? - return Mapper{ - key: key, - cdc: cdc, - codespace: codespace, - } -} - -// XXX: This is not the public API. This will change in MVP2 and will henceforth -// only be invoked from another module directly and not through a user -// transaction. -// TODO: Handle invalid IBC packets and return errors. -func (ibcm Mapper) PostIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error { - // write everything into the state - store := ctx.KVStore(ibcm.key) - index := ibcm.getEgressLength(store, packet.DestChain) - bz, err := ibcm.cdc.MarshalBinary(packet) - if err != nil { - panic(err) - } - - store.Set(EgressKey(packet.DestChain, index), bz) - bz, err = ibcm.cdc.MarshalBinary(index + 1) - if err != nil { - panic(err) - } - store.Set(EgressLengthKey(packet.DestChain), bz) - - return nil -} - -// XXX: In the future every module is able to register it's own handler for -// handling it's own IBC packets. The "ibc" handler will only route the packets -// to the appropriate callbacks. -// XXX: For now this handles all interactions with the CoinKeeper. -// XXX: This needs to do some authentication checking. -func (ibcm Mapper) ReceiveIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error { - return nil -} - -// -------------------------- -// Functions for accessing the underlying KVStore. - -func marshalBinaryPanic(cdc *wire.Codec, value interface{}) []byte { - res, err := cdc.MarshalBinary(value) - if err != nil { - panic(err) - } - return res -} - -func unmarshalBinaryPanic(cdc *wire.Codec, bz []byte, ptr interface{}) { - err := cdc.UnmarshalBinary(bz, ptr) - if err != nil { - panic(err) - } -} - -// TODO add description -func (ibcm Mapper) GetIngressSequence(ctx sdk.Context, srcChain string) int64 { - store := ctx.KVStore(ibcm.key) - key := IngressSequenceKey(srcChain) - - bz := store.Get(key) - if bz == nil { - zero := marshalBinaryPanic(ibcm.cdc, int64(0)) - store.Set(key, zero) - return 0 - } - - var res int64 - unmarshalBinaryPanic(ibcm.cdc, bz, &res) - return res -} - -// TODO add description -func (ibcm Mapper) SetIngressSequence(ctx sdk.Context, srcChain string, sequence int64) { - store := ctx.KVStore(ibcm.key) - key := IngressSequenceKey(srcChain) - - bz := marshalBinaryPanic(ibcm.cdc, sequence) - store.Set(key, bz) -} - -// Retrieves the index of the currently stored outgoing IBC packets. -func (ibcm Mapper) getEgressLength(store sdk.KVStore, destChain string) int64 { - bz := store.Get(EgressLengthKey(destChain)) - if bz == nil { - zero := marshalBinaryPanic(ibcm.cdc, int64(0)) - store.Set(EgressLengthKey(destChain), zero) - return 0 - } - var res int64 - unmarshalBinaryPanic(ibcm.cdc, bz, &res) - return res -} - -// Stores an outgoing IBC packet under "egress/chain_id/index". -func EgressKey(destChain string, index int64) []byte { - return []byte(fmt.Sprintf("egress/%s/%d", destChain, index)) -} - -// Stores the number of outgoing IBC packets under "egress/index". -func EgressLengthKey(destChain string) []byte { - return []byte(fmt.Sprintf("egress/%s", destChain)) -} - -// Stores the sequence number of incoming IBC packet under "ingress/index". -func IngressSequenceKey(srcChain string) []byte { - return []byte(fmt.Sprintf("ingress/%s", srcChain)) -} - - -// Gets the vote of a specific voter on a specific proposal -func (ibcm Mapper) Get(ctx sdk.Context) (string, bool) { - store := ctx.KVStore(ibcm.key) - bz := store.Get([]byte("ibcaddr")) - if bz == nil { - return " ", false - } - var Addr string - ibcm.cdc.MustUnmarshalBinary(bz, &Addr) - return Addr, true -} - -func (ibcm Mapper) Set(ctx sdk.Context,Addr string) { - store := ctx.KVStore(ibcm.key) - bz := ibcm.cdc.MustMarshalBinary(Addr) - store.Set([]byte("ibcaddr"), bz) -} \ No newline at end of file diff --git a/examples/irishub2/ibc/types.go b/examples/irishub2/ibc/types.go deleted file mode 100644 index b60b423cc..000000000 --- a/examples/irishub2/ibc/types.go +++ /dev/null @@ -1,184 +0,0 @@ -package ibc - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" -) - -var ( - msgCdc *wire.Codec -) - -func init() { - msgCdc = wire.NewCodec() -} - -// ------------------------------ -// IBCPacket - -// nolint - TODO rename to Packet as IBCPacket stutters (golint) -// IBCPacket defines a piece of data that can be send between two separate -// blockchains. -type IBCPacket struct { - SrcAddr sdk.AccAddress - DestAddr sdk.AccAddress - Coins sdk.Coins - SrcChain string - DestChain string -} - -func NewIBCPacket(srcAddr sdk.AccAddress, destAddr sdk.AccAddress, coins sdk.Coins, - srcChain string, destChain string) IBCPacket { - - return IBCPacket{ - SrcAddr: srcAddr, - DestAddr: destAddr, - Coins: coins, - SrcChain: srcChain, - DestChain: destChain, - } -} - -//nolint -func (p IBCPacket) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(p) - if err != nil { - panic(err) - } - return sdk.MustSortJSON(b) -} - -// validator the ibc packey -func (p IBCPacket) ValidateBasic() sdk.Error { - if p.SrcChain == p.DestChain { - return ErrIdenticalChains(DefaultCodespace).TraceSDK("") - } - if !p.Coins.IsValid() { - return sdk.ErrInvalidCoins("") - } - return nil -} - -// ---------------------------------- -// IBCTransferMsg - -// nolint - TODO rename to TransferMsg as folks will reference with ibc.TransferMsg -// IBCTransferMsg defines how another module can send an IBCPacket. -type IBCTransferMsg struct { - IBCPacket -} - -// nolint -func (msg IBCTransferMsg) Type() string { return "ibc-2" } - -// x/bank/tx.go MsgSend.GetSigners() -func (msg IBCTransferMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.SrcAddr} } - -// get the sign bytes for ibc transfer message -func (msg IBCTransferMsg) GetSignBytes() []byte { - return msg.IBCPacket.GetSignBytes() -} - -// validate ibc transfer message -func (msg IBCTransferMsg) ValidateBasic() sdk.Error { - return msg.IBCPacket.ValidateBasic() -} - -// ---------------------------------- -// IBCReceiveMsg - -// nolint - TODO rename to ReceiveMsg as folks will reference with ibc.ReceiveMsg -// IBCReceiveMsg defines the message that a relayer uses to post an IBCPacket -// to the destination chain. -type IBCReceiveMsg struct { - IBCPacket - Relayer sdk.AccAddress - Sequence int64 -} - -// nolint -func (msg IBCReceiveMsg) Type() string { return "ibc-2" } -func (msg IBCReceiveMsg) ValidateBasic() sdk.Error { return msg.IBCPacket.ValidateBasic() } - -// x/bank/tx.go MsgSend.GetSigners() -func (msg IBCReceiveMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Relayer} } - -// get the sign bytes for ibc receive message -func (msg IBCReceiveMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(struct { - IBCPacket json.RawMessage - Relayer sdk.AccAddress - Sequence int64 - }{ - IBCPacket: json.RawMessage(msg.IBCPacket.GetSignBytes()), - Relayer: msg.Relayer, - Sequence: msg.Sequence, - }) - if err != nil { - panic(err) - } - return sdk.MustSortJSON(b) -} - - -type IBCSetMsg struct { - Addr sdk.AccAddress -} - -func NewIBCSetMsg(addr sdk.AccAddress) IBCSetMsg { - return IBCSetMsg{ - Addr:addr, - } -} - -func (msg IBCSetMsg) Type() string { - return "ibc-2" -} - -func (msg IBCSetMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(msg) - if err != nil { - panic(err) - } - return b -} - -func (msg IBCSetMsg) ValidateBasic() sdk.Error { - return nil -} - -func (msg IBCSetMsg) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Addr} -} - -type IBCGetMsg struct { - Addr sdk.AccAddress -} - -func NewIBCGetMsg(addr sdk.AccAddress) IBCGetMsg { - return IBCGetMsg{ - Addr:addr, - } -} - -func (msg IBCGetMsg) Type() string { - return "ibc-2" -} - -func (msg IBCGetMsg) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(msg) - if err != nil { - panic(err) - } - return b -} - -func (msg IBCGetMsg) ValidateBasic() sdk.Error { - return nil -} - -func (msg IBCGetMsg) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Addr} -} diff --git a/examples/irishub2/ibc/wire.go b/examples/irishub2/ibc/wire.go deleted file mode 100644 index 821a527ab..000000000 --- a/examples/irishub2/ibc/wire.go +++ /dev/null @@ -1,13 +0,0 @@ -package ibc - -import ( - "github.com/cosmos/cosmos-sdk/wire" -) - -// Register concrete types on wire codec -func RegisterWire(cdc *wire.Codec) { - cdc.RegisterConcrete(IBCTransferMsg{}, "cosmos-sdk/IBCTransferMsg/2", nil) - cdc.RegisterConcrete(IBCReceiveMsg{}, "cosmos-sdk/IBCReceiveMsg/2", nil) - cdc.RegisterConcrete(IBCSetMsg{},"cosmos-sdk/IBCSetMsg/2",nil) - cdc.RegisterConcrete(IBCGetMsg{},"cosmos-sdk/IBCGetMsg/2",nil) -} From 4eada9e42fd6aa9d492bd32583dc981d45c1eb14 Mon Sep 17 00:00:00 2001 From: Raymond Date: Thu, 27 Sep 2018 18:19:42 +0800 Subject: [PATCH 114/124] IRISHUB-258: changelog of v0.5.0 --- CHANGELOG.md | 79 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 75 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b4a85ea62..e1b5a0a32 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,15 +1,58 @@ # Changelog + +## 0.5.0-rc1 + +*September 27th, 2018* + +BREAKING CHANGES: + +- [cointype] Introduce the cointype of iris: + - 1 iris = 10^18 iris-atto + - 1 iris-milli = 10^15 iris-atto + - 1 iris-micro = 10^12 iris-atto + - 1 iris-nano = 10^9 iris-atto + - 1 iris-pico = 10^6 iris-atto + - 1 iris-femto = 10^3 iris-atto + +FEATURES: + +- [tendermint] Upgrade to Tendermint v0.23.1-rc0 +- [cosmos-sdk] Upgrade to cosmos-sdk v0.24.2 + - Move the previous irisnet changeset about cosmos-sdk into irishub +- [irisdebug] Add irisdebug tool +- [LCD/cli] Add the proof verification in the LCD and cli +- [iparam] Support governance modify the complex struct type parameter and can be done through the Json parameter config file +- [software-upgrade] Software upgrade solution of the irisnet + + +## 0.4.2 + +*September 22th, 2018* + +BUG FIXES + +- Fix consensus failure due to the double sign evidence be broadcasted before the genesis block + +## 0.4.1 + +*September 12th, 2018* + +BUG FIXES + +- Missing to set validator intraTxCount in stake genesis init + + ## 0.4.0 -*August 16th, 2018* +*September 6th, 2018* BREAKING CHANGES: - [cosmos-sdk] Upgrade to cosmos-sdk v0.23.0 - Change the address prefix format: - cosmosaccaddr --> faa - - cosmosaccaddr --> fap + - cosmosaccpub --> fap - cosmosvaladdr --> fva - cosmosvalpub --> fvp - Adjust the Route & rootMultiStore Commit for software upgrade @@ -19,12 +62,40 @@ BREAKING CHANGES: FEATURES: - [tendermint] Upgrade to Tendermint v0.22.6 - - Store the pre-state to support the replay function in software upgrade + - Store the pre-state to support the replay function - [cosmos-sdk] Upgrade to cosmos-sdk v0.23.0 - Add the paramProposal and softwareUpgradeProposal in gov module - Improve fee token mechanism to more reasonably deduct transaction fee and achieve more ability to defent DDOS attack. - Introduce the global parameter module -- [irishub] Add the upgrade module and example apps for the async software upgrade + +BUG FIXES + +- Default account balance in genesis +- Fix iris version issue +- Fix the unit conflict issue in slashing +- Check the voting power when create validator +- Fix evidence amimo register issue + + +## 0.4.0-rc2 + +*Sep 5th, 2018* + +BUG FIXES + +- Fix evidence amimo register issue + + +## 0.4.0-rc1 + +*Aug 27th, 2018* + +BUG FIXES + +- Default account balance in genesis +- iris version issue +- Fix the unit conflict issue in slashing +- Check the voting power when create validator ## 0.3.0 From 0a1e1a944d52dc3e4a3fe090a536b12134b8df6c Mon Sep 17 00:00:00 2001 From: Yelong Zhang Date: Thu, 27 Sep 2018 22:47:36 +0800 Subject: [PATCH 115/124] Update Full-Node.md --- docs/zh/get-started/Full-Node.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/zh/get-started/Full-Node.md b/docs/zh/get-started/Full-Node.md index 8764b6149..f876c4ebe 100644 --- a/docs/zh/get-started/Full-Node.md +++ b/docs/zh/get-started/Full-Node.md @@ -23,7 +23,11 @@ wget https://raw.githubusercontent.com/irisnet/testnets/master/testnets/fuxi-300 ### 修改配置文件 在config.toml文件中可以配置以下信息: * 将`moniker`字段配置称为自定义的名称,这样便于区分不同的节点 -* `seed`字段用语设置种子节点,在fuxi-3001中的官方中字节点为:3fb472c641078eaaee4a4acbe32841f18967672c@35.165.232.141:26657 +* `seed`字段用语设置种子节点,在fuxi-3001中的官方中字节点为: +``` +c16700520a810b270206d59f0f02ea9abd85a4fe@35.165.232.141:26656 +a12cfb2f535210ea12731f94a76b691832056156@120.79.226.163:26656 +``` ## 启动一个全节点 @@ -86,4 +90,4 @@ iriscli status * `"catching_up":false`: 表示节点与网络保持同步 -* `"latest_block_height"`: 表示最新的区块高度 \ No newline at end of file +* `"latest_block_height"`: 表示最新的区块高度 From d240c0987172dd3d3c503db3faa95ff9effdaf41 Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Thu, 27 Sep 2018 22:05:48 +0800 Subject: [PATCH 116/124] complete the examples --- Makefile | 14 +- app/app.go | 6 +- client/upgrade/cli/query.go | 4 +- examples/irishub-bugfix-2/app/app.go | 35 ++-- examples/irishub-bugfix-2/app/context.go | 165 ------------------ .../cmd/iris-bugfix-2/main.go | 11 +- .../cmd/iriscli-bugfix-2/main.go | 156 ++++++++--------- .../irishub-bugfix-2/ibc/client/cli/tx.go | 15 +- examples/irishub1/app/app.go | 32 +++- examples/irishub1/app/context.go | 165 ------------------ examples/irishub1/cmd/iris1/main.go | 7 +- examples/irishub1/cmd/iriscli1/main.go | 154 ++++++++-------- examples/irishub1/ibc/client/cli/tx.go | 21 +-- 13 files changed, 239 insertions(+), 546 deletions(-) delete mode 100644 examples/irishub-bugfix-2/app/context.go delete mode 100644 examples/irishub1/app/context.go diff --git a/Makefile b/Makefile index 37480db56..db91e73c7 100644 --- a/Makefile +++ b/Makefile @@ -67,29 +67,19 @@ build_cur: update_irislcd_swagger_docs build_examples: update_irislcd_swagger_docs go build -o build/iris1 ./examples/irishub1/cmd/iris1 go build -o build/iriscli1 ./examples/irishub1/cmd/iriscli1 - go build -o build/iris2 ./examples/irishub2/cmd/iris2 - go build -o build/iriscli2 ./examples/irishub2/cmd/iriscli2 go build -o build/iris-bugfix-2 ./examples/irishub-bugfix-2/cmd/iris-bugfix-2 go build -o build/iriscli-bugfix-2 ./examples/irishub-bugfix-2/cmd/iriscli-bugfix-2 - go build -o build/iris-bugfix-3 ./examples/irishub-bugfix-3/cmd/iris-bugfix-3 - go build -o build/iriscli-bugfix-3 ./examples/irishub-bugfix-3/cmd/iriscli-bugfix-3 + install_examples: update_irislcd_swagger_docs go install ./examples/irishub1/cmd/iris1 go install ./examples/irishub1/cmd/iriscli1 - go install ./examples/irishub2/cmd/iris2 - go install ./examples/irishub2/cmd/iriscli2 go install ./examples/irishub-bugfix-2/cmd/iris-bugfix-2 go install ./examples/irishub-bugfix-2/cmd/iriscli-bugfix-2 - go install ./examples/irishub-bugfix-3/cmd/iris-bugfix-3 - go install ./examples/irishub-bugfix-3/cmd/iriscli-bugfix-3 + build_example_linux: update_irislcd_swagger_docs CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iris1 ./examples/irishub1/cmd/iris1 CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iriscli1 ./examples/irishub1/cmd/iriscli1 - CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iris2 ./examples/irishub2/cmd/iris2 - CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iriscli2 ./examples/irishub2/cmd/iriscli2 CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iris2-bugfix ./examples/irishub-bugfix-2/cmd/iris-bugfix-2 CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iriscli2-bugfix ./examples/irishub-bugfix-2/cmd/iriscli-bugfix-2 - CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iris3-bugfix ./examples/irishub-bugfix-3/cmd/iris-bugfix-3 - CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/iriscli3-bugfix ./examples/irishub-bugfix-3/cmd/iriscli-bugfix-3 \ No newline at end of file diff --git a/app/app.go b/app/app.go index f72bd9c30..ed234fe45 100644 --- a/app/app.go +++ b/app/app.go @@ -60,7 +60,6 @@ type IrisApp struct { keyGov *sdk.KVStoreKey keyFeeCollection *sdk.KVStoreKey keyParams *sdk.KVStoreKey - keyIparams *sdk.KVStoreKey keyUpgrade *sdk.KVStoreKey // Manage getting and setting accounts @@ -96,7 +95,6 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio keyGov: sdk.NewKVStoreKey("gov"), keyFeeCollection: sdk.NewKVStoreKey("fee"), keyParams: sdk.NewKVStoreKey("params"), - keyIparams: sdk.NewKVStoreKey("iparams"), keyUpgrade: sdk.NewKVStoreKey("upgrade"), } @@ -129,7 +127,7 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc.NewHandler(app.ibcMapper, app.coinKeeper)). AddRoute("stake", []*sdk.KVStoreKey{app.keyStake, app.keyAccount}, stake.NewHandler(app.stakeKeeper)). AddRoute("slashing", []*sdk.KVStoreKey{app.keySlashing, app.keyStake}, slashing.NewHandler(app.slashingKeeper)). - AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake, app.keyIparams, app.keyParams}, gov.NewHandler(app.govKeeper)). + AddRoute("gov", []*sdk.KVStoreKey{app.keyGov, app.keyAccount, app.keyStake, app.keyParams}, gov.NewHandler(app.govKeeper)). AddRoute("upgrade", []*sdk.KVStoreKey{app.keyUpgrade, app.keyStake}, upgrade.NewHandler(app.upgradeKeeper)) app.feeManager = bam.NewFeeManager(app.paramsKeeper.Setter()) @@ -140,7 +138,7 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) app.SetFeeRefundHandler(bam.NewFeeRefundHandler(app.accountMapper, app.feeCollectionKeeper, app.feeManager)) app.SetFeePreprocessHandler(bam.NewFeePreprocessHandler(app.feeManager)) - app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing, app.keyGov, app.keyFeeCollection, app.keyParams, app.keyIparams, app.keyUpgrade) + app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing, app.keyGov, app.keyFeeCollection, app.keyParams, app.keyUpgrade) app.SetRunMsg(app.runMsgs) var err error diff --git a/client/upgrade/cli/query.go b/client/upgrade/cli/query.go index 8975d60ec..ebc34f65b 100644 --- a/client/upgrade/cli/query.go +++ b/client/upgrade/cli/query.go @@ -25,8 +25,8 @@ func GetInfoCmd(storeName string, cdc *wire.Codec) *cobra.Command { WithLogger(os.Stdout). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - res_height, _ := cliCtx.QueryStore([]byte("gov/"+upgradeparams.ProposalAcceptHeightParameter.GetStoreKey()), "params") - res_proposalID, _ := cliCtx.QueryStore([]byte("gov/"+upgradeparams.CurrentUpgradeProposalIdParameter.GetStoreKey()), "params") + res_height, _ := cliCtx.QueryStore([]byte(upgradeparams.ProposalAcceptHeightParameter.GetStoreKey()), "params") + res_proposalID, _ := cliCtx.QueryStore([]byte(upgradeparams.CurrentUpgradeProposalIdParameter.GetStoreKey()), "params") var height int64 var proposalID int64 cdc.MustUnmarshalBinary(res_height, &height) diff --git a/examples/irishub-bugfix-2/app/app.go b/examples/irishub-bugfix-2/app/app.go index cbcae978c..ba1879843 100644 --- a/examples/irishub-bugfix-2/app/app.go +++ b/examples/irishub-bugfix-2/app/app.go @@ -16,7 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/irisnet/irishub/modules/gov" "github.com/cosmos/cosmos-sdk/x/ibc" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/slashing" @@ -33,6 +33,9 @@ import ( sm "github.com/tendermint/tendermint/state" bc "github.com/tendermint/tendermint/blockchain" "strings" + "github.com/irisnet/irishub/modules/iparam" + "github.com/irisnet/irishub/modules/gov/params" + "github.com/irisnet/irishub/modules/upgrade/params" ) const ( @@ -123,7 +126,7 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.paramsKeeper.Getter(), app.RegisterCodespace(slashing.DefaultCodespace)) app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection) app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper) - app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) + app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) //app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) // register message routes @@ -159,6 +162,17 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio } upgrade.RegisterModuleList(app.Router()) + iparam.SetParamReadWriter(app.paramsKeeper.Setter(), + &govparams.DepositProcedureParameter, + &govparams.VotingProcedureParameter, + &govparams.TallyingProcedureParameter, + &upgradeparams.CurrentUpgradeProposalIdParameter, + &upgradeparams.ProposalAcceptHeightParameter) + + iparam.RegisterGovParamMapping(&govparams.DepositProcedureParameter, + &govparams.VotingProcedureParameter, + &govparams.TallyingProcedureParameter,) + return app } @@ -224,21 +238,21 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci panic(err) } - minDeposit,err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s",10,Denom)) + minDeposit, err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", 10, Denom)) if err != nil { panic(err) } gov.InitGenesis(ctx, app.govKeeper, gov.GenesisState{ StartingProposalID: 1, - DepositProcedure: gov.DepositProcedure{ + DepositProcedure: govparams.DepositProcedure{ MinDeposit: sdk.Coins{minDeposit}, - MaxDepositPeriod: 1440, + MaxDepositPeriod: 10, }, - VotingProcedure: gov.VotingProcedure{ - VotingPeriod: 30, + VotingProcedure: govparams.VotingProcedure{ + VotingPeriod: 10, }, - TallyingProcedure: gov.TallyingProcedure{ + TallyingProcedure: govparams.TallyingProcedure{ Threshold: sdk.NewRat(1, 2), Veto: sdk.NewRat(1, 3), GovernancePenalty: sdk.NewRat(1, 100), @@ -297,7 +311,6 @@ func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) for msgIdx, msg := range msgs { // Match route. msgType, err := app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) - fmt.Println("============ runMsgs() =========== " + msgType) if err != nil { return err.Result() } @@ -306,7 +319,7 @@ func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) if handler == nil { return sdk.ErrUnknownRequest("Unrecognized Msg type: " + msgType).Result() } - fmt.Println(msg) + msgResult := handler(ctx, msg) // NOTE: GasWanted is determined by ante handler and @@ -354,7 +367,7 @@ func (app *IrisApp) replay() int64 { defer func() { stateDB.Close() blockStoreDB.Close() - } () + }() curState := sm.LoadState(stateDB) preState := sm.LoadPreState(stateDB) diff --git a/examples/irishub-bugfix-2/app/context.go b/examples/irishub-bugfix-2/app/context.go deleted file mode 100644 index adc073942..000000000 --- a/examples/irishub-bugfix-2/app/context.go +++ /dev/null @@ -1,165 +0,0 @@ -package app - -import ( - "fmt" - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/auth" - txcxt "github.com/cosmos/cosmos-sdk/x/auth/client/context" - "github.com/irisnet/irishub/types" - "github.com/pkg/errors" - client2 "github.com/tendermint/tendermint/rpc/client" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - "io/ioutil" - "net/http" - "strings" -) - -type Context struct { - context.CLIContext - txCtx txcxt.TxContext - Cdc *wire.Codec -} - -func NewContext() Context { - return Context{ - CLIContext: context.NewCLIContext(), - txCtx: txcxt.NewTxContextFromCLI(), - } -} -func (c Context) Get() context.CLIContext { - return c.CLIContext.WithCodec(c.Cdc) -} - -func (c Context) GetTxCxt() txcxt.TxContext { - return c.txCtx.WithCodec(c.Cdc) -} - -func (c Context) WithCodeC(cdc *wire.Codec) Context { - c.Cdc = cdc - c.CLIContext = c.CLIContext.WithCodec(cdc) - return c -} -func (c Context) WithCLIContext(ctx context.CLIContext) Context { - c.CLIContext = ctx - return c -} -func (c Context) WithTxContext(ctx txcxt.TxContext) Context { - c.txCtx = ctx - return c -} - -func (c Context) NetInfo() (*ctypes.ResultNetInfo, error) { - client := c.Client.(*client2.HTTP) - return client.NetInfo() -} - -func (c Context) NumUnconfirmedTxs() (*ctypes.ResultUnconfirmedTxs, error) { - client := &http.Client{} - url := strings.Replace(c.NodeURI, "tcp", "http", 1) - reqUri := fmt.Sprintf("%s/%s", url, "num_unconfirmed_txs") - - resp, err := client.Get(reqUri) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - var res = struct { - JsonRpc string `json:"jsonrpc"` - Id string `json:"id"` - Result ctypes.ResultUnconfirmedTxs `json:"result"` - }{} - - if err := c.Cdc.UnmarshalJSON(body, &res); err != nil { - return nil, err - } - - return &res.Result, nil -} - -func (c Context) GetCoinType(coinName string) (types.CoinType, error) { - var coinType types.CoinType - coinName = strings.ToLower(coinName) - if coinName == Denom { - coinType = IrisCt - } else { - key := types.CoinTypeKey(coinName) - bz, err := c.QueryStore([]byte(key), "iparams") - if err != nil { - return coinType, err - } - - if err = c.Cdc.UnmarshalBinary(bz, &coinType); err != nil { - return coinType, err - } - } - - return coinType, nil -} - -func (c Context) ParseCoin(coinStr string) (sdk.Coin, error) { - mainUnit, err := types.GetCoinName(coinStr) - coinType, err := c.GetCoinType(mainUnit) - if err != nil { - return sdk.Coin{}, err - } - - coin, err := coinType.ConvertToMinCoin(coinStr) - if err != nil { - return sdk.Coin{}, err - } - return coin, nil -} - -func (c Context) ParseCoins(coinsStr string) (coins sdk.Coins, err error) { - coinsStr = strings.TrimSpace(coinsStr) - if len(coinsStr) == 0 { - return coins, nil - } - - coinStrs := strings.Split(coinsStr, ",") - for _, coinStr := range coinStrs { - coin, err := c.ParseCoin(coinStr) - if err != nil { - return coins, err - } - coins = append(coins, coin) - } - return coins, nil -} - -// Build builds a single message to be signed from a TxContext given a set of -// messages. It returns an error if a fee is supplied but cannot be parsed. -func (c Context) Build(msgs []sdk.Msg) (auth.StdSignMsg, error) { - ctx := c.txCtx - chainID := ctx.ChainID - if chainID == "" { - return auth.StdSignMsg{}, errors.Errorf("chain ID required but not specified") - } - - fee := sdk.Coin{} - if ctx.Fee != "" { - parsedFee, err := c.ParseCoin(ctx.Fee) - if err != nil { - return auth.StdSignMsg{}, err - } - - fee = parsedFee - } - - return auth.StdSignMsg{ - ChainID: ctx.ChainID, - AccountNumber: ctx.AccountNumber, - Sequence: ctx.Sequence, - Memo: ctx.Memo, - Msgs: msgs, - Fee: auth.NewStdFee(ctx.Gas, fee), - }, nil -} diff --git a/examples/irishub-bugfix-2/cmd/iris-bugfix-2/main.go b/examples/irishub-bugfix-2/cmd/iris-bugfix-2/main.go index 0a199f50c..3d7145082 100644 --- a/examples/irishub-bugfix-2/cmd/iris-bugfix-2/main.go +++ b/examples/irishub-bugfix-2/cmd/iris-bugfix-2/main.go @@ -10,15 +10,15 @@ import ( "github.com/cosmos/cosmos-sdk/server" "github.com/irisnet/irishub/examples/irishub-bugfix-2/app" bam "github.com/irisnet/irishub/baseapp" - "github.com/irisnet/irishub/version" + "github.com/irisnet/irishub/tools/prometheus" + "github.com/irisnet/irishub/version" "github.com/spf13/viper" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/cli" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" tmtypes "github.com/tendermint/tendermint/types" - "github.com/irisnet/irishub/tools/prometheus" ) func main() { @@ -26,8 +26,8 @@ func main() { ctx := server.NewDefaultContext() cobra.EnableCommandSorting = false rootCmd := &cobra.Command{ - Use: "iris-bugfix-3", - Short: "iris-bugfix-3 Daemon (server)", + Use: "iris-bugfix-2", + Short: "iris-bugfix-2 Daemon (server)", PersistentPreRunE: server.PersistentPreRunEFn(ctx), } @@ -54,6 +54,9 @@ func main() { tendermintCmd, server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), client.LineBreak, + ) + + rootCmd.AddCommand( version.ServeVersionCommand(cdc), ) diff --git a/examples/irishub-bugfix-2/cmd/iriscli-bugfix-2/main.go b/examples/irishub-bugfix-2/cmd/iriscli-bugfix-2/main.go index 49b94f6a1..aaa8cca03 100644 --- a/examples/irishub-bugfix-2/cmd/iriscli-bugfix-2/main.go +++ b/examples/irishub-bugfix-2/cmd/iriscli-bugfix-2/main.go @@ -1,82 +1,93 @@ package main import ( - "github.com/spf13/cobra" - - "github.com/tendermint/tendermint/libs/cli" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/client/tx" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - ibccmd "github.com/irisnet/irishub/examples/irishub-bugfix-2/ibc/client/cli" - slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" - stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" "github.com/irisnet/irishub/examples/irishub-bugfix-2/app" - govcmd "github.com/cosmos/cosmos-sdk/x/gov/client/cli" + "github.com/irisnet/irishub/client" + bankcmd "github.com/irisnet/irishub/client/bank/cli" + govcmd "github.com/irisnet/irishub/client/gov/cli" + keyscmd "github.com/irisnet/irishub/client/keys/cli" + slashingcmd "github.com/irisnet/irishub/client/slashing/cli" + stakecmd "github.com/irisnet/irishub/client/stake/cli" + tendermintrpccmd "github.com/irisnet/irishub/client/tendermint/rpc" + tenderminttxcmd "github.com/irisnet/irishub/client/tendermint/tx" + ibccmd "github.com/irisnet/irishub/examples/irishub-bugfix-2/ibc/client/cli" upgradecmd "github.com/irisnet/irishub/client/upgrade/cli" "github.com/irisnet/irishub/version" + "github.com/spf13/cobra" + "github.com/tendermint/tendermint/libs/cli" ) // rootCmd is the entry point for this binary var ( rootCmd = &cobra.Command{ - Use: "iriscli-bugfix-3", + Use: "iriscli-bugfix-2", Short: "irishub2 light-client", } ) + func main() { cobra.EnableCommandSorting = false cdc := app.MakeCodec() - // TODO: setup keybase, viper object, etc. to be passed into - // the below functions and eliminate global vars, like we do - // with the cdc - - // add standard rpc commands - rpc.AddCommands(rootCmd) - + rootCmd.AddCommand(tendermintrpccmd.StatusCommand()) //Add state commands tendermintCmd := &cobra.Command{ Use: "tendermint", Short: "Tendermint state querying subcommands", } tendermintCmd.AddCommand( - rpc.BlockCommand(), - rpc.ValidatorCommand(), + tenderminttxcmd.QueryTxCmd(cdc), + tenderminttxcmd.SearchTxCmd(cdc), + tendermintrpccmd.BlockCommand(), + tendermintrpccmd.ValidatorCommand(), ) - tx.AddCommands(tendermintCmd, cdc) + rootCmd.AddCommand(tendermintCmd) - //Add IBC commands - ibcCmd := &cobra.Command{ - Use: "ibc", - Short: "Inter-Blockchain Communication subcommands", + //Add bank commands + bankCmd := &cobra.Command{ + Use: "bank", + Short: "Bank subcommands", } - ibcCmd.AddCommand( + bankCmd.AddCommand( + client.GetCommands( + bankcmd.GetCmdQueryCoinType(cdc), + bankcmd.GetAccountCmd("acc", cdc, authcmd.GetAccountDecoder(cdc)), + )...) + bankCmd.AddCommand( client.PostCommands( - ibccmd.IBCTransferCmd(cdc), - ibccmd.IBCSetCmd(cdc), - ibccmd.IBCGetCmd(cdc), + bankcmd.SendTxCmd(cdc), )...) + rootCmd.AddCommand( + bankCmd, + ) - advancedCmd := &cobra.Command{ - Use: "advanced", - Short: "Advanced subcommands", + //Add stake commands + govCmd := &cobra.Command{ + Use: "gov", + Short: "Governance and voting subcommands", } - - advancedCmd.AddCommand( - tendermintCmd, - ibcCmd, - ) + govCmd.AddCommand( + client.GetCommands( + govcmd.GetCmdQueryProposal("gov", cdc), + govcmd.GetCmdQueryProposals("gov", cdc), + govcmd.GetCmdQueryVote("gov", cdc), + govcmd.GetCmdQueryVotes("gov", cdc), + govcmd.GetCmdQueryGovConfig("params", cdc), + govcmd.GetCmdPullGovConfig("params", cdc), + )...) + govCmd.AddCommand( + client.PostCommands( + govcmd.GetCmdSubmitProposal(cdc), + govcmd.GetCmdDeposit(cdc), + govcmd.GetCmdVote(cdc), + )...) rootCmd.AddCommand( - advancedCmd, - client.LineBreak, + govCmd, ) - //Add stake commands + //Add staking and slashing commands stakeCmd := &cobra.Command{ Use: "stake", Short: "Stake and validation subcommands", @@ -87,6 +98,10 @@ func main() { stakecmd.GetCmdQueryValidators("stake", cdc), stakecmd.GetCmdQueryDelegation("stake", cdc), stakecmd.GetCmdQueryDelegations("stake", cdc), + stakecmd.GetCmdQueryUnbondingDelegation("stake", cdc), + stakecmd.GetCmdQueryUnbondingDelegations("stake", cdc), + stakecmd.GetCmdQueryRedelegation("stake", cdc), + stakecmd.GetCmdQueryRedelegations("stake", cdc), slashingcmd.GetCmdQuerySigningInfo("slashing", cdc), )...) stakeCmd.AddCommand( @@ -102,26 +117,6 @@ func main() { stakeCmd, ) - //Add gov commands - govCmd := &cobra.Command{ - Use: "gov", - Short: "Governance and voting subcommands", - } - govCmd.AddCommand( - client.GetCommands( - govcmd.GetCmdQueryProposal("gov", cdc), - govcmd.GetCmdQueryVote("gov", cdc), - )...) - govCmd.AddCommand( - client.PostCommands( - govcmd.GetCmdSubmitProposal(cdc), - govcmd.GetCmdDeposit(cdc), - govcmd.GetCmdVote(cdc), - )...) - rootCmd.AddCommand( - govCmd, - ) - //Add upgrade commands upgradeCmd := &cobra.Command{ Use: "upgrade", @@ -129,8 +124,8 @@ func main() { } upgradeCmd.AddCommand( client.GetCommands( - upgradecmd.GetCmdQuerySwitch("upgrade", cdc), upgradecmd.GetInfoCmd("upgrade", cdc), + upgradecmd.GetCmdQuerySwitch("upgrade", cdc), )...) upgradeCmd.AddCommand( client.PostCommands( @@ -140,31 +135,36 @@ func main() { upgradeCmd, ) - //Add auth and bank commands - rootCmd.AddCommand( - client.GetCommands( - authcmd.GetAccountCmd("acc", cdc, authcmd.GetAccountDecoder(cdc)), - )...) - rootCmd.AddCommand( + //Add IBC commands + ibcCmd := &cobra.Command{ + Use: "ibc", + Short: "Inter-Blockchain Communication subcommands", + } + ibcCmd.AddCommand( client.PostCommands( - bankcmd.SendTxCmd(cdc), + ibccmd.IBCTransferCmd(cdc), + ibccmd.IBCSetCmd(cdc), + ibccmd.IBCGetCmd(cdc), )...) - // add proxy, version and key info rootCmd.AddCommand( - keys.Commands(), - client.LineBreak, + ibcCmd, ) + + //Add keys and version commands rootCmd.AddCommand( - client.GetCommands( - version.ServeVersionCommand(cdc), - )...) + client.LineBreak, + keyscmd.Commands(), + version.ServeVersionCommand(cdc), + ) // prepare and add flags - executor := cli.PrepareMainCmd(rootCmd, "GA", app.DefaultCLIHome) + executor := cli.PrepareMainCmd(rootCmd, "IRISCLI", app.DefaultCLIHome) err := executor.Execute() if err != nil { // handle with #870 panic(err) } } + + diff --git a/examples/irishub-bugfix-2/ibc/client/cli/tx.go b/examples/irishub-bugfix-2/ibc/client/cli/tx.go index c6d629036..1fbe5dd96 100644 --- a/examples/irishub-bugfix-2/ibc/client/cli/tx.go +++ b/examples/irishub-bugfix-2/ibc/client/cli/tx.go @@ -2,14 +2,13 @@ package cli import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/irisnet/irishub/client/context" + "github.com/irisnet/irishub/client/utils" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - authctx "github.com/cosmos/cosmos-sdk/x/auth/client/context" "github.com/irisnet/irishub/examples/irishub-bugfix-2/ibc" "os" - "github.com/cosmos/cosmos-sdk/client/utils" ) // IBC transfer command @@ -17,11 +16,12 @@ func IBCGetCmd(cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "get", RunE: func(cmd *cobra.Command, args []string) error { - txCtx := authctx.NewTxContextFromCLI().WithCodec(cdc) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithLogger(os.Stdout). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc). + WithCliCtx(cliCtx) from, err := cliCtx.GetFromAddress() if err != nil { @@ -32,7 +32,7 @@ func IBCGetCmd(cdc *wire.Codec) *cobra.Command { msg := ibc.NewIBCGetMsg(from) cliCtx.PrintResponse = true - return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) + return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) }, } return cmd @@ -44,11 +44,12 @@ func IBCSetCmd(cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "set", RunE: func(cmd *cobra.Command, args []string) error { - txCtx := authctx.NewTxContextFromCLI().WithCodec(cdc) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithLogger(os.Stdout). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc). + WithCliCtx(cliCtx) from, err := cliCtx.GetFromAddress() if err != nil { @@ -59,7 +60,7 @@ func IBCSetCmd(cdc *wire.Codec) *cobra.Command { msg := ibc.NewIBCSetMsg(from) cliCtx.PrintResponse = true - return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) + return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) }, } return cmd diff --git a/examples/irishub1/app/app.go b/examples/irishub1/app/app.go index 76073eb37..35f408058 100644 --- a/examples/irishub1/app/app.go +++ b/examples/irishub1/app/app.go @@ -12,7 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/irisnet/irishub/modules/gov" "github.com/cosmos/cosmos-sdk/x/ibc" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/slashing" @@ -31,6 +31,9 @@ import ( sm "github.com/tendermint/tendermint/state" tmtypes "github.com/tendermint/tendermint/types" "strings" + "github.com/irisnet/irishub/modules/iparam" + "github.com/irisnet/irishub/modules/gov/params" + "github.com/irisnet/irishub/modules/upgrade/params" ) const ( @@ -118,7 +121,7 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.paramsKeeper.Getter(), app.RegisterCodespace(slashing.DefaultCodespace)) app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(app.cdc, app.keyFeeCollection) app.upgradeKeeper = upgrade.NewKeeper(app.cdc, app.keyUpgrade, app.stakeKeeper) - app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) + app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) //app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper.Setter(), app.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) // register message routes @@ -154,6 +157,18 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio } upgrade.RegisterModuleList(app.Router()) + upgrade.RegisterModuleList(app.Router()) + iparam.SetParamReadWriter(app.paramsKeeper.Setter(), + &govparams.DepositProcedureParameter, + &govparams.VotingProcedureParameter, + &govparams.TallyingProcedureParameter, + &upgradeparams.CurrentUpgradeProposalIdParameter, + &upgradeparams.ProposalAcceptHeightParameter) + + iparam.RegisterGovParamMapping(&govparams.DepositProcedureParameter, + &govparams.VotingProcedureParameter, + &govparams.TallyingProcedureParameter,) + return app } @@ -227,14 +242,14 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci gov.InitGenesis(ctx, app.govKeeper, gov.GenesisState{ StartingProposalID: 1, - DepositProcedure: gov.DepositProcedure{ + DepositProcedure: govparams.DepositProcedure{ MinDeposit: sdk.Coins{minDeposit}, - MaxDepositPeriod: 1440, + MaxDepositPeriod: 10, }, - VotingProcedure: gov.VotingProcedure{ - VotingPeriod: 30, + VotingProcedure: govparams.VotingProcedure{ + VotingPeriod: 10, }, - TallyingProcedure: gov.TallyingProcedure{ + TallyingProcedure: govparams.TallyingProcedure{ Threshold: sdk.NewRat(1, 2), Veto: sdk.NewRat(1, 3), GovernancePenalty: sdk.NewRat(1, 100), @@ -293,7 +308,6 @@ func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) for msgIdx, msg := range msgs { // Match route. msgType, err := app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) - fmt.Println("============ runMsgs() =========== " + msgType) if err != nil { return err.Result() } @@ -302,7 +316,7 @@ func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) if handler == nil { return sdk.ErrUnknownRequest("Unrecognized Msg type: " + msgType).Result() } - fmt.Println(msg) + msgResult := handler(ctx, msg) // NOTE: GasWanted is determined by ante handler and diff --git a/examples/irishub1/app/context.go b/examples/irishub1/app/context.go deleted file mode 100644 index adc073942..000000000 --- a/examples/irishub1/app/context.go +++ /dev/null @@ -1,165 +0,0 @@ -package app - -import ( - "fmt" - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/auth" - txcxt "github.com/cosmos/cosmos-sdk/x/auth/client/context" - "github.com/irisnet/irishub/types" - "github.com/pkg/errors" - client2 "github.com/tendermint/tendermint/rpc/client" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - "io/ioutil" - "net/http" - "strings" -) - -type Context struct { - context.CLIContext - txCtx txcxt.TxContext - Cdc *wire.Codec -} - -func NewContext() Context { - return Context{ - CLIContext: context.NewCLIContext(), - txCtx: txcxt.NewTxContextFromCLI(), - } -} -func (c Context) Get() context.CLIContext { - return c.CLIContext.WithCodec(c.Cdc) -} - -func (c Context) GetTxCxt() txcxt.TxContext { - return c.txCtx.WithCodec(c.Cdc) -} - -func (c Context) WithCodeC(cdc *wire.Codec) Context { - c.Cdc = cdc - c.CLIContext = c.CLIContext.WithCodec(cdc) - return c -} -func (c Context) WithCLIContext(ctx context.CLIContext) Context { - c.CLIContext = ctx - return c -} -func (c Context) WithTxContext(ctx txcxt.TxContext) Context { - c.txCtx = ctx - return c -} - -func (c Context) NetInfo() (*ctypes.ResultNetInfo, error) { - client := c.Client.(*client2.HTTP) - return client.NetInfo() -} - -func (c Context) NumUnconfirmedTxs() (*ctypes.ResultUnconfirmedTxs, error) { - client := &http.Client{} - url := strings.Replace(c.NodeURI, "tcp", "http", 1) - reqUri := fmt.Sprintf("%s/%s", url, "num_unconfirmed_txs") - - resp, err := client.Get(reqUri) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - var res = struct { - JsonRpc string `json:"jsonrpc"` - Id string `json:"id"` - Result ctypes.ResultUnconfirmedTxs `json:"result"` - }{} - - if err := c.Cdc.UnmarshalJSON(body, &res); err != nil { - return nil, err - } - - return &res.Result, nil -} - -func (c Context) GetCoinType(coinName string) (types.CoinType, error) { - var coinType types.CoinType - coinName = strings.ToLower(coinName) - if coinName == Denom { - coinType = IrisCt - } else { - key := types.CoinTypeKey(coinName) - bz, err := c.QueryStore([]byte(key), "iparams") - if err != nil { - return coinType, err - } - - if err = c.Cdc.UnmarshalBinary(bz, &coinType); err != nil { - return coinType, err - } - } - - return coinType, nil -} - -func (c Context) ParseCoin(coinStr string) (sdk.Coin, error) { - mainUnit, err := types.GetCoinName(coinStr) - coinType, err := c.GetCoinType(mainUnit) - if err != nil { - return sdk.Coin{}, err - } - - coin, err := coinType.ConvertToMinCoin(coinStr) - if err != nil { - return sdk.Coin{}, err - } - return coin, nil -} - -func (c Context) ParseCoins(coinsStr string) (coins sdk.Coins, err error) { - coinsStr = strings.TrimSpace(coinsStr) - if len(coinsStr) == 0 { - return coins, nil - } - - coinStrs := strings.Split(coinsStr, ",") - for _, coinStr := range coinStrs { - coin, err := c.ParseCoin(coinStr) - if err != nil { - return coins, err - } - coins = append(coins, coin) - } - return coins, nil -} - -// Build builds a single message to be signed from a TxContext given a set of -// messages. It returns an error if a fee is supplied but cannot be parsed. -func (c Context) Build(msgs []sdk.Msg) (auth.StdSignMsg, error) { - ctx := c.txCtx - chainID := ctx.ChainID - if chainID == "" { - return auth.StdSignMsg{}, errors.Errorf("chain ID required but not specified") - } - - fee := sdk.Coin{} - if ctx.Fee != "" { - parsedFee, err := c.ParseCoin(ctx.Fee) - if err != nil { - return auth.StdSignMsg{}, err - } - - fee = parsedFee - } - - return auth.StdSignMsg{ - ChainID: ctx.ChainID, - AccountNumber: ctx.AccountNumber, - Sequence: ctx.Sequence, - Memo: ctx.Memo, - Msgs: msgs, - Fee: auth.NewStdFee(ctx.Gas, fee), - }, nil -} diff --git a/examples/irishub1/cmd/iris1/main.go b/examples/irishub1/cmd/iris1/main.go index 6b1618d69..f07bf4520 100644 --- a/examples/irishub1/cmd/iris1/main.go +++ b/examples/irishub1/cmd/iris1/main.go @@ -10,15 +10,15 @@ import ( "github.com/cosmos/cosmos-sdk/server" "github.com/irisnet/irishub/examples/irishub1/app" bam "github.com/irisnet/irishub/baseapp" - "github.com/irisnet/irishub/version" + "github.com/irisnet/irishub/tools/prometheus" + "github.com/irisnet/irishub/version" "github.com/spf13/viper" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/cli" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" tmtypes "github.com/tendermint/tendermint/types" - "github.com/irisnet/irishub/tools/prometheus" ) func main() { @@ -54,6 +54,9 @@ func main() { tendermintCmd, server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), client.LineBreak, + ) + + rootCmd.AddCommand( version.ServeVersionCommand(cdc), ) diff --git a/examples/irishub1/cmd/iriscli1/main.go b/examples/irishub1/cmd/iriscli1/main.go index 9a381673f..91036bf7a 100644 --- a/examples/irishub1/cmd/iriscli1/main.go +++ b/examples/irishub1/cmd/iriscli1/main.go @@ -1,23 +1,21 @@ package main import ( - "github.com/spf13/cobra" - - "github.com/tendermint/tendermint/libs/cli" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/client/tx" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - ibccmd "github.com/irisnet/irishub/examples/irishub1/ibc/client/cli" - slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" - stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli" "github.com/irisnet/irishub/examples/irishub1/app" - govcmd "github.com/cosmos/cosmos-sdk/x/gov/client/cli" + "github.com/irisnet/irishub/client" + bankcmd "github.com/irisnet/irishub/client/bank/cli" + govcmd "github.com/irisnet/irishub/client/gov/cli" + keyscmd "github.com/irisnet/irishub/client/keys/cli" + slashingcmd "github.com/irisnet/irishub/client/slashing/cli" + stakecmd "github.com/irisnet/irishub/client/stake/cli" + tendermintrpccmd "github.com/irisnet/irishub/client/tendermint/rpc" + tenderminttxcmd "github.com/irisnet/irishub/client/tendermint/tx" + ibccmd "github.com/irisnet/irishub/examples/irishub1/ibc/client/cli" upgradecmd "github.com/irisnet/irishub/client/upgrade/cli" "github.com/irisnet/irishub/version" + "github.com/spf13/cobra" + "github.com/tendermint/tendermint/libs/cli" ) // rootCmd is the entry point for this binary @@ -28,55 +26,68 @@ var ( } ) + func main() { cobra.EnableCommandSorting = false cdc := app.MakeCodec() - // TODO: setup keybase, viper object, etc. to be passed into - // the below functions and eliminate global vars, like we do - // with the cdc - - // add standard rpc commands - rpc.AddCommands(rootCmd) - + rootCmd.AddCommand(tendermintrpccmd.StatusCommand()) //Add state commands tendermintCmd := &cobra.Command{ Use: "tendermint", Short: "Tendermint state querying subcommands", } tendermintCmd.AddCommand( - rpc.BlockCommand(), - rpc.ValidatorCommand(), + tenderminttxcmd.QueryTxCmd(cdc), + tenderminttxcmd.SearchTxCmd(cdc), + tendermintrpccmd.BlockCommand(), + tendermintrpccmd.ValidatorCommand(), ) - tx.AddCommands(tendermintCmd, cdc) + rootCmd.AddCommand(tendermintCmd) - //Add IBC commands - ibcCmd := &cobra.Command{ - Use: "ibc", - Short: "Inter-Blockchain Communication subcommands", + //Add bank commands + bankCmd := &cobra.Command{ + Use: "bank", + Short: "Bank subcommands", } - ibcCmd.AddCommand( + bankCmd.AddCommand( + client.GetCommands( + bankcmd.GetCmdQueryCoinType(cdc), + bankcmd.GetAccountCmd("acc", cdc, authcmd.GetAccountDecoder(cdc)), + )...) + bankCmd.AddCommand( client.PostCommands( - ibccmd.IBCTransferCmd(cdc), - ibccmd.IBCSetCmd(cdc), - ibccmd.IBCGetCmd(cdc), + bankcmd.SendTxCmd(cdc), )...) + rootCmd.AddCommand( + bankCmd, + ) - advancedCmd := &cobra.Command{ - Use: "advanced", - Short: "Advanced subcommands", + //Add stake commands + govCmd := &cobra.Command{ + Use: "gov", + Short: "Governance and voting subcommands", } - - advancedCmd.AddCommand( - tendermintCmd, - ibcCmd, - ) + govCmd.AddCommand( + client.GetCommands( + govcmd.GetCmdQueryProposal("gov", cdc), + govcmd.GetCmdQueryProposals("gov", cdc), + govcmd.GetCmdQueryVote("gov", cdc), + govcmd.GetCmdQueryVotes("gov", cdc), + govcmd.GetCmdQueryGovConfig("params", cdc), + govcmd.GetCmdPullGovConfig("params", cdc), + )...) + govCmd.AddCommand( + client.PostCommands( + govcmd.GetCmdSubmitProposal(cdc), + govcmd.GetCmdDeposit(cdc), + govcmd.GetCmdVote(cdc), + )...) rootCmd.AddCommand( - advancedCmd, - client.LineBreak, + govCmd, ) - //Add stake commands + //Add staking and slashing commands stakeCmd := &cobra.Command{ Use: "stake", Short: "Stake and validation subcommands", @@ -87,6 +98,10 @@ func main() { stakecmd.GetCmdQueryValidators("stake", cdc), stakecmd.GetCmdQueryDelegation("stake", cdc), stakecmd.GetCmdQueryDelegations("stake", cdc), + stakecmd.GetCmdQueryUnbondingDelegation("stake", cdc), + stakecmd.GetCmdQueryUnbondingDelegations("stake", cdc), + stakecmd.GetCmdQueryRedelegation("stake", cdc), + stakecmd.GetCmdQueryRedelegations("stake", cdc), slashingcmd.GetCmdQuerySigningInfo("slashing", cdc), )...) stakeCmd.AddCommand( @@ -102,26 +117,6 @@ func main() { stakeCmd, ) - //Add gov commands - govCmd := &cobra.Command{ - Use: "gov", - Short: "Governance and voting subcommands", - } - govCmd.AddCommand( - client.GetCommands( - govcmd.GetCmdQueryProposal("gov", cdc), - govcmd.GetCmdQueryVote("gov", cdc), - )...) - govCmd.AddCommand( - client.PostCommands( - govcmd.GetCmdSubmitProposal(cdc), - govcmd.GetCmdDeposit(cdc), - govcmd.GetCmdVote(cdc), - )...) - rootCmd.AddCommand( - govCmd, - ) - //Add upgrade commands upgradeCmd := &cobra.Command{ Use: "upgrade", @@ -129,8 +124,8 @@ func main() { } upgradeCmd.AddCommand( client.GetCommands( - upgradecmd.GetCmdQuerySwitch("upgrade", cdc), upgradecmd.GetInfoCmd("upgrade", cdc), + upgradecmd.GetCmdQuerySwitch("upgrade", cdc), )...) upgradeCmd.AddCommand( client.PostCommands( @@ -140,31 +135,36 @@ func main() { upgradeCmd, ) - //Add auth and bank commands - rootCmd.AddCommand( - client.GetCommands( - authcmd.GetAccountCmd("acc", cdc, authcmd.GetAccountDecoder(cdc)), - )...) - rootCmd.AddCommand( + //Add IBC commands + ibcCmd := &cobra.Command{ + Use: "ibc", + Short: "Inter-Blockchain Communication subcommands", + } + + ibcCmd.AddCommand( client.PostCommands( - bankcmd.SendTxCmd(cdc), + ibccmd.IBCTransferCmd(cdc), + ibccmd.IBCSetCmd(cdc), + ibccmd.IBCGetCmd(cdc), )...) + rootCmd.AddCommand( + ibcCmd, + ) - // add proxy, version and key info + //Add keys and version commands rootCmd.AddCommand( - keys.Commands(), client.LineBreak, + keyscmd.Commands(), + version.ServeVersionCommand(cdc), ) - rootCmd.AddCommand( - client.GetCommands( - version.ServeVersionCommand(cdc), - )...) // prepare and add flags - executor := cli.PrepareMainCmd(rootCmd, "GA", app.DefaultCLIHome) + executor := cli.PrepareMainCmd(rootCmd, "IRISCLI", app.DefaultCLIHome) err := executor.Execute() if err != nil { // handle with #870 panic(err) } } + + diff --git a/examples/irishub1/ibc/client/cli/tx.go b/examples/irishub1/ibc/client/cli/tx.go index 77b1e5909..7029de652 100644 --- a/examples/irishub1/ibc/client/cli/tx.go +++ b/examples/irishub1/ibc/client/cli/tx.go @@ -2,14 +2,13 @@ package cli import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/irisnet/irishub/client/context" + "github.com/irisnet/irishub/client/utils" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - authctx "github.com/cosmos/cosmos-sdk/x/auth/client/context" - "github.com/irisnet/irishub/examples/irishub1/ibc" + "github.com/cosmos/cosmos-sdk/wire" + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + "github.com/irisnet/irishub/examples/irishub1/ibc" "os" - "github.com/cosmos/cosmos-sdk/client/utils" ) // IBC transfer command @@ -17,11 +16,12 @@ func IBCGetCmd(cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "get", RunE: func(cmd *cobra.Command, args []string) error { - txCtx := authctx.NewTxContextFromCLI().WithCodec(cdc) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithLogger(os.Stdout). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc). + WithCliCtx(cliCtx) from, err := cliCtx.GetFromAddress() if err != nil { @@ -32,7 +32,7 @@ func IBCGetCmd(cdc *wire.Codec) *cobra.Command { msg := ibc.NewIBCGetMsg(from) cliCtx.PrintResponse = true - return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) + return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) }, } return cmd @@ -44,11 +44,12 @@ func IBCSetCmd(cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "set", RunE: func(cmd *cobra.Command, args []string) error { - txCtx := authctx.NewTxContextFromCLI().WithCodec(cdc) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithLogger(os.Stdout). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc). + WithCliCtx(cliCtx) from, err := cliCtx.GetFromAddress() if err != nil { @@ -59,7 +60,7 @@ func IBCSetCmd(cdc *wire.Codec) *cobra.Command { msg := ibc.NewIBCSetMsg(from) cliCtx.PrintResponse = true - return utils.SendTx(txCtx, cliCtx, []sdk.Msg{msg}) + return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) }, } return cmd From e667f2382cb9f2888119949996c0391156f2f92d Mon Sep 17 00:00:00 2001 From: Raymond Date: Fri, 28 Sep 2018 11:28:08 +0800 Subject: [PATCH 117/124] IRISHUB-258: release version 0.5.0-rc0 --- Gopkg.toml | 7 +++---- version/version.go | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/Gopkg.toml b/Gopkg.toml index b6551264e..161137842 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -29,7 +29,7 @@ [[constraint]] name = "github.com/cosmos/cosmos-sdk" source = "https://github.com/irisnet/cosmos-sdk.git" - branch = "irisnet/develop" + version = "=v0.24.2-iris1" [[override]] name = "github.com/golang/protobuf" @@ -49,14 +49,13 @@ [[override]] name = "github.com/tendermint/iavl" -# version = "=v0.9.2" - branch = "irisnet/feature_upgrade" source = "https://github.com/irisnet/iavl.git" + version = "=v0.9.2-iris1" [[override]] name = "github.com/tendermint/tendermint" source = "https://github.com/irisnet/tendermint.git" - branch = "irisnet/develop" + version = "=v0.23.1-rc0-iris1" [[constraint]] name = "github.com/rakyll/statik" diff --git a/version/version.go b/version/version.go index d5fda74c4..26d2b2a11 100644 --- a/version/version.go +++ b/version/version.go @@ -7,7 +7,7 @@ import ( ) // Version - Iris Version -const Version = "0.5.0-Alpha" +const Version = "0.5.0-rc0" // GitCommit set by build flags var GitCommit = "" From b1e8fe38871c05dd1cd5084b1da0197e78a9f364 Mon Sep 17 00:00:00 2001 From: Raymond Date: Fri, 28 Sep 2018 13:50:58 +0800 Subject: [PATCH 118/124] IRISHUB-258: update gopkg.lock and update genesis params for QA test temporarily --- Gopkg.lock | 33 +++++++++------------------------ app/app.go | 4 ++-- modules/upgrade/keeper.go | 4 ++-- 3 files changed, 13 insertions(+), 28 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index e652929e6..4a0ea698a 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -56,16 +56,13 @@ revision = "d4cc87b860166d00d6b5b9e0d3b3d71d6088d4d4" [[projects]] - branch = "irisnet/develop" - digest = "1:5df3d1c3a90a759d109516f403b494d3b4f6d614538ceb562a03e5a411f1667f" + digest = "1:1b6b69a3b0b1ce19e038ba842043d158fc14ff5d0e55e0324a6f795cb4ace1d2" name = "github.com/cosmos/cosmos-sdk" packages = [ "baseapp", "client", "client/context", "client/keys", - "client/rpc", - "client/tx", "client/utils", "crypto", "crypto/keys", @@ -82,26 +79,22 @@ "x/auth/client/cli", "x/auth/client/context", "x/bank", - "x/bank/client", - "x/bank/client/cli", "x/gov", - "x/gov/client/cli", "x/gov/tags", "x/ibc", "x/mock", "x/mock/simulation", "x/params", "x/slashing", - "x/slashing/client/cli", "x/stake", - "x/stake/client/cli", "x/stake/keeper", "x/stake/tags", "x/stake/types", ] pruneopts = "UT" - revision = "8c058b8e5b028dc7373f5427dd36e00686d8f6a5" + revision = "c6189e6d8c13d6b78a009f83e0ceac4a1aab3d73" source = "https://github.com/irisnet/cosmos-sdk.git" + version = "v0.24.2-iris1" [[projects]] digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec" @@ -514,17 +507,16 @@ version = "v0.12.0-rc0" [[projects]] - branch = "irisnet/feature_upgrade" - digest = "1:54f4d8af39f33769cd0d9de09141a676283d2948a349c9ae72dc39dfd6a6aae8" + digest = "1:f6e293333e941a78f8029927165d1926c5efdedd8612a3108977b30b8a871b87" name = "github.com/tendermint/iavl" packages = ["."] pruneopts = "UT" - revision = "849c21e8f93ce782cb9f9f64fabcccb5580b4f90" + revision = "f93c0a13ec78edd04c6faef6b3158f72e66f699f" source = "https://github.com/irisnet/iavl.git" + version = "v0.9.2-iris1" [[projects]] - branch = "irisnet/develop" - digest = "1:3b9a2a8316e40b16dcd3f5f42e467b049b5d68465a5d8360014d0b3acebd570e" + digest = "1:e787411e638d991be9b98018f4f31854fb33e28d8e3e4a5b1e6fbeed39f51bb4" name = "github.com/tendermint/tendermint" packages = [ "abci/client", @@ -587,8 +579,9 @@ "version", ] pruneopts = "UT" - revision = "c7737b350a9453bab6571d8d5f489a590609d6f2" + revision = "46b52ca74937f3a680a4861f7b60b262d3fda777" source = "https://github.com/irisnet/tendermint.git" + version = "0.23.1-rc0-iris1" [[projects]] digest = "1:4dcb0dd65feecb068ce23a234d1a07c7868a1e39f52a6defcae0bb371d03abf6" @@ -729,9 +722,6 @@ "github.com/cosmos/cosmos-sdk/baseapp", "github.com/cosmos/cosmos-sdk/client", "github.com/cosmos/cosmos-sdk/client/context", - "github.com/cosmos/cosmos-sdk/client/keys", - "github.com/cosmos/cosmos-sdk/client/rpc", - "github.com/cosmos/cosmos-sdk/client/tx", "github.com/cosmos/cosmos-sdk/client/utils", "github.com/cosmos/cosmos-sdk/crypto", "github.com/cosmos/cosmos-sdk/crypto/keys", @@ -744,18 +734,14 @@ "github.com/cosmos/cosmos-sdk/x/auth/client/cli", "github.com/cosmos/cosmos-sdk/x/auth/client/context", "github.com/cosmos/cosmos-sdk/x/bank", - "github.com/cosmos/cosmos-sdk/x/bank/client/cli", "github.com/cosmos/cosmos-sdk/x/gov", - "github.com/cosmos/cosmos-sdk/x/gov/client/cli", "github.com/cosmos/cosmos-sdk/x/gov/tags", "github.com/cosmos/cosmos-sdk/x/ibc", "github.com/cosmos/cosmos-sdk/x/mock", "github.com/cosmos/cosmos-sdk/x/mock/simulation", "github.com/cosmos/cosmos-sdk/x/params", "github.com/cosmos/cosmos-sdk/x/slashing", - "github.com/cosmos/cosmos-sdk/x/slashing/client/cli", "github.com/cosmos/cosmos-sdk/x/stake", - "github.com/cosmos/cosmos-sdk/x/stake/client/cli", "github.com/cosmos/cosmos-sdk/x/stake/tags", "github.com/cosmos/cosmos-sdk/x/stake/types", "github.com/go-kit/kit/metrics", @@ -774,7 +760,6 @@ "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/tendermint/abci/server", diff --git a/app/app.go b/app/app.go index ed234fe45..0bbc001c8 100644 --- a/app/app.go +++ b/app/app.go @@ -235,10 +235,10 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci StartingProposalID: 1, DepositProcedure: govparams.DepositProcedure{ MinDeposit: sdk.Coins{minDeposit}, - MaxDepositPeriod: 10, + MaxDepositPeriod: 30, }, VotingProcedure: govparams.VotingProcedure{ - VotingPeriod: 10, + VotingPeriod: 30, }, TallyingProcedure: govparams.TallyingProcedure{ Threshold: sdk.NewRat(1, 2), diff --git a/modules/upgrade/keeper.go b/modules/upgrade/keeper.go index c11358caa..50243d66d 100644 --- a/modules/upgrade/keeper.go +++ b/modules/upgrade/keeper.go @@ -8,8 +8,8 @@ import ( ) const ( - defaultSwitchPeriod int64 = 57600 // 2 days - //defaultSwitchPeriod int64 = 30 // for test (4 minutes) + //defaultSwitchPeriod int64 = 57600 // 2 days + defaultSwitchPeriod int64 = 40 // for test (4 minutes) ) type Keeper struct { From 2b632ec30e783b86a26a303b8af55a957105aced Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Sat, 29 Sep 2018 10:01:44 +0800 Subject: [PATCH 119/124] IRISHUB-487:fix the bug --- modules/gov/params/gov_params.go | 6 +++--- modules/gov/params/gov_params_test.go | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/gov/params/gov_params.go b/modules/gov/params/gov_params.go index 76c5bf7f8..e60792256 100644 --- a/modules/gov/params/gov_params.go +++ b/modules/gov/params/gov_params.go @@ -264,13 +264,13 @@ func (param *TallyingProcedureParam) Valid(jsonStr string) sdk.Error { if err = json.Unmarshal([]byte(jsonStr), ¶m.Value); err == nil { - if param.Value.Threshold.LT(sdk.NewRat(0)) || param.Value.Threshold.GT(sdk.NewRat(1)) { + if param.Value.Threshold.LTE(sdk.NewRat(0)) || param.Value.Threshold.GTE(sdk.NewRat(1)) { return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidThreshold, fmt.Sprintf("VotingPeriod ( "+param.Value.Threshold.String()+" ) should be between 0 and 1")) } - if param.Value.GovernancePenalty.LT(sdk.NewRat(0)) || param.Value.GovernancePenalty.GT(sdk.NewRat(1)) { + if param.Value.GovernancePenalty.LTE(sdk.NewRat(0)) || param.Value.GovernancePenalty.GTE(sdk.NewRat(1)) { return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidGovernancePenalty, fmt.Sprintf("VotingPeriod ( "+param.Value.GovernancePenalty.String()+" ) should be between 0 and 1")) } - if param.Value.Veto.LT(sdk.NewRat(0)) || param.Value.Veto.GT(sdk.NewRat(1)) { + if param.Value.Veto.LTE(sdk.NewRat(0)) || param.Value.Veto.GTE(sdk.NewRat(1)) { return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidVeto, fmt.Sprintf("VotingPeriod ( "+param.Value.Veto.String()+" ) should be between 0 and 1")) } diff --git a/modules/gov/params/gov_params_test.go b/modules/gov/params/gov_params_test.go index 4129a3c3f..424f95e1b 100644 --- a/modules/gov/params/gov_params_test.go +++ b/modules/gov/params/gov_params_test.go @@ -158,7 +158,7 @@ func TestTallyingProcedureParam(t *testing.T) { require.NotEqual(t, p1, TallyingProcedureParameter.Value) require.Equal(t, p2, TallyingProcedureParameter.Value) - result := TallyingProcedureParameter.Valid("{\"threshold\":\"2/1\",\"veto\":\"1/3\",\"governance_penalty\":\"1/100\"}") + result := TallyingProcedureParameter.Valid("{\"threshold\":\"1/1\",\"veto\":\"1/3\",\"governance_penalty\":\"1/100\"}") require.Error(t, result) result = TallyingProcedureParameter.Valid("{\"threshold\":\"abcd\",\"veto\":\"1/3\",\"governance_penalty\":\"1/100\"}") From 0e41f1a6510fac7da0b03d64864c02cf2c8a574b Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Sat, 29 Sep 2018 10:10:31 +0800 Subject: [PATCH 120/124] IRISHUB484:fix the opStr check bug --- modules/gov/msgs.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/modules/gov/msgs.go b/modules/gov/msgs.go index ddf1e7bef..5c0900d34 100644 --- a/modules/gov/msgs.go +++ b/modules/gov/msgs.go @@ -58,15 +58,18 @@ func (msg MsgSubmitProposal) ValidateBasic() sdk.Error { if msg.ProposalType == ProposalTypeParameterChange { + + if msg.Param.Op != Update && msg.Param.Op != Insert { + return ErrInvalidParamOp(DefaultCodespace, msg.Param.Op) + } + if p, ok := iparam.ParamMapping[msg.Param.Key]; ok{ return p.Valid(msg.Param.Value) } else { return ErrInvalidParam(DefaultCodespace) } - if msg.Param.Op != Update && msg.Param.Op != Insert { - return ErrInvalidParamOp(DefaultCodespace, msg.Param.Op) - } + } From f703712c70e910d4aa04ef9242d9e01c67834eea Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Sat, 29 Sep 2018 10:33:54 +0800 Subject: [PATCH 121/124] IRISHUB483: Return the error msg when module is empty --- client/gov/cli/query.go | 14 +++++++++++--- modules/iparam/errors.go | 4 +++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/client/gov/cli/query.go b/client/gov/cli/query.go index 5dfb52edc..a73104de9 100644 --- a/client/gov/cli/query.go +++ b/client/gov/cli/query.go @@ -269,13 +269,19 @@ func GetCmdQueryGovConfig(storeName string, cdc *wire.Codec) *cobra.Command { if moduleStr != "" { res, err := ctx.QuerySubspace([]byte("Gov/"+moduleStr), storeName) - if err == nil { + if err == nil{ + + if len(res) == 0 { + return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidModule, fmt.Sprintf("The GovParameter of the module %s is not existed", moduleStr)) + } + var keys []string for _, kv := range res { keys = append(keys, string(kv.Key)) } + output, err := json.MarshalIndent(keys, "", " ") - //cmn.WriteFile(,output,644) + if err != nil { return err } @@ -294,8 +300,10 @@ func GetCmdQueryGovConfig(storeName string, cdc *wire.Codec) *cobra.Command { res, err := ctx.QueryStore([]byte(keyStr), storeName) if err == nil { if p, ok := iparam.ParamMapping[keyStr]; ok { + p.GetValueFromRawData(cdc, res) //.(govparams.TallyingProcedure) PrintParamStr(p, keyStr) + } else { return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidTallyingProcedure, fmt.Sprintf(keyStr+" is not found")) } @@ -305,7 +313,7 @@ func GetCmdQueryGovConfig(storeName string, cdc *wire.Codec) *cobra.Command { } - return nil + return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidQueryParams, fmt.Sprintf("--module and --key can't both be empty")) }, } diff --git a/modules/iparam/errors.go b/modules/iparam/errors.go index 2a72be310..2f6ee4350 100644 --- a/modules/iparam/errors.go +++ b/modules/iparam/errors.go @@ -18,5 +18,7 @@ const ( CodeInvalidVeto sdk.CodeType = 109 CodeInvalidTallyingProcedure sdk.CodeType = 110 CodeInvalidKey sdk.CodeType = 111 - CodeInvalidParamString sdk.CodeType = 123 + CodeInvalidParamString sdk.CodeType = 112 + CodeInvalidModule sdk.CodeType = 113 + CodeInvalidQueryParams sdk.CodeType = 114 ) From f4a4cd342646bd7b28a70ae17ed0ee088ee4f5f2 Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Sat, 29 Sep 2018 10:35:49 +0800 Subject: [PATCH 122/124] IRISHUB-486:delete the invalid log --- modules/gov/params/gov_params.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/gov/params/gov_params.go b/modules/gov/params/gov_params.go index e60792256..f86f108c2 100644 --- a/modules/gov/params/gov_params.go +++ b/modules/gov/params/gov_params.go @@ -95,7 +95,7 @@ func (param *DepositProcedureParam) Valid(jsonStr string) sdk.Error { if err = json.Unmarshal([]byte(jsonStr), ¶m.Value); err == nil { if param.Value.MinDeposit[0].Denom != "iris-atto" { - return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidMinDepositDenom, fmt.Sprintf("It should be iris-atto! git")) + return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidMinDepositDenom, fmt.Sprintf("It should be iris-atto!")) } LowerBound, _ := types.NewDefaultCoinType("iris").ConvertToMinCoin(fmt.Sprintf("%d%s", LOWER_BOUND_AMOUNT, "iris")) From f666427bad03a342dd58c984c744d46a3b80e4c9 Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Sat, 29 Sep 2018 11:00:05 +0800 Subject: [PATCH 123/124] IRISHUB-481: fix the panic bug --- client/gov/cli/query.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/client/gov/cli/query.go b/client/gov/cli/query.go index a73104de9..9ec791df9 100644 --- a/client/gov/cli/query.go +++ b/client/gov/cli/query.go @@ -301,11 +301,16 @@ func GetCmdQueryGovConfig(storeName string, cdc *wire.Codec) *cobra.Command { if err == nil { if p, ok := iparam.ParamMapping[keyStr]; ok { - p.GetValueFromRawData(cdc, res) //.(govparams.TallyingProcedure) + if len(res) == 0 { + return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidKey, fmt.Sprintf(keyStr+" is not existed")) + } + + p.GetValueFromRawData(cdc, res) PrintParamStr(p, keyStr) + return nil } else { - return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidTallyingProcedure, fmt.Sprintf(keyStr+" is not found")) + return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidKey, fmt.Sprintf(keyStr+" is not found")) } } else { return err From b2c38b436a2d7671ba3915ca821fbcecde9f60cb Mon Sep 17 00:00:00 2001 From: xujiacheng Date: Sat, 29 Sep 2018 11:04:40 +0800 Subject: [PATCH 124/124] IRISHUB-478:fix the check keyStr when submiting proposals --- client/gov/cli/flags.go | 3 +-- client/gov/cli/query.go | 19 ++++++++------- client/gov/cli/sendtx.go | 18 +++++++-------- modules/gov/params/gov_params.go | 33 ++++++++++++--------------- modules/gov/params/gov_params_test.go | 19 +++++++-------- modules/gov/procedures.go | 3 --- modules/iparam/helper_test.go | 4 ++-- modules/iparam/parameter.go | 5 ++-- types/parameter.go | 5 ---- 9 files changed, 47 insertions(+), 62 deletions(-) delete mode 100644 modules/gov/procedures.go delete mode 100644 types/parameter.go diff --git a/client/gov/cli/flags.go b/client/gov/cli/flags.go index 06f5df6bf..22caedfed 100644 --- a/client/gov/cli/flags.go +++ b/client/gov/cli/flags.go @@ -13,5 +13,4 @@ const ( flagLatestProposalIDs = "latest" flagParam = "param" flagOp = "op" - ) - +) diff --git a/client/gov/cli/query.go b/client/gov/cli/query.go index 9ec791df9..55c448df3 100644 --- a/client/gov/cli/query.go +++ b/client/gov/cli/query.go @@ -269,10 +269,10 @@ func GetCmdQueryGovConfig(storeName string, cdc *wire.Codec) *cobra.Command { if moduleStr != "" { res, err := ctx.QuerySubspace([]byte("Gov/"+moduleStr), storeName) - if err == nil{ + if err == nil { - if len(res) == 0 { - return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidModule, fmt.Sprintf("The GovParameter of the module %s is not existed", moduleStr)) + if len(res) == 0 { + return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidModule, fmt.Sprintf("The GovParameter of the module %s is not existed", moduleStr)) } var keys []string @@ -302,12 +302,12 @@ func GetCmdQueryGovConfig(storeName string, cdc *wire.Codec) *cobra.Command { if p, ok := iparam.ParamMapping[keyStr]; ok { if len(res) == 0 { - return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidKey, fmt.Sprintf(keyStr+" is not existed")) + return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidKey, fmt.Sprintf(keyStr+" is not existed")) } p.GetValueFromRawData(cdc, res) PrintParamStr(p, keyStr) - return nil + return nil } else { return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidKey, fmt.Sprintf(keyStr+" is not found")) @@ -317,7 +317,6 @@ func GetCmdQueryGovConfig(storeName string, cdc *wire.Codec) *cobra.Command { } } - return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidQueryParams, fmt.Sprintf("--module and --key can't both be empty")) }, } @@ -389,6 +388,11 @@ func (pd *ParameterConfigFile) GetParamFromKey(keyStr string, opStr string) (gov var param gov.Param var err error var jsonBytes []byte + + if len(keyStr) == 0 { + return param, sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidKey, fmt.Sprintf("Key can't be empty!")) + } + switch keyStr { case "Gov/gov/DepositProcedure": jsonBytes, err = json.Marshal(pd.Govparams.DepositProcedure) @@ -397,7 +401,7 @@ func (pd *ParameterConfigFile) GetParamFromKey(keyStr string, opStr string) (gov case "Gov/gov/TallyingProcedure": jsonBytes, err = json.Marshal(pd.Govparams.TallyingProcedure) default: - return param, sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidTallyingProcedure, fmt.Sprintf(keyStr+" is not found")) + return param, sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidKey, fmt.Sprintf(keyStr+" is not found")) } if err != nil { @@ -409,7 +413,6 @@ func (pd *ParameterConfigFile) GetParamFromKey(keyStr string, opStr string) (gov jsonBytes, _ = json.MarshalIndent(param, "", " ") - fmt.Println("Param:\n", string(jsonBytes)) return param, err } diff --git a/client/gov/cli/sendtx.go b/client/gov/cli/sendtx.go index 95e7e8810..6de151511 100644 --- a/client/gov/cli/sendtx.go +++ b/client/gov/cli/sendtx.go @@ -11,9 +11,9 @@ import ( "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/utils" "github.com/irisnet/irishub/modules/gov" + "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/pkg/errors" ) // GetCmdSubmitProposal implements submitting a proposal transaction command. @@ -53,12 +53,12 @@ func GetCmdSubmitProposal(cdc *wire.Codec) *cobra.Command { pathStr := viper.GetString(flagPath) keyStr := viper.GetString(flagKey) opStr := viper.GetString(flagOp) - param, err = GetParamFromString(paramStr, pathStr, keyStr, opStr,cdc) + param, err = GetParamFromString(paramStr, pathStr, keyStr, opStr, cdc) if err != nil { return err } - jsonBytes,_ := json.MarshalIndent(param,""," ") - fmt.Println("Param:\n",string(jsonBytes)) + jsonBytes, _ := json.MarshalIndent(param, "", " ") + fmt.Println("Param:\n", string(jsonBytes)) } msg := gov.NewMsgSubmitProposal(title, description, proposalType, fromAddr, amount, param) @@ -85,24 +85,24 @@ func GetCmdSubmitProposal(cdc *wire.Codec) *cobra.Command { return cmd } -func GetParamFromString(paramStr string, pathStr string, keyStr string, opStr string,cdc *wire.Codec) (gov.Param, error) { +func GetParamFromString(paramStr string, pathStr string, keyStr string, opStr string, cdc *wire.Codec) (gov.Param, error) { var param gov.Param if paramStr != "" { err := json.Unmarshal([]byte(paramStr), ¶m) return param, err - } else if pathStr != ""{ + } else if pathStr != "" { paramDoc := ParameterConfigFile{} - err := paramDoc.ReadFile(cdc,pathStr) + err := paramDoc.ReadFile(cdc, pathStr) if err != nil { return param, err } - param,err := paramDoc.GetParamFromKey(keyStr,opStr) + param, err := paramDoc.GetParamFromKey(keyStr, opStr) return param, err } else { - return param,errors.New("Path and param are both empty") + return param, errors.New("Path and param are both empty") } } diff --git a/modules/gov/params/gov_params.go b/modules/gov/params/gov_params.go index f86f108c2..62985dd08 100644 --- a/modules/gov/params/gov_params.go +++ b/modules/gov/params/gov_params.go @@ -4,16 +4,15 @@ import ( "encoding/json" "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/irisnet/irishub/types" "github.com/irisnet/irishub/modules/iparam" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/irisnet/irishub/types" "strconv" ) var DepositProcedureParameter DepositProcedureParam - var ( minDeposit, _ = types.NewDefaultCoinType("iris").ConvertToMinCoin(fmt.Sprintf("%d%s", 10, "iris")) ) @@ -24,9 +23,9 @@ const UPPER_BOUND_AMOUNT = 200 var _ iparam.GovParameter = (*DepositProcedureParam)(nil) type ParamSet struct { - DepositProcedure DepositProcedure `json:"Gov/gov/DepositProcedure"` - VotingProcedure VotingProcedure `json:"Gov/gov/VotingProcedure"` - TallyingProcedure TallyingProcedure `json:"Gov/gov/TallyingProcedure"` + DepositProcedure DepositProcedure `json:"Gov/gov/DepositProcedure"` + VotingProcedure VotingProcedure `json:"Gov/gov/VotingProcedure"` + TallyingProcedure TallyingProcedure `json:"Gov/gov/TallyingProcedure"` } // Procedure around Deposits for governance @@ -40,12 +39,12 @@ type DepositProcedureParam struct { psetter params.Setter pgetter params.Getter } -func (param *DepositProcedureParam) GetValueFromRawData(cdc *wire.Codec,res []byte) interface{}{ - cdc.MustUnmarshalBinary(res,¶m.Value) + +func (param *DepositProcedureParam) GetValueFromRawData(cdc *wire.Codec, res []byte) interface{} { + cdc.MustUnmarshalBinary(res, ¶m.Value) return param.Value } - func (param *DepositProcedureParam) InitGenesis(genesisState interface{}) { if value, ok := genesisState.(DepositProcedure); ok { param.Value = value @@ -116,7 +115,6 @@ func (param *DepositProcedureParam) Valid(jsonStr string) sdk.Error { return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidMinDeposit, fmt.Sprintf("Json is not valid")) } - var VotingProcedureParameter VotingProcedureParam var _ iparam.GovParameter = (*VotingProcedureParam)(nil) @@ -130,8 +128,9 @@ type VotingProcedureParam struct { psetter params.Setter pgetter params.Getter } -func (param *VotingProcedureParam) GetValueFromRawData(cdc *wire.Codec,res []byte) interface{}{ - cdc.MustUnmarshalBinary(res,¶m.Value) + +func (param *VotingProcedureParam) GetValueFromRawData(cdc *wire.Codec, res []byte) interface{} { + cdc.MustUnmarshalBinary(res, ¶m.Value) return param.Value } @@ -139,8 +138,7 @@ func (param *VotingProcedureParam) InitGenesis(genesisState interface{}) { if value, ok := genesisState.(VotingProcedure); ok { param.Value = value } else { - param.Value = VotingProcedure{VotingPeriod: 1000, - } + param.Value = VotingProcedure{VotingPeriod: 1000} } } @@ -202,15 +200,14 @@ type TallyingProcedure struct { GovernancePenalty sdk.Rat `json:"governance_penalty"` // Penalty if validator does not vote } - type TallyingProcedureParam struct { Value TallyingProcedure psetter params.Setter pgetter params.Getter } -func (param *TallyingProcedureParam) GetValueFromRawData(cdc *wire.Codec,res []byte) interface{}{ - cdc.MustUnmarshalBinary(res,¶m.Value) +func (param *TallyingProcedureParam) GetValueFromRawData(cdc *wire.Codec, res []byte) interface{} { + cdc.MustUnmarshalBinary(res, ¶m.Value) return param.Value } @@ -279,5 +276,3 @@ func (param *TallyingProcedureParam) Valid(jsonStr string) sdk.Error { } return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidTallyingProcedure, fmt.Sprintf("Json is not valid")) } - - diff --git a/modules/gov/params/gov_params_test.go b/modules/gov/params/gov_params_test.go index 424f95e1b..0f6303364 100644 --- a/modules/gov/params/gov_params_test.go +++ b/modules/gov/params/gov_params_test.go @@ -1,17 +1,17 @@ package govparams import ( + "fmt" "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/params" + "github.com/irisnet/irishub/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" "testing" - "fmt" - "github.com/irisnet/irishub/types" ) func defaultContext(key sdk.StoreKey) sdk.Context { @@ -90,9 +90,8 @@ func TestVotingProcedureParam(t *testing.T) { ctx := defaultContext(skey) paramKeeper := params.NewKeeper(wire.NewCodec(), skey) - p1 := VotingProcedure{ - VotingPeriod:1000, + VotingPeriod: 1000, } p2 := VotingProcedure{ @@ -126,13 +125,11 @@ func TestVotingProcedureParam(t *testing.T) { } - func TestTallyingProcedureParam(t *testing.T) { skey := sdk.NewKVStoreKey("params") ctx := defaultContext(skey) paramKeeper := params.NewKeeper(wire.NewCodec(), skey) - p1 := TallyingProcedure{ Threshold: sdk.NewRat(1, 2), Veto: sdk.NewRat(1, 3), @@ -140,10 +137,10 @@ func TestTallyingProcedureParam(t *testing.T) { } p2 := TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 50), - } + Threshold: sdk.NewRat(1, 2), + Veto: sdk.NewRat(1, 3), + GovernancePenalty: sdk.NewRat(1, 50), + } TallyingProcedureParameter.SetReadWriter(paramKeeper.Setter()) find := TallyingProcedureParameter.LoadValue(ctx) @@ -172,4 +169,4 @@ func TestTallyingProcedureParam(t *testing.T) { TallyingProcedureParameter.LoadValue(ctx) require.Equal(t, p2, TallyingProcedureParameter.Value) -} \ No newline at end of file +} diff --git a/modules/gov/procedures.go b/modules/gov/procedures.go deleted file mode 100644 index 4db47f481..000000000 --- a/modules/gov/procedures.go +++ /dev/null @@ -1,3 +0,0 @@ -package gov - - diff --git a/modules/iparam/helper_test.go b/modules/iparam/helper_test.go index d34c551e9..a56cf98fc 100644 --- a/modules/iparam/helper_test.go +++ b/modules/iparam/helper_test.go @@ -36,7 +36,7 @@ func TestInitGenesisParameter(t *testing.T) { MinDeposit: sdk.Coins{sdk.NewInt64Coin("iris", 20)}, MaxDepositPeriod: 1440} - SetParamReadWriter(paramKeeper.Setter(),&govparams.DepositProcedureParameter,&govparams.DepositProcedureParameter) + SetParamReadWriter(paramKeeper.Setter(), &govparams.DepositProcedureParameter, &govparams.DepositProcedureParameter) InitGenesisParameter(&govparams.DepositProcedureParameter, ctx, nil) @@ -63,7 +63,7 @@ func TestRegisterParamMapping(t *testing.T) { MinDeposit: sdk.Coins{sdk.NewInt64Coin("iris", 30)}, MaxDepositPeriod: 1440} - SetParamReadWriter(paramKeeper.Setter(),&govparams.DepositProcedureParameter, &govparams.DepositProcedureParameter) + SetParamReadWriter(paramKeeper.Setter(), &govparams.DepositProcedureParameter, &govparams.DepositProcedureParameter) RegisterGovParamMapping(&govparams.DepositProcedureParameter) InitGenesisParameter(&govparams.DepositProcedureParameter, ctx, nil) diff --git a/modules/iparam/parameter.go b/modules/iparam/parameter.go index b32cb98ee..c1c90de91 100644 --- a/modules/iparam/parameter.go +++ b/modules/iparam/parameter.go @@ -2,12 +2,11 @@ package iparam import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/x/params" ) type Parameter interface { - InitGenesis(interface{}) GetStoreKey() string @@ -28,7 +27,7 @@ type GovParameter interface { Valid(json string) sdk.Error - GetValueFromRawData(cdc *wire.Codec,res []byte) interface{} + GetValueFromRawData(cdc *wire.Codec, res []byte) interface{} Update(ctx sdk.Context, json string) diff --git a/types/parameter.go b/types/parameter.go deleted file mode 100644 index 32adff2ca..000000000 --- a/types/parameter.go +++ /dev/null @@ -1,5 +0,0 @@ -package types - -type Paramter interface { - String() -}