diff --git a/Dockerfile b/Dockerfile index be034230a..e20408d22 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,9 +28,9 @@ RUN cd $REPO_PATH && \ make build_linux && \ make install && \ make install_examples && \ - make test_cli && \ - make test_lcd && \ - make test_sim + make test_cli +# make test_lcd && \ +# make test_sim FROM alpine:3.7 diff --git a/Gopkg.lock b/Gopkg.lock index 1d4707244..4de10c8e2 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -9,6 +9,14 @@ revision = "5d049714c4a64225c3c79a7cf7d02f7fb5b96338" version = "1.0.0" +[[projects]] + branch = "master" + digest = "1:7736fc6da04620727f8f3aa2ced8d77be8e074a302820937aa5993848c769b27" + name = "github.com/ZondaX/hid-go" + packages = ["."] + pruneopts = "UT" + revision = "48b08affede2cea076a3cf13b2e3f72ed262b743" + [[projects]] branch = "master" digest = "1:4cf11742b199ab3aacf26b00187e72f7ff8ba2145f363b74f295d54f098f79e4" @@ -22,6 +30,7 @@ revision = "5312a61534124124185d41f09206b9fef1d88403" [[projects]] + branch = "master" digest = "1:09a7f74eb6bb3c0f14d8926610c87f569c5cff68e978d30e9a3540aeb626fdf0" name = "github.com/bartekn/go-bip39" packages = ["."] @@ -44,14 +53,6 @@ revision = "4aabc24848ce5fd31929f7d1e4ea74d3709c14cd" version = "v0.1.0" -[[projects]] - branch = "master" - digest = "1:7736fc6da04620727f8f3aa2ced8d77be8e074a302820937aa5993848c769b27" - name = "github.com/brejski/hid" - packages = ["."] - pruneopts = "UT" - revision = "48b08affede2cea076a3cf13b2e3f72ed262b743" - [[projects]] branch = "master" digest = "1:c0decf632843204d2b8781de7b26e7038584e2dcccc7e2f401e88ae85b1df2b7" @@ -68,7 +69,7 @@ revision = "d4cc87b860166d00d6b5b9e0d3b3d71d6088d4d4" [[projects]] - digest = "1:f2f4e260193eb9a9ad307b26bcfcf94e57da65d2ea16b51023268435d3a116cc" + digest = "1:06d4b3860be91d8d0bf1933758dda2ce0b5709506343c0656e033d2b69ffd776" name = "github.com/cosmos/cosmos-sdk" packages = [ "baseapp", @@ -78,53 +79,58 @@ "client/rpc", "client/tx", "client/utils", + "codec", "crypto", "crypto/keys", - "crypto/keys/bcrypt", - "crypto/keys/bip39", "crypto/keys/hd", + "crypto/keys/keyerror", + "crypto/keys/mintkey", "server", "server/config", + "server/mock", "store", "tests", "types", "version", - "wire", "x/auth", "x/auth/client/cli", - "x/auth/client/context", + "x/auth/client/txbuilder", "x/bank", - "x/gov", - "x/gov/tags", + "x/distribution", + "x/distribution/keeper", + "x/distribution/tags", + "x/distribution/types", "x/ibc", - "x/mock", + "x/mint", "x/params", + "x/params/subspace", "x/slashing", "x/stake", "x/stake/client/rest", "x/stake/keeper", + "x/stake/querier", "x/stake/tags", "x/stake/types", ] pruneopts = "UT" - revision = "7c39b51abdd5089636060470e294b2ea1fec7954" + revision = "b352686dab3f9976be1347a860c7aba28c22abe0" source = "https://github.com/irisnet/cosmos-sdk.git" - version = "v0.24.2-irisv0.6" + version = "v0.26.0-iris" [[projects]] - digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec" - name = "github.com/davecgh/go-spew" - packages = ["spew"] + digest = "1:e8a3550c8786316675ff54ad6f09d265d129c9d986919af7f541afba50d87ce2" + name = "github.com/cosmos/go-bip39" + packages = ["."] pruneopts = "UT" - revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73" - version = "v1.1.1" + revision = "52158e4697b87de16ed390e1bdaf813e581008fa" [[projects]] - digest = "1:c7644c73a3d23741fdba8a99b1464e021a224b7e205be497271a8003a15ca41b" - name = "github.com/ebuchman/fail-test" - packages = ["."] + digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39" + name = "github.com/davecgh/go-spew" + packages = ["spew"] pruneopts = "UT" - revision = "95f809107225be108efcf10a3509e4ea6ceef3c4" + revision = "346938d642f2ec3594ed81d874461961cd0faa76" + version = "v1.1.0" [[projects]] digest = "1:50272737989a0ecdc6529d90e0cdf7dd2378220f1f8fce9870b410ad04d064b7" @@ -255,13 +261,12 @@ revision = "d9f6b97f8db22dd1e090fd0bbbe98f09cc7dd0a8" [[projects]] - digest = "1:c0d19ab64b32ce9fe5cf4ddceba78d5bc9807f0016db6b1183599da3dcc24d10" + digest = "1:ea40c24cdbacd054a6ae9de03e62c5f252479b96c716375aace5c120d68647c8" name = "github.com/hashicorp/hcl" packages = [ ".", "hcl/ast", "hcl/parser", - "hcl/printer", "hcl/scanner", "hcl/strconv", "hcl/token", @@ -282,12 +287,12 @@ version = "v1.0" [[projects]] - digest = "1:57485b77bf99ffca8552ef2f3dba12a9c9eaa32e2f1e4b8dbec9c03ee977741a" + digest = "1:0b9cab5474015038cc258d2af017ebaa01f2fb387ca2ab7eb78516f46669954c" name = "github.com/ipfs/go-ipfs-api" packages = ["."] pruneopts = "UT" - revision = "f1ca0efb95f180e287f6e2923749dd2057c448cc" - version = "v1.3.1" + revision = "c26fc48ff114bc48b2cc357f8d12484397f5738d" + version = "v1.3.5" [[projects]] digest = "1:960df862bef266ca070f8ed90aeb274edc89e9fd8fa2e12472e59845c77a4dab" @@ -313,6 +318,14 @@ pruneopts = "UT" revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0" +[[projects]] + digest = "1:19f2d2506cc0f9a233c9c0753e8c3fd5afa88afb43ff7b795cbba3629d0e96b5" + name = "github.com/libp2p/go-flow-metrics" + packages = ["."] + pruneopts = "UT" + revision = "cc546389dcf06b4bcbf6b8594069588e5c8a1451" + version = "v0.2.0" + [[projects]] digest = "1:4ff86c6d6dd8df23a58e6b6060fea5f150d1a502cdfe8a3e9efd5d25339196c6" name = "github.com/libp2p/go-libp2p-crypto" @@ -324,6 +337,14 @@ revision = "274de1bb6c27780863df6b230c91324ab481dab2" version = "v2.0.1" +[[projects]] + digest = "1:e01814b1390e3abc93ca170141d457fab1dcc0c532cdfdd269be58fb2cd6a9f4" + name = "github.com/libp2p/go-libp2p-metrics" + packages = ["."] + pruneopts = "UT" + revision = "20c0e3fed14ddf84ac8192038accfd393610ed82" + version = "v2.1.7" + [[projects]] digest = "1:d59d3f32a53e3d1ef4f19f92c8f4cbccabfae6c965760577958b2fb937fede98" name = "github.com/libp2p/go-libp2p-peer" @@ -333,12 +354,20 @@ version = "v2.4.0" [[projects]] - digest = "1:eca3b2ce3d7669b23248e1c41b9982f2dbd5265a8a224f6cc5935b3ed0d06eaa" + digest = "1:99c29233479cb14a63c7cb6b49927a60ae9d6b4b36d74deb12cc45ce503ddeb5" + name = "github.com/libp2p/go-libp2p-protocol" + packages = ["."] + pruneopts = "UT" + revision = "e34f0d7468b3519bf9bf4e43c1d028ce651eab51" + version = "v1.0.0" + +[[projects]] + digest = "1:0c84c529a410cea768ebeaf3ea70632f2d8df41662003204045ff1a32cd79cda" name = "github.com/libp2p/go-libp2p-pubsub" packages = ["pb"] pruneopts = "UT" - revision = "4986a90e6d122bf9207561efeea9d8afdf193629" - version = "v0.9.36" + revision = "3d408775deaf28da57cc356d37f2b8bf9c57db64" + version = "v0.10.2" [[projects]] digest = "1:c568d7727aa262c32bdf8a3f7db83614f7af0ed661474b24588de635c20024c7" @@ -511,7 +540,7 @@ revision = "e2704e165165ec55d062f5919b4b29494e9fa790" [[projects]] - digest = "1:22e4289b3741da96aceecc4d1dcbf682ae167c759d010fd88c63c65c9a2e8c72" + digest = "1:3fb45284d554f369d08136a0fd4d01f50897f6f79469358c41fb5a30a6379dfe" name = "github.com/shirou/gopsutil" packages = [ "cpu", @@ -523,8 +552,8 @@ "process", ] pruneopts = "UT" - revision = "8048a2e9c5773235122027dd585cf821b2af1249" - version = "v2.18.07" + revision = "3ec50d2876a36047b2ca39f955ba88fb7a455e92" + version = "v2.18.10" [[projects]] branch = "master" @@ -554,12 +583,12 @@ version = "v1.1.2" [[projects]] - digest = "1:516e71bed754268937f57d4ecb190e01958452336fa73dbac880894164e91c1f" + digest = "1:08d65904057412fc0270fc4812a1c90c594186819243160dc779a402d4b6d0bc" name = "github.com/spf13/cast" packages = ["."] pruneopts = "UT" - revision = "8965335b8c7107321228e3e3702cab9832751bac" - version = "v1.2.0" + revision = "8c9545af88b134710ab1cd196795e7f2388358d7" + version = "v1.3.0" [[projects]] digest = "1:7ffc0983035bc7e297da3688d9fe19d60a420e9c38bef23f845c53788ed6a05e" @@ -605,8 +634,7 @@ version = "v1.2.1" [[projects]] - branch = "master" - digest = "1:59483b8e8183f10ab21a85ba1f4cbb4a2335d48891801f79ed7b9499f44d383c" + digest = "1:b3cfb8d82b1601a846417c3f31c03a7961862cb2c98dcf0959c473843e6d9a2b" name = "github.com/syndtr/goleveldb" packages = [ "leveldb", @@ -623,39 +651,33 @@ "leveldb/util", ] pruneopts = "UT" - revision = "6b91fda63f2e36186f1c9d0e48578defb69c5d43" + revision = "c4c61651e9e37fa117f53c5a906d3b63090d8445" [[projects]] - branch = "master" - digest = "1:087aaa7920e5d0bf79586feb57ce01c35c830396ab4392798112e8aae8c47722" - name = "github.com/tendermint/ed25519" - packages = [ - ".", - "edwards25519", - "extra25519", - ] + digest = "1:605b6546f3f43745695298ec2d342d3e952b6d91cdf9f349bea9315f677d759f" + name = "github.com/tendermint/btcd" + packages = ["btcec"] pruneopts = "UT" - revision = "d8387025d2b9d158cf4efb07e7ebf814bcce2057" + revision = "e5840949ff4fff0c56f9b6a541e22b63581ea9df" [[projects]] - digest = "1:e0a2a4be1e20c305badc2b0a7a9ab7fef6da500763bec23ab81df3b5f9eec9ee" + digest = "1:10b3a599325740c84a7c81f3f3cb2e1fdb70b3ea01b7fa28495567a2519df431" name = "github.com/tendermint/go-amino" packages = ["."] pruneopts = "UT" - revision = "a8328986c1608950fa5d3d1c0472cccc4f8fc02c" - version = "v0.12.0-rc0" + revision = "6dcc6ddc143e116455c94b25c1004c99e0d0ca12" + version = "v0.14.0" [[projects]] - digest = "1:f6e293333e941a78f8029927165d1926c5efdedd8612a3108977b30b8a871b87" + digest = "1:9f8c4c93658315a795ffd3e0c943d39f78067dd8382b8d7bcfaf6686b92f3978" name = "github.com/tendermint/iavl" packages = ["."] pruneopts = "UT" - revision = "f93c0a13ec78edd04c6faef6b3158f72e66f699f" - source = "https://github.com/irisnet/iavl.git" - version = "v0.9.2-iris1" + revision = "fa74114f764f9827c4ad5573f990ed25bf8c4bac" + version = "v0.11.1" [[projects]] - digest = "1:e787411e638d991be9b98018f4f31854fb33e28d8e3e4a5b1e6fbeed39f51bb4" + digest = "1:83882681ddd65a2de8c1be7eae0f48075601077d85cc37050f343d00ab862bac" name = "github.com/tendermint/tendermint" packages = [ "abci/client", @@ -673,6 +695,8 @@ "crypto/ed25519", "crypto/encoding/amino", "crypto/merkle", + "crypto/multisig", + "crypto/multisig/bitarray", "crypto/secp256k1", "crypto/tmhash", "crypto/xsalsa20symmetric", @@ -684,7 +708,9 @@ "libs/clist", "libs/common", "libs/db", + "libs/errors", "libs/events", + "libs/fail", "libs/flowrate", "libs/log", "libs/pubsub", @@ -692,7 +718,6 @@ "lite", "lite/client", "lite/errors", - "lite/files", "lite/proxy", "mempool", "node", @@ -706,7 +731,6 @@ "rpc/core", "rpc/core/types", "rpc/grpc", - "rpc/lib", "rpc/lib/client", "rpc/lib/server", "rpc/lib/types", @@ -715,12 +739,13 @@ "state/txindex/kv", "state/txindex/null", "types", + "types/time", "version", ] pruneopts = "UT" - revision = "46b52ca74937f3a680a4861f7b60b262d3fda777" + revision = "650b6ddd80d00b193b3ba47a87800e72f12dd619" source = "https://github.com/irisnet/tendermint.git" - version = "0.23.1-rc0-iris1" + version = "v0.26.1-rc0-iris" [[projects]] digest = "1:bf6d9a827ea3cad964c2f863302e4f6823170d0b5ed16f72cf1184a7c615067e" @@ -739,21 +764,24 @@ revision = "8c6c8ba81d5c71fd69c0f48dbde4b2fb422b6dfc" [[projects]] - digest = "1:4dcb0dd65feecb068ce23a234d1a07c7868a1e39f52a6defcae0bb371d03abf6" + digest = "1:7886f86064faff6f8d08a3eb0e8c773648ff5a2e27730831e2bfbf07467f6666" name = "github.com/zondax/ledger-goclient" packages = ["."] pruneopts = "UT" - revision = "4296ee5701e945f9b3a7dbe51f402e0b9be57259" + revision = "58598458c11bc0ad1c1b8dac3dc3e11eaf270b79" + version = "v0.1.0" [[projects]] - branch = "master" - digest = "1:08ee0e71139155154f1bf134ac603cb13421e80176a7248b66f47f6fa3ce211b" + digest = "1:466100a50f42240378e484936fc7273b41ba7d9da1eec61c4b31156a7b118dd1" name = "golang.org/x/crypto" packages = [ + "bcrypt", "blake2s", "blowfish", "chacha20poly1305", "curve25519", + "ed25519", + "ed25519/internal/edwards25519", "hkdf", "internal/chacha20", "internal/subtle", @@ -768,7 +796,8 @@ "sha3", ] pruneopts = "UT" - revision = "0c41d7ab0a0ee717d4590a44bcb987dfd9e183eb" + revision = "3764759f34a542a3aef74d6b02e35be7ab893bba" + source = "https://github.com/tendermint/crypto" [[projects]] digest = "1:d36f55a999540d29b6ea3c2ea29d71c76b1d9853fdcd3e5c5cb4836f2ba118f1" @@ -788,7 +817,7 @@ [[projects]] branch = "master" - digest = "1:317d73d5f30aa478da851362c17dbed491e43f599f07d99eeb06323fa51e1e4f" + digest = "1:7e2cb6c95ac3f1ff730a61ec4ce423a1857c7c6c28abafd8fabae25d80ccb667" name = "golang.org/x/sys" packages = [ "cpu", @@ -796,7 +825,7 @@ "windows", ] pruneopts = "UT" - revision = "44b849a8bc13eb42e95e6c6c5e360481b73ec710" + revision = "9b800f95dbbc54abff0acf7ee32d88ba4e328c89" [[projects]] digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" @@ -822,12 +851,11 @@ version = "v0.3.0" [[projects]] - branch = "master" - digest = "1:56b0bca90b7e5d1facf5fbdacba23e4e0ce069d25381b8e2f70ef1e7ebfb9c1a" + digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c" name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] pruneopts = "UT" - revision = "94acd270e44e65579b9ee3cdab25034d33fed608" + revision = "383e8b2c3b9e36c4076b235b32537292176bae20" [[projects]] digest = "1:2dab32a43451e320e49608ff4542fdfc653c95dcc35d0065ec9c6c3dd540ed74" @@ -875,32 +903,36 @@ analyzer-name = "dep" analyzer-version = 1 input-imports = [ + "github.com/bartekn/go-bip39", "github.com/bgentry/speakeasy", + "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/codec", "github.com/cosmos/cosmos-sdk/crypto", "github.com/cosmos/cosmos-sdk/crypto/keys", + "github.com/cosmos/cosmos-sdk/crypto/keys/hd", + "github.com/cosmos/cosmos-sdk/crypto/keys/keyerror", "github.com/cosmos/cosmos-sdk/server", - "github.com/cosmos/cosmos-sdk/server/config", + "github.com/cosmos/cosmos-sdk/server/mock", "github.com/cosmos/cosmos-sdk/store", "github.com/cosmos/cosmos-sdk/tests", "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/context", + "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder", "github.com/cosmos/cosmos-sdk/x/bank", - "github.com/cosmos/cosmos-sdk/x/gov", + "github.com/cosmos/cosmos-sdk/x/distribution", + "github.com/cosmos/cosmos-sdk/x/distribution/types", "github.com/cosmos/cosmos-sdk/x/ibc", - "github.com/cosmos/cosmos-sdk/x/mock", + "github.com/cosmos/cosmos-sdk/x/mint", "github.com/cosmos/cosmos-sdk/x/params", "github.com/cosmos/cosmos-sdk/x/slashing", "github.com/cosmos/cosmos-sdk/x/stake", "github.com/cosmos/cosmos-sdk/x/stake/client/rest", + "github.com/cosmos/cosmos-sdk/x/stake/keeper", "github.com/cosmos/cosmos-sdk/x/stake/tags", "github.com/cosmos/cosmos-sdk/x/stake/types", "github.com/emicklei/proto", @@ -909,6 +941,7 @@ "github.com/gorilla/mux", "github.com/ipfs/go-ipfs-api", "github.com/mattn/go-isatty", + "github.com/mitchellh/go-homedir", "github.com/pelletier/go-toml", "github.com/pkg/errors", "github.com/prometheus/client_golang/prometheus", @@ -923,14 +956,18 @@ "github.com/spf13/viper", "github.com/stretchr/testify/assert", "github.com/stretchr/testify/require", + "github.com/syndtr/goleveldb/leveldb/opt", "github.com/tendermint/go-amino", "github.com/tendermint/tendermint/abci/server", "github.com/tendermint/tendermint/abci/types", "github.com/tendermint/tendermint/blockchain", + "github.com/tendermint/tendermint/cmd/tendermint/commands", "github.com/tendermint/tendermint/config", "github.com/tendermint/tendermint/consensus", "github.com/tendermint/tendermint/crypto", "github.com/tendermint/tendermint/crypto/ed25519", + "github.com/tendermint/tendermint/crypto/merkle", + "github.com/tendermint/tendermint/crypto/multisig", "github.com/tendermint/tendermint/crypto/secp256k1", "github.com/tendermint/tendermint/crypto/tmhash", "github.com/tendermint/tendermint/libs/cli", @@ -950,6 +987,7 @@ "github.com/tendermint/tendermint/rpc/lib/server", "github.com/tendermint/tendermint/state", "github.com/tendermint/tendermint/types", + "github.com/tendermint/tendermint/types/time", "github.com/tendermint/tmlibs/cli", ] solver-name = "gps-cdcl" diff --git a/Gopkg.toml b/Gopkg.toml index 670aeaec1..784f727db 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -29,12 +29,37 @@ [[constraint]] name = "github.com/cosmos/cosmos-sdk" source = "https://github.com/irisnet/cosmos-sdk.git" - version = "=v0.24.2-irisv0.6" + version = "=v0.26.0-iris" + +[[override]] + name = "github.com/tendermint/iavl" + version = "=v0.11.1" + +[[override]] + name = "github.com/tendermint/tendermint" + source = "https://github.com/irisnet/tendermint.git" + version = "=v0.26.1-rc0-iris" + +[[constraint]] + name = "github.com/prometheus/client_golang" + revision = "ae27198cdd90bf12cd134ad79d1366a6cf49f632" + +[[constraint]] + name = "github.com/emicklei/proto" + version = "=v1.6.5" + +[[constraint]] + name = "github.com/bgentry/speakeasy" + version = "~0.1.0" [[override]] name = "github.com/golang/protobuf" version = "=1.1.0" +[[constraint]] + name = "github.com/mattn/go-isatty" + version = "~0.0.3" + [[constraint]] name = "github.com/spf13/cobra" version = "~0.0.1" @@ -43,39 +68,58 @@ name = "github.com/spf13/viper" version = "~1.0.0" +[[constraint]] + name = "github.com/pkg/errors" + version = "=0.8.0" + +[[constraint]] + name = "github.com/stretchr/testify" + version = "=1.2.1" + [[override]] name = "github.com/tendermint/go-amino" - version = "=v0.12.0-rc0" + version = "=v0.14.0" + + +## deps without releases: [[override]] - name = "github.com/tendermint/iavl" - source = "https://github.com/irisnet/iavl.git" - version = "=v0.9.2-iris1" + name = "golang.org/x/crypto" + source = "https://github.com/tendermint/crypto" + revision = "3764759f34a542a3aef74d6b02e35be7ab893bba" + +[[constraint]] + name = "github.com/cosmos/go-bip39" + revision = "52158e4697b87de16ed390e1bdaf813e581008fa" + +[[constraint]] + name = "github.com/zondax/ledger-goclient" + version = "=v0.1.0" + +## transitive deps, with releases: [[override]] - name = "github.com/tendermint/tendermint" - source = "https://github.com/irisnet/tendermint.git" - version = "=v0.23.1-rc0-iris1" + name = "github.com/davecgh/go-spew" + version = "=v1.1.0" [[constraint]] name = "github.com/rakyll/statik" version = "=v0.1.4" [[constraint]] - name = "github.com/emicklei/proto" - version = "=v1.6.5" + name = "github.com/mitchellh/go-homedir" + version = "1.0.0" -[[constraint]] - name = "github.com/ipfs/go-ipfs-api" - version = "=v1.3.1" +## transitive deps, without releases: +# [[override]] - name = "github.com/libp2p/go-libp2p-pubsub" - version = "=v0.9.36" + name = "github.com/syndtr/goleveldb" + revision = "c4c61651e9e37fa117f53c5a906d3b63090d8445" -[[constraint]] - name = "github.com/prometheus/client_golang" - revision = "ae27198cdd90bf12cd134ad79d1366a6cf49f632" +[[override]] + name = "google.golang.org/genproto" + revision = "383e8b2c3b9e36c4076b235b32537292176bae20" [prune] go-tests = true diff --git a/Makefile b/Makefile index 9364be3af..a2d45cacb 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,8 @@ PACKAGES_NOSIMULATION=$(shell go list ./... | grep -v '/simulation' | grep -v '/prometheus' | grep -v '/clitest' | grep -v '/lcd' | grep -v '/protobuf') +PACKAGES_MODULES=$(shell go list ./... | grep 'modules') PACKAGES_SIMTEST=$(shell go list ./... | grep '/simulation') -all: get_vendor_deps install +all: get_tools get_vendor_deps install COMMIT_HASH := $(shell git rev-parse --short HEAD) BUILD_FLAGS = -ldflags "-X github.com/irisnet/irishub/version.GitCommit=${COMMIT_HASH}" @@ -40,7 +41,7 @@ draw_deps: ######################################## ### Generate swagger docs for irislcd update_irislcd_swagger_docs: - @statik -src=client/lcd/swaggerui -dest=client/lcd + @statik -src=client/lcd/swaggerui -dest=client/lcd -f ######################################## ### Compile and Install @@ -89,13 +90,18 @@ build_example_linux: update_irislcd_swagger_docs ### Testing test: test_unit test_cli test_lcd test_sim -test_sim: test_sim_modules test_sim_iris_nondeterminism test_sim_iris_fast + +test_sim: test_sim_modules test_sim_benchmark test_sim_iris_nondeterminism test_sim_iris_fast test_unit: - @go test $(PACKAGES_NOSIMULATION) + #@go test $(PACKAGES_NOSIMULATION) + @go test $(PACKAGES_MODULES) test_cli: - @go test -timeout 20m -count 1 -p 1 `go list github.com/irisnet/irishub/client/clitest` -tags=cli_test + @go test -timeout 20m -count 1 -p 1 client/clitest/utils.go client/clitest/bank_test.go client/clitest/distribution_test.go client/clitest/gov_test.go client/clitest/iparam_test.go client/clitest/irismon_test.go client/clitest/record_test.go client/clitest/service_test.go client/clitest/stake_test.go + +test_upgrade_cli: + @go test -timeout 20m -count 1 -p 1 client/clitest/utils.go client/clitest/bank_test.go test_lcd: @go test `go list github.com/irisnet/irishub/client/lcd` @@ -104,14 +110,49 @@ test_sim_modules: @echo "Running individual module simulations..." @go test $(PACKAGES_SIMTEST) +test_sim_benchmark: + @echo "Running benchmark test..." + @go test ./app -run=none -bench=BenchmarkFullIrisSimulation -v -SimulationCommit=true -SimulationNumBlocks=100 -timeout 24h + test_sim_iris_nondeterminism: @echo "Running nondeterminism test..." - @go test ./app -run TestAppStateDeterminism -SimulationEnabled=true -v -timeout 10m + @go test ./app -run TestAppStateDeterminism -v -SimulationEnabled=true -timeout 10m test_sim_iris_fast: @echo "Running quick Iris simulation. This may take several minutes..." - @go test ./app -run TestFullIrisSimulation -SimulationEnabled=true -SimulationNumBlocks=100 -timeout 24h + @go test ./app -run TestFullIrisSimulation -v -SimulationEnabled=true -SimulationNumBlocks=100 -timeout 24h test_sim_iris_slow: @echo "Running full Iris simulation. This may take awhile!" - @go test ./app -run TestFullIrisSimulation -SimulationEnabled=true -SimulationNumBlocks=1000 -SimulationVerbose=true -v -timeout 24h + @go test ./app -run TestFullIrisSimulation -v -SimulationEnabled=true -SimulationNumBlocks=1000 -SimulationVerbose=true -timeout 24h + +testnet_init: + @if ! [ -f build/iris ]; then $(MAKE) build_linux ; fi + @if ! [ -f build/nodecluster/node0/iris/config/genesis.json ]; then docker run --rm -v $(CURDIR)/build:/home ubuntu:16.04 /home/iris testnet --v 4 --output-dir /home/nodecluster --chain-id irishub-test --starting-ip-address 192.168.10.2 ; fi + @echo "To install jq command, please refer to this page: https://stedolan.github.io/jq/download/" + @jq '.app_state.accounts+= [{"address": "faa1ljemm0yznz58qxxs8xyak7fashcfxf5lssn6jm", "coins": [{ "denom":"iris-atto","amount": "1000000000000000000000000"}], "sequence_number": "0", "account_number": "0"}]' build/nodecluster/node0/iris/config/genesis.json > build/genesis_temp.json + @jq '.app_state.stake.pool.loose_tokens="1000600000000000000000000.0000000000"' build/genesis_temp.json > build/genesis_temp1.json + @sudo cp build/genesis_temp1.json build/nodecluster/node0/iris/config/genesis.json + @sudo cp build/genesis_temp1.json build/nodecluster/node1/iris/config/genesis.json + @sudo cp build/genesis_temp1.json build/nodecluster/node2/iris/config/genesis.json + @sudo cp build/genesis_temp1.json build/nodecluster/node3/iris/config/genesis.json + @rm build/genesis_temp.json build/genesis_temp1.json + @echo "Faucet address: faa1ljemm0yznz58qxxs8xyak7fashcfxf5lssn6jm" + @echo "Faucet coin amount: 1000000iris" + @echo "Faucet key seed: tube lonely pause spring gym veteran know want grid tired taxi such same mesh charge orient bracket ozone concert once good quick dry boss" + +testnet_start: + docker-compose up -d + +testnet_stop: + docker-compose down + +testnet_clean: + docker-compose down + sudo rm -rf build/* + +testnet_unsafe_reset: + @docker run --rm -v $(CURDIR)/build:/home ubuntu:16.04 /home/iris unsafe-reset-all --home=/home/nodecluster/node0/iris + @docker run --rm -v $(CURDIR)/build:/home ubuntu:16.04 /home/iris unsafe-reset-all --home=/home/nodecluster/node1/iris + @docker run --rm -v $(CURDIR)/build:/home ubuntu:16.04 /home/iris unsafe-reset-all --home=/home/nodecluster/node2/iris + @docker run --rm -v $(CURDIR)/build:/home ubuntu:16.04 /home/iris unsafe-reset-all --home=/home/nodecluster/node3/iris \ No newline at end of file diff --git a/app/app.go b/app/app.go index 78c278ea5..dc010b699 100644 --- a/app/app.go +++ b/app/app.go @@ -2,38 +2,36 @@ package app import ( "encoding/json" - "errors" "fmt" - "github.com/cosmos/cosmos-sdk/server" + "io" + "os" + "sort" + "strings" + + "github.com/cosmos/cosmos-sdk/codec" 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" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/stake" bam "github.com/irisnet/irishub/baseapp" + "github.com/irisnet/irishub/iparam" "github.com/irisnet/irishub/modules/gov" "github.com/irisnet/irishub/modules/gov/params" - "github.com/irisnet/irishub/modules/iparam" "github.com/irisnet/irishub/modules/record" + "github.com/irisnet/irishub/modules/service" + "github.com/irisnet/irishub/modules/service/params" "github.com/irisnet/irishub/modules/upgrade" "github.com/irisnet/irishub/modules/upgrade/params" - "github.com/irisnet/irishub/modules/iservice" "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" tmtypes "github.com/tendermint/tendermint/types" - "io" - "os" - "strings" ) const ( @@ -51,32 +49,37 @@ var ( // Extended ABCI application type IrisApp struct { *bam.BaseApp - cdc *wire.Codec + cdc *codec.Codec // keys to access the substores keyMain *sdk.KVStoreKey keyAccount *sdk.KVStoreKey - keyIBC *sdk.KVStoreKey keyStake *sdk.KVStoreKey + tkeyStake *sdk.TransientStoreKey keySlashing *sdk.KVStoreKey + keyMint *sdk.KVStoreKey + keyDistr *sdk.KVStoreKey + tkeyDistr *sdk.TransientStoreKey keyGov *sdk.KVStoreKey keyFeeCollection *sdk.KVStoreKey keyParams *sdk.KVStoreKey + tkeyParams *sdk.TransientStoreKey keyUpgrade *sdk.KVStoreKey - keyIservice *sdk.KVStoreKey + keyService *sdk.KVStoreKey keyRecord *sdk.KVStoreKey // Manage getting and setting accounts - accountMapper auth.AccountMapper + accountMapper auth.AccountKeeper feeCollectionKeeper auth.FeeCollectionKeeper - coinKeeper bank.Keeper - ibcMapper ibc.Mapper + bankKeeper bank.Keeper stakeKeeper stake.Keeper slashingKeeper slashing.Keeper - paramsKeeper params.Keeper + mintKeeper mint.Keeper + distrKeeper distr.Keeper govKeeper gov.Keeper + paramsKeeper params.Keeper upgradeKeeper upgrade.Keeper - iserviceKeeper iservice.Keeper + serviceKeeper service.Keeper recordKeeper record.Keeper // fee manager @@ -86,7 +89,7 @@ type IrisApp struct { 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 := bam.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...) bApp.SetCommitMultiStoreTracer(traceStore) // create your application object @@ -95,62 +98,125 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio cdc: cdc, keyMain: sdk.NewKVStoreKey("main"), keyAccount: sdk.NewKVStoreKey("acc"), - keyIBC: sdk.NewKVStoreKey("ibc"), keyStake: sdk.NewKVStoreKey("stake"), + tkeyStake: sdk.NewTransientStoreKey("transient_stake"), + keyMint: sdk.NewKVStoreKey("mint"), + keyDistr: sdk.NewKVStoreKey("distr"), + tkeyDistr: sdk.NewTransientStoreKey("transient_distr"), keySlashing: sdk.NewKVStoreKey("slashing"), keyGov: sdk.NewKVStoreKey("gov"), keyRecord: sdk.NewKVStoreKey("record"), keyFeeCollection: sdk.NewKVStoreKey("fee"), keyParams: sdk.NewKVStoreKey("params"), + tkeyParams: sdk.NewTransientStoreKey("transient_params"), keyUpgrade: sdk.NewKVStoreKey("upgrade"), - keyIservice: sdk.NewKVStoreKey("iservice"), + keyService: sdk.NewKVStoreKey("service"), } var lastHeight int64 if viper.GetBool(FlagReplay) { - lastHeight = app.replay() + lastHeight = bam.Replay(app.Logger) } - // define the accountMapper - app.accountMapper = auth.NewAccountMapper( + // define the AccountKeeper + app.accountMapper = auth.NewAccountKeeper( app.cdc, app.keyAccount, // target store auth.ProtoBaseAccount, // prototype ) // add handlers - app.paramsKeeper = params.NewKeeper(cdc, app.keyParams) - app.coinKeeper = bank.NewKeeper(app.accountMapper) - app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace)) - app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) - app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.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.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - app.recordKeeper = record.NewKeeper(app.cdc, app.keyRecord, app.RegisterCodespace(record.DefaultCodespace)) - app.iserviceKeeper = iservice.NewKeeper(app.cdc, app.keyIservice, app.RegisterCodespace(iservice.DefaultCodespace)) + app.bankKeeper = bank.NewBaseKeeper(app.accountMapper) + app.feeCollectionKeeper = auth.NewFeeCollectionKeeper( + app.cdc, + app.keyFeeCollection, + ) + app.paramsKeeper = params.NewKeeper( + app.cdc, + app.keyParams, app.tkeyParams, + ) + stakeKeeper := stake.NewKeeper( + app.cdc, + app.keyStake, app.tkeyStake, + app.bankKeeper, app.paramsKeeper.Subspace(stake.DefaultParamspace), + app.RegisterCodespace(stake.DefaultCodespace), + ) + app.mintKeeper = mint.NewKeeper(app.cdc, app.keyMint, + app.paramsKeeper.Subspace(mint.DefaultParamspace), + &stakeKeeper, app.feeCollectionKeeper, + ) + app.distrKeeper = distr.NewKeeper( + app.cdc, + app.keyDistr, + app.paramsKeeper.Subspace(distr.DefaultParamspace), + app.bankKeeper, &stakeKeeper, app.feeCollectionKeeper, + app.RegisterCodespace(stake.DefaultCodespace), + ) + app.slashingKeeper = slashing.NewKeeper( + app.cdc, + app.keySlashing, + &stakeKeeper, app.paramsKeeper.Subspace(slashing.DefaultParamspace), + app.RegisterCodespace(slashing.DefaultCodespace), + ) + + app.govKeeper = gov.NewKeeper( + app.cdc, + app.keyGov, + app.bankKeeper, &stakeKeeper, + app.RegisterCodespace(gov.DefaultCodespace), + ) + + app.recordKeeper = record.NewKeeper( + app.cdc, + app.keyRecord, + app.RegisterCodespace(record.DefaultCodespace), + ) + app.serviceKeeper = service.NewKeeper( + app.cdc, + app.keyService, + app.bankKeeper, + app.RegisterCodespace(service.DefaultCodespace), + ) + + // register the staking hooks + // NOTE: stakeKeeper above are passed by reference, + // so that it can be modified like below: + app.stakeKeeper = *stakeKeeper.SetHooks( + NewHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks())) + + app.upgradeKeeper = upgrade.NewKeeper( + app.cdc, + app.keyUpgrade, app.stakeKeeper, + ) // 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("stake", []*sdk.KVStoreKey{app.keyStake, app.keyAccount}, stake.NewHandler(app.stakeKeeper)). + AddRoute("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.bankKeeper)). + AddRoute("stake", []*sdk.KVStoreKey{app.keyStake, app.keyAccount, app.keyMint, app.keyDistr}, stake.NewHandler(app.stakeKeeper)). AddRoute("slashing", []*sdk.KVStoreKey{app.keySlashing, app.keyStake}, slashing.NewHandler(app.slashingKeeper)). + AddRoute("distr", []*sdk.KVStoreKey{app.keyDistr}, distr.NewHandler(app.distrKeeper)). 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("record", []*sdk.KVStoreKey{app.keyRecord}, record.NewHandler(app.recordKeeper)). - AddRoute("iservice", []*sdk.KVStoreKey{app.keyIservice}, iservice.NewHandler(app.iserviceKeeper)) + AddRoute("service", []*sdk.KVStoreKey{app.keyService}, service.NewHandler(app.serviceKeeper)) + + app.QueryRouter(). + AddRoute("gov", gov.NewQuerier(app.govKeeper)). + AddRoute("stake", stake.NewQuerier(app.stakeKeeper, app.cdc)) + + app.feeManager = bam.NewFeeManager(app.paramsKeeper.Subspace("Fee")) - app.feeManager = bam.NewFeeManager(app.paramsKeeper.Setter()) // initialize BaseApp + app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyStake, app.keySlashing, app.keyGov, app.keyMint, app.keyDistr, + app.keyFeeCollection, app.keyParams, app.keyUpgrade, app.keyRecord, app.keyService) app.SetInitChainer(app.initChainer) app.SetBeginBlocker(app.BeginBlocker) - app.SetEndBlocker(app.EndBlocker) app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) + app.MountStoresTransient(app.tkeyParams, app.tkeyStake, app.tkeyDistr) 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.keyRecord, app.keyIservice) + app.SetEndBlocker(app.EndBlocker) app.SetRunMsg(app.runMsgs) var err error @@ -166,15 +232,32 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio upgrade.RegisterModuleList(app.Router()) app.upgradeKeeper.RefreshVersionList(app.GetKVStore(app.keyUpgrade)) - iparam.SetParamReadWriter(app.paramsKeeper.Setter(), - &govparams.DepositProcedureParameter, - &govparams.VotingProcedureParameter, - &govparams.TallyingProcedureParameter, + iparam.SetParamReadWriter(app.paramsKeeper.Subspace(iparam.SignalParamspace).WithTypeTable( + params.NewTypeTable( + upgradeparams.CurrentUpgradeProposalIdParameter.GetStoreKey(), uint64((0)), + upgradeparams.ProposalAcceptHeightParameter.GetStoreKey(), int64(0), + upgradeparams.SwitchPeriodParameter.GetStoreKey(), int64(0), + )), &upgradeparams.CurrentUpgradeProposalIdParameter, &upgradeparams.ProposalAcceptHeightParameter, &upgradeparams.SwitchPeriodParameter) - iparam.RegisterGovParamMapping(&govparams.DepositProcedureParameter, + iparam.SetParamReadWriter(app.paramsKeeper.Subspace(iparam.GovParamspace).WithTypeTable( + params.NewTypeTable( + govparams.DepositProcedureParameter.GetStoreKey(), govparams.DepositProcedure{}, + govparams.VotingProcedureParameter.GetStoreKey(), govparams.VotingProcedure{}, + govparams.TallyingProcedureParameter.GetStoreKey(), govparams.TallyingProcedure{}, + serviceparams.MaxRequestTimeoutParameter.GetStoreKey(), int64(0), + serviceparams.MinProviderDepositParameter.GetStoreKey(), sdk.Coins{}, + )), + &govparams.DepositProcedureParameter, + &govparams.VotingProcedureParameter, + &govparams.TallyingProcedureParameter, + &serviceparams.MaxRequestTimeoutParameter, + &serviceparams.MinProviderDepositParameter) + + iparam.RegisterGovParamMapping( + &govparams.DepositProcedureParameter, &govparams.VotingProcedureParameter, &govparams.TallyingProcedureParameter) @@ -182,19 +265,19 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio } // custom tx codec -func MakeCodec() *wire.Codec { - var cdc = wire.NewCodec() - ibc.RegisterWire(cdc) - bank.RegisterWire(cdc) - stake.RegisterWire(cdc) - slashing.RegisterWire(cdc) - gov.RegisterWire(cdc) - record.RegisterWire(cdc) - auth.RegisterWire(cdc) - upgrade.RegisterWire(cdc) - iservice.RegisterWire(cdc) - sdk.RegisterWire(cdc) - wire.RegisterCrypto(cdc) +func MakeCodec() *codec.Codec { + var cdc = codec.New() + bank.RegisterCodec(cdc) + stake.RegisterCodec(cdc) + distr.RegisterCodec(cdc) + slashing.RegisterCodec(cdc) + gov.RegisterCodec(cdc) + record.RegisterCodec(cdc) + upgrade.RegisterCodec(cdc) + service.RegisterCodec(cdc) + auth.RegisterCodec(cdc) + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) return cdc } @@ -202,6 +285,12 @@ func MakeCodec() *wire.Codec { func (app *IrisApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) + // distribute rewards from previous block + distr.BeginBlocker(ctx, req, app.distrKeeper) + + // mint new tokens for this new block + mint.BeginBlocker(ctx, app.mintKeeper) + return abci.ResponseBeginBlock{ Tags: tags.ToKVPairs(), } @@ -212,8 +301,6 @@ func (app *IrisApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.R tags := gov.EndBlocker(ctx, app.govKeeper) validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) tags.AppendTags(upgrade.EndBlocker(ctx, app.upgradeKeeper)) - // Add these new validators to the addr -> pubkey map. - app.slashingKeeper.AddValidators(ctx, validatorUpdates) return abci.ResponseEndBlock{ ValidatorUpdates: validatorUpdates, Tags: tags, @@ -229,6 +316,10 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci if err != nil { panic(err) } + // sort by account number to maintain consistency + sort.Slice(genesisState.Accounts, func(i, j int) bool { + return genesisState.Accounts[i].AccountNumber < genesisState.Accounts[j].AccountNumber + }) // load the accounts for _, gacc := range genesisState.Accounts { @@ -249,12 +340,52 @@ 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.paramsKeeper.Setter(), feeTokenGensisConfig) + bam.InitGenesis(ctx, app.feeManager, feeTokenGensisConfig) // load the address to pubkey map - slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.StakeData) + auth.InitGenesis(ctx, app.feeCollectionKeeper, genesisState.AuthData) + slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.SlashingData, genesisState.StakeData) + mint.InitGenesis(ctx, app.mintKeeper, genesisState.MintData) + distr.InitGenesis(ctx, app.distrKeeper, genesisState.DistrData) + err = IrisValidateGenesisState(genesisState) + if err != nil { + panic(err) // TODO find a way to do this w/o panics + } + + if len(genesisState.GenTxs) > 0 { + for _, genTx := range genesisState.GenTxs { + var tx auth.StdTx + err = app.cdc.UnmarshalJSON(genTx, &tx) + if err != nil { + panic(err) + } + bz := app.cdc.MustMarshalBinaryLengthPrefixed(tx) + res := app.BaseApp.DeliverTx(bz) + if !res.IsOK() { + panic(res.Log) + } + } + + validators = app.stakeKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + } + + // sanity check + if len(req.Validators) > 0 { + if len(req.Validators) != len(validators) { + panic(fmt.Errorf("len(RequestInitChain.Validators) != len(validators) (%d != %d)", + len(req.Validators), len(validators))) + } + sort.Sort(abci.ValidatorUpdates(req.Validators)) + sort.Sort(abci.ValidatorUpdates(validators)) + for i, val := range validators { + if !val.Equal(req.Validators[i]) { + panic(fmt.Errorf("validators[%d] != req.Validators[%d] ", i, i)) + } + } + } upgrade.InitGenesis(ctx, app.upgradeKeeper, app.Router(), genesisState.UpgradeData) + service.InitGenesis(ctx, genesisState.ServiceData) return abci.ResponseInitChain{ Validators: validators, @@ -273,12 +404,18 @@ func (app *IrisApp) ExportAppStateAndValidators() (appState json.RawMessage, val return false } app.accountMapper.IterateAccounts(ctx, appendAccount) - - genState := GenesisState{ - Accounts: accounts, - StakeData: stake.WriteGenesis(ctx, app.stakeKeeper), - } - appState, err = wire.MarshalJSONIndent(app.cdc, genState) + genState := NewGenesisState( + accounts, + auth.ExportGenesis(ctx, app.feeCollectionKeeper), + stake.ExportGenesis(ctx, app.stakeKeeper), + mint.ExportGenesis(ctx, app.mintKeeper), + distr.ExportGenesis(ctx, app.distrKeeper), + gov.ExportGenesis(ctx, app.govKeeper), + upgrade.WriteGenesis(ctx, app.upgradeKeeper), + service.WriteGenesis(ctx), + slashing.ExportGenesis(ctx, app.slashingKeeper), + ) + appState, err = codec.MarshalJSONIndent(app.cdc, genState) if err != nil { return nil, nil, err } @@ -295,9 +432,17 @@ func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg, mode bam.RunTxMode) var code sdk.ABCICodeType for msgIdx, msg := range msgs { // Match route. - msgType, err := app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) - if err != nil { - return err.Result() + var msgType string + var err sdk.Error + if ctx.BlockHeight() != 0 { + msgType, err = app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) + + if err != nil { + return err.Result() + } + + } else { + msgType = msg.Route() } handler := app.Router().Route(msgType) @@ -341,36 +486,60 @@ func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg, mode bam.RunTxMode) 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")) - } +//______________________________________________________________________________________________ + +// Combined Staking Hooks +type Hooks struct { + dh distr.Hooks + sh slashing.Hooks +} + +func NewHooks(dh distr.Hooks, sh slashing.Hooks) Hooks { + return Hooks{dh, sh} +} + +var _ sdk.StakingHooks = Hooks{} + +func (h Hooks) OnValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { + h.dh.OnValidatorCreated(ctx, valAddr) + h.sh.OnValidatorCreated(ctx, valAddr) +} +func (h Hooks) OnValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { + h.dh.OnValidatorModified(ctx, valAddr) + h.sh.OnValidatorModified(ctx, valAddr) +} + +func (h Hooks) OnValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.OnValidatorRemoved(ctx, consAddr, valAddr) + h.sh.OnValidatorRemoved(ctx, consAddr, valAddr) +} + +func (h Hooks) OnValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.OnValidatorBonded(ctx, consAddr, valAddr) + h.sh.OnValidatorBonded(ctx, consAddr, valAddr) +} + +func (h Hooks) OnValidatorPowerDidChange(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.OnValidatorPowerDidChange(ctx, consAddr, valAddr) + h.sh.OnValidatorPowerDidChange(ctx, consAddr, valAddr) +} + +func (h Hooks) OnValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.OnValidatorBeginUnbonding(ctx, consAddr, valAddr) + h.sh.OnValidatorBeginUnbonding(ctx, consAddr, valAddr) +} + +func (h Hooks) OnDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.OnDelegationCreated(ctx, delAddr, valAddr) + h.sh.OnDelegationCreated(ctx, delAddr, valAddr) +} + +func (h Hooks) OnDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.OnDelegationSharesModified(ctx, delAddr, valAddr) + h.sh.OnDelegationSharesModified(ctx, delAddr, valAddr) +} - return loadHeight +func (h Hooks) OnDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.OnDelegationRemoved(ctx, delAddr, valAddr) + h.sh.OnDelegationRemoved(ctx, delAddr, valAddr) } diff --git a/app/genesis.go b/app/genesis.go index 2067a1d8d..62d5bef8b 100644 --- a/app/genesis.go +++ b/app/genesis.go @@ -3,242 +3,345 @@ package app import ( "encoding/json" "errors" - - "github.com/spf13/pflag" - "github.com/tendermint/tendermint/crypto" - tmtypes "github.com/tendermint/tendermint/types" - "fmt" + "io/ioutil" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/cosmos/cosmos-sdk/codec" "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" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/stake" "github.com/irisnet/irishub/modules/gov" + "github.com/irisnet/irishub/modules/service" "github.com/irisnet/irishub/modules/upgrade" "github.com/irisnet/irishub/types" - "time" + tmtypes "github.com/tendermint/tendermint/types" ) -// DefaultKeyPass contains the default key password for genesis transactions -const DefaultKeyPass = "1234567890" +var ( + Denom = "iris" + StakeDenom = Denom + "-" + types.Atto + FeeAmt = int64(100) + IrisCt = types.NewDefaultCoinType(Denom) + FreeFermionVal, _ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", FeeAmt, Denom)) + FreeFermionAcc, _ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", int64(150), Denom)) +) + +const ( + defaultUnbondingTime time.Duration = 60 * 10 * time.Second + // DefaultKeyPass contains the default key password for genesis transactions + DefaultKeyPass = "1234567890" +) // State to Unmarshal type GenesisState struct { - Accounts []GenesisAccount `json:"accounts"` - StakeData stake.GenesisState `json:"stake"` - GovData gov.GenesisState `json:"gov"` - UpgradeData upgrade.GenesisState `json:"upgrade"` + Accounts []GenesisAccount `json:"accounts"` + AuthData auth.GenesisState `json:"auth"` + StakeData stake.GenesisState `json:"stake"` + MintData mint.GenesisState `json:"mint"` + DistrData distr.GenesisState `json:"distr"` + GovData gov.GenesisState `json:"gov"` + UpgradeData upgrade.GenesisState `json:"upgrade"` + SlashingData slashing.GenesisState `json:"slashing"` + ServiceData service.GenesisState `json:"service"` + GenTxs []json.RawMessage `json:"gentxs"` +} + +func NewGenesisState(accounts []GenesisAccount, authData auth.GenesisState, stakeData stake.GenesisState, mintData mint.GenesisState, + distrData distr.GenesisState, govData gov.GenesisState, upgradeData upgrade.GenesisState, serviceData service.GenesisState, slashingData slashing.GenesisState) GenesisState { + + return GenesisState{ + Accounts: accounts, + AuthData: authData, + StakeData: stakeData, + MintData: mintData, + DistrData: distrData, + GovData: govData, + UpgradeData: upgradeData, + ServiceData: serviceData, + SlashingData: slashingData, + } } // GenesisAccount doesn't need pubkey or sequence type GenesisAccount struct { - Address sdk.AccAddress `json:"address"` - Coins sdk.Coins `json:"coins"` + Address sdk.AccAddress `json:"address"` + Coins sdk.Coins `json:"coins"` + Sequence int64 `json:"sequence_number"` + AccountNumber int64 `json:"account_number"` } func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount { return GenesisAccount{ - Address: acc.Address, - Coins: acc.Coins, + Address: acc.Address, + Coins: acc.Coins, + AccountNumber: acc.AccountNumber, + Sequence: acc.Sequence, } } func NewGenesisAccountI(acc auth.Account) GenesisAccount { return GenesisAccount{ - Address: acc.GetAddress(), - Coins: acc.GetCoins(), + Address: acc.GetAddress(), + Coins: acc.GetCoins(), + AccountNumber: acc.GetAccountNumber(), + Sequence: acc.GetSequence(), } } // convert GenesisAccount to auth.BaseAccount func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { return &auth.BaseAccount{ - Address: ga.Address, - Coins: ga.Coins.Sort(), + Address: ga.Address, + Coins: ga.Coins.Sort(), + AccountNumber: ga.AccountNumber, + Sequence: ga.Sequence, } } -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 +// NewDefaultGenesisState generates the default state for gaia. +func NewDefaultGenesisState() GenesisState { + return GenesisState{ + Accounts: nil, + StakeData: createStakeGenesisState(), + MintData: createMintGenesisState(), + DistrData: distr.DefaultGenesisState(), + GovData: gov.DefaultGenesisState(), + UpgradeData: upgrade.DefaultGenesisState(), + ServiceData: service.DefaultGenesisState(), + SlashingData: slashing.DefaultGenesisState(), + GenTxs: nil, + } +} // 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, + AppGenState: IrisAppGenStateJSON, } } -// simple genesis tx -type IrisGenTx struct { - Name string `json:"name"` - Address sdk.AccAddress `json:"address"` - PubKey string `json:"pub_key"` -} +// Create the core parameters for genesis initialization for iris +// note that the pubkey input is this machines pubkey +func IrisAppGenState(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []json.RawMessage) ( + genesisState GenesisState, err error) { + if err = cdc.UnmarshalJSON(genDoc.AppState, &genesisState); err != nil { + return genesisState, err + } -// 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 there are no gen txs to be processed, return the default empty state + if len(appGenTxs) == 0 { + return genesisState, errors.New("there must be at least one genesis tx") + } - if genTxConfig.Name == "" { - return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)") + stakeData := genesisState.StakeData + for i, genTx := range appGenTxs { + var tx auth.StdTx + if err := cdc.UnmarshalJSON(genTx, &tx); err != nil { + return genesisState, err + } + msgs := tx.GetMsgs() + if len(msgs) != 1 { + return genesisState, errors.New( + "must provide genesis StdTx with exactly 1 CreateValidator message") + } + if _, ok := msgs[0].(stake.MsgCreateValidator); !ok { + return genesisState, fmt.Errorf( + "Genesis transaction %v does not contain a MsgCreateValidator", i) + } } - var addr sdk.AccAddress - var secret string - addr, secret, err = server.GenerateSaveCoinKey(genTxConfig.CliRoot, genTxConfig.Name, DefaultKeyPass, genTxConfig.Overwrite) - if err != nil { - return + for _, acc := range genesisState.Accounts { + // create the genesis account, give'm few iris-atto and a buncha token with there name + for _, coin := range acc.Coins { + if coin.Denom == StakeDenom { + stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens. + Add(sdk.NewDecFromInt(coin.Amount)) // increase the supply + } + } } - mm := map[string]string{"secret": secret} - var bz []byte - bz, err = cdc.MarshalJSON(mm) + genesisState.StakeData = stakeData + genesisState.GenTxs = appGenTxs + genesisState.UpgradeData = genesisState.UpgradeData + return genesisState, nil +} + +func genesisAccountFromMsgCreateValidator(msg stake.MsgCreateValidator, amount sdk.Int) GenesisAccount { + accAuth := auth.NewBaseAccountWithAddress(sdk.AccAddress(msg.ValidatorAddr)) + accAuth.Coins = []sdk.Coin{ + {StakeDenom, amount}, + } + return NewGenesisAccount(&accAuth) +} + +// IrisValidateGenesisState ensures that the genesis state obeys the expected invariants +// TODO: No validators are both bonded and jailed (#2088) +// TODO: Error if there is a duplicate validator (#1708) +// TODO: Ensure all state machine parameters are in genesis (#1704) +func IrisValidateGenesisState(genesisState GenesisState) (err error) { + err = validateGenesisStateAccounts(genesisState.Accounts) if err != nil { return } - cliPrint = json.RawMessage(bz) - appGenTx, _, validator, err = IrisAppGenTxNF(cdc, pk, addr, genTxConfig.Name) + // skip stakeData validation as genesis is created from txs + if len(genesisState.GenTxs) > 0 { + return nil + } + return stake.ValidateGenesis(genesisState.StakeData) +} + +// Ensures that there are no duplicate accounts in the genesis state, +func validateGenesisStateAccounts(accs []GenesisAccount) (err error) { + addrMap := make(map[string]bool, len(accs)) + for i := 0; i < len(accs); i++ { + acc := accs[i] + strAddr := string(acc.Address) + if _, ok := addrMap[strAddr]; ok { + return fmt.Errorf("Duplicate account in genesis state: Address %v", acc.Address) + } + addrMap[strAddr] = true + } 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) { +// IrisAppGenState but with JSON +func IrisAppGenStateJSON(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []json.RawMessage) ( + appState json.RawMessage, err error) { - var bz []byte - gaiaGenTx := IrisGenTx{ - Name: name, - Address: addr, - PubKey: sdk.MustBech32ifyAccPub(pk), - } - bz, err = wire.MarshalJSONIndent(cdc, gaiaGenTx) + // create the final app state + genesisState, err := IrisAppGenState(cdc, genDoc, appGenTxs) if err != nil { - return - } - appGenTx = json.RawMessage(bz) - - validator = tmtypes.GenesisValidator{ - PubKey: pk, - Power: feeAmt, + return nil, err } + appState, err = codec.MarshalJSONIndent(cdc, genesisState) 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) { +// CollectStdTxs processes and validates application's genesis StdTxs and returns +// the list of appGenTxs, and persistent peers required to generate genesis.json. +func CollectStdTxs(cdc *codec.Codec, moniker string, genTxsDir string, genDoc tmtypes.GenesisDoc) ( + appGenTxs []auth.StdTx, persistentPeers string, err error) { - if len(appGenTxs) == 0 { - err = errors.New("must provide at least genesis transaction") - return + var fos []os.FileInfo + fos, err = ioutil.ReadDir(genTxsDir) + if err != nil { + return appGenTxs, persistentPeers, err } - stakeData := createGenesisState() - genaccs := make([]GenesisAccount, len(appGenTxs)) - for i, appGenTx := range appGenTxs { + // prepare a map of all accounts in genesis state to then validate + // against the validators addresses + var appState GenesisState + if err := cdc.UnmarshalJSON(genDoc.AppState, &appState); err != nil { + return appGenTxs, persistentPeers, err + } + addrMap := make(map[string]GenesisAccount, len(appState.Accounts)) + for i := 0; i < len(appState.Accounts); i++ { + acc := appState.Accounts[i] + strAddr := string(acc.Address) + addrMap[strAddr] = acc + } + + // addresses and IPs (and port) validator server info + var addressesIPs []string - var genTx IrisGenTx - err = cdc.UnmarshalJSON(appGenTx, &genTx) - if err != nil { - return + for _, fo := range fos { + filename := filepath.Join(genTxsDir, fo.Name()) + if !fo.IsDir() && (filepath.Ext(filename) != ".json") { + continue } - // 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, + // get the genStdTx + var jsonRawTx []byte + if jsonRawTx, err = ioutil.ReadFile(filename); err != nil { + return appGenTxs, persistentPeers, err } - 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, - } + var genStdTx auth.StdTx + if err = cdc.UnmarshalJSON(jsonRawTx, &genStdTx); err != nil { + return appGenTxs, persistentPeers, err + } + appGenTxs = append(appGenTxs, genStdTx) + + // the memo flag is used to store + // the ip and node-id, for example this may be: + // "528fd3df22b31f4969b05652bfe8f0fe921321d5@192.168.2.37:26656" + nodeAddrIP := genStdTx.GetMemo() + if len(nodeAddrIP) == 0 { + return appGenTxs, persistentPeers, fmt.Errorf( + "couldn't find node's address and IP in %s", fo.Name()) + } + + // genesis transactions must be single-message + msgs := genStdTx.GetMsgs() + if len(msgs) != 1 { - stakeData.Bonds = append(stakeData.Bonds, delegation) + return appGenTxs, persistentPeers, errors.New( + "each genesis transaction must provide a single genesis message") } - } - // create the final app state - genesisState = GenesisState{ - Accounts: genaccs, - StakeData: stakeData, - GovData: gov.DefaultGenesisState(), - UpgradeData: upgrade.DefaultGenesisState(), + // validate the validator address and funds against the accounts in the state + msg := msgs[0].(stake.MsgCreateValidator) + addr := string(sdk.AccAddress(msg.ValidatorAddr)) + acc, ok := addrMap[addr] + if !ok { + return appGenTxs, persistentPeers, fmt.Errorf( + "account %v not in genesis.json: %+v", addr, addrMap) + } + if acc.Coins.AmountOf(msg.Delegation.Denom).LT(msg.Delegation.Amount) { + err = fmt.Errorf("insufficient fund for the delegation: %s < %s", + acc.Coins.AmountOf(msg.Delegation.Denom), msg.Delegation.Amount) + } + + // exclude itself from persistent peers + if msg.Description.Moniker != moniker { + addressesIPs = append(addressesIPs, nodeAddrIP) + } } - return -} -// IrisAppGenState but with JSON -func IrisAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) { + sort.Strings(addressesIPs) + persistentPeers = strings.Join(addressesIPs, ",") - // create the final app state - genesisState, err := IrisAppGenState(cdc, appGenTxs) - if err != nil { - return nil, err + return appGenTxs, persistentPeers, nil +} + +func NewDefaultGenesisAccount(addr sdk.AccAddress) GenesisAccount { + accAuth := auth.NewBaseAccountWithAddress(addr) + accAuth.Coins = []sdk.Coin{ + FreeFermionAcc, } - appState, err = wire.MarshalJSONIndent(cdc, genesisState) - return + return NewGenesisAccount(&accAuth) } -func createGenesisState() stake.GenesisState { +func createStakeGenesisState() 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(), + LooseTokens: sdk.ZeroDec(), + BondedTokens: sdk.ZeroDec(), }, 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, + UnbondingTime: defaultUnbondingTime, + MaxValidators: 100, + BondDenom: StakeDenom, + }, + } +} + +func createMintGenesisState() mint.GenesisState { + return mint.GenesisState{ + Minter: mint.InitialMinter(), + Params: mint.Params{ + MintDenom: StakeDenom, + InflationRateChange: sdk.NewDecWithPrec(13, 2), + InflationMax: sdk.NewDecWithPrec(20, 2), + InflationMin: sdk.NewDecWithPrec(7, 2), + GoalBonded: sdk.NewDecWithPrec(67, 2), }, } } diff --git a/app/sim_test.go b/app/sim_test.go index f9ed24afc..1cb51bacd 100644 --- a/app/sim_test.go +++ b/app/sim_test.go @@ -4,22 +4,26 @@ import ( "encoding/json" "flag" "fmt" + "io/ioutil" "math/rand" + "os" "testing" + sdk "github.com/cosmos/cosmos-sdk/types" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/stake" "github.com/stretchr/testify/require" - - "github.com/tendermint/tendermint/crypto" + abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" - "github.com/irisnet/irishub/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/irisnet/irishub/modules/gov" banksim "github.com/irisnet/irishub/simulation/bank" govsim "github.com/irisnet/irishub/simulation/gov" "github.com/irisnet/irishub/simulation/mock/simulation" slashingsim "github.com/irisnet/irishub/simulation/slashing" - "github.com/cosmos/cosmos-sdk/x/stake" stakesim "github.com/irisnet/irishub/simulation/stake" ) @@ -29,58 +33,93 @@ var ( blockSize int enabled bool verbose bool + commit bool ) func init() { flag.Int64Var(&seed, "SimulationSeed", 42, "Simulation random seed") flag.IntVar(&numBlocks, "SimulationNumBlocks", 500, "Number of blocks") flag.IntVar(&blockSize, "SimulationBlockSize", 200, "Operations per block") - flag.BoolVar(&enabled, "SimulationEnabled", false, "Enable the simulation") + flag.BoolVar(&enabled, "SimulationEnabled", true, "Enable the simulation") flag.BoolVar(&verbose, "SimulationVerbose", false, "Verbose log output") + flag.BoolVar(&commit, "SimulationCommit", false, "Have the simulation commit") } -func appStateFn(r *rand.Rand, keys []crypto.PrivKey, accs []sdk.AccAddress) json.RawMessage { +func appStateFn(r *rand.Rand, accs []simulation.Account) json.RawMessage { + stakeGenesis := stake.DefaultGenesisState() + fmt.Printf("Selected randomly generated staking parameters: %+v\n", stakeGenesis) + var genesisAccounts []GenesisAccount + amount := sdk.NewIntWithDecimal(100, 18) + stakeAmount := sdk.NewIntWithDecimal(1, 2) + numInitiallyBonded := int64(r.Intn(250)) + //numInitiallyBonded := int64(4) + numAccs := int64(len(accs)) + if numInitiallyBonded > numAccs { + numInitiallyBonded = numAccs + } + fmt.Printf("Selected randomly generated parameters for simulated genesis: {amount of iris-atto per account: %v, initially bonded validators: %v}\n", amount, numInitiallyBonded) + // Randomly generate some genesis accounts for _, acc := range accs { - amountStr := "1000000000000000000000000" - amount, ok := sdk.NewIntFromString(amountStr) - if ok { - fmt.Errorf("invalid token amont %s", amountStr) + coins := sdk.Coins{ + { + Denom: "iris-atto", + Amount: amount, + }, + { + Denom: stakeGenesis.Params.BondDenom, + Amount: stakeAmount, + }, } - - //TODO: use two coins for stake test, will only one coin after sdk update to v0.25 - coins := sdk.Coins{{"iris-atto", amount}, {"steak", sdk.NewInt(100)}} genesisAccounts = append(genesisAccounts, GenesisAccount{ - Address: acc, + Address: acc.Address, Coins: coins, }) } - // Default genesis state - stakeGenesis := stake.DefaultGenesisState() - var validators []stake.Validator - var delegations []stake.Delegation - // XXX Try different numbers of initially bonded validators - numInitiallyBonded := int64(50) + // Random genesis states + govGenesis := gov.DefaultGenesisState() + fmt.Printf("Selected randomly generated governance parameters: %+v\n", govGenesis) + slashingGenesis := slashing.DefaultGenesisState() + fmt.Printf("Selected randomly generated slashing parameters: %+v\n", slashingGenesis) + mintGenesis := mint.DefaultGenesisState() + fmt.Printf("Selected randomly generated minting parameters: %v\n", mintGenesis) + var ( + validators []stake.Validator + delegations []stake.Delegation + ) + + decAmt := sdk.NewDecFromInt(sdk.NewIntWithDecimal(100, 18)) + valAddrs := make([]sdk.ValAddress, numInitiallyBonded) for i := 0; i < int(numInitiallyBonded); i++ { - validator := stake.NewValidator(accs[i], keys[i].PubKey(), stake.Description{}) - validator.Tokens = sdk.NewRat(100) - validator.DelegatorShares = sdk.NewRat(100) - delegation := stake.Delegation{accs[i], accs[i], sdk.NewRat(100), 0} + valAddr := sdk.ValAddress(accs[i].Address) + valAddrs[i] = valAddr + + validator := stake.NewValidator(valAddr, accs[i].PubKey, stake.Description{}) + validator.Tokens = decAmt + validator.DelegatorShares = decAmt + delegation := stake.Delegation{ + DelegatorAddr: accs[i].Address, + ValidatorAddr: valAddr, + Shares: decAmt, + Height: 0, + } validators = append(validators, validator) delegations = append(delegations, delegation) } - stakeGenesis.Pool.LooseTokens = sdk.NewRat(int64(100*250) + (numInitiallyBonded * 100)) + stakeGenesis.Pool.LooseTokens = sdk.NewDecFromInt(sdk.NewIntWithDecimal(100, 30)) stakeGenesis.Validators = validators stakeGenesis.Bonds = delegations - // No inflation, for now - stakeGenesis.Params.InflationMax = sdk.NewRat(0) - stakeGenesis.Params.InflationMin = sdk.NewRat(0) + genesis := GenesisState{ - Accounts: genesisAccounts, - StakeData: stakeGenesis, + Accounts: genesisAccounts, + StakeData: stakeGenesis, + MintData: mintGenesis, + DistrData: distr.DefaultGenesisWithValidators(valAddrs), + SlashingData: slashingGenesis, + GovData: govGenesis, } // Marshal genesis @@ -92,31 +131,56 @@ func appStateFn(r *rand.Rand, keys []crypto.PrivKey, accs []sdk.AccAddress) json return appState } -func testAndRunTxs(app *IrisApp) []simulation.TestAndRunTx { - return []simulation.TestAndRunTx{ - banksim.TestAndRunSingleInputMsgSend(app.accountMapper), - govsim.SimulateMsgSubmitProposal(app.govKeeper, app.stakeKeeper), - govsim.SimulateMsgDeposit(app.govKeeper, app.stakeKeeper), - govsim.SimulateMsgVote(app.govKeeper, app.stakeKeeper), - stakesim.SimulateMsgCreateValidator(app.accountMapper, app.stakeKeeper), - stakesim.SimulateMsgEditValidator(app.stakeKeeper), - stakesim.SimulateMsgDelegate(app.accountMapper, app.stakeKeeper), - stakesim.SimulateMsgBeginUnbonding(app.accountMapper, app.stakeKeeper), - stakesim.SimulateMsgCompleteUnbonding(app.stakeKeeper), - stakesim.SimulateMsgBeginRedelegate(app.accountMapper, app.stakeKeeper), - stakesim.SimulateMsgCompleteRedelegate(app.stakeKeeper), - slashingsim.SimulateMsgUnrevoke(app.slashingKeeper), +func testAndRunTxs(app *IrisApp) []simulation.WeightedOperation { + return []simulation.WeightedOperation{ + {100, banksim.SingleInputSendMsg(app.accountMapper, app.bankKeeper)}, + {5, govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, app.stakeKeeper)}, + {100, govsim.SimulateMsgDeposit(app.govKeeper, app.stakeKeeper)}, + {100, stakesim.SimulateMsgCreateValidator(app.accountMapper, app.stakeKeeper)}, + {5, stakesim.SimulateMsgEditValidator(app.stakeKeeper)}, + {100, stakesim.SimulateMsgDelegate(app.accountMapper, app.stakeKeeper)}, + {100, stakesim.SimulateMsgBeginUnbonding(app.accountMapper, app.stakeKeeper)}, + {100, stakesim.SimulateMsgBeginRedelegate(app.accountMapper, app.stakeKeeper)}, + {100, slashingsim.SimulateMsgUnjail(app.slashingKeeper)}, } } func invariants(app *IrisApp) []simulation.Invariant { - return []simulation.Invariant{ - func(t *testing.T, baseapp *baseapp.BaseApp, log string) { - banksim.NonnegativeBalanceInvariant(app.accountMapper)(t, baseapp, log) - govsim.AllInvariants()(t, baseapp, log) - stakesim.AllInvariants(app.coinKeeper, app.stakeKeeper, app.accountMapper)(t, baseapp, log) - slashingsim.AllInvariants()(t, baseapp, log) - }, + return []simulation.Invariant{} +} + +func BenchmarkFullIrisSimulation(b *testing.B) { + // Setup Iris application + var logger log.Logger + logger = log.NewNopLogger() + var db dbm.DB + dir, _ := ioutil.TempDir("", "goleveldb-iris-sim") + db, _ = dbm.NewGoLevelDB("Simulation", dir) + defer func() { + db.Close() + os.RemoveAll(dir) + }() + app := NewIrisApp(logger, db, nil) + + // Run randomized simulation + // TODO parameterize numbers, save for a later PR + err := simulation.SimulateFromSeed( + b, app.BaseApp, appStateFn, seed, + testAndRunTxs(app), + []simulation.RandSetup{}, + invariants(app), // these shouldn't get ran + numBlocks, + blockSize, + commit, + ) + if err != nil { + fmt.Println(err) + b.Fail() + } + if commit { + fmt.Println("GoLevelDB Stats") + fmt.Println(db.Stats()["leveldb.stats"]) + fmt.Println("GoLevelDB cached block size", db.Stats()["leveldb.cachedblock"]) } } @@ -132,20 +196,130 @@ func TestFullIrisSimulation(t *testing.T) { } else { logger = log.NewNopLogger() } - db := dbm.NewMemDB() + var db dbm.DB + dir, _ := ioutil.TempDir("", "goleveldb-iris-sim") + db, _ = dbm.NewGoLevelDB("Simulation", dir) + defer func() { + db.Close() + os.RemoveAll(dir) + }() app := NewIrisApp(logger, db, nil) require.Equal(t, "IrisApp", app.Name()) // Run randomized simulation - simulation.SimulateFromSeed( + err := simulation.SimulateFromSeed( t, app.BaseApp, appStateFn, seed, testAndRunTxs(app), []simulation.RandSetup{}, invariants(app), numBlocks, blockSize, - false, + commit, ) + if commit { + // for memdb: + // fmt.Println("Database Size", db.Stats()["database.size"]) + fmt.Println("GoLevelDB Stats") + fmt.Println(db.Stats()["leveldb.stats"]) + fmt.Println("GoLevelDB cached block size", db.Stats()["leveldb.cachedblock"]) + } + require.Nil(t, err) +} + +func TestIrisImportExport(t *testing.T) { + if !enabled { + t.Skip("Skipping Iris import/export simulation") + } + + // Setup Iris application + var logger log.Logger + if verbose { + logger = log.TestingLogger() + } else { + logger = log.NewNopLogger() + } + var db dbm.DB + dir, _ := ioutil.TempDir("", "goleveldb-iris-sim") + db, _ = dbm.NewGoLevelDB("Simulation", dir) + defer func() { + db.Close() + os.RemoveAll(dir) + }() + app := NewIrisApp(logger, db, nil) + require.Equal(t, "IrisApp", app.Name()) + + // Run randomized simulation + err := simulation.SimulateFromSeed( + t, app.BaseApp, appStateFn, seed, + testAndRunTxs(app), + []simulation.RandSetup{}, + invariants(app), + numBlocks, + blockSize, + commit, + ) + if commit { + // for memdb: + // fmt.Println("Database Size", db.Stats()["database.size"]) + fmt.Println("GoLevelDB Stats") + fmt.Println(db.Stats()["leveldb.stats"]) + fmt.Println("GoLevelDB cached block size", db.Stats()["leveldb.cachedblock"]) + } + require.Nil(t, err) + + fmt.Printf("Exporting genesis...\n") + + appState, _, err := app.ExportAppStateAndValidators() + if err != nil { + panic(err) + } + + fmt.Printf("Importing genesis...\n") + + newDir, _ := ioutil.TempDir("", "goleveldb-iris-sim-2") + newDB, _ := dbm.NewGoLevelDB("Simulation-2", dir) + defer func() { + newDB.Close() + os.RemoveAll(newDir) + }() + newApp := NewIrisApp(log.NewNopLogger(), newDB, nil) + require.Equal(t, "IrisApp", newApp.Name()) + request := abci.RequestInitChain{ + AppStateBytes: appState, + } + newApp.InitChain(request) + newApp.Commit() + + fmt.Printf("Comparing stores...\n") + ctxA := app.NewContext(true, abci.Header{}) + ctxB := newApp.NewContext(true, abci.Header{}) + type StoreKeysPrefixes struct { + A sdk.StoreKey + B sdk.StoreKey + Prefixes [][]byte + } + storeKeysPrefixes := []StoreKeysPrefixes{ + {app.keyMain, newApp.keyMain, [][]byte{}}, + {app.keyAccount, newApp.keyAccount, [][]byte{}}, + {app.keyStake, newApp.keyStake, [][]byte{stake.UnbondingQueueKey, stake.RedelegationQueueKey, stake.ValidatorQueueKey}}, // ordering may change but it doesn't matter + {app.keySlashing, newApp.keySlashing, [][]byte{}}, + {app.keyMint, newApp.keyMint, [][]byte{}}, + {app.keyDistr, newApp.keyDistr, [][]byte{}}, + {app.keyFeeCollection, newApp.keyFeeCollection, [][]byte{}}, + {app.keyParams, newApp.keyParams, [][]byte{}}, + {app.keyGov, newApp.keyGov, [][]byte{}}, + } + for _, storeKeysPrefix := range storeKeysPrefixes { + storeKeyA := storeKeysPrefix.A + storeKeyB := storeKeysPrefix.B + prefixes := storeKeysPrefix.Prefixes + storeA := ctxA.KVStore(storeKeyA) + storeB := ctxB.KVStore(storeKeyB) + kvA, kvB, count, equal := sdk.DiffKVStores(storeA, storeB, prefixes) + fmt.Printf("Compared %d key/value pairs between %s and %s\n", count, storeKeyA, storeKeyB) + require.True(t, equal, "unequal stores: %s / %s:\nstore A %s (%X) => %s (%X)\nstore B %s (%X) => %s (%X)", + storeKeyA, storeKeyB, kvA.Key, kvA.Key, kvA.Value, kvA.Value, kvB.Key, kvB.Key, kvB.Value, kvB.Value) + } } @@ -156,7 +330,7 @@ func TestAppStateDeterminism(t *testing.T) { t.Skip("Skipping Iris simulation") } - numSeeds := 5 + numSeeds := 3 numTimesToRunPerSeed := 5 appHashList := make([]json.RawMessage, numTimesToRunPerSeed) @@ -173,16 +347,16 @@ func TestAppStateDeterminism(t *testing.T) { testAndRunTxs(app), []simulation.RandSetup{}, []simulation.Invariant{}, - 20, - 20, + 50, + 100, true, ) + //app.Commit() appHash := app.LastCommitID().Hash - fmt.Printf(">>> APP HASH: %v, %X\n", appHash, appHash) appHashList[j] = appHash } for k := 1; k < numTimesToRunPerSeed; k++ { - require.Equal(t, appHashList[0], appHashList[k]) + require.Equal(t, appHashList[0], appHashList[k], "appHash list: %v", appHashList) } } } diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 5857f63ff..4e4074882 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -16,8 +16,8 @@ import ( "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/auth" + qr "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" "github.com/irisnet/irishub/types" "github.com/irisnet/irishub/version" ) @@ -45,14 +45,14 @@ type RunMsg func(ctx sdk.Context, msgs []sdk.Msg, mode RunTxMode) sdk.Result // BaseApp reflects the ABCI application implementation. type BaseApp struct { // initialized on creation - Logger log.Logger - name string // application name from abci.Info - cdc *wire.Codec // Amino codec - db dbm.DB // common DB backend - cms sdk.CommitMultiStore // Main (uncached) state - router Router // handle any kind of message - codespacer *sdk.Codespacer // handle module codespacing - txDecoder sdk.TxDecoder // unmarshal []byte into sdk.Tx + Logger log.Logger + name string // application name from abci.Info + db dbm.DB // common DB backend + cms sdk.CommitMultiStore // Main (uncached) state + router Router // handle any kind of message + queryRouter qr.QueryRouter // router for redirecting query calls + codespacer *sdk.Codespacer // handle module codespacing + txDecoder sdk.TxDecoder // unmarshal []byte into sdk.Tx anteHandler sdk.AnteHandler // ante handler for fee and auth feeRefundHandler types.FeeRefundHandler // fee handler for fee refund @@ -71,9 +71,12 @@ type BaseApp struct { // checkState is set on initialization and reset on Commit. // deliverState is set in InitChain and BeginBlock and cleared on Commit. // See methods setCheckState and setDeliverState. - checkState *state // for CheckTx - deliverState *state // for DeliverTx - signedValidators []abci.SigningValidator // absent validators from begin block + checkState *state // for CheckTx + deliverState *state // for DeliverTx + voteInfos []abci.VoteInfo // absent validators from begin block + + // minimum fees for spam prevention + minimumFees sdk.Coins // flag for sealing sealed bool @@ -90,16 +93,16 @@ var _ abci.Application = (*BaseApp)(nil) // NOTE: The db is used to store the version number for now. // Accepts a user-defined txDecoder // Accepts variable number of option functions, which act on the BaseApp to set configuration choices -func NewBaseApp(name string, cdc *wire.Codec, logger log.Logger, db dbm.DB, txDecoder sdk.TxDecoder, options ...func(*BaseApp)) *BaseApp { +func NewBaseApp(name string, logger log.Logger, db dbm.DB, txDecoder sdk.TxDecoder, options ...func(*BaseApp)) *BaseApp { app := &BaseApp{ - Logger: logger, - name: name, - cdc: cdc, - db: db, - cms: store.NewCommitMultiStore(db), - router: NewRouter(), - codespacer: sdk.NewCodespacer(), - txDecoder: txDecoder, + Logger: logger, + name: name, + db: db, + cms: store.NewCommitMultiStore(db), + router: NewRouter(), + queryRouter: qr.NewQueryRouter(), + codespacer: sdk.NewCodespacer(), + txDecoder: txDecoder, } // Register the undefined & root codespaces, which should not be used by @@ -127,13 +130,20 @@ func (app *BaseApp) RegisterCodespace(codespace sdk.CodespaceType) sdk.Codespace return app.codespacer.RegisterNext(codespace) } -// Mount a store to the provided key in the BaseApp multistore +// Mount IAVL stores to the provided keys in the BaseApp multistore func (app *BaseApp) MountStoresIAVL(keys ...*sdk.KVStoreKey) { for _, key := range keys { app.MountStore(key, sdk.StoreTypeIAVL) } } +// Mount stores to the provided keys in the BaseApp multistore +func (app *BaseApp) MountStoresTransient(keys ...*sdk.TransientStoreKey) { + for _, key := range keys { + app.MountStore(key, sdk.StoreTypeTransient) + } +} + // Mount a store to the provided key in the BaseApp multistore, using a specified DB func (app *BaseApp) MountStoreWithDB(key sdk.StoreKey, typ sdk.StoreType, db dbm.DB) { app.cms.MountStoreWithDB(key, typ, db) @@ -148,33 +158,8 @@ func (app *BaseApp) MountStore(key sdk.StoreKey, typ sdk.StoreType) { func (app *BaseApp) GetKVStore(key sdk.StoreKey) sdk.KVStore { return app.cms.GetKVStore(key) } - //////////////////// iris/cosmos-sdk end /////////////////////////// -// default custom logic for transaction decoding -// TODO: remove auth and wire dependencies from baseapp -// - move this to auth.DefaultTxDecoder -// - set the default here to JSON decode like docs/examples/app1 (it will fail -// for multiple messages ;)) -// - pass a TxDecoder into NewBaseApp, instead of a codec. -func defaultTxDecoder(cdc *wire.Codec) sdk.TxDecoder { - return func(txBytes []byte) (sdk.Tx, sdk.Error) { - var tx = auth.StdTx{} - - if len(txBytes) == 0 { - return nil, sdk.ErrTxDecode("txBytes are empty") - } - - // StdTx.Msg is an interface. The concrete sdk - // are registered by MakeTxCodec - err := cdc.UnmarshalBinary(txBytes, &tx) - if err != nil { - return nil, sdk.ErrTxDecode("").TraceSDK(err.Error()) - } - return tx, nil - } -} - func (app *BaseApp) SetRunMsg(runMsg RunMsg) { app.runMsg = runMsg } @@ -215,7 +200,7 @@ func (app *BaseApp) initFromStore(mainKey sdk.StoreKey) error { if main == nil { return errors.New("baseapp expects MultiStore with 'main' KVStore") } - // Needed for `gaiad export`, which inits from store but never calls initchain + // Needed for `iris export`, which inits from store but never calls initchain app.setCheckState(abci.Header{}) app.Seal() @@ -223,10 +208,13 @@ func (app *BaseApp) initFromStore(mainKey sdk.StoreKey) error { return nil } +// SetMinimumFees sets the minimum fees. +func (app *BaseApp) SetMinimumFees(fees sdk.Coins) { app.minimumFees = fees } + // NewContext returns a new Context with the correct store, the given header, and nil txBytes. func (app *BaseApp) NewContext(isCheckTx bool, header abci.Header) sdk.Context { if isCheckTx { - return sdk.NewContext(app.checkState.ms, header, true, app.Logger) + return sdk.NewContext(app.checkState.ms, header, true, app.Logger).WithMinimumFees(app.minimumFees) } return sdk.NewContext(app.deliverState.ms, header, false, app.Logger) } @@ -244,7 +232,7 @@ func (app *BaseApp) setCheckState(header abci.Header) { ms := app.cms.CacheMultiStore() app.checkState = &state{ ms: ms, - ctx: sdk.NewContext(ms, header, true, app.Logger), + ctx: sdk.NewContext(ms, header, true, app.Logger).WithMinimumFees(app.minimumFees), } } @@ -310,6 +298,7 @@ func (app *BaseApp) FilterPeerByPubKey(info string) abci.ResponseQuery { return abci.ResponseQuery{} } +// Splits a string path using the delimter '/'. i.e. "this/is/funny" becomes []string{"this", "is", "funny"} func splitPath(requestPath string) (path []string) { path = strings.Split(requestPath, "/") // first element is empty string @@ -335,6 +324,8 @@ func (app *BaseApp) Query(req abci.RequestQuery) (res abci.ResponseQuery) { return handleQueryStore(app, path, req) case "p2p": return handleQueryP2P(app, path, req) + case "custom": + return handleQueryCustom(app, path, req) } msg := "unknown query path" @@ -363,7 +354,7 @@ func handleQueryApp(app *BaseApp, path []string, req abci.RequestQuery) (res abc } // Encode with json - value := wire.Cdc.MustMarshalBinary(result) + value := codec.Cdc.MustMarshalBinaryLengthPrefixed(result) return abci.ResponseQuery{ Code: uint32(sdk.ABCICodeOK), Value: value, @@ -384,6 +375,7 @@ func handleQueryStore(app *BaseApp, path []string, req abci.RequestQuery) (res a return queryable.Query(req) } +// nolint: unparam func handleQueryP2P(app *BaseApp, path []string, req abci.RequestQuery) (res abci.ResponseQuery) { // "/p2p" prefix for p2p queries if len(path) >= 4 { @@ -406,6 +398,34 @@ func handleQueryP2P(app *BaseApp, path []string, req abci.RequestQuery) (res abc return sdk.ErrUnknownRequest(msg).QueryResult() } +func handleQueryCustom(app *BaseApp, path []string, req abci.RequestQuery) (res abci.ResponseQuery) { + // path[0] should be "custom" because "/custom" prefix is required for keeper queries. + // the queryRouter routes using path[1]. For example, in the path "custom/gov/proposal", queryRouter routes using "gov" + if len(path) < 2 || path[1] == "" { + return sdk.ErrUnknownRequest("No route for custom query specified").QueryResult() + } + querier := app.queryRouter.Route(path[1]) + if querier == nil { + return sdk.ErrUnknownRequest(fmt.Sprintf("no custom querier found for route %s", path[1])).QueryResult() + } + + ctx := sdk.NewContext(app.cms.CacheMultiStore(), app.checkState.ctx.BlockHeader(), true, app.Logger). + WithMinimumFees(app.minimumFees) + // Passes the rest of the path as an argument to the querier. + // For example, in the path "custom/gov/proposal/test", the gov querier gets []string{"proposal", "test"} as the path + resBytes, err := querier(ctx, path[2:], req) + if err != nil { + return abci.ResponseQuery{ + Code: uint32(err.ABCICode()), + Log: err.ABCILog(), + } + } + return abci.ResponseQuery{ + Code: uint32(sdk.ABCICodeOK), + Value: resBytes, + } +} + // BeginBlock implements the ABCI application interface. func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeginBlock) { if app.cms.TracingEnabled() { @@ -432,7 +452,7 @@ func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeg // set the signed validators for addition to context in deliverTx // TODO: communicate this result to the address to pubkey map in slashing - app.signedValidators = req.LastCommitInfo.GetValidators() + app.voteInfos = req.LastCommitInfo.GetVotes() return } @@ -534,15 +554,14 @@ func validateBasicTxMsgs(msgs []sdk.Msg) sdk.Error { return nil } +// retrieve the context for the ante handler and store the tx bytes; store +// the vote infos if the tx runs within the deliverTx() state. func (app *BaseApp) getContextForAnte(mode RunTxMode, txBytes []byte) (ctx sdk.Context) { // Get the context - if mode == RunTxModeCheck || mode == RunTxModeSimulate { - ctx = app.checkState.ctx.WithTxBytes(txBytes) - } else { - ctx = app.deliverState.ctx.WithTxBytes(txBytes) - ctx = ctx.WithSigningValidators(app.signedValidators) + ctx = getState(app, mode).ctx.WithTxBytes(txBytes) + if mode == RunTxModeDeliver { + ctx = ctx.WithVoteInfos(app.voteInfos) } - return } @@ -559,10 +578,10 @@ func (app *BaseApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg, mode RunTxMode) (re var code sdk.ABCICodeType for msgIdx, msg := range msgs { // Match route. - msgType := msg.Type() - handler := app.router.Route(msgType) + msgRoute := msg.Route() + handler := app.router.Route(msgRoute) if handler == nil { - return sdk.ErrUnknownRequest("Unrecognized Msg type: " + msgType).Result() + return sdk.ErrUnknownRequest("Unrecognized Msg type: " + msgRoute).Result() } var msgResult sdk.Result @@ -570,6 +589,7 @@ func (app *BaseApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg, mode RunTxMode) (re if mode != RunTxModeCheck { msgResult = handler(ctx, msg) } + msgResult.Tags = append(msgResult.Tags, sdk.MakeTag("action", []byte(msg.Type()))) // NOTE: GasWanted is determined by ante handler and // GasUsed by the GasMeter @@ -612,6 +632,13 @@ func getState(app *BaseApp, mode RunTxMode) *state { return app.deliverState } +func (app *BaseApp) initializeContext(ctx sdk.Context, mode RunTxMode) sdk.Context { + if mode == RunTxModeSimulate { + ctx = ctx.WithMultiStore(getState(app, RunTxModeSimulate).CacheMultiStore()) + } + return ctx +} + // runTx processes a transaction. The transactions is proccessed via an // anteHandler. txBytes may be nil in some cases, eg. in tests. Also, in the // future we may support "internal" transactions. @@ -620,8 +647,11 @@ func (app *BaseApp) runTx(mode RunTxMode, txBytes []byte, tx sdk.Tx) (result sdk // determined by the GasMeter. We need access to the context to get the gas // meter so we initialize upfront. var gasWanted int64 + var msCache sdk.CacheMultiStore ctx := app.getContextForAnte(mode, txBytes) + ctx = app.initializeContext(ctx, mode) ctxWithNoCache := ctx + defer func() { if r := recover(); r != nil { switch rType := r.(type) { @@ -635,31 +665,35 @@ func (app *BaseApp) runTx(mode RunTxMode, txBytes []byte, tx sdk.Tx) (result sdk } result.GasWanted = gasWanted - result.GasUsed = ctxWithNoCache.GasMeter().GasConsumed() + result.GasUsed = ctx.GasMeter().GasConsumed() // Refund unspent fee if mode != RunTxModeCheck && app.feeRefundHandler != nil { actualCostFee, err := app.feeRefundHandler(ctxWithNoCache, tx, result) - if err == nil { - fee, _ := actualCostFee.Amount.BigInt().MarshalJSON() - result.Tags = result.Tags.AppendTag("completeConsumedTxFee-"+actualCostFee.Denom, fee) - } else { + if err != nil { result = sdk.ErrInternal(err.Error()).Result() result.GasWanted = gasWanted - result.GasUsed = ctxWithNoCache.GasMeter().GasConsumed() + result.GasUsed = ctx.GasMeter().GasConsumed() + return } + fee, err := actualCostFee.Amount.MarshalJSON() + if err != nil { + result = sdk.ErrInternal(err.Error()).Result() + result.GasWanted = gasWanted + result.GasUsed = ctx.GasMeter().GasConsumed() + return + } + result.Tags = result.Tags.AppendTag("completeConsumedTxFee-"+actualCostFee.Denom, fee) } }() var msgs = tx.GetMsgs() - - err := validateBasicTxMsgs(msgs) - if err != nil { + if err := validateBasicTxMsgs(msgs); err != nil { return err.Result() } // run the fee handler - if app.feePreprocessHandler != nil { + if app.feePreprocessHandler != nil && ctx.BlockHeight() != 0 { err := app.feePreprocessHandler(ctx, tx) if err != nil { return sdk.ErrInvalidCoins(err.Error()).Result() @@ -668,21 +702,27 @@ func (app *BaseApp) runTx(mode RunTxMode, txBytes []byte, tx sdk.Tx) (result sdk // run the ante handler if app.anteHandler != nil { - newCtx, anteResult, abort := app.anteHandler(ctx, tx) + newCtx, result, abort := app.anteHandler(ctx, tx, (mode == RunTxModeSimulate)) if abort { - return anteResult + return result } if !newCtx.IsZero() { ctx = newCtx ctxWithNoCache = newCtx } - gasWanted = anteResult.GasWanted + gasWanted = result.GasWanted + } + + if mode == RunTxModeSimulate { + result = app.runMsgs(ctx, msgs, mode) + result.GasWanted = gasWanted + return } // Keep the state in a transient CacheWrap in case processing the messages // fails. - msCache := getState(app, mode).CacheMultiStore() + msCache = getState(app, mode).CacheMultiStore() if msCache.TracingEnabled() { msCache = msCache.WithTracingContext(sdk.TraceContext( map[string]interface{}{"txHash": cmn.HexBytes(tmhash.Sum(txBytes)).String()}, @@ -693,8 +733,8 @@ func (app *BaseApp) runTx(mode RunTxMode, txBytes []byte, tx sdk.Tx) (result sdk result = app.runMsgs(ctx, msgs, mode) result.GasWanted = gasWanted - // only update state if all messages pass and we're not in a simulation - if result.IsOK() && mode != RunTxModeSimulate { + // only update state if all messages pass + if result.IsOK() { msCache.Write() } diff --git a/baseapp/fee.go b/baseapp/fee.go index 49da4d592..d82ce12dd 100644 --- a/baseapp/fee.go +++ b/baseapp/fee.go @@ -1,40 +1,37 @@ package baseapp import ( + "errors" "fmt" - "runtime/debug" - "github.com/cosmos/cosmos-sdk/x/auth" sdk "github.com/cosmos/cosmos-sdk/types" - "errors" - "github.com/irisnet/irishub/types" + "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/params" + "github.com/irisnet/irishub/types" + "runtime/debug" ) var ( - nativeFeeTokenKey = "feeToken/native" - nativeGasPriceThresholdKey = "feeToken/gasPriceThreshold" -// FeeExchangeRatePrefix = "feeToken/exchangeRate/" // key = gov/feeToken/exchangeRate/, rate = BigInt(value)/10^9 -// RatePrecision = int64(1000000000) //10^9 + nativeFeeTokenKey = []byte("feeTokenNative") + nativeGasPriceThresholdKey = []byte("feeTokenGasPriceThreshold") + // FeeExchangeRatePrefix = "feeToken/exchangeRate/" // key = gov/feeToken/exchangeRate/, rate = BigInt(value)/10^9 + // RatePrecision = int64(1000000000) //10^9 ) -// NewFeePreprocessHandler creates a fee token preprocess handler +// NewFeePreprocessHandler creates a fee token preprocesser func NewFeePreprocessHandler(fm FeeManager) types.FeePreprocessHandler { - return func(ctx sdk.Context, tx sdk.Tx) (error) { + return func(ctx sdk.Context, tx sdk.Tx) error { stdTx, ok := tx.(auth.StdTx) if !ok { return sdk.ErrInternal("tx must be StdTx") } - fee := auth.StdFee{ - Gas: stdTx.Fee.Gas, - Amount: sdk.Coins{fm.getNativeFeeToken(ctx, stdTx.Fee.Amount)}, - } - return fm.feePreprocess(ctx, fee.Amount, fee.Gas) + totalNativeFee := fm.getNativeFeeToken(ctx, stdTx.Fee.Amount) + return fm.feePreprocess(ctx, sdk.Coins{totalNativeFee}, stdTx.Fee.Gas) } } // NewFeePreprocessHandler creates a fee token refund handler -func NewFeeRefundHandler(am auth.AccountMapper, fck auth.FeeCollectionKeeper, fm FeeManager) types.FeeRefundHandler { - return func(ctx sdk.Context, tx sdk.Tx, txResult sdk.Result) (refundResult sdk.Coin, err error) { +func NewFeeRefundHandler(am auth.AccountKeeper, fck auth.FeeCollectionKeeper, fm FeeManager) types.FeeRefundHandler { + return func(ctx sdk.Context, tx sdk.Tx, txResult sdk.Result) (actualCostFee sdk.Coin, err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("encountered panic error during fee refund, recovered: %v\nstack:\n%v", r, string(debug.Stack())) @@ -56,83 +53,86 @@ func NewFeeRefundHandler(am auth.AccountMapper, fck auth.FeeCollectionKeeper, fm // It is not reasonable to consume users' gas. So the context gas is reset to transaction gas ctx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter()) - fee := auth.StdFee{ - Gas: stdTx.Fee.Gas, - Amount: sdk.Coins{fm.getNativeFeeToken(ctx, stdTx.Fee.Amount)}, // consume gas - } + totalNativeFee := fm.getNativeFeeToken(ctx, stdTx.Fee.Amount) //If all gas has been consumed, then there is no necessary to run fee refund process if txResult.GasWanted <= txResult.GasUsed { - refundResult = sdk.Coin{ - Denom: fee.Amount[0].Denom, - Amount: fee.Amount[0].Amount, - } - return refundResult, nil + actualCostFee = totalNativeFee + return actualCostFee, nil } unusedGas := txResult.GasWanted - txResult.GasUsed - var refundCoins sdk.Coins - for _,coin := range fee.Amount { - newCoin := sdk.Coin{ - Denom: coin.Denom, - Amount: coin.Amount.Mul(sdk.NewInt(unusedGas)).Div(sdk.NewInt(txResult.GasWanted)), - } - refundCoins = append(refundCoins, newCoin) + refundCoin := sdk.Coin{ + Denom: totalNativeFee.Denom, + Amount: totalNativeFee.Amount.Mul(sdk.NewInt(unusedGas)).Div(sdk.NewInt(txResult.GasWanted)), } - coins := am.GetAccount(ctx, firstAccount.GetAddress()).GetCoins() // consume gas - err = firstAccount.SetCoins(coins.Plus(refundCoins)) + coins := am.GetAccount(ctx, firstAccount.GetAddress()).GetCoins() // consume gas + err = firstAccount.SetCoins(coins.Plus(sdk.Coins{refundCoin})) if err != nil { return sdk.Coin{}, err } - am.SetAccount(ctx, firstAccount) // consume gas - fck.RefundCollectedFees(ctx, refundCoins) // consume gas - // There must be just one fee token - refundResult = sdk.Coin{ - Denom: fee.Amount[0].Denom, - Amount: fee.Amount[0].Amount.Mul(sdk.NewInt(txResult.GasUsed)).Div(sdk.NewInt(txResult.GasWanted)), - } + am.SetAccount(ctx, firstAccount) + fck.RefundCollectedFees(ctx, sdk.Coins{refundCoin}) - return refundResult, nil + actualCostFee = sdk.Coin{ + Denom: totalNativeFee.Denom, + Amount: totalNativeFee.Amount.Sub(refundCoin.Amount), + } + return actualCostFee, nil } } +// Type declaration for parameters +func ParamTypeTable() params.TypeTable { + return params.NewTypeTable( + nativeFeeTokenKey, "", + nativeGasPriceThresholdKey, "", + ) +} + // FeeManager do fee tokens preprocess according to fee token configuration type FeeManager struct { - ps params.Setter + // The reference to the Paramstore to get and set gov specific params + paramSpace params.Subspace } -func NewFeeManager(ps params.Setter) FeeManager { +func NewFeeManager(paramSpace params.Subspace) FeeManager { return FeeManager{ - ps:ps, + paramSpace: paramSpace.WithTypeTable(ParamTypeTable()), } } func (fck FeeManager) getNativeFeeToken(ctx sdk.Context, coins sdk.Coins) sdk.Coin { - nativeFeeToken, err := fck.ps.GetString(ctx, nativeFeeTokenKey) - if err != nil { - panic(err) - } - for _,coin := range coins { + var nativeFeeToken string + fck.paramSpace.Get(ctx, nativeFeeTokenKey, &nativeFeeToken) + for _, coin := range coins { if coin.Denom == nativeFeeToken { + if coin.Amount.BigInt() == nil { + return sdk.Coin{ + Denom: coin.Denom, + Amount: sdk.ZeroInt(), + } + } return coin } } - return sdk.Coin{} + return sdk.Coin{ + Denom: "", + Amount: sdk.ZeroInt(), + } } func (fck FeeManager) feePreprocess(ctx sdk.Context, coins sdk.Coins, gasLimit int64) sdk.Error { if gasLimit <= 0 { return sdk.ErrInternal(fmt.Sprintf("gaslimit %d should be larger than 0", gasLimit)) } - nativeFeeToken, err := fck.ps.GetString(ctx, nativeFeeTokenKey) - if err != nil { - panic(err) - } - nativeGasPriceThreshold, err := fck.ps.GetString(ctx, nativeGasPriceThresholdKey) - if err != nil { - panic(err) - } + var nativeFeeToken string + fck.paramSpace.Get(ctx, nativeFeeTokenKey, &nativeFeeToken) + + var nativeGasPriceThreshold string + fck.paramSpace.Get(ctx, nativeGasPriceThresholdKey, &nativeGasPriceThreshold) + threshold, ok := sdk.NewIntFromString(nativeGasPriceThreshold) if !ok { panic(errors.New("failed to parse gas price from string")) @@ -171,11 +171,11 @@ func (fck FeeManager) feePreprocess(ctx sdk.Context, coins sdk.Coins, gasLimit i } type FeeGenesisStateConfig struct { - FeeTokenNative string `json:"fee_token_native"` - GasPriceThreshold int64 `json:"gas_price_threshold"` + FeeTokenNative string `json:"fee_token_native"` + GasPriceThreshold int64 `json:"gas_price_threshold"` } -func InitGenesis(ctx sdk.Context, ps params.Setter, data FeeGenesisStateConfig) { - ps.SetString(ctx, nativeFeeTokenKey, data.FeeTokenNative) - ps.SetString(ctx, nativeGasPriceThresholdKey, sdk.NewInt(data.GasPriceThreshold).String()) +func InitGenesis(ctx sdk.Context, ps FeeManager, data FeeGenesisStateConfig) { + ps.paramSpace.Set(ctx, nativeFeeTokenKey, data.FeeTokenNative) + ps.paramSpace.Set(ctx, nativeGasPriceThresholdKey, sdk.NewInt(data.GasPriceThreshold).String()) } diff --git a/baseapp/options.go b/baseapp/options.go index 0a404217a..2363be1ff 100644 --- a/baseapp/options.go +++ b/baseapp/options.go @@ -4,6 +4,11 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/store" + "github.com/irisnet/irishub/types" + dbm "github.com/tendermint/tendermint/libs/db" + qr "github.com/cosmos/cosmos-sdk/baseapp" + ) // File for storing in-package BaseApp optional functions, @@ -26,3 +31,105 @@ func SetPruning(pruning string) func(*BaseApp) { bap.cms.SetPruning(pruningEnum) } } + + +// SetMinimumFees returns an option that sets the minimum fees on the app. +func SetMinimumFees(minFees string) func(*BaseApp) { + fees, err := sdk.ParseCoins(minFees) + if err != nil { + panic(fmt.Sprintf("invalid minimum fees: %v", err)) + } + return func(bap *BaseApp) { bap.SetMinimumFees(fees) } +} + +// nolint - Setter functions +func (app *BaseApp) SetName(name string) { + if app.sealed { + panic("SetName() on sealed BaseApp") + } + app.name = name +} +func (app *BaseApp) SetDB(db dbm.DB) { + if app.sealed { + panic("SetDB() on sealed BaseApp") + } + app.db = db +} +func (app *BaseApp) SetCMS(cms store.CommitMultiStore) { + if app.sealed { + panic("SetEndBlocker() on sealed BaseApp") + } + app.cms = cms +} +func (app *BaseApp) SetTxDecoder(txDecoder sdk.TxDecoder) { + if app.sealed { + panic("SetTxDecoder() on sealed BaseApp") + } + app.txDecoder = txDecoder +} +func (app *BaseApp) SetInitChainer(initChainer sdk.InitChainer) { + if app.sealed { + panic("SetInitChainer() on sealed BaseApp") + } + app.initChainer = initChainer +} +func (app *BaseApp) SetBeginBlocker(beginBlocker sdk.BeginBlocker) { + if app.sealed { + panic("SetBeginBlocker() on sealed BaseApp") + } + app.beginBlocker = beginBlocker +} +func (app *BaseApp) SetEndBlocker(endBlocker sdk.EndBlocker) { + if app.sealed { + panic("SetEndBlocker() on sealed BaseApp") + } + app.endBlocker = endBlocker +} +func (app *BaseApp) SetAnteHandler(ah sdk.AnteHandler) { + if app.sealed { + panic("SetAnteHandler() on sealed BaseApp") + } + app.anteHandler = ah +} +func (app *BaseApp) SetFeeRefundHandler(fh types.FeeRefundHandler) { + if app.sealed { + panic("SetFeeRefundHandler() on sealed BaseApp") + } + app.feeRefundHandler = fh +} +func (app *BaseApp) SetFeePreprocessHandler(fh types.FeePreprocessHandler) { + if app.sealed { + panic("SetFeePreprocessHandler() on sealed BaseApp") + } + app.feePreprocessHandler = fh +} +func (app *BaseApp) SetAddrPeerFilter(pf sdk.PeerFilter) { + if app.sealed { + panic("SetAddrPeerFilter() on sealed BaseApp") + } + app.addrPeerFilter = pf +} +func (app *BaseApp) SetPubKeyPeerFilter(pf sdk.PeerFilter) { + if app.sealed { + panic("SetPubKeyPeerFilter() on sealed BaseApp") + } + app.pubkeyPeerFilter = pf +} +func (app *BaseApp) Router() Router { + //if app.sealed { + // panic("Router() on sealed BaseApp") + //} + return app.router +} + +func (app *BaseApp) QueryRouter() qr.QueryRouter { + return app.queryRouter +} + +func (app *BaseApp) Seal() { app.sealed = true } +func (app *BaseApp) IsSealed() bool { return app.sealed } +func (app *BaseApp) enforceSeal() { + if !app.sealed { + panic("enforceSeal() on BaseApp but not sealed") + } +} diff --git a/baseapp/replay.go b/baseapp/replay.go new file mode 100644 index 000000000..12fa9d426 --- /dev/null +++ b/baseapp/replay.go @@ -0,0 +1,53 @@ +package baseapp + +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" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/node" + sm "github.com/tendermint/tendermint/state" +) + +func Replay(logger log.Logger) 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(fmt.Errorf("there is no block now, can't replay")) + } + var loadHeight int64 + if blockStore.Height() == curState.LastBlockHeight { + logger.Info(fmt.Sprintf("blockstore height equals to current state height %d", curState.LastBlockHeight)) + logger.Info("Just reset state DB to last height") + sm.SaveState(stateDB, preState) + loadHeight = preState.LastBlockHeight + } else if blockStore.Height() == curState.LastBlockHeight+1 { + logger.Info(fmt.Sprintf("blockstore height %d, current state height %d", blockStore.Height(), curState.LastBlockHeight)) + logger.Info(fmt.Sprintf("Retreat block %d in block store and reset state DB to last height", blockStore.Height())) + blockStore.RetreatLastBlock() + sm.SaveState(stateDB, preState) + loadHeight = preState.LastBlockHeight + } else { + panic(fmt.Errorf("tendermint block store height should be at most one ahead of the its state height")) + } + + return loadHeight +} diff --git a/baseapp/router.go b/baseapp/router.go index bea695334..99d106d75 100644 --- a/baseapp/router.go +++ b/baseapp/router.go @@ -39,14 +39,14 @@ func NewRouter() *router { } } -var isAlpha = regexp.MustCompile(`^[a-zA-Z]+$`).MatchString +var isAlphaNumeric = regexp.MustCompile(`^[a-zA-Z0-9]+$`).MatchString // AddRoute - TODO add description //////////////////// iris/cosmos-sdk begin /////////////////////////// func (rtr *router) AddRoute(r string, s []*sdk.KVStoreKey, h sdk.Handler) Router { rstrs := strings.Split(r, "-") - if !isAlpha(rstrs[0]) { + if !isAlphaNumeric(rstrs[0]) { panic("route expressions can only contain alphabet characters") } rtr.routes = append(rtr.routes, route{r, s, h}) diff --git a/baseapp/setters.go b/baseapp/setters.go deleted file mode 100644 index 29e8ce41a..000000000 --- a/baseapp/setters.go +++ /dev/null @@ -1,96 +0,0 @@ -package baseapp - -import ( - dbm "github.com/tendermint/tendermint/libs/db" - - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/irisnet/irishub/types" -) - -// nolint - Setter functions -func (app *BaseApp) SetName(name string) { - if app.sealed { - panic("SetName() on sealed BaseApp") - } - app.name = name -} -func (app *BaseApp) SetDB(db dbm.DB) { - if app.sealed { - panic("SetDB() on sealed BaseApp") - } - app.db = db -} -func (app *BaseApp) SetCMS(cms store.CommitMultiStore) { - if app.sealed { - panic("SetEndBlocker() on sealed BaseApp") - } - app.cms = cms -} -func (app *BaseApp) SetTxDecoder(txDecoder sdk.TxDecoder) { - if app.sealed { - panic("SetTxDecoder() on sealed BaseApp") - } - app.txDecoder = txDecoder -} -func (app *BaseApp) SetInitChainer(initChainer sdk.InitChainer) { - if app.sealed { - panic("SetInitChainer() on sealed BaseApp") - } - app.initChainer = initChainer -} -func (app *BaseApp) SetBeginBlocker(beginBlocker sdk.BeginBlocker) { - if app.sealed { - panic("SetBeginBlocker() on sealed BaseApp") - } - app.beginBlocker = beginBlocker -} -func (app *BaseApp) SetEndBlocker(endBlocker sdk.EndBlocker) { - if app.sealed { - panic("SetEndBlocker() on sealed BaseApp") - } - app.endBlocker = endBlocker -} -func (app *BaseApp) SetAnteHandler(ah sdk.AnteHandler) { - if app.sealed { - panic("SetAnteHandler() on sealed BaseApp") - } - app.anteHandler = ah -} -func (app *BaseApp) SetFeeRefundHandler(fh types.FeeRefundHandler) { - if app.sealed { - panic("SetFeeRefundHandler() on sealed BaseApp") - } - app.feeRefundHandler = fh -} -func (app *BaseApp) SetFeePreprocessHandler(fh types.FeePreprocessHandler) { - if app.sealed { - panic("SetFeePreprocessHandler() on sealed BaseApp") - } - app.feePreprocessHandler = fh -} -func (app *BaseApp) SetAddrPeerFilter(pf sdk.PeerFilter) { - if app.sealed { - panic("SetAddrPeerFilter() on sealed BaseApp") - } - app.addrPeerFilter = pf -} -func (app *BaseApp) SetPubKeyPeerFilter(pf sdk.PeerFilter) { - if app.sealed { - panic("SetPubKeyPeerFilter() on sealed BaseApp") - } - app.pubkeyPeerFilter = pf -} -func (app *BaseApp) Router() Router { - //if app.sealed { - // panic("Router() on sealed BaseApp") - //} - return app.router -} -func (app *BaseApp) Seal() { app.sealed = true } -func (app *BaseApp) IsSealed() bool { return app.sealed } -func (app *BaseApp) enforceSeal() { - if !app.sealed { - panic("enforceSeal() on BaseApp but not sealed") - } -} diff --git a/client/bank/cli/query.go b/client/bank/cli/query.go index c4cea9dd2..23232a05f 100644 --- a/client/bank/cli/query.go +++ b/client/bank/cli/query.go @@ -3,7 +3,7 @@ package cli import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/irisnet/irishub/client/context" "github.com/spf13/cobra" @@ -13,7 +13,7 @@ import ( // GetAccountCmd returns a query account that will display the state of the // account at a given address. // nolint: unparam -func GetAccountCmd(storeName string, cdc *wire.Codec, decoder auth.AccountDecoder) *cobra.Command { +func GetAccountCmd(storeName string, cdc *codec.Codec, decoder auth.AccountDecoder) *cobra.Command { return &cobra.Command{ Use: "account [address]", Short: "Query account balance", @@ -21,9 +21,9 @@ func GetAccountCmd(storeName string, cdc *wire.Codec, decoder auth.AccountDecode Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { // find the key to look up the account - addr := args[0] + addrString := args[0] - key, err := sdk.AccAddressFromBech32(addr) + addr, err := sdk.AccAddressFromBech32(addrString) if err != nil { return err } @@ -32,11 +32,11 @@ func GetAccountCmd(storeName string, cdc *wire.Codec, decoder auth.AccountDecode WithCodec(cdc). WithAccountDecoder(decoder) - if err := cliCtx.EnsureAccountExistsFromAddr(key); err != nil { + if err := cliCtx.EnsureAccountExistsFromAddr(addr); err != nil { return err } - acc, err := cliCtx.GetAccount(key) + acc, err := cliCtx.GetAccount(addr) if err != nil { return err } @@ -46,7 +46,7 @@ func GetAccountCmd(storeName string, cdc *wire.Codec, decoder auth.AccountDecode return err } - output, err := wire.MarshalJSONIndent(cdc, accountRes) + output, err := codec.MarshalJSONIndent(cdc, accountRes) if err != nil { return err } @@ -58,7 +58,7 @@ func GetAccountCmd(storeName string, cdc *wire.Codec, decoder auth.AccountDecode } // GetCmdQueryCoinType performs coin type query -func GetCmdQueryCoinType(cdc *wire.Codec) *cobra.Command { +func GetCmdQueryCoinType(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "coin-type [coin_name]", Short: "query coin type", @@ -70,7 +70,7 @@ func GetCmdQueryCoinType(cdc *wire.Codec) *cobra.Command { if err != nil { return err } - output, err := wire.MarshalJSONIndent(cdc, res) + output, err := codec.MarshalJSONIndent(cdc, res) if err != nil { return err } diff --git a/client/bank/cli/sendTx.go b/client/bank/cli/sendTx.go index 40b911597..f4f89f76e 100644 --- a/client/bank/cli/sendTx.go +++ b/client/bank/cli/sendTx.go @@ -2,15 +2,16 @@ package cli import ( "fmt" + "os" + + "github.com/cosmos/cosmos-sdk/codec" 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/bank" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/utils" "github.com/spf13/cobra" "github.com/spf13/viper" - "os" - "github.com/irisnet/irishub/client/bank" ) const ( @@ -19,18 +20,17 @@ const ( ) // SendTxCmd will create a send tx and sign it with the given key. -func SendTxCmd(cdc *wire.Codec) *cobra.Command { +func SendTxCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "send", - Short: "Create and sign a send tx", + Use: "send", + Short: "Create and sign a send tx", Example: "iriscli bank send --to= --from --fee=0.004iris --chain-id= --amount=10iris", RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext(). WithCodec(cdc). WithLogger(os.Stdout). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - txCtx := context.NewTxContextFromCLI().WithCodec(cdc). - WithCliCtx(cliCtx) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc).WithCliCtx(cliCtx) if err := cliCtx.EnsureAccountExists(); err != nil { return err @@ -44,9 +44,8 @@ func SendTxCmd(cdc *wire.Codec) *cobra.Command { } // parse coins trying to be sent - amountString := viper.GetString(flagAmount) - - coins, err := cliCtx.ParseCoins(amountString) + amount := viper.GetString(flagAmount) + coins, err := cliCtx.ParseCoins(amount) if err != nil { return err } @@ -62,11 +61,15 @@ func SendTxCmd(cdc *wire.Codec) *cobra.Command { } // ensure account has enough coins - if !account.GetCoins().IsGTE(coins) { - return fmt.Errorf("address %s doesn't have enough coins to pay for this transaction", from) + if !account.GetCoins().IsAllGTE(coins) { + return fmt.Errorf("Address %s doesn't have enough coins to pay for this transaction.", from) } + // build and sign the transaction, then broadcast to Tendermint msg := bank.BuildMsg(from, to, coins) + if cliCtx.GenerateOnly { + return utils.PrintUnsignedStdTx(txCtx, cliCtx, []sdk.Msg{msg}, false) + } return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) }, @@ -74,6 +77,8 @@ func SendTxCmd(cdc *wire.Codec) *cobra.Command { cmd.Flags().String(flagTo, "", "Bech32 encoding address to receive coins") cmd.Flags().String(flagAmount, "", "Amount of coins to send, for instance: 10iris") + cmd.MarkFlagRequired(flagTo) + cmd.MarkFlagRequired(flagAmount) return cmd } diff --git a/client/bank/cli/sign.go b/client/bank/cli/sign.go new file mode 100644 index 000000000..c71578dbf --- /dev/null +++ b/client/bank/cli/sign.go @@ -0,0 +1,101 @@ +package cli + +import ( + "fmt" + "io/ioutil" + + "github.com/spf13/viper" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/irisnet/irishub/client" + "github.com/irisnet/irishub/client/context" + "github.com/irisnet/irishub/client/utils" + "github.com/spf13/cobra" + "github.com/tendermint/go-amino" +) + +const ( + flagAppend = "append" + flagPrintSigs = "print-sigs" + flagOffline = "offline" +) + +// GetSignCommand returns the sign command +func GetSignCommand(codec *amino.Codec, decoder auth.AccountDecoder) *cobra.Command { + cmd := &cobra.Command{ + Use: "sign ", + Short: "Sign transactions generated offline", + Long: `Sign transactions created with the --generate-only flag. +Read a transaction from , sign it, and print its JSON encoding. + +The --offline flag makes sure that the client will not reach out to the local cache. +Thus account number or sequence number lookups will not be performed and it is +recommended to set such parameters manually.`, + RunE: makeSignCmd(codec, decoder), + Args: cobra.ExactArgs(1), + } + cmd.Flags().String(client.FlagName, "", "Name of private key with which to sign") + cmd.Flags().Bool(flagAppend, true, "Append the signature to the existing ones. If disabled, old signatures would be overwritten") + cmd.Flags().Bool(flagPrintSigs, false, "Print the addresses that must sign the transaction and those who have already signed it, then exit") + cmd.Flags().Bool(flagOffline, false, "Offline mode. Do not query local cache.") + return cmd +} + +func makeSignCmd(cdc *amino.Codec, decoder auth.AccountDecoder) func(cmd *cobra.Command, args []string) error { + return func(cmd *cobra.Command, args []string) (err error) { + stdTx, err := readAndUnmarshalStdTx(cdc, args[0]) + if err != nil { + return + } + + if viper.GetBool(flagPrintSigs) { + printSignatures(stdTx) + return nil + } + + name := viper.GetString(client.FlagName) + cliCtx := context.NewCLIContext().WithCodec(cdc).WithAccountDecoder(decoder) + txCtx := context.NewTxContextFromCLI() + + newTx, err := utils.SignStdTx(txCtx, cliCtx, name, stdTx, viper.GetBool(flagAppend), viper.GetBool(flagOffline)) + if err != nil { + return err + } + var json []byte + if cliCtx.Indent { + json, err = cdc.MarshalJSONIndent(newTx, "", " ") + } else { + json, err = cdc.MarshalJSON(newTx) + } + if err != nil { + return err + } + fmt.Printf("%s\n", json) + return + } +} + +func printSignatures(stdTx auth.StdTx) { + fmt.Println("Signers:") + for i, signer := range stdTx.GetSigners() { + fmt.Printf(" %v: %v\n", i, signer.String()) + } + fmt.Println("") + fmt.Println("Signatures:") + for i, sig := range stdTx.GetSignatures() { + fmt.Printf(" %v: %v\n", i, sdk.AccAddress(sig.Address()).String()) + } + return +} + +func readAndUnmarshalStdTx(cdc *amino.Codec, filename string) (stdTx auth.StdTx, err error) { + var bytes []byte + if bytes, err = ioutil.ReadFile(filename); err != nil { + return + } + if err = cdc.UnmarshalJSON(bytes, &stdTx); err != nil { + return + } + return +} diff --git a/client/bank/lcd/query.go b/client/bank/lcd/query.go index 686a55dc4..8a6e4acdb 100644 --- a/client/bank/lcd/query.go +++ b/client/bank/lcd/query.go @@ -2,21 +2,25 @@ package lcd import ( "fmt" + "net/http" + + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/gorilla/mux" + "github.com/irisnet/irishub/client/bank" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/utils" - "net/http" - "github.com/irisnet/irishub/client/bank" + "strings" ) -// QueryAccountRequestHandlerFn performs account information query -func QueryAccountRequestHandlerFn(storeName string, cdc *wire.Codec, +// query accountREST Handler +func QueryBalancesRequestHandlerFn( + storeName string, cdc *codec.Codec, decoder auth.AccountDecoder, cliCtx context.CLIContext, ) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") vars := mux.Vars(r) bech32addr := vars["address"] @@ -28,7 +32,7 @@ func QueryAccountRequestHandlerFn(storeName string, cdc *wire.Codec, res, err := cliCtx.QueryStore(auth.AddressStoreKey(addr), storeName) if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("couldn't query account. Error: %s", err.Error())) + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } @@ -41,44 +45,72 @@ func QueryAccountRequestHandlerFn(storeName string, cdc *wire.Codec, // decode the value account, err := decoder(res) if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("couldn't parse query result. Result: %s. Error: %s", res, err.Error())) + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - accountRes, err := bank.ConvertAccountCoin(cliCtx, account) + utils.PostProcessResponse(w, cdc, account.GetCoins(), cliCtx.Indent) + } +} + +// QueryAccountRequestHandlerFn performs account information query +func QueryAccountRequestHandlerFn(storeName string, cdc *codec.Codec, + decoder auth.AccountDecoder, cliCtx context.CLIContext, +) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + bech32addr := vars["address"] + + addr, err := sdk.AccAddressFromBech32(bech32addr) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - // print out whole account - output, err := cdc.MarshalJSONIndent(accountRes, "", " ") + res, err := cliCtx.QueryStore(auth.AddressStoreKey(addr), storeName) + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("couldn't query account. Error: %s", err.Error())) + return + } + + // the query will return empty if there is no data for this account + if len(res) == 0 { + w.WriteHeader(http.StatusNoContent) + return + } + + // decode the value + account, err := decoder(res) if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("couldn't marshall query result. Error: %s", err.Error())) + utils.WriteErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("couldn't parse query result. Result: %s. Error: %s", res, err.Error())) return } - w.Write(output) + accountRes, err := bank.ConvertAccountCoin(cliCtx, account) + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + utils.PostProcessResponse(w, cdc, accountRes, cliCtx.Indent) } } // QueryCoinTypeRequestHandlerFn performs coin type query -func QueryCoinTypeRequestHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext, +func QueryCoinTypeRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext, ) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) coinType := vars["coin-type"] res, err := cliCtx.GetCoinType(coinType) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + if err != nil && strings.Contains(err.Error(),"unsupported coin type") { + w.WriteHeader(http.StatusNoContent) return - } - output, err := wire.MarshalJSONIndent(cdc, res) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + } else if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - w.Write(output) + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) } } diff --git a/client/bank/lcd/rest.go b/client/bank/lcd/rest.go index 850424bed..ff54fdf6d 100644 --- a/client/bank/lcd/rest.go +++ b/client/bank/lcd/rest.go @@ -1,17 +1,25 @@ package lcd import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/gorilla/mux" "github.com/irisnet/irishub/client/context" ) // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Codec) { - r.HandleFunc("/bank/{address}/send", SendRequestHandlerFn(cdc, cliCtx)).Methods("POST") - r.HandleFunc("/bank/accounts/{address}", +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { + r.HandleFunc("/auth/accounts/{address}", QueryAccountRequestHandlerFn("acc", cdc, authcmd.GetAccountDecoder(cdc), cliCtx)).Methods("GET") + + r.HandleFunc("/bank/balances/{address}", + QueryBalancesRequestHandlerFn("acc", cdc, authcmd.GetAccountDecoder(cdc), cliCtx)).Methods("GET") + r.HandleFunc("/bank/accounts/{address}/transfers", SendRequestHandlerFn(cdc, cliCtx)).Methods("POST") r.HandleFunc("/bank/coin/{coin-type}", QueryCoinTypeRequestHandlerFn(cdc, cliCtx)).Methods("GET") + + r.HandleFunc("/tx/sign", SignTxRequestHandlerFn(cdc, cliCtx)).Methods("POST") + r.HandleFunc("/tx/broadcast", BroadcastTxRequestHandlerFn(cdc, cliCtx)).Methods("POST") + + r.HandleFunc("/txs/send", SendTxRequestHandlerFn(cliCtx, cdc)).Methods("POST") } diff --git a/client/bank/lcd/sendtx.go b/client/bank/lcd/sendtx.go index 51c2655ad..1f10748e2 100644 --- a/client/bank/lcd/sendtx.go +++ b/client/bank/lcd/sendtx.go @@ -1,13 +1,18 @@ package lcd import ( + "fmt" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" "github.com/gorilla/mux" "github.com/irisnet/irishub/client/bank" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/utils" "net/http" + "io/ioutil" + "github.com/cosmos/cosmos-sdk/x/auth" + "encoding/json" + "github.com/tendermint/tendermint/crypto" ) type sendBody struct { @@ -18,9 +23,10 @@ type sendBody struct { // SendRequestHandlerFn - http request handler to send coins to a address // nolint: gocyclo -func SendRequestHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func SendRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - // collect data + // Init context and read request parameters + cliCtx = utils.InitReqCliCtx(cliCtx, r) vars := mux.Vars(r) bech32addr := vars["address"] to, err := sdk.AccAddressFromBech32(bech32addr) @@ -33,30 +39,132 @@ func SendRequestHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.Handl if err != nil { return } - cliCtx = utils.InitRequestClictx(cliCtx, r, m.BaseTx.LocalAccountName, m.Sender) - txCtx, err := context.NewTxContextFromBaseTx(cliCtx, cdc, m.BaseTx) + baseReq := m.BaseTx.Sanitize() + if !baseReq.ValidateBasic(w, cliCtx) { + return + } + // Build message + amount, err := cliCtx.ParseCoins(m.Amount) if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - fromAddress, err := cliCtx.GetFromAddress() + sender, err := sdk.AccAddressFromBech32(m.Sender) if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) + return + } + msg := bank.BuildMsg(sender, to, amount) + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } + // Broadcast or return unsigned transaction + utils.SendOrReturnUnsignedTx(w, cliCtx, m.BaseTx, []sdk.Msg{msg}) + } +} - amount, err := cliCtx.ParseCoins(m.Amount) +type broadcastBody struct { + Tx auth.StdTx `json:"tx"` +} + +// BroadcastTxRequestHandlerFn returns the broadcast tx REST handler +func BroadcastTxRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + cliCtx = utils.InitReqCliCtx(cliCtx, r) + var m broadcastBody + if err := utils.ReadPostBody(w, r, cliCtx.Codec, &m); err != nil { + return + } + + txBytes, err := cliCtx.Codec.MarshalBinaryLengthPrefixed(m.Tx) if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - // build message - msg := bank.BuildMsg(fromAddress, to, amount) + res, err := cliCtx.BroadcastTx(txBytes) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - utils.SendOrReturnUnsignedTx(w, cliCtx, txCtx, m.BaseTx, []sdk.Msg{msg}) + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) } } + +type sendTx struct { + Msgs []string `json:"msgs"` + Fee auth.StdFee `json:"fee"` + Signatures []stdSignature `json:"signatures"` + Memo string `json:"memo"` +} + +type stdSignature struct { + PubKey []byte `json:"pub_key"` // optional + Signature []byte `json:"signature"` + AccountNumber int64 `json:"account_number"` + Sequence int64 `json:"sequence"` +} + +func SendTxRequestHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var sendTxBody sendTx + body, err := ioutil.ReadAll(r.Body) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + err = json.Unmarshal(body, &sendTxBody) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + cliCtx = utils.InitReqCliCtx(cliCtx, r) + + var sig = make([]auth.StdSignature, len(sendTxBody.Signatures)) + for index, s := range sendTxBody.Signatures { + var pubkey crypto.PubKey + if err := cdc.UnmarshalBinaryBare(s.PubKey, &pubkey); err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + sig[index].PubKey = pubkey + sig[index].Signature = s.Signature + sig[index].AccountNumber = s.AccountNumber + sig[index].Sequence = s.Sequence + } + + var msgs = make([]sdk.Msg, len(sendTxBody.Msgs)) + for index, msgS := range sendTxBody.Msgs { + var data = []byte(msgS) + var msg sdk.Msg + if err := cdc.UnmarshalJSON(data, &msg); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + msgs[index] = msg + } + + var stdTx = auth.StdTx{ + Msgs: msgs, + Fee: sendTxBody.Fee, + Signatures: sig, + Memo: sendTxBody.Memo, + } + txBytes, err := cdc.MarshalBinaryLengthPrefixed(stdTx) + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + var res interface{} + if cliCtx.Async { + res, err = cliCtx.BroadcastTxAsync(txBytes) + } else { + res, err = cliCtx.BroadcastTx(txBytes) + } + + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) + } +} \ No newline at end of file diff --git a/client/bank/lcd/sign.go b/client/bank/lcd/sign.go new file mode 100644 index 000000000..c57d64f8d --- /dev/null +++ b/client/bank/lcd/sign.go @@ -0,0 +1,55 @@ +package lcd + +import ( + "net/http" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys/keyerror" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/irisnet/irishub/client/context" + "github.com/irisnet/irishub/client/utils" +) + +// SignBody defines the properties of a sign request's body. +type SignBody struct { + Tx auth.StdTx `json:"tx"` + Name string `json:"name"` + Password string `json:"password"` + ChainID string `json:"chain_id"` + AccountNumber int64 `json:"account_number"` + Sequence int64 `json:"sequence"` + AppendSig bool `json:"append_sig"` +} + +// nolint: unparam +// SignTxRequestHandlerFn sign tx REST handler +func SignTxRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var m SignBody + err := utils.ReadPostBody(w, r, cdc, &m) + if err != nil { + return + } + + txCtx := context.TxContext{ + Codec: cliCtx.Codec, + ChainID: m.ChainID, + AccountNumber: m.AccountNumber, + Sequence: m.Sequence, + } + + signedTx, err := txCtx.SignStdTx(m.Name, m.Password, m.Tx, m.AppendSig) + if keyerror.IsErrKeyNotFound(err) { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } else if keyerror.IsErrWrongPassword(err) { + utils.WriteErrorResponse(w, http.StatusUnauthorized, err.Error()) + return + } else if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + utils.PostProcessResponse(w, cdc, signedTx, cliCtx.Indent) + } +} diff --git a/client/bank/common.go b/client/bank/utils.go similarity index 100% rename from client/bank/common.go rename to client/bank/utils.go diff --git a/client/clitest/bank_test.go b/client/clitest/bank_test.go index 1dc463bb3..99c5ea243 100644 --- a/client/clitest/bank_test.go +++ b/client/clitest/bank_test.go @@ -2,31 +2,15 @@ package clitest import ( "fmt" - "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/tests" "github.com/stretchr/testify/require" "testing" - "github.com/irisnet/irishub/app" ) -func init() { - irisHome, iriscliHome = getTestingHomeDirs() -} - func TestIrisCLIBankSend(t *testing.T) { - tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe_reset_all", irisHome), "") - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s foo", iriscliHome), app.DefaultKeyPass) - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s bar", iriscliHome), app.DefaultKeyPass) - chainID, nodeID = executeInit(t, fmt.Sprintf("iris init -o --name=foo --home=%s --home-client=%s", irisHome, iriscliHome)) - executeWrite(t, fmt.Sprintf("iriscli keys add --home=%s bar", iriscliHome), app.DefaultKeyPass) - - err := modifyGenesisFile(irisHome) - require.NoError(t, err) - - // get a free port, also setup some common flags - servAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) + chainID, servAddr, port := initializeFixtures(t) + flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) // start iris server @@ -41,7 +25,7 @@ func TestIrisCLIBankSend(t *testing.T) { fooAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) fooCoin := convertToIrisBaseAccount(t, fooAcc) - require.Equal(t, "100iris", fooCoin) + require.Equal(t, "50iris", fooCoin) executeWrite(t, fmt.Sprintf("iriscli bank send %v --amount=10iris --to=%s --from=foo --gas=10000 --fee=0.04iris", flags, barAddr), app.DefaultKeyPass) tests.WaitForNextNBlocksTM(2, port) @@ -54,8 +38,8 @@ func TestIrisCLIBankSend(t *testing.T) { fooCoin = convertToIrisBaseAccount(t, fooAcc) num := getAmountFromCoinStr(fooCoin) - if !(num > 89 && num < 90) { - t.Error("Test Failed: (89, 90) expected, recieved: {}", num) + if !(num > 39 && num < 40) { + t.Error("Test Failed: (39, 40) expected, recieved: {}", num) } // test autosequencing @@ -70,8 +54,8 @@ func TestIrisCLIBankSend(t *testing.T) { fooCoin = convertToIrisBaseAccount(t, fooAcc) num = getAmountFromCoinStr(fooCoin) - if !(num > 79 && num < 80) { - t.Error("Test Failed: (79, 80) expected, recieved: {}", num) + if !(num > 29 && num < 30) { + t.Error("Test Failed: (29, 30) expected, recieved: {}", num) } // test memo @@ -86,7 +70,7 @@ func TestIrisCLIBankSend(t *testing.T) { fooCoin = convertToIrisBaseAccount(t, fooAcc) num = getAmountFromCoinStr(fooCoin) - if !(num > 69 && num < 70) { + if !(num > 19 && num < 20) { t.Error("Test Failed: (69, 70) expected, recieved: {}", num) } } diff --git a/client/clitest/distribution_test.go b/client/clitest/distribution_test.go new file mode 100644 index 000000000..bf1d14a2d --- /dev/null +++ b/client/clitest/distribution_test.go @@ -0,0 +1,137 @@ +package clitest + +import ( + "fmt" + "testing" + + "github.com/cosmos/cosmos-sdk/tests" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/irisnet/irishub/app" + "github.com/stretchr/testify/require" +) + +func TestIrisCLIDistribution(t *testing.T) { + chainID, servAddr, port := initializeFixtures(t) + + flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) + + // start iris server + proc := tests.GoExecuteTWithStdout(t, fmt.Sprintf("iris start --home=%s --rpc.laddr=%v", irisHome, servAddr)) + + defer proc.Stop(false) + tests.WaitForTMStart(port) + tests.WaitForNextNBlocksTM(2, port) + + fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("iriscli keys show foo --output=json --home=%s", iriscliHome)) + barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("iriscli keys show bar --output=json --home=%s", iriscliHome)) + + fooAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) + fooCoin := convertToIrisBaseAccount(t, fooAcc) + require.Equal(t, "50iris", fooCoin) + + executeWrite(t, fmt.Sprintf("iriscli bank send %v --amount=2iris --to=%s --from=foo --gas=10000 --fee=10iris", flags, barAddr), app.DefaultKeyPass) + tests.WaitForNextNBlocksTM(2, port) + + valAddr := sdk.ValAddress(fooAddr).String() + + withdrawAddress, err := tests.ExecuteT(t, fmt.Sprintf("iriscli distribution withdraw-address %s %s", fooAddr, flags), "") + require.Empty(t, err) + require.Equal(t, "No withdraw address specified. If the delegator does have valid delegations, then the withdraw address should be the same as the delegator address", withdrawAddress) + + executeWrite(t, fmt.Sprintf("iriscli distribution set-withdraw-addr %s --from=foo --fee=0.004iris %s", barAddr, flags), app.DefaultKeyPass) + tests.WaitForNextNBlocksTM(2, port) + + withdrawAddress, err = tests.ExecuteT(t, fmt.Sprintf("iriscli distribution withdraw-address %s %s", fooAddr, flags), "") + require.Empty(t, err) + require.Equal(t, barAddr.String(), withdrawAddress) + + barAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", barAddr, flags)) + barCoin := convertToIrisBaseAccount(t, barAcc) + require.Equal(t, "2iris", barCoin) + num := getAmountFromCoinStr(barCoin) + + ddiList := executeGetDelegatorDistrInfo(t, fmt.Sprintf("iriscli distribution delegator-distr-info %s %s", fooAddr, flags)) + require.Equal(t, 1, len(ddiList)) + require.Equal(t, int64(0), ddiList[0].DelPoolWithdrawalHeight) + require.Equal(t, fooAddr, ddiList[0].DelegatorAddr) + require.Equal(t, valAddr, ddiList[0].ValOperatorAddr.String()) + + ddi := executeGetDelegationDistrInfo(t, fmt.Sprintf("iriscli distribution delegation-distr-info --address-delegator=%s --address-validator=%s %s", fooAddr, valAddr, flags)) + require.Equal(t, int64(0), ddi.DelPoolWithdrawalHeight) + require.Equal(t, fooAddr, ddi.DelegatorAddr) + require.Equal(t, valAddr, ddi.ValOperatorAddr.String()) + + vdi := executeGetValidatorDistrInfo(t, fmt.Sprintf("iriscli distribution validator-distr-info %s %s", valAddr, flags)) + require.Equal(t, valAddr, vdi.OperatorAddr.String()) + require.Equal(t, int64(0), vdi.FeePoolWithdrawalHeight) + numDelPool := getAmountFromCoinStr(vdi.DelPool) + numValCommission := getAmountFromCoinStr(vdi.ValCommission) + require.True(t, numDelPool>numValCommission) + + executeWrite(t, fmt.Sprintf("iriscli distribution withdraw-rewards --from=foo --fee=0.004iris %s", flags), app.DefaultKeyPass) + tests.WaitForNextNBlocksTM(2, port) + + barAcc = executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", barAddr, flags)) + barCoin = convertToIrisBaseAccount(t, barAcc) + numNew := getAmountFromCoinStr(barCoin) + require.True(t, numNew>num) +} + +func TestIrisCLIWithdrawReward(t *testing.T) { + chainID, servAddr, port := initializeFixtures(t) + + flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) + + // start iris server + proc := tests.GoExecuteTWithStdout(t, fmt.Sprintf("iris start --home=%s --rpc.laddr=%v", irisHome, servAddr)) + + defer proc.Stop(false) + tests.WaitForTMStart(port) + tests.WaitForNextNBlocksTM(2, port) + + fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("iriscli keys show foo --output=json --home=%s", iriscliHome)) + barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("iriscli keys show bar --output=json --home=%s", iriscliHome)) + + fooAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) + fooCoin := convertToIrisBaseAccount(t, fooAcc) + require.Equal(t, "50iris", fooCoin) + + executeWrite(t, fmt.Sprintf("iriscli bank send %v --amount=2iris --to=%s --from=foo --gas=10000 --fee=30iris", flags, barAddr), app.DefaultKeyPass) + tests.WaitForNextNBlocksTM(2, port) + + valAddr := sdk.ValAddress(fooAddr).String() + + executeWrite(t, fmt.Sprintf("iriscli distribution set-withdraw-addr %s --from=foo --fee=0.004iris %s", barAddr, flags), app.DefaultKeyPass) + tests.WaitForNextNBlocksTM(2, port) + + vdi := executeGetValidatorDistrInfo(t, fmt.Sprintf("iriscli distribution validator-distr-info %s %s", valAddr, flags)) + require.Equal(t, valAddr, vdi.OperatorAddr.String()) + require.Equal(t, int64(0), vdi.FeePoolWithdrawalHeight) + numDelPool := getAmountFromCoinStr(vdi.DelPool) + numValCommission := getAmountFromCoinStr(vdi.ValCommission) + require.True(t, numDelPool>numValCommission) + + executeWrite(t, fmt.Sprintf("iriscli distribution withdraw-rewards --only-from-validator=%s --from=foo --fee=0.004iris %s", valAddr, flags), app.DefaultKeyPass) + tests.WaitForNextNBlocksTM(2, port) + + barAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", barAddr, flags)) + barCoin := convertToIrisBaseAccount(t, barAcc) + num := getAmountFromCoinStr(barCoin) + require.True(t, num > 10) + + vdi = executeGetValidatorDistrInfo(t, fmt.Sprintf("iriscli distribution validator-distr-info %s %s", valAddr, flags)) + require.Equal(t, valAddr, vdi.OperatorAddr.String()) + numValCommission = getAmountFromCoinStr(vdi.ValCommission) + require.True(t, numValCommission>0) + + executeWrite(t, fmt.Sprintf("iriscli distribution withdraw-rewards --is-validator=true --from=foo --fee=0.004iris %s", flags), app.DefaultKeyPass) + tests.WaitForNextNBlocksTM(2, port) + + barAcc = executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", barAddr, flags)) + barCoin = convertToIrisBaseAccount(t, barAcc) + numNew := getAmountFromCoinStr(barCoin) + + if numNew <= num { + t.Error("Test Failed: if --is-validator is true, more reward should be return") + } +} diff --git a/client/clitest/gov_test.go b/client/clitest/gov_test.go index 405dbaf8b..33f3f976f 100644 --- a/client/clitest/gov_test.go +++ b/client/clitest/gov_test.go @@ -2,7 +2,6 @@ package clitest import ( "fmt" - "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/tests" "github.com/stretchr/testify/require" "testing" @@ -11,23 +10,8 @@ import ( "github.com/irisnet/irishub/modules/gov" ) -func init() { - irisHome, iriscliHome = getTestingHomeDirs() -} - func TestIrisCLISubmitProposal(t *testing.T) { - tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe_reset_all", irisHome), "") - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s foo", iriscliHome), app.DefaultKeyPass) - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s bar", iriscliHome), app.DefaultKeyPass) - chainID, nodeID = executeInit(t, fmt.Sprintf("iris init -o --name=foo --home=%s --home-client=%s", irisHome, iriscliHome)) - executeWrite(t, fmt.Sprintf("iriscli keys add --home=%s bar", iriscliHome), app.DefaultKeyPass) - - err := modifyGenesisFile(irisHome) - require.NoError(t, err) - - // get a free port, also setup some common flags - servAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) + chainID, servAddr, port := initializeFixtures(t) flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) // start iris server @@ -41,9 +25,9 @@ func TestIrisCLISubmitProposal(t *testing.T) { fooAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) fooCoin := convertToIrisBaseAccount(t, fooAcc) - require.Equal(t, "100iris", fooCoin) + require.Equal(t, "50iris", fooCoin) - proposalsQuery := tests.ExecuteT(t, fmt.Sprintf("iriscli gov query-proposals %v", flags), "") + proposalsQuery, _ := tests.ExecuteT(t, fmt.Sprintf("iriscli gov query-proposals %v", flags), "") require.Equal(t, "No matching proposals found", proposalsQuery) // submit a test proposal @@ -62,15 +46,15 @@ func TestIrisCLISubmitProposal(t *testing.T) { fooCoin = convertToIrisBaseAccount(t, fooAcc) num := getAmountFromCoinStr(fooCoin) - if !(num > 94 && num < 95) { - t.Error("Test Failed: (94, 95) expected, recieved: {}", num) + if !(num > 44 && num < 45) { + t.Error("Test Failed: (44, 45) expected, recieved:", num) } proposal1 := executeGetProposal(t, fmt.Sprintf("iriscli gov query-proposal --proposal-id=1 --output=json %v", flags)) - require.Equal(t, int64(1), proposal1.ProposalID) + require.Equal(t, uint64(1), proposal1.ProposalID) require.Equal(t, gov.StatusDepositPeriod, proposal1.Status) - proposalsQuery = tests.ExecuteT(t, fmt.Sprintf("iriscli gov query-proposals %v", flags), "") + proposalsQuery, _ = tests.ExecuteT(t, fmt.Sprintf("iriscli gov query-proposals %v", flags), "") require.Equal(t, " 1 - Test", proposalsQuery) depositStr := fmt.Sprintf("iriscli gov deposit %v", flags) @@ -86,16 +70,14 @@ func TestIrisCLISubmitProposal(t *testing.T) { fooCoin = convertToIrisBaseAccount(t, fooAcc) num = getAmountFromCoinStr(fooCoin) - if !(num > 89 && num < 90) { - t.Error("Test Failed: (89, 90) expected, recieved: {}", num) + if !(num > 39 && num < 40) { + t.Error("Test Failed: (39, 40) expected, recieved: ", num) } proposal1 = executeGetProposal(t, fmt.Sprintf("iriscli gov query-proposal --proposal-id=1 --output=json %v", flags)) - require.Equal(t, int64(1), proposal1.ProposalID) + require.Equal(t, uint64(1), proposal1.ProposalID) require.Equal(t, gov.StatusVotingPeriod, proposal1.Status) - votingStartBlock1 := proposal1.VotingStartBlock - voteStr := fmt.Sprintf("iriscli gov vote %v", flags) voteStr += fmt.Sprintf(" --from=%s", "foo") voteStr += fmt.Sprintf(" --proposal-id=%s", "1") @@ -106,23 +88,23 @@ func TestIrisCLISubmitProposal(t *testing.T) { tests.WaitForNextNBlocksTM(2, port) vote := executeGetVote(t, fmt.Sprintf("iriscli gov query-vote --proposal-id=1 --voter=%s --output=json %v", fooAddr, flags)) - require.Equal(t, int64(1), vote.ProposalID) + require.Equal(t, uint64(1), vote.ProposalID) require.Equal(t, gov.OptionYes, vote.Option) votes := executeGetVotes(t, fmt.Sprintf("iriscli gov query-votes --proposal-id=1 --output=json %v", flags)) require.Len(t, votes, 1) - require.Equal(t, int64(1), votes[0].ProposalID) + require.Equal(t, uint64(1), votes[0].ProposalID) require.Equal(t, gov.OptionYes, votes[0].Option) - proposalsQuery = tests.ExecuteT(t, fmt.Sprintf("iriscli gov query-proposals --status=DepositPeriod %v", flags), "") + proposalsQuery, _ = tests.ExecuteT(t, fmt.Sprintf("iriscli gov query-proposals --status=DepositPeriod %v", flags), "") require.Equal(t, "No matching proposals found", proposalsQuery) - proposalsQuery = tests.ExecuteT(t, fmt.Sprintf("iriscli gov query-proposals --status=VotingPeriod %v", flags), "") + proposalsQuery, _ = tests.ExecuteT(t, fmt.Sprintf("iriscli gov query-proposals --status=VotingPeriod %v", flags), "") require.Equal(t, " 1 - Test", proposalsQuery) - tests.WaitForHeightTM(votingStartBlock1+20, port) + tests.WaitForNextNBlocksTM(20, port) proposal1 = executeGetProposal(t, fmt.Sprintf("iriscli gov query-proposal --proposal-id=1 --output=json %v", flags)) - require.Equal(t, int64(1), proposal1.ProposalID) + require.Equal(t, uint64(1), proposal1.ProposalID) require.Equal(t, gov.StatusPassed, proposal1.Status) // submit a second test proposal @@ -137,6 +119,6 @@ func TestIrisCLISubmitProposal(t *testing.T) { executeWrite(t, spStr, app.DefaultKeyPass) tests.WaitForNextNBlocksTM(2, port) - proposalsQuery = tests.ExecuteT(t, fmt.Sprintf("iriscli gov query-proposals --latest=1 %v", flags), "") + proposalsQuery, _ = tests.ExecuteT(t, fmt.Sprintf("iriscli gov query-proposals --limit=1 %v", flags), "") require.Equal(t, " 2 - Apples", proposalsQuery) } diff --git a/client/clitest/iparam_test.go b/client/clitest/iparam_test.go index d3109e523..f16044863 100644 --- a/client/clitest/iparam_test.go +++ b/client/clitest/iparam_test.go @@ -2,7 +2,6 @@ package clitest import ( "fmt" - "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/tests" "github.com/stretchr/testify/require" "testing" @@ -11,21 +10,8 @@ import ( "github.com/irisnet/irishub/modules/gov" ) -func init() { - irisHome, iriscliHome = getTestingHomeDirs() -} - func TestIrisCLIParameterChangeProposal(t *testing.T) { - tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe_reset_all", irisHome), "") - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s foo", iriscliHome), app.DefaultKeyPass) - chainID, nodeID = executeInit(t, fmt.Sprintf("iris init -o --name=foo --home=%s --home-client=%s", irisHome, iriscliHome)) - - err := modifyGenesisFile(irisHome) - require.NoError(t, err) - - // get a free port, also setup some common flags - servAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) + chainID, servAddr, port := initializeFixtures(t) flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) // start iris server @@ -39,9 +25,9 @@ func TestIrisCLIParameterChangeProposal(t *testing.T) { fooAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) fooCoin := convertToIrisBaseAccount(t, fooAcc) - require.Equal(t, "100iris", fooCoin) + require.Equal(t, "50iris", fooCoin) - proposalsQuery := tests.ExecuteT(t, fmt.Sprintf("iriscli gov query-proposals %v", flags), "") + proposalsQuery, _ := tests.ExecuteT(t, fmt.Sprintf("iriscli gov query-proposals %v", flags), "") require.Equal(t, "No matching proposals found", proposalsQuery) // submit a test proposal @@ -52,7 +38,7 @@ func TestIrisCLIParameterChangeProposal(t *testing.T) { spStr += fmt.Sprintf(" --title=%s", "Test") spStr += fmt.Sprintf(" --description=%s", "test") spStr += fmt.Sprintf(" --fee=%s", "0.004iris") - spStr += fmt.Sprintf(" --param=%s", "{\"key\":\"Gov/gov/DepositProcedure\",\"value\":\"{\\\"min_deposit\\\":[{\\\"denom\\\":\\\"iris-atto\\\",\\\"amount\\\":\\\"10000000000000000000\\\"}],\\\"max_deposit_period\\\":1440}\",\"op\":\"update\"}") + spStr += fmt.Sprintf(" --param=%s", "{\"key\":\"Gov/govDepositProcedure\",\"value\":\"{\\\"min_deposit\\\":[{\\\"denom\\\":\\\"iris-atto\\\",\\\"amount\\\":\\\"10000000000000000000\\\"}],\\\"max_deposit_period\\\":30000000000}\",\"op\":\"update\"}") executeWrite(t, spStr, app.DefaultKeyPass) tests.WaitForNextNBlocksTM(2, port) @@ -61,16 +47,14 @@ func TestIrisCLIParameterChangeProposal(t *testing.T) { fooCoin = convertToIrisBaseAccount(t, fooAcc) num := getAmountFromCoinStr(fooCoin) - if !(num > 89 && num < 90) { - t.Error("Test Failed: (89, 90) expected, recieved: {}", num) + if !(num > 39 && num < 40) { + t.Error("Test Failed: (39, 40) expected, recieved: ", num) } proposal1 := executeGetProposal(t, fmt.Sprintf("iriscli gov query-proposal --proposal-id=1 --output=json %v", flags)) - require.Equal(t, int64(1), proposal1.ProposalID) + require.Equal(t, uint64(1), proposal1.ProposalID) require.Equal(t, gov.StatusVotingPeriod, proposal1.Status) - votingStartBlock1 := proposal1.VotingStartBlock - voteStr := fmt.Sprintf("iriscli gov vote %v", flags) voteStr += fmt.Sprintf(" --from=%s", "foo") voteStr += fmt.Sprintf(" --proposal-id=%s", "1") @@ -81,30 +65,21 @@ func TestIrisCLIParameterChangeProposal(t *testing.T) { tests.WaitForNextNBlocksTM(2, port) vote := executeGetVote(t, fmt.Sprintf("iriscli gov query-vote --proposal-id=1 --voter=%s --output=json %v", fooAddr, flags)) - require.Equal(t, int64(1), vote.ProposalID) + require.Equal(t, uint64(1), vote.ProposalID) require.Equal(t, gov.OptionYes, vote.Option) - tests.WaitForHeightTM(votingStartBlock1+20, port) + tests.WaitForNextNBlocksTM(15, port) proposal1 = executeGetProposal(t, fmt.Sprintf("iriscli gov query-proposal --proposal-id=1 --output=json %v", flags)) - require.Equal(t, int64(1), proposal1.ProposalID) + require.Equal(t, uint64(1), proposal1.ProposalID) require.Equal(t, gov.StatusPassed, proposal1.Status) - param := executeGetParam(t, fmt.Sprintf("iriscli gov query-params --key=%v --output=json %v ","Gov/gov/DepositProcedure",flags)) - require.Equal(t,param,gov.Param{Key:"Gov/gov/DepositProcedure",Value:"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":1440}",Op:""}) + param := executeGetParam(t, fmt.Sprintf("iriscli gov query-params --key=%v --output=json %v ","Gov/govDepositProcedure",flags)) + require.Equal(t,param,gov.Param{Key:"Gov/govDepositProcedure",Value:"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":30000000000}",Op:""}) } func TestIrisCLIQueryParams(t *testing.T) { - tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe_reset_all", irisHome), "") - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s foo", iriscliHome), app.DefaultKeyPass) - chainID, nodeID = executeInit(t, fmt.Sprintf("iris init -o --name=foo --home=%s --home-client=%s", irisHome, iriscliHome)) - - err := modifyGenesisFile(irisHome) - require.NoError(t, err) - - // get a free port, also setup some common flags - servAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) + chainID, servAddr, port := initializeFixtures(t) flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) // start iris server @@ -118,23 +93,14 @@ func TestIrisCLIQueryParams(t *testing.T) { fooAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) fooCoin := convertToIrisBaseAccount(t, fooAcc) - require.Equal(t, "100iris", fooCoin) + require.Equal(t, "50iris", fooCoin) - param := executeGetParam(t, fmt.Sprintf("iriscli gov query-params --key=%v --output=json %v ","Gov/gov/DepositProcedure",flags)) - require.Equal(t,param,gov.Param{Key:"Gov/gov/DepositProcedure",Value:"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":10}",Op:""}) + param := executeGetParam(t, fmt.Sprintf("iriscli gov query-params --key=%v --output=json %v ","Gov/govDepositProcedure",flags)) + require.Equal(t,param,gov.Param{Key:"Gov/govDepositProcedure",Value:"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":60000000000}",Op:""}) } func TestIrisCLIPullParams(t *testing.T) { - tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe_reset_all", irisHome), "") - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s foo", iriscliHome), app.DefaultKeyPass) - chainID, nodeID = executeInit(t, fmt.Sprintf("iris init -o --name=foo --home=%s --home-client=%s", irisHome, iriscliHome)) - - err := modifyGenesisFile(irisHome) - require.NoError(t, err) - - // get a free port, also setup some common flags - servAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) + chainID, servAddr, port := initializeFixtures(t) flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) // start iris server @@ -148,7 +114,7 @@ func TestIrisCLIPullParams(t *testing.T) { fooAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) fooCoin := convertToIrisBaseAccount(t, fooAcc) - require.Equal(t, "100iris", fooCoin) + require.Equal(t, "50iris", fooCoin) tests.ExecuteT(t, fmt.Sprintf("iriscli gov pull-params --path=%v --output=json %v ",irisHome,flags), "") } \ No newline at end of file diff --git a/client/clitest/irismon_test.go b/client/clitest/irismon_test.go index 38592dfbd..b4d9d34b0 100644 --- a/client/clitest/irismon_test.go +++ b/client/clitest/irismon_test.go @@ -7,30 +7,16 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/tests" "github.com/cosmos/cosmos-sdk/server" - "github.com/irisnet/irishub/app" sdk "github.com/cosmos/cosmos-sdk/types" "encoding/hex" "net/http" "time" ) -func init() { - irisHome, iriscliHome = getTestingHomeDirs() -} - func TestIrismon(t *testing.T) { - tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe_reset_all", irisHome), "") - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s foo", iriscliHome), app.DefaultKeyPass) - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s bar", iriscliHome), app.DefaultKeyPass) - chainID, _ := executeInit(t, fmt.Sprintf("iris init -o --name=foo --home=%s --home-client=%s", irisHome, iriscliHome)) - executeWrite(t, fmt.Sprintf("iriscli keys add --home=%s bar", iriscliHome), app.DefaultKeyPass) + t.SkipNow() - err := modifyGenesisFile(irisHome) - require.NoError(t, err) - - // get a free port, also setup some common flags - servAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) + chainID, servAddr, port := initializeFixtures(t) flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) // start iris server @@ -42,7 +28,7 @@ func TestIrismon(t *testing.T) { accountAddress, _ := executeGetAddrPK(t, fmt.Sprintf("iriscli keys show foo --output=json --home=%s", iriscliHome)) validator := executeGetValidator(t, fmt.Sprintf("iriscli stake validator %s --output=json %v", accountAddress, flags)) - pk, err := sdk.GetValPubKeyBech32(validator.PubKey) + pk, err := sdk.GetValPubKeyBech32(validator.ConsPubKey) pkHex := hex.EncodeToString(pk.Bytes()) // get a free port diff --git a/client/clitest/iservice_test.go b/client/clitest/iservice_test.go deleted file mode 100644 index d9e206ca4..000000000 --- a/client/clitest/iservice_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package clitest - -import ( - "testing" - "github.com/cosmos/cosmos-sdk/tests" - "fmt" - "github.com/irisnet/irishub/app" - "io/ioutil" - "os" - "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/server" -) - -func init() { - irisHome, iriscliHome = getTestingHomeDirs() -} - -func TestIrisCLIIserviceDefine(t *testing.T) { - tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe_reset_all", irisHome), "") - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s foo", iriscliHome), app.DefaultKeyPass) - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s bar", iriscliHome), app.DefaultKeyPass) - chainID, _ := executeInit(t, fmt.Sprintf("iris init -o --name=foo --home=%s --home-client=%s", irisHome, iriscliHome)) - executeWrite(t, fmt.Sprintf("iriscli keys add --home=%s bar", iriscliHome), app.DefaultKeyPass) - - err := modifyGenesisFile(irisHome) - require.NoError(t, err) - - // get a free port, also setup some common flags - servAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) - flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) - - // start iris server - proc := tests.GoExecuteTWithStdout(t, fmt.Sprintf("iris start --home=%s --rpc.laddr=%v", irisHome, servAddr)) - - defer proc.Stop(false) - tests.WaitForTMStart(port) - tests.WaitForNextNBlocksTM(2, port) - - fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("iriscli keys show foo --output=json --home=%s", iriscliHome)) - - serviceName := "testService" - - serviceQuery := tests.ExecuteT(t, fmt.Sprintf("iriscli iservice definition --name=%s --def-chain-id=%s %v", serviceName, chainID, flags), "") - require.Equal(t, "", serviceQuery) - - fooAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) - fooCoin := convertToIrisBaseAccount(t, fooAcc) - num := getAmountFromCoinStr(fooCoin) - require.Equal(t, "100iris", fooCoin) - - // iservice define - fileName := iriscliHome + string(os.PathSeparator) + "test.proto" - defer tests.ExecuteT(t, fmt.Sprintf("rm -f %s", fileName), "") - ioutil.WriteFile(fileName, []byte(idlContent), 0644) - sdStr := fmt.Sprintf("iriscli iservice define %v", flags) - sdStr += fmt.Sprintf(" --from=%s", "foo") - sdStr += fmt.Sprintf(" --name=%s", serviceName) - sdStr += fmt.Sprintf(" --service-description=%s", "test") - sdStr += fmt.Sprintf(" --tags=%s", "tag1 tag2") - sdStr += fmt.Sprintf(" --author-description=%s", "foo") - sdStr += fmt.Sprintf(" --broadcast=%s", "Broadcast") - sdStr += fmt.Sprintf(" --file=%s", fileName) - sdStr += fmt.Sprintf(" --fee=%s", "0.004iris") - - executeWrite(t, sdStr, app.DefaultKeyPass) - tests.WaitForNextNBlocksTM(2, port) - - fooAcc = executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) - fooCoin = convertToIrisBaseAccount(t, fooAcc) - num = getAmountFromCoinStr(fooCoin) - - if !(num > 99 && num < 100) { - t.Error("Test Failed: (99, 100) expected, recieved: {}", num) - } - - serviceDef := executeGetServiceDefinition(t, fmt.Sprintf("iriscli iservice definition --name=%s --def-chain-id=%s %v", serviceName, chainID, flags)) - require.Equal(t, serviceName, serviceDef.Name) - - // method test - require.Equal(t, "SayHello", serviceDef.Methods[0].Name) - require.Equal(t, "sayHello", serviceDef.Methods[0].Description) - require.Equal(t, "NoCached", serviceDef.Methods[0].OutputCached.String()) - require.Equal(t, "NoPrivacy", serviceDef.Methods[0].OutputPrivacy.String()) -} - -const idlContent = ` - syntax = "proto3"; - - // The greeting service definition. - service Greeter { - //@Attribute description:sayHello - //@Attribute output_privacy:NoPrivacy - //@Attribute output_cached:NoCached - rpc SayHello (HelloRequest) returns (HelloReply) {} - } - - // The request message containing the user's name. - message HelloRequest { - string name = 1; - } - - // The response message containing the greetings - message HelloReply { - string message = 1; - }` diff --git a/client/clitest/record_test.go b/client/clitest/record_test.go index e59dea2af..998a3506f 100644 --- a/client/clitest/record_test.go +++ b/client/clitest/record_test.go @@ -4,30 +4,14 @@ import ( "fmt" "testing" - "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/tests" "github.com/stretchr/testify/require" "github.com/irisnet/irishub/app" ) -func init() { - irisHome, iriscliHome = getTestingHomeDirs() -} - func TestIrisCLISubmitRecord(t *testing.T) { - tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe_reset_all", irisHome), "") - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s foo", iriscliHome), app.DefaultKeyPass) - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s bar", iriscliHome), app.DefaultKeyPass) - chainID, nodeID = executeInit(t, fmt.Sprintf("iris init -o --name=foo --home=%s --home-client=%s", irisHome, iriscliHome)) - executeWrite(t, fmt.Sprintf("iriscli keys add --home=%s bar", iriscliHome), app.DefaultKeyPass) - - err := modifyGenesisFile(irisHome) - require.NoError(t, err) - - // get a free port, also setup some common flags - servAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) + chainID, servAddr, port := initializeFixtures(t) flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) // start iris server @@ -41,7 +25,7 @@ func TestIrisCLISubmitRecord(t *testing.T) { fooAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) fooCoin := convertToIrisBaseAccount(t, fooAcc) - require.Equal(t, "100iris", fooCoin) + require.Equal(t, "50iris", fooCoin) // submit q first record onchain test srStr := fmt.Sprintf("iriscli record submit %v", flags) @@ -57,7 +41,7 @@ func TestIrisCLISubmitRecord(t *testing.T) { recordID1 := executeGetRecordID(t, fmt.Sprintf("iriscli tendermint tx %v --output json --trust-node=true %v", recordTxHash, flags)) // Submit same record twice - res := tests.ExecuteT(t, srStr, "") + res, _ := tests.ExecuteT(t, srStr, "") require.Equal(t, fmt.Sprintf("Warning: Record ID %v already exists.", string(recordID1)), res) record1 := executeGetRecord(t, fmt.Sprintf("iriscli record query --record-id=%s --output=json %v", recordID1, flags)) @@ -68,8 +52,8 @@ func TestIrisCLISubmitRecord(t *testing.T) { downloadOK := executeDownloadRecord(t, fmt.Sprintf("iriscli record download --record-id=%s --file-name=%s %v", recordID1, "download.txt", flags), iriscliHome+"/download.txt", true) require.Equal(t, true, downloadOK) - res = tests.ExecuteT(t, fmt.Sprintf("iriscli record download --record-id=%s --file-name=%s %v", recordID1, "download.txt", flags), "") - require.Equal(t, fmt.Sprintf("Warning: %s already exists, please try another file name.", iriscliHome+"/download.txt"), res) + res, _ = tests.ExecuteT(t, fmt.Sprintf("iriscli record download --record-id=%s --file-name=%s %v", recordID1, "download.txt", flags), "") + //require.Equal(t, fmt.Sprintf("Warning: %s already exists, please try another file name.", iriscliHome+"/download.txt"), res) // submit a second record onchain test srStr = fmt.Sprintf("iriscli record submit %v", flags) diff --git a/client/clitest/service_test.go b/client/clitest/service_test.go new file mode 100644 index 000000000..552ed4b40 --- /dev/null +++ b/client/clitest/service_test.go @@ -0,0 +1,176 @@ +package clitest + +import ( + "fmt" + "os" + "testing" + "io/ioutil" + + "github.com/cosmos/cosmos-sdk/tests" + "github.com/irisnet/irishub/app" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" +) + +func TestIrisCLIServiceDefine(t *testing.T) { + chainID, servAddr, port := initializeFixtures(t) + flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) + + // start iris server + proc := tests.GoExecuteTWithStdout(t, fmt.Sprintf("iris start --home=%s --rpc.laddr=%v", irisHome, servAddr)) + + defer proc.Stop(false) + tests.WaitForTMStart(port) + tests.WaitForNextNBlocksTM(2, port) + + fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("iriscli keys show foo --output=json --home=%s", iriscliHome)) + barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("iriscli keys show bar --output=json --home=%s", iriscliHome)) + + serviceName := "testService" + + serviceQuery, _ := tests.ExecuteT(t, fmt.Sprintf("iriscli service definition --service-name=%s --def-chain-id=%s %v", serviceName, chainID, flags), "") + require.Equal(t, "", serviceQuery) + + fooAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) + fooCoin := convertToIrisBaseAccount(t, fooAcc) + num := getAmountFromCoinStr(fooCoin) + require.Equal(t, "50iris", fooCoin) + + // service define + fileName := iriscliHome + string(os.PathSeparator) + "test.proto" + defer tests.ExecuteT(t, fmt.Sprintf("rm -f %s", fileName), "") + ioutil.WriteFile(fileName, []byte(idlContent), 0644) + sdStr := fmt.Sprintf("iriscli service define %v", flags) + sdStr += fmt.Sprintf(" --from=%s", "foo") + sdStr += fmt.Sprintf(" --service-name=%s", serviceName) + sdStr += fmt.Sprintf(" --service-description=%s", "test") + sdStr += fmt.Sprintf(" --tags=%s", "tag1,tag2") + sdStr += fmt.Sprintf(" --author-description=%s", "foo") + sdStr += fmt.Sprintf(" --file=%s", fileName) + sdStr += fmt.Sprintf(" --fee=%s", "0.004iris") + + executeWrite(t, sdStr, app.DefaultKeyPass) + tests.WaitForNextNBlocksTM(2, port) + + fooAcc = executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) + fooCoin = convertToIrisBaseAccount(t, fooAcc) + num = getAmountFromCoinStr(fooCoin) + + if !(num > 49 && num < 50) { + t.Error("Test Failed: (49, 50) expected, recieved: {}", num) + } + + serviceDef := executeGetServiceDefinition(t, fmt.Sprintf("iriscli service definition --service-name=%s --def-chain-id=%s %v", serviceName, chainID, flags)) + require.Equal(t, serviceName, serviceDef.Name) + + // method test + require.Equal(t, "SayHello", serviceDef.Methods[0].Name) + require.Equal(t, "sayHello", serviceDef.Methods[0].Description) + require.Equal(t, "NoCached", serviceDef.Methods[0].OutputCached.String()) + require.Equal(t, "NoPrivacy", serviceDef.Methods[0].OutputPrivacy.String()) + + // binding test + sdStr = fmt.Sprintf("iriscli service bind %v", flags) + sdStr += fmt.Sprintf(" --service-name=%s", serviceName) + sdStr += fmt.Sprintf(" --def-chain-id=%s", chainID) + sdStr += fmt.Sprintf(" --bind-type=%s", "Local") + sdStr += fmt.Sprintf(" --deposit=%s", "10iris") + sdStr += fmt.Sprintf(" --prices=%s", "1iris") + sdStr += fmt.Sprintf(" --avg-rsp-time=%d", 10000) + sdStr += fmt.Sprintf(" --usable-time=%d", 10000) + sdStr += fmt.Sprintf(" --fee=%s", "0.004iris") + + sdStrFoo := sdStr + fmt.Sprintf(" --from=%s", "foo") + sdStrBar := sdStr + fmt.Sprintf(" --from=%s", "bar") + + executeWrite(t, sdStrFoo, app.DefaultKeyPass) + tests.WaitForNextNBlocksTM(2, port) + + fooAcc = executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) + fooCoin = convertToIrisBaseAccount(t, fooAcc) + num = getAmountFromCoinStr(fooCoin) + + if !(num > 39 && num < 40) { + t.Error("Test Failed: (39, 40) expected, recieved: {}", num) + } + + executeWrite(t, fmt.Sprintf("iriscli bank send --to=%s --from=%s --amount=20iris --fee=0.004iris %v", barAddr.String(), "foo", flags), app.DefaultKeyPass) + tests.WaitForNextNBlocksTM(2, port) + executeWrite(t, sdStrBar, app.DefaultKeyPass) + tests.WaitForNextNBlocksTM(2, port) + barAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", barAddr, flags)) + barCoin := convertToIrisBaseAccount(t, barAcc) + barNum := getAmountFromCoinStr(barCoin) + + if !(barNum > 9 && barNum < 10) { + t.Error("Test Failed: (9, 10) expected, recieved: {}", barNum) + } + + serviceBinding := executeGetServiceBinding(t, fmt.Sprintf("iriscli service binding --service-name=%s --def-chain-id=%s --bind-chain-id=%s --provider=%s %v", serviceName, chainID, chainID, fooAddr.String(), flags)) + require.NotNil(t, serviceBinding) + + serviceBindings := executeGetServiceBindings(t, fmt.Sprintf("iriscli service bindings --service-name=%s --def-chain-id=%s %v", serviceName, chainID, flags)) + require.Equal(t, 2, len(serviceBindings)) + + // binding update test + sdStr = fmt.Sprintf("iriscli service update-binding %v", flags) + sdStr += fmt.Sprintf(" --service-name=%s", serviceName) + sdStr += fmt.Sprintf(" --def-chain-id=%s", chainID) + sdStr += fmt.Sprintf(" --bind-type=%s", "Global") + sdStr += fmt.Sprintf(" --deposit=%s", "1iris") + sdStr += fmt.Sprintf(" --prices=%s", "5iris") + sdStr += fmt.Sprintf(" --avg-rsp-time=%d", 99) + sdStr += fmt.Sprintf(" --usable-time=%d", 99) + sdStr += fmt.Sprintf(" --fee=%s", "0.004iris") + sdStr += fmt.Sprintf(" --from=%s", "bar") + executeWrite(t, sdStr, app.DefaultKeyPass) + tests.WaitForNextNBlocksTM(2, port) + barAcc = executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", barAddr, flags)) + barCoin = convertToIrisBaseAccount(t, barAcc) + barNum = getAmountFromCoinStr(barCoin) + + if !(barNum > 8 && barNum < 9) { + t.Error("Test Failed: (8, 9) expected, recieved: {}", barNum) + } + serviceBindings = executeGetServiceBindings(t, fmt.Sprintf("iriscli service bindings --service-name=%s --def-chain-id=%s %v", serviceName, chainID, flags)) + var totalDeposit sdk.Coins + for _, bind := range serviceBindings { + totalDeposit = totalDeposit.Plus(bind.Deposit) + } + require.Equal(t, "21000000000000000000iris-atto", totalDeposit.String()) + + // disable binding + executeWrite(t, fmt.Sprintf("iriscli service disable --def-chain-id=%s --service-name=%s --from=%s --fee=0.004iris %v", chainID, serviceName, "bar", flags), app.DefaultKeyPass) + + // refund-deposit test + tests.WaitForNextNBlocksTM(12, port) + executeWrite(t, fmt.Sprintf("iriscli service refund-deposit --service-name=%s --def-chain-id=%s --from=%s --fee=0.004iris %v", serviceName, chainID, "bar", flags), app.DefaultKeyPass) + tests.WaitForNextNBlocksTM(2, port) + barAcc = executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", barAddr, flags)) + barCoin = convertToIrisBaseAccount(t, barAcc) + barNum = getAmountFromCoinStr(barCoin) + if !(barNum > 19 && barNum < 20) { + t.Error("Test Failed: (19, 20) expected, recieved: {}", barNum) + } +} + +const idlContent = ` + syntax = "proto3"; + + // The greeting service definition. + service Greeter { + //@Attribute description:sayHello + //@Attribute output_privacy:NoPrivacy + //@Attribute output_cached:NoCached + rpc SayHello (HelloRequest) returns (HelloReply) {} + } + + // The request message containing the user's name. + message HelloRequest { + string name = 1; + } + + // The response message containing the greetings + message HelloReply { + string message = 1; + }` diff --git a/client/clitest/stake_test.go b/client/clitest/stake_test.go index 9ea22ca94..1c4c0938b 100644 --- a/client/clitest/stake_test.go +++ b/client/clitest/stake_test.go @@ -2,32 +2,16 @@ package clitest import ( "fmt" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/tests" - "github.com/stretchr/testify/require" "testing" - "github.com/irisnet/irishub/app" + "github.com/cosmos/cosmos-sdk/tests" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/irisnet/irishub/app" + "github.com/stretchr/testify/require" ) -func init() { - irisHome, iriscliHome = getTestingHomeDirs() -} - func TestIrisCLIStakeCreateValidator(t *testing.T) { - tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe_reset_all", irisHome), "") - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s foo", iriscliHome), app.DefaultKeyPass) - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s bar", iriscliHome), app.DefaultKeyPass) - chainID, nodeID = executeInit(t, fmt.Sprintf("iris init -o --name=foo --home=%s --home-client=%s", irisHome, iriscliHome)) - executeWrite(t, fmt.Sprintf("iriscli keys add --home=%s bar", iriscliHome), app.DefaultKeyPass) - - err := modifyGenesisFile(irisHome) - require.NoError(t, err) - - // get a free port, also setup some common flags - servAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) + chainID, servAddr, port := initializeFixtures(t) flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) // start iris server @@ -38,8 +22,10 @@ func TestIrisCLIStakeCreateValidator(t *testing.T) { tests.WaitForNextNBlocksTM(2, port) fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf("iriscli keys show foo --output=json --home=%s", iriscliHome)) - barAddr, barPubKey := executeGetAddrPK(t, fmt.Sprintf("iriscli keys show bar --output=json --home=%s", iriscliHome)) - barCeshPubKey := sdk.MustBech32ifyValPub(barPubKey) + barAddr, _ := executeGetAddrPK(t, fmt.Sprintf("iriscli keys show bar --output=json --home=%s", iriscliHome)) + + irisHomeB, _ := getTestingHomeDirsB() + barCeshPubKey := executeGetValidatorPK(t, fmt.Sprintf("iris tendermint show-validator --home=%s", irisHomeB)) executeWrite(t, fmt.Sprintf("iriscli bank send %v --amount=10iris --to=%s --from=foo --gas=10000 --fee=0.04iris", flags, barAddr), app.DefaultKeyPass) tests.WaitForNextNBlocksTM(2, port) @@ -52,8 +38,8 @@ func TestIrisCLIStakeCreateValidator(t *testing.T) { fooCoin := convertToIrisBaseAccount(t, fooAcc) num := getAmountFromCoinStr(fooCoin) - if !(num > 89 && num < 90) { - t.Error("Test Failed: (89, 90) expected, recieved: {}", num) + if !(num > 39 && num < 40) { + t.Error("Test Failed: (39, 40) expected, recieved: {}", num) } // create validator @@ -63,6 +49,9 @@ func TestIrisCLIStakeCreateValidator(t *testing.T) { cvStr += fmt.Sprintf(" --amount=%v", "2iris") cvStr += fmt.Sprintf(" --moniker=%v", "bar-vally") cvStr += fmt.Sprintf(" --fee=%s", "0.004iris") + cvStr += fmt.Sprintf(" --commission-max-change-rate=%s", "0.01") + cvStr += fmt.Sprintf(" --commission-max-rate=%s", "0.5") + cvStr += fmt.Sprintf(" --commission-rate=%s", "0.1") executeWrite(t, cvStr, app.DefaultKeyPass) tests.WaitForNextNBlocksTM(2, port) @@ -75,14 +64,15 @@ func TestIrisCLIStakeCreateValidator(t *testing.T) { t.Error("Test Failed: (7, 8) expected, recieved: {}", num) } - validator := executeGetValidator(t, fmt.Sprintf("iriscli stake validator %s --output=json %v", barAddr, flags)) - require.Equal(t, validator.Owner, barAddr) + valAddr := sdk.ValAddress(barAddr).String() + validator := executeGetValidator(t, fmt.Sprintf("iriscli stake validator %s --output=json %v", valAddr, flags)) + require.Equal(t, valAddr, validator.OperatorAddr.String()) require.Equal(t, "2.0000000000", validator.Tokens) // unbond a single share - unbondStr := fmt.Sprintf("iriscli stake unbond begin %v", flags) + unbondStr := fmt.Sprintf("iriscli stake unbond %v", flags) unbondStr += fmt.Sprintf(" --from=%s", "bar") - unbondStr += fmt.Sprintf(" --address-validator=%s", barAddr) + unbondStr += fmt.Sprintf(" --address-validator=%s", valAddr) unbondStr += fmt.Sprintf(" --shares-amount=%v", "1") unbondStr += fmt.Sprintf(" --fee=%s", "0.004iris") @@ -90,6 +80,6 @@ func TestIrisCLIStakeCreateValidator(t *testing.T) { require.True(t, success) tests.WaitForNextNBlocksTM(2, port) - validator = executeGetValidator(t, fmt.Sprintf("iriscli stake validator %s --output=json %v", barAddr, flags)) + validator = executeGetValidator(t, fmt.Sprintf("iriscli stake validator %s --output=json %v", valAddr, flags)) require.Equal(t, "1.0000000000", validator.Tokens) } diff --git a/client/clitest/upgrade_test.go b/client/clitest/upgrade_test.go index c46f6e984..db9708a49 100644 --- a/client/clitest/upgrade_test.go +++ b/client/clitest/upgrade_test.go @@ -2,39 +2,26 @@ package clitest import ( "fmt" + "testing" + "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/tests" "github.com/stretchr/testify/require" - "testing" "github.com/irisnet/irishub/app" //sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/irisnet/irishub/modules/gov" "sync" + + "github.com/irisnet/irishub/modules/gov" ) var ( lastSwitchHeight int64 - wg sync.WaitGroup + wg sync.WaitGroup ) -func init() { - irisHome, iriscliHome = getTestingHomeDirs() -} - func TestIrisCLISoftwareUpgrade(t *testing.T) { - tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe_reset_all", irisHome), "") - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s foo", iriscliHome), app.DefaultKeyPass) - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s bar", iriscliHome), app.DefaultKeyPass) - chainID, nodeID = executeInit(t, fmt.Sprintf("iris init -o --name=foo --home=%s --home-client=%s", irisHome, iriscliHome)) - executeWrite(t, fmt.Sprintf("iriscli keys add --home=%s bar", iriscliHome), app.DefaultKeyPass) - - err := modifyGenesisFile(irisHome) - require.NoError(t, err) - - // get a free port, also setup some common flags - servAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) + chainID, servAddr, port := initializeFixtures(t) flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) // start iris server @@ -48,11 +35,11 @@ func TestIrisCLISoftwareUpgrade(t *testing.T) { fooAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) fooCoin := convertToIrisBaseAccount(t, fooAcc) - require.Equal(t, "100iris", fooCoin) + require.Equal(t, "50iris", fooCoin) // check the upgrade info upgradeInfo := executeGetUpgradeInfo(t, fmt.Sprintf("iriscli upgrade info --output=json %v", flags)) - require.Equal(t, int64(-1), upgradeInfo.CurrentProposalId) + require.Equal(t, uint64(0), upgradeInfo.CurrentProposalId) require.Equal(t, int64(0), upgradeInfo.Verion.Id) /////////////////// Upgrade Proposal ///////////////////////////////// @@ -69,11 +56,9 @@ func TestIrisCLISoftwareUpgrade(t *testing.T) { tests.WaitForNextNBlocksTM(2, port) proposal1 := executeGetProposal(t, fmt.Sprintf("iriscli gov query-proposal --proposal-id=1 --output=json %v", flags)) - require.Equal(t, int64(1), proposal1.ProposalID) + require.Equal(t, uint64(1), proposal1.ProposalID) require.Equal(t, gov.StatusVotingPeriod, proposal1.Status) - votingStartBlock1 := proposal1.VotingStartBlock - voteStr := fmt.Sprintf("iriscli gov vote %v", flags) voteStr += fmt.Sprintf(" --from=%s", "foo") voteStr += fmt.Sprintf(" --proposal-id=%s", "1") @@ -85,12 +70,12 @@ func TestIrisCLISoftwareUpgrade(t *testing.T) { votes := executeGetVotes(t, fmt.Sprintf("iriscli gov query-votes --proposal-id=1 --output=json %v", flags)) require.Len(t, votes, 1) - require.Equal(t, int64(1), votes[0].ProposalID) + require.Equal(t, uint64(1), votes[0].ProposalID) require.Equal(t, gov.OptionYes, votes[0].Option) - tests.WaitForHeightTM(votingStartBlock1+12, port) + tests.WaitForNextNBlocksTM(12, port) proposal1 = executeGetProposal(t, fmt.Sprintf("iriscli gov query-proposal --proposal-id=1 --output=json %v", flags)) - require.Equal(t, int64(1), proposal1.ProposalID) + require.Equal(t, uint64(1), proposal1.ProposalID) require.Equal(t, gov.StatusPassed, proposal1.Status) /////////////// Stop and Run new version Software //////////////////// @@ -106,14 +91,14 @@ func TestIrisCLISoftwareUpgrade(t *testing.T) { // check the upgrade info upgradeInfo = executeGetUpgradeInfo(t, fmt.Sprintf("iriscli1 upgrade info --output=json %v", flags)) - require.Equal(t, int64(1), upgradeInfo.CurrentProposalId) - require.Equal(t, votingStartBlock1+10, upgradeInfo.CurrentProposalAcceptHeight) + require.Equal(t, uint64(1), upgradeInfo.CurrentProposalId) + //require.Equal(t, votingStartBlock1+10, upgradeInfo.CurrentProposalAcceptHeight) require.Equal(t, int64(0), upgradeInfo.Verion.Id) // submit switch msg switchStr := fmt.Sprintf("iriscli1 upgrade submit-switch %v", flags) switchStr += fmt.Sprintf(" --from=%s", "foo") - switchStr += fmt.Sprintf(" --proposalID=%s", "1") + switchStr += fmt.Sprintf(" --proposal-id=%s", "1") switchStr += fmt.Sprintf(" --title=%s", "Upgrade") switchStr += fmt.Sprintf(" --fee=%s", "0.004iris") @@ -121,8 +106,8 @@ func TestIrisCLISoftwareUpgrade(t *testing.T) { tests.WaitForNextNBlocksTM(2, port) // check switch msg - switchMsg := executeGetSwitch(t, fmt.Sprintf("iriscli1 upgrade query-switch --proposalID=1 --voter=%v --output=json %v", fooAddr.String(), flags)) - require.Equal(t, int64(1), switchMsg.ProposalID) + switchMsg := executeGetSwitch(t, fmt.Sprintf("iriscli1 upgrade query-switch --proposal-id=1 --voter=%v --output=json %v", fooAddr.String(), flags)) + require.Equal(t, uint64(1), switchMsg.ProposalID) require.Equal(t, "Upgrade", switchMsg.Title) // check whether switched to the new version @@ -130,10 +115,14 @@ func TestIrisCLISoftwareUpgrade(t *testing.T) { tests.WaitForHeightTM(lastSwitchHeight, port) upgradeInfo = executeGetUpgradeInfo(t, fmt.Sprintf("iriscli1 upgrade info --output=json %v", flags)) - require.Equal(t, int64(-1), upgradeInfo.CurrentProposalId) - require.Equal(t, votingStartBlock1+10, upgradeInfo.CurrentProposalAcceptHeight) + require.Equal(t, uint64(0), upgradeInfo.CurrentProposalId) + //require.Equal(t, votingStartBlock1+10, upgradeInfo.CurrentProposalAcceptHeight) require.Equal(t, int64(1), upgradeInfo.Verion.Id) + //////////////////// replay from version 0 for new coming node ///////////////////////////// + /// start a old node with old version and then use a new version to start + startOldNodeBToReplay(t, chainID) + //////////////////////////////// Bugfix Software Upgrade //////////////////////////////// /////////////////// Upgrade Proposal ///////////////////////////////// @@ -150,10 +139,10 @@ func TestIrisCLISoftwareUpgrade(t *testing.T) { tests.WaitForNextNBlocksTM(2, port) proposal2 := executeGetProposal(t, fmt.Sprintf("iriscli1 gov query-proposal --proposal-id=2 --output=json %v", flags)) - require.Equal(t, int64(2), proposal2.ProposalID) + require.Equal(t, uint64(2), proposal2.ProposalID) require.Equal(t, gov.StatusVotingPeriod, proposal2.Status) - votingStartBlock2 := proposal2.VotingStartBlock + //votingStartBlock2 := proposal2.VotingStartBlock voteStr = fmt.Sprintf("iriscli1 gov vote %v", flags) voteStr += fmt.Sprintf(" --from=%s", "foo") @@ -166,12 +155,12 @@ func TestIrisCLISoftwareUpgrade(t *testing.T) { votes = executeGetVotes(t, fmt.Sprintf("iriscli1 gov query-votes --proposal-id=2 --output=json %v", flags)) require.Len(t, votes, 1) - require.Equal(t, int64(2), votes[0].ProposalID) + require.Equal(t, uint64(2), votes[0].ProposalID) require.Equal(t, gov.OptionYes, votes[0].Option) - tests.WaitForHeightTM(votingStartBlock2+12, port) + tests.WaitForNextNBlocksTM(12, port) proposal2 = executeGetProposal(t, fmt.Sprintf("iriscli1 gov query-proposal --proposal-id=2 --output=json %v", flags)) - require.Equal(t, int64(2), proposal2.ProposalID) + require.Equal(t, uint64(2), proposal2.ProposalID) require.Equal(t, gov.StatusPassed, proposal2.Status) /////////////// Stop and Run new version Software //////////////////// @@ -187,14 +176,14 @@ func TestIrisCLISoftwareUpgrade(t *testing.T) { // check the upgrade info upgradeInfo = executeGetUpgradeInfo(t, fmt.Sprintf("iriscli2-bugfix upgrade info --output=json %v", flags)) - require.Equal(t, int64(2), upgradeInfo.CurrentProposalId) - require.Equal(t, votingStartBlock2+10, upgradeInfo.CurrentProposalAcceptHeight) + require.Equal(t, uint64(2), upgradeInfo.CurrentProposalId) + //require.Equal(t, votingStartBlock2+10, upgradeInfo.CurrentProposalAcceptHeight) require.Equal(t, int64(1), upgradeInfo.Verion.Id) // submit switch msg switchStr = fmt.Sprintf("iriscli2-bugfix upgrade submit-switch %v", flags) switchStr += fmt.Sprintf(" --from=%s", "foo") - switchStr += fmt.Sprintf(" --proposalID=%s", "2") + switchStr += fmt.Sprintf(" --proposal-id=%s", "2") switchStr += fmt.Sprintf(" --title=%s", "Upgrade") switchStr += fmt.Sprintf(" --fee=%s", "0.004iris") @@ -202,8 +191,8 @@ func TestIrisCLISoftwareUpgrade(t *testing.T) { tests.WaitForNextNBlocksTM(2, port) // check switch msg - switchMsg = executeGetSwitch(t, fmt.Sprintf("iriscli2-bugfix upgrade query-switch --proposalID=2 --voter=%v --output=json %v", fooAddr.String(), flags)) - require.Equal(t, int64(2), switchMsg.ProposalID) + switchMsg = executeGetSwitch(t, fmt.Sprintf("iriscli2-bugfix upgrade query-switch --proposal-id=2 --voter=%v --output=json %v", fooAddr.String(), flags)) + require.Equal(t, uint64(2), switchMsg.ProposalID) require.Equal(t, "Upgrade", switchMsg.Title) // check whether switched to the new version @@ -211,29 +200,66 @@ func TestIrisCLISoftwareUpgrade(t *testing.T) { tests.WaitForHeightTM(lastSwitchHeight, port) upgradeInfo = executeGetUpgradeInfo(t, fmt.Sprintf("iriscli2-bugfix upgrade info --output=json %v", flags)) - require.Equal(t, int64(-1), upgradeInfo.CurrentProposalId) - require.Equal(t, votingStartBlock2+10, upgradeInfo.CurrentProposalAcceptHeight) + require.Equal(t, uint64(0), upgradeInfo.CurrentProposalId) + //require.Equal(t, votingStartBlock2+10, upgradeInfo.CurrentProposalAcceptHeight) require.Equal(t, int64(2), upgradeInfo.Verion.Id) //////////////////// replay from version 0 for new coming node ///////////////////////////// /// start a new node - go startNodeBToReplay(t) + go startNodeBToReplay(t, chainID) wg.Add(1) wg.Wait() proc2.Stop(true) } -func startNodeBToReplay(t *testing.T) { +func startOldNodeBToReplay(t *testing.T, chainID string) { irisBHome, iriscliBHome := getTestingHomeDirsB() require.True(t, irisBHome != irisHome) require.True(t, iriscliBHome != iriscliHome) - tests.ExecuteT(t, fmt.Sprintf("iris2-bugfix --home=%s unsafe_reset_all", irisBHome), "") + tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe-reset-all", irisBHome), "") + executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s foo", iriscliBHome), app.DefaultKeyPass) + executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s bar", iriscliBHome), app.DefaultKeyPass) + executeWrite(t, fmt.Sprintf("iriscli keys add --home=%s foo", iriscliBHome), app.DefaultKeyPass) + executeInit(t, fmt.Sprintf("iris init -o --moniker=foo --home=%s", irisBHome)) + + err := setupGenesisAndConfig(irisHome, irisBHome) + require.NoError(t, err) + + // get a free port, also setup some common flags + servAddr, port, err := server.FreeTCPAddr() + require.NoError(t, err) + flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliBHome, servAddr, chainID) + + // start old iris server + tests.ExecuteT(t, fmt.Sprintf("iris start --home=%s --rpc.laddr=%v", irisBHome, servAddr), "") + + // start new iris2-bugfix server + proc3 := tests.GoExecuteTWithStdout(t, fmt.Sprintf("iris1 start --replay --home=%s --rpc.laddr=%v", irisBHome, servAddr)) + defer proc3.Stop(false) + + tests.WaitForTMStart(port) + tests.WaitForHeightTM(lastSwitchHeight+10, port) + + // check the upgrade info + upgradeInfo := executeGetUpgradeInfo(t, fmt.Sprintf("iriscli1 upgrade info --output=json %v", flags)) + require.Equal(t, uint64(0), upgradeInfo.CurrentProposalId) + require.Equal(t, int64(1), upgradeInfo.Verion.Id) + +} + +func startNodeBToReplay(t *testing.T, chainID string) { + irisBHome, iriscliBHome := getTestingHomeDirsB() + require.True(t, irisBHome != irisHome) + require.True(t, iriscliBHome != iriscliHome) + + tests.ExecuteT(t, fmt.Sprintf("iris2-bugfix --home=%s unsafe-reset-all", irisBHome), "") executeWrite(t, fmt.Sprintf("iriscli2-bugfix keys delete --home=%s foo", iriscliBHome), app.DefaultKeyPass) executeWrite(t, fmt.Sprintf("iriscli2-bugfix keys delete --home=%s bar", iriscliBHome), app.DefaultKeyPass) - executeInit(t, fmt.Sprintf("iris2-bugfix init -o --name=foo --home=%s --home-client=%s", irisBHome, iriscliBHome)) + executeWrite(t, fmt.Sprintf("iriscli2-bugfix keys add --home=%s foo", iriscliBHome), app.DefaultKeyPass) + executeInit(t, fmt.Sprintf("iris2-bugfix init -o --moniker=foo --home=%s", irisBHome)) err := setupGenesisAndConfig(irisHome, irisBHome) require.NoError(t, err) @@ -248,11 +274,11 @@ func startNodeBToReplay(t *testing.T) { defer proc3.Stop(false) tests.WaitForTMStart(port) - tests.WaitForHeightTM(lastSwitchHeight + 10, port) + tests.WaitForHeightTM(lastSwitchHeight+10, port) // check the upgrade info upgradeInfo := executeGetUpgradeInfo(t, fmt.Sprintf("iriscli2-bugfix upgrade info --output=json %v", flags)) - require.Equal(t, int64(-1), upgradeInfo.CurrentProposalId) + require.Equal(t, uint64(0), upgradeInfo.CurrentProposalId) require.Equal(t, int64(2), upgradeInfo.Verion.Id) wg.Done() @@ -260,18 +286,7 @@ func startNodeBToReplay(t *testing.T) { func TestIrisStartTwoNodesToSyncBlocks(t *testing.T) { - tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe_reset_all", irisHome), "") - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s foo", iriscliHome), app.DefaultKeyPass) - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s bar", iriscliHome), app.DefaultKeyPass) - chainID, nodeID = executeInit(t, fmt.Sprintf("iris init -o --name=foo --home=%s --home-client=%s", irisHome, iriscliHome)) - executeWrite(t, fmt.Sprintf("iriscli keys add --home=%s bar", iriscliHome), app.DefaultKeyPass) - - err := modifyGenesisFile(irisHome) - require.NoError(t, err) - - // get a free port, also setup some common flags - servAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) + chainID, servAddr, port := initializeFixtures(t) flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) // start iris server @@ -285,11 +300,11 @@ func TestIrisStartTwoNodesToSyncBlocks(t *testing.T) { fooAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) fooCoin := convertToIrisBaseAccount(t, fooAcc) - require.Equal(t, "100iris", fooCoin) + require.Equal(t, "50iris", fooCoin) //////////////////////// start node B //////////////////////////// - go irisStartNodeB(t) + go irisStartNodeB(t, chainID) wg.Add(1) wg.Wait() @@ -297,23 +312,22 @@ func TestIrisStartTwoNodesToSyncBlocks(t *testing.T) { } -func irisStartNodeB(t *testing.T) { +func irisStartNodeB(t *testing.T, chainID string) { irisBHome, iriscliBHome := getTestingHomeDirsB() require.True(t, irisBHome != irisHome) require.True(t, iriscliBHome != iriscliHome) - tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe_reset_all", irisBHome), "") + tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe-reset-all", irisBHome), "") executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s foo", iriscliBHome), app.DefaultKeyPass) - executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s bar", iriscliBHome), app.DefaultKeyPass) - executeInit(t, fmt.Sprintf("iris init -o --name=foo --home=%s --home-client=%s", irisBHome, iriscliBHome)) - + executeWrite(t, fmt.Sprintf("iriscli keys add --home=%s foo", iriscliBHome), app.DefaultKeyPass) + executeInit(t, fmt.Sprintf("iris init -o --moniker=foo --home=%s", irisBHome)) err := setupGenesisAndConfig(irisHome, irisBHome) require.NoError(t, err) // get a free port, also setup some common flags servAddr, port, err := server.FreeTCPAddr() require.NoError(t, err) - flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliBHome, servAddr, chainID) + flags := fmt.Sprintf("--home=%s --node=%v --chain-id=%v", iriscliHome, servAddr, chainID) // start new iris2-bugfix server proc3 := tests.GoExecuteTWithStdout(t, fmt.Sprintf("iris start --home=%s --rpc.laddr=%v", irisBHome, servAddr)) @@ -326,7 +340,7 @@ func irisStartNodeB(t *testing.T) { fooAcc := executeGetAccount(t, fmt.Sprintf("iriscli bank account %s %v", fooAddr, flags)) fooCoin := convertToIrisBaseAccount(t, fooAcc) - require.Equal(t, "100iris", fooCoin) + require.Equal(t, "50iris", fooCoin) wg.Done() } diff --git a/client/clitest/utils.go b/client/clitest/utils.go index c91dc00e5..bb80286d4 100644 --- a/client/clitest/utils.go +++ b/client/clitest/utils.go @@ -7,18 +7,20 @@ import ( "strconv" "strings" "testing" - "bufio" "io" + irisInit "github.com/irisnet/irishub/init" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/tests" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/irisnet/irishub/app" "github.com/irisnet/irishub/client/bank" "github.com/irisnet/irishub/client/context" - govcli "github.com/irisnet/irishub/client/gov" - iservicecli "github.com/irisnet/irishub/client/iservice" + distributionclient "github.com/irisnet/irishub/client/distribution" + servicecli "github.com/irisnet/irishub/client/service" "github.com/irisnet/irishub/client/keys" recordCli "github.com/irisnet/irishub/client/record" stakecli "github.com/irisnet/irishub/client/stake" @@ -31,6 +33,10 @@ import ( "github.com/tendermint/tendermint/crypto" cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/types" + "github.com/irisnet/irishub/modules/service" + "github.com/cosmos/cosmos-sdk/x/auth" + "path/filepath" + "io/ioutil" ) var ( @@ -40,12 +46,21 @@ var ( nodeID = "" ) +func init() { + irisHome, iriscliHome = getTestingHomeDirs() + config := sdk.GetConfig() + config.SetBech32PrefixForAccount(irisInit.Bech32PrefixAccAddr, irisInit.Bech32PrefixAccPub) + config.SetBech32PrefixForValidator(irisInit.Bech32PrefixValAddr, irisInit.Bech32PrefixValPub) + config.SetBech32PrefixForConsensusNode(irisInit.Bech32PrefixConsAddr, irisInit.Bech32PrefixConsPub) + config.Seal() +} + //___________________________________________________________________________________ -// helper methods +// irisnet helper methods -func convertToIrisBaseAccount(t *testing.T, acc *bank.BaseAccount) string { - cdc := wire.NewCodec() - wire.RegisterCrypto(cdc) +func convertToIrisBaseAccount(t *testing.T, acc bank.BaseAccount) string { + cdc := codec.New() + codec.RegisterCrypto(cdc) cliCtx := context.NewCLIContext(). WithCodec(cdc) @@ -102,34 +117,11 @@ func setupGenesisAndConfig(srcHome, dstHome string) error { return nil } -func modifyGenesisFile(irisHome string) error { - genesisFilePath := fmt.Sprintf("%s%sconfig%sgenesis.json", irisHome, string(os.PathSeparator), string(os.PathSeparator)) - - genesisDoc, err := types.GenesisDocFromFile(genesisFilePath) - if err != nil { - return err - } - - var genesisState app.GenesisState - - cdc := wire.NewCodec() - wire.RegisterCrypto(cdc) - - err = cdc.UnmarshalJSON(genesisDoc.AppState, &genesisState) - if err != nil { - return err - } - +func modifyGenesisState(genesisState app.GenesisState) app.GenesisState { genesisState.GovData = gov.DefaultGenesisStateForCliTest() genesisState.UpgradeData = upgrade.DefaultGenesisStateForTest() - - bz, err := cdc.MarshalJSON(genesisState) - if err != nil { - return err - } - - genesisDoc.AppState = bz - return genesisDoc.SaveAs(genesisFilePath) + genesisState.ServiceData = service.DefaultGenesisStateForTest() + return genesisState } func modifyConfigFile(configSrcPath, configDstPath string) error { @@ -195,11 +187,69 @@ func copyFile(dstFile, srcFile string) error { _, err = io.Copy(dst, src) return err } +//___________________________________________________________________________________ +// helper methods + + + +func initializeFixtures(t *testing.T) (chainID, servAddr, port string) { + tests.ExecuteT(t, fmt.Sprintf("iris --home=%s unsafe-reset-all", irisHome), "") + executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s foo", iriscliHome), app.DefaultKeyPass) + executeWrite(t, fmt.Sprintf("iriscli keys delete --home=%s bar", iriscliHome), app.DefaultKeyPass) + executeWrite(t, fmt.Sprintf("iriscli keys add --home=%s foo", iriscliHome), app.DefaultKeyPass) + executeWrite(t, fmt.Sprintf("iriscli keys add --home=%s bar", iriscliHome), app.DefaultKeyPass) + fooAddr, _ := executeGetAddrPK(t, fmt.Sprintf( + "iriscli keys show foo --output=json --home=%s", iriscliHome)) + chainID = executeInit(t, fmt.Sprintf("iris init -o --moniker=foo --home=%s", irisHome)) + nodeID,_ = tests.ExecuteT(t, fmt.Sprintf("iris tendermint show-node-id --home=%s ", irisHome), "") + genFile := filepath.Join(irisHome, "config", "genesis.json") + genDoc := readGenesisFile(t, genFile) + var appState app.GenesisState + err := codec.Cdc.UnmarshalJSON(genDoc.AppState, &appState) + require.NoError(t, err) + appState.Accounts = []app.GenesisAccount{app.NewDefaultGenesisAccount(fooAddr)} + appState = modifyGenesisState(appState) + appStateJSON, err := codec.Cdc.MarshalJSON(appState) + require.NoError(t, err) + genDoc.AppState = appStateJSON + genDoc.SaveAs(genFile) + executeWrite(t, fmt.Sprintf( + "iris gentx --name=foo --home=%s --home-client=%s", irisHome, iriscliHome), + app.DefaultKeyPass) + executeWrite(t, fmt.Sprintf("iris collect-gentxs --home=%s", irisHome), app.DefaultKeyPass) + // get a free port, also setup some common flags + servAddr, port, err = server.FreeTCPAddr() + require.NoError(t, err) + return +} + +func unmarshalStdTx(t *testing.T, s string) (stdTx auth.StdTx) { + cdc := app.MakeCodec() + require.Nil(t, cdc.UnmarshalJSON([]byte(s), &stdTx)) + return +} + +func readGenesisFile(t *testing.T, genFile string) types.GenesisDoc { + var genDoc types.GenesisDoc + fp, err := os.Open(genFile) + require.NoError(t, err) + fileContents, err := ioutil.ReadAll(fp) + require.NoError(t, err) + defer fp.Close() + err = codec.Cdc.UnmarshalJSON(fileContents, &genDoc) + require.NoError(t, err) + return genDoc +} //___________________________________________________________________________________ // executors -func executeWrite(t *testing.T, cmdStr string, writes ...string) bool { +func executeWrite(t *testing.T, cmdStr string, writes ...string) (exitSuccess bool) { + exitSuccess, _, _ = executeWriteRetStdStreams(t, cmdStr, writes...) + return +} + +func executeWriteRetStdStreams(t *testing.T, cmdStr string, writes ...string) (bool, string, string) { proc := tests.GoExecuteT(t, cmdStr) for _, write := range writes { @@ -219,46 +269,46 @@ func executeWrite(t *testing.T, cmdStr string, writes ...string) bool { } proc.Wait() - return proc.ExitState.Success() - // bz := proc.StdoutBuffer.Bytes() - // fmt.Println("EXEC WRITE", string(bz)) + return proc.ExitState.Success(), string(stdout), string(stderr) } -func executeInit(t *testing.T, cmdStr string) (chainID, nodeID string) { - out := tests.ExecuteT(t, cmdStr, app.DefaultKeyPass) +func executeInit(t *testing.T, cmdStr string) (chainID string) { + _, stderr := tests.ExecuteT(t, cmdStr, app.DefaultKeyPass) var initRes map[string]json.RawMessage - err := json.Unmarshal([]byte(out), &initRes) + err := json.Unmarshal([]byte(stderr), &initRes) require.NoError(t, err) err = json.Unmarshal(initRes["chain_id"], &chainID) require.NoError(t, err) - err = json.Unmarshal(initRes["node_id"], &nodeID) - require.NoError(t, err) - return } func executeGetAddrPK(t *testing.T, cmdStr string) (sdk.AccAddress, crypto.PubKey) { - out := tests.ExecuteT(t, cmdStr, "") + out, _ := tests.ExecuteT(t, cmdStr, "") var ko keys.KeyOutput keys.UnmarshalJSON([]byte(out), &ko) pk, err := sdk.GetAccPubKeyBech32(ko.PubKey) require.NoError(t, err) - return ko.Address, pk + accAddr, err := sdk.AccAddressFromBech32(ko.Address) + require.NoError(t, err) + + return accAddr, pk } -func executeGetAccount(t *testing.T, cmdStr string) (acc *bank.BaseAccount) { - out := tests.ExecuteT(t, cmdStr, "") +// irisnet-module-helper function + +func executeGetAccount(t *testing.T, cmdStr string) (acc bank.BaseAccount) { + out, _ := tests.ExecuteT(t, cmdStr, "") var initRes map[string]json.RawMessage err := json.Unmarshal([]byte(out), &initRes) require.NoError(t, err, "out %v, err %v", out, err) - cdc := wire.NewCodec() - wire.RegisterCrypto(cdc) + cdc := codec.New() + codec.RegisterCrypto(cdc) err = cdc.UnmarshalJSON([]byte(out), &acc) require.NoError(t, err, "acc %v, err %v", string(out), err) @@ -266,8 +316,51 @@ func executeGetAccount(t *testing.T, cmdStr string) (acc *bank.BaseAccount) { return acc } +func executeGetValidatorPK(t *testing.T, cmdStr string) string { + out, errMsg := tests.ExecuteT(t, cmdStr, "") + require.Empty(t, errMsg) + + return out +} + +func executeGetDelegatorDistrInfo(t *testing.T, cmdStr string) []distributiontypes.DelegationDistInfo { + out, errMsg := tests.ExecuteT(t, cmdStr, "") + require.Empty(t, errMsg) + + cdc := app.MakeCodec() + var ddiList []distributiontypes.DelegationDistInfo + err := cdc.UnmarshalJSON([]byte(out), &ddiList) + + require.Empty(t, err) + return ddiList +} + +func executeGetDelegationDistrInfo(t *testing.T, cmdStr string) distributiontypes.DelegationDistInfo { + out, errMsg := tests.ExecuteT(t, cmdStr, "") + require.Empty(t, errMsg) + + cdc := app.MakeCodec() + var ddi distributiontypes.DelegationDistInfo + err := cdc.UnmarshalJSON([]byte(out), &ddi) + + require.Empty(t, err) + return ddi +} + +func executeGetValidatorDistrInfo(t *testing.T, cmdStr string) distributionclient.ValidatorDistInfoOutput { + out, errMsg := tests.ExecuteT(t, cmdStr, "") + require.Empty(t, errMsg) + + cdc := app.MakeCodec() + var vdi distributionclient.ValidatorDistInfoOutput + err := cdc.UnmarshalJSON([]byte(out), &vdi) + + require.Empty(t, err) + return vdi +} + func executeGetValidator(t *testing.T, cmdStr string) stakecli.ValidatorOutput { - out := tests.ExecuteT(t, cmdStr, "") + out, _ := tests.ExecuteT(t, cmdStr, "") var validator stakecli.ValidatorOutput cdc := app.MakeCodec() err := cdc.UnmarshalJSON([]byte(out), &validator) @@ -275,9 +368,9 @@ func executeGetValidator(t *testing.T, cmdStr string) stakecli.ValidatorOutput { return validator } -func executeGetProposal(t *testing.T, cmdStr string) govcli.ProposalOutput { - out := tests.ExecuteT(t, cmdStr, "") - var proposal govcli.ProposalOutput +func executeGetProposal(t *testing.T, cmdStr string) gov.ProposalOutput { + out, _ := tests.ExecuteT(t, cmdStr, "") + var proposal gov.ProposalOutput cdc := app.MakeCodec() err := cdc.UnmarshalJSON([]byte(out), &proposal) require.NoError(t, err, "out %v\n, err %v", out, err) @@ -285,7 +378,7 @@ func executeGetProposal(t *testing.T, cmdStr string) govcli.ProposalOutput { } func executeGetVote(t *testing.T, cmdStr string) gov.Vote { - out := tests.ExecuteT(t, cmdStr, "") + out, _ := tests.ExecuteT(t, cmdStr, "") var vote gov.Vote cdc := app.MakeCodec() err := cdc.UnmarshalJSON([]byte(out), &vote) @@ -294,7 +387,7 @@ func executeGetVote(t *testing.T, cmdStr string) gov.Vote { } func executeGetVotes(t *testing.T, cmdStr string) []gov.Vote { - out := tests.ExecuteT(t, cmdStr, "") + out, _ := tests.ExecuteT(t, cmdStr, "") var votes []gov.Vote cdc := app.MakeCodec() err := cdc.UnmarshalJSON([]byte(out), &votes) @@ -303,7 +396,7 @@ func executeGetVotes(t *testing.T, cmdStr string) []gov.Vote { } func executeGetParam(t *testing.T, cmdStr string) gov.Param { - out := tests.ExecuteT(t, cmdStr, "") + out, _ := tests.ExecuteT(t, cmdStr, "") var param gov.Param cdc := app.MakeCodec() err := cdc.UnmarshalJSON([]byte(out), ¶m) @@ -312,7 +405,7 @@ func executeGetParam(t *testing.T, cmdStr string) gov.Param { } func executeGetUpgradeInfo(t *testing.T, cmdStr string) upgcli.UpgradeInfoOutput { - out := tests.ExecuteT(t, cmdStr, "") + out, _ := tests.ExecuteT(t, cmdStr, "") var info upgcli.UpgradeInfoOutput cdc := app.MakeCodec() err := cdc.UnmarshalJSON([]byte(out), &info) @@ -322,7 +415,7 @@ func executeGetUpgradeInfo(t *testing.T, cmdStr string) upgcli.UpgradeInfoOutput } func executeGetSwitch(t *testing.T, cmdStr string) upgrade.MsgSwitch { - out := tests.ExecuteT(t, cmdStr, "") + out, _ := tests.ExecuteT(t, cmdStr, "") var switchMsg upgrade.MsgSwitch cdc := app.MakeCodec() err := cdc.UnmarshalJSON([]byte(out), &switchMsg) @@ -331,15 +424,33 @@ func executeGetSwitch(t *testing.T, cmdStr string) upgrade.MsgSwitch { return switchMsg } -func executeGetServiceDefinition(t *testing.T, cmdStr string) iservicecli.ServiceOutput { - out := tests.ExecuteT(t, cmdStr, "") - var serviceDef iservicecli.ServiceOutput +func executeGetServiceDefinition(t *testing.T, cmdStr string) servicecli.ServiceOutput { + out, _ := tests.ExecuteT(t, cmdStr, "") + var serviceDef servicecli.ServiceOutput cdc := app.MakeCodec() err := cdc.UnmarshalJSON([]byte(out), &serviceDef) require.NoError(t, err, "out %v\n, err %v", out, err) return serviceDef } +func executeGetServiceBinding(t *testing.T, cmdStr string) service.SvcBinding { + out, _ := tests.ExecuteT(t, cmdStr, "") + var serviceBinding service.SvcBinding + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &serviceBinding) + require.NoError(t, err, "out %v\n, err %v", out, err) + return serviceBinding +} + +func executeGetServiceBindings(t *testing.T, cmdStr string) []service.SvcBinding { + out, _ := tests.ExecuteT(t, cmdStr, "") + var serviceBindings []service.SvcBinding + cdc := app.MakeCodec() + err := cdc.UnmarshalJSON([]byte(out), &serviceBindings) + require.NoError(t, err, "out %v\n, err %v", out, err) + return serviceBindings +} + func executeSubmitRecordAndGetTxHash(t *testing.T, cmdStr string, writes ...string) string { proc := tests.GoExecuteT(t, cmdStr) @@ -360,9 +471,9 @@ func executeSubmitRecordAndGetTxHash(t *testing.T, cmdStr string, writes ...stri } type toJSON struct { - Height int64 `json:"Height"` - TxHash string `json:"TxHash"` - Response string `json:"Response"` + Height int64 `json:"Height"` + TxHash string `json:"TxHash"` + //Response string `json:"Response"` } var res toJSON cdc := app.MakeCodec() @@ -373,7 +484,7 @@ func executeSubmitRecordAndGetTxHash(t *testing.T, cmdStr string, writes ...stri } func executeGetRecordID(t *testing.T, cmdStr string) string { - out := tests.ExecuteT(t, cmdStr, "") + out, _ := tests.ExecuteT(t, cmdStr, "") var info tx.Info cdc := app.MakeCodec() err := cdc.UnmarshalJSON([]byte(out), &info) @@ -387,7 +498,7 @@ func executeGetRecordID(t *testing.T, cmdStr string) string { } func executeGetRecord(t *testing.T, cmdStr string) recordCli.RecordOutput { - out := tests.ExecuteT(t, cmdStr, "") + out, _ := tests.ExecuteT(t, cmdStr, "") var record recordCli.RecordOutput cdc := app.MakeCodec() err := cdc.UnmarshalJSON([]byte(out), &record) @@ -427,3 +538,5 @@ func executeDownloadRecord(t *testing.T, cmdStr string, filePath string, force b return true } + + diff --git a/client/config.go b/client/config.go new file mode 100644 index 000000000..e35866832 --- /dev/null +++ b/client/config.go @@ -0,0 +1,164 @@ +package client + +import ( + "bufio" + "fmt" + "io/ioutil" + "os" + "path" + + "github.com/mitchellh/go-homedir" + "github.com/pelletier/go-toml" + "github.com/spf13/cobra" +) + +type cliConfig struct { + Home string `toml:"home"` + ChainID string `toml:"chain-id"` + TrustNode bool `toml:"trust-node"` + Encoding string `toml:"encoding"` + Output string `toml:"output"` + Node string `toml:"node"` + Trace bool `toml:"trace"` + Fee string `toml:"fee"` +} + +// ConfigCmd returns a CLI command to interactively create a +// IRISCLI config file. +func ConfigCmd() *cobra.Command { + cfg := &cobra.Command{ + Use: "config", + Short: "Interactively creates a iriscli config file", + RunE: runConfigCmd, + } + + return cfg +} + +func runConfigCmd(cmd *cobra.Command, args []string) error { + home, err := homedir.Dir() + if err != nil { + return err + } + + stdin := BufferStdin() + iriscliHome, err := handleIRISCLIHome(home, stdin) + if err != nil { + return err + } + node, err := handleNode(stdin) + if err != nil { + return err + } + trustNode, err := handleTrustNode(stdin) + if err != nil { + return err + } + + encoding := "btc" + output := "text" + + chainID, err := handleChainID(stdin) + if err != nil { + return err + } + + fee, err := handleFee(stdin) + if err != nil { + return err + } + + cfg := &cliConfig{ + Home: iriscliHome, + ChainID: chainID, + TrustNode: trustNode, + Encoding: encoding, + Output: output, + Node: node, + Trace: false, + Fee: fee, + } + + return createIRISCLIConfig(cfg) +} + +func handleIRISCLIHome(dir string, stdin *bufio.Reader) (string, error) { + dirName := ".iriscli" + home, err := GetString(fmt.Sprintf("Where is your iriscli home directory? (Default: ~/%s)", dirName), stdin) + if err != nil { + return "", err + } + + if home == "" { + home = path.Join(dir, dirName) + } + + return home, nil +} + +func handleNode(stdin *bufio.Reader) (string, error) { + defaultNode := "tcp://localhost:26657" + node, err := GetString(fmt.Sprintf("Where is your validator node running? (Default: %s)", defaultNode), stdin) + if err != nil { + return "", err + } + + if node == "" { + node = defaultNode + } + + return node, nil +} + +func handleChainID(stdin *bufio.Reader) (string, error) { + chainID, err := GetString("What is your chainID?", stdin) + if err != nil { + return "", err + } + + if chainID == "" { + return "", fmt.Errorf("you must specify your chainID") + } + + return chainID, nil +} + +func handleFee(stdin *bufio.Reader) (string, error) { + fee, err := GetString("Please specify default fee", stdin) + if err != nil { + return "", err + } + + if fee == "" { + fmt.Println("No fee has been specified") + } + + return fee, nil +} + +func handleTrustNode(stdin *bufio.Reader) (bool, error) { + return GetConfirmation("Do you trust this node?", stdin) +} + +func createIRISCLIConfig(cfg *cliConfig) error { + cfgPath := path.Join(cfg.Home, "config") + err := os.MkdirAll(cfgPath, os.ModePerm) + if err != nil { + return err + } + + data, err := toml.Marshal(*cfg) + if err != nil { + return err + } + + cfgFile := path.Join(cfgPath, "config.toml") + if info, err := os.Stat(cfgFile); err == nil && !info.IsDir() { + err = os.Rename(cfgFile, path.Join(cfgPath, "config.toml-old")) + if err != nil { + return err + } + } + + return ioutil.WriteFile(cfgFile, data, os.ModePerm) +} diff --git a/client/context/broadcast.go b/client/context/broadcast.go new file mode 100644 index 000000000..3ad8eba27 --- /dev/null +++ b/client/context/broadcast.go @@ -0,0 +1,187 @@ +package context + +import ( + "fmt" + "io" + + "github.com/pkg/errors" + + abci "github.com/tendermint/tendermint/abci/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" + "strings" + "encoding/json" +) + +// TODO: This should get deleted eventually, and perhaps +// ctypes.ResultBroadcastTx be stripped of unused fields, and +// ctypes.ResultBroadcastTxCommit returned for tendermint RPC BroadcastTxSync. +// +// The motivation is that we want a unified type to return, and the better +// option is the one that can hold CheckTx/DeliverTx responses optionally. +func resultBroadcastTxToCommit(res *ctypes.ResultBroadcastTx) *ctypes.ResultBroadcastTxCommit { + return &ctypes.ResultBroadcastTxCommit{ + Hash: res.Hash, + // NOTE: other fields are unused for async. + } +} + +// BroadcastTx broadcasts a transactions either synchronously or asynchronously +// based on the context parameters. The result of the broadcast is parsed into +// an intermediate structure which is logged if the context has a logger +// defined. +func (cliCtx CLIContext) BroadcastTx(txBytes []byte) (*ctypes.ResultBroadcastTxCommit, error) { + if cliCtx.Async { + res, err := cliCtx.broadcastTxAsync(txBytes) + if err != nil { + return nil, err + } + + resCommit := resultBroadcastTxToCommit(res) + return resCommit, err + } + + return cliCtx.broadcastTxCommit(txBytes) +} + +// BroadcastTxAndAwaitCommit broadcasts transaction bytes to a Tendermint node +// and waits for a commit. +func (cliCtx CLIContext) BroadcastTxAndAwaitCommit(tx []byte) (*ctypes.ResultBroadcastTxCommit, error) { + node, err := cliCtx.GetNode() + if err != nil { + return nil, err + } + + res, err := node.BroadcastTxCommit(tx) + if err != nil { + return res, err + } + + if !res.CheckTx.IsOK() { + return res, errors.Errorf(res.CheckTx.Log) + } + + if !res.DeliverTx.IsOK() { + return res, errors.Errorf(res.DeliverTx.Log) + } + + return res, err +} + +// BroadcastTxSync broadcasts transaction bytes to a Tendermint node +// synchronously. +func (cliCtx CLIContext) BroadcastTxSync(tx []byte) (*ctypes.ResultBroadcastTx, error) { + node, err := cliCtx.GetNode() + if err != nil { + return nil, err + } + + res, err := node.BroadcastTxSync(tx) + if err != nil { + return res, err + } + + return res, err +} + +// BroadcastTxAsync broadcasts transaction bytes to a Tendermint node +// asynchronously. +func (cliCtx CLIContext) BroadcastTxAsync(tx []byte) (*ctypes.ResultBroadcastTx, error) { + node, err := cliCtx.GetNode() + if err != nil { + return nil, err + } + + res, err := node.BroadcastTxAsync(tx) + if err != nil { + return res, err + } + + return res, err +} + +func (cliCtx CLIContext) broadcastTxAsync(txBytes []byte) (*ctypes.ResultBroadcastTx, error) { + res, err := cliCtx.BroadcastTxAsync(txBytes) + if err != nil { + return res, err + } + + if cliCtx.Logger != nil { + if cliCtx.JSON { + type toJSON struct { + TxHash string + } + + resJSON := toJSON{res.Hash.String()} + bz, err := cliCtx.Codec.MarshalJSON(resJSON) + if err != nil { + return res, err + } + + cliCtx.Logger.Write(bz) + io.WriteString(cliCtx.Logger, "\n") + } else { + io.WriteString(cliCtx.Logger, fmt.Sprintf("async tx sent (tx hash: %s)\n", res.Hash)) + } + } + + return res, nil +} + +func (cliCtx CLIContext) broadcastTxCommit(txBytes []byte) (*ctypes.ResultBroadcastTxCommit, error) { + res, err := cliCtx.BroadcastTxAndAwaitCommit(txBytes) + if err != nil { + return res, err + } + + if cliCtx.JSON { + // Since JSON is intended for automated scripts, always include response in + // JSON mode. + type toJSON struct { + Height int64 + TxHash string + Response abci.ResponseDeliverTx + } + + if cliCtx.Logger != nil { + resJSON := toJSON{res.Height, res.Hash.String(), res.DeliverTx} + bz, err := cliCtx.Codec.MarshalJSON(resJSON) + if err != nil { + return res, err + } + + cliCtx.Logger.Write(bz) + io.WriteString(cliCtx.Logger, "\n") + } + + return res, nil + } + + if cliCtx.Logger != nil { + resStr := fmt.Sprintf("Committed at block %d (tx hash: %s)\n", res.Height, res.Hash.String()) + + if cliCtx.PrintResponse { + jsonStr, _ := deliverTxMarshalIndentJSON(res.DeliverTx) + resStr = fmt.Sprintf("Committed at block %d (tx hash: %s, response: %+v)\n%s\n", + res.Height, res.Hash.String(), res.DeliverTx, string(jsonStr), + ) + } + + io.WriteString(cliCtx.Logger, resStr) + } + + return res, nil +} + +func deliverTxMarshalIndentJSON(dtx abci.ResponseDeliverTx) ([]byte, error) { + + tags := make(map[string]string) + for _, kv := range dtx.Tags { + tags[string(kv.Key)] = strings.Replace(string(kv.Value), "\\", "", -1) + } + + return json.MarshalIndent(&struct { + Tags map[string]string `json:"tags,omitempty"` + }{ + Tags: tags, + }, " ", " ") +} diff --git a/client/context/context.go b/client/context/context.go index dfe67911d..9c7407147 100644 --- a/client/context/context.go +++ b/client/context/context.go @@ -3,18 +3,23 @@ package context import ( "io" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/irisnet/irishub/client" "bytes" "fmt" + "os" + + cskeys "github.com/cosmos/cosmos-sdk/crypto/keys" + "github.com/cosmos/cosmos-sdk/types" + "github.com/irisnet/irishub/client/keys" "github.com/spf13/viper" "github.com/tendermint/tendermint/libs/cli" + "github.com/tendermint/tendermint/libs/log" tmlite "github.com/tendermint/tendermint/lite" tmliteProxy "github.com/tendermint/tendermint/lite/proxy" rpcclient "github.com/tendermint/tendermint/rpc/client" - "os" ) const ctxAccStoreName = "acc" @@ -22,23 +27,24 @@ const ctxAccStoreName = "acc" // CLIContext implements a typical CLI context created in SDK modules for // transaction handling and queries. type CLIContext struct { - Codec *wire.Codec - AccDecoder auth.AccountDecoder - Client rpcclient.Client - Logger io.Writer - Height int64 - NodeURI string - FromAddressName string - //If GenerateOnly is true and FromAddressName is not specified, the signer is required for building msg - SignerAddr string - AccountStore string - TrustNode bool - UseLedger bool - Async bool - JSON bool - PrintResponse bool - Certifier tmlite.Certifier - GenerateOnly bool + Codec *codec.Codec + AccDecoder auth.AccountDecoder + Client rpcclient.Client + Logger io.Writer + Height int64 + NodeURI string + AccountStore string + TrustNode bool + UseLedger bool + Async bool + JSON bool + PrintResponse bool + Verifier tmlite.Verifier + GenerateOnly bool + fromAddress types.AccAddress + fromName string + Indent bool + DryRun bool } // NewCLIContext returns a new initialized CLIContext with parameters from the @@ -46,29 +52,34 @@ type CLIContext struct { func NewCLIContext() CLIContext { var rpc rpcclient.Client + from := viper.GetString(client.FlagFrom) + fromAddress, fromName := fromFields(from) + nodeURI := viper.GetString(client.FlagNode) if nodeURI != "" { rpc = rpcclient.NewHTTP(nodeURI, "/websocket") } return CLIContext{ - Client: rpc, - NodeURI: nodeURI, - AccountStore: ctxAccStoreName, - FromAddressName: viper.GetString(client.FlagFrom), - SignerAddr: viper.GetString(client.FlagSignerAddr), - Height: viper.GetInt64(client.FlagHeight), - TrustNode: viper.GetBool(client.FlagTrustNode), - UseLedger: viper.GetBool(client.FlagUseLedger), - Async: viper.GetBool(client.FlagAsync), - JSON: viper.GetBool(client.FlagJson), - PrintResponse: viper.GetBool(client.FlagPrintResponse), - Certifier: createCertifier(), - GenerateOnly: viper.GetBool(client.FlagGenerateOnly), + Client: rpc, + NodeURI: nodeURI, + AccountStore: ctxAccStoreName, + Height: viper.GetInt64(client.FlagHeight), + TrustNode: viper.GetBool(client.FlagTrustNode), + UseLedger: viper.GetBool(client.FlagUseLedger), + Async: viper.GetBool(client.FlagAsync), + JSON: viper.GetBool(client.FlagJson), + PrintResponse: viper.GetBool(client.FlagPrintResponse), + Verifier: createVerifier(), + DryRun: viper.GetBool(client.FlagDryRun), + GenerateOnly: viper.GetBool(client.FlagGenerateOnly), + fromAddress: fromAddress, + fromName: fromName, + Indent: viper.GetBool(client.FlagIndentResponse), } } -func createCertifier() tmlite.Certifier { +func createVerifier() tmlite.Verifier { trustNodeDefined := viper.IsSet(client.FlagTrustNode) if !trustNodeDefined { return nil @@ -98,17 +109,67 @@ func createCertifier() tmlite.Certifier { os.Exit(1) } - certifier, err := tmliteProxy.GetCertifier(chainID, home, nodeURI) + node := rpcclient.NewHTTP(nodeURI, "/websocket") + cacheSize := 10 // TODO: determine appropriate cache size + verifier, err := tmliteProxy.NewVerifier( + chainID, home, + node, log.NewNopLogger(), cacheSize, + ) + + if err != nil { + fmt.Printf("Create verifier failed: %s\n", err.Error()) + fmt.Printf("Please check network connection and verify the address of the node to connect to\n") + os.Exit(1) + } + + return verifier +} + +func fromFields(from string) (fromAddr types.AccAddress, fromName string) { + // In generate-only mode, if the signer key doesn't exist in keystore, the fromAddress can be specified by --from-addr + if from == "" { + fromAddrString := viper.GetString(client.FlagFromAddr) + if fromAddrString == "" { + return nil, "" + } + address, err := types.AccAddressFromBech32(fromAddrString) + if err != nil { + fmt.Printf("invalid from address %s\n", fromAddrString) + os.Exit(1) + } + fromAddr = address + fromName = "" + return + } + + keybase, err := keys.GetKeyBase() if err != nil { - fmt.Printf("Abort!! IRISLCD encountered fatal error in creating certifier: %s", err.Error()) + fmt.Println("no keybase found") os.Exit(1) } - return certifier + var info cskeys.Info + if addr, err := types.AccAddressFromBech32(from); err == nil { + info, err = keybase.GetByAddress(addr) + if err != nil { + fmt.Printf("could not find key %s\n", from) + os.Exit(1) + } + } else { + info, err = keybase.Get(from) + if err != nil { + fmt.Printf("could not find key %s\n", from) + os.Exit(1) + } + } + + fromAddr = info.GetAddress() + fromName = info.GetName() + return } // WithCodec returns a copy of the context with an updated codec. -func (ctx CLIContext) WithCodec(cdc *wire.Codec) CLIContext { +func (ctx CLIContext) WithCodec(cdc *codec.Codec) CLIContext { ctx.Codec = cdc return ctx } @@ -132,13 +193,6 @@ func (ctx CLIContext) WithAccountStore(accountStore string) CLIContext { return ctx } -// WithFromAddressName returns a copy of the context with an updated from -// address. -func (ctx CLIContext) WithFromAddressName(addrName string) CLIContext { - ctx.FromAddressName = addrName - return ctx -} - // WithTrustNode returns a copy of the context with an updated TrustNode flag. func (ctx CLIContext) WithTrustNode(trustNode bool) CLIContext { ctx.TrustNode = trustNode @@ -166,7 +220,7 @@ func (ctx CLIContext) WithUseLedger(useLedger bool) CLIContext { } // WithCertifier - return a copy of the context with an updated Certifier -func (ctx CLIContext) WithCertifier(certifier tmlite.Certifier) CLIContext { - ctx.Certifier = certifier +func (ctx CLIContext) WithCertifier(verifier tmlite.Verifier) CLIContext { + ctx.Verifier = verifier return ctx } diff --git a/client/context/errors.go b/client/context/errors.go index 478c6f605..70df4056e 100644 --- a/client/context/errors.go +++ b/client/context/errors.go @@ -16,7 +16,7 @@ Are you sure there has been a transaction involving it?`, addr) // height can't be verified. The reason is that the base checkpoint of the certifier is // newer than the given height func ErrVerifyCommit(height int64) error { - return errors.Errorf(`The height of base truststore in gaia-lite is higher than height %d. + return errors.Errorf(`The height of base truststore in lcd is higher than height %d. Can't verify blockchain proof at this height. Please set --trust-node to true and try again`, height) } diff --git a/client/context/query.go b/client/context/query.go index f190379e0..9471e5cb2 100644 --- a/client/context/query.go +++ b/client/context/query.go @@ -2,31 +2,28 @@ package context import ( "fmt" - "io" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/pkg/errors" - "encoding/json" + "strings" + "github.com/cosmos/cosmos-sdk/store" - "github.com/cosmos/cosmos-sdk/wire" "github.com/irisnet/irishub/app" - "github.com/irisnet/irishub/client/keys" "github.com/irisnet/irishub/types" abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/common" cmn "github.com/tendermint/tendermint/libs/common" - "github.com/tendermint/tendermint/lite" tmliteErr "github.com/tendermint/tendermint/lite/errors" tmliteProxy "github.com/tendermint/tendermint/lite/proxy" + "github.com/tendermint/tendermint/crypto/merkle" rpcclient "github.com/tendermint/tendermint/rpc/client" tmclient "github.com/tendermint/tendermint/rpc/client" ctypes "github.com/tendermint/tendermint/rpc/core/types" + tmtypes "github.com/tendermint/tendermint/types" "io/ioutil" "net/http" - "strings" ) // GetNode returns an RPC client. If the context's client is not defined, an @@ -40,8 +37,13 @@ func (cliCtx CLIContext) GetNode() (rpcclient.Client, error) { } // Query performs a query for information about the connected node. -func (cliCtx CLIContext) Query(path string) (res []byte, err error) { - return cliCtx.query(path, nil) +func (cliCtx CLIContext) Query(path string, data cmn.HexBytes) (res []byte, err error) { + return cliCtx.query(path, data) +} + +// Query information about the connected node with a data payload +func (cliCtx CLIContext) QueryWithData(path string, data []byte) (res []byte, err error) { + return cliCtx.query(path, data) } // QueryStore performs a query from a Tendermint node with the provided key and @@ -58,7 +60,7 @@ func (cliCtx CLIContext) QuerySubspace(subspace []byte, storeName string) (res [ return res, err } - cliCtx.Codec.MustUnmarshalBinary(resRaw, &res) + cliCtx.Codec.MustUnmarshalBinaryLengthPrefixed(resRaw, &res) return } @@ -85,27 +87,13 @@ func (cliCtx CLIContext) GetAccount(address []byte) (auth.Account, error) { } // GetFromAddress returns the from address from the context's name. -func (cliCtx CLIContext) GetFromAddress() (from sdk.AccAddress, err error) { - kb, err := keys.GetKeyBase() - if err != nil { - return nil, err - } - if cliCtx.GenerateOnly { - signerAddress, err := sdk.AccAddressFromBech32(cliCtx.SignerAddr) - // When generate-only is true, if the user specified signer address is correct, then just return the address. - if err == nil { - return signerAddress, nil - } - } - if cliCtx.FromAddressName == "" { - return nil, fmt.Errorf("must provide a from address name") - } - info, err := kb.Get(cliCtx.FromAddressName) - if err != nil { - return nil, err - } +func (cliCtx CLIContext) GetFromAddress() (sdk.AccAddress, error) { + return cliCtx.fromAddress, nil +} - return sdk.AccAddress(info.GetPubKey().Address()), nil +// GetFromName returns the key name for the current context. +func (cliCtx CLIContext) GetFromName() (string, error) { + return cliCtx.fromName, nil } // GetAccountNumber returns the next account number for the given account @@ -130,49 +118,6 @@ func (cliCtx CLIContext) GetAccountSequence(address []byte) (int64, error) { return account.GetSequence(), nil } -// BroadcastTx broadcasts transaction bytes to a Tendermint node. -func (cliCtx CLIContext) BroadcastTx(tx []byte) (*ctypes.ResultBroadcastTxCommit, error) { - node, err := cliCtx.GetNode() - if err != nil { - return nil, err - } - - res, err := node.BroadcastTxCommit(tx) - if err != nil { - return res, err - } - - if !res.CheckTx.IsOK() { - return res, errors.Errorf("checkTx failed: (%d) %s", - res.CheckTx.Code, - res.CheckTx.Log) - } - - if !res.DeliverTx.IsOK() { - return res, errors.Errorf("deliverTx failed: (%d) %s", - res.DeliverTx.Code, - res.DeliverTx.Log) - } - - return res, err -} - -// BroadcastTxAsync broadcasts transaction bytes to a Tendermint node -// asynchronously. -func (cliCtx CLIContext) BroadcastTxAsync(tx []byte) (*ctypes.ResultBroadcastTx, error) { - node, err := cliCtx.GetNode() - if err != nil { - return nil, err - } - - res, err := node.BroadcastTxAsync(tx) - if err != nil { - return res, err - } - - return res, err -} - // EnsureAccountExists ensures that an account exists for a given context. An // error is returned if it does not. func (cliCtx CLIContext) EnsureAccountExists() error { @@ -209,111 +154,9 @@ func (cliCtx CLIContext) EnsureAccountExistsFromAddr(addr sdk.AccAddress) error return nil } -// EnsureBroadcastTx broadcasts a transactions either synchronously or -// asynchronously based on the context parameters. The result of the broadcast -// is parsed into an intermediate structure which is logged if the context has -// a logger defined. -func (cliCtx CLIContext) EnsureBroadcastTx(txBytes []byte) error { - if cliCtx.Async { - return cliCtx.ensureBroadcastTxAsync(txBytes) - } - - return cliCtx.ensureBroadcastTx(txBytes) -} - -func (cliCtx CLIContext) ensureBroadcastTxAsync(txBytes []byte) error { - res, err := cliCtx.BroadcastTxAsync(txBytes) - if err != nil { - return err - } - - if cliCtx.JSON { - type toJSON struct { - TxHash string - } - - if cliCtx.Logger != nil { - resJSON := toJSON{res.Hash.String()} - bz, err := cliCtx.Codec.MarshalJSON(resJSON) - if err != nil { - return err - } - - cliCtx.Logger.Write(bz) - io.WriteString(cliCtx.Logger, "\n") - } - } else { - if cliCtx.Logger != nil { - io.WriteString(cliCtx.Logger, fmt.Sprintf("Async tx sent (tx hash: %s)\n", res.Hash)) - } - } - - return nil -} - -func (cliCtx CLIContext) ensureBroadcastTx(txBytes []byte) error { - res, err := cliCtx.BroadcastTx(txBytes) - if err != nil { - return err - } - - if cliCtx.JSON { - // since JSON is intended for automated scripts, always include - // response in JSON mode. - type toJSON struct { - Height int64 - TxHash string - Response string - } - - if cliCtx.Logger != nil { - resJSON := toJSON{res.Height, res.Hash.String(), fmt.Sprintf("%+v", res.DeliverTx)} - bz, err := cliCtx.Codec.MarshalJSON(resJSON) - if err != nil { - return err - } - - cliCtx.Logger.Write(bz) - io.WriteString(cliCtx.Logger, "\n") - } - - return nil - } - - if cliCtx.Logger != nil { - resStr := fmt.Sprintf("Committed at block %d (tx hash: %s)\n", res.Height, res.Hash.String()) - - if cliCtx.PrintResponse { - jsonStr, _ := DeliverTxMarshalIndentJSON(res.DeliverTx) - resStr = fmt.Sprintf("Committed at block %d (tx hash: %s, response: %+v)\n%s\n", - res.Height, res.Hash.String(), res.DeliverTx, string(jsonStr), - ) - - } - - io.WriteString(cliCtx.Logger, resStr) - } - - return nil -} - -func DeliverTxMarshalIndentJSON(dtx abci.ResponseDeliverTx) ([]byte, error) { - - tags := make(map[string]string) - for _, kv := range dtx.Tags { - tags[string(kv.Key)] = strings.Replace(string(kv.Value), "\\", "", -1) - } - - return json.MarshalIndent(&struct { - Tags map[string]string `json:"tags,omitempty"` - }{ - Tags: tags, - }, " ", " ") -} - // query performs a query from a Tendermint node with the provided store name // and path. -func (cliCtx CLIContext) query(path string, key common.HexBytes) (res []byte, err error) { +func (cliCtx CLIContext) query(path string, key cmn.HexBytes) (res []byte, err error) { node, err := cliCtx.GetNode() if err != nil { return res, err @@ -321,7 +164,7 @@ func (cliCtx CLIContext) query(path string, key common.HexBytes) (res []byte, er opts := rpcclient.ABCIQueryOptions{ Height: cliCtx.Height, - Trusted: cliCtx.TrustNode, + Prove: !cliCtx.TrustNode, } result, err := node.ABCIQueryWithOptions(path, key, opts) @@ -331,7 +174,7 @@ func (cliCtx CLIContext) query(path string, key common.HexBytes) (res []byte, er resp := result.Response if !resp.IsOK() { - return res, errors.Errorf("query failed: (%d) %s", resp.Code, resp.Log) + return res, errors.Errorf(resp.Log) } // data from trusted node or subspace query doesn't need verification @@ -347,41 +190,47 @@ func (cliCtx CLIContext) query(path string, key common.HexBytes) (res []byte, er return resp.Value, nil } -// verifyProof perform response proof verification -func (cliCtx CLIContext) verifyProof(path string, resp abci.ResponseQuery) error { - - if cliCtx.Certifier == nil { - return fmt.Errorf("missing valid certifier to verify data from untrusted node") +// Verify verifies the consensus proof at given height. +func (cliCtx CLIContext) Verify(height int64) (tmtypes.SignedHeader, error) { + check, err := tmliteProxy.GetCertifiedCommit(height, cliCtx.Client, cliCtx.Verifier) + switch { + case tmliteErr.IsErrCommitNotFound(err): + return tmtypes.SignedHeader{}, ErrVerifyCommit(height) + case err != nil: + return tmtypes.SignedHeader{}, err } - node, err := cliCtx.GetNode() - if err != nil { - return err + return check, nil +} + +// verifyProof perform response proof verification. +func (cliCtx CLIContext) verifyProof(queryPath string, resp abci.ResponseQuery) error { + if cliCtx.Verifier == nil { + return fmt.Errorf("missing valid certifier to verify data from distrusted node") } - // AppHash for height H is in header H+1 - commit, err := tmliteProxy.GetCertifiedCommit(resp.Height+1, node, cliCtx.Certifier) + // the AppHash for height H is in header H+1 + commit, err := cliCtx.Verify(resp.Height + 1) if err != nil { return err } - var multiStoreProof store.MultiStoreProof - cdc := wire.NewCodec() - err = cdc.UnmarshalBinary(resp.Proof, &multiStoreProof) - if err != nil { - return errors.Wrap(err, "failed to unmarshalBinary rangeProof") - } + // TODO: Instead of reconstructing, stash on CLIContext field? + prt := store.DefaultProofRuntime() - // Verify the substore commit hash against trusted appHash - substoreCommitHash, err := store.VerifyMultiStoreCommitInfo( - multiStoreProof.StoreName, multiStoreProof.StoreInfos, commit.Header.AppHash) + // TODO: Better convention for path? + storeName, err := parseQueryStorePath(queryPath) if err != nil { - return errors.Wrap(err, "failed in verifying the proof against appHash") + return err } - err = store.VerifyRangeProof(resp.Key, resp.Value, substoreCommitHash, multiStoreProof.RangeProof) + kp := merkle.KeyPath{} + kp = kp.AppendKey([]byte(storeName), merkle.KeyEncodingURL) + kp = kp.AppendKey(resp.Key, merkle.KeyEncodingURL) + + err = prt.VerifyValue(resp.Proof, commit.Header.AppHash, kp.String(), resp.Value) if err != nil { - return errors.Wrap(err, "failed in the range proof verification") + return errors.Wrap(err, "failed to prove merkle proof") } return nil @@ -394,6 +243,41 @@ func (cliCtx CLIContext) queryStore(key cmn.HexBytes, storeName, endPath string) return cliCtx.query(path, key) } +// isQueryStoreWithProof expects a format like /// +// queryType can be app or store. +func isQueryStoreWithProof(path string) bool { + if !strings.HasPrefix(path, "/") { + return false + } + paths := strings.SplitN(path[1:], "/", 3) + switch { + case len(paths) != 3: + return false + case paths[0] != "store": + return false + case store.RequireProof("/" + paths[2]): + return true + } + return false +} + +// parseQueryStorePath expects a format like /store//key. +func parseQueryStorePath(path string) (storeName string, err error) { + if !strings.HasPrefix(path, "/") { + return "", errors.New("expected path to start with /") + } + paths := strings.SplitN(path[1:], "/", 3) + switch { + case len(paths) != 3: + return "", errors.New("expected format like /store//key") + case paths[0] != "store": + return "", errors.New("expected format like /store//key") + case paths[2] != "key": + return "", errors.New("expected format like /store//key") + } + return paths[1], nil +} + func (cliCtx CLIContext) GetCoinType(coinName string) (types.CoinType, error) { var coinType types.CoinType coinName = strings.ToLower(coinName) @@ -413,7 +297,7 @@ func (cliCtx CLIContext) GetCoinType(coinName string) (types.CoinType, error) { return types.CoinType{}, fmt.Errorf("unsupported coin type \"%s\"", coinName) } - if err = cliCtx.Codec.UnmarshalBinary(bz, &coinType); err != nil { + if err = cliCtx.Codec.UnmarshalBinaryLengthPrefixed(bz, &coinType); err != nil { return coinType, err } } @@ -421,49 +305,27 @@ func (cliCtx CLIContext) GetCoinType(coinName string) (types.CoinType, error) { return coinType, nil } -func (cliCtx CLIContext) NetInfo() (*ctypes.ResultNetInfo, error) { - client := cliCtx.Client.(*tmclient.HTTP) - return client.NetInfo() -} - -func (cliCtx CLIContext) NumUnconfirmedTxs() (*ctypes.ResultUnconfirmedTxs, error) { - client := &http.Client{} - url := strings.Replace(cliCtx.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 := cliCtx.Codec.UnmarshalJSON(body, &res); err != nil { - return nil, err +func (cliCtx CLIContext) ConvertCoinToMainUnit(coinsStr string) (coins []string, err error) { + coinsStr = strings.TrimSpace(coinsStr) + if len(coinsStr) == 0 { + return coins, nil } - return &res.Result, nil -} + coinStrs := strings.Split(coinsStr, ",") + for _, coinStr := range coinStrs { + mainUnit, err := types.GetCoinName(coinStr) + coinType, err := cliCtx.GetCoinType(mainUnit) + if err != nil { + return nil, err + } -// Certify verifies the consensus proof at given height -func (cliCtx CLIContext) Certify(height int64) (lite.Commit, error) { - check, err := tmliteProxy.GetCertifiedCommit(height, cliCtx.Client, cliCtx.Certifier) - if tmliteErr.IsCommitNotFoundErr(err) { - return lite.Commit{}, ErrVerifyCommit(height) - } else if err != nil { - return lite.Commit{}, err + coin, err := coinType.Convert(coinStr, mainUnit) + if err != nil { + return nil, err + } + coins = append(coins, coin) } - return check, nil + return coins, nil } func (cliCtx CLIContext) ParseCoin(coinStr string) (sdk.Coin, error) { @@ -497,42 +359,40 @@ func (cliCtx CLIContext) ParseCoins(coinsStr string) (coins sdk.Coins, err error return coins, nil } -func (cliCtx CLIContext) ConvertCoinToMainUnit(coinsStr string) (coins []string, err error) { - coinsStr = strings.TrimSpace(coinsStr) - if len(coinsStr) == 0 { - return coins, nil +func (cliCtx CLIContext) NetInfo() (*ctypes.ResultNetInfo, error) { + client, err := cliCtx.GetNode() + if err != nil { + return nil, err } + httpClient := client.(*tmclient.HTTP) + return httpClient.NetInfo() +} - coinStrs := strings.Split(coinsStr, ",") - for _, coinStr := range coinStrs { - mainUnit, err := types.GetCoinName(coinStr) - coinType, err := cliCtx.GetCoinType(mainUnit) - if err != nil { - return nil, err - } +func (cliCtx CLIContext) NumUnconfirmedTxs() (*ctypes.ResultUnconfirmedTxs, error) { + client := &http.Client{} + url := strings.Replace(cliCtx.NodeURI, "tcp", "http", 1) + reqUri := fmt.Sprintf("%s/%s", url, "num_unconfirmed_txs") - coin, err := coinType.Convert(coinStr, mainUnit) - if err != nil { - return nil, err - } - coins = append(coins, coin) + resp, err := client.Get(reqUri) + if err != nil { + return nil, err } - return coins, nil -} + defer resp.Body.Close() -// isQueryStoreWithProof expects a format like /// -// queryType can be app or store -func isQueryStoreWithProof(path string) bool { - if !strings.HasPrefix(path, "/") { - return false - } - paths := strings.SplitN(path[1:], "/", 3) - if len(paths) != 3 { - return false + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err } - if store.RequireProof("/" + paths[2]) { - return true + var res = struct { + JsonRpc string `json:"jsonrpc"` + Id string `json:"id"` + Result ctypes.ResultUnconfirmedTxs `json:"result"` + }{} + + if err := cliCtx.Codec.UnmarshalJSON(body, &res); err != nil { + return nil, err } - return false + + return &res.Result, nil } diff --git a/client/context/txcontext.go b/client/context/txcontext.go index 7912f0f71..7ac1ccb9d 100644 --- a/client/context/txcontext.go +++ b/client/context/txcontext.go @@ -2,114 +2,120 @@ package context import ( "fmt" + "net/http" + "strings" + + "github.com/pkg/errors" + "github.com/spf13/viper" + + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/auth" + authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" "github.com/irisnet/irishub/client" "github.com/irisnet/irishub/client/keys" - "github.com/spf13/viper" - "os" ) -type BaseTx struct { - LocalAccountName string `json:"name"` - Password string `json:"password"` - ChainID string `json:"chain_id"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` - Gas int64 `json:"gas"` - Fees string `json:"fee"` - Memo string `json:"memo"` -} - -func (baseTx BaseTx) Validate(cliCtx CLIContext) error { - if cliCtx.GenerateOnly { - if len(baseTx.LocalAccountName) == 0 && len(cliCtx.SignerAddr) == 0 { - return ErrInvalidBaseTx("In generate-only mode, either key name or signer address should be specified") - } - } else { - if len(baseTx.LocalAccountName) == 0 { - return ErrInvalidBaseTx("In non-generate-only mode, name required but not specified") - } - if len(baseTx.Password) == 0 { - return ErrInvalidBaseTx("In non-generate-only mode, password required but not specified") - } - } +//---------------------------------------- +// Building / Sending utilities - if len(baseTx.ChainID) == 0 { - return ErrInvalidBaseTx("ChainID required but not specified") - } +// BaseReq defines a structure that can be embedded in other request structures +// that all share common "base" fields. +type BaseTx struct { + Name string `json:"name"` + Password string `json:"password"` + ChainID string `json:"chain_id"` + AccountNumber int64 `json:"account_number"` + Sequence int64 `json:"sequence"` + Gas string `json:"gas"` + GasAdjustment string `json:"gas_adjustment"` + Fee string `json:"fee"` +} - if baseTx.AccountNumber < 0 { - return ErrInvalidBaseTx("Account Number required but not specified") +// Sanitize performs basic sanitization on a BaseReq object. +func (br BaseTx) Sanitize() BaseTx { + return BaseTx{ + Name: strings.TrimSpace(br.Name), + Password: strings.TrimSpace(br.Password), + ChainID: strings.TrimSpace(br.ChainID), + Gas: strings.TrimSpace(br.Gas), + Fee: strings.TrimSpace(br.Fee), + GasAdjustment: strings.TrimSpace(br.GasAdjustment), + AccountNumber: br.AccountNumber, + Sequence: br.Sequence, } +} - if baseTx.Sequence < 0 { - return ErrInvalidBaseTx("Sequence required but not specified") - } +// ValidateBasic performs basic validation of a BaseReq. If custom validation +// logic is needed, the implementing request handler should perform those +// checks manually. +func (br BaseTx) ValidateBasic(w http.ResponseWriter, cliCtx CLIContext) bool { + switch { + case !cliCtx.GenerateOnly && len(br.Name) == 0: + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("name required but not specified")) + return false - if baseTx.Gas < 0 { - return ErrInvalidBaseTx("Gas should not be less then zero") - } + case !cliCtx.GenerateOnly && len(br.Password) == 0: + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte("password required but not specified")) + return false - if len(baseTx.Fees) == 0 { - return ErrInvalidBaseTx("Fee required but not specified") + case len(br.ChainID) == 0: + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("chainID required but not specified")) + return false } - return nil + return true } // TxContext implements a transaction context created in SDK modules. type TxContext struct { - Codec *wire.Codec + Codec *codec.Codec cliCtx CLIContext AccountNumber int64 Sequence int64 - Gas int64 + Gas int64 // TODO: should this turn into uint64? requires further discussion - see #2173 + GasAdjustment float64 + SimulateGas bool ChainID string Memo string Fee string } -// NewTxContextFromCLI returns a new initialized TxContext with parameters from +// NewTxBuilderFromCLI returns a new initialized TxContext with parameters from // the command line using Viper. func NewTxContextFromCLI() TxContext { // if chain ID is not specified manually, read default chain ID chainID := viper.GetString(client.FlagChainID) if chainID == "" { - fmt.Printf("must specify --chain-id") - os.Exit(1) + defaultChainID, err := sdk.DefaultChainID() + if err != nil { + chainID = defaultChainID + } } return TxContext{ ChainID: chainID, - Gas: viper.GetInt64(client.FlagGas), AccountNumber: viper.GetInt64(client.FlagAccountNumber), + Gas: client.GasFlagVar.Gas, + GasAdjustment: viper.GetFloat64(client.FlagGasAdjustment), Sequence: viper.GetInt64(client.FlagSequence), + SimulateGas: client.GasFlagVar.Simulate, Fee: viper.GetString(client.FlagFee), Memo: viper.GetString(client.FlagMemo), } } -func NewTxContextFromBaseTx(cliCtx CLIContext, cdc *wire.Codec, baseTx BaseTx) (TxContext, error) { - err := baseTx.Validate(cliCtx) - if err != nil { - return TxContext{}, err - } - return TxContext{ - Codec: cdc, - cliCtx: cliCtx, - ChainID: baseTx.ChainID, - Gas: baseTx.Gas, - AccountNumber: baseTx.AccountNumber, - Sequence: baseTx.Sequence, - Fee: baseTx.Fees, - Memo: baseTx.Memo, - }, nil +// WithCodec returns a copy of the context with an updated codec. +func (txCtx TxContext) WithCliCtx(ctx CLIContext) TxContext { + txCtx.cliCtx = ctx + return txCtx } // WithCodec returns a copy of the context with an updated codec. -func (txCtx TxContext) WithCodec(cdc *wire.Codec) TxContext { +func (txCtx TxContext) WithCodec(cdc *codec.Codec) TxContext { txCtx.Codec = cdc return txCtx } @@ -150,31 +156,25 @@ func (txCtx TxContext) WithAccountNumber(accnum int64) TxContext { return txCtx } -// WithCliCtx returns a copy of the context with a CLIContext -func (txCtx TxContext) WithCliCtx(cliCtx CLIContext) TxContext { - txCtx.cliCtx = cliCtx - return txCtx -} - // 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 (txCtx TxContext) Build(msgs []sdk.Msg) (auth.StdSignMsg, error) { +func (txCtx TxContext) Build(msgs []sdk.Msg) (authtxb.StdSignMsg, error) { chainID := txCtx.ChainID if chainID == "" { - return auth.StdSignMsg{}, fmt.Errorf("chain ID required but not specified") + return authtxb.StdSignMsg{}, errors.Errorf("chain ID required but not specified") } fee := sdk.Coins{} if txCtx.Fee != "" { parsedFee, err := txCtx.cliCtx.ParseCoins(txCtx.Fee) if err != nil { - return auth.StdSignMsg{}, fmt.Errorf("encountered error in parsing transaction fee: %s", err.Error()) + return authtxb.StdSignMsg{}, fmt.Errorf("encountered error in parsing transaction fee: %s", err.Error()) } fee = parsedFee } - return auth.StdSignMsg{ + return authtxb.StdSignMsg{ ChainID: txCtx.ChainID, AccountNumber: txCtx.AccountNumber, Sequence: txCtx.Sequence, @@ -186,13 +186,42 @@ func (txCtx TxContext) Build(msgs []sdk.Msg) (auth.StdSignMsg, error) { // Sign signs a transaction given a name, passphrase, and a single message to // signed. An error is returned if signing fails. -func (txCtx TxContext) Sign(name, passphrase string, msg auth.StdSignMsg) ([]byte, error) { +func (txCtx TxContext) Sign(name, passphrase string, msg authtxb.StdSignMsg) ([]byte, error) { + sig, err := MakeSignature(name, passphrase, msg) + if err != nil { + return nil, err + } + return txCtx.Codec.MarshalBinaryLengthPrefixed(auth.NewStdTx(msg.Msgs, msg.Fee, []auth.StdSignature{sig}, msg.Memo)) +} + +// BuildAndSign builds a single message to be signed, and signs a transaction +// with the built message given a name, passphrase, and a set of +// messages. +func (txCtx TxContext) BuildAndSign(name, passphrase string, msgs []sdk.Msg) ([]byte, error) { + msg, err := txCtx.Build(msgs) + if err != nil { + return nil, err + } + + return txCtx.Sign(name, passphrase, msg) +} + +// BuildWithPubKey builds a single message to be signed from a TxContext given a set of +// messages and attach the public key associated to the given name. +// It returns an error if a fee is supplied but cannot be parsed or the key cannot be +// retrieved. +func (txCtx TxContext) BuildWithPubKey(name string, msgs []sdk.Msg) ([]byte, error) { + msg, err := txCtx.Build(msgs) + if err != nil { + return nil, err + } + keybase, err := keys.GetKeyBase() if err != nil { return nil, err } - sig, pubkey, err := keybase.Sign(name, passphrase, msg.Bytes()) + info, err := keybase.Get(name) if err != nil { return nil, err } @@ -200,21 +229,51 @@ func (txCtx TxContext) Sign(name, passphrase string, msg auth.StdSignMsg) ([]byt sigs := []auth.StdSignature{{ AccountNumber: msg.AccountNumber, Sequence: msg.Sequence, - PubKey: pubkey, - Signature: sig, + PubKey: info.GetPubKey(), }} - return txCtx.Codec.MarshalBinary(auth.NewStdTx(msg.Msgs, msg.Fee, sigs, msg.Memo)) + return txCtx.Codec.MarshalBinaryLengthPrefixed(auth.NewStdTx(msg.Msgs, msg.Fee, sigs, msg.Memo)) } -// BuildAndSign builds a single message to be signed, and signs a transaction -// with the built message given a name, passphrase, and a set of -// messages. -func (txCtx TxContext) BuildAndSign(name, passphrase string, msgs []sdk.Msg) ([]byte, error) { - msg, err := txCtx.Build(msgs) +// SignStdTx appends a signature to a StdTx and returns a copy of a it. If append +// is false, it replaces the signatures already attached with the new signature. +func (txCtx TxContext) SignStdTx(name, passphrase string, stdTx auth.StdTx, appendSig bool) (signedStdTx auth.StdTx, err error) { + stdSignature, err := MakeSignature(name, passphrase, authtxb.StdSignMsg{ + ChainID: txCtx.ChainID, + AccountNumber: txCtx.AccountNumber, + Sequence: txCtx.Sequence, + Fee: stdTx.Fee, + Msgs: stdTx.GetMsgs(), + Memo: stdTx.GetMemo(), + }) if err != nil { - return nil, err + return } - return txCtx.Sign(name, passphrase, msg) + sigs := stdTx.GetSignatures() + if len(sigs) == 0 || !appendSig { + sigs = []auth.StdSignature{stdSignature} + } else { + sigs = append(sigs, stdSignature) + } + signedStdTx = auth.NewStdTx(stdTx.GetMsgs(), stdTx.Fee, sigs, stdTx.GetMemo()) + return +} + +// MakeSignature builds a StdSignature given key name, passphrase, and a StdSignMsg. +func MakeSignature(name, passphrase string, msg authtxb.StdSignMsg) (sig auth.StdSignature, err error) { + keybase, err := keys.GetKeyBase() + if err != nil { + return + } + sigBytes, pubkey, err := keybase.Sign(name, passphrase, msg.Bytes()) + if err != nil { + return + } + return auth.StdSignature{ + AccountNumber: msg.AccountNumber, + Sequence: msg.Sequence, + PubKey: pubkey, + Signature: sigBytes, + }, nil } diff --git a/client/slashing/cli/flags.go b/client/distribution/cli/flags.go similarity index 60% rename from client/slashing/cli/flags.go rename to client/distribution/cli/flags.go index 43f8fa90a..f0345f3ca 100644 --- a/client/slashing/cli/flags.go +++ b/client/distribution/cli/flags.go @@ -1,6 +1,6 @@ package cli -// nolint const ( + FlagAddressDelegator = "address-delegator" FlagAddressValidator = "address-validator" ) diff --git a/client/distribution/cli/query.go b/client/distribution/cli/query.go new file mode 100644 index 000000000..85300f4f5 --- /dev/null +++ b/client/distribution/cli/query.go @@ -0,0 +1,186 @@ +package cli + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/irisnet/irishub/client/context" + distributionclient "github.com/irisnet/irishub/client/distribution" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// GetWithdrawAddress returns withdraw address of a given delegator address +func GetWithdrawAddress(storeName string, cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "withdraw-address", + Short: "Query withdraw address", + Example: "iriscli distribution withdraw-address ", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + // find the key to look up the account + addrString := args[0] + + delAddr, err := sdk.AccAddressFromBech32(addrString) + if err != nil { + return err + } + + key := distribution.GetDelegatorWithdrawAddrKey(delAddr) + + cliCtx := context.NewCLIContext().WithCodec(cdc) + + res, err := cliCtx.QueryStore(key, storeName) + if err != nil { + return err + } + if len(res) == 0 { + fmt.Println("No withdraw address specified. If the delegator does have valid delegations, then the withdraw address should be the same as the delegator address") + return nil + } + withdrawAddress := sdk.AccAddress(res) + + fmt.Println(withdrawAddress.String()) + return nil + }, + } +} + +// GetDelegationDistInfo returns the delegation distribution information of a given delegation +func GetDelegationDistInfo(storeName string, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "delegation-distr-info", + Short: "Query delegation distribution information", + Example: "iriscli distribution delegation-distr-info --address-delegator= --address-validator=", + RunE: func(cmd *cobra.Command, args []string) error { + + valAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidator)) + if err != nil { + return err + } + delAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressDelegator)) + if err != nil { + return err + } + + key := distribution.GetDelegationDistInfoKey(delAddr, valAddr) + + cliCtx := context.NewCLIContext().WithCodec(cdc) + + res, err := cliCtx.QueryStore(key, storeName) + if err != nil { + return err + } + var ddi types.DelegationDistInfo + err = cdc.UnmarshalBinaryLengthPrefixed(res, &ddi) + if err != nil { + return err + } + + output, err := codec.MarshalJSONIndent(cdc, ddi) + if err != nil { + return err + } + + fmt.Println(string(output)) + return nil + }, + } + cmd.Flags().String(FlagAddressDelegator, "", "bech address of the delegator") + cmd.Flags().String(FlagAddressValidator, "", "bech address of the validator") + cmd.MarkFlagRequired(FlagAddressDelegator) + cmd.MarkFlagRequired(FlagAddressValidator) + return cmd +} + +// GetAllDelegationDistInfo returns all delegation distribution information of a given delegator +func GetAllDelegationDistInfo(storeName string, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "delegator-distr-info", + Short: "Query delegator distribution information", + Example: "iriscli distribution delegator-distr-info ", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + addrString := args[0] + + delAddr, err := sdk.AccAddressFromBech32(addrString) + if err != nil { + return err + } + + key := distribution.GetDelegationDistInfosKey(delAddr) + + cliCtx := context.NewCLIContext().WithCodec(cdc) + + resKVs, err := cliCtx.QuerySubspace(key, storeName) + if err != nil { + return err + } + var ddiList []types.DelegationDistInfo + for _, kv := range resKVs { + var ddi types.DelegationDistInfo + err = cdc.UnmarshalBinaryLengthPrefixed(kv.Value, &ddi) + if err != nil { + return err + } + ddiList = append(ddiList, ddi) + } + + output, err := codec.MarshalJSONIndent(cdc, ddiList) + if err != nil { + return err + } + + fmt.Println(string(output)) + return nil + }, + } + return cmd +} + +// GetValidatorDistInfo returns the validator distribution information of a given validator +func GetValidatorDistInfo(storeName string, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "validator-distr-info", + Short: "Query validator distribution information", + Example: "iriscli distribution validator-distr-info ", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + + addrString := args[0] + + valAddr, err := sdk.ValAddressFromBech32(addrString) + if err != nil { + return err + } + + key := distribution.GetValidatorDistInfoKey(valAddr) + + cliCtx := context.NewCLIContext().WithCodec(cdc) + + res, err := cliCtx.QueryStore(key, storeName) + if err != nil { + return err + } + var vdi types.ValidatorDistInfo + err = cdc.UnmarshalBinaryLengthPrefixed(res, &vdi) + if err != nil { + return err + } + + vdiOutput := distributionclient.ConvertToValidatorDistInfoOutput(cliCtx, vdi) + + output, err := codec.MarshalJSONIndent(cdc, vdiOutput) + if err != nil { + return err + } + + fmt.Println(string(output)) + return nil + }, + } + return cmd +} diff --git a/client/distribution/cli/sendtx.go b/client/distribution/cli/sendtx.go new file mode 100644 index 000000000..32e6505ba --- /dev/null +++ b/client/distribution/cli/sendtx.go @@ -0,0 +1,119 @@ +// nolint +package cli + +import ( + "fmt" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + + "os" + + "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/irisnet/irishub/client/context" + "github.com/irisnet/irishub/client/utils" +) + +var ( + flagOnlyFromValidator = "only-from-validator" + flagIsValidator = "is-validator" +) + +// command to withdraw rewards +func GetCmdWithdrawRewards(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "withdraw-rewards", + Short: "withdraw rewards for either: all-delegations, a delegation, or a validator", + Example: "iriscli distribution withdraw-rewards --from --fee=0.004iris --chain-id=", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + + onlyFromVal := viper.GetString(flagOnlyFromValidator) + isVal := viper.GetBool(flagIsValidator) + + if onlyFromVal != "" && isVal { + return fmt.Errorf("cannot use --%v, and --%v flags together", + flagOnlyFromValidator, flagIsValidator) + } + + cliCtx := context.NewCLIContext(). + WithCodec(cdc). + WithLogger(os.Stdout). + WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc).WithCliCtx(cliCtx) + + var msg sdk.Msg + switch { + case isVal: + addr, err := cliCtx.GetFromAddress() + if err != nil { + return err + } + valAddr := sdk.ValAddress(addr.Bytes()) + msg = types.NewMsgWithdrawValidatorRewardsAll(valAddr) + case onlyFromVal != "": + delAddr, err := cliCtx.GetFromAddress() + if err != nil { + return err + } + + valAddr, err := sdk.ValAddressFromBech32(onlyFromVal) + if err != nil { + return err + } + + msg = types.NewMsgWithdrawDelegatorReward(delAddr, valAddr) + default: + delAddr, err := cliCtx.GetFromAddress() + if err != nil { + return err + } + msg = types.NewMsgWithdrawDelegatorRewardsAll(delAddr) + } + + // build and sign the transaction, then broadcast to Tendermint + return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) + }, + } + cmd.Flags().String(flagOnlyFromValidator, "", "only withdraw from this validator address (in bech)") + cmd.Flags().Bool(flagIsValidator, false, "also withdraw validator's commission") + return cmd +} + +// GetCmdDelegate implements the delegate command. +func GetCmdSetWithdrawAddr(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "set-withdraw-addr [withdraw-addr]", + Short: "change the default withdraw address for rewards associated with an address", + Example: "iriscli distribution set-withdraw-addr
--from --fee=0.004iris --chain-id=", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + + cliCtx := context.NewCLIContext(). + WithCodec(cdc). + WithLogger(os.Stdout). + WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc).WithCliCtx(cliCtx) + + delAddr, err := cliCtx.GetFromAddress() + if err != nil { + return err + } + + withdrawAddr, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { + return err + } + + msg := types.NewMsgSetWithdrawAddress(delAddr, withdrawAddr) + + // build and sign the transaction, then broadcast to Tendermint + return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) + }, + } + return cmd +} diff --git a/client/distribution/lcd/query.go b/client/distribution/lcd/query.go new file mode 100644 index 000000000..fa4477953 --- /dev/null +++ b/client/distribution/lcd/query.go @@ -0,0 +1,151 @@ +package lcd + +import ( + "net/http" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/gorilla/mux" + "github.com/irisnet/irishub/client/context" + distributionclient "github.com/irisnet/irishub/client/distribution" + "github.com/irisnet/irishub/client/utils" +) + +// QueryWithdrawAddressHandlerFn performs withdraw address query +func QueryWithdrawAddressHandlerFn(storeName string, cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + bech32addr := vars["delegatorAddr"] + + delAddr, err := sdk.AccAddressFromBech32(bech32addr) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + key := distribution.GetDelegatorWithdrawAddrKey(delAddr) + + res, err := cliCtx.QueryStore(key, storeName) + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + if len(res) == 0 { + utils.WriteErrorResponse(w, http.StatusNoContent, "") + return + } + withdrawAddress := sdk.AccAddress(res) + + w.Write([]byte(withdrawAddress.String())) + } +} + +// QueryDelegatorDistInfoHandlerFn query all delegation distribution info of the specified delegator +func QueryDelegatorDistInfoHandlerFn(storeName string, cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + bech32addr := vars["delegatorAddr"] + + delAddr, err := sdk.AccAddressFromBech32(bech32addr) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + key := distribution.GetDelegationDistInfosKey(delAddr) + resKVs, err := cliCtx.QuerySubspace(key, storeName) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + var ddiList []types.DelegationDistInfo + for _, kv := range resKVs { + var ddi types.DelegationDistInfo + err = cliCtx.Codec.UnmarshalBinaryLengthPrefixed(kv.Value, &ddi) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + ddiList = append(ddiList, ddi) + } + utils.PostProcessResponse(w, cliCtx.Codec, ddiList, cliCtx.Indent) + } +} + +// QueryDelegationDistInfoHandlerFn query delegation distribution info +func QueryDelegationDistInfoHandlerFn(storeName string, cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + + delegatorAddrStr := vars["delegatorAddr"] + delAddr, err := sdk.AccAddressFromBech32(delegatorAddrStr) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + validatorAddrStr := vars["validatorAddr"] + valAddr, err := sdk.ValAddressFromBech32(validatorAddrStr) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + key := distribution.GetDelegationDistInfoKey(delAddr, valAddr) + res, err := cliCtx.QueryStore(key, storeName) + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + if len(res) == 0 { + utils.WriteErrorResponse(w, http.StatusNoContent, "") + return + } + + var ddi types.DelegationDistInfo + err = cliCtx.Codec.UnmarshalBinaryLengthPrefixed(res, &ddi) + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + utils.PostProcessResponse(w, cliCtx.Codec, ddi, cliCtx.Indent) + } +} + +// QueryValidatorDistInfoHandlerFn query validator distribution info +func QueryValidatorDistInfoHandlerFn(storeName string, cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + + validatorAddrStr := vars["validatorAddr"] + valAddr, err := sdk.ValAddressFromBech32(validatorAddrStr) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + key := distribution.GetValidatorDistInfoKey(valAddr) + + res, err := cliCtx.QueryStore(key, storeName) + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + if len(res) == 0 { + utils.WriteErrorResponse(w, http.StatusNoContent, "") + return + } + + var vdi types.ValidatorDistInfo + err = cliCtx.Codec.UnmarshalBinaryLengthPrefixed(res, &vdi) + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + vdiOutput := distributionclient.ConvertToValidatorDistInfoOutput(cliCtx, vdi) + + utils.PostProcessResponse(w, cliCtx.Codec, vdiOutput, cliCtx.Indent) + } +} diff --git a/client/distribution/lcd/rest.go b/client/distribution/lcd/rest.go new file mode 100644 index 000000000..da3cda0bd --- /dev/null +++ b/client/distribution/lcd/rest.go @@ -0,0 +1,24 @@ +package lcd + +import ( + "github.com/cosmos/cosmos-sdk/codec" + "github.com/gorilla/mux" + "github.com/irisnet/irishub/client/context" +) + +const storeName = "distr" + +// RegisterRoutes - Central function to define routes that get registered by the main application +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { + r.HandleFunc("/distribution/{delegatorAddr}/withdrawAddress", SetWithdrawAddressHandlerFn(cdc, cliCtx)).Methods("POST") + r.HandleFunc("/distribution/{delegatorAddr}/withdrawReward", WithdrawRewardsHandlerFn(cdc, cliCtx)).Methods("POST") + + r.HandleFunc("/distribution/{delegatorAddr}/withdrawAddress", + QueryWithdrawAddressHandlerFn(storeName, cliCtx)).Methods("GET") + r.HandleFunc("/distribution/{delegatorAddr}/distrInfo/{validatorAddr}", + QueryDelegationDistInfoHandlerFn(storeName, cliCtx)).Methods("GET") + r.HandleFunc("/distribution/{delegatorAddr}/distrInfos", + QueryDelegatorDistInfoHandlerFn(storeName, cliCtx)).Methods("GET") + r.HandleFunc("/distribution/{validatorAddr}/valDistrInfo", + QueryValidatorDistInfoHandlerFn(storeName, cliCtx)).Methods("GET") +} diff --git a/client/distribution/lcd/sendtx.go b/client/distribution/lcd/sendtx.go new file mode 100644 index 000000000..3f480706f --- /dev/null +++ b/client/distribution/lcd/sendtx.go @@ -0,0 +1,97 @@ +package lcd + +import ( + "net/http" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/gorilla/mux" + "github.com/irisnet/irishub/client/context" + "github.com/irisnet/irishub/client/utils" +) + +type setWithdrawAddressBody struct { + WithdrawAddress sdk.AccAddress `json:"withdraw_address"` + BaseTx context.BaseTx `json:"base_tx"` +} + +// SetWithdrawAddressHandlerFn - http request handler to set withdraw address +// nolint: gocyclo +func SetWithdrawAddressHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + // Init context and read request parameters + vars := mux.Vars(r) + bech32addr := vars["delegatorAddr"] + delegatorAddress, err := sdk.AccAddressFromBech32(bech32addr) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + cliCtx = utils.InitReqCliCtx(cliCtx, r) + var m setWithdrawAddressBody + err = utils.ReadPostBody(w, r, cdc, &m) + if err != nil { + return + } + baseReq := m.BaseTx.Sanitize() + if !baseReq.ValidateBasic(w, cliCtx) { + return + } + // Build message + msg := types.NewMsgSetWithdrawAddress(delegatorAddress, m.WithdrawAddress) + // Broadcast or return unsigned transaction + utils.SendOrReturnUnsignedTx(w, cliCtx, m.BaseTx, []sdk.Msg{msg}) + } +} + +type withdrawRewardsBody struct { + ValidatorAddress sdk.ValAddress `json:"validator_address"` + IsValidator bool `json:"is_validator"` + BaseTx context.BaseTx `json:"base_tx"` +} + +func WithdrawRewardsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + // Init context and read request parameters + vars := mux.Vars(r) + bech32addr := vars["delegatorAddr"] + delegatorAddress, err := sdk.AccAddressFromBech32(bech32addr) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + cliCtx = utils.InitReqCliCtx(cliCtx, r) + var m withdrawRewardsBody + err = utils.ReadPostBody(w, r, cdc, &m) + if err != nil { + return + } + baseReq := m.BaseTx.Sanitize() + if !baseReq.ValidateBasic(w, cliCtx) { + return + } + // Build message + onlyFromVal := m.ValidatorAddress + isVal := m.IsValidator + if onlyFromVal != nil && isVal { + utils.WriteErrorResponse(w, http.StatusBadRequest, "if is_validator is true, validator_address should not be specified") + return + } + + var msg sdk.Msg + switch { + case isVal: + valAddr := sdk.ValAddress(delegatorAddress) + msg = types.NewMsgWithdrawValidatorRewardsAll(valAddr) + case onlyFromVal != nil: + msg = types.NewMsgWithdrawDelegatorReward(delegatorAddress, m.ValidatorAddress) + default: + msg = types.NewMsgWithdrawDelegatorRewardsAll(delegatorAddress) + } + // Broadcast or return unsigned transaction + utils.SendOrReturnUnsignedTx(w, cliCtx, m.BaseTx, []sdk.Msg{msg}) + } +} diff --git a/client/distribution/utils.go b/client/distribution/utils.go new file mode 100644 index 000000000..37eb44033 --- /dev/null +++ b/client/distribution/utils.go @@ -0,0 +1,31 @@ +package distribution + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/client/context" + "github.com/irisnet/irishub/client/utils" +) + +// distribution info for a particular validator +type ValidatorDistInfoOutput struct { + OperatorAddr sdk.ValAddress `json:"operator_addr"` + FeePoolWithdrawalHeight int64 `json:"fee_pool_withdrawal_height"` + DelAccum distribution.TotalAccum `json:"del_accum"` + DelPool string `json:"del_pool"` + ValCommission string `json:"val_commission"` +} + +func ConvertToValidatorDistInfoOutput(cliCtx context.CLIContext, vdi distribution.ValidatorDistInfo) ValidatorDistInfoOutput { + exRate := utils.ExRateFromStakeTokenToMainUnit(cliCtx) + delPool := utils.ConvertDecToRat(vdi.DelPool.AmountOf(app.Denom+"-"+"atto")).Mul(exRate).FloatString() + app.Denom + valCommission := utils.ConvertDecToRat(vdi.ValCommission.AmountOf(app.Denom+"-"+"atto")).Mul(exRate).FloatString() + app.Denom + return ValidatorDistInfoOutput{ + OperatorAddr: vdi.OperatorAddr, + FeePoolWithdrawalHeight: vdi.FeePoolWithdrawalHeight, + DelAccum: vdi.DelAccum, + DelPool: delPool, + ValCommission: valCommission, + } +} diff --git a/client/flags.go b/client/flags.go index 05806f8e7..ab2ec5c28 100644 --- a/client/flags.go +++ b/client/flags.go @@ -1,34 +1,47 @@ package client -import "github.com/spf13/cobra" +import ( + "fmt" + "strconv" + + "github.com/spf13/cobra" +) // nolint const ( - FlagUseLedger = "ledger" - FlagChainID = "chain-id" - FlagNode = "node" - FlagHeight = "height" - FlagGas = "gas" - FlagTrustNode = "trust-node" - FlagFrom = "from" - FlagSignerAddr = "signer-addr" - FlagAccountNumber = "account-number" - FlagSequence = "sequence" - FlagMemo = "memo" - FlagFee = "fee" - FlagAsync = "async" - FlagJson = "json" - FlagPrintResponse = "print-response" - FlagGenerateOnly = "generate-only" -) + // DefaultGasAdjustment is applied to gas estimates to avoid tx + // execution failures due to state changes that might + // occur between the tx simulation and the actual run. + DefaultGasAdjustment = 1.0 + DefaultGasLimit = 200000 + GasFlagSimulate = "simulate" -// LineBreak can be included in a command list to provide a blank line -// to help with readability -var LineBreak = &cobra.Command{Run: func(*cobra.Command, []string) {}} + FlagUseLedger = "ledger" + FlagChainID = "chain-id" + FlagNode = "node" + FlagHeight = "height" + FlagGas = "gas" + FlagTrustNode = "trust-node" + FlagFrom = "from" + FlagFromAddr = "from-addr" + FlagAccountNumber = "account-number" + FlagSequence = "sequence" + FlagMemo = "memo" + FlagFee = "fee" + FlagAsync = "async" + FlagJson = "json" + FlagPrintResponse = "print-response" + FlagGenerateOnly = "generate-only" + FlagName = "name" + FlagIndentResponse = "indent" + FlagDryRun = "dry-run" + FlagGasAdjustment = "gas-adjustment" +) // GetCommands adds common flags to query commands func GetCommands(cmds ...*cobra.Command) []*cobra.Command { for _, c := range cmds { + c.Flags().Bool(FlagIndentResponse, false, "Add indent to JSON response") c.Flags().Bool(FlagTrustNode, true, "Don't verify proofs for responses") c.Flags().Bool(FlagUseLedger, false, "Use a connected Ledger device") c.Flags().String(FlagChainID, "", "Chain ID of tendermint node") @@ -41,6 +54,7 @@ func GetCommands(cmds ...*cobra.Command) []*cobra.Command { // PostCommands adds common flags for commands to post tx func PostCommands(cmds ...*cobra.Command) []*cobra.Command { for _, c := range cmds { + c.Flags().Bool(FlagIndentResponse, false, "Add indent to JSON response") c.Flags().String(FlagFrom, "", "Name of private key with which to sign") c.Flags().Int64(FlagAccountNumber, 0, "AccountNumber number to sign the tx") c.Flags().Int64(FlagSequence, 0, "Sequence number to sign the tx") @@ -49,13 +63,64 @@ func PostCommands(cmds ...*cobra.Command) []*cobra.Command { c.Flags().String(FlagChainID, "", "Chain ID of tendermint node") c.Flags().String(FlagNode, "tcp://localhost:26657", ": to tendermint rpc interface for this chain") c.Flags().Bool(FlagUseLedger, false, "Use a connected Ledger device") - c.Flags().Int64(FlagGas, 200000, "gas limit to set per-transaction") + c.Flags().Var(&GasFlagVar, FlagGas, fmt.Sprintf( + "gas limit to set per-transaction; set to %q to calculate required gas automatically", GasFlagSimulate)) c.Flags().Bool(FlagAsync, false, "broadcast transactions asynchronously") c.Flags().Bool(FlagJson, false, "return output in json format") c.Flags().Bool(FlagTrustNode, true, "Don't verify proofs for responses") c.Flags().Bool(FlagPrintResponse, false, "return tx response (only works with async = false)") c.Flags().Bool(FlagGenerateOnly, false, "build an unsigned transaction and write it to STDOUT") - c.Flags().String(FlagSignerAddr, "", "Specify signer address for generate-only mode") + c.Flags().String(FlagFromAddr, "", "Specify from address in generate-only mode") + c.Flags().Bool(FlagDryRun, false, "ignore the --gas flag and perform a simulation of a transaction, but don't broadcast it") + c.Flags().Float64(FlagGasAdjustment, DefaultGasAdjustment, "adjustment factor to be multiplied against the estimate returned by the tx simulation; if the gas limit is set manually this flag is ignored ") } return cmds } + +// LineBreak can be included in a command list to provide a blank line +// to help with readability +var ( + LineBreak = &cobra.Command{Run: func(*cobra.Command, []string) {}} + GasFlagVar = GasSetting{Gas: DefaultGasLimit} +) + +// Gas flag parsing functions + +// GasSetting encapsulates the possible values passed through the --gas flag. +type GasSetting struct { + Simulate bool + Gas int64 +} + +// Type returns the flag's value type. +func (v *GasSetting) Type() string { return "string" } + +// Set parses and sets the value of the --gas flag. +func (v *GasSetting) Set(s string) (err error) { + v.Simulate, v.Gas, err = ReadGasFlag(s) + return +} + +func (v *GasSetting) String() string { + if v.Simulate { + return GasFlagSimulate + } + return strconv.FormatInt(v.Gas, 10) +} + +// ParseGasFlag parses the value of the --gas flag. +func ReadGasFlag(s string) (simulate bool, gas int64, err error) { + switch s { + case "": + gas = DefaultGasLimit + case GasFlagSimulate: + simulate = true + default: + gas, err = strconv.ParseInt(s, 10, 64) + if err != nil { + err = fmt.Errorf("gas must be either integer or %q", GasFlagSimulate) + return + } + } + return +} diff --git a/client/gov/cli/flags.go b/client/gov/cli/flags.go index 22caedfed..400854d2f 100644 --- a/client/gov/cli/flags.go +++ b/client/gov/cli/flags.go @@ -8,9 +8,9 @@ const ( flagDeposit = "deposit" flagVoter = "voter" flagOption = "option" - flagDepositer = "depositer" + flagDepositor = "depositor" flagStatus = "status" - flagLatestProposalIDs = "latest" + flagNumLimit = "limit" flagParam = "param" flagOp = "op" ) diff --git a/client/gov/cli/query.go b/client/gov/cli/query.go index 99c1abd16..d2602adac 100644 --- a/client/gov/cli/query.go +++ b/client/gov/cli/query.go @@ -4,45 +4,42 @@ import ( "encoding/json" "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/irisnet/irishub/client/context" - govClient "github.com/irisnet/irishub/client/gov" "github.com/irisnet/irishub/modules/gov" "github.com/irisnet/irishub/modules/gov/params" - "github.com/irisnet/irishub/modules/iparam" + client "github.com/irisnet/irishub/client/gov" + "github.com/irisnet/irishub/iparam" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/irisnet/irishub/app" ) // GetCmdQueryProposal implements the query proposal command. -func GetCmdQueryProposal(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQueryProposal(queryRoute string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "query-proposal", - Short: "query proposal details", + Short: "Query details of a single proposal", Example: "iriscli gov query-proposal --proposal-id=1", RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - proposalID := viper.GetInt64(flagProposalID) + proposalID := uint64(viper.GetInt64(flagProposalID)) - res, err := cliCtx.QueryStore(gov.KeyProposal(proposalID), storeName) - if len(res) == 0 || err != nil { - return fmt.Errorf("proposalID [%d] is not existed", proposalID) + params := gov.QueryProposalParams{ + ProposalID: proposalID, } - var proposal gov.Proposal - cdc.MustUnmarshalBinary(res, &proposal) - - proposalResponse, err := govClient.ConvertProposalToProposalOutput(cliCtx, proposal) + bz, err := cdc.MarshalJSON(params) if err != nil { return err } - output, err := wire.MarshalJSONIndent(cdc, proposalResponse) + + res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/proposal", queryRoute), bz) if err != nil { return err } - fmt.Println(string(output)) + fmt.Println(string(res)) return nil }, } @@ -54,93 +51,61 @@ func GetCmdQueryProposal(storeName string, cdc *wire.Codec) *cobra.Command { // nolint: gocyclo // GetCmdQueryProposals implements a query proposals command. -func GetCmdQueryProposals(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQueryProposals(queryRoute string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "query-proposals", Short: "query proposals with optional filters", Example: "iriscli gov query-proposals --status=Passed", RunE: func(cmd *cobra.Command, args []string) error { - bechDepositerAddr := viper.GetString(flagDepositer) + bechDepositorAddr := viper.GetString(flagDepositor) bechVoterAddr := viper.GetString(flagVoter) strProposalStatus := viper.GetString(flagStatus) - latestProposalsIDs := viper.GetInt64(flagLatestProposalIDs) + numLimit := uint64(viper.GetInt64(flagNumLimit)) - var err error - var voterAddr sdk.AccAddress - var depositerAddr sdk.AccAddress - var proposalStatus gov.ProposalStatus + params := gov.QueryProposalsParams{ + Limit:numLimit, + } - if len(bechDepositerAddr) != 0 { - depositerAddr, err = sdk.AccAddressFromBech32(bechDepositerAddr) + if len(bechDepositorAddr) != 0 { + depositorAddr, err := sdk.AccAddressFromBech32(bechDepositorAddr) if err != nil { return err } + params.Depositor = depositorAddr } if len(bechVoterAddr) != 0 { - voterAddr, err = sdk.AccAddressFromBech32(bechVoterAddr) + voterAddr, err := sdk.AccAddressFromBech32(bechVoterAddr) if err != nil { return err } + params.Voter = voterAddr } if len(strProposalStatus) != 0 { - proposalStatus, err = gov.ProposalStatusFromString(strProposalStatus) + proposalStatus, err := gov.ProposalStatusFromString(client.NormalizeProposalStatus(strProposalStatus)) if err != nil { return err } + params.ProposalStatus = proposalStatus } - cliCtx := context.NewCLIContext().WithCodec(cdc) - - res, err := cliCtx.QueryStore(gov.KeyNextProposalID, storeName) + bz, err := cdc.MarshalJSON(params) if err != nil { return err } - var maxProposalID int64 - cdc.MustUnmarshalBinary(res, &maxProposalID) - matchingProposals := []govClient.ProposalOutput{} + cliCtx := context.NewCLIContext().WithCodec(cdc) - if latestProposalsIDs == 0 { - latestProposalsIDs = maxProposalID + res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/proposals", queryRoute), bz) + if err != nil { + return err } - - for proposalID := maxProposalID - latestProposalsIDs; proposalID < maxProposalID; proposalID++ { - if voterAddr != nil { - res, err = cliCtx.QueryStore(gov.KeyVote(proposalID, voterAddr), storeName) - if err != nil || len(res) == 0 { - continue - } - } - - if depositerAddr != nil { - res, err = cliCtx.QueryStore(gov.KeyDeposit(proposalID, depositerAddr), storeName) - if err != nil || len(res) == 0 { - continue - } - } - - res, err = cliCtx.QueryStore(gov.KeyProposal(proposalID), storeName) - if err != nil || len(res) == 0 { - continue - } - - var proposal gov.Proposal - cdc.MustUnmarshalBinary(res, &proposal) - - if len(strProposalStatus) != 0 { - if proposal.GetStatus() != proposalStatus { - continue - } - } - - proposalResponse, err := govClient.ConvertProposalToProposalOutput(cliCtx, proposal) - if err != nil { - return err - } - - matchingProposals = append(matchingProposals, proposalResponse) + //////////////////// iris begin /////////////////////////// + var matchingProposals gov.ProposalOutputs + err = cdc.UnmarshalJSON(res, &matchingProposals) + if err != nil { + return err } if len(matchingProposals) == 0 { @@ -151,13 +116,13 @@ func GetCmdQueryProposals(storeName string, cdc *wire.Codec) *cobra.Command { for _, proposal := range matchingProposals { fmt.Printf(" %d - %s\n", proposal.ProposalID, proposal.Title) } - + //////////////////// iris end ///////////////////////////// return nil }, } - cmd.Flags().String(flagLatestProposalIDs, "", "(optional) limit to latest [number] proposals. Defaults to all proposals") - cmd.Flags().String(flagDepositer, "", "(optional) filter by proposals deposited on by depositer") + cmd.Flags().String(flagNumLimit, "", "(optional) limit to latest [number] proposals. Defaults to all proposals") + cmd.Flags().String(flagDepositor, "", "(optional) filter by proposals deposited on by depositor") cmd.Flags().String(flagVoter, "", "(optional) filter by proposals voted on by voted") cmd.Flags().String(flagStatus, "", "(optional) filter proposals by proposal status") @@ -166,34 +131,35 @@ func GetCmdQueryProposals(storeName string, cdc *wire.Codec) *cobra.Command { // Command to Get a Proposal Information // GetCmdQueryVote implements the query proposal vote command. -func GetCmdQueryVote(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQueryVote(queryRoute string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "query-vote", Short: "query vote", Example: "iriscli gov query-vote --proposal-id=1 --voter=", RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - proposalID := viper.GetInt64(flagProposalID) + proposalID := uint64(viper.GetInt64(flagProposalID)) voterAddr, err := sdk.AccAddressFromBech32(viper.GetString(flagVoter)) if err != nil { return err } - res, err := cliCtx.QueryStore(gov.KeyVote(proposalID, voterAddr), storeName) - if len(res) == 0 || err != nil { - return fmt.Errorf("proposalID [%d] does not exist", proposalID) + params := gov.QueryVoteParams{ + Voter: voterAddr, + ProposalID: proposalID, + } + bz, err := cdc.MarshalJSON(params) + if err != nil { + return err } - var vote gov.Vote - cdc.MustUnmarshalBinary(res, &vote) - - output, err := wire.MarshalJSONIndent(cdc, vote) + res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/vote", queryRoute), bz) if err != nil { return err } - fmt.Println(string(output)) + fmt.Println(string(res)) return nil }, } @@ -205,51 +171,141 @@ func GetCmdQueryVote(storeName string, cdc *wire.Codec) *cobra.Command { } // GetCmdQueryVotes implements the command to query for proposal votes. -func GetCmdQueryVotes(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQueryVotes(queryRoute string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "query-votes", Short: "query votes on a proposal", Example: "iriscli gov query-votes --proposal-id=1", RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - proposalID := viper.GetInt64(flagProposalID) + proposalID := uint64(viper.GetInt64(flagProposalID)) + + params := gov.QueryVotesParams{ + ProposalID: proposalID, + } + bz, err := cdc.MarshalJSON(params) + if err != nil { + return err + } - res, err := cliCtx.QueryStore(gov.KeyProposal(proposalID), storeName) - if len(res) == 0 || err != nil { - return fmt.Errorf("proposalID [%d] does not exist", proposalID) + res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/votes", queryRoute), bz) + if err != nil { + return err } - var proposal gov.Proposal - cdc.MustUnmarshalBinary(res, &proposal) + fmt.Println(string(res)) + return nil + }, + } - if proposal.GetStatus() != gov.StatusVotingPeriod { - fmt.Println("Proposal not in voting period.") - return nil + cmd.Flags().String(flagProposalID, "", "proposalID of which proposal's votes are being queried") + + return cmd +} + +// Command to Get a specific Deposit Information +// GetCmdQueryDeposit implements the query proposal deposit command. +func GetCmdQueryDeposit(queryRoute string, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "query-deposit", + Short: "Query details of a deposit", + Example: "iriscli gov query-deposit --proposal-id=1 --depositor=", + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc) + proposalID := uint64(viper.GetInt64(flagProposalID)) + + depositorAddr, err := sdk.AccAddressFromBech32(viper.GetString(flagDepositor)) + if err != nil { + return err + } + + params := gov.QueryDepositParams{ + Depositor: depositorAddr, + ProposalID: proposalID, + } + bz, err := cdc.MarshalJSON(params) + if err != nil { + return err + } + + res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/deposit", queryRoute), bz) + if err != nil { + return err + } + + fmt.Println(string(res)) + return nil + }, + } + + cmd.Flags().String(flagProposalID, "", "proposalID of proposal deposited on") + cmd.Flags().String(flagDepositor, "", "bech32 depositor address") + + return cmd +} + +// GetCmdQueryDeposits implements the command to query for proposal deposits. +func GetCmdQueryDeposits(queryRoute string, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "query-deposits", + Short: "Query deposits on a proposal", + Example: "iriscli gov query-deposits --proposal-id=4", + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc) + proposalID := uint64(viper.GetInt64(flagProposalID)) + + params := gov.QueryDepositsParams{ + ProposalID: proposalID, + } + bz, err := cdc.MarshalJSON(params) + if err != nil { + return err } - res2, err := cliCtx.QuerySubspace(gov.KeyVotesSubspace(proposalID), storeName) + res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/deposits", queryRoute), bz) if err != nil { return err } - var votes []gov.Vote - for i := 0; i < len(res2); i++ { - var vote gov.Vote - cdc.MustUnmarshalBinary(res2[i].Value, &vote) - votes = append(votes, vote) + fmt.Println(string(res)) + return nil + }, + } + + cmd.Flags().String(flagProposalID, "", "proposalID of which proposal's deposits are being queried") + + return cmd +} + +// GetCmdQueryDeposits implements the command to query for proposal deposits. +func GetCmdQueryTally(queryRoute string, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "query-tally", + Short: "Get the tally of a proposal vote", + Example: "iriscli gov query-tally --proposal-id=4", + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc) + proposalID := uint64(viper.GetInt64(flagProposalID)) + + params := gov.QueryTallyParams{ + ProposalID: proposalID, + } + bz, err := cdc.MarshalJSON(params) + if err != nil { + return err } - output, err := wire.MarshalJSONIndent(cdc, votes) + res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/tally", queryRoute), bz) if err != nil { return err } - fmt.Println(string(output)) + fmt.Println(string(res)) return nil }, } - cmd.Flags().String(flagProposalID, "", "proposalID of which proposal's votes are being queried") + cmd.Flags().String(flagProposalID, "", "proposalID of which proposal is being tallied") return cmd } @@ -260,7 +316,7 @@ const ( flagPath = "path" ) -func GetCmdQueryGovConfig(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQueryGovConfig(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "query-params", Short: "query parameter proposal's config", @@ -310,7 +366,7 @@ func GetCmdQueryGovConfig(storeName string, cdc *wire.Codec) *cobra.Command { } p.GetValueFromRawData(cdc, res) - PrintParamStr(p, keyStr) + printParamStr(p, keyStr) return nil } else { @@ -330,7 +386,7 @@ func GetCmdQueryGovConfig(storeName string, cdc *wire.Codec) *cobra.Command { return cmd } -func PrintParamStr(p iparam.GovParameter, keyStr string) { +func printParamStr(p iparam.GovParameter, keyStr string) { var param gov.Param param.Key = keyStr param.Value = p.ToJson("") @@ -339,7 +395,7 @@ func PrintParamStr(p iparam.GovParameter, keyStr string) { fmt.Println(string(jsonBytes)) } -func GetCmdPullGovConfig(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdPullGovConfig(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "pull-params", Short: "generate param.json file", @@ -362,3 +418,4 @@ func GetCmdPullGovConfig(storeName string, cdc *wire.Codec) *cobra.Command { cmd.Flags().String(flagPath, app.DefaultNodeHome, "directory of iris home") return cmd } + diff --git a/client/gov/cli/sendtx.go b/client/gov/cli/sendtx.go index ac74212bd..9e172aa52 100644 --- a/client/gov/cli/sendtx.go +++ b/client/gov/cli/sendtx.go @@ -6,7 +6,7 @@ import ( "encoding/json" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/utils" @@ -14,19 +14,23 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/viper" + client "github.com/irisnet/irishub/client/gov" ) // GetCmdSubmitProposal implements submitting a proposal transaction command. -func GetCmdSubmitProposal(cdc *wire.Codec) *cobra.Command { +func GetCmdSubmitProposal(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "submit-proposal", Short: "Submit a proposal along with an initial deposit", + Example: "iriscli gov submit-proposal --chain-id= --from= --fee=0.004iris --type=Text --description=test --title=test-proposal", RunE: func(cmd *cobra.Command, args []string) error { title := viper.GetString(flagTitle) description := viper.GetString(flagDescription) strProposalType := viper.GetString(flagProposalType) initialDeposit := viper.GetString(flagDeposit) + //////////////////// iris begin /////////////////////////// paramStr := viper.GetString(flagParam) + //////////////////// iris end ///////////////////////////// cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) @@ -47,26 +51,21 @@ func GetCmdSubmitProposal(cdc *wire.Codec) *cobra.Command { if err != nil { return err } - + //////////////////// iris begin /////////////////////////// var param gov.Param if proposalType == gov.ProposalTypeParameterChange { 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 } } + //////////////////// iris end ///////////////////////////// - msg := gov.NewMsgSubmitProposal(title, description, proposalType, fromAddr, amount, param) - if cliCtx.GenerateOnly { - return utils.PrintUnsignedStdTx(txCtx, cliCtx, []sdk.Msg{msg}) - } - // Build and sign the transaction, then broadcast to Tendermint - // proposalID must be returned, and it is a part of response. - cliCtx.PrintResponse = true + msg := gov.NewMsgSubmitProposal(title, description, proposalType, fromAddr, amount, param) return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) }, @@ -76,14 +75,16 @@ func GetCmdSubmitProposal(cdc *wire.Codec) *cobra.Command { cmd.Flags().String(flagDescription, "", "description of proposal") cmd.Flags().String(flagProposalType, "", "proposalType of proposal,eg:Text/ParameterChange/SoftwareUpgrade") cmd.Flags().String(flagDeposit, "", "deposit of proposal") + //////////////////// iris begin /////////////////////////// cmd.Flags().String(flagParam, "", "parameter of proposal,eg. [{key:key,value:value,op:update}]") cmd.Flags().String(flagKey, "", "the key of parameter") cmd.Flags().String(flagOp, "", "the operation of parameter") cmd.Flags().String(flagPath, "", "the path of param.json") + //////////////////// iris end ///////////////////////////// return cmd } - -func GetParamFromString(paramStr string, pathStr string, keyStr string, opStr string, cdc *wire.Codec) (gov.Param, error) { +//////////////////// iris begin /////////////////////////// +func getParamFromString(paramStr string, pathStr string, keyStr string, opStr string, cdc *codec.Codec) (gov.Param, error) { var param gov.Param if paramStr != "" { @@ -103,12 +104,15 @@ func GetParamFromString(paramStr string, pathStr string, keyStr string, opStr st return param, errors.New("Path and param are both empty") } } +//////////////////// iris end ///////////////////////////// + // GetCmdDeposit implements depositing tokens for an active proposal. -func GetCmdDeposit(cdc *wire.Codec) *cobra.Command { +func GetCmdDeposit(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "deposit", Short: "deposit tokens for activing proposal", + Example: "iriscli gov deposit --chain-id= --from= --fee=0.004iris --proposal-id=1 --deposit=10iris", RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext(). WithCodec(cdc). @@ -117,43 +121,44 @@ func GetCmdDeposit(cdc *wire.Codec) *cobra.Command { txCtx := context.NewTxContextFromCLI().WithCodec(cdc). WithCliCtx(cliCtx) - depositerAddr, err := cliCtx.GetFromAddress() + depositorAddr, err := cliCtx.GetFromAddress() if err != nil { return err } - proposalID := viper.GetInt64(flagProposalID) + proposalID := uint64(viper.GetInt64(flagProposalID)) + //////////////////// iris begin /////////////////////////// amount, err := cliCtx.ParseCoins(viper.GetString(flagDeposit)) + //////////////////// iris end ///////////////////////////// + if err != nil { return err } - msg := gov.NewMsgDeposit(depositerAddr, proposalID, amount) + msg := gov.NewMsgDeposit(depositorAddr, proposalID, amount) err = msg.ValidateBasic() if 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(flagProposalID, "", "proposalID of proposal depositing on") cmd.Flags().String(flagDeposit, "", "amount of deposit") - + cmd.MarkFlagRequired(flagProposalID) + cmd.MarkFlagRequired(flagDeposit) return cmd } // GetCmdVote implements creating a new vote command. -func GetCmdVote(cdc *wire.Codec) *cobra.Command { +func GetCmdVote(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "vote", Short: "vote for an active proposal, options: Yes/No/NoWithVeto/Abstain", + Example: "iriscli gov vote --chain-id= --from= --fee=0.004iris --proposal-id=1 --option=Yes", RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext(). WithCodec(cdc). @@ -167,10 +172,10 @@ func GetCmdVote(cdc *wire.Codec) *cobra.Command { return err } - proposalID := viper.GetInt64(flagProposalID) + proposalID := uint64(viper.GetInt64(flagProposalID)) option := viper.GetString(flagOption) - byteVoteOption, err := gov.VoteOptionFromString(option) + byteVoteOption, err := gov.VoteOptionFromString(client.NormalizeVoteOption(option)) if err != nil { return err } @@ -195,6 +200,7 @@ func GetCmdVote(cdc *wire.Codec) *cobra.Command { cmd.Flags().String(flagProposalID, "", "proposalID of proposal voting on") cmd.Flags().String(flagOption, "", "vote option {Yes, No, NoWithVeto, Abstain}") - + cmd.MarkFlagRequired(flagProposalID) + cmd.MarkFlagRequired(flagOption) return cmd } diff --git a/client/gov/common.go b/client/gov/common.go deleted file mode 100644 index d03fd5396..000000000 --- a/client/gov/common.go +++ /dev/null @@ -1,77 +0,0 @@ -package gov - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/irisnet/irishub/client/context" - "github.com/irisnet/irishub/modules/gov" -) - -// Deposit -type DepositOutput struct { - Depositer sdk.AccAddress `json:"depositer"` // Address of the depositer - ProposalID int64 `json:"proposal_id"` // proposalID of the proposal - Amount []string `json:"amount"` // Deposit amount -} - -type ProposalOutput 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 gov.ProposalKind `json:"proposal_type"` // Type of proposal. Initial set {PlainTextProposal, SoftwareUpgradeProposal} - - Status gov.ProposalStatus `json:"proposal_status"` // Status of the Proposal {Pending, Active, Passed, Rejected} - TallyResult gov.TallyResult `json:"tally_result"` // Result of Tallys - - SubmitBlock int64 `json:"submit_block"` // Height of the block where TxGovSubmitProposal was included - TotalDeposit []string `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 - - Param gov.Param `json:"param"` -} - -type KvPair struct { - K string `json:"key"` - V string `json:"value"` -} - -func ConvertProposalToProposalOutput(cliCtx context.CLIContext, proposal gov.Proposal) (ProposalOutput, error) { - totalDeposit, err := cliCtx.ConvertCoinToMainUnit(proposal.GetTotalDeposit().String()) - if err != nil { - return ProposalOutput{}, err - } - - proposalOutput := ProposalOutput{ - ProposalID: proposal.GetProposalID(), - Title: proposal.GetTitle(), - Description: proposal.GetDescription(), - ProposalType: proposal.GetProposalType(), - - Status: proposal.GetStatus(), - TallyResult: proposal.GetTallyResult(), - - SubmitBlock: proposal.GetSubmitBlock(), - TotalDeposit: totalDeposit, - - VotingStartBlock: proposal.GetVotingStartBlock(), - Param: gov.Param{}, - } - - if proposal.GetProposalType() == gov.ProposalTypeParameterChange { - proposalOutput.Param = proposal.(*gov.ParameterProposal).Param - } - - return proposalOutput, nil -} - -func ConvertDepositToDepositOutput(cliCtx context.CLIContext, deposite gov.Deposit) (DepositOutput, error) { - amount, err := cliCtx.ConvertCoinToMainUnit(deposite.Amount.String()) - if err != nil { - return DepositOutput{}, err - } - return DepositOutput{ - ProposalID: deposite.ProposalID, - Depositer: deposite.Depositer, - Amount: amount, - }, nil -} diff --git a/client/gov/lcd/flags.go b/client/gov/lcd/flags.go index a4b9a984a..1901998a0 100644 --- a/client/gov/lcd/flags.go +++ b/client/gov/lcd/flags.go @@ -2,8 +2,9 @@ package lcd const ( RestProposalID = "proposalID" - RestDepositer = "depositer" + RestDepositor = "depositor" RestVoter = "voter" RestProposalStatus = "status" + RestNumLimit = "limit" storeName = "gov" ) diff --git a/client/gov/lcd/query.go b/client/gov/lcd/query.go index 5c5ad7b9b..465704694 100644 --- a/client/gov/lcd/query.go +++ b/client/gov/lcd/query.go @@ -1,343 +1,370 @@ package lcd import ( - "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/gorilla/mux" "github.com/irisnet/irishub/client/context" - govClient "github.com/irisnet/irishub/client/gov" "github.com/irisnet/irishub/modules/gov" "net/http" - "strconv" "github.com/irisnet/irishub/client/utils" + "github.com/pkg/errors" + client "github.com/irisnet/irishub/client/gov" ) -func queryProposalHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func queryProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] if len(strProposalID) == 0 { - utils.WriteErrorResponse(w, http.StatusBadRequest, "proposalId required but not specified") + err := errors.New("proposalId required but not specified") + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - proposalID, err := strconv.ParseInt(strProposalID, 10, 64) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("proposalID [%d] is not positive", proposalID)) + proposalID, ok := utils.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { return } - res, err := cliCtx.QueryStore(gov.KeyProposal(proposalID), storeName) - if err != nil || len(res) == 0 { - utils.WriteErrorResponse(w, http.StatusNotFound, fmt.Sprintf("proposalID [%d] does not exist", proposalID)) + params := gov.QueryProposalParams{ + ProposalID: proposalID, + } + + bz, err := cdc.MarshalJSON(params) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - var proposal gov.Proposal - cdc.MustUnmarshalBinary(res, &proposal) - proposalResponse, err := govClient.ConvertProposalToProposalOutput(cliCtx, proposal) + res, err := cliCtx.QueryWithData("custom/gov/proposal", bz) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - output, err := wire.MarshalJSONIndent(cdc, proposalResponse) + + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) + } +} + +func queryDepositsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + strProposalID := vars[RestProposalID] + + proposalID, ok := utils.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { + return + } + + params := gov.QueryDepositsParams{ + ProposalID: proposalID, + } + + bz, err := cdc.MarshalJSON(params) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + res, err := cliCtx.QueryWithData("custom/gov/deposits", bz) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - w.Write(output) + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) } } -func queryDepositHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func queryDepositHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] - bechDepositerAddr := vars[RestDepositer] + bechDepositorAddr := vars[RestDepositor] if len(strProposalID) == 0 { - utils.WriteErrorResponse(w, http.StatusBadRequest, "proposalId required but not specified") + err := errors.New("proposalId required but not specified") + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - proposalID, err := strconv.ParseInt(strProposalID, 10, 64) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("proposalID [%d] is not positive", proposalID)) + proposalID, ok := utils.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { return } - if len(bechDepositerAddr) == 0 { - utils.WriteErrorResponse(w, http.StatusBadRequest, "depositer address required but not specified") + if len(bechDepositorAddr) == 0 { + err := errors.New("depositor address required but not specified") + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - depositerAddr, err := sdk.AccAddressFromBech32(bechDepositerAddr) + depositorAddr, err := sdk.AccAddressFromBech32(bechDepositorAddr) if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("'%s' needs to be bech32 encoded", RestDepositer)) + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - res, err := cliCtx.QueryStore(gov.KeyDeposit(proposalID, depositerAddr), storeName) - if err != nil || len(res) == 0 { - res, err := cliCtx.QueryStore(gov.KeyProposal(proposalID), storeName) - if err != nil || len(res) == 0 { - utils.WriteErrorResponse(w, http.StatusNotFound, fmt.Sprintf("proposalID [%d] does not exist", proposalID)) - return - } + params := gov.QueryDepositParams{ + ProposalID: proposalID, + Depositor: depositorAddr, + } - utils.WriteErrorResponse(w, http.StatusNotFound, fmt.Sprintf("depositer [%s] did not deposit on proposalID [%d]", - bechDepositerAddr, proposalID)) + bz, err := cdc.MarshalJSON(params) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - var deposit gov.Deposit - cdc.MustUnmarshalBinary(res, &deposit) - - depositeResponse, err := govClient.ConvertDepositToDepositOutput(cliCtx, deposit) + res, err := cliCtx.QueryWithData("custom/gov/deposit", bz) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - output, err := wire.MarshalJSONIndent(cdc, depositeResponse) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + + var deposit gov.Deposit + cdc.UnmarshalJSON(res, &deposit) + if deposit.Empty() { + res, err := cliCtx.QueryWithData("custom/gov/proposal", cdc.MustMarshalBinaryLengthPrefixed(gov.QueryProposalParams{params.ProposalID})) + if err != nil || len(res) == 0 { + err := errors.Errorf("proposalID [%d] does not exist", proposalID) + utils.WriteErrorResponse(w, http.StatusNotFound, err.Error()) + return + } + err = errors.Errorf("depositor [%s] did not deposit on proposalID [%d]", bechDepositorAddr, proposalID) + utils.WriteErrorResponse(w, http.StatusNotFound, err.Error()) return } - w.Write(output) + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) } } -func queryVoteHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func queryVoteHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] bechVoterAddr := vars[RestVoter] if len(strProposalID) == 0 { - utils.WriteErrorResponse(w, http.StatusBadRequest, "proposalId required but not specified") + err := errors.New("proposalId required but not specified") + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - proposalID, err := strconv.ParseInt(strProposalID, 10, 64) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("proposalID [%d] is not positive", proposalID)) + proposalID, ok := utils.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { return } if len(bechVoterAddr) == 0 { - utils.WriteErrorResponse(w, http.StatusBadRequest, "voter address required but not specified") + err := errors.New("voter address required but not specified") + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } voterAddr, err := sdk.AccAddressFromBech32(bechVoterAddr) if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("'%s' needs to be bech32 encoded", RestVoter)) + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - res, err := cliCtx.QueryStore(gov.KeyVote(proposalID, voterAddr), storeName) - if err != nil || len(res) == 0 { - res, err := cliCtx.QueryStore(gov.KeyProposal(proposalID), storeName) - if err != nil || len(res) == 0 { - utils.WriteErrorResponse(w, http.StatusNotFound, fmt.Sprintf("proposalID [%d] does not exist", proposalID)) - return - } - utils.WriteErrorResponse(w, http.StatusNotFound, fmt.Sprintf("voter [%s] did not vote on proposalID [%d]", - bechVoterAddr, proposalID)) + params := gov.QueryVoteParams{ + Voter: voterAddr, + ProposalID: proposalID, + } + bz, err := cdc.MarshalJSON(params) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - var vote gov.Vote - cdc.MustUnmarshalBinary(res, &vote) - - output, err := wire.MarshalJSONIndent(cdc, vote) + res, err := cliCtx.QueryWithData("custom/gov/vote", bz) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - w.Write(output) + var vote gov.Vote + cdc.UnmarshalJSON(res, &vote) + if vote.Empty() { + bz, err := cdc.MarshalJSON(gov.QueryProposalParams{params.ProposalID}) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + res, err := cliCtx.QueryWithData("custom/gov/proposal", bz) + if err != nil || len(res) == 0 { + err := errors.Errorf("proposalID [%d] does not exist", proposalID) + utils.WriteErrorResponse(w, http.StatusNotFound, err.Error()) + return + } + err = errors.Errorf("voter [%s] did not deposit on proposalID [%d]", bechVoterAddr, proposalID) + utils.WriteErrorResponse(w, http.StatusNotFound, err.Error()) + return + } + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) } } -// nolint: gocyclo // todo: Split this functionality into helper functions to remove the above -func queryVotesOnProposalHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func queryVotesOnProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] if len(strProposalID) == 0 { - utils.WriteErrorResponse(w, http.StatusBadRequest, "proposalId required but not specified") - return - } - - proposalID, err := strconv.ParseInt(strProposalID, 10, 64) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("proposalID [%d] is not positive", proposalID)) + err := errors.New("proposalId required but not specified") + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - res, err := cliCtx.QueryStore(gov.KeyProposal(proposalID), storeName) - if err != nil || len(res) == 0 { - utils.WriteErrorResponse(w, http.StatusNotFound, fmt.Sprintf("proposalID [%d] does not exist", proposalID)) + proposalID, ok := utils.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { return } - var proposal gov.Proposal - cdc.MustUnmarshalBinary(res, &proposal) - - if proposal.GetStatus() != gov.StatusVotingPeriod { - utils.WriteErrorResponse(w, http.StatusNotFound, fmt.Sprintf("proposal [%d] is not in Voting Period", proposalID)) - return + params := gov.QueryVotesParams{ + ProposalID: proposalID, } - - res2, err := cliCtx.QuerySubspace(gov.KeyVotesSubspace(proposalID), storeName) + bz, err := cdc.MarshalJSON(params) if err != nil { - utils.WriteErrorResponse(w, http.StatusNotFound, "ProposalID doesn't exist") + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - var votes []gov.Vote - - for i := 0; i < len(res2); i++ { - var vote gov.Vote - cdc.MustUnmarshalBinary(res2[i].Value, &vote) - votes = append(votes, vote) - } - - output, err := wire.MarshalJSONIndent(cdc, votes) + res, err := cliCtx.QueryWithData("custom/gov/votes", bz) if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - w.Write(output) + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) } } -// nolint: gocyclo // todo: Split this functionality into helper functions to remove the above -func queryProposalsWithParameterFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func queryProposalsWithParameterFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { bechVoterAddr := r.URL.Query().Get(RestVoter) - bechDepositerAddr := r.URL.Query().Get(RestDepositer) + bechDepositorAddr := r.URL.Query().Get(RestDepositor) strProposalStatus := r.URL.Query().Get(RestProposalStatus) + strNumLimit := r.URL.Query().Get(RestNumLimit) - var err error - var voterAddr sdk.AccAddress - var depositerAddr sdk.AccAddress - var proposalStatus gov.ProposalStatus + params := gov.QueryProposalsParams{} if len(bechVoterAddr) != 0 { - voterAddr, err = sdk.AccAddressFromBech32(bechVoterAddr) + voterAddr, err := sdk.AccAddressFromBech32(bechVoterAddr) if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("'%s' needs to be bech32 encoded", RestVoter)) + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } + params.Voter = voterAddr } - if len(bechDepositerAddr) != 0 { - depositerAddr, err = sdk.AccAddressFromBech32(bechDepositerAddr) + if len(bechDepositorAddr) != 0 { + depositorAddr, err := sdk.AccAddressFromBech32(bechDepositorAddr) if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("'%s' needs to be bech32 encoded", RestDepositer)) + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } + params.Depositor = depositorAddr } if len(strProposalStatus) != 0 { - proposalStatus, err = gov.ProposalStatusFromString(strProposalStatus) + proposalStatus, err := gov.ProposalStatusFromString(client.NormalizeProposalStatus(strProposalStatus)) if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("'%s' is not a valid Proposal Status", strProposalStatus)) + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + params.ProposalStatus = proposalStatus + } + if len(strNumLimit) != 0 { + numLatest, ok := utils.ParseUint64OrReturnBadRequest(w, strNumLimit) + if !ok { return } + params.Limit = numLatest } - res, err := cliCtx.QueryStore(gov.KeyNextProposalID, storeName) + bz, err := cdc.MarshalJSON(params) if err != nil { - utils.WriteErrorResponse(w, http.StatusNotFound, "no proposals exist yet and proposalID has not been set") + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - var maxProposalID int64 - cdc.MustUnmarshalBinary(res, &maxProposalID) + res, err := cliCtx.QueryWithData("custom/gov/proposals", bz) + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } - matchingProposals := []govClient.ProposalOutput{} + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) + } +} - for proposalID := int64(0); proposalID < maxProposalID; proposalID++ { - if voterAddr != nil { - res, err = cliCtx.QueryStore(gov.KeyVote(proposalID, voterAddr), storeName) - if err != nil || len(res) == 0 { - continue - } - } +// todo: Split this functionality into helper functions to remove the above +func queryTallyOnProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + strProposalID := vars[RestProposalID] - if depositerAddr != nil { - res, err = cliCtx.QueryStore(gov.KeyDeposit(proposalID, depositerAddr), storeName) - if err != nil || len(res) == 0 { - continue - } - } + if len(strProposalID) == 0 { + w.WriteHeader(http.StatusBadRequest) + err := errors.New("proposalId required but not specified") + w.Write([]byte(err.Error())) - res, err = cliCtx.QueryStore(gov.KeyProposal(proposalID), storeName) - if err != nil || len(res) == 0 { - continue - } + return + } - var proposal gov.Proposal - cdc.MustUnmarshalBinary(res, &proposal) + proposalID, ok := utils.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { + return + } - if len(strProposalStatus) != 0 { - if proposal.GetStatus() != proposalStatus { - continue - } - } - proposalResponse, err := govClient.ConvertProposalToProposalOutput(cliCtx, proposal) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - matchingProposals = append(matchingProposals, proposalResponse) + params := gov.QueryTallyParams{ + ProposalID: proposalID, + } + bz, err := cdc.MarshalJSON(params) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return } - output, err := wire.MarshalJSONIndent(cdc, matchingProposals) + res, err := cliCtx.QueryWithData("custom/gov/tally", bz) if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) return } - w.Write(output) + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) } } + // nolint: gocyclo -func queryConfigHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func queryParamsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - res, err := cliCtx.QuerySubspace([]byte(gov.Prefix), storeName) + res, err := cliCtx.QuerySubspace([]byte("Gov/"), "params") if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - var kvs []govClient.KvPair + var pd gov.ParameterConfigFile for _, kv := range res { - var v string - cdc.UnmarshalBinary(kv.Value, &v) - kv := govClient.KvPair{ - K: string(kv.Key), - V: v, + switch string(kv.Key) { + case "Gov/govDepositProcedure": + cdc.UnmarshalJSON(kv.Value, &pd.Govparams.DepositProcedure) + case "Gov/govVotingProcedure": + cdc.UnmarshalJSON(kv.Value, &pd.Govparams.VotingProcedure) + case "Gov/govTallyingProcedure": + cdc.UnmarshalJSON(kv.Value, &pd.Govparams.TallyingProcedure) } - kvs = append(kvs, kv) } - output, err := wire.MarshalJSONIndent(cdc, kvs) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - w.Write(output) + utils.PostProcessResponse(w, cdc, pd, cliCtx.Indent) } } diff --git a/client/gov/lcd/rest.go b/client/gov/lcd/rest.go index 55edd4bc1..f26467ea4 100644 --- a/client/gov/lcd/rest.go +++ b/client/gov/lcd/rest.go @@ -1,25 +1,25 @@ package lcd import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "fmt" "github.com/irisnet/irishub/client/context" "github.com/gorilla/mux" ) // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Codec) { +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { r.HandleFunc("/gov/proposals", postProposalHandlerFn(cdc, cliCtx)).Methods("POST") r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), depositHandlerFn(cdc, cliCtx)).Methods("POST") r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), voteHandlerFn(cdc, cliCtx)).Methods("POST") + r.HandleFunc("/gov/proposals", queryProposalsWithParameterFn(cdc, cliCtx)).Methods("GET") r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}", RestProposalID), queryProposalHandlerFn(cdc, cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits/{%s}", RestProposalID, RestDepositer), queryDepositHandlerFn(cdc, cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes/{%s}", RestProposalID, RestVoter), queryVoteHandlerFn(cdc, cliCtx)).Methods("GET") - + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), queryDepositsHandlerFn(cdc, cliCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits/{%s}", RestProposalID, RestDepositor), queryDepositHandlerFn(cdc, cliCtx)).Methods("GET") r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), queryVotesOnProposalHandlerFn(cdc, cliCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes/{%s}", RestProposalID, RestVoter), queryVoteHandlerFn(cdc, cliCtx)).Methods("GET") - r.HandleFunc("/gov/proposals", queryProposalsWithParameterFn(cdc, cliCtx)).Methods("GET") - - r.HandleFunc("/gov/params", queryConfigHandlerFn(cdc, cliCtx)).Methods("GET") + r.HandleFunc(fmt.Sprint("/gov/proposals/{%s}/tally_result",RestProposalID),queryTallyOnProposalHandlerFn(cdc, cliCtx)).Methods("GET") + r.HandleFunc("/gov/params", queryParamsHandlerFn(cdc, cliCtx)).Methods("GET") } \ No newline at end of file diff --git a/client/gov/lcd/sendtx.go b/client/gov/lcd/sendtx.go index 6f8b5adf1..779530071 100644 --- a/client/gov/lcd/sendtx.go +++ b/client/gov/lcd/sendtx.go @@ -2,54 +2,55 @@ package lcd import ( "errors" - "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/gorilla/mux" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/utils" "github.com/irisnet/irishub/modules/gov" "net/http" - "strconv" + client "github.com/irisnet/irishub/client/gov" ) type postProposalReq struct { BaseTx context.BaseTx `json:"base_tx"` - Param gov.Param `json:"param"` Title string `json:"title"` // Title of the proposal Description string `json:"description"` // Description of the proposal - ProposalType gov.ProposalKind `json:"proposal_type"` // Type of proposal. Initial set {PlainTextProposal, SoftwareUpgradeProposal} - Proposer string `json:"proposer"` // Address of the proposer + ProposalType string `json:"proposal_type"` // Type of proposal. Initial set {PlainTextProposal, SoftwareUpgradeProposal} + Proposer sdk.AccAddress `json:"proposer"` // Address of the proposer InitialDeposit string `json:"initial_deposit"` // Coins to add to the proposal's deposit + Param gov.Param `json:"param"` } type depositReq struct { BaseTx context.BaseTx `json:"base_tx"` - Depositer string `json:"depositer"` // Address of the depositer + Depositor sdk.AccAddress `json:"depositor"` // Address of the depositor Amount string `json:"amount"` // Coins to add to the proposal's deposit } type voteReq struct { BaseTx context.BaseTx `json:"base_tx"` - Voter string `json:"voter"` // address of the voter - Option gov.VoteOption `json:"option"` // option from OptionSet chosen by the voter + Voter sdk.AccAddress `json:"voter"` // address of the voter + Option string `json:"option"` // option from OptionSet chosen by the voter } -func postProposalHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func postProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + + cliCtx = utils.InitReqCliCtx(cliCtx, r) + var req postProposalReq err := utils.ReadPostBody(w, r, cdc, &req) if err != nil { return } - cliCtx = utils.InitRequestClictx(cliCtx, r, req.BaseTx.LocalAccountName, req.Proposer) - txCtx, err := context.NewTxContextFromBaseTx(cliCtx, cdc, req.BaseTx) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + + baseReq := req.BaseTx.Sanitize() + if !baseReq.ValidateBasic(w, cliCtx) { return } - proposer, err := sdk.AccAddressFromBech32(req.Proposer) + proposalType, err := gov.ProposalTypeFromString(client.NormalizeProposalType(req.ProposalType)) if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -60,20 +61,23 @@ func postProposalHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.Hand utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } + // create the message - msg := gov.NewMsgSubmitProposal(req.Title, req.Description, req.ProposalType, proposer, initDepositAmount, req.Param) + msg := gov.NewMsgSubmitProposal(req.Title, req.Description, proposalType, req.Proposer, initDepositAmount, req.Param) err = msg.ValidateBasic() if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - utils.SendOrReturnUnsignedTx(w, cliCtx, txCtx, req.BaseTx, []sdk.Msg{msg}) + utils.SendOrReturnUnsignedTx(w, cliCtx, req.BaseTx, []sdk.Msg{msg}) } } -func depositHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func depositHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + + cliCtx = utils.InitReqCliCtx(cliCtx, r) vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -82,93 +86,84 @@ func depositHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFu return } - proposalID, err := strconv.ParseInt(strProposalID, 10, 64) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + proposalID, ok := utils.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { return } var req depositReq - err = utils.ReadPostBody(w, r, cdc, &req) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - cliCtx = utils.InitRequestClictx(cliCtx, r, req.BaseTx.LocalAccountName, req.Depositer) - txCtx, err := context.NewTxContextFromBaseTx(cliCtx, cdc, req.BaseTx) + err := utils.ReadPostBody(w, r, cdc, &req) if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - depositer, err := sdk.AccAddressFromBech32(req.Depositer) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + baseReq := req.BaseTx.Sanitize() + if !baseReq.ValidateBasic(w, cliCtx) { return } + depositAmount, err := cliCtx.ParseCoins(req.Amount) if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } // create the message - msg := gov.NewMsgDeposit(depositer, proposalID, depositAmount) + msg := gov.NewMsgDeposit(req.Depositor, proposalID, depositAmount) err = msg.ValidateBasic() if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - utils.SendOrReturnUnsignedTx(w, cliCtx, txCtx, req.BaseTx, []sdk.Msg{msg}) + utils.SendOrReturnUnsignedTx(w, cliCtx, req.BaseTx, []sdk.Msg{msg}) } } -func voteHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func voteHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + + cliCtx = utils.InitReqCliCtx(cliCtx, r) vars := mux.Vars(r) strProposalID := vars[RestProposalID] if len(strProposalID) == 0 { - w.WriteHeader(http.StatusBadRequest) err := errors.New("proposalId required but not specified") - w.Write([]byte(err.Error())) - + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - proposalID, err := strconv.ParseInt(strProposalID, 10, 64) - if err != nil { - err := fmt.Errorf("proposalID [%d] is not positive", proposalID) - w.Write([]byte(err.Error())) + proposalID, ok := utils.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { return } var req voteReq - err = utils.ReadPostBody(w, r, cdc, &req) + err := utils.ReadPostBody(w, r, cdc, &req) if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - cliCtx = utils.InitRequestClictx(cliCtx, r, req.BaseTx.LocalAccountName, req.Voter) - txCtx, err := context.NewTxContextFromBaseTx(cliCtx, cdc, req.BaseTx) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + + baseReq := req.BaseTx.Sanitize() + if !baseReq.ValidateBasic(w, cliCtx) { return } - voter, err := sdk.AccAddressFromBech32(req.Voter) + voteOption, err := gov.VoteOptionFromString(client.NormalizeVoteOption(req.Option)) if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } + // create the message - msg := gov.NewMsgVote(voter, proposalID, req.Option) + msg := gov.NewMsgVote(req.Voter, proposalID, voteOption) err = msg.ValidateBasic() if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - utils.SendOrReturnUnsignedTx(w, cliCtx, txCtx, req.BaseTx, []sdk.Msg{msg}) + utils.SendOrReturnUnsignedTx(w, cliCtx, req.BaseTx, []sdk.Msg{msg}) } } diff --git a/client/gov/utils.go b/client/gov/utils.go new file mode 100644 index 000000000..c82b298b1 --- /dev/null +++ b/client/gov/utils.go @@ -0,0 +1,60 @@ +package gov + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// Deposit +type DepositOutput struct { + Depositor sdk.AccAddress `json:"depositor"` // Address of the depositor + ProposalID int64 `json:"proposal_id"` // proposalID of the proposal + Amount []string `json:"amount"` // Deposit amount +} + +type KvPair struct { + K string `json:"key"` + V string `json:"value"` +} + +// NormalizeVoteOption - normalize user specified vote option +func NormalizeVoteOption(option string) string { + switch option { + case "Yes", "yes": + return "Yes" + case "Abstain", "abstain": + return "Abstain" + case "No", "no": + return "No" + case "NoWithVeto", "no_with_veto": + return "NoWithVeto" + } + return "" +} + +//NormalizeProposalType - normalize user specified proposal type +func NormalizeProposalType(proposalType string) string { + switch proposalType { + case "Text", "text": + return "Text" + case "ParameterChange", "parameter_change": + return "ParameterChange" + case "SoftwareUpgrade", "software_upgrade": + return "SoftwareUpgrade" + } + return "" +} + +//NormalizeProposalStatus - normalize user specified proposal status +func NormalizeProposalStatus(status string) string { + switch status { + case "DepositPeriod", "deposit_period": + return "DepositPeriod" + case "VotingPeriod", "voting_period": + return "VotingPeriod" + case "Passed", "passed": + return "Passed" + case "Rejected", "rejected": + return "Rejected" + } + return "" +} diff --git a/client/input.go b/client/input.go new file mode 100644 index 000000000..46c838e2e --- /dev/null +++ b/client/input.go @@ -0,0 +1,133 @@ +package client + +import ( + "bufio" + "fmt" + "os" + "strings" + + "github.com/bgentry/speakeasy" + "github.com/mattn/go-isatty" + "github.com/pkg/errors" +) + +// MinPassLength is the minimum acceptable password length +const MinPassLength = 8 + +// BufferStdin is used to allow reading prompts for stdin +// multiple times, when we read from non-tty +func BufferStdin() *bufio.Reader { + return bufio.NewReader(os.Stdin) +} + +// GetPassword will prompt for a password one-time (to sign a tx) +// It enforces the password length +func GetPassword(prompt string, buf *bufio.Reader) (pass string, err error) { + if inputIsTty() { + pass, err = speakeasy.FAsk(os.Stderr, prompt) + } else { + pass, err = readLineFromBuf(buf) + } + + if err != nil { + return "", err + } + + if len(pass) < MinPassLength { + // Return the given password to the upstream client so it can handle a + // non-STDIN failure gracefully. + return pass, errors.Errorf("password must be at least %d characters", MinPassLength) + } + + return pass, nil +} + +// GetSeed will request a seed phrase from stdin and trims off +// leading/trailing spaces +func GetSeed(prompt string, buf *bufio.Reader) (string, error) { + return GetString(prompt, buf) +} + +// GetCheckPassword will prompt for a password twice to verify they +// match (for creating a new password). +// It enforces the password length. Only parses password once if +// input is piped in. +func GetCheckPassword(prompt, prompt2 string, buf *bufio.Reader) (string, error) { + // simple read on no-tty + if !inputIsTty() { + return GetPassword(prompt, buf) + } + + // TODO: own function??? + pass, err := GetPassword(prompt, buf) + if err != nil { + return "", err + } + pass2, err := GetPassword(prompt2, buf) + if err != nil { + return "", err + } + if pass != pass2 { + return "", errors.New("passphrases don't match") + } + return pass, nil +} + +// GetConfirmation will request user give the confirmation from stdin. +// "y", "Y", "yes", "YES", and "Yes" all count as confirmations. +// If the input is not recognized, it will ask again. +func GetConfirmation(prompt string, buf *bufio.Reader) (bool, error) { + for { + if inputIsTty() { + fmt.Print(fmt.Sprintf("%s [y/n]:", prompt)) + } + response, err := readLineFromBuf(buf) + if err != nil { + return false, err + } + + response = strings.ToLower(strings.TrimSpace(response)) + if response == "y" || response == "yes" { + return true, nil + } else if response == "n" || response == "no" { + return false, nil + } + } +} + +// GetString simply returns the trimmed string output of a given reader. +func GetString(prompt string, buf *bufio.Reader) (string, error) { + if inputIsTty() && prompt != "" { + PrintPrefixed(prompt) + } + + out, err := readLineFromBuf(buf) + if err != nil { + return "", err + } + return strings.TrimSpace(out), nil +} + +// inputIsTty returns true iff we have an interactive prompt, +// where we can disable echo and request to repeat the password. +// If false, we can optimize for piped input from another command +func inputIsTty() bool { + return isatty.IsTerminal(os.Stdin.Fd()) || isatty.IsCygwinTerminal(os.Stdin.Fd()) +} + +// readLineFromBuf reads one line from stdin. +// Subsequent calls reuse the same buffer, so we don't lose +// any input when reading a password twice (to verify) +func readLineFromBuf(buf *bufio.Reader) (string, error) { + pass, err := buf.ReadString('\n') + if err != nil { + return "", err + } + return strings.TrimSpace(pass), nil +} + +// PrintPrefixed prints a string with > prefixed for use in prompts. +func PrintPrefixed(msg string) { + msg = fmt.Sprintf("> %s\n", msg) + fmt.Fprint(os.Stderr, msg) +} diff --git a/client/iservice/cli/flags.go b/client/iservice/cli/flags.go deleted file mode 100644 index 9a5161b1c..000000000 --- a/client/iservice/cli/flags.go +++ /dev/null @@ -1,38 +0,0 @@ -package cli - -import ( - flag "github.com/spf13/pflag" -) - -const ( - FlagDefChainID = "def-chain-id" - FlagServiceName = "name" - FlagServiceDescription = "service-description" - FlagTags = "tags" - FlagAuthorDescription = "author-description" - FlagIdlContent = "idl-content" - FlagBroadcast = "broadcast" - FlagFile = "file" -) - -var ( - FsDefChainID = flag.NewFlagSet("", flag.ContinueOnError) - FsServiceName = flag.NewFlagSet("", flag.ContinueOnError) - FsServiceDescription = flag.NewFlagSet("", flag.ContinueOnError) - FsTags = flag.NewFlagSet("", flag.ContinueOnError) - FsAuthorDescription = flag.NewFlagSet("", flag.ContinueOnError) - FsIdlContent = flag.NewFlagSet("", flag.ContinueOnError) - FsBroadcast = flag.NewFlagSet("", flag.ContinueOnError) - FsFile = flag.NewFlagSet("", flag.ContinueOnError) -) - -func init() { - FsDefChainID.String(FlagDefChainID, "", "the ID of the blockchain defined of the iService") - FsServiceName.String(FlagServiceName, "", "service name") - FsServiceDescription.String(FlagServiceDescription, "", "service description") - FsTags.String(FlagTags, "", "service tags") - FsAuthorDescription.String(FlagAuthorDescription, "", "service author description") - FsIdlContent.String(FlagIdlContent, "", "content of service interface description language") - FsBroadcast.String(FlagBroadcast, "", "service broadcast type, valid values can be Broadcast and Unicast") - FsFile.String(FlagFile, "", "path of file which contains service interface description language") -} diff --git a/client/iservice/cli/query.go b/client/iservice/cli/query.go deleted file mode 100644 index 84f2e58ca..000000000 --- a/client/iservice/cli/query.go +++ /dev/null @@ -1,61 +0,0 @@ -package cli - -import ( - "github.com/irisnet/irishub/modules/iservice" - "github.com/spf13/cobra" - "os" - "github.com/spf13/viper" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/irisnet/irishub/client/context" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - "fmt" - cmn "github.com/irisnet/irishub/client/iservice" -) - -func GetCmdQueryScvDef(storeName string, cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "definition", - Short: "query service definition", - Example: "iriscli iservice definition --name= --chain-id=", - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout). - WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - - name := viper.GetString(FlagServiceName) - defChainId := viper.GetString(FlagDefChainID) - - res, err := cliCtx.QueryStore(iservice.GetServiceDefinitionKey(defChainId, name), storeName) - if len(res) == 0 || err != nil { - return fmt.Errorf("chaind-id [%s] service [%s] is not existed", defChainId, name) - } - - var msgSvcDef iservice.MsgSvcDef - cdc.MustUnmarshalBinary(res, &msgSvcDef) - - res2, err := cliCtx.QuerySubspace(iservice.GetMethodsSubspaceKey(defChainId, name), storeName) - if err != nil { - return err - } - - var methods []iservice.MethodProperty - for i := 0; i < len(res2); i++ { - var method iservice.MethodProperty - cdc.MustUnmarshalBinary(res2[i].Value, &method) - methods = append(methods, method) - } - - service := cmn.ServiceOutput{MsgSvcDef: msgSvcDef, Methods: methods} - output, err := wire.MarshalJSONIndent(cdc, service) - if err != nil { - return err - } - - fmt.Println(string(output)) - return nil - }, - } - cmd.Flags().AddFlagSet(FsDefChainID) - cmd.Flags().AddFlagSet(FsServiceName) - - return cmd -} diff --git a/client/iservice/cli/sendtx.go b/client/iservice/cli/sendtx.go deleted file mode 100644 index 052c266bc..000000000 --- a/client/iservice/cli/sendtx.go +++ /dev/null @@ -1,77 +0,0 @@ -package cli - -import ( - "os" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/spf13/cobra" - "github.com/irisnet/irishub/client/context" - "github.com/irisnet/irishub/client/utils" - authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - "github.com/irisnet/irishub/modules/iservice" - "github.com/spf13/viper" - "github.com/irisnet/irishub/client" - cmn "github.com/tendermint/tendermint/libs/common" - "fmt" - "strings" -) - -func GetCmdScvDef(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "define", - Short: "create new service definition", - Example: "iriscli iservice define --chain-id= --from= --fee=0.004iris " + - "--name= --service-description= --author-description= " + - "--tags=\"tag1 tag2\" --idl-content= --broadcast=Broadcast", - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout). - WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - txCtx := context.NewTxContextFromCLI().WithCodec(cdc). - WithCliCtx(cliCtx) - - name := viper.GetString(FlagServiceName) - description := viper.GetString(FlagServiceDescription) - authorDescription := viper.GetString(FlagAuthorDescription) - tags := viper.GetStringSlice(FlagTags) - content := viper.GetString(FlagIdlContent) - if len(content) > 0 { - content = strings.Replace(content, `\n`, "\n", -1) - } - filePath := viper.GetString(FlagFile) - if len(filePath) > 0 { - contentBytes, err := cmn.ReadFile(filePath) - if err != nil { - return err - } - content = string(contentBytes) - } - fmt.Printf("idl condent: \n%s\n", content) - broadcastStr := viper.GetString(FlagBroadcast) - chainId := viper.GetString(client.FlagChainID) - - fromAddr, err := cliCtx.GetFromAddress() - if err != nil { - return err - } - - broadcast, err := iservice.BroadcastEnumFromString(broadcastStr) - if err != nil { - return err - } - - msg := iservice.NewMsgSvcDef(name, chainId, description, tags, fromAddr, authorDescription, content, broadcast) - cliCtx.PrintResponse = true - return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) - }, - } - cmd.Flags().AddFlagSet(FsServiceName) - cmd.Flags().AddFlagSet(FsServiceDescription) - cmd.Flags().AddFlagSet(FsTags) - cmd.Flags().AddFlagSet(FsAuthorDescription) - cmd.Flags().AddFlagSet(FsIdlContent) - cmd.Flags().AddFlagSet(FsBroadcast) - cmd.Flags().AddFlagSet(FsFile) - - return cmd -} diff --git a/client/iservice/common.go b/client/iservice/common.go deleted file mode 100644 index d36575613..000000000 --- a/client/iservice/common.go +++ /dev/null @@ -1,10 +0,0 @@ -package iservice - -import ( - "github.com/irisnet/irishub/modules/iservice" -) - -type ServiceOutput struct { - iservice.MsgSvcDef - Methods []iservice.MethodProperty `json:"methods"` -} diff --git a/client/keys/cli/add.go b/client/keys/cli/add.go index 1ffa4abf4..d7881a8f9 100644 --- a/client/keys/cli/add.go +++ b/client/keys/cli/add.go @@ -62,7 +62,7 @@ func runAddCmd(cmd *cobra.Command, args []string) error { return errors.New("you must provide a name for the key") } name = args[0] - kb, err = keys.GetKeyBase() + kb, err = keys.GetKeyBaseWithWritePerm() if err != nil { return err } @@ -125,7 +125,7 @@ func printCreate(info cryptokeys.Info, seed string) { output := viper.Get(cli.OutputFlag) switch output { case "text": - keys.PrintInfo(cdc, info) + keys.PrintKeyInfo(info, keys.Bech32KeyOutput) // print seed unless requested not to. if !viper.GetBool(client.FlagUseLedger) && !viper.GetBool(flagNoBackup) { fmt.Println("**Important** write this seed phrase in a safe place.") @@ -141,11 +141,16 @@ func printCreate(info cryptokeys.Info, seed string) { if !viper.GetBool(flagNoBackup) { out.Seed = seed } - json, err := cdc.MarshalJSON(out) + var jsonString []byte + if viper.GetBool(client.FlagIndentResponse) { + jsonString, err = cdc.MarshalJSONIndent(out, "", " ") + } else { + jsonString, err = cdc.MarshalJSON(out) + } if err != nil { panic(err) // really shouldn't happen... } - fmt.Println(string(json)) + fmt.Println(string(jsonString)) default: panic(fmt.Sprintf("I can't speak: %s", output)) } diff --git a/client/keys/cli/delete.go b/client/keys/cli/delete.go index eac6aa503..0f7286e05 100644 --- a/client/keys/cli/delete.go +++ b/client/keys/cli/delete.go @@ -2,17 +2,18 @@ package keys import ( "fmt" + "github.com/irisnet/irishub/client/keys" "github.com/spf13/cobra" ) func deleteKeyCommand() *cobra.Command { cmd := &cobra.Command{ - Use: "delete ", - Short: "Delete the given key", + Use: "delete ", + Short: "Delete the given key", Example: "iriscli keys delete ", - RunE: runDeleteCmd, - Args: cobra.ExactArgs(1), + RunE: runDeleteCmd, + Args: cobra.ExactArgs(1), } return cmd } @@ -20,7 +21,7 @@ func deleteKeyCommand() *cobra.Command { func runDeleteCmd(cmd *cobra.Command, args []string) error { name := args[0] - kb, err := keys.GetKeyBase() + kb, err := keys.GetKeyBaseWithWritePerm() if err != nil { return err } diff --git a/client/keys/cli/mnemonic.go b/client/keys/cli/mnemonic.go new file mode 100644 index 000000000..2890697e0 --- /dev/null +++ b/client/keys/cli/mnemonic.go @@ -0,0 +1,77 @@ +package keys + +import ( + "crypto/sha256" + "fmt" + + bip39 "github.com/bartekn/go-bip39" + "github.com/irisnet/irishub/client" + "github.com/spf13/cobra" +) + +const ( + flagUserEntropy = "unsafe-entropy" + + mnemonicEntropySize = 256 +) + +func mnemonicKeyCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "mnemonic", + Short: "Compute the bip39 mnemonic for some input entropy", + Long: "Create a bip39 mnemonic, sometimes called a seed phrase, by reading from the system entropy. To pass your own entropy, use --unsafe-entropy", + RunE: runMnemonicCmd, + } + cmd.Flags().Bool(flagUserEntropy, false, "Prompt the user to supply their own entropy, instead of relying on the system") + return cmd +} + +func runMnemonicCmd(cmd *cobra.Command, args []string) error { + flags := cmd.Flags() + + userEntropy, _ := flags.GetBool(flagUserEntropy) + + var entropySeed []byte + + if userEntropy { + // prompt the user to enter some entropy + buf := client.BufferStdin() + inputEntropy, err := client.GetString("> WARNING: Generate at least 256-bits of entropy and enter the results here:", buf) + if err != nil { + return err + } + if len(inputEntropy) < 43 { + return fmt.Errorf("256-bits is 43 characters in Base-64, and 100 in Base-6. You entered %v, and probably want more", len(inputEntropy)) + } + conf, err := client.GetConfirmation( + fmt.Sprintf("> Input length: %d", len(inputEntropy)), + buf) + if err != nil { + return err + } + if !conf { + return nil + } + + // hash input entropy to get entropy seed + hashedEntropy := sha256.Sum256([]byte(inputEntropy)) + entropySeed = hashedEntropy[:] + printStep() + } else { + // read entropy seed straight from crypto.Rand + var err error + entropySeed, err = bip39.NewEntropy(mnemonicEntropySize) + if err != nil { + return err + } + } + + mnemonic, err := bip39.NewMnemonic(entropySeed[:]) + if err != nil { + return err + } + + fmt.Println(mnemonic) + + return nil +} diff --git a/client/keys/cli/new.go b/client/keys/cli/new.go new file mode 100644 index 000000000..5e92fb947 --- /dev/null +++ b/client/keys/cli/new.go @@ -0,0 +1,188 @@ +package keys + +import ( + "fmt" + + "github.com/bartekn/go-bip39" + cryptokeys "github.com/cosmos/cosmos-sdk/crypto/keys" + "github.com/cosmos/cosmos-sdk/crypto/keys/hd" + "github.com/irisnet/irishub/client" + "github.com/irisnet/irishub/client/keys" + "github.com/pkg/errors" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +const ( + flagNewDefault = "default" + flagBIP44Path = "bip44-path" +) + +func newKeyCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "new", + Short: "Interactive command to derive a new private key, encrypt it, and save to disk", + Long: `Derive a new private key using an interactive command that will prompt you for each input. +Optionally specify a bip39 mnemonic, a bip39 passphrase to further secure the mnemonic, +and a bip32 HD path to derive a specific account. The key will be stored under the given name +and encrypted with the given password. The only input that is required is the encryption password.`, + Args: cobra.ExactArgs(1), + RunE: runNewCmd, + } + cmd.Flags().Bool(flagNewDefault, false, "Skip the prompts and just use the default values for everything") + cmd.Flags().Bool(client.FlagUseLedger, false, "Store a local reference to a private key on a Ledger device") + cmd.Flags().String(flagBIP44Path, "44'/118'/0'/0/0", "BIP44 path from which to derive a private key") + return cmd +} + +/* +input + - bip39 mnemonic + - bip39 passphrase + - bip44 path + - local encryption password +output + - armor encrypted private key (saved to file) +*/ +func runNewCmd(cmd *cobra.Command, args []string) error { + name := args[0] + kb, err := keys.GetKeyBaseWithWritePerm() + if err != nil { + return err + } + + buf := client.BufferStdin() + + _, err = kb.Get(name) + if err == nil { + // account exists, ask for user confirmation + if response, err := client.GetConfirmation( + fmt.Sprintf("> override the existing name %s", name), buf); err != nil || !response { + return err + } + } + + flags := cmd.Flags() + useDefaults, _ := flags.GetBool(flagNewDefault) + bipFlag := flags.Lookup(flagBIP44Path) + + bip44Params, err := getBIP44ParamsAndPath(bipFlag.Value.String(), bipFlag.Changed || useDefaults) + if err != nil { + return err + } + + // If we're using ledger, only thing we need is the path. So generate key and + // we're done. + if viper.GetBool(client.FlagUseLedger) { + algo := cryptokeys.Secp256k1 + path := bip44Params.DerivationPath() // ccrypto.DerivationPath{44, 118, account, 0, index} + + info, err := kb.CreateLedger(name, path, algo) + if err != nil { + return err + } + + printCreate(info, "") + return nil + } + + var mnemonic string + + if !useDefaults { + mnemonic, err = client.GetString("Enter your bip39 mnemonic, or hit enter to generate one.", buf) + if err != nil { + return err + } + } + + if len(mnemonic) == 0 { + // read entropy seed straight from crypto.Rand and convert to mnemonic + entropySeed, err := bip39.NewEntropy(mnemonicEntropySize) + if err != nil { + return err + } + + mnemonic, err = bip39.NewMnemonic(entropySeed[:]) + if err != nil { + return err + } + } + + // get bip39 passphrase + var bip39Passphrase string + if !useDefaults { + printStep() + printPrefixed("Enter your bip39 passphrase. This is combined with the mnemonic to derive the seed") + + bip39Passphrase, err = client.GetString("Most users should just hit enter to use the default, \"\"", buf) + if err != nil { + return err + } + + // if they use one, make them re-enter it + if len(bip39Passphrase) != 0 { + p2, err := client.GetString("Repeat the passphrase:", buf) + if err != nil { + return err + } + + if bip39Passphrase != p2 { + return errors.New("passphrases don't match") + } + } + } + + printStep() + + // get the encryption password + encryptPassword, err := client.GetCheckPassword( + "> Enter a passphrase to encrypt your key to disk:", + "> Repeat the passphrase:", buf) + if err != nil { + return err + } + + info, err := kb.Derive(name, mnemonic, bip39Passphrase, encryptPassword, *bip44Params) + if err != nil { + return err + } + + _ = info + return nil +} + +func getBIP44ParamsAndPath(path string, flagSet bool) (*hd.BIP44Params, error) { + buf := client.BufferStdin() + bip44Path := path + + // if it wasn't set in the flag, give it a chance to overide interactively + if !flagSet { + var err error + + printStep() + + bip44Path, err = client.GetString(fmt.Sprintf("Enter your bip44 path. Default is %s\n", path), buf) + if err != nil { + return nil, err + } + + if len(bip44Path) == 0 { + bip44Path = path + } + } + + bip44params, err := hd.NewParamsFromPath(bip44Path) + if err != nil { + return nil, err + } + + return bip44params, nil +} + +func printPrefixed(msg string) { + fmt.Printf("> %s\n", msg) +} + +func printStep() { + printPrefixed("-------------------------------------") +} diff --git a/client/keys/cli/root.go b/client/keys/cli/root.go index 4a585262b..060b09144 100644 --- a/client/keys/cli/root.go +++ b/client/keys/cli/root.go @@ -18,9 +18,11 @@ func Commands() *cobra.Command { needs to sign with a private key.`, } cmd.AddCommand( + mnemonicKeyCommand(), + newKeyCommand(), addKeyCommand(), listKeysCmd, - showKeysCmd, + showKeysCmd(), client.LineBreak, deleteKeyCommand(), updateKeyCommand(), diff --git a/client/keys/cli/show.go b/client/keys/cli/show.go index a67f6c0a6..2b688f630 100644 --- a/client/keys/cli/show.go +++ b/client/keys/cli/show.go @@ -1,22 +1,127 @@ package keys import ( - "github.com/irisnet/irishub/client/keys" + "fmt" + + cryptokeys "github.com/cosmos/cosmos-sdk/crypto/keys" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/crypto/multisig" + + "github.com/irisnet/irishub/client/keys" + "github.com/tendermint/tmlibs/cli" + +) + +const ( + // FlagAddress is the flag for the user's address on the command line. + FlagAddress = "address" + // FlagPublicKey represents the user's public key on the command line. + FlagPublicKey = "pubkey" + // FlagBechPrefix defines a desired Bech32 prefix encoding for a key. + FlagBechPrefix = "bech" + + flagMultiSigThreshold = "multisig-threshold" + defaultMultiSigKeyName = "multi" ) -var showKeysCmd = &cobra.Command{ - Use: "show ", - Short: "Show key info for the given name", - Long: `Return public details of one local key.`, - Example: "iriscli keys show ", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - name := args[0] - info, err := keys.GetKey(name) - if err == nil { - keys.PrintInfo(cdc, info) +var _ cryptokeys.Info = (*multiSigKey)(nil) + +type multiSigKey struct { + name string + key crypto.PubKey +} + +func (m multiSigKey) GetName() string { return m.name } +func (m multiSigKey) GetType() cryptokeys.KeyType { return cryptokeys.TypeLocal } +func (m multiSigKey) GetPubKey() crypto.PubKey { return m.key } +func (m multiSigKey) GetAddress() sdk.AccAddress { return sdk.AccAddress(m.key.Address()) } + +func showKeysCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "show [name]", + Short: "Show key info for the given name", + Long: `Return public details of one local key.`, + Args: cobra.MinimumNArgs(1), + RunE: runShowCmd, + } + + cmd.Flags().String(FlagBechPrefix, "acc", "The Bech32 prefix encoding for a key (acc|val|cons)") + cmd.Flags().Bool(FlagAddress, false, "output the address only (overrides --output)") + cmd.Flags().Bool(FlagPublicKey, false, "output the public key only (overrides --output)") + cmd.Flags().Uint(flagMultiSigThreshold, 1, "K out of N required signatures") + + return cmd +} + +func runShowCmd(cmd *cobra.Command, args []string) (err error) { + var info cryptokeys.Info + + if len(args) == 1 { + info, err = keys.GetKeyInfo(args[0]) + if err != nil { + return err } + } else { + pks := make([]crypto.PubKey, len(args)) + for i, keyName := range args { + info, err := keys.GetKeyInfo(keyName) + if err != nil { + return err + } + pks[i] = info.GetPubKey() + } + + multisigThreshold := viper.GetInt(flagMultiSigThreshold) + err = validateMultisigThreshold(multisigThreshold, len(args)) + if err != nil { + return err + } + multikey := multisig.NewPubKeyMultisigThreshold(multisigThreshold, pks) + info = multiSigKey{ + name: defaultMultiSigKeyName, + key: multikey, + } + } + + isShowAddr := viper.GetBool(FlagAddress) + isShowPubKey := viper.GetBool(FlagPublicKey) + isOutputSet := cmd.Flag(cli.OutputFlag).Changed + + if isShowAddr && isShowPubKey { + return fmt.Errorf("cannot use both --address and --pubkey at once") + } + + if isOutputSet && (isShowAddr || isShowPubKey) { + return fmt.Errorf("cannot use --output with --address or --pubkey") + } + + bechKeyOut, err := keys.GetBechKeyOut(viper.GetString(FlagBechPrefix)) + if err != nil { return err - }, + } + + switch { + case isShowAddr: + keys.PrintKeyAddress(info, bechKeyOut) + case isShowPubKey: + keys.PrintPubKey(info, bechKeyOut) + default: + keys.PrintKeyInfo(info, bechKeyOut) + } + + return nil +} + +func validateMultisigThreshold(k, nKeys int) error { + if k <= 0 { + return fmt.Errorf("threshold must be a positive integer") + } + if nKeys < k { + return fmt.Errorf( + "threshold k of n multisignature: %d < %d", nKeys, k) + } + return nil } diff --git a/client/keys/cli/update.go b/client/keys/cli/update.go index c1fc1df75..2510ce046 100644 --- a/client/keys/cli/update.go +++ b/client/keys/cli/update.go @@ -21,7 +21,7 @@ func runUpdateCmd(cmd *cobra.Command, args []string) error { name := args[0] buf := keys.BufferStdin() - kb, err := keys.GetKeyBase() + kb, err := keys.GetKeyBaseWithWritePerm() if err != nil { return err } diff --git a/client/keys/cli/wire.go b/client/keys/cli/wire.go index a163f995a..6bbb16850 100644 --- a/client/keys/cli/wire.go +++ b/client/keys/cli/wire.go @@ -1,14 +1,14 @@ package keys import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" ) -var cdc *wire.Codec +var cdc *codec.Codec func init() { - cdc = wire.NewCodec() - wire.RegisterCrypto(cdc) + cdc = codec.New() + codec.RegisterCrypto(cdc) } // marshal keys diff --git a/client/keys/codec.go b/client/keys/codec.go index a163f995a..6bbb16850 100644 --- a/client/keys/codec.go +++ b/client/keys/codec.go @@ -1,14 +1,14 @@ package keys import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" ) -var cdc *wire.Codec +var cdc *codec.Codec func init() { - cdc = wire.NewCodec() - wire.RegisterCrypto(cdc) + cdc = codec.New() + codec.RegisterCrypto(cdc) } // marshal keys diff --git a/client/keys/errors.go b/client/keys/errors.go new file mode 100644 index 000000000..664461c70 --- /dev/null +++ b/client/keys/errors.go @@ -0,0 +1,19 @@ +package keys + +import "fmt" + +func ErrKeyNameConflict(name string) error { + return fmt.Errorf("acount with name %s already exists", name) +} + +func ErrMissingName() error { + return fmt.Errorf("you have to specify a name for the locally stored account") +} + +func ErrMissingPassword() error { + return fmt.Errorf("you have to specify a password for the locally stored account") +} + +func ErrMissingSeed() error { + return fmt.Errorf("you have to specify seed for key recover") +} \ No newline at end of file diff --git a/client/keys/input.go b/client/keys/input.go index 50446c131..d7395ac96 100644 --- a/client/keys/input.go +++ b/client/keys/input.go @@ -24,7 +24,7 @@ func BufferStdin() *bufio.Reader { // It enforces the password length func GetPassword(prompt string, buf *bufio.Reader) (pass string, err error) { if inputIsTty() { - pass, err = speakeasy.Ask(prompt) + pass, err = speakeasy.FAsk(os.Stderr, prompt) } else { pass, err = readLineFromBuf(buf) } diff --git a/client/keys/lcd/add.go b/client/keys/lcd/add.go index d315412b8..ca3e2d54d 100644 --- a/client/keys/lcd/add.go +++ b/client/keys/lcd/add.go @@ -1,11 +1,11 @@ package keys import ( - "fmt" + "io/ioutil" "net/http" cryptokeys "github.com/cosmos/cosmos-sdk/crypto/keys" - + "github.com/gorilla/mux" "github.com/irisnet/irishub/client/keys" "github.com/irisnet/irishub/client/utils" ) @@ -18,72 +18,70 @@ type NewKeyBody struct { } // AddNewKeyRequestHandler performs create or recover new keys operation -func AddNewKeyRequestHandler(w http.ResponseWriter, r *http.Request) { - var kb cryptokeys.Keybase - var m NewKeyBody - - kb, err := keys.GetKeyBase() - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } +func AddNewKeyRequestHandler(indent bool) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var kb cryptokeys.Keybase + var m NewKeyBody - err = utils.ReadPostBody(w, r, cdc, &m) - if err != nil { - return - } + kb, err := keys.GetKeyBase() + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } - if m.Name == "" { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("You have to specify a name for the locally stored account.")) - return - } - if m.Password == "" { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("You have to specify a password for the locally stored account.")) - return - } + err = utils.ReadPostBody(w, r, cdc, &m) + if err != nil { + return + } - // check if already exists - infos, err := kb.List() - for _, i := range infos { - if i.GetName() == m.Name { - w.WriteHeader(http.StatusConflict) - w.Write([]byte(fmt.Sprintf("Account with name %s already exists.", m.Name))) + if m.Name == "" { + w.WriteHeader(http.StatusBadRequest) + err = keys.ErrMissingName() + w.Write([]byte(err.Error())) + return + } + if m.Password == "" { + w.WriteHeader(http.StatusBadRequest) + err = keys.ErrMissingPassword() + w.Write([]byte(err.Error())) return } - } - // create account - seed := m.Seed - if seed == "" { - seed = getSeed(cryptokeys.Secp256k1) - } - info, err := kb.CreateKey(m.Name, seed, m.Password) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } + // check if already exists + infos, err := kb.List() + for _, i := range infos { + if i.GetName() == m.Name { + w.WriteHeader(http.StatusConflict) + err = keys.ErrKeyNameConflict(m.Name) + w.Write([]byte(err.Error())) + return + } + } - keyOutput, err := keys.Bech32KeyOutput(info) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } + // create account + seed := m.Seed + if seed == "" { + seed = getSeed(cryptokeys.Secp256k1) + } + info, err := kb.CreateKey(m.Name, seed, m.Password) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } - keyOutput.Seed = seed + keyOutput, err := keys.Bech32KeyOutput(info) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } - bz, err := cdc.MarshalJSONIndent(keyOutput,""," ") - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } + keyOutput.Seed = seed - w.Write(bz) + keys.PostProcessResponse(w, cdc, keyOutput, indent) + } } // function to just a new seed to display in the UI before actually persisting it in the keybase @@ -94,3 +92,104 @@ func getSeed(algo cryptokeys.SigningAlgo) string { _, seed, _ := kb.CreateMnemonic(name, cryptokeys.English, pass, algo) return seed } + +type seedOutput struct { + Seed string `json:"seed"` +} +// Seed REST request handler +func SeedRequestHandler(indent bool) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + algoType := vars["type"] + // algo type defaults to secp256k1 + if algoType == "" { + algoType = "secp256k1" + } + algo := cryptokeys.SigningAlgo(algoType) + + seed := getSeed(algo) + seedOutput := seedOutput{ + Seed: seed, + } + keys.PostProcessResponse(w, cdc, seedOutput, indent) + } +} + +// RecoverKeyBody is recover key request REST body +type RecoverKeyBody struct { + Password string `json:"password"` + Seed string `json:"seed"` +} + +// RecoverRequestHandler performs key recover request +func RecoverRequestHandler(indent bool) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + name := vars["name"] + var m RecoverKeyBody + 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 + } + + if name == "" { + w.WriteHeader(http.StatusBadRequest) + err = keys.ErrMissingName() + w.Write([]byte(err.Error())) + return + } + if m.Password == "" { + w.WriteHeader(http.StatusBadRequest) + err = keys.ErrMissingPassword() + w.Write([]byte(err.Error())) + return + } + if m.Seed == "" { + w.WriteHeader(http.StatusBadRequest) + err = keys.ErrMissingSeed() + w.Write([]byte(err.Error())) + return + } + + kb, err := keys.GetKeyBaseWithWritePerm() + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + // check if already exists + infos, err := kb.List() + for _, info := range infos { + if info.GetName() == name { + w.WriteHeader(http.StatusConflict) + err = keys.ErrKeyNameConflict(name) + w.Write([]byte(err.Error())) + return + } + } + + info, err := kb.CreateKey(name, m.Seed, m.Password) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + keyOutput, err := keys.Bech32KeyOutput(info) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + keys.PostProcessResponse(w, cdc, keyOutput, indent) + } +} diff --git a/client/keys/lcd/list.go b/client/keys/lcd/list.go index 5edc3a4f0..3bc5ad8c9 100644 --- a/client/keys/lcd/list.go +++ b/client/keys/lcd/list.go @@ -1,42 +1,37 @@ package keys import ( - "encoding/json" "net/http" "github.com/irisnet/irishub/client/keys" ) // query key list REST handler -func QueryKeysRequestHandler(w http.ResponseWriter, r *http.Request) { - kb, err := keys.GetKeyBase() - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return +func QueryKeysRequestHandler(indent bool) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + kb, err := keys.GetKeyBase() + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + infos, err := kb.List() + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + // an empty list will be JSONized as null, but we want to keep the empty list + if len(infos) == 0 { + w.Write([]byte("[]")) + return + } + keysOutput, err := keys.Bech32KeysOutput(infos) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + keys.PostProcessResponse(w, cdc, keysOutput, indent) } - infos, err := kb.List() - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - // an empty list will be JSONized as null, but we want to keep the empty list - if len(infos) == 0 { - w.Write([]byte("[]")) - return - } - keysOutput, err := keys.Bech32KeysOutput(infos) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - output, err := json.MarshalIndent(keysOutput, "", " ") - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - w.Write(output) } diff --git a/client/keys/lcd/root.go b/client/keys/lcd/root.go index d9f7f592f..0edde97ec 100644 --- a/client/keys/lcd/root.go +++ b/client/keys/lcd/root.go @@ -5,10 +5,12 @@ import ( ) // resgister REST routes -func RegisterRoutes(r *mux.Router) { - r.HandleFunc("/keys", QueryKeysRequestHandler).Methods("GET") - r.HandleFunc("/keys", AddNewKeyRequestHandler).Methods("POST") - r.HandleFunc("/keys/{name}", GetKeyRequestHandler).Methods("GET") +func RegisterRoutes(r *mux.Router, indent bool) { + r.HandleFunc("/keys", QueryKeysRequestHandler(indent)).Methods("GET") + r.HandleFunc("/keys", AddNewKeyRequestHandler(indent)).Methods("POST") + r.HandleFunc("/keys/seed", SeedRequestHandler(indent)).Methods("GET") + r.HandleFunc("/keys/{name}/recover", RecoverRequestHandler(indent)).Methods("POST") + r.HandleFunc("/keys/{name}", GetKeyRequestHandler(indent)).Methods("GET") r.HandleFunc("/keys/{name}", UpdateKeyRequestHandler).Methods("PUT") r.HandleFunc("/keys/{name}", DeleteKeyRequestHandler).Methods("DELETE") } diff --git a/client/keys/lcd/show.go b/client/keys/lcd/show.go index c2f63a267..084ab5d94 100644 --- a/client/keys/lcd/show.go +++ b/client/keys/lcd/show.go @@ -1,47 +1,53 @@ package keys import ( - "encoding/json" - "fmt" + "net/http" + + "github.com/cosmos/cosmos-sdk/crypto/keys/keyerror" "github.com/gorilla/mux" "github.com/irisnet/irishub/client/keys" - "net/http" - "strings" + keycli "github.com/irisnet/irishub/client/keys/cli" ) /////////////////////////// // REST // get key REST handler -func GetKeyRequestHandler(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - name := vars["name"] - - info, err := keys.GetKey(name) - if err != nil { - if strings.Contains(err.Error(), fmt.Sprintf("Key %s not found", name)) { - w.WriteHeader(http.StatusNotFound) +func GetKeyRequestHandler(indent bool) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + name := vars["name"] + bechPrefix := r.URL.Query().Get(keycli.FlagBechPrefix) + + if bechPrefix == "" { + bechPrefix = "acc" + } + + bechKeyOut, err := keys.GetBechKeyOut(bechPrefix) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + + info, err := keys.GetKeyInfo(name) + if keyerror.IsErrKeyNotFound(err) { + w.WriteHeader(http.StatusNoContent) w.Write([]byte(err.Error())) return - } else { + } else if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } - } - keyOutput, err := keys.Bech32KeyOutput(info) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - output, err := json.MarshalIndent(keyOutput, "", " ") - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } + keyOutput, err := bechKeyOut(info) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } - w.Write(output) + keys.PostProcessResponse(w, cdc, keyOutput, indent) + } } diff --git a/client/keys/lcd/update.go b/client/keys/lcd/update.go index 99b544865..1367d138d 100644 --- a/client/keys/lcd/update.go +++ b/client/keys/lcd/update.go @@ -26,6 +26,12 @@ func UpdateKeyRequestHandler(w http.ResponseWriter, r *http.Request) { return } + if len(m.NewPassword) == 0 { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("new password should not be empty")) + return + } + kb, err := keys.GetKeyBase() if err != nil { w.WriteHeader(http.StatusInternalServerError) diff --git a/client/keys/lcd/wire.go b/client/keys/lcd/wire.go index a163f995a..6bbb16850 100644 --- a/client/keys/lcd/wire.go +++ b/client/keys/lcd/wire.go @@ -1,14 +1,14 @@ package keys import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" ) -var cdc *wire.Codec +var cdc *codec.Codec func init() { - cdc = wire.NewCodec() - wire.RegisterCrypto(cdc) + cdc = codec.New() + codec.RegisterCrypto(cdc) } // marshal keys diff --git a/client/keys/common.go b/client/keys/utils.go similarity index 50% rename from client/keys/common.go rename to client/keys/utils.go index bdc727f0d..1d469a114 100644 --- a/client/keys/common.go +++ b/client/keys/utils.go @@ -2,18 +2,24 @@ package keys import ( "fmt" + "net/http" + "path/filepath" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" "github.com/spf13/viper" + "github.com/syndtr/goleveldb/leveldb/opt" "github.com/tendermint/tendermint/libs/cli" dbm "github.com/tendermint/tendermint/libs/db" - "path/filepath" ) // KeyDBName is the directory under root where we store the keys const KeyDBName = "keys" +type BechKeyOutFn func(keyInfo keys.Info) (KeyOutput, error) + // keybase is used to make GetKeyBase a singleton var keybase keys.Keybase @@ -60,6 +66,28 @@ func GetPassphrase(name string) (string, error) { return passphrase, nil } +// GetKeyBaseWithWritePerm initialize a keybase based on the configuration with write permissions. +func GetKeyBaseWithWritePerm() (keys.Keybase, error) { + rootDir := viper.GetString(cli.HomeFlag) + return GetKeyBaseFromDirWithWritePerm(rootDir) +} + +// GetKeyBaseFromDirWithWritePerm initializes a keybase at a particular dir with write permissions. +func GetKeyBaseFromDirWithWritePerm(rootDir string) (keys.Keybase, error) { + return getKeyBaseFromDirWithOpts(rootDir, nil) +} + +func getKeyBaseFromDirWithOpts(rootDir string, o *opt.Options) (keys.Keybase, error) { + if keybase == nil { + db, err := dbm.NewGoLevelDBWithOpts(KeyDBName, filepath.Join(rootDir, "keys"), o) + if err != nil { + return nil, err + } + keybase = client.GetKeyBase(db) + } + return keybase, nil +} + // ReadPassphraseFromStdin attempts to read a passphrase from STDIN return an // error upon failure. func ReadPassphraseFromStdin(name string) (string, error) { @@ -97,11 +125,11 @@ func GetKey(name string) (keys.Info, error) { // used for outputting keys.Info over REST type KeyOutput struct { - Name string `json:"name"` - Type string `json:"type"` - Address sdk.AccAddress `json:"address"` - PubKey string `json:"pub_key"` - Seed string `json:"seed,omitempty"` + Name string `json:"name"` + Type string `json:"type"` + Address string `json:"address"` + PubKey string `json:"pub_key"` + Seed string `json:"seed,omitempty"` } // create a list of KeyOutput in bech32 format @@ -117,40 +145,78 @@ func Bech32KeysOutput(infos []keys.Info) ([]KeyOutput, error) { return kos, nil } -// create a KeyOutput in bech32 format +// Bech32KeyOutput create a KeyOutput in bech32 format func Bech32KeyOutput(info keys.Info) (KeyOutput, error) { - account := sdk.AccAddress(info.GetPubKey().Address().Bytes()) + accAddr := sdk.AccAddress(info.GetPubKey().Address().Bytes()) bechPubKey, err := sdk.Bech32ifyAccPub(info.GetPubKey()) if err != nil { return KeyOutput{}, err } + return KeyOutput{ Name: info.GetName(), Type: info.GetType().String(), - Address: account, + Address: accAddr.String(), + PubKey: bechPubKey, + }, nil +} + +// Bech32ConsKeyOutput returns key output for a consensus node's key +// information. +func Bech32ConsKeyOutput(keyInfo keys.Info) (KeyOutput, error) { + consAddr := sdk.ConsAddress(keyInfo.GetPubKey().Address().Bytes()) + + bechPubKey, err := sdk.Bech32ifyConsPub(keyInfo.GetPubKey()) + if err != nil { + return KeyOutput{}, err + } + + return KeyOutput{ + Name: keyInfo.GetName(), + Type: keyInfo.GetType().String(), + Address: consAddr.String(), + PubKey: bechPubKey, + }, nil +} + +// Bech32ValKeyOutput returns key output for a validator's key information. +func Bech32ValKeyOutput(keyInfo keys.Info) (KeyOutput, error) { + valAddr := sdk.ValAddress(keyInfo.GetPubKey().Address().Bytes()) + + bechPubKey, err := sdk.Bech32ifyValPub(keyInfo.GetPubKey()) + if err != nil { + return KeyOutput{}, err + } + + return KeyOutput{ + Name: keyInfo.GetName(), + Type: keyInfo.GetType().String(), + Address: valAddr.String(), PubKey: bechPubKey, }, nil } -func PrintInfo(cdc *wire.Codec, info keys.Info) { - ko, err := Bech32KeyOutput(info) +func PrintKeyInfo(keyInfo keys.Info, bechKeyOut BechKeyOutFn) { + ko, err := bechKeyOut(keyInfo) if err != nil { panic(err) } + switch viper.Get(cli.OutputFlag) { case "text": fmt.Printf("NAME:\tTYPE:\tADDRESS:\t\t\t\t\t\tPUBKEY:\n") - printKeyOutput(ko) + PrintKeyOutput(ko) case "json": - out, err := cdc.MarshalJSON(ko) + out, err := MarshalJSON(ko) if err != nil { panic(err) } + fmt.Println(string(out)) } } -func PrintInfos(cdc *wire.Codec, infos []keys.Info) { +func PrintInfos(cdc *codec.Codec, infos []keys.Info) { kos, err := Bech32KeysOutput(infos) if err != nil { panic(err) @@ -159,7 +225,7 @@ func PrintInfos(cdc *wire.Codec, infos []keys.Info) { case "text": fmt.Printf("NAME:\tTYPE:\tADDRESS:\t\t\t\t\t\tPUBKEY:\n") for _, ko := range kos { - printKeyOutput(ko) + PrintKeyOutput(ko) } case "json": out, err := cdc.MarshalJSON(kos) @@ -170,6 +236,60 @@ func PrintInfos(cdc *wire.Codec, infos []keys.Info) { } } -func printKeyOutput(ko KeyOutput) { +func PrintKeyOutput(ko KeyOutput) { fmt.Printf("%s\t%s\t%s\t%s\n", ko.Name, ko.Type, ko.Address, ko.PubKey) } + +func PrintKeyAddress(info keys.Info, bechKeyOut BechKeyOutFn) { + ko, err := bechKeyOut(info) + if err != nil { + panic(err) + } + + fmt.Println(ko.Address) +} + +func PrintPubKey(info keys.Info, bechKeyOut BechKeyOutFn) { + ko, err := bechKeyOut(info) + if err != nil { + panic(err) + } + + fmt.Println(ko.PubKey) +} + +func GetBechKeyOut(bechPrefix string) (BechKeyOutFn, error) { + switch bechPrefix { + case "acc": + return Bech32KeyOutput, nil + case "val": + return Bech32ValKeyOutput, nil + case "cons": + return Bech32ConsKeyOutput, nil + } + + return nil, fmt.Errorf("invalid Bech32 prefix encoding provided: %s", bechPrefix) +} + +// PostProcessResponse performs post process for rest response +func PostProcessResponse(w http.ResponseWriter, cdc *codec.Codec, response interface{}, indent bool) { + var output []byte + switch response.(type) { + default: + var err error + if indent { + output, err = cdc.MarshalJSONIndent(response, "", " ") + } else { + output, err = cdc.MarshalJSON(response) + } + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + case []byte: + output = response.([]byte) + } + w.Header().Set("Content-Type", "application/json") + w.Write(output) +} diff --git a/client/lcd/lcd.go b/client/lcd/lcd.go index afcdd4d06..69aada25d 100644 --- a/client/lcd/lcd.go +++ b/client/lcd/lcd.go @@ -5,18 +5,19 @@ import ( "net/http" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/gorilla/mux" "github.com/irisnet/irishub/client" bankhandler "github.com/irisnet/irishub/client/bank/lcd" "github.com/irisnet/irishub/client/context" + distributionhandler "github.com/irisnet/irishub/client/distribution/lcd" govhandler "github.com/irisnet/irishub/client/gov/lcd" keyshandler "github.com/irisnet/irishub/client/keys/lcd" recordhandle "github.com/irisnet/irishub/client/record/lcd" - slashinghandler "github.com/irisnet/irishub/client/slashing/lcd" - stakehandler "github.com/irisnet/irishub/client/stake/lcd" rpchandler "github.com/irisnet/irishub/client/tendermint/rpc" + slashinghandler "github.com/irisnet/irishub/client/slashing/lcd" txhandler "github.com/irisnet/irishub/client/tendermint/tx" + stakehandler "github.com/irisnet/irishub/client/stake/lcd" "github.com/rakyll/statik/fs" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -26,14 +27,14 @@ import ( ) // ServeLCDStartCommand will start irislcd node, which provides rest APIs with swagger-ui -func ServeLCDStartCommand(cdc *wire.Codec) *cobra.Command { +func ServeLCDStartCommand(cdc *codec.Codec) *cobra.Command { flagListenAddr := "laddr" flagCORS := "cors" flagMaxOpenConnections := "max-open" cmd := &cobra.Command{ - Use: "start", - Short: "Start IRISLCD (IRISHUB light-client daemon), a local REST server with swagger-ui: http://localhost:1317/swagger-ui/", + Use: "start", + Short: "Start IRISLCD (IRISHUB light-client daemon), a local REST server with swagger-ui: http://localhost:1317/swagger-ui/", Example: "irislcd start --chain-id= --trust-node --node=tcp://localhost:26657", RunE: func(cmd *cobra.Command, args []string) error { listenAddr := viper.GetString(flagListenAddr) @@ -71,15 +72,16 @@ func ServeLCDStartCommand(cdc *wire.Codec) *cobra.Command { cmd.Flags().String(flagListenAddr, "tcp://localhost:1317", "The address for the server to listen on") cmd.Flags().String(flagCORS, "", "Set the domains that can make CORS requests (* for all)") - cmd.Flags().String(client.FlagChainID, "", "The chain ID to connect to") + cmd.Flags().String(client.FlagChainID, "", "Chain ID of tendermint node") cmd.Flags().String(client.FlagNode, "tcp://localhost:26657", "Address of the node to connect to") cmd.Flags().Int(flagMaxOpenConnections, 1000, "The number of maximum open connections") cmd.Flags().Bool(client.FlagTrustNode, false, "Don't verify proofs for responses") + cmd.Flags().Bool(client.FlagIndentResponse, true, "Add indent to JSON response") return cmd } -func createHandler(cdc *wire.Codec) *mux.Router { +func createHandler(cdc *codec.Codec) *mux.Router { r := mux.NewRouter() cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout) @@ -87,8 +89,9 @@ func createHandler(cdc *wire.Codec) *mux.Router { r.HandleFunc("/version", CLIVersionRequestHandler).Methods("GET") r.HandleFunc("/node_version", NodeVersionRequestHandler(cliCtx)).Methods("GET") - keyshandler.RegisterRoutes(r) + keyshandler.RegisterRoutes(r, cliCtx.Indent) bankhandler.RegisterRoutes(cliCtx, r, cdc) + distributionhandler.RegisterRoutes(cliCtx, r, cdc) slashinghandler.RegisterRoutes(cliCtx, r, cdc) stakehandler.RegisterRoutes(cliCtx, r, cdc) govhandler.RegisterRoutes(cliCtx, r, cdc) diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index ba638fd41..669cf167c 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -46,7 +46,7 @@ func init() { func TestKeys(t *testing.T) { name, password := "test", "1234567890" addr, seed := CreateAddr(t, "test", password, GetKeyBase(t)) - cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) + cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) defer cleanup() newName := "test_newname" @@ -115,7 +115,7 @@ func TestKeys(t *testing.T) { } func TestVersion(t *testing.T) { - cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}) + cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}) defer cleanup() // node info @@ -138,7 +138,7 @@ func TestVersion(t *testing.T) { } func TestNodeStatus(t *testing.T) { - cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}) + cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}) defer cleanup() // node info @@ -160,7 +160,7 @@ func TestNodeStatus(t *testing.T) { } func TestBlock(t *testing.T) { - cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}) + cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}) defer cleanup() var resultBlock ctypes.ResultBlock @@ -190,7 +190,7 @@ func TestBlock(t *testing.T) { } func TestValidators(t *testing.T) { - cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}) + cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}) defer cleanup() var resultVals rpc.ResultValidatorsOutput @@ -225,7 +225,7 @@ func TestValidators(t *testing.T) { func TestCoinSend(t *testing.T) { name, password := "test", "1234567890" addr, seed := CreateAddr(t, "test", password, GetKeyBase(t)) - cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) + cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) defer cleanup() bz, err := hex.DecodeString("8FA6AB57AD6870F6B5B2E57735F38F2F30E73CB6") @@ -267,7 +267,7 @@ func TestCoinSend(t *testing.T) { func TestTxs(t *testing.T) { name, password := "test", "1234567890" addr, seed := CreateAddr(t, "test", password, GetKeyBase(t)) - cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) + cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}) defer cleanup() // query wrong @@ -324,7 +324,7 @@ func TestTxs(t *testing.T) { } func TestValidatorsQuery(t *testing.T) { - cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}) + cleanup, pks, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}) defer cleanup() require.Equal(t, 1, len(pks)) @@ -341,7 +341,7 @@ func TestValidatorsQuery(t *testing.T) { } func TestValidatorQuery(t *testing.T) { - cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}) + cleanup, pks,_, port := InitializeTestLCD(t, 1, []sdk.AccAddress{}) defer cleanup() require.Equal(t, 1, len(pks)) @@ -591,11 +591,11 @@ func TestProposalsQuery(t *testing.T) { require.Equal(t, proposalID3, (proposals[2]).ProposalID) // Test query deposited by addr1 - proposals = getProposalsFilterDepositer(t, port, addr) + proposals = getProposalsFilterDepositor(t, port, addr) require.Equal(t, proposalID1, (proposals[0]).ProposalID) // Test query deposited by addr2 - proposals = getProposalsFilterDepositer(t, port, addr2) + proposals = getProposalsFilterDepositor(t, port, addr2) require.Equal(t, proposalID2, (proposals[0]).ProposalID) require.Equal(t, proposalID3, (proposals[1]).ProposalID) @@ -609,7 +609,7 @@ func TestProposalsQuery(t *testing.T) { require.Equal(t, proposalID3, (proposals[0]).ProposalID) // Test query voted and deposited by addr1 - proposals = getProposalsFilterVoterDepositer(t, port, addr, addr) + proposals = getProposalsFilterVoterDepositor(t, port, addr, addr) require.Equal(t, proposalID2, (proposals[0]).ProposalID) // Test query votes on Proposal 2 @@ -963,17 +963,17 @@ func getValidator(t *testing.T, port string, validatorAddr sdk.AccAddress) stake // ============= Governance Module ================ -func getProposal(t *testing.T, port string, proposalID int64) govcli.ProposalOutput { +func getProposal(t *testing.T, port string, proposalID int64) gov.ProposalOutput { res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d", proposalID), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var proposal govcli.ProposalOutput + var proposal gov.ProposalOutput err := cdc.UnmarshalJSON([]byte(body), &proposal) require.Nil(t, err) return proposal } -func getDeposit(t *testing.T, port string, proposalID int64, depositerAddr sdk.AccAddress) govcli.DepositOutput { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/deposits/%s", proposalID, depositerAddr), nil) +func getDeposit(t *testing.T, port string, proposalID int64, depositorAddr sdk.AccAddress) govcli.DepositOutput { + res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/deposits/%s", proposalID, depositorAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) var deposit govcli.DepositOutput err := cdc.UnmarshalJSON([]byte(body), &deposit) @@ -999,51 +999,51 @@ func getVotes(t *testing.T, port string, proposalID int64) []gov.Vote { return votes } -func getProposalsAll(t *testing.T, port string) []govcli.ProposalOutput { +func getProposalsAll(t *testing.T, port string) gov.ProposalOutputs { res, body := Request(t, port, "GET", "/gov/proposals", nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var proposals []govcli.ProposalOutput + var proposals gov.ProposalOutputs err := cdc.UnmarshalJSON([]byte(body), &proposals) require.Nil(t, err) return proposals } -func getProposalsFilterDepositer(t *testing.T, port string, depositerAddr sdk.AccAddress) []govcli.ProposalOutput { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?depositer=%s", depositerAddr), nil) +func getProposalsFilterDepositor(t *testing.T, port string, depositorAddr sdk.AccAddress) gov.ProposalOutputs { + res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?depositor=%s", depositorAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var proposals []govcli.ProposalOutput + var proposals gov.ProposalOutputs err := cdc.UnmarshalJSON([]byte(body), &proposals) require.Nil(t, err) return proposals } -func getProposalsFilterVoter(t *testing.T, port string, voterAddr sdk.AccAddress) []govcli.ProposalOutput { +func getProposalsFilterVoter(t *testing.T, port string, voterAddr sdk.AccAddress) gov.ProposalOutputs { res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?voter=%s", voterAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var proposals []govcli.ProposalOutput + var proposals gov.ProposalOutputs err := cdc.UnmarshalJSON([]byte(body), &proposals) require.Nil(t, err) return proposals } -func getProposalsFilterVoterDepositer(t *testing.T, port string, voterAddr, depositerAddr sdk.AccAddress) []govcli.ProposalOutput { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?depositer=%s&voter=%s", depositerAddr, voterAddr), nil) +func getProposalsFilterVoterDepositor(t *testing.T, port string, voterAddr, depositorAddr sdk.AccAddress) gov.ProposalOutputs { + res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?depositor=%s&voter=%s", depositorAddr, voterAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var proposals []govcli.ProposalOutput + var proposals gov.ProposalOutputs err := cdc.UnmarshalJSON([]byte(body), &proposals) require.Nil(t, err) return proposals } -func getProposalsFilterStatus(t *testing.T, port string, status gov.ProposalStatus) []govcli.ProposalOutput { +func getProposalsFilterStatus(t *testing.T, port string, status gov.ProposalStatus) gov.ProposalOutputs { res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?status=%s", status), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var proposals []govcli.ProposalOutput + var proposals gov.ProposalOutputs err := cdc.UnmarshalJSON([]byte(body), &proposals) require.Nil(t, err) return proposals @@ -1100,7 +1100,7 @@ func doDeposit(t *testing.T, port, seed, name, password string, proposerAddr sdk // deposit on proposal jsonStr := []byte(fmt.Sprintf(`{ - "depositer": "%s", + "depositor": "%s", "amount": "5iris", "base_tx": { "name": "%s", diff --git a/client/lcd/swaggerui/index.html b/client/lcd/swaggerui/index.html index b7cb77fdb..0c4855763 100644 --- a/client/lcd/swaggerui/index.html +++ b/client/lcd/swaggerui/index.html @@ -40,7 +40,7 @@ // Build a system const ui = SwaggerUIBundle({ - url: "./swagger.json", + url: "./swagger.yaml", dom_id: '#swagger-ui', deepLinking: true, presets: [ diff --git a/client/lcd/swaggerui/swagger.json b/client/lcd/swaggerui/swagger.json deleted file mode 100644 index 40ff01bc9..000000000 --- a/client/lcd/swaggerui/swagger.json +++ /dev/null @@ -1,3045 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "description": "All IRISLCD supported APIs will be shown by this swagger-ui page. You can access them on this page.", - "version": "1.0", - "title": "IRISLCD Swagger-UI", - "termsOfService": "https://www.irisnet.org", - "contact": { - "name": "边界智能", - "url": "https://bianjie.ai/", - "email": "service@bianjie.ai" - }, - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - } - }, - "basePath": "/", - "paths": { - "/node_version": { - "get": { - "tags": [ - "Version" - ], - "summary": "Get the version of connected full node", - "description": "Get the version of connected full node", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/version": { - "get": { - "tags": [ - "Version" - ], - "summary": "Get irislcd version", - "description": "Get irislcd version", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/bank/accounts/{address}": { - "get": { - "tags": [ - "ICS20: Bank" - ], - "summary": "Get account information", - "description": "Get account information", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "parameters": [ - { - "name": "address", - "in": "path", - "required": true, - "type": "string" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/bank.AccountQueryResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/bank/coin/{coin-type}": { - "get": { - "tags": [ - "ICS20: Bank" - ], - "summary": "Get coin type", - "description": "Get the detailed information about the given coin type", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "parameters": [ - { - "name": "coin-type", - "in": "path", - "required": true, - "type": "string" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/bank.CoinTypeResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/bank/{address}/send": { - "post": { - "tags": [ - "ICS20: Bank" - ], - "summary": "Send tokens", - "description": "Send tokens to given address.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "parameters": [ - { - "in": "path", - "name": "address", - "description": "address to receive tokens", - "required": true, - "type": "string" - }, - { - "in": "query", - "name": "generate-only", - "description": "if true, only generate an unsigned transaction without broadcasting", - "required": false, - "type": "boolean" - }, - { - "in": "query", - "name": "async", - "description": "if true, broadcast transaction asynchronously", - "required": false, - "type": "boolean" - }, - { - "in": "body", - "name": "sendToken", - "description": "The `\"sender\"` field is required only when generate-only is true. Otherwise, just omit it. \nThe `\"amount\"` field can specify multiple tokens, for instance: `\"10iris,20atom\"`. \nThe `\"fee\"` field can specify multi-tokens as transaction fee, for instance, `\"0.1iris,0.1atom\"`. \nCurrently, only iris token is supported. Other tokens will be ingnored. \ngasPrice = fee/gas, gasPrice should be no less than 2*10^(-8)iris. The suggested gas is 10000, and the suggested fee is 0.0002iris.", - "required": true, - "schema": { - "$ref": "#/definitions/bank.TransferBody" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/common.BroadcastTxCommitResult" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/keys": { - "get": { - "description": "List all keys in the key store", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS1: Key Management" - ], - "summary": "List all keys in the key store", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/keys.KeyOutputResponse" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - }, - "post": { - "description": "Create a new key and save it to the keystore", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS1: Key Management" - ], - "summary": "Create a new key and save it to the keystore", - "parameters": [ - { - "description": "if the seed field is not empty, it will be used to recover a key", - "name": "CreateNewKeyBody", - "in": "body", - "required": true, - "schema": { - "type": "object", - "$ref": "#/definitions/keys.NewKeyBody" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "$ref": "#/definitions/keys.KeyOutputResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/keys/{name}": { - "get": { - "description": "Get the detailed information of a key", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS1: Key Management" - ], - "summary": "Get the detailed information of a key by its name", - "parameters": [ - { - "type": "string", - "description": "key name", - "name": "name", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "$ref": "#/definitions/keys.KeyOutputResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - }, - "put": { - "description": "Update key password", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS1: Key Management" - ], - "summary": "Update key password", - "parameters": [ - { - "type": "string", - "name": "name", - "required": true, - "in": "path" - }, - { - "name": "pwd", - "in": "body", - "required": true, - "schema": { - "type": "object", - "$ref": "#/definitions/keys.UpdateKeyBody" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - }, - "delete": { - "description": "Delete key by its name", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS1: Key Management" - ], - "summary": "Delete key by its name", - "parameters": [ - { - "type": "string", - "name": "name", - "required": true, - "in": "path" - }, - { - "name": "pwd", - "in": "body", - "required": true, - "schema": { - "type": "object", - "$ref": "#/definitions/keys.DeleteKeyBody" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/gov/proposals": { - "post": { - "description": "Send transaction to submit a proposal", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS22: Governance" - ], - "summary": "Submit a proposal", - "parameters": [ - { - "in": "query", - "name": "generate-only", - "description": "if true, only generate an unsigned transaction without broadcasting", - "required": false, - "type": "boolean" - }, - { - "in": "query", - "name": "async", - "description": "if true, broadcast transaction asynchronously", - "required": false, - "type": "boolean" - }, - { - "description": "The `\"initial_deposit\"` field can specify multiple tokens, for instance: `\"10iris,20atom\"`. \nThe `\"proposal_type\"` represent proposal type, and its value can be `\"Text\"`, `\"ParameterChange\"`, `\"SoftwareUpgrade\"`. \nThe `\"fee\"` field can specify multi-tokens as transaction fee. For instance, `\"0.1iris, 0.1atom\"`. \nCurrently, only iris token is supported. Other tokens will be ingnored. \ngasPrice = fee/gas, gasPrice should be no less than 2*10^(-8)iris. The suggested gas is 200000, and the suggested fee is 0.004iris.", - "name": "postProposalBody", - "in": "body", - "required": true, - "schema": { - "type": "object", - "$ref": "#/definitions/gov.PostProposalBody" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "$ref": "#/definitions/common.BroadcastTxCommitResult" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - }, - "get": { - "description": "Query proposals information with parameters", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS22: Governance" - ], - "parameters": [ - { - "in": "query", - "name": "voter", - "description": "voter address", - "required": false, - "type": "string" - }, - { - "in": "query", - "name": "depositer", - "description": "depositer address", - "required": false, - "type": "string" - }, - { - "in": "query", - "name": "status", - "description": "proposal status, supported values: `\"DepositPeriod\"`, `\"VotingPeriod\"`, `\"Passed\"`, `\"Rejected\"`", - "required": false, - "type": "string" - } - ], - "summary": "Query proposals", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/gov.TextProposalResponse" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/gov/proposals/{proposal-id}/deposits": { - "post": { - "description": "Send transaction to deposit tokens to a proposal", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS22: Governance" - ], - "summary": "Deposit tokens to a proposal", - "parameters": [ - { - "in": "query", - "name": "generate-only", - "description": "if true, only generate an unsigned transaction without broadcasting", - "required": false, - "type": "boolean" - }, - { - "in": "query", - "name": "async", - "description": "if true, broadcast transaction asynchronously", - "required": false, - "type": "boolean" - }, - { - "type": "string", - "description": "proposal id", - "name": "proposal-id", - "required": true, - "in": "path" - }, - { - "description": "The `\"amount\"` field can specify multiple tokens, for instance: `\"10iris,20atom\"`. \nThe `\"fee\"` field can specify multi-tokens as transaction fee, for instance, `\"0.1iris,0.1atom\"`. \nCurrently, only iris token is supported. Other tokens will be ingnored. \ngasPrice = fee/gas, gasPrice should be no less than 2*10^(-8)iris. The suggested gas is 200000, and the suggested fee is 0.004iris.", - "name": "depositBody", - "in": "body", - "required": true, - "schema": { - "type": "object", - "$ref": "#/definitions/gov.DepositBody" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "$ref": "#/definitions/common.BroadcastTxCommitResult" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/gov/proposals/{proposal-id}/votes": { - "post": { - "description": "Send transaction to vote a proposal", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS22: Governance" - ], - "summary": "Vote a proposal", - "parameters": [ - { - "in": "query", - "name": "generate-only", - "description": "if true, only generate an unsigned transaction without broadcasting", - "required": false, - "type": "boolean" - }, - { - "in": "query", - "name": "async", - "description": "if true, broadcast transaction asynchronously", - "required": false, - "type": "boolean" - }, - { - "type": "string", - "description": "proposal id", - "name": "proposal-id", - "required": true, - "in": "path" - }, - { - "description": "The value of `\"option\"` field can be `\"Yes\"`, `\"No\"`, `\"NoWithVeto\"` and `\"Abstain\"`. \nThe `\"fee\"` field can specify multi-tokens as transaction fee, for instance, `\"0.1iris,0.1atom\"`. \nCurrently, only iris token is supported. Other tokens will be ingnored. \ngasPrice = fee/gas, gasPrice should be no less than 2*10^(-8)iris. The suggested gas is 200000, and the suggested fee is 0.004iris.", - "name": "voteBody", - "in": "body", - "required": true, - "schema": { - "type": "object", - "$ref": "#/definitions/gov.VoteBody" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "$ref": "#/definitions/common.BroadcastTxCommitResult" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - }, - "get": { - "description": "Query voters information by proposal-id", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS22: Governance" - ], - "summary": "Query voters", - "parameters": [ - { - "type": "string", - "description": "proposal id", - "name": "proposal-id", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/gov.VoteResponse" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/gov/proposals/{proposal-id}": { - "get": { - "description": "Query a proposal by id", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS22: Governance" - ], - "summary": "Query a proposal", - "parameters": [ - { - "type": "string", - "name": "proposal-id", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "$ref": "#/definitions/gov.TextProposalResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/gov/proposals/{proposal-id}/deposits/{depositer}": { - "get": { - "description": "Query deposit by proposal-id and depositer address", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS22: Governance" - ], - "summary": "Query deposit", - "parameters": [ - { - "type": "string", - "description": "proposal id", - "name": "proposal-id", - "required": true, - "in": "path" - }, - { - "type": "string", - "description": "depositer address", - "name": "depositer", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "$ref": "#/definitions/gov.DepositResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/gov/proposals/{proposal-id}/votes/{voter}": { - "get": { - "description": "Query vote information by proposal-id and voter address", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS22: Governance" - ], - "summary": "Query vote", - "parameters": [ - { - "type": "string", - "description": "proposal id", - "name": "proposal-id", - "required": true, - "in": "path" - }, - { - "type": "string", - "description": "voter address", - "name": "voter", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "$ref": "#/definitions/gov.VoteResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/gov/params": { - "get": { - "description": "Query parameters which were added or modified by governance", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS22: Governance" - ], - "summary": "Query parameters which were added or modified by governance", - "parameters": [ - - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/common.KVPair" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/stake/delegators/{delegatorAddr}/delegations": { - "post": { - "description": "Send staking transactions", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS21: Staking" - ], - "summary": "Send staking transactions", - "parameters": [ - { - "type": "string", - "description": "delegator address", - "name": "delegatorAddr", - "required": true, - "in": "path" - }, - { - "in": "query", - "name": "generate-only", - "description": "if true, only generate an unsigned transaction without broadcasting", - "required": false, - "type": "boolean" - }, - { - "in": "query", - "name": "async", - "description": "if true, broadcast transaction asynchronously", - "required": false, - "type": "boolean" - }, - { - "description": "The `\"delegation\"` field under `\"delegations\"` represents the delegation token amount. Only iris token is supported, for instance: `\"10iris\"` or `\"5.5iris\"`. \nThe `\"fee\"` field can specify multi-tokens as transaction fee, for instance, `\"0.1iris,0.1atom\"`. \nCurrently, only iris token is supported. Other tokens will be ingnored. \ngasPrice = fee/gas, gasPrice should be no less than 2*10^(-8)iris. The suggested gas is 200000, and the suggested fee is 0.004iris.", - "name": "EditDelegationsBody", - "in": "body", - "required": true, - "schema": { - "type": "object", - "$ref": "#/definitions/stake.EditDelegationsBody" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "$ref": "#/definitions/common.BroadcastTxCommitResult" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/stake/delegators/{delegatorAddr}": { - "get": { - "description": "Get all delegations (delegation, undelegation and redelegation) from a delegator", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS21: Staking" - ], - "summary": "Get all delegations from a delegator", - "parameters": [ - { - "type": "string", - "description": "delegator address", - "name": "delegatorAddr", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "$ref": "#/definitions/stake.DelegationSummaryResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/stake/delegators/{delegatorAddr}/txs": { - "get": { - "description": "Get all staking txs (i.e msgs) from a delegator", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS21: Staking" - ], - "summary": "Get all staking txs from a delegator", - "parameters": [ - { - "type": "string", - "description": "delegator address", - "name": "delegatorAddr", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/stake.TxInfoResponse" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/stake/delegators/{delegatorAddr}/validators": { - "get": { - "description": "Query all validators that a delegator is bonded to", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS21: Staking" - ], - "summary": "Query all validators that a delegator is bonded to", - "parameters": [ - { - "type": "string", - "description": "delegator address", - "name": "delegatorAddr", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/stake.BechValidatorResponse" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/stake/delegators/{delegatorAddr}/validators/{validatorAddr}": { - "get": { - "description": "Query a validator that a delegator is bonded to", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS21: Staking" - ], - "summary": "Query a validator that a delegator is bonded to", - "parameters": [ - { - "type": "string", - "description": "delegator address", - "name": "delegatorAddr", - "required": true, - "in": "path" - }, - { - "type": "string", - "description": "validator address", - "name": "validatorAddr", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "$ref": "#/definitions/stake.BechValidatorResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/stake/delegators/{delegatorAddr}/delegations/{validatorAddr}": { - "get": { - "description": "Query a delegation between a delegator and a validator", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS21: Staking" - ], - "summary": "Query a delegation between a delegator and a validator", - "parameters": [ - { - "type": "string", - "description": "delegator address", - "name": "delegatorAddr", - "required": true, - "in": "path" - }, - { - "type": "string", - "description": "validator address", - "name": "validatorAddr", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "$ref": "#/definitions/stake.DelegationWithoutRatResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}": { - "get": { - "description": "Query all unbonding_delegations between a delegator and a validator", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS21: Staking" - ], - "summary": "Query all unbonding_delegations between a delegator and a validator", - "parameters": [ - { - "type": "string", - "description": "delegator address", - "name": "delegatorAddr", - "required": true, - "in": "path" - }, - { - "type": "string", - "description": "validator address", - "name": "validatorAddr", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/stake.UnbondingDelegationResponse" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/stake/validators": { - "get": { - "description": "Get all validators", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS21: Staking" - ], - "summary": "Get all validators", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/stake.BechValidatorResponse" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/stake/validators/{addr}": { - "get": { - "description": "Get a specific validator", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS21: Staking" - ], - "summary": "Get a specific validator", - "parameters": [ - { - "type": "string", - "description": "validator address", - "name": "addr", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "$ref": "#/definitions/stake.BechValidatorResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/stake/validator/{addr}/exRate": { - "get": { - "description": "Get the delegated share exchange rate of the given validator", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS21: Staking" - ], - "summary": "Get the delegated share exchange rate of the given validator", - "parameters": [ - { - "type": "string", - "description": "validator address", - "name": "addr", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/slashing/signing_info/{validator_pub}": { - "get": { - "description": "Get validator's sign info", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS23: Slashing" - ], - "summary": "Get validator's sign info", - "parameters": [ - { - "type": "string", - "description": "validator's public key", - "name": "validator_pub", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/slashing/unrevoke": { - "post": { - "description": "Unrevoke a revoked validator", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS23: Slashing" - ], - "summary": "Unrevoke a revoked validator", - "parameters": [ - { - "description": "The `\"fee\"` field can specify multi-tokens as transaction fee. For instance, `\"0.1iris,0.1atom\"`. \nCurrently, only iris token is supported. Other tokens will be ingnored. \ngasPrice = fee/gas, gasPrice should be no less than 2*10^(-8)iris. The suggested gas is 200000, and the suggested fee is 0.004iris.", - "name": "UnrevokeBody", - "in": "body", - "required": true, - "schema": { - "type": "object", - "$ref": "#/definitions/slashing.UnrevokeBody" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/node_info": { - "get": { - "description": "Get connected full node's information", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS0: Tendermint" - ], - "summary": "Get connected full node's information", - "parameters": [ - - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/syncing": { - "get": { - "description": "Get the sync status of the connected full node", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS0: Tendermint" - ], - "summary": "Get the sync status of the connected full node", - "parameters": [ - - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "boolean" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/blocks/latest": { - "get": { - "description": "Get the latest block", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS0: Tendermint" - ], - "summary": "Get the latest block", - "parameters": [ - - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/blocks/{height}": { - "get": { - "description": "Get block at a given height", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS0: Tendermint" - ], - "summary": "Get block at a given height", - "parameters": [ - { - "type": "integer", - "description": "block height", - "name": "height", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/validatorsets/latest": { - "get": { - "description": "Get the latest validator set", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS0: Tendermint" - ], - "summary": "Get the latest validator set", - "parameters": [ - - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/validatorsets/{height}": { - "get": { - "description": "Get a validator set at a given height", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS0: Tendermint" - ], - "summary": "Get a validator set at a given height", - "parameters": [ - { - "type": "string", - "description": "blockchain height", - "name": "height", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/txs": { - "get": { - "description": "Search a transaction by the given tags", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS0: Tendermint" - ], - "summary": "Search a transaction", - "parameters": [ - { - "type": "string", - "description": "transaction tag, for instance: sender=`'faa12lyh9nzczkamen2ppa0v2ej0jkax9mqzaqqr57'`", - "name": "tag", - "required": true, - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/txs/{hash}": { - "get": { - "description": "Get a transaction by hash", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS0: Tendermint" - ], - "summary": "Get a transaction by hash", - "parameters": [ - { - "type": "string", - "description": "transaction hash", - "name": "hash", - "required": true, - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - }, - "/txs/send": { - "post": { - "description": "Compose and broadcast a transaction", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "ICS0: Tendermint" - ], - "summary": "Broadcast a transaction", - "parameters": [ - { - "in": "query", - "name": "async", - "description": "if true, broadcast transaction asynchronously", - "required": false, - "type": "boolean" - }, - { - "description": "stdTx", - "name": "sendTxBody", - "in": "body", - "required": true, - "schema": { - "type": "object", - "$ref": "#/definitions/tx.SendTxBody" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "object", - "$ref": "#/definitions/common.HTTPError" - } - } - } - } - } - }, - "definitions": { - "common.HTTPError": { - "type": "object", - "properties": { - "rest api": { - "type": "string", - "example": "2.0" - }, - "code": { - "type": "integer", - "example": 500 - }, - "error message": { - "type": "string" - } - } - }, - "common.Coin": { - "type": "object", - "properties": { - "denom": { - "type": "string" - }, - "amount": { - "type": "string" - } - } - }, - "common.KVPair": { - "type": "object", - "properties": { - "key": { - "type": "string" - }, - "value": { - "type": "string" - } - } - }, - "common.CheckTxResult": { - "type": "object", - "properties": { - "code": { - "type": "integer" - }, - "data": { - "type": "string" - }, - "gas_used": { - "type": "integer" - }, - "gas_wanted": { - "type": "integer" - }, - "info": { - "type": "string" - }, - "log": { - "type": "string" - }, - "tags": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/common.KVPair" - } - } - }, - "example": { - "code": 0, - "data": "data", - "log": "log", - "gas_used": 6, - "gas_wanted": 1, - "info": "info", - "tags": [ - "", - "" - ] - } - }, - "common.DeliverTxResult": { - "type": "object", - "properties": { - "code": { - "type": "integer" - }, - "data": { - "type": "string" - }, - "gas_used": { - "type": "integer" - }, - "gas_wanted": { - "type": "integer" - }, - "info": { - "type": "string" - }, - "log": { - "type": "string" - }, - "tags": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/common.KVPair" - } - } - }, - "example": { - "code": 5, - "data": "data", - "log": "log", - "gas_used": 5, - "gas_wanted": 2, - "info": "info", - "tags": [ - "", - "" - ] - } - }, - "common.BroadcastTxCommitResult": { - "type": "object", - "properties": { - "check_tx": { - "$ref": "#/definitions/common.CheckTxResult" - }, - "deliver_tx": { - "$ref": "#/definitions/common.DeliverTxResult" - }, - "hash": { - "type": "string" - }, - "height": { - "type": "integer" - } - }, - "example": { - "check_tx": { - "code": 0, - "data": "data", - "log": "log", - "gas_used": 6, - "gas_wanted": 1, - "info": "info", - "tags": [ - "", - "" - ] - }, - "deliver_tx": { - "code": 5, - "data": "data", - "log": "log", - "gas_used": 5, - "gas_wanted": 2, - "info": "info", - "tags": [ - "", - "" - ] - }, - "hash": "hash", - "height": 7 - } - }, - "common.coinUnit": { - "type": "object", - "properties": { - "denom": { - "type": "string" - }, - "decimal": { - "type": "integer" - } - } - }, - "common.BaseTx": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "password": { - "type": "string" - }, - "chain_id": { - "type": "string" - }, - "account_number": { - "type": "string" - }, - "sequence": { - "type": "string" - }, - "gas": { - "type": "string" - }, - "fee": { - "type": "string" - } - } - }, - "bank.AccountQueryResponse": { - "type": "object", - "properties": { - "account_number": { - "type": "integer" - }, - "address": { - "type": "string" - }, - "coins": { - "type": "array", - "items": { - "type": "string" - } - }, - "public_key": { - "type": "string" - }, - "sequence": { - "type": "integer" - } - } - }, - "bank.TransferBody": { - "type": "object", - "properties": { - "amount": { - "type": "string" - }, - "sender": { - "type": "string" - }, - "base_tx": { - "$ref": "#/definitions/common.BaseTx" - } - } - }, - "bank.CoinTypeResponse": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "desc": { - "type": "string" - }, - "min_unit": { - "$ref": "#/definitions/common.coinUnit" - }, - "Units": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/common.coinUnit" - } - }, - "origin": { - "type": "integer" - } - } - }, - "keys.DeleteKeyBody": { - "type": "object", - "properties": { - "password": { - "type": "string" - } - } - }, - "keys.NewKeyBody": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "password": { - "type": "string" - }, - "seed": { - "type": "string" - } - } - }, - "keys.UpdateKeyBody": { - "type": "object", - "properties": { - "new_password": { - "type": "string" - }, - "old_password": { - "type": "string" - } - } - }, - "keys.KeyOutputResponse": { - "type": "object", - "properties": { - "address": { - "type": "string" - }, - "name": { - "type": "string" - }, - "pub_key": { - "type": "string" - }, - "type": { - "type": "string" - } - } - }, - "gov.PostProposalBody": { - "type": "object", - "properties": { - "base_tx": { - "$ref": "#/definitions/common.BaseTx" - }, - "title": { - "type": "string" - }, - "description": { - "type": "string" - }, - "proposal_type": { - "type": "string" - }, - "proposer": { - "type": "string" - }, - "initial_deposit": { - "type": "string" - } - } - }, - "gov.DepositBody": { - "type": "object", - "properties": { - "base_tx": { - "$ref": "#/definitions/common.BaseTx" - }, - "depositer": { - "type": "string" - }, - "amount": { - "type": "string" - } - } - }, - "gov.VoteBody": { - "type": "object", - "properties": { - "base_tx": { - "$ref": "#/definitions/common.BaseTx" - }, - "voter": { - "type": "string" - }, - "option": { - "type": "string" - } - } - }, - "gov.TextProposalResponse": { - "type": "object", - "properties": { - "base_req": { - "$ref": "#/definitions/common.BaseTx" - }, - "voter": { - "type": "string" - }, - "option": { - "type": "string" - } - } - }, - "gov.DepositResponse": { - "type": "object", - "properties": { - "amount": { - "$ref": "#/definitions/common.BaseTx" - }, - "voter": { - "type": "string" - }, - "option": { - "type": "string" - } - } - }, - "gov.VoteResponse": { - "type": "object", - "properties": { - "voter": { - "type": "string" - }, - "proposal_id": { - "type": "integer" - }, - "option": { - "type": "string" - } - } - }, - "stake.MsgDelegationsInput": { - "type": "object", - "properties": { - "validator_addr": { - "type": "string" - }, - "delegation": { - "type": "string" - } - } - }, - "stake.MsgBeginUnbondingInput": { - "type": "object", - "properties": { - "validator_addr": { - "type": "string" - }, - "shares": { - "type": "string" - } - } - }, - "stake.MsgCompleteUnbondingInput": { - "type": "object", - "properties": { - "validator_addr": { - "type": "string" - } - } - }, - "stake.MsgBeginRedelegateInput": { - "type": "object", - "properties": { - "validator_src_addr": { - "type": "string" - }, - "validator_dst_addr": { - "type": "string" - }, - "shares": { - "type": "string" - } - } - }, - "stake.MsgCompleteRedelegateInput": { - "type": "object", - "properties": { - "validator_src_addr": { - "type": "string" - }, - "validator_dst_addr": { - "type": "string" - } - } - }, - "stake.EditDelegationsBody": { - "type": "object", - "properties": { - "base_tx": { - "$ref": "#/definitions/common.BaseTx" - }, - "delegations": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/stake.MsgDelegationsInput" - } - }, - "begin_unbondings": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/stake.MsgBeginUnbondingInput" - } - }, - "complete_unbondings": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/stake.MsgCompleteUnbondingInput" - } - }, - "begin_redelegates": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/stake.MsgBeginRedelegateInput" - } - }, - "complete_redelegates": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/stake.MsgCompleteRedelegateInput" - } - } - } - }, - "common.StdSignature": { - "type": "object", - "properties": { - "pub_key": { - "type": "string" - }, - "signature": { - "type": "string" - }, - "account_number": { - "type": "string" - }, - "sequence": { - "type": "string" - } - } - }, - "common.StdFee": { - "type": "object", - "properties": { - "gas": { - "type": "string" - }, - "amount": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/common.Coin" - } - } - } - }, - "tx.SendTxBody": { - "type": "object", - "properties": { - "memo": { - "type": "string" - }, - "fee": { - "type": "object", - "$ref": "#/definitions/common.StdFee" - }, - "msgs": { - "type": "array", - "items": { - "type": "string" - } - }, - "signatures": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/common.StdSignature" - } - } - } - }, - "stake.UnbondingDelegationResponse": { - "type": "object", - "properties": { - "delegator_addr": { - "type": "string" - }, - "validator_addr": { - "type": "string" - }, - "initial_balance": { - "type": "string" - }, - "balance": { - "type": "string" - }, - "creation_height": { - "type": "integer" - }, - "min_time": { - "type": "integer" - } - } - }, - "stake.RedelegationResponse": { - "type": "object", - "properties": { - "delegator_addr": { - "type": "string" - }, - "validator_src_addr": { - "type": "string" - }, - "validator_dst_addr": { - "type": "string" - }, - "creation_height": { - "type": "integer" - }, - "min_time": { - "type": "integer" - }, - "initial_balance": { - "type": "string" - }, - "balance": { - "type": "string" - }, - "shares_src": { - "type": "string" - }, - "shares_dst": { - "type": "string" - } - } - }, - "stake.DescriptionResponse": { - "type": "object", - "properties": { - "moniker": { - "type": "string" - }, - "identity": { - "type": "string" - }, - "website": { - "type": "string" - }, - "details": { - "type": "string" - } - } - }, - "stake.BechValidatorResponse": { - "type": "object", - "properties": { - "operator": { - "type": "string" - }, - "pub_key": { - "type": "string" - }, - "revoked": { - "type": "boolean" - }, - "status": { - "type": "integer" - }, - "tokens": { - "type": "string" - }, - "delegator_shares": { - "type": "string" - }, - "description": { - "type": "object", - "$ref": "#/definitions/stake.DescriptionResponse" - }, - "bond_height": { - "type": "integer" - }, - "bond_intra_tx_counter": { - "type": "integer" - }, - "proposer_reward_pool": { - "type": "string" - }, - "commission": { - "type": "string" - }, - "commission_max": { - "type": "string" - }, - "commission_change_rate": { - "type": "string" - }, - "commission_change_today": { - "type": "string" - }, - "prev_bonded_shares": { - "type": "string" - } - } - }, - "stake.DelegationWithoutRatResponse": { - "type": "object", - "properties": { - "delegator_addr": { - "type": "string" - }, - "validator_addr": { - "type": "string" - }, - "shares": { - "type": "string" - }, - "height": { - "type": "integer" - } - } - }, - "stake.DelegationSummaryResponse": { - "type": "object", - "properties": { - "redelegations": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/stake.RedelegationResponse" - } - }, - "unbonding_delegations": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/stake.UnbondingDelegationResponse" - } - }, - "delegations": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/stake.DelegationWithoutRatResponse" - } - } - } - }, - "stake.TxInfoResponse": { - "type": "object", - "properties": { - "hash": { - "type": "string" - }, - "height": { - "type": "integer" - }, - "tx": { - "type": "string" - }, - "result": { - "type": "object", - "$ref": "#/definitions/common.DeliverTxResult" - } - } - }, - "slashing.UnrevokeBody": { - "type": "object", - "properties": { - "base_tx": { - "$ref": "#/definitions/common.BaseTx" - }, - "validator_addr": { - "type": "string" - } - } - } - } -} diff --git a/client/lcd/swaggerui/swagger.yaml b/client/lcd/swaggerui/swagger.yaml new file mode 100644 index 000000000..c532cd301 --- /dev/null +++ b/client/lcd/swaggerui/swagger.yaml @@ -0,0 +1,2469 @@ +--- +swagger: '2.0' +info: + description: A REST interface for state queries, transaction generation, signing, and broadcast. + version: '1.0' + title: IRISLCD Swagger-UI + termsOfService: https://www.irisnet.org + contact: + name: 边界智能 + url: https://bianjie.ai/ + email: service@bianjie.ai + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html +tags: +- name: ICS0 + description: Tendermint APIs, such as query blocks, transactions and validatorset +- name: ICS1 + description: Key management APIs +- name: ICS20 + description: Create, sign and broadcast transactions +- name: ICS21 + description: Stake module APIs +- name: ICS22 + description: Governance module APIs +- name: ICS23 + description: Slashing module APIs +- name: ICS24 + description: Distribution module APIs +- name: version + description: Query app version +paths: + /version: + get: + summary: Version of irislcd + tags: + - version + description: Get the version of irislcd running locally to compare against expected + responses: + 200: + description: Plaintext version i.e. "v0.7.0" + /node_version: + get: + summary: Version of the connected node + tags: + - version + description: Get the version of the SDK running on the connected node to compare against expected + responses: + 200: + description: Plaintext version i.e. "v0.7.0" + 500: + description: failed to query node version + /node_info: + get: + description: Information about the connected node + summary: The properties of the connected node + tags: + - ICS0 + produces: + - application/json + responses: + 200: + description: Node status + schema: + type: object + properties: + id: + type: string + moniker: + type: string + example: validator-name + network: + type: string + example: irishub-mainnet + channels: + type: string + listen_addr: + type: string + example: 192.168.56.1:26656 + version: + description: Tendermint version + type: string + example: 0.7.0 + other: + description: more information on versions + type: array + items: + type: string + 500: + description: Failed to query node status + /syncing: + get: + summary: Syncing state of node + tags: + - ICS0 + description: Get if the node is currently syning with other nodes + responses: + 200: + description: node sync status + schema: + type: object + properties: + syncing: + type: boolean + example: false + 500: + description: Server internal error + /blocks/latest: + get: + summary: Get the latest block + tags: + - ICS0 + produces: + - application/json + responses: + 200: + description: The latest block + schema: + $ref: "#/definitions/BlockQuery" + 500: + description: Server internal error + /blocks/{height}: + get: + summary: Get a block at a certain height + tags: + - ICS0 + produces: + - application/json + parameters: + - in: path + name: height + description: Block height + required: true + type: number + responses: + 200: + description: The block at a specific height + schema: + $ref: "#/definitions/BlockQuery" + 404: + description: Request block height doesn't + 400: + description: Invalid height + 500: + description: Server internal error + /validatorsets/latest: + get: + summary: Get the latest validator set + tags: + - ICS0 + produces: + - application/json + responses: + 200: + description: The validator set at the latest block height + schema: + type: object + properties: + block_height: + type: number + validators: + type: array + items: + $ref: "#/definitions/TendermintValidator" + 500: + description: Server internal error + /validatorsets/{height}: + get: + summary: Get a validator set a certain height + tags: + - ICS0 + produces: + - application/json + parameters: + - in: path + name: height + description: Block height + required: true + type: number + responses: + 200: + description: The validator set at a specific block height + schema: + type: object + properties: + block_height: + type: number + validators: + type: array + items: + $ref: "#/definitions/TendermintValidator" + 404: + description: Block at height not available + 400: + description: Invalid height + 500: + description: Server internal error + /txs/{hash}: + get: + summary: Get a Tx by hash + tags: + - ICS0 + produces: + - application/json + parameters: + - in: path + name: hash + description: Tx hash + required: true + type: string + responses: + 200: + description: Tx with the provided hash + schema: + $ref: "#/definitions/TxQuery" + 500: + description: Internal Server Error + /txs: + get: + tags: + - ICS0 + summary: Search transactions + description: Search transactions by tag + produces: + - application/json + parameters: + - in: query + name: tag + type: string + description: "transaction tag, for instance: sender_bech32=`'faa1xp8ptallwun6p0hv5ym4adruupc8q5djc95k30'`" + required: true + - in: query + name: page + description: Pagination page, default value 0 + type: integer + - in: query + name: size + description: Pagination size, default value 100 + type: integer + responses: + 200: + description: All Tx matching the provided tags + schema: + type: array + items: + $ref: "#/definitions/TxQuery" + 400: + description: Invalid search tags + 500: + description: Internal Server Error + post: + tags: + - ICS0 + summary: broadcast Tx + description: broadcast tx with tendermint rpc + consumes: + - application/json + produces: + - application/json + parameters: + - in: body + name: broadcastTxBody + description: Build a StdTx transaction and serilize it to a byte array with amino, then the `"tx"` field in the post body will be the base64 encoding of the byte array. The supported return types includes `"block"`(return after tx commit), `"sync"`(return afer CheckTx) and `"async"`(return right away). + required: true + schema: + type: object + properties: + tx: + type: string + return: + type: string + example: block + responses: + 200: + description: Broadcast tx result + schema: + $ref: "#/definitions/BroadcastTxCommitResult" + 500: + description: Internal Server Error + + /tx/sign: + post: + tags: + - ICS20 + summary: Sign a transation + description: Sign a transation providing locally stored account and according password, return a StdTx with amino encoding signature and public key + consumes: + - application/json + produces: + - application/json + parameters: + - in: body + name: sendToken + description: sign tx + required: true + schema: + type: object + properties: + tx: + $ref: "#/definitions/StdTx" + name: + type: string + password: + type: string + chain_id: + type: string + account_number: + type: string + example: "0" + sequence: + type: string + example: "0" + append_sig: + type: boolean + example: true + responses: + 200: + description: The signed Tx + schema: + $ref: "#/definitions/StdTx" + 400: + description: The Tx was malformated or key doesn't exist + 401: + description: Key password is wrong + 500: + description: Server internal error + /tx/broadcast: + post: + tags: + - ICS20 + summary: Broadcast a signed StdTx with amino encoding signature and public key + description: Broadcast a signed StdTx with amino encoding signature and public key to full iris node + consumes: + - application/json + produces: + - application/json + parameters: + - in: query + name: async + description: if true, broadcast transaction asynchronously + required: false + type: boolean + - in: body + name: broadcastTxBody + description: broadcast tx + required: true + schema: + type: object + properties: + tx: + $ref: "#/definitions/StdTx" + responses: + 202: + description: Tx was send and will probably be added to the next block + schema: + $ref: "#/definitions/BroadcastTxCommitResult" + 400: + description: The Tx was malformated + 500: + description: Server internal error + /txs/send: + post: + summary: Send non-amino encoding transaction + description: Send non-amino encoding transaction + consumes: + - application/json + produces: + - application/json + tags: + - ICS20 + parameters: + - in: query + name: async + description: if true, broadcast transaction asynchronously + required: false + type: boolean + - description: stdTx + name: sendTxBody + in: body + required: true + schema: + type: object + properties: + memo: + type: string + fee: + type: object + properties: + gas: + type: string + example: "10000" + amount: + type: array + items: + $ref: "#/definitions/Coin" + msgs: + type: array + items: + $ref: "#/definitions/Msg" + signatures: + type: array + items: + type: object + properties: + pub_key: + type: string + signature: + type: string + account_number: + type: string + example: "0" + sequence: + type: string + example: "0" + responses: + 200: + description: OK + schema: + type: string + 400: + description: Bad Request + 404: + description: Not Found + 500: + description: Internal Server Error + /bank/coin/{coin-type}: + get: + tags: + - ICS20 + summary: Get coin type + description: Get the detailed information about the given coin type + consumes: + - application/json + produces: + - application/json + parameters: + - name: coin-type + in: path + required: true + type: string + responses: + 200: + description: OK + schema: + type: object + properties: + name: + type: string + desc: + type: string + min_unit: + type: object + properties: + denom: + type: string + decimal: + type: integer + Units: + type: array + items: + type: object + properties: + denom: + type: string + decimal: + type: integer + origin: + type: integer + 400: + description: Bad Request + 404: + description: Not Found + 500: + description: Internal Server Error + /bank/balances/{address}: + get: + summary: Get the account information on blockchain + tags: + - ICS20 + produces: + - application/json + parameters: + - in: path + name: address + description: Account address + required: true + type: string + responses: + 200: + description: Account information on the blockchain + schema: + type: array + items: + $ref: "#/definitions/Coin" + 204: + description: No content about this account address + 500: + description: Server internel error + /bank/accounts/{address}/transfers: + post: + summary: Send coins (build -> sign -> send) + description: Send coins (build -> sign -> send) + tags: + - ICS20 + consumes: + - application/json + produces: + - application/json + parameters: + - in: query + name: async + description: if true, broadcast transaction asynchronously + required: false + type: boolean + - in: query + name: simulate + description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it + required: false + type: boolean + - in: query + name: generate-only + description: if true, build an unsigned transaction and write it back + required: false + type: boolean + - in: path + name: address + description: Account address in bech32 format + required: true + type: string + - in: body + name: account + description: The password of the account to remove from the KMS + required: true + schema: + type: object + properties: + base_tx: + $ref: "#/definitions/BaseTx" + sender: + $ref: "#/definitions/Address" + amount: + type: string + example: "1iris" + responses: + 202: + description: Tx was send and will probably be added to the next block + schema: + $ref: "#/definitions/BroadcastTxCommitResult" + 400: + description: Invalid request + 401: + description: Key password is wrong + 500: + description: Server internal error + + /keys: + get: + summary: List of accounts stored locally + tags: + - ICS1 + produces: + - application/json + responses: + 200: + description: Array of accounts + schema: + type: array + items: + $ref: '#/definitions/KeyOutput' + 500: + description: Server internal error + post: + summary: Create a new account locally + tags: + - ICS1 + consumes: + - application/json + produces: + - application/json + parameters: + - in: body + name: account + description: The account to create + schema: + type: object + required: + - name + - password + - seed + properties: + name: + type: string + password: + type: string + seed: + type: string + responses: + 200: + description: Returns account information of the created key + schema: + $ref: "#/definitions/KeyOutput" + 400: + description: Invalid request + 409: + description: Key name confliction + 500: + description: Server internal error + /keys/seed: + get: + summary: Create a new seed to create a new account with + tags: + - ICS1 + produces: + - application/json + responses: + 200: + description: 24 word Seed + schema: + type: object + properties: + seed: + type: string + example: blossom pool issue kidney elevator blame furnace winter account merry vessel security depend exact travel bargain problem jelly rural net again mask roast chest + /keys/{name}/recover: + post: + summary: Recover a account from a seed + tags: + - ICS1 + consumes: + - application/json + produces: + - application/json + parameters: + - in: path + name: name + description: Account name + required: true + type: string + - in: body + name: pwdAndSeed + description: Provide password and seed to recover a key + schema: + type: object + required: + - password + - seed + properties: + password: + type: string + seed: + type: string + responses: + 200: + description: Returns account information of the recovered key + schema: + $ref: "#/definitions/KeyOutput" + 400: + description: Invalid request + 409: + description: Key name confliction + 500: + description: Server internal error + /keys/{name}: + parameters: + - in: path + name: name + description: Account name + required: true + type: string + get: + summary: Get a certain locally stored account + tags: + - ICS1 + produces: + - application/json + responses: + 200: + description: Locally stored account + schema: + $ref: "#/definitions/KeyOutput" + 404: + description: Key doesn't exist + put: + summary: Update the password for this account in the KMS + tags: + - ICS1 + consumes: + - application/json + parameters: + - in: body + name: account + description: The new and old password + schema: + type: object + required: + - new_password + - old_password + properties: + new_password: + type: string + old_password: + type: string + responses: + 200: + description: Updated password + 401: + description: Key password is wrong + 404: + description: Key doesn't exist + delete: + summary: Remove an account + tags: + - ICS1 + consumes: + - application/json + parameters: + - in: body + name: account + description: The password of the account to remove from the KMS + schema: + type: object + required: + - password + properties: + password: + type: string + responses: + 200: + description: Removed account + 401: + description: Key password is wrong + 404: + description: Key doesn't exist + /auth/accounts/{address}: + get: + summary: Get the account information on blockchain + tags: + - ICS1 + produces: + - application/json + parameters: + - in: path + name: address + description: Account address + required: true + type: string + responses: + 200: + description: Account information on the blockchain + schema: + type: object + properties: + type: + type: string + value: + type: object + properties: + account_number: + type: string + address: + type: string + coins: + type: array + items: + $ref: "#/definitions/Coin" + public_key: + type: string + sequence: + type: string + 204: + description: No content about this account address + 500: + description: Server internel error + + /stake/delegators/{delegatorAddr}/delegate: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + post: + summary: Submit delegation + parameters: + - in: query + name: async + description: if true, broadcast transaction asynchronously + required: false + type: boolean + - in: query + name: simulate + description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it + required: false + type: boolean + - in: query + name: generate-only + description: if true, build an unsigned transaction and write it back + required: false + type: boolean + - in: body + name: delegate + description: The password of the account to remove from the KMS + schema: + type: object + properties: + base_tx: + "$ref": "#/definitions/BaseTx" + delegate: + type: object + properties: + validator_addr: + $ref: "#/definitions/ValidatorAddress" + delegation: + type: string + example: 10iris + tags: + - ICS21 + consumes: + - application/json + produces: + - application/json + responses: + 200: + description: OK + schema: + $ref: "#/definitions/BroadcastTxCommitResult" + 400: + description: Invalid delegator address or delegation body + 401: + description: Key password is wrong + 500: + description: Internal Server Error + + /stake/delegators/{delegatorAddr}/redelegate: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + post: + summary: Submit redelegation + parameters: + - in: query + name: async + description: if true, broadcast transaction asynchronously + required: false + type: boolean + - in: query + name: simulate + description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it + required: false + type: boolean + - in: query + name: generate-only + description: if true, build an unsigned transaction and write it back + required: false + type: boolean + - in: body + name: redelegate + description: The password of the account to remove from the KMS + schema: + type: object + properties: + base_tx: + "$ref": "#/definitions/BaseTx" + redelegate: + type: object + properties: + validator_src_addr: + $ref: "#/definitions/ValidatorAddress" + validator_dst_addr: + $ref: "#/definitions/ValidatorAddress" + shares: + type: string + example: "100" + tags: + - ICS21 + consumes: + - application/json + produces: + - application/json + responses: + 200: + description: OK + schema: + $ref: "#/definitions/BroadcastTxCommitResult" + 400: + description: Invalid delegator address or delegation body + 401: + description: Key password is wrong + 500: + description: Internal Server Error + + /stake/delegators/{delegatorAddr}/unbond: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + post: + summary: Submit unbonding + parameters: + - in: query + name: async + description: if true, broadcast transaction asynchronously + required: false + type: boolean + - in: query + name: simulate + description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it + required: false + type: boolean + - in: query + name: generate-only + description: if true, build an unsigned transaction and write it back + required: false + type: boolean + - in: body + name: delegation + description: The password of the account to remove from the KMS + schema: + type: object + properties: + base_tx: + "$ref": "#/definitions/BaseTx" + unbond: + type: object + properties: + validator_addr: + $ref: "#/definitions/ValidatorAddress" + shares: + type: string + example: "100" + tags: + - ICS21 + consumes: + - application/json + produces: + - application/json + responses: + 200: + description: OK + schema: + $ref: "#/definitions/BroadcastTxCommitResult" + 400: + description: Invalid delegator address or delegation body + 401: + description: Key password is wrong + 500: + description: Internal Server Error + + /stake/delegators/{delegatorAddr}/delegations: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + get: + summary: Get all delegations from a delegator + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + type: array + items: + type: object + "$ref": "#/definitions/Delegation" + 400: + description: Invalid delegator address + 500: + description: Internal Server Error + + /stake/delegators/{delegatorAddr}/unbonding_delegations: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + get: + summary: Get all unbonding delegations from a delegator + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + type: array + items: + type: object + "$ref": "#/definitions/UnbondingDelegation" + 400: + description: Invalid delegator address + 500: + description: Internal Server Error + /stake/delegators/{delegatorAddr}/redelegations: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + get: + summary: Get all redelegations from a delegator + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + type: array + items: + type: object + "$ref": "#/definitions/Redelegation" + 400: + description: Invalid delegator address + 500: + description: Internal Server Error + /stake/delegators/{delegatorAddr}/validators: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + get: + summary: Query all validators that a delegator is bonded to + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + type: array + items: + $ref: "#/definitions/Validator" + 400: + description: Invalid delegator address + 500: + description: Internal Server Error + /stake/delegators/{delegatorAddr}/validators/{validatorAddr}: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + - in: path + name: validatorAddr + description: Bech32 ValAddress of Delegator + required: true + type: string + get: + summary: Query a validator that a delegator is bonded to + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + $ref: "#/definitions/Validator" + 400: + description: Invalid delegator address or validator address + 500: + description: Internal Server Error + /stake/delegators/{delegatorAddr}/txs: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + get: + summary: Get all staking txs (i.e msgs) from a delegator + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + type: array + items: + $ref: "#/definitions/TxQuery" + 204: + description: No staking transaction about this delegator address + 400: + description: Invalid delegator address + 500: + description: Internal Server Error + /stake/delegators/{delegatorAddr}/delegations/{validatorAddr}: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + - in: path + name: validatorAddr + description: Bech32 OperatorAddress of validator + required: true + type: string + get: + summary: Query the current delegation between a delegator and a validator + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + $ref: "#/definitions/Delegation" + 400: + description: Invalid delegator address or validator address + 500: + description: Internal Server Error + /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + - in: path + name: validatorAddr + description: Bech32 OperatorAddress of validator + required: true + type: string + get: + summary: Query all unbonding delegations between a delegator and a validator + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + type: array + items: + type: object + "$ref": "#/definitions/UnbondingDelegation" + 400: + description: Invalid delegator address or validator address + 500: + description: Internal Server Error + /stake/validators: + get: + summary: Get all validator candidates + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + type: array + items: + $ref: "#/definitions/Validator" + 500: + description: Internal Server Error + /stake/validators/{validatorAddr}: + parameters: + - in: path + name: validatorAddr + description: Bech32 OperatorAddress of validator + required: true + type: string + get: + summary: Query the information from a single validator + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + $ref: "#/definitions/Validator" + 400: + description: Invalid validator address + 500: + description: Internal Server Error + /stake/validators/{validatorAddr}/unbonding_delegations: + parameters: + - in: path + name: validatorAddr + description: Bech32 OperatorAddress of validator + required: true + type: string + get: + summary: Get all unbonding delegations from a validator + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + type: array + items: + $ref: "#/definitions/UnbondingDelegation" + 400: + description: Invalid validator address + 500: + description: Internal Server Error + /stake/validators/{validatorAddr}/redelegations: + parameters: + - in: path + name: validatorAddr + description: Bech32 OperatorAddress of validator + required: true + type: string + get: + summary: Get all outgoing redelegations from a validator + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + type: array + items: + $ref: "#/definitions/Redelegation" + 400: + description: Invalid validator address + 500: + description: Internal Server Error + /stake/pool: + get: + summary: Get the current state of the staking pool + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + type: object + properties: + loose_tokens: + type: string + bonded_tokens: + type: string + total_supply: + type: string + bonded_ratio: + type: string + 500: + description: Internal Server Error + /stake/parameters: + get: + summary: Get the current staking parameter values + tags: + - ICS21 + produces: + - application/json + responses: + 200: + description: OK + schema: + type: object + properties: + unbonding_time: + type: string + max_validators: + type: integer + bond_denom: + type: string + 500: + description: Internal Server Error + + /slashing/validators/{validatorPubKey}/signing_info: + get: + summary: Get sign info of given validator + description: Get sign info of given validator + produces: + - application/json + tags: + - ICS23 + parameters: + - type: string + description: Bech32 validator public key + name: validatorPubKey + required: true + in: path + responses: + 200: + description: OK + schema: + type: object + properties: + start_height: + type: string + index_offset: + type: string + jailed_until: + type: string + missed_blocks_counter: + type: string + 204: + description: No sign info of this validator + 400: + description: Invalid validator public key + 500: + description: Internal Server Error + /slashing/validators/{validatorAddr}/unjail: + post: + summary: Unjail a jailed validator + description: Send transaction to unjail a jailed validator + consumes: + - application/json + produces: + - application/json + tags: + - ICS23 + parameters: + - in: query + name: async + description: if true, broadcast transaction asynchronously + required: false + type: boolean + - in: query + name: simulate + description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it + required: false + type: boolean + - in: query + name: generate-only + description: if true, build an unsigned transaction and write it back + required: false + type: boolean + - type: string + description: Bech32 validator operator address + name: validatorAddr + required: true + in: path + - description: '' + name: UnjailBody + in: body + required: true + schema: + type: object + properties: + base_tx: + "$ref": "#/definitions/BaseTx" + responses: + 200: + description: OK + schema: + $ref: "#/definitions/BroadcastTxCommitResult" + 400: + description: Invalid validator address or base_tx + 401: + description: Key password is wrong + 500: + description: Internal Server Error + + /gov/proposals: + post: + summary: Submit a proposal + description: Send transaction to submit a proposal + consumes: + - application/json + produces: + - application/json + tags: + - ICS22 + parameters: + - in: query + name: async + description: if true, broadcast transaction asynchronously + required: false + type: boolean + - in: query + name: simulate + description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it + required: false + type: boolean + - in: query + name: generate-only + description: if true, build an unsigned transaction and write it back + required: false + type: boolean + - description: valid value of `"proposal_type"` can be `"Text"`, `"ParameterChange"`, `"SoftwareUpgrade"` + name: post_proposal_body + in: body + required: true + schema: + type: object + properties: + base_tx: + "$ref": "#/definitions/BaseTx" + title: + type: string + description: + type: string + proposal_type: + type: string + example: "Text" + proposer: + "$ref": "#/definitions/Address" + initial_deposit: + type: string + example: "10iris" + responses: + 200: + description: OK + schema: + "$ref": "#/definitions/BroadcastTxCommitResult" + 400: + description: Invalid proposal body + 401: + description: Key password is wrong + 500: + description: Internal Server Error + get: + summary: Query proposals + description: Query proposals information with parameters + produces: + - application/json + tags: + - ICS22 + parameters: + - in: query + name: voter + description: voter address + required: false + type: string + - in: query + name: depositor + description: depositor address + required: false + type: string + - in: query + name: status + description: proposal status, valid values can be `"DepositPeriod"`, `"VotingPeriod"`, `"Passed"`, `"Rejected"` + required: false + type: string + - in: query + name: limit + description: limit to latest [number] proposals. Defaults to all proposals + required: false + type: string + responses: + 200: + description: OK + schema: + type: array + items: + "$ref": "#/definitions/TextProposal" + 400: + description: Invalid query parameters + 500: + description: Internal Server Error + /gov/proposals/{proposalId}/deposits: + post: + summary: Deposit tokens to a proposal + description: Send transaction to deposit tokens to a proposal + consumes: + - application/json + produces: + - application/json + tags: + - ICS22 + parameters: + - in: query + name: async + description: if true, broadcast transaction asynchronously + required: false + type: boolean + - in: query + name: simulate + description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it + required: false + type: boolean + - in: query + name: generate-only + description: if true, build an unsigned transaction and write it back + required: false + type: boolean + - type: string + description: proposal id + name: proposalId + required: true + in: path + - description: '' + name: post_deposit_body + in: body + required: true + schema: + type: object + properties: + base_tx: + "$ref": "#/definitions/BaseTx" + depositor: + "$ref": "#/definitions/Address" + amount: + type: string + example: 10iris + responses: + 200: + description: OK + schema: + "$ref": "#/definitions/BroadcastTxCommitResult" + 400: + description: Invalid proposal id or deposit body + 401: + description: Key password is wrong + 500: + description: Internal Server Error + get: + summary: Query deposits + description: Query deposits by proposalId + produces: + - application/json + tags: + - ICS22 + parameters: + - type: string + name: proposalId + required: true + in: path + responses: + 200: + description: OK + schema: + type: array + items: + "$ref": "#/definitions/Deposit" + 400: + description: Invalid proposal id + 500: + description: Internal Server Error + /gov/proposals/{proposalId}/votes: + post: + summary: Vote a proposal + description: Send transaction to vote a proposal + consumes: + - application/json + produces: + - application/json + tags: + - ICS22 + parameters: + - in: query + name: async + description: if true, broadcast transaction asynchronously + required: false + type: boolean + - in: query + name: simulate + description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it + required: false + type: boolean + - in: query + name: generate-only + description: if true, build an unsigned transaction and write it back + required: false + type: boolean + - type: string + description: proposal id + name: proposalId + required: true + in: path + - description: valid value of `"option"` field can be `"Yes"`, `"No"`, `"NoWithVeto"` and `"Abstain"` + name: post_vote_body + in: body + required: true + schema: + type: object + properties: + base_tx: + "$ref": "#/definitions/BaseTx" + voter: + "$ref": "#/definitions/Address" + option: + type: string + example: "Yes" + responses: + 200: + description: OK + schema: + "$ref": "#/definitions/BroadcastTxCommitResult" + 400: + description: Invalid proposal id or vote body + 401: + description: Key password is wrong + 500: + description: Internal Server Error + get: + summary: Query voters + description: Query voters information by proposalId + produces: + - application/json + tags: + - ICS22 + parameters: + - type: string + description: proposal id + name: proposalId + required: true + in: path + responses: + 200: + description: OK + schema: + type: array + items: + "$ref": "#/definitions/Vote" + 400: + description: Invalid proposal id + 500: + description: Internal Server Error + /gov/proposals/{proposalId}: + get: + summary: Query a proposal + description: Query a proposal by id + produces: + - application/json + tags: + - ICS22 + parameters: + - type: string + name: proposalId + required: true + in: path + responses: + 200: + description: OK + schema: + "$ref": "#/definitions/TextProposal" + 400: + description: Invalid proposal id + 500: + description: Internal Server Error + /gov/proposals/{proposalId}/deposits/{depositor}: + get: + summary: Query deposit + description: Query deposit by proposalId and depositor address + produces: + - application/json + tags: + - ICS22 + parameters: + - type: string + description: proposal id + name: proposalId + required: true + in: path + - type: string + description: Bech32 depositor address + name: depositor + required: true + in: path + responses: + 200: + description: OK + schema: + $ref: "#/definitions/Deposit" + 400: + description: Invalid proposal id or depositor address + 404: + description: Found no deposit + 500: + description: Internal Server Error + /gov/proposals/{proposalId}/votes/{voter}: + get: + summary: Query vote + description: Query vote information by proposalId and voter address + produces: + - application/json + tags: + - ICS22 + parameters: + - type: string + description: proposal id + name: proposalId + required: true + in: path + - type: string + description: Bech32 voter address + name: voter + required: true + in: path + responses: + 200: + description: OK + schema: + $ref: "#/definitions/Vote" + 400: + description: Invalid proposal id or voter address + 404: + description: Found no vote + 500: + description: Internal Server Error + /gov/params: + get: + summary: Query governance parameters + description: Query governance parameters + produces: + - application/json + tags: + - ICS22 + responses: + 200: + description: OK + #TODO add response schema + 500: + description: Internal Server Error + + /distribution/{delegatorAddr}/withdrawAddress: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + post: + summary: Set withdraw address + tags: + - ICS24 + consumes: + - application/json + produces: + - application/json + parameters: + - in: query + name: async + description: if true, broadcast transaction asynchronously + required: false + type: boolean + - in: query + name: simulate + description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it + required: false + type: boolean + - in: query + name: generate-only + description: if true, build an unsigned transaction and write it back + required: false + type: boolean + - name: withdraw_address_body + in: body + required: true + schema: + type: object + properties: + base_tx: + "$ref": "#/definitions/BaseTx" + withdraw_address: + "$ref": "#/definitions/Address" + responses: + 200: + description: OK + schema: + "$ref": "#/definitions/BroadcastTxCommitResult" + 400: + description: Invalid proposal body + 401: + description: Key password is wrong + 500: + description: Internal Server Error + get: + summary: Query withdraw address + tags: + - ICS24 + responses: + 200: + description: OK + schema: + type: string + example: faa1ezzh0humhy3329xg4avhcjtay985nll0zswc5j + 400: + description: Invalid delegator address + 204: + description: No other address have been specified as withdraw address, delegator address will be used. + 500: + description: Internal Server Error + /distribution/{delegatorAddr}/withdrawReward: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + post: + summary: Withdraw rewards + tags: + - ICS24 + consumes: + - application/json + produces: + - application/json + parameters: + - in: query + name: async + description: if true, broadcast transaction asynchronously + required: false + type: boolean + - in: query + name: simulate + description: if true, ignore the gas field and perform a simulation of a transaction, but don't broadcast it + required: false + type: boolean + - in: query + name: generate-only + description: if true, build an unsigned transaction and write it back + required: false + type: boolean + - name: withdraw_reward_body + description: if is_validator is true, validator_address should not be presented + in: body + required: true + schema: + type: object + properties: + base_tx: + "$ref": "#/definitions/BaseTx" + validator_address: + "$ref": "#/definitions/Address" + is_validator: + type: boolean + responses: + 200: + description: OK + schema: + "$ref": "#/definitions/BroadcastTxCommitResult" + 400: + description: Invalid proposal body + 401: + description: Key password is wrong + 500: + description: Internal Server Error + /distribution/{delegatorAddr}/distrInfo/{validatorAddr}: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + - in: path + name: validatorAddr + description: Bech32 OperatorAddress of validator + required: true + type: string + get: + summary: Query distribution information for a delegation + tags: + - ICS24 + responses: + 200: + description: OK + schema: + $ref: "#/definitions/DelegationDistInfo" + 204: + description: No content + 400: + description: Invalid delegator address or validator address + 500: + description: Internal Server Error + /distribution/{delegatorAddr}/distrInfos: + parameters: + - in: path + name: delegatorAddr + description: Bech32 AccAddress of Delegator + required: true + type: string + get: + summary: Query distribution information list for a given delegator + tags: + - ICS24 + responses: + 200: + description: OK + schema: + type: array + items: + $ref: "#/definitions/DelegationDistInfo" + 400: + description: Invalid delegator address + 500: + description: Internal Server Error + /distribution/{validatorAddr}/valDistrInfo: + parameters: + - in: path + name: validatorAddr + description: Bech32 ValAddress of Validator + required: true + type: string + get: + summary: Query withdraw address + tags: + - ICS24 + responses: + 200: + description: OK + schema: + type: object + properties: + operator_addr: + type: string + fee_pool_withdrawal_height: + type: string + example: "0" + del_accum: + type: object + properties: + update_height: + type: string + example: "0" + accum: + type: string + example: "0.0000000000" + del_pool: + type: string + example: "0.1iris" + val_commission: + type: string + example: "0.1iris" + 400: + description: Invalid delegator address + 204: + description: Invalid delegator address + 500: + description: Internal Server Error + +definitions: + CheckTxResult: + type: object + properties: + code: + type: integer + data: + type: string + gas_used: + type: integer + gas_wanted: + type: integer + info: + type: string + log: + type: string + tags: + type: array + items: + "$ref": "#/definitions/KVPair" + example: + code: 0 + data: data + log: log + gas_used: 5000 + gas_wanted: 10000 + info: info + tags: + - '' + - '' + DeliverTxResult: + type: object + properties: + code: + type: integer + data: + type: string + gas_used: + type: integer + gas_wanted: + type: integer + info: + type: string + log: + type: string + tags: + type: array + items: + "$ref": "#/definitions/KVPair" + example: + code: 5 + data: data + log: log + gas_used: 5000 + gas_wanted: 10000 + info: info + tags: + - '' + - '' + BroadcastTxCommitResult: + type: object + properties: + check_tx: + $ref: "#/definitions/CheckTxResult" + deliver_tx: + $ref: "#/definitions/DeliverTxResult" + hash: + $ref: "#/definitions/Hash" + height: + type: integer + KVPair: + type: object + properties: + key: + type: string + value: + type: string + Msg: + type: object + properties: + type: + type: string + example: cosmos-sdk/Send + value: + type: object + properties: + inputs: + type: array + items: + type: object + properties: + address: + type: string + example: faa1ezzh0humhy3329xg4avhcjtay985nll0zswc5j + coins: + type: array + items: + $ref: "#/definitions/Coin" + outputs: + type: array + items: + type: object + properties: + address: + type: string + example: faa18c9j808qgsvvuf7nz5xer973lwsw07ae3j79zv + coins: + type: array + items: + $ref: "#/definitions/Coin" + Address: + type: string + description: bech32 encoded address + example: faa1r93p0tpdlxgpac744rghvj9kqntvd54lc3msk2 + ValidatorAddress: + type: string + description: bech32 encoded address + example: fva178ja5mcj5agnhyphga9f65nlzu59gcl5ktgte2 + Coin: + type: object + properties: + denom: + type: string + example: iris + amount: + type: string + example: "50" + Hash: + type: string + example: EE5F3404034C524501629B56E0DDC38FAD651F04 + TxQuery: + type: object + properties: + hash: + type: string + height: + type: number + tx: + $ref: "#/definitions/StdTx" + result: + type: object + properties: + log: + type: string + gas_wanted: + type: string + example: "0" + gas_used: + type: string + example: "0" + tags: + type: array + items: + $ref: "#/definitions/KVPair" + StdTx: + type: object + properties: + msg: + type: array + items: + $ref: "#/definitions/Msg" + fee: + type: object + properties: + gas: + type: string + example: "10000" + amount: + type: array + items: + $ref: "#/definitions/Coin" + memo: + type: string + signature: + type: object + properties: + signature: + type: string + example: MEUCIQD02fsDPra8MtbRsyB1w7bqTM55Wu138zQbFcWx4+CFyAIge5WNPfKIuvzBZ69MyqHsqD8S1IwiEp+iUb6VSdtlpgY= + pub_key: + type: object + properties: + type: + type: string + example: "tendermint/PubKeySecp256k1" + value: + type: string + example: "Avz04VhtKJh8ACCVzlI8aTosGy0ikFXKIVHQ3jKMrosH" + account_number: + type: string + example: "0" + sequence: + type: string + example: "0" + KeyOutput: + type: object + properties: + name: + type: string + example: Main Account + address: + type: string + example: faa1xp8ptallwun6p0hv5ym4adruupc8q5djc95k30 + pub_key: + type: string + example: "fap1addwnpepqvfp3mzkvpldhd2m6dzmz3q7rzlfww9yr0x0qy9y9vhak26rvtcf6s93txc" + type: + type: string + example: local + seed: + type: string + BlockID: + type: object + properties: + hash: + $ref: "#/definitions/Hash" + parts: + type: object + properties: + total: + type: number + example: 0 + hash: + $ref: "#/definitions/Hash" + BlockHeader: + type: object + properties: + chain_id: + type: string + example: irishub-mainnet + height: + type: number + example: 1 + time: + type: string + example: '2017-12-30T05:53:09.287+01:00' + num_txs: + type: number + example: 0 + last_block_id: + $ref: "#/definitions/BlockID" + total_txs: + type: number + example: 35 + last_commit_hash: + $ref: "#/definitions/Hash" + data_hash: + $ref: "#/definitions/Hash" + validators_hash: + $ref: "#/definitions/Hash" + next_validators_hash: + $ref: "#/definitions/Hash" + consensus_hash: + $ref: "#/definitions/Hash" + app_hash: + $ref: "#/definitions/Hash" + last_results_hash: + $ref: "#/definitions/Hash" + evidence_hash: + $ref: "#/definitions/Hash" + proposer_address: + $ref: "#/definitions/Address" + Block: + type: object + properties: + header: + $ref: "#/definitions/BlockHeader" + txs: + type: array + items: + type: string + evidence: + type: array + items: + type: string + last_commit: + type: object + properties: + block_id: + $ref: "#/definitions/BlockID" + precommits: + type: array + items: + type: object + properties: + validator_address: + type: string + validator_index: + type: string + example: "0" + height: + type: string + example: "0" + round: + type: string + example: "0" + timestamp: + type: string + example: '2017-12-30T05:53:09.287+01:00' + type: + type: number + example: 2 + block_id: + $ref: "#/definitions/BlockID" + signature: + type: string + example: '7uTC74QlknqYWEwg7Vn6M8Om7FuZ0EO4bjvuj6rwH1mTUJrRuMMZvAAqT9VjNgP0RA/TDp6u/92AqrZfXJSpBQ==' + BlockQuery: + type: object + properties: + block_meta: + type: object + properties: + header: + $ref: "#/definitions/BlockHeader" + block_id: + $ref: "#/definitions/BlockID" + block: + $ref: "#/definitions/Block" + BaseTx: + type: object + properties: + name: + type: string + password: + type: string + example: "1234567890" + chain_id: + type: string + account_number: + type: string + example: "0" + sequence: + type: string + example: "0" + gas: + type: string + example: "200000" + fee: + type: string + example: "0.004iris" + gas_adjustment: + type: string + example: "1.2" + TendermintValidator: + type: object + properties: + address: + $ref: '#/definitions/ValidatorAddress' + pub_key: + type: string + example: fvp1zcjduepq6td0utl8pgjh9uud5mvev7z9k90562qpj2gq9sjruenmd4ypp62qgtf6ac + power: + type: string + example: "1000" + accum: + type: string + example: "1000" + TextProposal: + type: object + properties: + proposal_id: + type: integer + title: + type: string + description: + type: string + proposal_type: + type: string + proposal_status: + type: string + tally_result: + type: object + properties: + yes: + type: string + abstain: + type: string + no: + type: string + no_with_veto: + type: string + submit_time: + type: string + total_deposit: + type: array + items: + "$ref": "#/definitions/Coin" + voting_start_time: + type: string + Deposit: + type: object + properties: + amount: + type: string + example: 10iris + proposal_id: + type: integer + depositor: + "$ref": "#/definitions/Address" + Vote: + type: object + properties: + voter: + type: string + proposal_id: + type: integer + option: + type: string + Validator: + type: object + properties: + operator_address: + $ref: '#/definitions/ValidatorAddress' + consensus_pubkey: + type: string + example: fvp1zcjduepq20pzdy56z2k5ccdzz43g8g7vwfw4pzny3mhz6ckc444fj0avamhsazfp09 + jailed: + type: boolean + status: + type: integer + tokens: + type: string + delegator_shares: + type: string + description: + type: object + properties: + moniker: + type: string + identity: + type: string + website: + type: string + details: + type: string + bond_height: + type: string + example: '0' + bond_intra_tx_counter: + type: integer + example: 0 + unbonding_height: + type: string + example: '0' + unbonding_time: + type: string + example: '1970-01-01T00:00:00Z' + commission: + type: object + properties: + rate: + type: string + example: '0' + max_rate: + type: string + example: '0' + max_change_rate: + type: string + example: '0' + update_time: + type: string + example: '1970-01-01T00:00:00Z' + Delegation: + type: object + properties: + delegator_addr: + type: string + validator_addr: + type: string + shares: + type: string + height: + type: integer + UnbondingDelegation: + type: object + properties: + delegator_addr: + type: string + validator_addr: + type: string + initial_balance: + type: string + balance: + type: string + creation_height: + type: integer + min_time: + type: integer + Redelegation: + type: object + properties: + delegator_addr: + type: string + validator_src_addr: + type: string + validator_dst_addr: + type: string + creation_height: + type: integer + min_time: + type: integer + initial_balance: + type: string + balance: + type: string + shares_src: + type: string + shares_dst: + type: string + DelegationDistInfo: + type: object + properties: + delegator_addr: + "$ref": "#/definitions/Address" + val_operator_addr: + "$ref": "#/definitions/Address" + del_pool_withdrawal_height: + type: string + example: "0" \ No newline at end of file diff --git a/client/lcd/test_helpers.go b/client/lcd/test_helpers.go index f1a237629..a16f26e00 100644 --- a/client/lcd/test_helpers.go +++ b/client/lcd/test_helpers.go @@ -12,33 +12,37 @@ import ( "strings" "testing" + "github.com/cosmos/cosmos-sdk/codec" crkeys "github.com/cosmos/cosmos-sdk/crypto/keys" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/tests" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/spf13/viper" "github.com/stretchr/testify/require" + txbuilder "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + "github.com/cosmos/cosmos-sdk/x/stake" + irisapp "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/client" + "github.com/irisnet/irishub/client/keys" + "github.com/irisnet/irishub/modules/gov" + "github.com/irisnet/irishub/modules/upgrade" abci "github.com/tendermint/tendermint/abci/types" tmcfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" + "github.com/tendermint/tendermint/crypto/secp256k1" "github.com/tendermint/tendermint/libs/cli" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" nm "github.com/tendermint/tendermint/node" + "github.com/tendermint/tendermint/p2p" pvm "github.com/tendermint/tendermint/privval" "github.com/tendermint/tendermint/proxy" tmrpc "github.com/tendermint/tendermint/rpc/lib/server" tmtypes "github.com/tendermint/tendermint/types" - "github.com/irisnet/irishub/client/keys" - irisapp "github.com/irisnet/irishub/app" - "github.com/irisnet/irishub/client" - "github.com/irisnet/irishub/modules/gov" - "github.com/irisnet/irishub/modules/upgrade" ) // makePathname creates a unique pathname for each test. It will panic if it @@ -125,7 +129,14 @@ func extractPortFromAddress(listenAddress string) string { // their respective sockets where nValidators is the total number of validators // and initAddrs are the accounts to initialize with some steak tokens. It // returns a cleanup function, a set of validator public keys, and a port. -func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress) (func(), []crypto.PubKey, string) { +func InitializeTestLCD( + t *testing.T, nValidators int, initAddrs []sdk.AccAddress, +) (cleanup func(), valConsPubKeys []crypto.PubKey, valOperAddrs []sdk.ValAddress, port string) { + + if nValidators < 1 { + panic("InitializeTestLCD must use at least one validator") + } + config := GetConfig() config.Consensus.TimeoutCommit = 100 config.Consensus.SkipTimeoutCommit = false @@ -144,56 +155,58 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress genesisFile := config.GenesisFile() genDoc, err := tmtypes.GenesisDocFromFile(genesisFile) - require.NoError(t, err) - - if nValidators < 1 { - panic("InitializeTestLCD must use at least one validator") - } - - for i := 1; i < nValidators; i++ { - genDoc.Validators = append(genDoc.Validators, - tmtypes.GenesisValidator{ - PubKey: ed25519.GenPrivKey().PubKey(), - Power: 1, - Name: "val", - }, + require.Nil(t, err) + genDoc.Validators = nil + genDoc.SaveAs(genesisFile) + genTxs := []json.RawMessage{} + + // append any additional (non-proposing) validators + for i := 0; i < nValidators; i++ { + operPrivKey := secp256k1.GenPrivKey() + operAddr := operPrivKey.PubKey().Address() + pubKey := privVal.PubKey + delegation := 20 + if i > 0 { + pubKey = ed25519.GenPrivKey().PubKey() + delegation = 18 + } + msg := stake.NewMsgCreateValidator( + sdk.ValAddress(operAddr), + pubKey, + sdk.NewCoin("iris-atto", sdk.NewIntWithDecimal(1, delegation)), + stake.Description{Moniker: fmt.Sprintf("validator-%d", i+1)}, + stake.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), ) + stdSignMsg := txbuilder.StdSignMsg{ + ChainID: genDoc.ChainID, + Msgs: []sdk.Msg{msg}, + } + sig, err := operPrivKey.Sign(stdSignMsg.Bytes()) + require.Nil(t, err) + tx := auth.NewStdTx([]sdk.Msg{msg}, auth.StdFee{}, []auth.StdSignature{{Signature: sig, PubKey: operPrivKey.PubKey()}}, "") + txBytes, err := cdc.MarshalJSON(tx) + require.Nil(t, err) + genTxs = append(genTxs, txBytes) + valConsPubKeys = append(valConsPubKeys, pubKey) + valOperAddrs = append(valOperAddrs, sdk.ValAddress(operAddr)) } - var validatorsPKs []crypto.PubKey - - // NOTE: It's bad practice to reuse public key address for the owner - // address but doing in the test for simplicity. - var appGenTxs []json.RawMessage - for _, gdValidator := range genDoc.Validators { - pk := gdValidator.PubKey - validatorsPKs = append(validatorsPKs, pk) - - appGenTx, _, _, err := irisapp.IrisAppGenTxNF(cdc, pk, sdk.AccAddress(pk.Address()), "test_val1") - require.NoError(t, err) - - appGenTxs = append(appGenTxs, appGenTx) - } - - genesisState, err := irisapp.IrisAppGenState(cdc, appGenTxs[:]) + genesisState, err := irisapp.IrisAppGenState(cdc, *genDoc, genTxs) require.NoError(t, err) - genesisState.GovData = gov.DefaultGenesisStateForLCDTest() - genesisState.UpgradeData = upgrade.DefaultGenesisStateForTest() - // add some tokens to init accounts for _, addr := range initAddrs { accAuth := auth.NewBaseAccountWithAddress(addr) - accAuth.Coins = sdk.Coins{sdk.Coin{ - Denom: irisapp.Denom + "-" + "atto", - Amount: sdk.NewInt(100).Mul(sdk.NewIntWithDecimal(1,18)), - }} + accAuth.Coins = sdk.Coins{sdk.NewCoin("iris-atto", sdk.NewIntWithDecimal(1, 20))} acc := irisapp.NewGenesisAccount(&accAuth) genesisState.Accounts = append(genesisState.Accounts, acc) - genesisState.StakeData.Pool.LooseTokens = genesisState.StakeData.Pool.LooseTokens.Add(sdk.NewRatFromInt(sdk.NewIntWithDecimal(1,18))) + genesisState.StakeData.Pool.LooseTokens = genesisState.StakeData.Pool.LooseTokens.Add(sdk.NewDecFromInt(sdk.NewIntWithDecimal(1, 20))) } - appState, err := wire.MarshalJSONIndent(cdc, genesisState) + genesisState.GovData = gov.DefaultGenesisStateForLCDTest() + genesisState.UpgradeData = upgrade.DefaultGenesisStateForTest() + + appState, err := codec.MarshalJSONIndent(cdc, genesisState) require.NoError(t, err) genDoc.AppState = appState @@ -203,26 +216,30 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress // XXX: Need to set this so LCD knows the tendermint node address! viper.Set(client.FlagNode, config.RPC.ListenAddress) viper.Set(client.FlagChainID, genDoc.ChainID) + // TODO Set to false once the upstream Tendermint proof verification issue is fixed. viper.Set(client.FlagTrustNode, true) + dir, err := ioutil.TempDir("", "lcd_test") + require.NoError(t, err) + viper.Set(cli.HomeFlag, dir) node, err := startTM(config, logger, genDoc, privVal, app) require.NoError(t, err) - tests.WaitForNextHeightTM(extractPortFromAddress(config.RPC.ListenAddress)) + tests.WaitForNextHeightTM(tests.ExtractPortFromAddress(config.RPC.ListenAddress)) lcd, err := startLCD(logger, listenAddr, cdc) require.NoError(t, err) tests.WaitForLCDStart(port) tests.WaitForHeight(1, port) - cleanup := func() { + cleanup = func() { logger.Debug("cleaning up LCD initialization") node.Stop() node.Wait() lcd.Close() } - return cleanup, validatorsPKs, port + return cleanup, valConsPubKeys, valOperAddrs, port } // startTM creates and starts an in-process Tendermint node with memDB and @@ -236,9 +253,14 @@ func startTM( ) (*nm.Node, error) { genDocProvider := func() (*tmtypes.GenesisDoc, error) { return genDoc, nil } dbProvider := func(*nm.DBContext) (dbm.DB, error) { return dbm.NewMemDB(), nil } + nodeKey, err := p2p.LoadOrGenNodeKey(tmcfg.NodeKeyFile()) + if err != nil { + return nil, err + } node, err := nm.NewNode( tmcfg, privVal, + nodeKey, proxy.NewLocalClientCreator(app), genDocProvider, dbProvider, @@ -263,7 +285,7 @@ func startTM( // startLCD starts the LCD. // // NOTE: This causes the thread to block. -func startLCD(logger log.Logger, listenAddr string, cdc *wire.Codec) (net.Listener, error) { +func startLCD(logger log.Logger, listenAddr string, cdc *codec.Codec) (net.Listener, error) { return tmrpc.StartHTTPServer(listenAddr, createHandler(cdc), logger, tmrpc.Config{}) } diff --git a/client/lcd/version.go b/client/lcd/version.go index e0840eb30..5ff5d644c 100644 --- a/client/lcd/version.go +++ b/client/lcd/version.go @@ -16,7 +16,7 @@ func CLIVersionRequestHandler(w http.ResponseWriter, r *http.Request) { // connected node version REST handler endpoint func NodeVersionRequestHandler(cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - version, err := cliCtx.Query("/app/version") + version, err := cliCtx.Query("/app/version",nil) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Could't query version. Error: %s", err.Error()))) diff --git a/client/lcd/wire.go b/client/lcd/wire.go index f146e102e..7210660e7 100644 --- a/client/lcd/wire.go +++ b/client/lcd/wire.go @@ -1,11 +1,11 @@ package lcd import ( - amino "github.com/tendermint/go-amino" ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/cosmos/cosmos-sdk/codec" ) -var cdc = amino.NewCodec() +var cdc = codec.New() func init() { ctypes.RegisterAmino(cdc) diff --git a/client/record/cli/download.go b/client/record/cli/download.go index ccdd9731b..0a3bed5b0 100644 --- a/client/record/cli/download.go +++ b/client/record/cli/download.go @@ -5,7 +5,7 @@ import ( "os" "path/filepath" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/modules/record" "github.com/spf13/cobra" @@ -15,7 +15,7 @@ import ( shell "github.com/ipfs/go-ipfs-api" ) -func GetCmdDownload(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdDownload(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "download [record ID]", Short: "download related data with unique record ID to specified file", @@ -34,7 +34,7 @@ func GetCmdDownload(storeName string, cdc *wire.Codec) *cobra.Command { } var submitFile record.MsgSubmitRecord - cdc.MustUnmarshalBinary(res, &submitFile) + cdc.MustUnmarshalBinaryLengthPrefixed(res, &submitFile) filePath := filepath.Join(home, downloadFileName) if _, err := os.Stat(filePath); !os.IsNotExist(err) { diff --git a/client/record/cli/query.go b/client/record/cli/query.go index 6ed74cce3..26b45a83b 100644 --- a/client/record/cli/query.go +++ b/client/record/cli/query.go @@ -3,7 +3,7 @@ package cli import ( "fmt" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/modules/record" "github.com/spf13/cobra" @@ -21,7 +21,7 @@ type RecordMetadata struct { //PinedNode string } -func GetCmdQureyRecord(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQureyRecord(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "query", Short: "query specified record", @@ -37,14 +37,14 @@ func GetCmdQureyRecord(storeName string, cdc *wire.Codec) *cobra.Command { } var submitRecord record.MsgSubmitRecord - cdc.MustUnmarshalBinary(res, &submitRecord) + cdc.MustUnmarshalBinaryLengthPrefixed(res, &submitRecord) recordResponse, err := recordClient.ConvertRecordToRecordOutput(cliCtx, submitRecord) if err != nil { return err } - output, err := wire.MarshalJSONIndent(cdc, recordResponse) + output, err := codec.MarshalJSONIndent(cdc, recordResponse) if err != nil { return err } diff --git a/client/record/cli/sendtx.go b/client/record/cli/sendtx.go index c4dc59c35..242cb4593 100644 --- a/client/record/cli/sendtx.go +++ b/client/record/cli/sendtx.go @@ -9,7 +9,7 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/utils" @@ -19,7 +19,7 @@ import ( ) // GetCmdSubmitFile implements submitting upload file transaction command. -func GetCmdSubmitRecord(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdSubmitRecord(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "submit", Short: "Submit a new record", @@ -28,10 +28,15 @@ func GetCmdSubmitRecord(storeName string, cdc *wire.Codec) *cobra.Command { description := viper.GetString(flagDescription) onchainData := viper.GetString(flagOnchainData) - cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout). + cliCtx := context.NewCLIContext(). + WithCodec(cdc). + WithLogger(os.Stdout). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - txCtx := context.NewTxContextFromCLI().WithCodec(cdc). - WithCliCtx(cliCtx) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc).WithCliCtx(cliCtx) + + if err := cliCtx.EnsureAccountExists(); err != nil { + return err + } fromAddr, err := cliCtx.GetFromAddress() if err != nil { @@ -63,13 +68,6 @@ func GetCmdSubmitRecord(storeName string, cdc *wire.Codec) *cobra.Command { onchainData, ) - if cliCtx.GenerateOnly { - return utils.PrintUnsignedStdTx(txCtx, cliCtx, []sdk.Msg{msg}) - } - - // Build and sign the transaction, then broadcast to Tendermint - cliCtx.PrintResponse = true - return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) }, } diff --git a/client/record/lcd/query.go b/client/record/lcd/query.go index 865bb5e0e..c9aaf3998 100644 --- a/client/record/lcd/query.go +++ b/client/record/lcd/query.go @@ -4,7 +4,7 @@ import ( "fmt" "net/http" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/gorilla/mux" "github.com/irisnet/irishub/client/context" recordClient "github.com/irisnet/irishub/client/record" @@ -13,7 +13,7 @@ import ( ) // nolint: gocyclo -func queryRecordsWithParameterFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func queryRecordsWithParameterFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { recordID := r.URL.Query().Get(RestRecordID) @@ -34,7 +34,7 @@ func queryRecordsWithParameterFn(cdc *wire.Codec, cliCtx context.CLIContext) htt } var submitFile record.MsgSubmitRecord - cdc.MustUnmarshalBinary(res, &submitFile) + cdc.MustUnmarshalBinaryLengthPrefixed(res, &submitFile) recordResponse, err := recordClient.ConvertRecordToRecordOutput(cliCtx, submitFile) if err != nil { @@ -42,7 +42,7 @@ func queryRecordsWithParameterFn(cdc *wire.Codec, cliCtx context.CLIContext) htt return } - output, err := wire.MarshalJSONIndent(cdc, recordResponse) + output, err := codec.MarshalJSONIndent(cdc, recordResponse) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -52,7 +52,7 @@ func queryRecordsWithParameterFn(cdc *wire.Codec, cliCtx context.CLIContext) htt } } -func queryRecordHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func queryRecordHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) recordID := vars[RestRecordID] @@ -73,7 +73,7 @@ func queryRecordHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.Handl } var submitFile record.MsgSubmitRecord - cdc.MustUnmarshalBinary(res, &submitFile) + cdc.MustUnmarshalBinaryLengthPrefixed(res, &submitFile) recordResponse, err := recordClient.ConvertRecordToRecordOutput(cliCtx, submitFile) if err != nil { @@ -81,7 +81,7 @@ func queryRecordHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.Handl return } - output, err := wire.MarshalJSONIndent(cdc, recordResponse) + output, err := codec.MarshalJSONIndent(cdc, recordResponse) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return diff --git a/client/record/lcd/rest.go b/client/record/lcd/rest.go index ac462992d..240f34b5f 100644 --- a/client/record/lcd/rest.go +++ b/client/record/lcd/rest.go @@ -3,13 +3,13 @@ package lcd import ( "fmt" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/gorilla/mux" "github.com/irisnet/irishub/client/context" ) // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Codec) { +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { r.HandleFunc("/record/records", postRecordHandlerFn(cdc, cliCtx)).Methods("POST") diff --git a/client/record/lcd/sendtx.go b/client/record/lcd/sendtx.go index 6eb24838c..6d9f676ce 100644 --- a/client/record/lcd/sendtx.go +++ b/client/record/lcd/sendtx.go @@ -9,7 +9,7 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/utils" "github.com/irisnet/irishub/modules/record" @@ -22,18 +22,19 @@ type postRecordReq struct { Data string `json:"data"` // for onchain } -func postRecordHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func postRecordHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + // Init context and read request parameters + cliCtx = utils.InitReqCliCtx(cliCtx, r) + var req postRecordReq err := utils.ReadPostBody(w, r, cdc, &req) if err != nil { return } - cliCtx = utils.InitRequestClictx(cliCtx, r, req.BaseTx.LocalAccountName, req.Submitter) - txCtx, err := context.NewTxContextFromBaseTx(cliCtx, cdc, req.BaseTx) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + baseReq := req.BaseTx.Sanitize() + if !baseReq.ValidateBasic(w, cliCtx) { return } @@ -85,6 +86,6 @@ func postRecordHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.Handle return } - utils.SendOrReturnUnsignedTx(w, cliCtx, txCtx, req.BaseTx, []sdk.Msg{msg}) + utils.SendOrReturnUnsignedTx(w, cliCtx, req.BaseTx, []sdk.Msg{msg}) } } diff --git a/client/record/common.go b/client/record/utils.go similarity index 100% rename from client/record/common.go rename to client/record/utils.go diff --git a/client/service/cli/flags.go b/client/service/cli/flags.go new file mode 100644 index 000000000..4381c4069 --- /dev/null +++ b/client/service/cli/flags.go @@ -0,0 +1,60 @@ +package cli + +import ( + flag "github.com/spf13/pflag" +) + +const ( + FlagDefChainID = "def-chain-id" + FlagServiceName = "service-name" + FlagServiceDescription = "service-description" + FlagTags = "tags" + FlagAuthorDescription = "author-description" + FlagIdlContent = "idl-content" + FlagFile = "file" + FlagProvider = "provider" + FlagBindChainID = "bind-chain-id" + FlagBindType = "bind-type" + FlagDeposit = "deposit" + FlagPrices = "prices" + FlagAvgRspTime = "avg-rsp-time" + FlagUsableTime = "usable-time" + FlagExpiration = "expiration" +) + +var ( + FsDefChainID = flag.NewFlagSet("", flag.ContinueOnError) + FsServiceName = flag.NewFlagSet("", flag.ContinueOnError) + FsServiceDescription = flag.NewFlagSet("", flag.ContinueOnError) + FsTags = flag.NewFlagSet("", flag.ContinueOnError) + FsAuthorDescription = flag.NewFlagSet("", flag.ContinueOnError) + FsIdlContent = flag.NewFlagSet("", flag.ContinueOnError) + FsFile = flag.NewFlagSet("", flag.ContinueOnError) + FsProvider = flag.NewFlagSet("", flag.ContinueOnError) + FsBindChainID = flag.NewFlagSet("", flag.ContinueOnError) + FsBindType = flag.NewFlagSet("", flag.ContinueOnError) + FsDeposit = flag.NewFlagSet("", flag.ContinueOnError) + FsPrices = flag.NewFlagSet("", flag.ContinueOnError) + FsAvgRspTime = flag.NewFlagSet("", flag.ContinueOnError) + FsUsableTime = flag.NewFlagSet("", flag.ContinueOnError) + FsExpiration = flag.NewFlagSet("", flag.ContinueOnError) +) + +func init() { + FsDefChainID.String(FlagDefChainID, "", "the ID of the blockchain defined of the service") + FsServiceName.String(FlagServiceName, "", "service name") + FsServiceDescription.String(FlagServiceDescription, "", "service description") + FsTags.StringSlice(FlagTags, []string{}, "service tags") + FsAuthorDescription.String(FlagAuthorDescription, "", "service author description") + FsIdlContent.String(FlagIdlContent, "", "content of service interface description language") + FsFile.String(FlagFile, "", "path of file which contains service interface description language") + + FsProvider.String(FlagProvider, "", "bech32 encoded account created the service binding") + FsBindChainID.String(FlagBindChainID, "", "the ID of the blockchain bond of the service") + FsBindType.String(FlagBindType, "", "type of binding, valid values can be Local and Global") + FsDeposit.String(FlagDeposit, "", "deposit of binding") + FsPrices.StringSlice(FlagPrices, []string{}, "prices of binding, will contains all method") + FsAvgRspTime.Int64(FlagAvgRspTime, 0, "the average service response time in milliseconds") + FsUsableTime.Int64(FlagUsableTime, 0, "an integer represents the number of usable service invocations per 10,000") + FsExpiration.String(FlagExpiration, "", "the blockchain height where this binding expires") +} diff --git a/client/service/cli/query.go b/client/service/cli/query.go new file mode 100644 index 000000000..7694366b9 --- /dev/null +++ b/client/service/cli/query.go @@ -0,0 +1,143 @@ +package cli + +import ( + "os" + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/irisnet/irishub/modules/service" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/irisnet/irishub/client/context" + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + cmn "github.com/irisnet/irishub/client/service" +) + +func GetCmdQueryScvDef(storeName string, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "definition", + Short: "Query service definition", + Example: "iriscli service definition --def-chain-id= --service-name=", + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout). + WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + + name := viper.GetString(FlagServiceName) + defChainId := viper.GetString(FlagDefChainID) + + res, err := cliCtx.QueryStore(service.GetServiceDefinitionKey(defChainId, name), storeName) + if err != nil { + return err + } + if len(res) == 0 { + return fmt.Errorf("chain-id [%s] service [%s] is not existed", defChainId, name) + } + + var svcDef service.SvcDef + cdc.MustUnmarshalBinaryLengthPrefixed(res, &svcDef) + + res2, err := cliCtx.QuerySubspace(service.GetMethodsSubspaceKey(defChainId, name), storeName) + if err != nil { + return err + } + + var methods []service.MethodProperty + for i := 0; i < len(res2); i++ { + var method service.MethodProperty + cdc.MustUnmarshalBinaryLengthPrefixed(res2[i].Value, &method) + methods = append(methods, method) + } + + service := cmn.ServiceOutput{SvcDef: svcDef, Methods: methods} + output, err := codec.MarshalJSONIndent(cdc, service) + if err != nil { + return err + } + + fmt.Println(string(output)) + return nil + }, + } + cmd.Flags().AddFlagSet(FsDefChainID) + cmd.Flags().AddFlagSet(FsServiceName) + + return cmd +} + +func GetCmdQueryScvBind(storeName string, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "binding", + Short: "Query service binding", + Example: "iriscli service binding --def-chain-id= --service-name= --bind-chain-id= --provider=", + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout). + WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + + name := viper.GetString(FlagServiceName) + defChainId := viper.GetString(FlagDefChainID) + bindChainId := viper.GetString(FlagBindChainID) + providerStr := viper.GetString(FlagProvider) + + provider, err := sdk.AccAddressFromBech32(providerStr) + if err != nil { + return err + } + res, err := cliCtx.QueryStore(service.GetServiceBindingKey(defChainId, name, bindChainId, provider), storeName) + if err != nil { + return err + } + if len(res) == 0 { + return fmt.Errorf("def-chain-id [%s] service [%s] bind-chain-id [%s] provider [%s] is not existed", defChainId, name, bindChainId, provider) + } + + var svcBinding service.SvcBinding + cdc.MustUnmarshalBinaryLengthPrefixed(res, &svcBinding) + output, err := codec.MarshalJSONIndent(cdc, svcBinding) + fmt.Println(string(output)) + return nil + }, + } + cmd.Flags().AddFlagSet(FsDefChainID) + cmd.Flags().AddFlagSet(FsServiceName) + cmd.Flags().AddFlagSet(FsBindChainID) + cmd.Flags().AddFlagSet(FsProvider) + + return cmd +} + +func GetCmdQueryScvBinds(storeName string, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "bindings", + Short: "Query service bindings", + Example: "iriscli service bindings --def-chain-id= --service-name=", + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout). + WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + + name := viper.GetString(FlagServiceName) + defChainId := viper.GetString(FlagDefChainID) + + res, err := cliCtx.QuerySubspace(service.GetBindingsSubspaceKey(defChainId, name), storeName) + if err != nil { + return err + } + + var bindings []service.SvcBinding + for i := 0; i < len(res); i++ { + + var binding service.SvcBinding + cdc.MustUnmarshalBinaryLengthPrefixed(res[i].Value, &binding) + bindings = append(bindings, binding) + } + + output, err := cdc.MarshalJSONIndent(bindings, "", "") + fmt.Println(string(output)) + return nil + }, + } + cmd.Flags().AddFlagSet(FsDefChainID) + cmd.Flags().AddFlagSet(FsServiceName) + + return cmd +} diff --git a/client/service/cli/sendtx.go b/client/service/cli/sendtx.go new file mode 100644 index 000000000..9fc65014c --- /dev/null +++ b/client/service/cli/sendtx.go @@ -0,0 +1,311 @@ +package cli + +import ( + "os" + "fmt" + "strings" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/spf13/cobra" + "github.com/irisnet/irishub/client/context" + "github.com/irisnet/irishub/client/utils" + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + "github.com/irisnet/irishub/modules/service" + "github.com/spf13/viper" + "github.com/irisnet/irishub/client" + cmn "github.com/tendermint/tendermint/libs/common" +) + +func GetCmdScvDef(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "define", + Short: "Create a new service definition", + Example: "iriscli service define --chain-id= --from= --fee=0.004iris " + + "--service-name= --service-description= --author-description= " + + "--tags=tag1,tag2 --idl-content= --file=test.proto", + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout). + WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc). + WithCliCtx(cliCtx) + + name := viper.GetString(FlagServiceName) + description := viper.GetString(FlagServiceDescription) + authorDescription := viper.GetString(FlagAuthorDescription) + tags := viper.GetStringSlice(FlagTags) + content := viper.GetString(FlagIdlContent) + if len(content) > 0 { + content = strings.Replace(content, `\n`, "\n", -1) + } + filePath := viper.GetString(FlagFile) + if len(filePath) > 0 { + contentBytes, err := cmn.ReadFile(filePath) + if err != nil { + return err + } + content = string(contentBytes) + } + fmt.Printf("idl condent: \n%s\n", content) + chainId := viper.GetString(client.FlagChainID) + + fromAddr, err := cliCtx.GetFromAddress() + if err != nil { + return err + } + + if err != nil { + return err + } + + msg := service.NewMsgSvcDef(name, chainId, description, tags, fromAddr, authorDescription, content) + cliCtx.PrintResponse = true + return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) + }, + } + cmd.Flags().AddFlagSet(FsServiceName) + cmd.Flags().AddFlagSet(FsServiceDescription) + cmd.Flags().AddFlagSet(FsTags) + cmd.Flags().AddFlagSet(FsAuthorDescription) + cmd.Flags().AddFlagSet(FsIdlContent) + cmd.Flags().AddFlagSet(FsFile) + + return cmd +} + +func GetCmdScvBind(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "bind", + Short: "Create a new service binding", + Example: "iriscli service bind --chain-id= --from= --fee=0.004iris " + + "--service-name= --def-chain-id= --bind-type=Local " + + "--deposit=1iris --prices=1iris,2iris --avg-rsp-time=10000 --usable-time=100", + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout). + WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc). + WithCliCtx(cliCtx) + + fromAddr, err := cliCtx.GetFromAddress() + if err != nil { + return err + } + chainId := viper.GetString(client.FlagChainID) + + name := viper.GetString(FlagServiceName) + defChainId := viper.GetString(FlagDefChainID) + initialDeposit := viper.GetString(FlagDeposit) + initialPrices := viper.GetStringSlice(FlagPrices) + avgRspTime := viper.GetInt64(FlagAvgRspTime) + usableTime := viper.GetInt64(FlagUsableTime) + bindingTypeStr := viper.GetString(FlagBindType) + + bindingType, err := service.BindingTypeFromString(bindingTypeStr) + if err != nil { + return err + } + + deposit, err := cliCtx.ParseCoins(initialDeposit) + if err != nil { + return err + } + + var prices []sdk.Coin + for _, ip := range initialPrices { + price, err := cliCtx.ParseCoin(ip) + if err != nil { + return err + } + prices = append(prices, price) + } + + level := service.Level{AvgRspTime: avgRspTime, UsableTime: usableTime} + msg := service.NewMsgSvcBind(defChainId, name, chainId, fromAddr, bindingType, deposit, prices, level) + cliCtx.PrintResponse = true + return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) + }, + } + cmd.Flags().AddFlagSet(FsServiceName) + cmd.Flags().AddFlagSet(FsDefChainID) + cmd.Flags().AddFlagSet(FsDeposit) + cmd.Flags().AddFlagSet(FsPrices) + cmd.Flags().AddFlagSet(FsBindType) + cmd.Flags().AddFlagSet(FsAvgRspTime) + cmd.Flags().AddFlagSet(FsUsableTime) + + return cmd +} + +func GetCmdScvBindUpdate(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "update-binding", + Short: "Update a service binding", + Example: "iriscli service update-binding --chain-id= --from= --fee=0.004iris " + + "--service-name= --def-chain-id= --bind-type=Local " + + "--deposit=1iris --prices=1iris,2iris --avg-rsp-time=10000 --usable-time=100", + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout). + WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc). + WithCliCtx(cliCtx) + + fromAddr, err := cliCtx.GetFromAddress() + if err != nil { + return err + } + + chainId := viper.GetString(client.FlagChainID) + name := viper.GetString(FlagServiceName) + defChainId := viper.GetString(FlagDefChainID) + initialDeposit := viper.GetString(FlagDeposit) + initialPrices := viper.GetStringSlice(FlagPrices) + avgRspTime := viper.GetInt64(FlagAvgRspTime) + usableTime := viper.GetInt64(FlagUsableTime) + bindingTypeStr := viper.GetString(FlagBindType) + + var bindingType service.BindingType + if bindingTypeStr != "" { + bindingType, err = service.BindingTypeFromString(bindingTypeStr) + if err != nil { + return err + } + } + + var deposit sdk.Coins + if initialDeposit != "" { + deposit, err = cliCtx.ParseCoins(initialDeposit) + if err != nil { + return err + } + } + + var prices []sdk.Coin + for _, ip := range initialPrices { + price, err := cliCtx.ParseCoin(ip) + if err != nil { + return err + } + prices = append(prices, price) + } + + level := service.Level{AvgRspTime: avgRspTime, UsableTime: usableTime} + msg := service.NewMsgSvcBindingUpdate(defChainId, name, chainId, fromAddr, bindingType, deposit, prices, level) + cliCtx.PrintResponse = true + return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) + }, + } + cmd.Flags().AddFlagSet(FsServiceName) + cmd.Flags().AddFlagSet(FsDefChainID) + cmd.Flags().AddFlagSet(FsDeposit) + cmd.Flags().AddFlagSet(FsPrices) + cmd.Flags().AddFlagSet(FsBindType) + cmd.Flags().AddFlagSet(FsAvgRspTime) + cmd.Flags().AddFlagSet(FsUsableTime) + + return cmd +} + +func GetCmdScvDisable(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "disable", + Short: "Disable a available service binding", + Example: "iriscli service disable --chain-id= --from= --fee=0.004iris " + + "--service-name= --def-chain-id=", + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout). + WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc). + WithCliCtx(cliCtx) + + fromAddr, err := cliCtx.GetFromAddress() + if err != nil { + return err + } + + chainId := viper.GetString(client.FlagChainID) + + name := viper.GetString(FlagServiceName) + defChainId := viper.GetString(FlagDefChainID) + + msg := service.NewMsgSvcDisable(defChainId, name, chainId, fromAddr) + cliCtx.PrintResponse = true + return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) + }, + } + cmd.Flags().AddFlagSet(FsServiceName) + cmd.Flags().AddFlagSet(FsDefChainID) + + return cmd +} + +func GetCmdScvEnable(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "enable", + Short: "Enable a unavailable service binding", + Example: "iriscli service enable --chain-id= --from= --fee=0.004iris " + + "--service-name= --def-chain-id= --deposit=1iris", + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout). + WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc). + WithCliCtx(cliCtx) + + fromAddr, err := cliCtx.GetFromAddress() + if err != nil { + return err + } + + chainId := viper.GetString(client.FlagChainID) + + name := viper.GetString(FlagServiceName) + defChainId := viper.GetString(FlagDefChainID) + + initialDeposit := viper.GetString(FlagDeposit) + deposit, err := cliCtx.ParseCoins(initialDeposit) + if err != nil { + return err + } + + msg := service.NewMsgSvcEnable(defChainId, name, chainId, fromAddr, deposit) + cliCtx.PrintResponse = true + return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) + }, + } + cmd.Flags().AddFlagSet(FsServiceName) + cmd.Flags().AddFlagSet(FsDefChainID) + cmd.Flags().AddFlagSet(FsDeposit) + + return cmd +} + +func GetCmdScvRefundDeposit(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "refund-deposit", + Short: "Refund all deposit from a service binding", + Example: "iriscli service refund-deposit --chain-id= --from= --fee=0.004iris " + + "--service-name= --def-chain-id=", + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout). + WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) + txCtx := context.NewTxContextFromCLI().WithCodec(cdc). + WithCliCtx(cliCtx) + + fromAddr, err := cliCtx.GetFromAddress() + if err != nil { + return err + } + + chainId := viper.GetString(client.FlagChainID) + + name := viper.GetString(FlagServiceName) + defChainId := viper.GetString(FlagDefChainID) + + msg := service.NewMsgSvcRefundDeposit(defChainId, name, chainId, fromAddr) + cliCtx.PrintResponse = true + return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) + }, + } + cmd.Flags().AddFlagSet(FsServiceName) + cmd.Flags().AddFlagSet(FsDefChainID) + + return cmd +} diff --git a/client/service/utils.go b/client/service/utils.go new file mode 100644 index 000000000..707bd9a7b --- /dev/null +++ b/client/service/utils.go @@ -0,0 +1,10 @@ +package service + +import ( + "github.com/irisnet/irishub/modules/service" +) + +type ServiceOutput struct { + service.SvcDef + Methods []service.MethodProperty `json:"methods"` +} diff --git a/client/slashing/cli/query.go b/client/slashing/cli/query.go index 00e5d5d70..08a9b804f 100644 --- a/client/slashing/cli/query.go +++ b/client/slashing/cli/query.go @@ -7,38 +7,38 @@ import ( "github.com/spf13/viper" "github.com/tendermint/tendermint/libs/cli" + "github.com/cosmos/cosmos-sdk/codec" // XXX fix sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" // XXX fix "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/irisnet/irishub/client/context" ) // GetCmdQuerySigningInfo implements the command to query signing info. -func GetCmdQuerySigningInfo(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQuerySigningInfo(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "signing-info [validator-pubkey]", - Short: "Query a validator's signing information", + Use: "signing-info [validator-pubkey]", + Short: "Query a validator's signing information", Example: "iriscli stake signing-info ", - Args: cobra.ExactArgs(1), + Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { pk, err := sdk.GetValPubKeyBech32(args[0]) if err != nil { return err } - key := slashing.GetValidatorSigningInfoKey(sdk.ValAddress(pk.Address())) + key := slashing.GetValidatorSigningInfoKey(sdk.ConsAddress(pk.Address())) cliCtx := context.NewCLIContext().WithCodec(cdc) res, err := cliCtx.QueryStore(key, storeName) if err != nil { return err } - if len(res) ==0 { + if len(res) == 0 { return fmt.Errorf("the signing information of this validator %s is empty, please make sure its existence", args[0]) } signingInfo := new(slashing.ValidatorSigningInfo) - cdc.MustUnmarshalBinary(res, signingInfo) + cdc.MustUnmarshalBinaryLengthPrefixed(res, signingInfo) switch viper.Get(cli.OutputFlag) { @@ -48,7 +48,7 @@ func GetCmdQuerySigningInfo(storeName string, cdc *wire.Codec) *cobra.Command { case "json": // parse out the signing info - output, err := wire.MarshalJSONIndent(cdc, signingInfo) + output, err := codec.MarshalJSONIndent(cdc, signingInfo) if err != nil { return err } diff --git a/client/slashing/cli/sendtx.go b/client/slashing/cli/sendtx.go index 93104c26e..f1e938654 100644 --- a/client/slashing/cli/sendtx.go +++ b/client/slashing/cli/sendtx.go @@ -3,23 +3,23 @@ package cli import ( "os" + "github.com/cosmos/cosmos-sdk/codec" 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/cosmos/cosmos-sdk/x/slashing" - "github.com/spf13/cobra" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/utils" + "github.com/spf13/cobra" ) // GetCmdUnrevoke implements the create unrevoke validator command. -func GetCmdUnrevoke(cdc *wire.Codec) *cobra.Command { +func GetCmdUnrevoke(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "unrevoke", - Args: cobra.ExactArgs(0), - Short: "unrevoke validator previously revoked for downtime", - Example: "iriscli stake unrevoke --to= --from --fee=0.004iris --chain-id=", + Use: "unjail", + Args: cobra.ExactArgs(0), + Short: "unjail validator previously jailed for downtime", + Example: "iriscli stake unjail --from --fee=0.004iris --chain-id=", RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext(). WithCodec(cdc). @@ -33,7 +33,7 @@ func GetCmdUnrevoke(cdc *wire.Codec) *cobra.Command { return err } - msg := slashing.NewMsgUnrevoke(validatorAddr) + msg := slashing.NewMsgUnjail(sdk.ValAddress(validatorAddr)) return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) }, diff --git a/client/slashing/lcd/query.go b/client/slashing/lcd/query.go index acf1e0a0f..a079cf2ff 100644 --- a/client/slashing/lcd/query.go +++ b/client/slashing/lcd/query.go @@ -2,8 +2,8 @@ package lcd import ( "fmt" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/gorilla/mux" "github.com/irisnet/irishub/client/context" @@ -12,43 +12,36 @@ import ( ) // http request handler to query signing info -func signingInfoHandlerFn(cliCtx context.CLIContext, storeName string, cdc *wire.Codec) http.HandlerFunc { +func signingInfoHandlerFn(cliCtx context.CLIContext, storeName string, cdc *codec.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - pk, err := sdk.GetValPubKeyBech32(vars["validator_pub"]) + pk, err := sdk.GetValPubKeyBech32(vars["validatorPubKey"]) if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - key := slashing.GetValidatorSigningInfoKey(sdk.ValAddress(pk.Address())) + key := slashing.GetValidatorSigningInfoKey(sdk.ConsAddress(pk.Address())) res, err := cliCtx.QueryStore(key, storeName) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("couldn't query signing info. Error: %s", err.Error())) return } - if len(res) ==0 { - utils.WriteErrorResponse(w, http.StatusBadRequest, - fmt.Sprintf("the signing information of this validator %s is empty, please make sure its existence", vars["validator_pub"])) + if len(res) == 0 { + utils.WriteErrorResponse(w, http.StatusNoContent, "") return } var signingInfo slashing.ValidatorSigningInfo - err = cdc.UnmarshalBinary(res, &signingInfo) + err = cdc.UnmarshalBinaryLengthPrefixed(res, &signingInfo) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("couldn't decode signing info. Error: %s", err.Error())) return } - output, err := cdc.MarshalJSONIndent(signingInfo, "", " ") - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - w.Write(output) + utils.PostProcessResponse(w, cliCtx.Codec, signingInfo, cliCtx.Indent) } } diff --git a/client/slashing/lcd/rest.go b/client/slashing/lcd/rest.go index 84a36b666..49034317f 100644 --- a/client/slashing/lcd/rest.go +++ b/client/slashing/lcd/rest.go @@ -1,15 +1,15 @@ package lcd import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/gorilla/mux" "github.com/irisnet/irishub/client/context" ) // RegisterRoutes registers staking-related REST handlers to a router -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Codec) { - r.HandleFunc("/slashing/signing_info/{validator_pub}", +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { + r.HandleFunc("/slashing/validators/{validatorPubKey}/signing_info", signingInfoHandlerFn(cliCtx, "slashing", cdc)).Methods("GET") - r.HandleFunc("/slashing/unrevoke", + r.HandleFunc("/slashing/validators/{validatorAddr}/unjail", unrevokeRequestHandlerFn(cdc, cliCtx)).Methods("POST") } diff --git a/client/slashing/lcd/sendtx.go b/client/slashing/lcd/sendtx.go index b750d331d..3802bac61 100644 --- a/client/slashing/lcd/sendtx.go +++ b/client/slashing/lcd/sendtx.go @@ -1,56 +1,44 @@ package lcd import ( - "bytes" - "fmt" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/utils" "net/http" + "github.com/gorilla/mux" ) // Unrevoke TX body -type UnrevokeBody struct { +type UnjailBody struct { BaseTx context.BaseTx `json:"base_tx"` - ValidatorAddr string `json:"validator_addr"` } -func unrevokeRequestHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func unrevokeRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var m UnrevokeBody - err := utils.ReadPostBody(w, r, cdc, &m) - if err != nil { - return - } - cliCtx = utils.InitRequestClictx(cliCtx, r, m.BaseTx.LocalAccountName, m.ValidatorAddr) - txCtx, err := context.NewTxContextFromBaseTx(cliCtx, cdc, m.BaseTx) + cliCtx = utils.InitReqCliCtx(cliCtx, r) + vars := mux.Vars(r) + + validatorAddr, err := sdk.ValAddressFromBech32(vars["validatorAddr"]) if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - validatorAddr, err := sdk.AccAddressFromBech32(m.ValidatorAddr) + var m UnjailBody + err = utils.ReadPostBody(w, r, cdc, &m) if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error())) return } - if !cliCtx.GenerateOnly { - fromAddress, err := cliCtx.GetFromAddress() - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - if !bytes.Equal(fromAddress, validatorAddr) { - utils.WriteErrorResponse(w, http.StatusUnauthorized, "Must use own validator address") - return - } + baseReq := m.BaseTx.Sanitize() + if !baseReq.ValidateBasic(w, cliCtx) { + return } - msg := slashing.NewMsgUnrevoke(validatorAddr) + msg := slashing.NewMsgUnjail(validatorAddr) - utils.SendOrReturnUnsignedTx(w, cliCtx, txCtx, m.BaseTx, []sdk.Msg{msg}) + utils.SendOrReturnUnsignedTx(w, cliCtx, m.BaseTx, []sdk.Msg{msg}) } } diff --git a/client/stake/cli/flags.go b/client/stake/cli/flags.go index f37e0c1c1..c567173a3 100644 --- a/client/stake/cli/flags.go +++ b/client/stake/cli/flags.go @@ -10,8 +10,8 @@ import ( const ( FlagAddressDelegator = "address-delegator" FlagAddressValidator = "address-validator" - FlagAddressValidatorSrc = "addr-validator-source" - FlagAddressValidatorDst = "addr-validator-dest" + FlagAddressValidatorSrc = "address-validator-source" + FlagAddressValidatorDst = "address-validator-dest" FlagPubKey = "pubkey" FlagAmount = "amount" FlagSharesAmount = "shares-amount" @@ -21,14 +21,26 @@ const ( FlagIdentity = "identity" FlagWebsite = "website" FlagDetails = "details" + + FlagCommissionRate = "commission-rate" + FlagCommissionMaxRate = "commission-max-rate" + FlagCommissionMaxChangeRate = "commission-max-change-rate" + + FlagGenesisFormat = "genesis-format" + FlagNodeID = "node-id" + FlagIP = "ip" + + FlagOutputDocument = "output-document" // inspired by wget -O ) // common flagsets to add to various functions var ( - fsPk = flag.NewFlagSet("", flag.ContinueOnError) - fsAmount = flag.NewFlagSet("", flag.ContinueOnError) + FsPk = flag.NewFlagSet("", flag.ContinueOnError) + FsAmount = flag.NewFlagSet("", flag.ContinueOnError) fsShares = flag.NewFlagSet("", flag.ContinueOnError) fsDescriptionCreate = flag.NewFlagSet("", flag.ContinueOnError) + FsCommissionCreate = flag.NewFlagSet("", flag.ContinueOnError) + fsCommissionUpdate = flag.NewFlagSet("", flag.ContinueOnError) fsDescriptionEdit = flag.NewFlagSet("", flag.ContinueOnError) fsValidator = flag.NewFlagSet("", flag.ContinueOnError) fsDelegator = flag.NewFlagSet("", flag.ContinueOnError) @@ -36,20 +48,24 @@ var ( ) func init() { - fsPk.String(FlagPubKey, "", "Go-Amino encoded hex PubKey of the validator. For Ed25519 the go-amino prepend hex is 1624de6220") - fsAmount.String(FlagAmount, "", "Amount of coins to bond") + FsPk.String(FlagPubKey, "", "Go-Amino encoded hex PubKey of the validator. For Ed25519 the go-amino prepend hex is 1624de6220") + FsAmount.String(FlagAmount, "", "Amount of coins to bond") fsShares.String(FlagSharesAmount, "", "Amount of source-shares to either unbond or redelegate as a positive integer or decimal") fsShares.String(FlagSharesPercent, "", "Percent of source-shares to either unbond or redelegate as a positive integer or decimal >0 and <=1") fsDescriptionCreate.String(FlagMoniker, "", "validator name") fsDescriptionCreate.String(FlagIdentity, "", "optional identity signature (ex. UPort or Keybase)") fsDescriptionCreate.String(FlagWebsite, "", "optional website") fsDescriptionCreate.String(FlagDetails, "", "optional details") + fsCommissionUpdate.String(FlagCommissionRate, "", "The new commission rate percentage") + FsCommissionCreate.String(FlagCommissionRate, "", "The initial commission rate percentage") + FsCommissionCreate.String(FlagCommissionMaxRate, "", "The maximum commission rate percentage") + FsCommissionCreate.String(FlagCommissionMaxChangeRate, "", "The maximum commission change rate percentage (per day)") fsDescriptionEdit.String(FlagMoniker, types.DoNotModifyDesc, "validator name") fsDescriptionEdit.String(FlagIdentity, types.DoNotModifyDesc, "optional identity signature (ex. UPort or Keybase)") fsDescriptionEdit.String(FlagWebsite, types.DoNotModifyDesc, "optional website") fsDescriptionEdit.String(FlagDetails, types.DoNotModifyDesc, "optional details") - fsValidator.String(FlagAddressValidator, "", "bech32 encoding address of the validator") - fsDelegator.String(FlagAddressDelegator, "", "bech32 encoding address of the delegator") - fsRedelegation.String(FlagAddressValidatorSrc, "", "bech32 encoding address of the source validator") - fsRedelegation.String(FlagAddressValidatorDst, "", "bech32 encoding address of the destination validator") + fsValidator.String(FlagAddressValidator, "", "bech address of the validator") + fsDelegator.String(FlagAddressDelegator, "", "bech address of the delegator") + fsRedelegation.String(FlagAddressValidatorSrc, "", "bech address of the source validator") + fsRedelegation.String(FlagAddressValidatorDst, "", "bech address of the destination validator") } diff --git a/client/stake/cli/query.go b/client/stake/cli/query.go index 491cc8fd9..9e42087de 100644 --- a/client/stake/cli/query.go +++ b/client/stake/cli/query.go @@ -7,8 +7,8 @@ import ( "github.com/spf13/viper" "github.com/tendermint/tendermint/libs/cli" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/stake" "github.com/cosmos/cosmos-sdk/x/stake/types" "github.com/irisnet/irishub/client/context" @@ -16,14 +16,14 @@ import ( ) // GetCmdQueryValidator implements the validator query command. -func GetCmdQueryValidator(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQueryValidator(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "validator [owner-addr]", - Short: "Query a validator", + Use: "validator [owner-addr]", + Short: "Query a validator", Example: "iriscli stake validator ", - Args: cobra.ExactArgs(1), + Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - addr, err := sdk.AccAddressFromBech32(args[0]) + addr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err } @@ -39,11 +39,11 @@ func GetCmdQueryValidator(storeName string, cdc *wire.Codec) *cobra.Command { } validator := types.MustUnmarshalValidator(cdc, addr, res) - validatorOutput,err := stakeClient.ConvertValidatorToValidatorOutput(cliCtx, validator) + validatorOutput := stakeClient.ConvertValidatorToValidatorOutput(cliCtx, validator) if err != nil { return err } - + switch viper.Get(cli.OutputFlag) { case "text": human, err := validatorOutput.HumanReadableString() @@ -54,7 +54,7 @@ func GetCmdQueryValidator(storeName string, cdc *wire.Codec) *cobra.Command { case "json": // parse out the validator - output, err := wire.MarshalJSONIndent(cdc, validatorOutput) + output, err := codec.MarshalJSONIndent(cdc, validatorOutput) if err != nil { return err } @@ -71,10 +71,10 @@ func GetCmdQueryValidator(storeName string, cdc *wire.Codec) *cobra.Command { } // GetCmdQueryValidators implements the query all validators command. -func GetCmdQueryValidators(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQueryValidators(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "validators", - Short: "Query for all validators", + Use: "validators", + Short: "Query for all validators", Example: "iriscli stake validators", RunE: func(cmd *cobra.Command, args []string) error { key := stake.ValidatorsKey @@ -90,7 +90,7 @@ func GetCmdQueryValidators(storeName string, cdc *wire.Codec) *cobra.Command { for _, kv := range resKVs { addr := kv.Key[1:] validator := types.MustUnmarshalValidator(cdc, addr, kv.Value) - validatorOutput, err := stakeClient.ConvertValidatorToValidatorOutput(cliCtx, validator) + validatorOutput := stakeClient.ConvertValidatorToValidatorOutput(cliCtx, validator) if err != nil { return err } @@ -108,7 +108,7 @@ func GetCmdQueryValidators(storeName string, cdc *wire.Codec) *cobra.Command { fmt.Println(resp) } case "json": - output, err := wire.MarshalJSONIndent(cdc, validators) + output, err := codec.MarshalJSONIndent(cdc, validators) if err != nil { return err } @@ -125,14 +125,77 @@ func GetCmdQueryValidators(storeName string, cdc *wire.Codec) *cobra.Command { return cmd } +// GetCmdQueryValidatorUnbondingDelegations implements the query all unbonding delegatations from a validator command. +func GetCmdQueryValidatorUnbondingDelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "unbonding-delegations-from [operator-addr]", + Short: "Query all unbonding delegatations from a validator", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + valAddr, err := sdk.ValAddressFromBech32(args[0]) + if err != nil { + return err + } + cliCtx := context.NewCLIContext().WithCodec(cdc) + params := stake.QueryValidatorParams{ + ValidatorAddr: valAddr, + } + bz, err := cdc.MarshalJSON(params) + if err != nil { + return err + } + res, err := cliCtx.QueryWithData( + fmt.Sprintf("custom/%s/validatorUnbondingDelegations", queryRoute), + bz) + if err != nil { + return err + } + fmt.Println(string(res)) + return nil + }, + } + return cmd +} +// GetCmdQueryValidatorRedelegations implements the query all redelegatations from a validator command. +func GetCmdQueryValidatorRedelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "redelegations-from [operator-addr]", + Short: "Query all outgoing redelegatations from a validator", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + valAddr, err := sdk.ValAddressFromBech32(args[0]) + if err != nil { + return err + } + cliCtx := context.NewCLIContext().WithCodec(cdc) + params := stake.QueryValidatorParams{ + ValidatorAddr: valAddr, + } + bz, err := cdc.MarshalJSON(params) + if err != nil { + return err + } + res, err := cliCtx.QueryWithData( + fmt.Sprintf("custom/%s/validatorRedelegations", queryRoute), + bz) + if err != nil { + return err + } + fmt.Println(string(res)) + return nil + }, + } + return cmd +} + // GetCmdQueryDelegation the query delegation command. -func GetCmdQueryDelegation(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQueryDelegation(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "delegation", - Short: "Query a delegation based on address and validator address", + Use: "delegation", + Short: "Query a delegation based on address and validator address", Example: "iriscli stake delegation --address-validator= --address-delegator=", RunE: func(cmd *cobra.Command, args []string) error { - valAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidator)) + valAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidator)) if err != nil { return err } @@ -152,7 +215,7 @@ func GetCmdQueryDelegation(storeName string, cdc *wire.Codec) *cobra.Command { return fmt.Errorf("no delegation found with delegator %s on validator %s", delAddr, valAddr) } - // parse out the delegation + // parse out the unbonding delegation delegation := types.MustUnmarshalDelegation(cdc, key, res) delegationOutput := stakeClient.ConvertDelegationToDelegationOutput(cliCtx, delegation) switch viper.Get(cli.OutputFlag) { @@ -164,7 +227,7 @@ func GetCmdQueryDelegation(storeName string, cdc *wire.Codec) *cobra.Command { fmt.Println(resp) case "json": - output, err := wire.MarshalJSONIndent(cdc, delegationOutput) + output, err := codec.MarshalJSONIndent(cdc, delegationOutput) if err != nil { return err } @@ -185,12 +248,12 @@ func GetCmdQueryDelegation(storeName string, cdc *wire.Codec) *cobra.Command { // GetCmdQueryDelegations implements the command to query all the delegations // made from one delegator. -func GetCmdQueryDelegations(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQueryDelegations(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "delegations [delegator-addr]", - Short: "Query all delegations made from one delegator", + Use: "delegations [delegator-addr]", + Short: "Query all delegations made from one delegator", Example: "iriscli stake delegations ", - Args: cobra.ExactArgs(1), + Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { delegatorAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -213,7 +276,7 @@ func GetCmdQueryDelegations(storeName string, cdc *wire.Codec) *cobra.Command { delegations = append(delegations, delegationOutput) } - output, err := wire.MarshalJSONIndent(cdc, delegations) + output, err := codec.MarshalJSONIndent(cdc, delegations) if err != nil { return err } @@ -230,13 +293,13 @@ func GetCmdQueryDelegations(storeName string, cdc *wire.Codec) *cobra.Command { // GetCmdQueryUnbondingDelegation implements the command to query a single // unbonding-delegation record. -func GetCmdQueryUnbondingDelegation(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQueryUnbondingDelegation(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "unbonding-delegation", - Short: "Query an unbonding-delegation record based on delegator and validator address", + Use: "unbonding-delegation", + Short: "Query an unbonding-delegation record based on delegator and validator address", Example: "iriscli stake unbonding-delegation --address-validator= --address-delegator=", RunE: func(cmd *cobra.Command, args []string) error { - valAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidator)) + valAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidator)) if err != nil { return err } @@ -269,7 +332,7 @@ func GetCmdQueryUnbondingDelegation(storeName string, cdc *wire.Codec) *cobra.Co fmt.Println(resp) case "json": - output, err := wire.MarshalJSONIndent(cdc, ubdOutput) + output, err := codec.MarshalJSONIndent(cdc, ubdOutput) if err != nil { return err } @@ -290,12 +353,12 @@ func GetCmdQueryUnbondingDelegation(storeName string, cdc *wire.Codec) *cobra.Co // GetCmdQueryUnbondingDelegations implements the command to query all the // unbonding-delegation records for a delegator. -func GetCmdQueryUnbondingDelegations(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQueryUnbondingDelegations(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "unbonding-delegations [delegator-addr]", - Short: "Query all unbonding-delegations records for one delegator", + Use: "unbonding-delegations [delegator-addr]", + Short: "Query all unbonding-delegations records for one delegator", Example: "iriscli stake unbonding-delegation ", - Args: cobra.ExactArgs(1), + Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { delegatorAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -318,7 +381,7 @@ func GetCmdQueryUnbondingDelegations(storeName string, cdc *wire.Codec) *cobra.C ubds = append(ubds, ubdOutput) } - output, err := wire.MarshalJSONIndent(cdc, ubds) + output, err := codec.MarshalJSONIndent(cdc, ubds) if err != nil { return err } @@ -335,18 +398,18 @@ func GetCmdQueryUnbondingDelegations(storeName string, cdc *wire.Codec) *cobra.C // GetCmdQueryRedelegation implements the command to query a single // redelegation record. -func GetCmdQueryRedelegation(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQueryRedelegation(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "redelegation", - Short: "Query a redelegation record based on delegator and a source and destination validator address", + Use: "redelegation", + Short: "Query a redelegation record based on delegator and a source and destination validator address", Example: "iriscli stake redelegation --address-validator-source= --address-validator-dest= --address-delegator=", RunE: func(cmd *cobra.Command, args []string) error { - valSrcAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidatorSrc)) + valSrcAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidatorSrc)) if err != nil { return err } - valDstAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidatorDst)) + valDstAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidatorDst)) if err != nil { return err } @@ -379,7 +442,7 @@ func GetCmdQueryRedelegation(storeName string, cdc *wire.Codec) *cobra.Command { fmt.Println(resp) case "json": - output, err := wire.MarshalJSONIndent(cdc, redOutput) + output, err := codec.MarshalJSONIndent(cdc, redOutput) if err != nil { return err } @@ -400,12 +463,12 @@ func GetCmdQueryRedelegation(storeName string, cdc *wire.Codec) *cobra.Command { // GetCmdQueryRedelegations implements the command to query all the // redelegation records for a delegator. -func GetCmdQueryRedelegations(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQueryRedelegations(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "redelegations [delegator-addr]", - Short: "Query all redelegations records for one delegator", + Use: "redelegations [delegator-addr]", + Short: "Query all redelegations records for one delegator", Example: "iriscli stake redelegations ", - Args: cobra.ExactArgs(1), + Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { delegatorAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -428,7 +491,7 @@ func GetCmdQueryRedelegations(storeName string, cdc *wire.Codec) *cobra.Command reds = append(reds, redOutput) } - output, err := wire.MarshalJSONIndent(cdc, reds) + output, err := codec.MarshalJSONIndent(cdc, reds) if err != nil { return err } @@ -442,3 +505,86 @@ func GetCmdQueryRedelegations(storeName string, cdc *wire.Codec) *cobra.Command return cmd } + +// GetCmdQueryPool implements the pool query command. +func GetCmdQueryPool(storeName string, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "pool", + Short: "Query the current staking pool values", + Example: "iriscli stake pool", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + key := stake.PoolKey + cliCtx := context.NewCLIContext().WithCodec(cdc) + + res, err := cliCtx.QueryStore(key, storeName) + if err != nil { + return err + } + + pool := types.MustUnmarshalPool(cdc, res) + poolOutput := stakeClient.ConvertPoolToPoolOutput(cliCtx, pool) + + switch viper.Get(cli.OutputFlag) { + case "text": + human := poolOutput.HumanReadableString() + + fmt.Println(human) + + case "json": + // parse out the pool + output, err := codec.MarshalJSONIndent(cdc, poolOutput) + if err != nil { + return err + } + + fmt.Println(string(output)) + } + return nil + }, + } + + return cmd +} + +// GetCmdQueryPool implements the params query command. +func GetCmdQueryParams(storeName string, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "parameters", + Short: "Query the current staking parameters information", + Example: "iriscli stake parameters", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx := context.NewCLIContext().WithCodec(cdc) + bz, err := cliCtx.QueryWithData("custom/stake/"+stake.QueryParameters, nil) + if err != nil { + return err + } + + var params stake.Params + err = cdc.UnmarshalJSON(bz, ¶ms) + if err != nil { + return err + } + + switch viper.Get(cli.OutputFlag) { + case "text": + human := params.HumanReadableString() + + fmt.Println(human) + + case "json": + // parse out the params + output, err := codec.MarshalJSONIndent(cdc, params) + if err != nil { + return err + } + + fmt.Println(string(output)) + } + return nil + }, + } + + return cmd +} diff --git a/client/stake/cli/sendtx.go b/client/stake/cli/sendtx.go index 09b7cc2cd..d08c9b70b 100644 --- a/client/stake/cli/sendtx.go +++ b/client/stake/cli/sendtx.go @@ -4,13 +4,13 @@ import ( "fmt" "os" + "github.com/cosmos/cosmos-sdk/codec" 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/cosmos/cosmos-sdk/x/stake" "github.com/cosmos/cosmos-sdk/x/stake/types" - "github.com/irisnet/irishub/client" + "github.com/irisnet/irishub/app" "github.com/irisnet/irishub/client/context" stakeClient "github.com/irisnet/irishub/client/stake" "github.com/irisnet/irishub/client/utils" @@ -20,11 +20,11 @@ import ( ) // GetCmdCreateValidator implements the create validator command handler. -func GetCmdCreateValidator(cdc *wire.Codec) *cobra.Command { +func GetCmdCreateValidator(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "create-validator", - Short: "create new validator initialized with a self-delegation to it", - Example: "iriscli stake create-validator --chain-id= --from= --fee=0.004iris --pubkey= --amount=10iris --moniker=", + Use: "create-validator", + Short: "create new validator initialized with a self-delegation to it", + Example: "iriscli stake create-validator --chain-id= --from= --fee=0.004iris --pubkey= --amount=10iris --moniker= --commission-max-change-rate=0.1 --commission-max-rate=0.5 --commission-rate=0.1", RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext(). WithCodec(cdc). @@ -52,7 +52,7 @@ func GetCmdCreateValidator(cdc *wire.Codec) *cobra.Command { return fmt.Errorf("must use --pubkey flag") } - pk, err := sdk.GetValPubKeyBech32(pkStr) + pk, err := sdk.GetConsPubKeyBech32(pkStr) if err != nil { return err } @@ -68,36 +68,70 @@ func GetCmdCreateValidator(cdc *wire.Codec) *cobra.Command { Details: viper.GetString(FlagDetails), } + // get the initial validator commission parameters + rateStr := viper.GetString(FlagCommissionRate) + maxRateStr := viper.GetString(FlagCommissionMaxRate) + maxChangeRateStr := viper.GetString(FlagCommissionMaxChangeRate) + commissionMsg, err := stakeClient.BuildCommissionMsg(rateStr, maxRateStr, maxChangeRateStr) + if err != nil { + return err + } + var msg sdk.Msg if viper.GetString(FlagAddressDelegator) != "" { - delegatorAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressDelegator)) + delAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressDelegator)) if err != nil { return err } - msg = stake.NewMsgCreateValidatorOnBehalfOf(delegatorAddr, validatorAddr, pk, amount, description) + msg = stake.NewMsgCreateValidatorOnBehalfOf( + delAddr, sdk.ValAddress(validatorAddr), pk, amount, description, commissionMsg, + ) } else { - msg = stake.NewMsgCreateValidator(validatorAddr, pk, amount, description) + msg = stake.NewMsgCreateValidator( + sdk.ValAddress(validatorAddr), pk, amount, description, commissionMsg, + ) + } + + if viper.GetBool(FlagGenesisFormat) { + ip := viper.GetString(FlagIP) + nodeID := viper.GetString(FlagNodeID) + if nodeID != "" && ip != "" { + txCtx = txCtx.WithMemo(fmt.Sprintf("%s@%s:26656", nodeID, ip)) + } + } + + if viper.GetBool(FlagGenesisFormat) || cliCtx.GenerateOnly { + return utils.PrintUnsignedStdTx(txCtx, cliCtx, []sdk.Msg{msg}, true) } return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) }, } - cmd.Flags().AddFlagSet(fsPk) - cmd.Flags().AddFlagSet(fsAmount) + cmd.Flags().AddFlagSet(FsPk) + cmd.Flags().AddFlagSet(FsAmount) cmd.Flags().AddFlagSet(fsDescriptionCreate) + cmd.Flags().AddFlagSet(FsCommissionCreate) cmd.Flags().AddFlagSet(fsDelegator) - + cmd.Flags().Bool(FlagGenesisFormat, false, "Export the transaction in gen-tx format; it implies --generate-only") + cmd.Flags().String(FlagIP, "", fmt.Sprintf("Node's public IP. It takes effect only when used in combination with --%s", FlagGenesisFormat)) + cmd.Flags().String(FlagNodeID, "", "Node's ID") + cmd.MarkFlagRequired(FlagMoniker) + cmd.MarkFlagRequired(FlagPubKey) + cmd.MarkFlagRequired(FlagAmount) + cmd.MarkFlagRequired(FlagCommissionRate) + cmd.MarkFlagRequired(FlagCommissionMaxRate) + cmd.MarkFlagRequired(FlagCommissionMaxChangeRate) return cmd } // GetCmdEditValidator implements the create edit validator command. -func GetCmdEditValidator(cdc *wire.Codec) *cobra.Command { +func GetCmdEditValidator(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "edit-validator", - Short: "edit and existing validator account", - Example: "iriscli stake edit-validator --chain-id= --from= --fee=0.004iris --moniker=", + Use: "edit-validator", + Short: "edit and existing validator account", + Example: "iriscli stake create-validator --chain-id= --from= --fee=0.004iris --moniker=", RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext(). WithCodec(cdc). @@ -106,7 +140,7 @@ func GetCmdEditValidator(cdc *wire.Codec) *cobra.Command { txCtx := context.NewTxContextFromCLI().WithCodec(cdc). WithCliCtx(cliCtx) - validatorAddr, err := cliCtx.GetFromAddress() + valAddr, err := cliCtx.GetFromAddress() if err != nil { return err } @@ -117,22 +151,41 @@ func GetCmdEditValidator(cdc *wire.Codec) *cobra.Command { Website: viper.GetString(FlagWebsite), Details: viper.GetString(FlagDetails), } - msg := stake.NewMsgEditValidator(validatorAddr, description) + var newRate *sdk.Dec + + commissionRate := viper.GetString(FlagCommissionRate) + if commissionRate != "" { + rate, err := sdk.NewDecFromStr(commissionRate) + if err != nil { + return fmt.Errorf("invalid new commission rate: %v", err) + } + + newRate = &rate + } + + msg := stake.NewMsgEditValidator(sdk.ValAddress(valAddr), description, newRate) + + if cliCtx.GenerateOnly { + return utils.PrintUnsignedStdTx(txCtx, cliCtx, []sdk.Msg{msg}, false) + } + + // build and sign the transaction, then broadcast to Tendermint return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) }, } cmd.Flags().AddFlagSet(fsDescriptionEdit) + cmd.Flags().AddFlagSet(fsCommissionUpdate) return cmd } // GetCmdDelegate implements the delegate command. -func GetCmdDelegate(cdc *wire.Codec) *cobra.Command { +func GetCmdDelegate(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "delegate", - Short: "delegate liquid tokens to an validator", + Use: "delegate", + Short: "delegate liquid tokens to an validator", Example: "iriscli stake delegate --chain-id= --from= --fee=0.004iris --amount=10iris --address-validator=", RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext(). @@ -152,7 +205,7 @@ func GetCmdDelegate(cdc *wire.Codec) *cobra.Command { return err } - validatorAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidator)) + validatorAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidator)) if err != nil { return err } @@ -163,34 +216,19 @@ func GetCmdDelegate(cdc *wire.Codec) *cobra.Command { }, } - cmd.Flags().AddFlagSet(fsAmount) + cmd.Flags().AddFlagSet(FsAmount) cmd.Flags().AddFlagSet(fsValidator) - + cmd.MarkFlagRequired(FlagAmount) + cmd.MarkFlagRequired(FlagAddressValidator) return cmd } // GetCmdRedelegate implements the redelegate validator command. -func GetCmdRedelegate(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdRedelegate(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "redelegate", - Short: "redelegate illiquid tokens from one validator to another", - } - - cmd.AddCommand( - client.PostCommands( - GetCmdBeginRedelegate(storeName, cdc), - GetCmdCompleteRedelegate(cdc), - )...) - - return cmd -} - -// GetCmdBeginRedelegate the begin redelegation command. -func GetCmdBeginRedelegate(storeName string, cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "begin", - Short: "begin redelegation", - Example: "iriscli stake redelegation begin --chain-id= --from= --fee=0.004iris --address-validator-source= --address-validator-dest= shares-percent=0.5", + Use: "redelegate", + Short: "redelegate illiquid tokens from one validator to another", + Example: "iriscli stake redelegation --chain-id= --from= --fee=0.004iris --address-validator-source= --address-validator-dest= --shares-percent=0.5", RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext(). WithCodec(cdc). @@ -205,12 +243,12 @@ func GetCmdBeginRedelegate(storeName string, cdc *wire.Codec) *cobra.Command { return err } - validatorSrcAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidatorSrc)) + validatorSrcAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidatorSrc)) if err != nil { return err } - validatorDstAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidatorDst)) + validatorDstAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidatorDst)) if err != nil { return err } @@ -234,37 +272,47 @@ func GetCmdBeginRedelegate(storeName string, cdc *wire.Codec) *cobra.Command { cmd.Flags().AddFlagSet(fsShares) cmd.Flags().AddFlagSet(fsRedelegation) - + cmd.MarkFlagRequired(FlagAddressValidatorSrc) + cmd.MarkFlagRequired(FlagAddressValidatorDst) return cmd } // nolint: gocyclo // TODO: Make this pass gocyclo linting func getShares( - storeName string, cliCtx context.CLIContext, cdc *wire.Codec, sharesAmountStr, - sharesPercentStr string, delegatorAddr, validatorAddr sdk.AccAddress, -) (sharesAmount sdk.Rat, err error) { + storeName string, cliCtx context.CLIContext, cdc *codec.Codec, sharesAmountStr, + sharesPercentStr string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, +) (sharesAmount sdk.Dec, err error) { switch { case sharesAmountStr != "" && sharesPercentStr != "": return sharesAmount, errors.Errorf("can either specify the amount OR the percent of the shares, not both") + case sharesAmountStr == "" && sharesPercentStr == "": return sharesAmount, errors.Errorf("can either specify the amount OR the percent of the shares, not both") + case sharesAmountStr != "": - sharesAmount, err = sdk.NewRatFromDecimal(sharesAmountStr, types.MaxBondDenominatorPrecision) + sharesAmount, err = sdk.NewDecFromStr(sharesAmountStr) if err != nil { return sharesAmount, err } - if !sharesAmount.GT(sdk.ZeroRat()) { + if !sharesAmount.GT(sdk.ZeroDec()) { return sharesAmount, errors.Errorf("shares amount must be positive number (ex. 123, 1.23456789)") } - sharesAmount = sharesAmount.Quo(stakeClient.ExRateFromStakeTokenToMainUnit(cliCtx)) + + stakeTokenDenom, err := cliCtx.GetCoinType(app.Denom) + if err != nil { + panic(err) + } + decimalDiff := stakeTokenDenom.MinUnit.Decimal - stakeTokenDenom.GetMainUnit().Decimal + exRate := sdk.NewDecFromInt(sdk.NewIntWithDecimal(1, decimalDiff)) + sharesAmount = sharesAmount.Mul(exRate) case sharesPercentStr != "": - var sharesPercent sdk.Rat - sharesPercent, err = sdk.NewRatFromDecimal(sharesPercentStr, types.MaxBondDenominatorPrecision) + var sharesPercent sdk.Dec + sharesPercent, err = sdk.NewDecFromStr(sharesPercentStr) if err != nil { return sharesAmount, err } - if !sharesPercent.GT(sdk.ZeroRat()) || !sharesPercent.LTE(sdk.OneRat()) { + if !sharesPercent.GT(sdk.ZeroDec()) || !sharesPercent.LTE(sdk.OneDec()) { return sharesAmount, errors.Errorf("shares percent must be >0 and <=1 (ex. 0.01, 0.75, 1)") } @@ -279,75 +327,22 @@ func getShares( return sharesAmount, errors.Errorf("cannot find delegation to determine percent Error: %v", err) } - delegation := types.MustUnmarshalDelegation(cdc, key, resQuery) + delegation, err := types.UnmarshalDelegation(cdc, key, resQuery) + if err != nil { + return sdk.ZeroDec(), err + } + sharesAmount = sharesPercent.Mul(delegation.Shares) } - return } -// GetCmdCompleteRedelegate implements the complete redelegation command. -func GetCmdCompleteRedelegate(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "complete", - Short: "complete redelegation", - Example: "iriscli stake redelegation complete --chain-id= --from= --fee=0.004iris --address-validator-source= --address-validator-dest=", - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext(). - WithCodec(cdc). - WithLogger(os.Stdout). - WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - txCtx := context.NewTxContextFromCLI().WithCodec(cdc). - WithCliCtx(cliCtx) - - delegatorAddr, err := cliCtx.GetFromAddress() - if err != nil { - return err - } - - validatorSrcAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidatorSrc)) - if err != nil { - return err - } - - validatorDstAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidatorDst)) - if err != nil { - return err - } - - msg := stake.NewMsgCompleteRedelegate(delegatorAddr, validatorSrcAddr, validatorDstAddr) - - return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) - }, - } - - cmd.Flags().AddFlagSet(fsRedelegation) - - return cmd -} - -// GetCmdUnbond implements the unbond validator command. -func GetCmdUnbond(storeName string, cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "unbond", - Short: "begin or complete unbonding shares from a validator", - } - - cmd.AddCommand( - client.PostCommands( - GetCmdBeginUnbonding(storeName, cdc), - GetCmdCompleteUnbonding(cdc), - )...) - - return cmd -} - // GetCmdBeginUnbonding implements the begin unbonding validator command. -func GetCmdBeginUnbonding(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdUnbond(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "begin", - Short: "begin unbonding", - Example: "iriscli stake unbond begin --chain-id= --from= --fee=0.004iris --address-validator= shares-percent=0.5", + Use: "unbond", + Short: "unbond shares from a validator", + Example: "iriscli stake unbond --chain-id= --from= --fee=0.004iris --address-validator= --shares-percent=0.5", RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext(). WithCodec(cdc). @@ -361,7 +356,7 @@ func GetCmdBeginUnbonding(storeName string, cdc *wire.Codec) *cobra.Command { return err } - validatorAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidator)) + validatorAddr, err := sdk.ValAddressFromBech32(viper.GetString(FlagAddressValidator)) if err != nil { return err } @@ -385,41 +380,7 @@ func GetCmdBeginUnbonding(storeName string, cdc *wire.Codec) *cobra.Command { cmd.Flags().AddFlagSet(fsShares) cmd.Flags().AddFlagSet(fsValidator) - - return cmd -} - -// GetCmdCompleteUnbonding implements the complete unbonding validator command. -func GetCmdCompleteUnbonding(cdc *wire.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "complete", - Short: "complete unbonding", - Example: "iriscli stake unbond complete --chain-id= --from= --fee=0.004iris --address-validator=", - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext(). - WithCodec(cdc). - WithLogger(os.Stdout). - WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - txCtx := context.NewTxContextFromCLI().WithCodec(cdc). - WithCliCtx(cliCtx) - - delegatorAddr, err := cliCtx.GetFromAddress() - if err != nil { - return err - } - - validatorAddr, err := sdk.AccAddressFromBech32(viper.GetString(FlagAddressValidator)) - if err != nil { - return err - } - - msg := stake.NewMsgCompleteUnbonding(delegatorAddr, validatorAddr) - - return utils.SendOrPrintTx(txCtx, cliCtx, []sdk.Msg{msg}) - }, - } - - cmd.Flags().AddFlagSet(fsValidator) + cmd.MarkFlagRequired(FlagAddressValidator) return cmd } diff --git a/client/stake/lcd/query.go b/client/stake/lcd/query.go index 41799478b..67f09dfe7 100644 --- a/client/stake/lcd/query.go +++ b/client/stake/lcd/query.go @@ -1,11 +1,8 @@ package lcd import ( - "encoding/json" - "fmt" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/stake" "github.com/cosmos/cosmos-sdk/x/stake/tags" "github.com/cosmos/cosmos-sdk/x/stake/types" "github.com/gorilla/mux" @@ -19,115 +16,125 @@ import ( const storeName = "stake" -// aggregation of all delegations, unbondings and redelegations -type DelegationSummary struct { - Delegations []stakeClient.DelegationOutput `json:"delegations"` - UnbondingDelegations []stakeClient.UnbondingDelegationOutput `json:"unbonding_delegations"` - Redelegations []stakeClient.RedelegationOutput `json:"redelegations"` -} +func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { + + // Get all delegations from a delegator + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/delegations", + delegatorDelegationsHandlerFn(cliCtx, cdc), + ).Methods("GET") + + // Get all unbonding delegations from a delegator + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/unbonding_delegations", + delegatorUnbondingDelegationsHandlerFn(cliCtx, cdc), + ).Methods("GET") + + // Get all redelegations from a delegator + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/redelegations", + delegatorRedelegationsHandlerFn(cliCtx, cdc), + ).Methods("GET") + + // Get all staking txs (i.e msgs) from a delegator + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/txs", + delegatorTxsHandlerFn(cliCtx, cdc), + ).Methods("GET") + + // Query all validators that a delegator is bonded to + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/validators", + delegatorValidatorsHandlerFn(cliCtx, cdc), + ).Methods("GET") + + // Query a validator that a delegator is bonded to + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/validators/{validatorAddr}", + delegatorValidatorHandlerFn(cliCtx, cdc), + ).Methods("GET") + + // Query a delegation between a delegator and a validator + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/delegations/{validatorAddr}", + delegationHandlerFn(cliCtx, cdc), + ).Methods("GET") + + // Query all unbonding delegations between a delegator and a validator + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}", + unbondingDelegationHandlerFn(cliCtx, cdc), + ).Methods("GET") + + // Get all validators + r.HandleFunc( + "/stake/validators", + validatorsHandlerFn(cliCtx, cdc), + ).Methods("GET") + + // Get a single validator info + r.HandleFunc( + "/stake/validators/{validatorAddr}", + validatorHandlerFn(cliCtx, cdc), + ).Methods("GET") + + // Get all unbonding delegations from a validator + r.HandleFunc( + "/stake/validators/{validatorAddr}/unbonding_delegations", + validatorUnbondingDelegationsHandlerFn(cliCtx, cdc), + ).Methods("GET") + + // Get all outgoing redelegations from a validator + r.HandleFunc( + "/stake/validators/{validatorAddr}/redelegations", + validatorRedelegationsHandlerFn(cliCtx, cdc), + ).Methods("GET") + + // Get the current state of the staking pool + r.HandleFunc( + "/stake/pool", + poolHandlerFn(cliCtx, cdc), + ).Methods("GET") + + // Get the current staking parameter values + r.HandleFunc( + "/stake/parameters", + paramsHandlerFn(cliCtx, cdc), + ).Methods("GET") -type ExRateResponse struct { - ExRate float64 `json:"token_shares_rate"` } // HTTP request handler to query a delegator delegations -func delegatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - - var validatorAddr sdk.AccAddress - var delegationSummary = DelegationSummary{} - - // read parameters - vars := mux.Vars(r) - bech32delegator := vars["delegatorAddr"] - - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - // Get all validators using key - validators, statusCode, errMsg, err := getValidatorOutputs(storeName, cliCtx, cdc) - if err != nil { - w.WriteHeader(statusCode) - w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) - return - } - - for _, validator := range validators { - validatorAddr = validator.Owner - - // Delegations - delegations, statusCode, errMsg, err := getDelegatorDelegations(cliCtx, cdc, delegatorAddr, validatorAddr) - if err != nil { - w.WriteHeader(statusCode) - w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) - return - } - if statusCode != http.StatusNoContent { - delegationSummary.Delegations = append(delegationSummary.Delegations, delegations) - } - - // Undelegations - unbondingDelegation, statusCode, errMsg, err := getDelegatorUndelegations(cliCtx, cdc, delegatorAddr, validatorAddr) - if err != nil { - w.WriteHeader(statusCode) - w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) - return - } - if statusCode != http.StatusNoContent { - delegationSummary.UnbondingDelegations = append(delegationSummary.UnbondingDelegations, - stakeClient.ConvertUBDToUBDOutput(cliCtx, unbondingDelegation)) - } - - // Redelegations - // only querying redelegations to a validator as this should give us already all relegations - // if we also would put in redelegations from, we would have every redelegation double - redelegations, statusCode, errMsg, err := getDelegatorRedelegations(cliCtx, cdc, delegatorAddr, validatorAddr) - if err != nil { - w.WriteHeader(statusCode) - w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) - return - } - if statusCode != http.StatusNoContent { - delegationSummary.Redelegations = append(delegationSummary.Redelegations, - stakeClient.ConvertREDToREDOutput(cliCtx, redelegations)) - } - } +func delegatorDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return queryDelegator(cliCtx, cdc, "custom/stake/delegatorDelegations") +} - output, err := cdc.MarshalJSONIndent(delegationSummary, "", " ") - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } +// HTTP request handler to query a delegator unbonding delegations +func delegatorUnbondingDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return queryDelegator(cliCtx, cdc, "custom/stake/delegatorUnbondingDelegations") +} - w.Write(output) - } +// HTTP request handler to query a delegator redelegations +func delegatorRedelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return queryDelegator(cliCtx, cdc, "custom/stake/delegatorRedelegations") } -// nolint gocyclo // HTTP request handler to query all staking txs (msgs) from a delegator -func delegatorTxsHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { +func delegatorTxsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var output []byte var typesQuerySlice []string vars := mux.Vars(r) delegatorAddr := vars["delegatorAddr"] _, err := sdk.AccAddressFromBech32(delegatorAddr) if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } node, err := cliCtx.GetNode() if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't get current Node information. Error: %s", err.Error()))) + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } @@ -169,360 +176,107 @@ func delegatorTxsHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.Hand for _, action := range actions { foundTxs, errQuery := queryTxs(node, cliCtx, cdc, action, delegatorAddr) if errQuery != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("error querying transactions. Error: %s", errQuery.Error()))) + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) } txs = append(txs, foundTxs...) } - output, err = cdc.MarshalJSONIndent(txs, "", " ") - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - w.Write(output) + utils.PostProcessResponse(w, cdc, txs, cliCtx.Indent) } } // HTTP request handler to query an unbonding-delegation -func unbondingDelegationsHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - bech32delegator := vars["delegatorAddr"] - bech32validator := vars["validatorAddr"] - - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - validatorAddrAcc := sdk.AccAddress(validatorAddr) - - key := stake.GetUBDKey(delegatorAddr, validatorAddrAcc) - - res, err := cliCtx.QueryStore(key, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query unbonding-delegation. Error: %s", err.Error()))) - return - } - - // the query will return empty if there is no data for this record - if len(res) == 0 { - w.WriteHeader(http.StatusNoContent) - return - } - - ubd, err := types.UnmarshalUBD(cdc, key, res) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't unmarshall unbonding-delegation. Error: %s", err.Error()))) - return - } - - // unbondings will be a list in the future but is not yet, but we want to keep the API consistent - ubdArray := []stakeClient.UnbondingDelegationOutput{stakeClient.ConvertUBDToUBDOutput(cliCtx, ubd)} - - output, err := cdc.MarshalJSONIndent(ubdArray, "", " ") - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't marshall unbonding-delegation. Error: %s", err.Error()))) - return - } - - w.Write(output) - } +func unbondingDelegationHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return queryBonds(cliCtx, cdc, "custom/stake/unbondingDelegation") } -// HTTP request handler to query a bonded validator -func delegationHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - // read parameters - vars := mux.Vars(r) - bech32delegator := vars["delegatorAddr"] - bech32validator := vars["validatorAddr"] - - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - validatorAddr, err := sdk.AccAddressFromBech32(bech32validator) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - validatorAddrAcc := sdk.AccAddress(validatorAddr) - - key := stake.GetDelegationKey(delegatorAddr, validatorAddrAcc) - - res, err := cliCtx.QueryStore(key, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query delegation. Error: %s", err.Error()))) - return - } - - // the query will return empty if there is no data for this record - if len(res) == 0 { - w.WriteHeader(http.StatusNoContent) - return - } - - delegation, err := types.UnmarshalDelegation(cdc, key, res) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - outputDelegation := stakeClient.ConvertDelegationToDelegationOutput(cliCtx, delegation) - - output, err := cdc.MarshalJSONIndent(outputDelegation, "", " ") - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - - w.Write(output) - } +// HTTP request handler to query a delegation +func delegationHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return queryBonds(cliCtx, cdc, "custom/stake/delegation") } // HTTP request handler to query all delegator bonded validators -func delegatorValidatorsHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - - var validatorAccAddr sdk.AccAddress - var bondedValidators []stakeClient.ValidatorOutput - - // read parameters - vars := mux.Vars(r) - bech32delegator := vars["delegatorAddr"] - - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } - - // Get all validators using key - kvs, err := cliCtx.QuerySubspace(stake.ValidatorsKey, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query validators. Error: %s", err.Error()))) - return - } else if len(kvs) == 0 { - // the query will return empty if there are no validators - w.WriteHeader(http.StatusNoContent) - return - } - - validators, err := getValidators(cliCtx, cdc, kvs) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) - return - } - - for _, validator := range validators { - // get all transactions from the delegator to val and append - validatorAccAddr = validator.Owner - - validator, statusCode, errMsg, errRes := getDelegatorValidator(cliCtx, cdc, delegatorAddr, validatorAccAddr) - if errRes != nil { - w.WriteHeader(statusCode) - w.Write([]byte(fmt.Sprintf("%s%s", errMsg, errRes.Error()))) - return - } else if statusCode == http.StatusNoContent { - continue - } - - bondedValidators = append(bondedValidators, validator) - } - output, err := cdc.MarshalJSONIndent(bondedValidators, "", " ") - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - w.Write(output) - } +func delegatorValidatorsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return queryDelegator(cliCtx, cdc, "custom/stake/delegatorValidators") } // HTTP request handler to get information from a currently bonded validator -func delegatorValidatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - // read parameters - var output []byte - vars := mux.Vars(r) - bech32delegator := vars["delegatorAddr"] - bech32validator := vars["validatorAddr"] - - delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) - return - } - validatorAccAddr, err := sdk.AccAddressFromBech32(bech32validator) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) - return - } - - // Check if there if the delegator is bonded or redelegated to the validator - - validator, statusCode, errMsg, err := getDelegatorValidator(cliCtx, cdc, delegatorAddr, validatorAccAddr) - if err != nil { - w.WriteHeader(statusCode) - w.Write([]byte(fmt.Sprintf("%s%s", errMsg, err.Error()))) - return - } else if statusCode == http.StatusNoContent { - w.WriteHeader(statusCode) - return - } - output, err = cdc.MarshalJSONIndent(validator, "", " ") - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return - } - w.Write(output) - } +func delegatorValidatorHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return queryBonds(cliCtx, cdc, "custom/stake/delegatorValidator") } -// TODO bech32 -// http request handler to query list of validators -func validatorsHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { +// HTTP request handler to query list of validators +func validatorsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - kvs, err := cliCtx.QuerySubspace(stake.ValidatorsKey, storeName) + res, err := cliCtx.QueryWithData("custom/stake/validators", nil) if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("couldn't query validators. Error: %s", err.Error()))) - return - } - - // the query will return empty if there are no validators - if len(kvs) == 0 { - w.WriteHeader(http.StatusNoContent) + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - validators, err := getValidators(cliCtx, cdc, kvs) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + var validators []types.Validator + if err = cdc.UnmarshalJSON(res, &validators); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - output, err := cdc.MarshalJSONIndent(validators, "", " ") - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(err.Error())) - return + validatorOutputs := make([]stakeClient.ValidatorOutput, len(validators)) + for index, validator := range validators { + validatorOutput := stakeClient.ConvertValidatorToValidatorOutput(cliCtx, validator) + validatorOutputs[index] = validatorOutput } - w.Write(output) + utils.PostProcessResponse(w, cdc, validatorOutputs, cliCtx.Indent) } } // HTTP request handler to query the validator information from a given validator address -func validatorHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var output []byte - // read parameters - vars := mux.Vars(r) - bech32validatorAddr := vars["addr"] - valAddress, err := sdk.AccAddressFromBech32(bech32validatorAddr) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) - return - } - - kvs, err := cliCtx.QuerySubspace(stake.ValidatorsKey, storeName) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) - return - } - - validator, err := getValidator(valAddress, kvs, cliCtx, cdc) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(err.Error())) - return - } +func validatorHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return queryValidator(cliCtx, cdc, "custom/stake/validator") +} - output, err = cdc.MarshalJSONIndent(validator, "", " ") - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) - return - } +// HTTP request handler to query all unbonding delegations from a validator +func validatorUnbondingDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return queryValidator(cliCtx, cdc, "custom/stake/validatorUnbondingDelegations") +} - if output == nil { - w.WriteHeader(http.StatusNoContent) - return - } - w.Write(output) - } +// HTTP request handler to query all redelegations from a source validator +func validatorRedelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return queryValidator(cliCtx, cdc, "custom/stake/validatorRedelegations") } -func getValidatorExRate(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { +// HTTP request handler to query the pool information +func poolHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - // read parameters - vars := mux.Vars(r) - bech32validatorAddr := vars["addr"] - valAddress, err := sdk.AccAddressFromBech32(bech32validatorAddr) + res, err := cliCtx.QueryWithData("custom/stake/pool", nil) if err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte(fmt.Sprintf("Error: %s", err.Error()))) + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - key := stake.GetValidatorKey(valAddress) - - res, err := cliCtx.QueryStore(key, storeName) - if err != nil { + var pool types.Pool + if err = cdc.UnmarshalJSON(res, &pool); err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return - } else if len(res) == 0 { - utils.WriteErrorResponse(w, http.StatusNotFound, fmt.Sprintf("No validator found with address %s", valAddress)) - return } - validator := types.MustUnmarshalValidator(cdc, valAddress, res) - - // validator exRate - valExRate := validator.DelegatorShareExRate() - - floatExRate, _ := valExRate.Float64() - exRate := ExRateResponse{ - ExRate: floatExRate, + poolOutput := stakeClient.ConvertPoolToPoolOutput(cliCtx, pool) + if res, err = codec.MarshalJSONIndent(cdc, poolOutput); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return } + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) + } +} - resRaw, err := json.Marshal(exRate) +// HTTP request handler to query the staking params values +func paramsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + res, err := cliCtx.QueryWithData("custom/stake/parameters", nil) if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - - w.Write(resRaw) + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) } } diff --git a/client/stake/lcd/rest.go b/client/stake/lcd/rest.go index ecbadc669..f5adb3d79 100644 --- a/client/stake/lcd/rest.go +++ b/client/stake/lcd/rest.go @@ -1,65 +1,13 @@ package lcd import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/gorilla/mux" "github.com/irisnet/irishub/client/context" ) -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Codec) { - r.HandleFunc( - "/stake/delegators/{delegatorAddr}/delegations", - delegationsRequestHandlerFn(cdc, cliCtx), - ).Methods("POST") - - // GET /stake/delegators/{delegatorAddr} // Get all delegations (delegation, undelegation and redelegation) from a delegator - r.HandleFunc( - "/stake/delegators/{delegatorAddr}", - delegatorHandlerFn(cliCtx, cdc), - ).Methods("GET") - - // GET /stake/delegators/{delegatorAddr}/txs?type= // Get all staking txs (i.e msgs) from a delegator - r.HandleFunc( - "/stake/delegators/{delegatorAddr}/txs", - delegatorTxsHandlerFn(cliCtx, cdc), - ).Methods("GET") - - // GET /stake/delegators/{delegatorAddr}/validators // Query all validators that a delegator is bonded to - r.HandleFunc( - "/stake/delegators/{delegatorAddr}/validators", - delegatorValidatorsHandlerFn(cliCtx, cdc), - ).Methods("GET") - - // GET /stake/delegators/{delegatorAddr}/validators/{validatorAddr} // Query a validator that a delegator is bonded to - r.HandleFunc( - "/stake/delegators/{delegatorAddr}/validators/{validatorAddr}", - delegatorValidatorHandlerFn(cliCtx, cdc), - ).Methods("GET") - - // GET /stake/delegators/{delegatorAddr}/delegations/{validatorAddr} // Query a delegation between a delegator and a validator - r.HandleFunc( - "/stake/delegators/{delegatorAddr}/delegations/{validatorAddr}", - delegationHandlerFn(cliCtx, cdc), - ).Methods("GET") - - // GET /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr} // Query all unbonding_delegations between a delegator and a validator - r.HandleFunc( - "/stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}", - unbondingDelegationsHandlerFn(cliCtx, cdc), - ).Methods("GET") - - // GET /stake/validators/ - r.HandleFunc( - "/stake/validators", - validatorsHandlerFn(cliCtx, cdc), - ).Methods("GET") - - // GET /stake/validators/{addr} - r.HandleFunc( - "/stake/validators/{addr}", - validatorHandlerFn(cliCtx, cdc), - ).Methods("GET") - - r.HandleFunc("/stake/validator/{addr}/exRate", - getValidatorExRate(cliCtx, cdc)).Methods("GET") +// RegisterRoutes registers staking-related REST handlers to a router +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { + registerQueryRoutes(cliCtx, r, cdc) + registerTxRoutes(cliCtx, r, cdc) } diff --git a/client/stake/lcd/sendtx.go b/client/stake/lcd/sendtx.go index 289cf615c..1cf37dc42 100644 --- a/client/stake/lcd/sendtx.go +++ b/client/stake/lcd/sendtx.go @@ -1,212 +1,218 @@ package lcd import ( - "bytes" - "fmt" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/cosmos/cosmos-sdk/x/stake/types" "github.com/gorilla/mux" "github.com/irisnet/irishub/client/context" - stakeClient "github.com/irisnet/irishub/client/stake" "github.com/irisnet/irishub/client/utils" "net/http" ) -type msgDelegationsInput struct { - ValidatorAddr string `json:"validator_addr"` // in bech32 - Delegation string `json:"delegation"` +func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/delegate", + delegationsRequestHandlerFn(cdc, cliCtx), + ).Methods("POST") + + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/redelegate", + beginRedelegatesRequestHandlerFn(cdc, cliCtx), + ).Methods("POST") + + r.HandleFunc( + "/stake/delegators/{delegatorAddr}/unbond", + beginUnbondingRequestHandlerFn(cdc, cliCtx), + ).Methods("POST") } -type msgBeginRedelegateInput struct { - ValidatorSrcAddr string `json:"validator_src_addr"` // in bech32 - ValidatorDstAddr string `json:"validator_dst_addr"` // in bech32 - SharesAmount string `json:"shares"` -} -type msgCompleteRedelegateInput struct { - ValidatorSrcAddr string `json:"validator_src_addr"` // in bech32 - ValidatorDstAddr string `json:"validator_dst_addr"` // in bech32 -} -type msgBeginUnbondingInput struct { - ValidatorAddr string `json:"validator_addr"` // in bech32 - SharesAmount string `json:"shares"` -} -type msgCompleteUnbondingInput struct { - ValidatorAddr string `json:"validator_addr"` // in bech32 + +type ( + msgDelegateInput struct { + ValidatorAddr string `json:"validator_addr"` // in bech32 + Delegation string `json:"delegation"` + } + + msgRedelegateInput struct { + ValidatorSrcAddr string `json:"validator_src_addr"` // in bech32 + ValidatorDstAddr string `json:"validator_dst_addr"` // in bech32 + SharesAmount string `json:"shares"` + } + + msgUnbondInput struct { + ValidatorAddr string `json:"validator_addr"` // in bech32 + SharesAmount string `json:"shares"` + } + + // the request body for edit delegations + DelegationsReq struct { + BaseReq context.BaseTx `json:"base_tx"` + Delegation msgDelegateInput `json:"delegate"` + } + + BeginUnbondingReq struct { + BaseReq context.BaseTx `json:"base_tx"` + BeginUnbond msgUnbondInput `json:"unbond"` + } + + BeginRedelegatesReq struct { + BaseReq context.BaseTx `json:"base_tx"` + BeginRedelegate msgRedelegateInput `json:"redelegate"` + } +) + +// TODO: Split this up into several smaller functions, and remove the above nolint +// TODO: use sdk.ValAddress instead of sdk.AccAddress for validators in messages +// TODO: Seriously consider how to refactor...do we need to make it multiple txs? +// If not, we can just use CompleteAndBroadcastTxREST. +func delegationsRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + cliCtx = utils.InitReqCliCtx(cliCtx, r) + vars := mux.Vars(r) + bech32delegator := vars["delegatorAddr"] + + var req DelegationsReq + + err := utils.ReadPostBody(w, r, cdc, &req) + if err != nil { + return + } + + baseReq := req.BaseReq.Sanitize() + if !baseReq.ValidateBasic(w, cliCtx) { + return + } + + // build messages + delAddr, err := sdk.AccAddressFromBech32(bech32delegator) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + valAddr, err := sdk.ValAddressFromBech32(req.Delegation.ValidatorAddr) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + delegationToken, err := cliCtx.ParseCoin(req.Delegation.Delegation) + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + msg := stake.MsgDelegate{ + DelegatorAddr: delAddr, + ValidatorAddr: valAddr, + Delegation: delegationToken} + // Broadcast or return unsigned transaction + utils.SendOrReturnUnsignedTx(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + } } -// the request body for edit delegations -type EditDelegationsBody struct { - BaseTx context.BaseTx `json:"base_tx"` - Delegations []msgDelegationsInput `json:"delegations"` - BeginUnbondings []msgBeginUnbondingInput `json:"begin_unbondings"` - CompleteUnbondings []msgCompleteUnbondingInput `json:"complete_unbondings"` - BeginRedelegates []msgBeginRedelegateInput `json:"begin_redelegates"` - CompleteRedelegates []msgCompleteRedelegateInput `json:"complete_redelegates"` +// TODO: Split this up into several smaller functions, and remove the above nolint +// TODO: use sdk.ValAddress instead of sdk.AccAddress for validators in messages +// TODO: Seriously consider how to refactor...do we need to make it multiple txs? +// If not, we can just use CompleteAndBroadcastTxREST. +func beginRedelegatesRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + cliCtx = utils.InitReqCliCtx(cliCtx, r) + vars := mux.Vars(r) + bech32delegator := vars["delegatorAddr"] + + var req BeginRedelegatesReq + + err := utils.ReadPostBody(w, r, cdc, &req) + if err != nil { + return + } + + baseReq := req.BaseReq.Sanitize() + if !baseReq.ValidateBasic(w, cliCtx) { + return + } + + delAddr, err := sdk.AccAddressFromBech32(bech32delegator) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + valSrcAddr, err := sdk.ValAddressFromBech32(req.BeginRedelegate.ValidatorSrcAddr) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + valDstAddr, err := sdk.ValAddressFromBech32(req.BeginRedelegate.ValidatorDstAddr) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + shares, err := sdk.NewDecFromStr(req.BeginRedelegate.SharesAmount) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + msg := stake.MsgBeginRedelegate{ + DelegatorAddr: delAddr, + ValidatorSrcAddr: valSrcAddr, + ValidatorDstAddr: valDstAddr, + SharesAmount: sdk.NewDecFromInt(utils.ConvertDecToRat(shares).Quo(utils.ExRateFromStakeTokenToMainUnit(cliCtx)).Num()), + } + + utils.SendOrReturnUnsignedTx(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + } } -// nolint: gocyclo // TODO: Split this up into several smaller functions, and remove the above nolint // TODO: use sdk.ValAddress instead of sdk.AccAddress for validators in messages -func delegationsRequestHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +// TODO: Seriously consider how to refactor...do we need to make it multiple txs? +// If not, we can just use CompleteAndBroadcastTxREST. +func beginUnbondingRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + cliCtx = utils.InitReqCliCtx(cliCtx, r) vars := mux.Vars(r) - delegatorAddr := vars["delegatorAddr"] + bech32delegator := vars["delegatorAddr"] - var m EditDelegationsBody - err := utils.ReadPostBody(w, r, cdc, &m) + var req BeginUnbondingReq + + err := utils.ReadPostBody(w, r, cdc, &req) if err != nil { return } - cliCtx = utils.InitRequestClictx(cliCtx, r, m.BaseTx.LocalAccountName, delegatorAddr) - txCtx, err := context.NewTxContextFromBaseTx(cliCtx, cdc, m.BaseTx) + + baseReq := req.BaseReq.Sanitize() + if !baseReq.ValidateBasic(w, cliCtx) { + return + } + + delAddr, err := sdk.AccAddressFromBech32(bech32delegator) if err != nil { utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - delegatorAccAddress, err := sdk.AccAddressFromBech32(delegatorAddr) + valAddr, err := sdk.ValAddressFromBech32(req.BeginUnbond.ValidatorAddr) if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode delegator. Error: %s", err.Error()))) + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - if !cliCtx.GenerateOnly { - fromAddress, err := cliCtx.GetFromAddress() - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - if !bytes.Equal(fromAddress, delegatorAccAddress) { - utils.WriteErrorResponse(w, http.StatusUnauthorized, "Must use own delegator address") - return - } + + shares, err := sdk.NewDecFromStr(req.BeginUnbond.SharesAmount) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return } - // build messages - messages := make([]sdk.Msg, len(m.Delegations)+ - len(m.BeginRedelegates)+ - len(m.CompleteRedelegates)+ - len(m.BeginUnbondings)+ - len(m.CompleteUnbondings)) - - i := 0 - for _, msg := range m.Delegations { - - validatorAddr, err := sdk.AccAddressFromBech32(msg.ValidatorAddr) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) - return - } - - delegationToken, err := cliCtx.ParseCoin(msg.Delegation) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - messages[i] = stake.MsgDelegate{ - DelegatorAddr: delegatorAccAddress, - ValidatorAddr: validatorAddr, - Delegation: delegationToken, - } - - i++ - } - - for _, msg := range m.BeginRedelegates { - validatorSrcAddr, err := sdk.AccAddressFromBech32(msg.ValidatorSrcAddr) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) - return - } - validatorDstAddr, err := sdk.AccAddressFromBech32(msg.ValidatorDstAddr) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) - return - } - - shares, err := sdk.NewRatFromDecimal(msg.SharesAmount, types.MaxBondDenominatorPrecision) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode shares amount. Error: %s", err.Error()))) - return - } - - messages[i] = stake.MsgBeginRedelegate{ - DelegatorAddr: delegatorAccAddress, - ValidatorSrcAddr: validatorSrcAddr, - ValidatorDstAddr: validatorDstAddr, - SharesAmount: shares.Quo(stakeClient.ExRateFromStakeTokenToMainUnit(cliCtx)), - } - - i++ - } - - for _, msg := range m.CompleteRedelegates { - validatorSrcAddr, err := sdk.AccAddressFromBech32(msg.ValidatorSrcAddr) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) - return - } - validatorDstAddr, err := sdk.AccAddressFromBech32(msg.ValidatorDstAddr) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) - return - } - - messages[i] = stake.MsgCompleteRedelegate{ - DelegatorAddr: delegatorAccAddress, - ValidatorSrcAddr: validatorSrcAddr, - ValidatorDstAddr: validatorDstAddr, - } - - i++ - } - - for _, msg := range m.BeginUnbondings { - validatorAddr, err := sdk.AccAddressFromBech32(msg.ValidatorAddr) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) - return - } - - shares, err := sdk.NewRatFromDecimal(msg.SharesAmount, types.MaxBondDenominatorPrecision) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode shares amount. Error: %s", err.Error()))) - return - } - - messages[i] = stake.MsgBeginUnbonding{ - DelegatorAddr: delegatorAccAddress, - ValidatorAddr: validatorAddr, - SharesAmount: shares.Quo(stakeClient.ExRateFromStakeTokenToMainUnit(cliCtx)), - } - - i++ - } - - for _, msg := range m.CompleteUnbondings { - validatorAddr, err := sdk.AccAddressFromBech32(msg.ValidatorAddr) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) - return - } - - messages[i] = stake.MsgCompleteUnbonding{ - DelegatorAddr: delegatorAccAddress, - ValidatorAddr: validatorAddr, - } - i++ - } - - utils.SendOrReturnUnsignedTx(w, cliCtx, txCtx, m.BaseTx, messages) + + msg := stake.MsgBeginUnbonding{ + DelegatorAddr: delAddr, + ValidatorAddr: valAddr, + SharesAmount: sdk.NewDecFromInt(utils.ConvertDecToRat(shares).Quo(utils.ExRateFromStakeTokenToMainUnit(cliCtx)).Num()), + } + + utils.SendOrReturnUnsignedTx(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/client/stake/lcd/utils.go b/client/stake/lcd/utils.go index 5a0acd9ac..47313f8a7 100644 --- a/client/stake/lcd/utils.go +++ b/client/stake/lcd/utils.go @@ -1,19 +1,19 @@ package lcd import ( - "bytes" "fmt" "net/http" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/stake" "github.com/cosmos/cosmos-sdk/x/stake/tags" "github.com/cosmos/cosmos-sdk/x/stake/types" + "github.com/gorilla/mux" "github.com/irisnet/irishub/client/context" stakeClient "github.com/irisnet/irishub/client/stake" "github.com/irisnet/irishub/client/tendermint/tx" - "github.com/pkg/errors" + "github.com/irisnet/irishub/client/utils" rpcclient "github.com/tendermint/tendermint/rpc/client" ) @@ -27,198 +27,282 @@ func contains(stringSlice []string, txType string) bool { return false } -func getDelegatorValidator(cliCtx context.CLIContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAccAddr sdk.AccAddress) ( - validator stakeClient.ValidatorOutput, httpStatusCode int, errMsg string, err error) { - - // check if the delegator is bonded or redelegated to the validator - keyDel := stake.GetDelegationKey(delegatorAddr, validatorAccAddr) - - res, err := cliCtx.QueryStore(keyDel, storeName) +// queries staking txs +func queryTxs(node rpcclient.Client, cliCtx context.CLIContext, cdc *codec.Codec, tag string, delegatorAddr string) ([]tx.Info, error) { + page := 0 + perPage := 100 + prove := !cliCtx.TrustNode + query := fmt.Sprintf("%s='%s' AND %s='%s'", tags.Action, tag, tags.Delegator, delegatorAddr) + res, err := node.TxSearch(query, prove, page, perPage) if err != nil { - return stakeClient.ValidatorOutput{}, http.StatusInternalServerError, "couldn't query delegation. Error: ", err + return nil, err } - if len(res) == 0 { - return stakeClient.ValidatorOutput{}, http.StatusNoContent, "", nil + if prove { + for _, txData := range res.Txs { + err := tx.ValidateTxResult(cliCtx, txData) + if err != nil { + return nil, err + } + } } - kvs, err := cliCtx.QuerySubspace(stake.ValidatorsKey, storeName) - if err != nil { - return stakeClient.ValidatorOutput{}, http.StatusInternalServerError, "Error: ", err - } - if len(kvs) == 0 { - // the query will return empty if there are no delegations - return stakeClient.ValidatorOutput{}, http.StatusNoContent, "", nil - } + return tx.FormatTxResults(cdc, res.Txs) +} + +func queryBonds(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + bech32delegator := vars["delegatorAddr"] + bech32validator := vars["validatorAddr"] + + delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + validatorAddr, err := sdk.ValAddressFromBech32(bech32validator) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + params := stake.QueryBondsParams{ + DelegatorAddr: delegatorAddr, + ValidatorAddr: validatorAddr, + } + + bz, err := cdc.MarshalJSON(params) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + res, err := cliCtx.QueryWithData(endpoint, bz) + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } - validator, errVal := getValidatorFromAccAdrr(validatorAccAddr, kvs, cliCtx, cdc) - if errVal != nil { - return stakeClient.ValidatorOutput{}, http.StatusInternalServerError, "Couldn't get info from validator. Error: ", errVal + switch endpoint { + case "custom/stake/unbondingDelegation": + var unbondingDelegation types.UnbondingDelegation + if err = cdc.UnmarshalJSON(res, &unbondingDelegation); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + unbondingDelegationOutput := stakeClient.ConvertUBDToUBDOutput(cliCtx, unbondingDelegation) + if res, err = codec.MarshalJSONIndent(cdc, unbondingDelegationOutput); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + case "custom/stake/delegation": + var delegation types.Delegation + // parse out the validators + if err = cdc.UnmarshalJSON(res, &delegation); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + delegationOutput := stakeClient.ConvertDelegationToDelegationOutput(cliCtx, delegation) + if res, err = codec.MarshalJSONIndent(cdc, delegationOutput); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + case "custom/stake/delegatorValidator": + var validator types.Validator + if err = cdc.UnmarshalJSON(res, &validator); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + validatorOutput := stakeClient.ConvertValidatorToValidatorOutput(cliCtx, validator) + if res, err = codec.MarshalJSONIndent(cdc, validatorOutput); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + } + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) } - return validator, http.StatusOK, "", nil } -func getDelegatorDelegations(cliCtx context.CLIContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( - outputDelegation stakeClient.DelegationOutput, httpStatusCode int, errMsg string, err error) { - delegationKey := stake.GetDelegationKey(delegatorAddr, validatorAddr) - marshalledDelegation, err := cliCtx.QueryStore(delegationKey, storeName) - if err != nil { - return stakeClient.DelegationOutput{}, http.StatusInternalServerError, "couldn't query delegation. Error: ", err - } +func queryDelegator(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + bech32delegator := vars["delegatorAddr"] - // the query will return empty if there is no data for this record - if len(marshalledDelegation) == 0 { - return stakeClient.DelegationOutput{}, http.StatusNoContent, "", nil - } + delegatorAddr, err := sdk.AccAddressFromBech32(bech32delegator) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } - delegation, err := types.UnmarshalDelegation(cdc, delegationKey, marshalledDelegation) - if err != nil { - return stakeClient.DelegationOutput{}, http.StatusInternalServerError, "couldn't unmarshall delegation. Error: ", err - } + params := stake.QueryDelegatorParams{ + DelegatorAddr: delegatorAddr, + } - outputDelegation = stakeClient.ConvertDelegationToDelegationOutput(cliCtx, delegation) + bz, err := cdc.MarshalJSON(params) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } - return outputDelegation, http.StatusOK, "", nil -} + res, err := cliCtx.QueryWithData(endpoint, bz) + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } -func getDelegatorUndelegations(cliCtx context.CLIContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( - unbonds types.UnbondingDelegation, httpStatusCode int, errMsg string, err error) { - undelegationKey := stake.GetUBDKey(delegatorAddr, validatorAddr) - marshalledUnbondingDelegation, err := cliCtx.QueryStore(undelegationKey, storeName) - if err != nil { - return types.UnbondingDelegation{}, http.StatusInternalServerError, "couldn't query unbonding-delegation. Error: ", err - } + switch endpoint { + case "custom/stake/delegatorDelegations": + var delegations []types.Delegation + // parse out the validators + if err = cdc.UnmarshalJSON(res, &delegations); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } - // the query will return empty if there is no data for this record - if len(marshalledUnbondingDelegation) == 0 { - return types.UnbondingDelegation{}, http.StatusNoContent, "", nil - } + delegationOutputs := make([]stakeClient.DelegationOutput, len(delegations)) + for index, delegation := range delegations { + delegationOutput := stakeClient.ConvertDelegationToDelegationOutput(cliCtx, delegation) + delegationOutputs[index] = delegationOutput + } + if res, err = codec.MarshalJSONIndent(cdc, delegationOutputs); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } - unbondingDelegation, err := types.UnmarshalUBD(cdc, undelegationKey, marshalledUnbondingDelegation) - if err != nil { - return types.UnbondingDelegation{}, http.StatusInternalServerError, "couldn't unmarshall unbonding-delegation. Error: ", err - } - return unbondingDelegation, http.StatusOK, "", nil -} + case "custom/stake/delegatorUnbondingDelegations": + var unbondingDelegations []types.UnbondingDelegation + if err = cdc.UnmarshalJSON(res, &unbondingDelegations); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + unbondingDelegationsOutputs := make([]stakeClient.UnbondingDelegationOutput, len(unbondingDelegations)) + for index, unbondingDelegation := range unbondingDelegations { + unbondingDelegationOutput := stakeClient.ConvertUBDToUBDOutput(cliCtx, unbondingDelegation) + unbondingDelegationsOutputs[index] = unbondingDelegationOutput + } -func getDelegatorRedelegations(cliCtx context.CLIContext, cdc *wire.Codec, delegatorAddr sdk.AccAddress, validatorAddr sdk.AccAddress) ( - regelegations types.Redelegation, httpStatusCode int, errMsg string, err error) { + if res, err = codec.MarshalJSONIndent(cdc, unbondingDelegationsOutputs); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } - keyRedelegateTo := stake.GetREDsByDelToValDstIndexKey(delegatorAddr, validatorAddr) - marshalledRedelegations, err := cliCtx.QueryStore(keyRedelegateTo, storeName) - if err != nil { - return types.Redelegation{}, http.StatusInternalServerError, "couldn't query redelegation. Error: ", err - } + case "custom/stake/delegatorRedelegations": + var relegations []types.Redelegation + if err = cdc.UnmarshalJSON(res, &relegations); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } - if len(marshalledRedelegations) == 0 { - return types.Redelegation{}, http.StatusNoContent, "", nil - } + relegationsOutputs := make([]stakeClient.RedelegationOutput, len(relegations)) + for index, relegation := range relegations { + relegationOutput := stakeClient.ConvertREDToREDOutput(cliCtx, relegation) + relegationsOutputs[index] = relegationOutput + } - redelegations, err := types.UnmarshalRED(cdc, keyRedelegateTo, marshalledRedelegations) - if err != nil { - return types.Redelegation{}, http.StatusInternalServerError, "couldn't unmarshall redelegations. Error: ", err - } + if res, err = codec.MarshalJSONIndent(cdc, relegationsOutputs); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } - return redelegations, http.StatusOK, "", nil -} + case "custom/stake/delegatorValidators": + var validators []types.Validator + if err = cdc.UnmarshalJSON(res, &validators); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } -// queries staking txs -func queryTxs(node rpcclient.Client, cliCtx context.CLIContext, cdc *wire.Codec, tag string, delegatorAddr string) ([]tx.Info, error) { - page := 0 - perPage := 100 - prove := !cliCtx.TrustNode - query := fmt.Sprintf("%s='%s' AND %s='%s'", tags.Action, tag, tags.Delegator, delegatorAddr) - res, err := node.TxSearch(query, prove, page, perPage) - if err != nil { - return nil, err - } + validatorOutputs := make([]stakeClient.ValidatorOutput, len(validators)) + for index, validator := range validators { + validatorOutput := stakeClient.ConvertValidatorToValidatorOutput(cliCtx, validator) + validatorOutputs[index] = validatorOutput + } - return tx.FormatTxResults(cdc, res.Txs) + if res, err = codec.MarshalJSONIndent(cdc, validatorOutputs); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + } + + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) + } } -// gets all validators -func getValidators(cliCtx context.CLIContext, cdc *wire.Codec, validatorKVs []sdk.KVPair) ([]stakeClient.ValidatorOutput, error) { - validators := make([]stakeClient.ValidatorOutput, len(validatorKVs)) - for i, kv := range validatorKVs { +func queryValidator(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + bech32validatorAddr := vars["validatorAddr"] - addr := kv.Key[1:] - validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) + validatorAddr, err := sdk.ValAddressFromBech32(bech32validatorAddr) if err != nil { - return nil, err + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return } - validatorOutput, err := stakeClient.ConvertValidatorToValidatorOutput(cliCtx, validator) + params := stake.QueryValidatorParams{ + ValidatorAddr: validatorAddr, + } + + bz, err := cdc.MarshalJSON(params) if err != nil { - return nil, err + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return } - validators[i] = validatorOutput - } - return validators, nil -} -// gets a validator given a ValAddress -func getValidator(address sdk.AccAddress, validatorKVs []sdk.KVPair, cliCtx context.CLIContext, cdc *wire.Codec) (stakeClient.ValidatorOutput, error) { - // parse out the validators - for _, kv := range validatorKVs { - addr := kv.Key[1:] - validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) + res, err := cliCtx.QueryWithData(endpoint, bz) if err != nil { - return stakeClient.ValidatorOutput{}, err + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return } - ownerAddress := validator.Owner - if bytes.Equal(ownerAddress.Bytes(), address.Bytes()) { - validatorOutput, err := stakeClient.ConvertValidatorToValidatorOutput(cliCtx, validator) - if err != nil { - return stakeClient.ValidatorOutput{}, err + switch endpoint { + case "custom/stake/validator": + var validator types.Validator + if err = cdc.UnmarshalJSON(res, &validator); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return } - return validatorOutput, nil - } - } - return stakeClient.ValidatorOutput{}, errors.Errorf("Couldn't find validator") -} + validatorOutput := stakeClient.ConvertValidatorToValidatorOutput(cliCtx, validator) + if res, err = codec.MarshalJSONIndent(cdc, validatorOutput); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } -// gets a validator given an AccAddress -func getValidatorFromAccAdrr(address sdk.AccAddress, validatorKVs []sdk.KVPair, cliCtx context.CLIContext, cdc *wire.Codec) (stakeClient.ValidatorOutput, error) { - // parse out the validators - for _, kv := range validatorKVs { - addr := kv.Key[1:] - validator, err := types.UnmarshalValidator(cdc, addr, kv.Value) - if err != nil { - return stakeClient.ValidatorOutput{}, err - } + case "custom/stake/validatorUnbondingDelegations": + var unbondingDelegations []types.UnbondingDelegation + if err = cdc.UnmarshalJSON(res, &unbondingDelegations); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + unbondingDelegationsOutputs := make([]stakeClient.UnbondingDelegationOutput, len(unbondingDelegations)) + for index, unbondingDelegation := range unbondingDelegations { + unbondingDelegationOutput := stakeClient.ConvertUBDToUBDOutput(cliCtx, unbondingDelegation) + unbondingDelegationsOutputs[index] = unbondingDelegationOutput + } - ownerAddress := validator.Owner - if bytes.Equal(ownerAddress.Bytes(), address.Bytes()) { - validatorOutput, err := stakeClient.ConvertValidatorToValidatorOutput(cliCtx, validator) - if err != nil { - return stakeClient.ValidatorOutput{}, err + if res, err = codec.MarshalJSONIndent(cdc, unbondingDelegationsOutputs); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return } - return validatorOutput, nil - } - } - return stakeClient.ValidatorOutput{}, errors.Errorf("Couldn't find validator") -} + case "custom/stake/validatorRedelegations": + var relegations []types.Redelegation + if err = cdc.UnmarshalJSON(res, &relegations); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } -// gets all Bech32 validators from a key -func getValidatorOutputs(storeName string, cliCtx context.CLIContext, cdc *wire.Codec) ( - validators []stakeClient.ValidatorOutput, httpStatusCode int, errMsg string, err error) { - // Get all validators using key - kvs, err := cliCtx.QuerySubspace(stake.ValidatorsKey, storeName) - if err != nil { - return nil, http.StatusInternalServerError, "couldn't query validators. Error: ", err - } + relegationsOutputs := make([]stakeClient.RedelegationOutput, len(relegations)) + for index, relegation := range relegations { + relegationOutput := stakeClient.ConvertREDToREDOutput(cliCtx, relegation) + relegationsOutputs[index] = relegationOutput + } - // the query will return empty if there are no validators - if len(kvs) == 0 { - return nil, http.StatusNoContent, "", nil - } + if res, err = codec.MarshalJSONIndent(cdc, relegationsOutputs); err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + } - validators, err = getValidators(cliCtx, cdc, kvs) - if err != nil { - return nil, http.StatusInternalServerError, "Error: ", err + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) } - return validators, http.StatusOK, "", nil } diff --git a/client/stake/common.go b/client/stake/utils.go similarity index 51% rename from client/stake/common.go rename to client/stake/utils.go index 2f9aae70e..9a88c25c7 100644 --- a/client/stake/common.go +++ b/client/stake/utils.go @@ -2,17 +2,19 @@ package stake import ( "fmt" + "time" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/stake" - "github.com/irisnet/irishub/app" + "github.com/cosmos/cosmos-sdk/x/stake/types" "github.com/irisnet/irishub/client/context" - "time" + "github.com/irisnet/irishub/client/utils" ) // defines a delegation without type Rat for shares type DelegationOutput struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` - ValidatorAddr sdk.AccAddress `json:"validator_addr"` + ValidatorAddr sdk.ValAddress `json:"validator_addr"` Shares string `json:"shares"` Height int64 `json:"height"` } @@ -21,7 +23,7 @@ func (d DelegationOutput) HumanReadableString() (string, error) { resp := "Delegation \n" resp += fmt.Sprintf("Delegator: %s\n", d.DelegatorAddr) resp += fmt.Sprintf("Validator: %s\n", d.ValidatorAddr) - resp += fmt.Sprintf("Shares: %s", d.Shares) + resp += fmt.Sprintf("Shares: %s\n", d.Shares) resp += fmt.Sprintf("Height: %d", d.Height) return resp, nil @@ -30,7 +32,7 @@ func (d DelegationOutput) HumanReadableString() (string, error) { // UnbondingDelegation reflects a delegation's passive unbonding queue. type UnbondingDelegationOutput struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` // delegator - ValidatorAddr sdk.AccAddress `json:"validator_addr"` // validator unbonding from owner addr + ValidatorAddr sdk.ValAddress `json:"validator_addr"` // validator unbonding from owner addr CreationHeight int64 `json:"creation_height"` // height which the unbonding took place MinTime time.Time `json:"min_time"` // unix time for unbonding completion InitialBalance string `json:"initial_balance"` // atoms initially scheduled to receive at completion @@ -51,14 +53,14 @@ func (d UnbondingDelegationOutput) HumanReadableString() (string, error) { type RedelegationOutput struct { DelegatorAddr sdk.AccAddress `json:"delegator_addr"` // delegator - ValidatorSrcAddr sdk.AccAddress `json:"validator_src_addr"` // validator redelegation source owner addr - ValidatorDstAddr sdk.AccAddress `json:"validator_dst_addr"` // validator redelegation destination owner addr + ValidatorSrcAddr sdk.ValAddress `json:"validator_src_addr"` // validator redelegation source owner addr + ValidatorDstAddr sdk.ValAddress `json:"validator_dst_addr"` // validator redelegation destination owner addr CreationHeight int64 `json:"creation_height"` // height which the redelegation took place MinTime time.Time `json:"min_time"` // unix time for redelegation completion InitialBalance string `json:"initial_balance"` // initial balance when redelegation started Balance string `json:"balance"` // current balance - SharesSrc sdk.Rat `json:"shares_src"` // amount of source shares redelegating - SharesDst sdk.Rat `json:"shares_dst"` // amount of destination shares redelegating + SharesSrc string `json:"shares_src"` // amount of source shares redelegating + SharesDst string `json:"shares_dst"` // amount of destination shares redelegating } func (d RedelegationOutput) HumanReadableString() (string, error) { @@ -68,105 +70,105 @@ func (d RedelegationOutput) HumanReadableString() (string, error) { resp += fmt.Sprintf("Destination Validator: %s\n", d.ValidatorDstAddr) resp += fmt.Sprintf("Creation height: %v\n", d.CreationHeight) resp += fmt.Sprintf("Min time to unbond (unix): %v\n", d.MinTime) - resp += fmt.Sprintf("Source shares: %s", d.SharesSrc.String()) - resp += fmt.Sprintf("Destination shares: %s", d.SharesDst.String()) + resp += fmt.Sprintf("Source shares: %s\n", d.SharesSrc) + resp += fmt.Sprintf("Destination shares: %s", d.SharesDst) return resp, nil } -type ValidatorOutput struct { - Owner sdk.AccAddress `json:"owner"` // in bech32 - PubKey string `json:"pub_key"` // in bech32 - Revoked bool `json:"revoked"` // has the validator been revoked from bonded status? - - Status sdk.BondStatus `json:"status"` // validator status (bonded/unbonding/unbonded) - Tokens string `json:"tokens"` // delegated tokens (incl. self-delegation) - DelegatorShares string `json:"delegator_shares"` // total shares issued to a validator's delegators - - Description stake.Description `json:"description"` // description terms for the validator - BondHeight int64 `json:"bond_height"` // earliest height as a bonded validator - BondIntraTxCounter int16 `json:"bond_intra_tx_counter"` // block-local tx index of validator change - ProposerRewardPool []string `json:"proposer_reward_pool"` // XXX reward pool collected from being the proposer - - Commission sdk.Rat `json:"commission"` // XXX the commission rate of fees charged to any delegators - CommissionMax sdk.Rat `json:"commission_max"` // XXX maximum commission rate which this validator can ever charge - CommissionChangeRate sdk.Rat `json:"commission_change_rate"` // XXX maximum daily increase of the validator commission - CommissionChangeToday sdk.Rat `json:"commission_change_today"` // XXX commission rate change today, reset each day (UTC time) +type Commission struct { + Rate string `json:"rate"` + MaxRate string `json:"max_rate"` + MaxChangeRate string `json:"max_change_rate"` + UpdateTime time.Time `json:"update_time"` +} - // fee related - LastBondedTokens sdk.Rat `json:"prev_bonded_tokens"` // last bonded token amount +type ValidatorOutput struct { + OperatorAddr sdk.ValAddress `json:"operator_address"` + ConsPubKey string `json:"consensus_pubkey"` + Jailed bool `json:"jailed"` + Status sdk.BondStatus `json:"status"` + Tokens string `json:"tokens"` + DelegatorShares string `json:"delegator_shares"` + Description stake.Description `json:"description"` + BondHeight int64 `json:"bond_height"` + BondIntraTxCounter int16 `json:"bond_intra_tx_counter"` + UnbondingHeight int64 `json:"unbonding_height"` + UnbondingMinTime time.Time `json:"unbonding_time"` + Commission Commission `json:"commission"` } func (v ValidatorOutput) HumanReadableString() (string, error) { resp := "Validator \n" - resp += fmt.Sprintf("Owner: %s\n", v.Owner) - resp += fmt.Sprintf("Validator: %s\n", v.PubKey) - resp += fmt.Sprintf("Revoked: %v\n", v.Revoked) + resp += fmt.Sprintf("Operator Address: %s\n", v.OperatorAddr) + resp += fmt.Sprintf("Validator Consensus Pubkey: %s\n", v.ConsPubKey) + resp += fmt.Sprintf("Jailed: %v\n", v.Jailed) resp += fmt.Sprintf("Status: %s\n", sdk.BondStatusToString(v.Status)) resp += fmt.Sprintf("Tokens: %s\n", v.Tokens) resp += fmt.Sprintf("Delegator Shares: %s\n", v.DelegatorShares) resp += fmt.Sprintf("Description: %s\n", v.Description) resp += fmt.Sprintf("Bond Height: %d\n", v.BondHeight) - resp += fmt.Sprintf("Proposer Reward Pool: %s\n", v.ProposerRewardPool) - resp += fmt.Sprintf("Commission: %s\n", v.Commission.String()) - resp += fmt.Sprintf("Max Commission Rate: %s\n", v.CommissionMax.String()) - resp += fmt.Sprintf("Commission Change Rate: %s\n", v.CommissionChangeRate.String()) - resp += fmt.Sprintf("Commission Change Today: %s\n", v.CommissionChangeToday.String()) - resp += fmt.Sprintf("Previous Bonded Tokens: %s\n", v.LastBondedTokens.String()) + resp += fmt.Sprintf("Unbonding Height: %d\n", v.UnbondingHeight) + resp += fmt.Sprintf("Minimum Unbonding Time: %v\n", v.UnbondingMinTime) + resp += fmt.Sprintf("Commission: {%s}", v.Commission) return resp, nil } -func ExRateFromStakeTokenToMainUnit(cliCtx context.CLIContext) sdk.Rat { - stakeTokenDenom, err := cliCtx.GetCoinType(app.Denom) - if err != nil { - panic(err) - } - decimalDiff := stakeTokenDenom.MinUnit.Decimal - stakeTokenDenom.GetMainUnit().Decimal - exRate := sdk.NewRat(1).Quo(sdk.NewRatFromInt(sdk.NewIntWithDecimal(1, decimalDiff))) - return exRate +type PoolOutput struct { + LooseTokens string `json:"loose_tokens"` + BondedTokens string `json:"bonded_tokens"` + TokenSupply string `json:"total_supply"` + BondedRatio string `json:"bonded_ratio"` +} + +func (p PoolOutput) HumanReadableString() string { + + resp := "Pool \n" + resp += fmt.Sprintf("Loose Tokens: %s\n", p.LooseTokens) + resp += fmt.Sprintf("Bonded Tokens: %s\n", p.BondedTokens) + resp += fmt.Sprintf("Token Supply: %s\n", p.TokenSupply) + resp += fmt.Sprintf("Bonded Ratio: %v", p.BondedRatio) + return resp } -func ConvertValidatorToValidatorOutput(cliCtx context.CLIContext, v stake.Validator) (ValidatorOutput, error) { - exRate := ExRateFromStakeTokenToMainUnit(cliCtx) - poolToken, err := cliCtx.ConvertCoinToMainUnit(v.ProposerRewardPool.String()) +func ConvertValidatorToValidatorOutput(cliCtx context.CLIContext, v stake.Validator) ValidatorOutput { + exRate := utils.ExRateFromStakeTokenToMainUnit(cliCtx) + + bechValPubkey, err := sdk.Bech32ifyValPub(v.ConsPubKey) if err != nil { - return ValidatorOutput{}, err + panic(err) } - bechValPubkey, err := sdk.Bech32ifyValPub(v.PubKey) - if err != nil { - return ValidatorOutput{}, err + + commission := Commission{ + Rate: utils.ConvertDecToRat(v.Commission.Rate).FloatString(), + MaxRate: utils.ConvertDecToRat(v.Commission.MaxRate).FloatString(), + MaxChangeRate: utils.ConvertDecToRat(v.Commission.MaxChangeRate).FloatString(), + UpdateTime: v.Commission.UpdateTime, } return ValidatorOutput{ - Owner: v.Owner, - PubKey: bechValPubkey, - Revoked: v.Revoked, - - Status: v.Status, - Tokens: v.Tokens.Mul(exRate).FloatString(), - DelegatorShares: v.DelegatorShares.Mul(exRate).FloatString(), - + OperatorAddr: v.OperatorAddr, + ConsPubKey: bechValPubkey, + Jailed: v.Jailed, + Status: v.Status, + Tokens: utils.ConvertDecToRat(v.Tokens).Mul(exRate).FloatString(), + DelegatorShares: utils.ConvertDecToRat(v.DelegatorShares).Mul(exRate).FloatString(), Description: v.Description, - BondHeight: v.BondHeight, + BondHeight: v.UnbondingHeight, BondIntraTxCounter: v.BondIntraTxCounter, - ProposerRewardPool: poolToken, - - Commission: v.Commission, - CommissionMax: v.CommissionMax, - CommissionChangeRate: v.CommissionChangeRate, - CommissionChangeToday: v.CommissionChangeToday, - - LastBondedTokens: v.LastBondedTokens, - }, nil + UnbondingHeight: v.UnbondingHeight, + UnbondingMinTime: v.UnbondingMinTime, + Commission: commission, + } } func ConvertDelegationToDelegationOutput(cliCtx context.CLIContext, delegation stake.Delegation) DelegationOutput { - exRate := ExRateFromStakeTokenToMainUnit(cliCtx) + exRate := utils.ExRateFromStakeTokenToMainUnit(cliCtx) return DelegationOutput{ DelegatorAddr: delegation.DelegatorAddr, ValidatorAddr: delegation.ValidatorAddr, - Shares: delegation.Shares.Mul(exRate).FloatString(), + Shares: utils.ConvertDecToRat(delegation.Shares).Mul(exRate).FloatString(), Height: delegation.Height, } } @@ -191,7 +193,7 @@ func ConvertUBDToUBDOutput(cliCtx context.CLIContext, ubd stake.UnbondingDelegat } func ConvertREDToREDOutput(cliCtx context.CLIContext, red stake.Redelegation) RedelegationOutput { - exRate := ExRateFromStakeTokenToMainUnit(cliCtx) + exRate := utils.ExRateFromStakeTokenToMainUnit(cliCtx) initialBalance, err := cliCtx.ConvertCoinToMainUnit(sdk.Coins{red.InitialBalance}.String()) if err != nil && len(initialBalance) != 1 { panic(err) @@ -208,7 +210,41 @@ func ConvertREDToREDOutput(cliCtx context.CLIContext, red stake.Redelegation) Re MinTime: red.MinTime, InitialBalance: initialBalance[0], Balance: balance[0], - SharesSrc: red.SharesSrc.Mul(exRate), - SharesDst: red.SharesDst.Mul(exRate), + SharesSrc: utils.ConvertDecToRat(red.SharesSrc).Mul(exRate).FloatString(), + SharesDst: utils.ConvertDecToRat(red.SharesDst).Mul(exRate).FloatString(), + } +} + +func ConvertPoolToPoolOutput(cliCtx context.CLIContext, pool stake.Pool) PoolOutput { + exRate := utils.ExRateFromStakeTokenToMainUnit(cliCtx) + return PoolOutput{ + LooseTokens: utils.ConvertDecToRat(pool.LooseTokens).Mul(exRate).FloatString(), + BondedTokens: utils.ConvertDecToRat(pool.BondedTokens).Mul(exRate).FloatString(), + TokenSupply: utils.ConvertDecToRat(pool.BondedTokens.Add(pool.LooseTokens)).Mul(exRate).FloatString(), + BondedRatio: utils.ConvertDecToRat(pool.BondedTokens.Quo(pool.BondedTokens.Add(pool.LooseTokens))).FloatString(), + } +} + +func BuildCommissionMsg(rateStr, maxRateStr, maxChangeRateStr string) (commission types.CommissionMsg, err error) { + if rateStr == "" || maxRateStr == "" || maxChangeRateStr == "" { + return commission, fmt.Errorf("must specify all validator commission parameters") } + + rate, err := sdk.NewDecFromStr(rateStr) + if err != nil { + return commission, err + } + + maxRate, err := sdk.NewDecFromStr(maxRateStr) + if err != nil { + return commission, err + } + + maxChangeRate, err := sdk.NewDecFromStr(maxChangeRateStr) + if err != nil { + return commission, err + } + + commission = types.NewCommissionMsg(rate, maxRate, maxChangeRate) + return commission, nil } diff --git a/client/tendermint/rpc/block.go b/client/tendermint/rpc/block.go index 52d396e99..abedaf024 100644 --- a/client/tendermint/rpc/block.go +++ b/client/tendermint/rpc/block.go @@ -9,6 +9,7 @@ import ( tmliteProxy "github.com/tendermint/tendermint/lite/proxy" "net/http" "strconv" + "github.com/irisnet/irishub/client/utils" ) //BlockCommand returns the verified block data for a given heights @@ -42,7 +43,7 @@ func getBlock(cliCtx context.CLIContext, height *int64) ([]byte, error) { } if !cliCtx.TrustNode { - check, err := cliCtx.Certify(res.Block.Height) + check, err := cliCtx.Verify(res.Block.Height) if err != nil { return nil, err } @@ -58,13 +59,10 @@ func getBlock(cliCtx context.CLIContext, height *int64) ([]byte, error) { } } - // TODO move maarshalling into cmd/rest functions - // output, err := tmcodec.MarshalJSON(res) - output, err := cdc.MarshalJSONIndent(res, "", " ") - if err != nil { - return nil, err + if cliCtx.Indent { + return cdc.MarshalJSONIndent(res, "", " ") } - return output, nil + return cdc.MarshalJSON(res) } // get the current blockchain height @@ -111,23 +109,23 @@ func BlockRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { vars := mux.Vars(r) height, err := strconv.ParseInt(vars["height"], 10, 64) if err != nil { - w.WriteHeader(400) + w.WriteHeader(http.StatusBadRequest) w.Write([]byte("ERROR: Couldn't parse block height. Assumed format is '/block/{height}'.")) return } chainHeight, err := GetChainHeight(cliCtx) if height > chainHeight { - w.WriteHeader(404) + w.WriteHeader(http.StatusNotFound) w.Write([]byte("ERROR: Requested block height is bigger then the chain length.")) return } output, err := getBlock(cliCtx, &height) if err != nil { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } - w.Write(output) + utils.PostProcessResponse(w, cdc, output, cliCtx.Indent) } } @@ -136,16 +134,16 @@ func LatestBlockRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { height, err := GetChainHeight(cliCtx) if err != nil { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } output, err := getBlock(cliCtx, &height) if err != nil { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } - w.Write(output) + utils.PostProcessResponse(w, cdc, output, cliCtx.Indent) } } diff --git a/client/tendermint/rpc/wire.go b/client/tendermint/rpc/codec.go similarity index 100% rename from client/tendermint/rpc/wire.go rename to client/tendermint/rpc/codec.go diff --git a/client/tendermint/rpc/rest.go b/client/tendermint/rpc/rest.go index 733e76391..c3e590b3c 100644 --- a/client/tendermint/rpc/rest.go +++ b/client/tendermint/rpc/rest.go @@ -1,13 +1,13 @@ package rpc import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/gorilla/mux" "github.com/irisnet/irishub/client/context" ) // register REST routes -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Codec) { +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { r.HandleFunc("/node_info", NodeInfoRequestHandlerFn(cliCtx)).Methods("GET") r.HandleFunc("/syncing", NodeSyncingRequestHandlerFn(cliCtx)).Methods("GET") r.HandleFunc("/blocks/latest", LatestBlockRequestHandlerFn(cliCtx)).Methods("GET") diff --git a/client/tendermint/rpc/status.go b/client/tendermint/rpc/status.go index 7f00cd069..33bf6345f 100644 --- a/client/tendermint/rpc/status.go +++ b/client/tendermint/rpc/status.go @@ -7,7 +7,8 @@ import ( "github.com/spf13/cobra" ctypes "github.com/tendermint/tendermint/rpc/core/types" "net/http" - "strconv" + "github.com/spf13/viper" + "github.com/irisnet/irishub/client/utils" ) func StatusCommand() *cobra.Command { @@ -22,7 +23,7 @@ func StatusCommand() *cobra.Command { return cmd } -func GetNodeStatus(cliCtx context.CLIContext) (*ctypes.ResultStatus, error) { +func getNodeStatus(cliCtx context.CLIContext) (*ctypes.ResultStatus, error) { // get the node node, err := cliCtx.GetNode() if err != nil { @@ -35,13 +36,20 @@ func GetNodeStatus(cliCtx context.CLIContext) (*ctypes.ResultStatus, error) { // CMD func printNodeStatus(cmd *cobra.Command, args []string) error { - status, err := GetNodeStatus(context.NewCLIContext()) + // No need to verify proof in getting node status + viper.Set(client.FlagTrustNode, true) + cliCtx := context.NewCLIContext() + status, err := getNodeStatus(cliCtx) if err != nil { return err } - output, err := cdc.MarshalJSON(status) - // output, err := cdc.MarshalJSONIndent(res, " ", "") + var output []byte + if cliCtx.Indent { + output, err = cdc.MarshalJSONIndent(status, "", " ") + } else { + output, err = cdc.MarshalJSON(status) + } if err != nil { return err } @@ -53,42 +61,42 @@ func printNodeStatus(cmd *cobra.Command, args []string) error { // REST handler for node info func NodeInfoRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - status, err := GetNodeStatus(cliCtx) + status, err := getNodeStatus(cliCtx) if err != nil { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } nodeInfo := status.NodeInfo - output, err := cdc.MarshalJSONIndent(nodeInfo,"", " ") - if err != nil { - w.WriteHeader(500) - w.Write([]byte(err.Error())) - return - } - - w.Write(output) + utils.PostProcessResponse(w, cdc, nodeInfo, cliCtx.Indent) } } +type nodeStaus struct { + Syncing bool `json:"syncing"` +} // REST handler for node syncing func NodeSyncingRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - status, err := GetNodeStatus(cliCtx) + status, err := getNodeStatus(cliCtx) if err != nil { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } syncing := status.SyncInfo.CatchingUp if err != nil { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } - w.Write([]byte(strconv.FormatBool(syncing))) + nodeStaus := nodeStaus{ + Syncing: syncing, + } + + utils.PostProcessResponse(w, cdc, nodeStaus, cliCtx.Indent) } } diff --git a/client/tendermint/rpc/validatorset.go b/client/tendermint/rpc/validatorset.go index a1fe4393e..5efc194ae 100644 --- a/client/tendermint/rpc/validatorset.go +++ b/client/tendermint/rpc/validatorset.go @@ -13,6 +13,7 @@ import ( "github.com/irisnet/irishub/client/context" tmtypes "github.com/tendermint/tendermint/types" "net/http" + "github.com/irisnet/irishub/client/utils" ) // TODO these next two functions feel kinda hacky based on their placement @@ -73,12 +74,12 @@ func getValidators(cliCtx context.CLIContext, height *int64) ([]byte, error) { } if !cliCtx.TrustNode { - check, err := cliCtx.Certify(validatorsRes.BlockHeight) + check, err := cliCtx.Verify(validatorsRes.BlockHeight) if err != nil { return nil, err } - if !bytes.Equal(check.ValidatorsHash(), tmtypes.NewValidatorSet(validatorsRes.Validators).Hash()) { + if !bytes.Equal(check.ValidatorsHash, tmtypes.NewValidatorSet(validatorsRes.Validators).Hash()) { return nil, fmt.Errorf("got invalid validatorset") } } @@ -95,12 +96,10 @@ func getValidators(cliCtx context.CLIContext, height *int64) ([]byte, error) { } } - output, err := cdc.MarshalJSONIndent(outputValidatorsRes, "", " ") - if err != nil { - return nil, err + if cliCtx.Indent { + return cdc.MarshalJSONIndent(outputValidatorsRes, "", " ") } - - return output, nil + return cdc.MarshalJSON(outputValidatorsRes) } // CMD @@ -135,26 +134,26 @@ func ValidatorSetRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { height, err := strconv.ParseInt(vars["height"], 10, 64) if err != nil { - w.WriteHeader(400) + w.WriteHeader(http.StatusBadRequest) w.Write([]byte("ERROR: Couldn't parse block height. Assumed format is '/validatorsets/{height}'.")) return } chainHeight, err := GetChainHeight(cliCtx) if height > chainHeight { - w.WriteHeader(404) + w.WriteHeader(http.StatusNotFound) w.Write([]byte("ERROR: Requested block height is bigger then the chain length.")) return } output, err := getValidators(cliCtx, &height) if err != nil { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } - w.Write(output) + utils.PostProcessResponse(w, cdc, output, cliCtx.Indent) } } @@ -163,18 +162,18 @@ func LatestValidatorSetRequestHandlerFn(cliCtx context.CLIContext) http.HandlerF return func(w http.ResponseWriter, r *http.Request) { height, err := GetChainHeight(cliCtx) if err != nil { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } output, err := getValidators(cliCtx, &height) if err != nil { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } - w.Write(output) + utils.PostProcessResponse(w, cdc, output, cliCtx.Indent) } } diff --git a/client/tendermint/tx/broadcast.go b/client/tendermint/tx/broadcast.go new file mode 100644 index 000000000..4877d6535 --- /dev/null +++ b/client/tendermint/tx/broadcast.go @@ -0,0 +1,60 @@ +package tx + +import ( + "net/http" + "io/ioutil" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/irisnet/irishub/client/context" + "github.com/irisnet/irishub/client/utils" +) + +const ( + // Returns with the response from CheckTx. + flagSync = "sync" + // Returns right away, with no response + flagAsync = "async" + // Only returns error if mempool.BroadcastTx errs (ie. problem with the app) or if we timeout waiting for tx to commit. + flagBlock = "block" +) + +// BroadcastBody Tx Broadcast Body +type BroadcastBody struct { + TxBytes []byte `json:"tx"` + Return string `json:"return"` +} + +// BroadcastTxRequest REST Handler +// nolint: gocyclo +func BroadcastTxRequest(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var m BroadcastBody + body, err := ioutil.ReadAll(r.Body) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + err = cdc.UnmarshalJSON(body, &m) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + var res interface{} + switch m.Return { + case flagBlock: + res, err = cliCtx.BroadcastTx(m.TxBytes) + case flagSync: + res, err = cliCtx.BroadcastTxSync(m.TxBytes) + case flagAsync: + res, err = cliCtx.BroadcastTxAsync(m.TxBytes) + default: + utils.WriteErrorResponse(w, http.StatusInternalServerError, "unsupported return type. supported types: block, sync, async") + return + } + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) + } +} diff --git a/client/tendermint/tx/querytx.go b/client/tendermint/tx/querytx.go index 74254712f..3cc9cb82a 100644 --- a/client/tendermint/tx/querytx.go +++ b/client/tendermint/tx/querytx.go @@ -4,7 +4,7 @@ import ( "encoding/hex" "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/gorilla/mux" "github.com/irisnet/irishub/client" @@ -14,10 +14,11 @@ import ( "github.com/tendermint/tendermint/libs/common" ctypes "github.com/tendermint/tendermint/rpc/core/types" "net/http" + "github.com/irisnet/irishub/client/utils" ) // QueryTxCmd implements the default command for a tx query. -func QueryTxCmd(cdc *wire.Codec) *cobra.Command { +func QueryTxCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "tx [hash]", Short: "Matches this txhash over all committed blocks", @@ -45,7 +46,7 @@ func QueryTxCmd(cdc *wire.Codec) *cobra.Command { return cmd } -func queryTx(cdc *wire.Codec, cliCtx context.CLIContext, hashHexStr string) ([]byte, error) { +func queryTx(cdc *codec.Codec, cliCtx context.CLIContext, hashHexStr string) ([]byte, error) { hash, err := hex.DecodeString(hashHexStr) if err != nil { return nil, err @@ -73,12 +74,15 @@ func queryTx(cdc *wire.Codec, cliCtx context.CLIContext, hashHexStr string) ([]b return nil, err } - return cdc.MarshalJSONIndent(info, "", " ") + if cliCtx.Indent { + return cdc.MarshalJSONIndent(info, "", " ") + } + return cdc.MarshalJSON(info) } // ValidateTxResult performs transaction verification func ValidateTxResult(cliCtx context.CLIContext, res *ctypes.ResultTx) error { - check, err := cliCtx.Certify(res.Height) + check, err := cliCtx.Verify(res.Height) if err != nil { return err } @@ -90,7 +94,7 @@ func ValidateTxResult(cliCtx context.CLIContext, res *ctypes.ResultTx) error { return nil } -func formatTxResult(cdc *wire.Codec, res *ctypes.ResultTx) (Info, error) { +func formatTxResult(cdc *codec.Codec, res *ctypes.ResultTx) (Info, error) { tx, err := parseTx(cdc, res.Tx) if err != nil { return Info{}, err @@ -112,10 +116,10 @@ type Info struct { Result abci.ResponseDeliverTx `json:"result"` } -func parseTx(cdc *wire.Codec, txBytes []byte) (sdk.Tx, error) { +func parseTx(cdc *codec.Codec, txBytes []byte) (sdk.Tx, error) { var tx auth.StdTx - err := cdc.UnmarshalBinary(txBytes, &tx) + err := cdc.UnmarshalBinaryLengthPrefixed(txBytes, &tx) if err != nil { return nil, err } @@ -124,18 +128,18 @@ func parseTx(cdc *wire.Codec, txBytes []byte) (sdk.Tx, error) { } // transaction query REST handler -func QueryTxRequestHandlerFn(cdc *wire.Codec, cliCtx context.CLIContext) http.HandlerFunc { +func QueryTxRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) hashHexStr := vars["hash"] output, err := queryTx(cdc, cliCtx, hashHexStr) if err != nil { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } - w.Write(output) + utils.PostProcessResponse(w, cdc, output, cliCtx.Indent) } } diff --git a/client/tendermint/tx/rest.go b/client/tendermint/tx/rest.go index 776146a54..4f8d76afd 100644 --- a/client/tendermint/tx/rest.go +++ b/client/tendermint/tx/rest.go @@ -1,14 +1,14 @@ package tx import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/gorilla/mux" "github.com/irisnet/irishub/client/context" ) // register REST routes -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Codec) { +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { r.HandleFunc("/txs/{hash}", QueryTxRequestHandlerFn(cdc, cliCtx)).Methods("GET") r.HandleFunc("/txs", SearchTxRequestHandlerFn(cliCtx, cdc)).Methods("GET") - r.HandleFunc("/txs/send", SendTxRequestHandlerFn(cliCtx, cdc)).Methods("POST") + r.HandleFunc("/txs", BroadcastTxRequest(cliCtx, cdc)).Methods("POST") } diff --git a/client/tendermint/tx/searchtx.go b/client/tendermint/tx/searchtx.go index 870afb1dc..6a3671a1a 100644 --- a/client/tendermint/tx/searchtx.go +++ b/client/tendermint/tx/searchtx.go @@ -8,10 +8,11 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" "github.com/irisnet/irishub/client" "github.com/irisnet/irishub/client/context" + "github.com/irisnet/irishub/client/utils" ctypes "github.com/tendermint/tendermint/rpc/core/types" "net/http" "net/url" @@ -20,10 +21,12 @@ import ( const ( flagTags = "tag" flagAny = "any" + flagPage = "page" + flagSize = "size" ) // default client command to search through tagged transactions -func SearchTxCmd(cdc *wire.Codec) *cobra.Command { +func SearchTxCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "txs", Short: "Search for all transactions that match the given tags.", @@ -33,26 +36,32 @@ passed to the --tags option. To match any transaction, use the --any option. For example: -$ gaiacli tendermint txs --tag test1,test2 +$ iriscli tendermint txs --tag test1,test2 will match any transaction tagged with both test1,test2. To match a transaction tagged with either test1 or test2, use: -$ gaiacli tendermint txs --tag test1,test2 --any +$ iriscli tendermint txs --tag test1,test2 --any `), RunE: func(cmd *cobra.Command, args []string) error { tags := viper.GetStringSlice(flagTags) - + page := viper.GetInt(flagPage) + size := viper.GetInt(flagSize) + if page < 0 || size < 0 { + return fmt.Errorf("page or size should not be negative") + } cliCtx := context.NewCLIContext().WithCodec(cdc) - txs, err := searchTxs(cliCtx, cdc, tags) + txs, err := searchTxs(cliCtx, cdc, tags, page, size) if err != nil { return err } - output, err := cdc.MarshalJSONIndent(txs, "", " ") - if err != nil { - return err + var output []byte + if cliCtx.Indent { + output, err = cdc.MarshalJSONIndent(txs, "", " ") + } else { + output, err = cdc.MarshalJSON(txs) } fmt.Println(string(output)) @@ -65,10 +74,12 @@ $ gaiacli tendermint txs --tag test1,test2 --any cmd.Flags().String(client.FlagChainID, "", "Chain ID of Tendermint node") cmd.Flags().StringSlice(flagTags, nil, "Comma-separated list of tags that must match") cmd.Flags().Bool(flagAny, false, "Return transactions that match ANY tag, rather than ALL") + cmd.Flags().Int(flagPage, 0, "Pagination page") + cmd.Flags().Int(flagSize, 100, "Pagination size") return cmd } -func searchTxs(cliCtx context.CLIContext, cdc *wire.Codec, tags []string) ([]Info, error) { +func searchTxs(cliCtx context.CLIContext, cdc *codec.Codec, tags []string, page, size int) ([]Info, error) { if len(tags) == 0 { return nil, errors.New("must declare at least one tag to search") } @@ -84,10 +95,7 @@ func searchTxs(cliCtx context.CLIContext, cdc *wire.Codec, tags []string) ([]Inf prove := !cliCtx.TrustNode - // TODO: take these as args - page := 0 - perPage := 100 - res, err := node.TxSearch(query, prove, page, perPage) + res, err := node.TxSearch(query, prove, page, size) if err != nil { return nil, err } @@ -110,7 +118,7 @@ func searchTxs(cliCtx context.CLIContext, cdc *wire.Codec, tags []string) ([]Inf } // parse the indexed txs into an array of Info -func FormatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]Info, error) { +func FormatTxResults(cdc *codec.Codec, res []*ctypes.ResultTx) ([]Info, error) { var err error out := make([]Info, len(res)) for i := range res { @@ -123,21 +131,26 @@ func FormatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]Info, error) { } // Search Tx REST Handler -func SearchTxRequestHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { +func SearchTxRequestHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { tag := r.FormValue("tag") if tag == "" { - w.WriteHeader(400) + w.WriteHeader(http.StatusBadRequest) w.Write([]byte("You need to provide at least a tag as a key=value pair to search for. Postfix the key with _bech32 to search bech32-encoded addresses or public keys")) return } keyValue := strings.Split(tag, "=") - key := keyValue[0] + if len(keyValue) != 2 { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("Invalid tag, tag pattern should be something like key=value pair")) + return + } + key := keyValue[0] value, err := url.QueryUnescape(keyValue[1]) if err != nil { - w.WriteHeader(400) + w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Could not decode address: " + err.Error())) return } @@ -147,17 +160,40 @@ func SearchTxRequestHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.H prefix := strings.Split(bech32address, "1")[0] bz, err := sdk.GetFromBech32(bech32address, prefix) if err != nil { - w.WriteHeader(400) + w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } tag = strings.TrimRight(key, "_bech32") + "='" + sdk.AccAddress(bz).String() + "'" } + pageString := r.FormValue("page") + sizeString := r.FormValue("size") + page := int64(0) + size := int64(100) + if pageString != "" { + var ok bool + page, ok = utils.ParseInt64OrReturnBadRequest(w, pageString) + if !ok { + return + } + } + if sizeString != "" { + var ok bool + size, ok = utils.ParseInt64OrReturnBadRequest(w, sizeString) + if !ok { + return + } + } + if page < 0 || size < 0 { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("page or size should not be negative")) + return + } - txs, err := searchTxs(cliCtx, cdc, []string{tag}) + txs, err := searchTxs(cliCtx, cdc, []string{tag}, int(page), int(size)) if err != nil { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } @@ -167,13 +203,6 @@ func SearchTxRequestHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.H return } - output, err := cdc.MarshalJSON(txs) - if err != nil { - w.WriteHeader(500) - w.Write([]byte(err.Error())) - return - } - - w.Write(output) + utils.PostProcessResponse(w, cdc, txs, cliCtx.Indent) } } diff --git a/client/tendermint/tx/sendtx.go b/client/tendermint/tx/sendtx.go deleted file mode 100644 index 3232e2afe..000000000 --- a/client/tendermint/tx/sendtx.go +++ /dev/null @@ -1,95 +0,0 @@ -package tx - -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/irisnet/irishub/client/context" - "github.com/irisnet/irishub/client/utils" - "github.com/tendermint/tendermint/crypto" - "io/ioutil" - "net/http" -) - -type sendTx struct { - Msgs []string `json:"msgs"` - Fee auth.StdFee `json:"fee"` - Signatures []stdSignature `json:"signatures"` - Memo string `json:"memo"` -} - -type stdSignature struct { - PubKey []byte `json:"pub_key"` // optional - Signature []byte `json:"signature"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` -} - -func SendTxRequestHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var sendTxBody sendTx - body, err := ioutil.ReadAll(r.Body) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - err = json.Unmarshal(body, &sendTxBody) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - cliCtx.Async = utils.AsyncOnlyArg(r) - - var sig = make([]auth.StdSignature, len(sendTxBody.Signatures)) - for index, s := range sendTxBody.Signatures { - var pubkey crypto.PubKey - if err := cdc.UnmarshalBinaryBare(s.PubKey, &pubkey); err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - sig[index].PubKey = pubkey - sig[index].Signature = s.Signature - sig[index].AccountNumber = s.AccountNumber - sig[index].Sequence = s.Sequence - } - - var msgs = make([]sdk.Msg, len(sendTxBody.Msgs)) - for index, msgS := range sendTxBody.Msgs { - var data = []byte(msgS) - var msg sdk.Msg - if err := cdc.UnmarshalJSON(data, &msg); err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - msgs[index] = msg - } - - var stdTx = auth.StdTx{ - Msgs: msgs, - Fee: sendTxBody.Fee, - Signatures: sig, - Memo: sendTxBody.Memo, - } - txBytes, err := cdc.MarshalBinary(stdTx) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - var res interface{} - if cliCtx.Async { - res, err = cliCtx.BroadcastTxAsync(txBytes) - } else { - res, err = cliCtx.BroadcastTx(txBytes) - } - - output, err := cdc.MarshalJSONIndent(res, "", " ") - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - w.Write(output) - } -} diff --git a/client/upgrade/cli/query.go b/client/upgrade/cli/query.go index e436e17fd..ee35455a8 100644 --- a/client/upgrade/cli/query.go +++ b/client/upgrade/cli/query.go @@ -3,7 +3,7 @@ package cli import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/irisnet/irishub/client/context" upgcli "github.com/irisnet/irishub/client/upgrade" @@ -13,9 +13,10 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" "os" + "github.com/irisnet/irishub/iparam" ) -func GetInfoCmd(storeName string, cdc *wire.Codec) *cobra.Command { +func GetInfoCmd(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "info", Short: "query the information of upgrade module", @@ -27,24 +28,24 @@ func GetInfoCmd(storeName string, cdc *wire.Codec) *cobra.Command { WithLogger(os.Stdout). WithAccountDecoder(authcmd.GetAccountDecoder(cdc)) - res_height, _ := cliCtx.QueryStore([]byte(upgradeparams.ProposalAcceptHeightParameter.GetStoreKey()), "params") - res_proposalID, _ := cliCtx.QueryStore([]byte(upgradeparams.CurrentUpgradeProposalIdParameter.GetStoreKey()), "params") + res_height, _ := cliCtx.QueryStore(append([]byte(iparam.SignalParamspace + "/"), upgradeparams.ProposalAcceptHeightParameter.GetStoreKey()...), "params") + res_proposalID, _ := cliCtx.QueryStore(append([]byte(iparam.SignalParamspace + "/"), upgradeparams.CurrentUpgradeProposalIdParameter.GetStoreKey()...), "params") var height int64 - var proposalID int64 - cdc.MustUnmarshalBinary(res_height, &height) - cdc.MustUnmarshalBinary(res_proposalID, &proposalID) + var proposalID uint64 + cdc.UnmarshalJSON(res_height, &height) + cdc.UnmarshalJSON(res_proposalID, &proposalID) res_versionID, _ := cliCtx.QueryStore(upgrade.GetCurrentVersionKey(), storeName) var versionID int64 - cdc.MustUnmarshalBinary(res_versionID, &versionID) + cdc.MustUnmarshalBinaryLengthPrefixed(res_versionID, &versionID) res_version, _ := cliCtx.QueryStore(upgrade.GetVersionIDKey(versionID), storeName) var version upgrade.Version - cdc.MustUnmarshalBinary(res_version, &version) + cdc.MustUnmarshalBinaryLengthPrefixed(res_version, &version) upgradeInfoOutput := upgcli.ConvertUpgradeInfoToUpgradeOutput(version, proposalID, height) - output, err := wire.MarshalJSONIndent(cdc, upgradeInfoOutput) + output, err := codec.MarshalJSONIndent(cdc, upgradeInfoOutput) if err != nil { return err } @@ -57,13 +58,13 @@ func GetInfoCmd(storeName string, cdc *wire.Codec) *cobra.Command { } // Command to Get a Switch Information -func GetCmdQuerySwitch(storeName string, cdc *wire.Codec) *cobra.Command { +func GetCmdQuerySwitch(storeName string, cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "query-switch", Short: "query switch details", - Example: "iriscli upgrade query-switch --proposalID 1 --voter ", + Example: "iriscli upgrade query-switch --proposal-id 1 --voter ", RunE: func(cmd *cobra.Command, args []string) error { - proposalID := viper.GetInt64(flagProposalID) + proposalID := uint64(viper.GetInt64(flagProposalID)) voterStr := viper.GetString(flagVoter) voter, err := sdk.AccAddressFromBech32(voterStr) @@ -82,8 +83,8 @@ func GetCmdQuerySwitch(storeName string, cdc *wire.Codec) *cobra.Command { } var switchMsg upgrade.MsgSwitch - cdc.MustUnmarshalBinary(res, &switchMsg) - output, err := wire.MarshalJSONIndent(cdc, switchMsg) + cdc.MustUnmarshalBinaryLengthPrefixed(res, &switchMsg) + output, err := codec.MarshalJSONIndent(cdc, switchMsg) if err != nil { return err } diff --git a/client/upgrade/cli/sendtx.go b/client/upgrade/cli/sendtx.go index 53d03d46f..10facecb5 100644 --- a/client/upgrade/cli/sendtx.go +++ b/client/upgrade/cli/sendtx.go @@ -2,7 +2,7 @@ package cli import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/utils" @@ -13,20 +13,20 @@ import ( ) const ( - flagProposalID = "proposalID" + flagProposalID = "proposal-id" flagTitle = "title" flagVoter = "voter" ) // submit switch msg -func GetCmdSubmitSwitch(cdc *wire.Codec) *cobra.Command { +func GetCmdSubmitSwitch(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "submit-switch", Short: "Submit a switch msg for a upgrade propsal", - Example: "iriscli upgrade submit-switch --chain-id= --from= --fee=0.004iris --proposalID 1 --title ", + Example: "iriscli upgrade submit-switch --chain-id=<chain-id> --from=<key name> --fee=0.004iris --proposal-id 1 --title <title>", RunE: func(cmd *cobra.Command, args []string) error { title := viper.GetString(flagTitle) - proposalID := viper.GetInt64(flagProposalID) + proposalID := uint64(viper.GetInt64(flagProposalID)) cliCtx := context.NewCLIContext(). WithCodec(cdc). diff --git a/client/upgrade/lcd/query.go b/client/upgrade/lcd/query.go index e38e632e0..921742694 100644 --- a/client/upgrade/lcd/query.go +++ b/client/upgrade/lcd/query.go @@ -1,7 +1,7 @@ package lcd import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/utils" "github.com/irisnet/irishub/modules/upgrade" @@ -16,23 +16,23 @@ type VersionInfo struct { ProposalId int64 `json:"proposal_id"` } -func InfoHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec, storeName string) http.HandlerFunc { +func InfoHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec, storeName string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { res_height, _ := cliCtx.QueryStore([]byte("gov/"+upgradeparams.ProposalAcceptHeightParameter.GetStoreKey()), "params") res_proposalID, _ := cliCtx.QueryStore([]byte("gov/"+upgradeparams.CurrentUpgradeProposalIdParameter.GetStoreKey()), "params") var height int64 var proposalID int64 - cdc.MustUnmarshalBinary(res_height, &height) - cdc.MustUnmarshalBinary(res_proposalID, &proposalID) + cdc.MustUnmarshalBinaryLengthPrefixed(res_height, &height) + cdc.MustUnmarshalBinaryLengthPrefixed(res_proposalID, &proposalID) res_versionID, _ := cliCtx.QueryStore(upgrade.GetCurrentVersionKey(), storeName) var versionID int64 - cdc.MustUnmarshalBinary(res_versionID, &versionID) + cdc.MustUnmarshalBinaryLengthPrefixed(res_versionID, &versionID) res_version, _ := cliCtx.QueryStore(upgrade.GetVersionIDKey(versionID), storeName) var version upgrade.Version - cdc.MustUnmarshalBinary(res_version, &version) + cdc.MustUnmarshalBinaryLengthPrefixed(res_version, &version) output, err := cdc.MarshalJSONIndent(version, "", " ") if err != nil { utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) diff --git a/client/upgrade/common.go b/client/upgrade/utils.go similarity index 74% rename from client/upgrade/common.go rename to client/upgrade/utils.go index 0cfbbd743..1ce932527 100644 --- a/client/upgrade/common.go +++ b/client/upgrade/utils.go @@ -5,12 +5,12 @@ import ( ) type UpgradeInfoOutput struct { - CurrentProposalId int64 `json:"current_proposal_id"` // proposalID of the proposal + CurrentProposalId uint64 `json:"current_proposal_id"` // proposalID of the proposal CurrentProposalAcceptHeight int64 `json:"current_proposal_accept_height"` Verion upgrade.Version `json:"version"` } -func ConvertUpgradeInfoToUpgradeOutput(version upgrade.Version, proposalId, hight int64) UpgradeInfoOutput { +func ConvertUpgradeInfoToUpgradeOutput(version upgrade.Version, proposalId uint64, hight int64) UpgradeInfoOutput { return UpgradeInfoOutput{ CurrentProposalId: proposalId, diff --git a/client/utils/rest.go b/client/utils/rest.go index dbec8138a..2ccbc8996 100644 --- a/client/utils/rest.go +++ b/client/utils/rest.go @@ -1,101 +1,244 @@ package utils import ( + "fmt" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys/keyerror" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/irisnet/irishub/client" "github.com/irisnet/irishub/client/context" + "io/ioutil" "net/http" "net/url" - "github.com/cosmos/cosmos-sdk/wire" - "io/ioutil" + "strconv" ) const ( - Async = "async" - GenerateOnly = "generate-only" + Async = "async" + queryArgDryRun = "simulate" + queryArgGenerateOnly = "generate-only" ) +//---------------------------------------- +// Basic HTTP utilities + // WriteErrorResponse prepares and writes a HTTP error // given a status code and an error message. -func WriteErrorResponse(w http.ResponseWriter, status int, msg string) { +func WriteErrorResponse(w http.ResponseWriter, status int, err string) { w.WriteHeader(status) - w.Write([]byte(msg)) + w.Write([]byte(err)) +} + +// WriteSimulationResponse prepares and writes an HTTP +// response for transactions simulations. +func WriteSimulationResponse(w http.ResponseWriter, gas int64) { + w.WriteHeader(http.StatusOK) + w.Write([]byte(fmt.Sprintf(`{"gas_estimate":%v}`, gas))) +} + +// HasDryRunArg returns true if the request's URL query contains the dry run +// argument and its value is set to "true". +func HasDryRunArg(r *http.Request) bool { + return urlQueryHasArg(r.URL, queryArgDryRun) +} + +// HasGenerateOnlyArg returns whether a URL's query "generate-only" parameter +// is set to "true". +func HasGenerateOnlyArg(r *http.Request) bool { + return urlQueryHasArg(r.URL, queryArgGenerateOnly) +} + +// AsyncOnlyArg returns whether a URL's query "async" parameter +func AsyncOnlyArg(r *http.Request) bool { + return urlQueryHasArg(r.URL, Async) +} + +// ParseInt64OrReturnBadRequest converts s to a int64 value. +func ParseInt64OrReturnBadRequest(w http.ResponseWriter, s string) (n int64, ok bool) { + var err error + + n, err = strconv.ParseInt(s, 10, 64) + if err != nil { + err := fmt.Errorf("'%s' is not a valid int64", s) + WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return n, false + } + + return n, true +} + +// ParseUint64OrReturnBadRequest converts s to a uint64 value. +func ParseUint64OrReturnBadRequest(w http.ResponseWriter, s string) (n uint64, ok bool) { + var err error + n, err = strconv.ParseUint(s, 10, 64) + if err != nil { + err := fmt.Errorf("'%s' is not a valid uint64", s) + WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return n, false + } + return n, true } -func ReadPostBody(w http.ResponseWriter, r *http.Request, cdc *wire.Codec, req interface{}) error { +// ParseFloat64OrReturnBadRequest converts s to a float64 value. It returns a +// default value, defaultIfEmpty, if the string is empty. +func ParseFloat64OrReturnBadRequest(w http.ResponseWriter, s string, defaultIfEmpty float64) (n float64, ok bool) { + if len(s) == 0 { + return defaultIfEmpty, true + } + + n, err := strconv.ParseFloat(s, 64) + if err != nil { + WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return n, false + } + + return n, true +} + +// WriteGenerateStdTxResponse writes response for the generate_only mode. +func WriteGenerateStdTxResponse(w http.ResponseWriter, txCtx context.TxContext, msgs []sdk.Msg) { + stdMsg, err := txCtx.Build(msgs) + if err != nil { + WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + output, err := txCtx.Codec.MarshalJSON(auth.NewStdTx(stdMsg.Msgs, stdMsg.Fee, nil, stdMsg.Memo)) + if err != nil { + WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + w.Write(output) + return +} + +func urlQueryHasArg(url *url.URL, arg string) bool { return url.Query().Get(arg) == "true" } + +// ReadPostBody +func ReadPostBody(w http.ResponseWriter, r *http.Request, cdc *codec.Codec, req interface{}) (err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("invalid post body") + WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + } + }() body, err := ioutil.ReadAll(r.Body) if err != nil { WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return err } + err = cdc.UnmarshalJSON(body, req) if err != nil { WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return err } + return nil } -func InitRequestClictx(cliCtx context.CLIContext, r *http.Request, name string, signerAddress string) context.CLIContext { - cliCtx.GenerateOnly = GenerateOnlyArg(r) +// InitReqCliCtx +func InitReqCliCtx(cliCtx context.CLIContext, r *http.Request) context.CLIContext { + cliCtx.GenerateOnly = HasGenerateOnlyArg(r) cliCtx.Async = AsyncOnlyArg(r) - cliCtx.FromAddressName = name - cliCtx.SignerAddr = signerAddress + cliCtx.DryRun = HasDryRunArg(r) return cliCtx } -func SendOrReturnUnsignedTx(w http.ResponseWriter, cliCtx context.CLIContext, txCtx context.TxContext, baseTx context.BaseTx, msgs []sdk.Msg) { +// SendOrReturnUnsignedTx implements a utility function that facilitates +// sending a series of messages in a signed transaction given a TxBuilder and a +// QueryContext. It ensures that the account exists, has a proper number and +// sequence set. In addition, it builds and signs a transaction with the +// supplied messages. Finally, it broadcasts the signed transaction to a node. +// +// NOTE: Also see SendOrPrintTx. +// NOTE: Also see x/stake/client/rest/tx.go delegationsRequestHandlerFn. +func SendOrReturnUnsignedTx(w http.ResponseWriter, cliCtx context.CLIContext, baseTx context.BaseTx, msgs []sdk.Msg) { + + simulateGas, gas, err := client.ReadGasFlag(baseTx.Gas) + if err != nil { + WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + adjustment, ok := ParseFloat64OrReturnBadRequest(w, baseTx.GasAdjustment, client.DefaultGasAdjustment) + if !ok { + return + } + + txCtx := context.TxContext{ + Codec: cliCtx.Codec, + Gas: gas, + Fee: baseTx.Fee, + GasAdjustment: adjustment, + SimulateGas: simulateGas, + ChainID: baseTx.ChainID, + AccountNumber: baseTx.AccountNumber, + Sequence: baseTx.Sequence, + } + txCtx = txCtx.WithCliCtx(cliCtx) if cliCtx.GenerateOnly { WriteGenerateStdTxResponse(w, txCtx, msgs) return } - txBytes, err := txCtx.BuildAndSign(baseTx.LocalAccountName, baseTx.Password, msgs) - if err != nil { - WriteErrorResponse(w, http.StatusUnauthorized, err.Error()) - return - } + if cliCtx.DryRun || txCtx.SimulateGas { + newTxCtx, err := EnrichCtxWithGas(txCtx, cliCtx, baseTx.Name, msgs) + if err != nil { + WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + if cliCtx.DryRun { + WriteSimulationResponse(w, newTxCtx.Gas) + return + } - var res interface{} - if cliCtx.Async { - res, err = cliCtx.BroadcastTxAsync(txBytes) - } else { - res, err = cliCtx.BroadcastTx(txBytes) + txCtx = newTxCtx } - if err != nil { + txBytes, err := txCtx.BuildAndSign(baseTx.Name, baseTx.Password, msgs) + if keyerror.IsErrKeyNotFound(err) { + WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } else if keyerror.IsErrWrongPassword(err) { + WriteErrorResponse(w, http.StatusUnauthorized, err.Error()) + return + } else if err != nil { WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - output, err := txCtx.Codec.MarshalJSONIndent(res, "", " ") + res, err := cliCtx.BroadcastTx(txBytes) if err != nil { WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - w.Write(output) + PostProcessResponse(w, cliCtx.Codec, res, cliCtx.Indent) } -// WriteGenerateStdTxResponse writes response for the generate_only mode. -func WriteGenerateStdTxResponse(w http.ResponseWriter, txCtx context.TxContext, msgs []sdk.Msg) { - stdMsg, err := txCtx.Build(msgs) - if err != nil { - WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - output, err := txCtx.Codec.MarshalJSON(auth.NewStdTx(stdMsg.Msgs, stdMsg.Fee, nil, stdMsg.Memo)) - if err != nil { - WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return +// PostProcessResponse performs post process for rest response +func PostProcessResponse(w http.ResponseWriter, cdc *codec.Codec, response interface{}, indent bool) { + var output []byte + switch response.(type) { + default: + var err error + if indent { + output, err = cdc.MarshalJSONIndent(response, "", " ") + } else { + output, err = cdc.MarshalJSON(response) + } + if err != nil { + WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + case []byte: + output = response.([]byte) } + w.Header().Set("Content-Type", "application/json") w.Write(output) - return } - -func AsyncOnlyArg(r *http.Request) bool { return urlQueryHasArg(r.URL, Async) } - -func GenerateOnlyArg(r *http.Request) bool { return urlQueryHasArg(r.URL, GenerateOnly) } - -func urlQueryHasArg(url *url.URL, arg string) bool { return url.Query().Get(arg) == "true" } diff --git a/client/utils/utils.go b/client/utils/utils.go index b83f62744..57131358a 100644 --- a/client/utils/utils.go +++ b/client/utils/utils.go @@ -1,16 +1,31 @@ package utils import ( + "bytes" "fmt" + "os" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/irisnet/irishub/app" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/keys" + irishubType "github.com/irisnet/irishub/types" + "github.com/tendermint/go-amino" + "github.com/tendermint/tendermint/libs/common" ) +// SendOrPrintTx implements a utility function that +// facilitates sending a series of messages in a signed +// transaction given a TxContext and a QueryContext. It ensures +// that the account exists, has a proper number and sequence +// set. In addition, it builds and signs a transaction with the +// supplied messages. Finally, it broadcasts the signed +// transaction to a node. +// NOTE: Also see CompleteAndBroadcastTxREST. func SendOrPrintTx(txCtx context.TxContext, cliCtx context.CLIContext, msgs []sdk.Msg) error { if cliCtx.GenerateOnly { - return PrintUnsignedStdTx(txCtx, cliCtx, msgs) + return PrintUnsignedStdTx(txCtx, cliCtx, msgs, false) } // Build and sign the transaction, then broadcast to a Tendermint // node. @@ -21,46 +36,153 @@ func SendOrPrintTx(txCtx context.TxContext, cliCtx context.CLIContext, msgs []sd return err } - passphrase, err := keys.GetPassphrase(cliCtx.FromAddressName) + name, err := cliCtx.GetFromName() if err != nil { return err } - // build and sign the transaction - txBytes, err := txCtx.BuildAndSign(cliCtx.FromAddressName, passphrase, msgs) + if txCtx.SimulateGas || cliCtx.DryRun { + txCtx, err = EnrichCtxWithGas(txCtx, cliCtx, name, msgs) + if err != nil { + return err + } + fmt.Fprintf(os.Stderr, "estimated gas = %v\n", txCtx.Gas) + } + if cliCtx.DryRun { + return nil + } + + passphrase, err := keys.GetPassphrase(name) if err != nil { return err } + // build and sign the transaction + txBytes, err := txCtx.BuildAndSign(name, passphrase, msgs) + if err != nil { + return err + } // broadcast to a Tendermint node - return cliCtx.EnsureBroadcastTx(txBytes) + _, err = cliCtx.BroadcastTx(txBytes) + return err +} + +// EnrichCtxWithGas calculates the gas estimate that would be consumed by the +// transaction and set the transaction's respective value accordingly. +func EnrichCtxWithGas(txCtx context.TxContext, cliCtx context.CLIContext, name string, msgs []sdk.Msg) (context.TxContext, error) { + _, adjusted, err := simulateMsgs(txCtx, cliCtx, name, msgs) + if err != nil { + return txCtx, err + } + return txCtx.WithGas(adjusted), nil +} + +// CalculateGas simulates the execution of a transaction and returns +// both the estimate obtained by the query and the adjusted amount. +func CalculateGas(queryFunc func(string, common.HexBytes) ([]byte, error), cdc *amino.Codec, txBytes []byte, adjustment float64) (estimate, adjusted int64, err error) { + // run a simulation (via /app/simulate query) to + // estimate gas and update TxContext accordingly + rawRes, err := queryFunc("/app/simulate", txBytes) + if err != nil { + return + } + estimate, err = parseQueryResponse(cdc, rawRes) + if err != nil { + return + } + adjusted = adjustGasEstimate(estimate, adjustment) + return } // PrintUnsignedStdTx builds an unsigned StdTx and prints it to os.Stdout. -func PrintUnsignedStdTx(txCtx context.TxContext, cliCtx context.CLIContext, msgs []sdk.Msg) (err error) { - stdTx, err := buildUnsignedStdTx(txCtx, cliCtx, msgs) +// Don't perform online validation or lookups if offline is true. +func PrintUnsignedStdTx(txCtx context.TxContext, cliCtx context.CLIContext, msgs []sdk.Msg, offline bool) (err error) { + var stdTx auth.StdTx + if offline { + stdTx, err = buildUnsignedStdTxOffline(txCtx, cliCtx, msgs) + } else { + stdTx, err = buildUnsignedStdTx(txCtx, cliCtx, msgs) + } if err != nil { return } - json, err := txCtx.Codec.MarshalJSON(stdTx) + var json []byte + if cliCtx.Indent { + json, err = txCtx.Codec.MarshalJSONIndent(stdTx, "", " ") + } else { + json, err = txCtx.Codec.MarshalJSON(stdTx) + } if err == nil { fmt.Printf("%s\n", json) } return } -// buildUnsignedStdTx builds a StdTx as per the parameters passed in the -// contexts. Gas is automatically estimated if gas wanted is set to 0. -func buildUnsignedStdTx(txCtx context.TxContext, cliCtx context.CLIContext, msgs []sdk.Msg) (stdTx auth.StdTx, err error) { - txCtx, err = prepareTxContext(txCtx, cliCtx) +// SignStdTx appends a signature to a StdTx and returns a copy of a it. If appendSig +// is false, it replaces the signatures already attached with the new signature. +// Don't perform online validation or lookups if offline is true. +func SignStdTx(txCtx context.TxContext, cliCtx context.CLIContext, name string, stdTx auth.StdTx, appendSig bool, offline bool) (auth.StdTx, error) { + var signedStdTx auth.StdTx + + keybase, err := keys.GetKeyBase() if err != nil { - return + return signedStdTx, err } - stdSignMsg, err := txCtx.Build(msgs) + info, err := keybase.Get(name) + if err != nil { + return signedStdTx, err + } + addr := info.GetPubKey().Address() + + // Check whether the address is a signer + if !isTxSigner(sdk.AccAddress(addr), stdTx.GetSigners()) { + fmt.Fprintf(os.Stderr, "WARNING: The generated transaction's intended signer does not match the given signer: '%v'\n", name) + } + + if !offline && txCtx.AccountNumber == 0 { + accNum, err := cliCtx.GetAccountNumber(addr) + if err != nil { + return signedStdTx, err + } + txCtx = txCtx.WithAccountNumber(accNum) + } + + if !offline && txCtx.Sequence == 0 { + accSeq, err := cliCtx.GetAccountSequence(addr) + if err != nil { + return signedStdTx, err + } + txCtx = txCtx.WithSequence(accSeq) + } + + passphrase, err := keys.GetPassphrase(name) + if err != nil { + return signedStdTx, err + } + return txCtx.SignStdTx(name, passphrase, stdTx, appendSig) +} + +// nolint +// SimulateMsgs simulates the transaction and returns the gas estimate and the adjusted value. +func simulateMsgs(txCtx context.TxContext, cliCtx context.CLIContext, name string, msgs []sdk.Msg) (estimated, adjusted int64, err error) { + txBytes, err := txCtx.BuildWithPubKey(name, msgs) if err != nil { return } - return auth.NewStdTx(stdSignMsg.Msgs, stdSignMsg.Fee, nil, stdSignMsg.Memo), nil + estimated, adjusted, err = CalculateGas(cliCtx.Query, cliCtx.Codec, txBytes, txCtx.GasAdjustment) + return +} + +func adjustGasEstimate(estimate int64, adjustment float64) int64 { + return int64(adjustment * float64(estimate)) +} + +func parseQueryResponse(cdc *amino.Codec, rawRes []byte) (int64, error) { + var simulationResult sdk.Result + if err := cdc.UnmarshalBinaryLengthPrefixed(rawRes, &simulationResult); err != nil { + return 0, err + } + return simulationResult.GasUsed, nil } func prepareTxContext(txCtx context.TxContext, cliCtx context.CLIContext) (context.TxContext, error) { @@ -73,6 +195,7 @@ func prepareTxContext(txCtx context.TxContext, cliCtx context.CLIContext) (conte return txCtx, err } + // TODO: (ref #1903) Allow for user supplied account number without // automatically doing a manual lookup. if txCtx.AccountNumber == 0 { accNum, err := cliCtx.GetAccountNumber(from) @@ -82,6 +205,7 @@ func prepareTxContext(txCtx context.TxContext, cliCtx context.CLIContext) (conte txCtx = txCtx.WithAccountNumber(accNum) } + // TODO: (ref #1903) Allow for user supplied account sequence without // automatically doing a manual lookup. if txCtx.Sequence == 0 { accSeq, err := cliCtx.GetAccountSequence(from) @@ -92,3 +216,61 @@ func prepareTxContext(txCtx context.TxContext, cliCtx context.CLIContext) (conte } return txCtx, nil } + +// buildUnsignedStdTx builds a StdTx as per the parameters passed in the +// contexts. Gas is automatically estimated if gas wanted is set to 0. +func buildUnsignedStdTx(txCtx context.TxContext, cliCtx context.CLIContext, msgs []sdk.Msg) (stdTx auth.StdTx, err error) { + txCtx, err = prepareTxContext(txCtx, cliCtx) + if err != nil { + return + } + return buildUnsignedStdTxOffline(txCtx, cliCtx, msgs) +} + +func buildUnsignedStdTxOffline(txCtx context.TxContext, cliCtx context.CLIContext, msgs []sdk.Msg) (stdTx auth.StdTx, err error) { + if txCtx.SimulateGas { + var name string + name, err = cliCtx.GetFromName() + if err != nil { + return + } + + txCtx, err = EnrichCtxWithGas(txCtx, cliCtx, name, msgs) + if err != nil { + return + } + fmt.Fprintf(os.Stderr, "estimated gas = %v\n", txCtx.Gas) + } + stdSignMsg, err := txCtx.Build(msgs) + if err != nil { + return + } + return auth.NewStdTx(stdSignMsg.Msgs, stdSignMsg.Fee, nil, stdSignMsg.Memo), nil +} + +func isTxSigner(user sdk.AccAddress, signers []sdk.AccAddress) bool { + for _, s := range signers { + if bytes.Equal(user.Bytes(), s.Bytes()) { + return true + } + } + return false +} + +func ExRateFromStakeTokenToMainUnit(cliCtx context.CLIContext) irishubType.Rat { + stakeTokenDenom, err := cliCtx.GetCoinType(app.Denom) + if err != nil { + panic(err) + } + decimalDiff := stakeTokenDenom.MinUnit.Decimal - stakeTokenDenom.GetMainUnit().Decimal + exRate := irishubType.NewRat(1).Quo(irishubType.NewRatFromInt(sdk.NewIntWithDecimal(1, decimalDiff))) + return exRate +} + +func ConvertDecToRat(input sdk.Dec) irishubType.Rat { + output, err := irishubType.NewRatFromDecimal(input.String(), 10) + if err != nil { + panic(err.Error()) + } + return output +} diff --git a/cmd/iris/main.go b/cmd/iris/main.go index bee2c1f92..abf7a6700 100644 --- a/cmd/iris/main.go +++ b/cmd/iris/main.go @@ -6,11 +6,13 @@ import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" "github.com/irisnet/irishub/app" bam "github.com/irisnet/irishub/baseapp" + "github.com/irisnet/irishub/client" + sdk "github.com/cosmos/cosmos-sdk/types" + irisInit "github.com/irisnet/irishub/init" "github.com/irisnet/irishub/version" "github.com/spf13/viper" abci "github.com/tendermint/tendermint/abci/types" @@ -21,6 +23,13 @@ import ( ) func main() { + + config := sdk.GetConfig() + config.SetBech32PrefixForAccount(irisInit.Bech32PrefixAccAddr, irisInit.Bech32PrefixAccPub) + config.SetBech32PrefixForValidator(irisInit.Bech32PrefixValAddr, irisInit.Bech32PrefixValPub) + config.SetBech32PrefixForConsensusNode(irisInit.Bech32PrefixConsAddr, irisInit.Bech32PrefixConsPub) + config.Seal() + cdc := app.MakeCodec() ctx := server.NewDefaultContext() cobra.EnableCommandSorting = false @@ -40,18 +49,22 @@ func main() { tendermintCmd.AddCommand( server.ShowNodeIDCmd(ctx), server.ShowValidatorCmd(ctx), + server.ShowAddressCmd(ctx), ) - startCmd := server.StartCmd(ctx, server.ConstructAppCreator(newApp, "iris")) + startCmd := server.StartCmd(ctx, newApp) startCmd.Flags().Bool(app.FlagReplay, false, "Replay the last block") rootCmd.AddCommand( - server.InitCmd(ctx, cdc, app.IrisAppInit()), + irisInit.InitCmd(ctx, cdc, app.IrisAppInit()), + irisInit.GenTxCmd(ctx, cdc), + irisInit.TestnetFilesCmd(ctx, cdc, app.IrisAppInit()), + irisInit.CollectGenTxsCmd(ctx, cdc), startCmd, //server.TestnetFilesCmd(ctx, cdc, app.IrisAppInit()), server.UnsafeResetAllCmd(ctx), client.LineBreak, tendermintCmd, - server.ExportCmd(ctx, cdc, server.ConstructAppExporter(exportAppStateAndTMValidators, "iris")), + server.ExportCmd(ctx, cdc, exportAppStateAndTMValidators), client.LineBreak, ) diff --git a/cmd/iriscli/main.go b/cmd/iriscli/main.go index 70d077fc5..d90ec84bb 100644 --- a/cmd/iriscli/main.go +++ b/cmd/iriscli/main.go @@ -1,12 +1,17 @@ package main import ( + "os" + "path" + + sdk "github.com/cosmos/cosmos-sdk/types" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/irisnet/irishub/app" "github.com/irisnet/irishub/client" bankcmd "github.com/irisnet/irishub/client/bank/cli" + distributioncmd "github.com/irisnet/irishub/client/distribution/cli" govcmd "github.com/irisnet/irishub/client/gov/cli" - iservicecmd "github.com/irisnet/irishub/client/iservice/cli" + servicecmd "github.com/irisnet/irishub/client/service/cli" keyscmd "github.com/irisnet/irishub/client/keys/cli" recordcmd "github.com/irisnet/irishub/client/record/cli" slashingcmd "github.com/irisnet/irishub/client/slashing/cli" @@ -14,8 +19,10 @@ import ( tendermintrpccmd "github.com/irisnet/irishub/client/tendermint/rpc" tenderminttxcmd "github.com/irisnet/irishub/client/tendermint/tx" upgradecmd "github.com/irisnet/irishub/client/upgrade/cli" + irisInit "github.com/irisnet/irishub/init" "github.com/irisnet/irishub/version" "github.com/spf13/cobra" + "github.com/spf13/viper" "github.com/tendermint/tendermint/libs/cli" ) @@ -28,9 +35,19 @@ var ( ) func main() { + + config := sdk.GetConfig() + config.SetBech32PrefixForAccount(irisInit.Bech32PrefixAccAddr, irisInit.Bech32PrefixAccPub) + config.SetBech32PrefixForValidator(irisInit.Bech32PrefixValAddr, irisInit.Bech32PrefixValPub) + config.SetBech32PrefixForConsensusNode(irisInit.Bech32PrefixConsAddr, irisInit.Bech32PrefixConsPub) + config.Seal() + cobra.EnableCommandSorting = false cdc := app.MakeCodec() + rootCmd.AddCommand(client.ConfigCmd()) + rootCmd.AddCommand(client.LineBreak) + rootCmd.AddCommand(tendermintrpccmd.StatusCommand()) //Add state commands tendermintCmd := &cobra.Command{ @@ -44,6 +61,7 @@ func main() { tendermintrpccmd.ValidatorCommand(), ) rootCmd.AddCommand(tendermintCmd) + rootCmd.AddCommand(client.LineBreak) //Add bank commands bankCmd := &cobra.Command{ @@ -58,11 +76,33 @@ func main() { bankCmd.AddCommand( client.PostCommands( bankcmd.SendTxCmd(cdc), + bankcmd.GetSignCommand(cdc, authcmd.GetAccountDecoder(cdc)), )...) rootCmd.AddCommand( bankCmd, ) + //Add distribution commands + distributionCmd := &cobra.Command{ + Use: "distribution", + Short: "Distribution subcommands", + } + distributionCmd.AddCommand( + client.GetCommands( + distributioncmd.GetWithdrawAddress("distr", cdc), + distributioncmd.GetDelegationDistInfo("distr", cdc), + distributioncmd.GetValidatorDistInfo("distr", cdc), + distributioncmd.GetAllDelegationDistInfo("distr", cdc), + )...) + distributionCmd.AddCommand( + client.PostCommands( + distributioncmd.GetCmdSetWithdrawAddr(cdc), + distributioncmd.GetCmdWithdrawRewards(cdc), + )...) + rootCmd.AddCommand( + distributionCmd, + ) + //Add gov commands govCmd := &cobra.Command{ Use: "gov", @@ -74,6 +114,9 @@ func main() { govcmd.GetCmdQueryProposals("gov", cdc), govcmd.GetCmdQueryVote("gov", cdc), govcmd.GetCmdQueryVotes("gov", cdc), + govcmd.GetCmdQueryDeposit("gov", cdc), + govcmd.GetCmdQueryDeposits("gov", cdc), + govcmd.GetCmdQueryTally("gov", cdc), govcmd.GetCmdQueryGovConfig("params", cdc), govcmd.GetCmdPullGovConfig("params", cdc), )...) @@ -100,8 +143,12 @@ func main() { stakecmd.GetCmdQueryDelegations("stake", cdc), stakecmd.GetCmdQueryUnbondingDelegation("stake", cdc), stakecmd.GetCmdQueryUnbondingDelegations("stake", cdc), + stakecmd.GetCmdQueryValidatorUnbondingDelegations("stake", cdc), + stakecmd.GetCmdQueryValidatorRedelegations("stake", cdc), stakecmd.GetCmdQueryRedelegation("stake", cdc), stakecmd.GetCmdQueryRedelegations("stake", cdc), + stakecmd.GetCmdQueryPool("stake", cdc), + stakecmd.GetCmdQueryParams("stake", cdc), slashingcmd.GetCmdQuerySigningInfo("slashing", cdc), )...) stakeCmd.AddCommand( @@ -135,21 +182,28 @@ func main() { upgradeCmd, ) - //Add iservice commands - iserviceCmd := &cobra.Command{ - Use: "iservice", - Short: "iservice subcommands", + //Add service commands + serviceCmd := &cobra.Command{ + Use: "service", + Short: "Service subcommands", } - iserviceCmd.AddCommand( + serviceCmd.AddCommand( client.GetCommands( - iservicecmd.GetCmdQueryScvDef("iservice", cdc), + servicecmd.GetCmdQueryScvDef("service", cdc), + servicecmd.GetCmdQueryScvBind("service", cdc), + servicecmd.GetCmdQueryScvBinds("service", cdc), )...) - iserviceCmd.AddCommand(client.PostCommands( - iservicecmd.GetCmdScvDef(cdc), + serviceCmd.AddCommand(client.PostCommands( + servicecmd.GetCmdScvDef(cdc), + servicecmd.GetCmdScvBind(cdc), + servicecmd.GetCmdScvBindUpdate(cdc), + servicecmd.GetCmdScvDisable(cdc), + servicecmd.GetCmdScvEnable(cdc), + servicecmd.GetCmdScvRefundDeposit(cdc), )...) rootCmd.AddCommand( - iserviceCmd, + serviceCmd, ) //add record command @@ -176,14 +230,41 @@ func main() { rootCmd.AddCommand( client.LineBreak, keyscmd.Commands(), + client.LineBreak, version.ServeVersionCommand(cdc), ) // prepare and add flags executor := cli.PrepareMainCmd(rootCmd, "IRISCLI", app.DefaultCLIHome) - err := executor.Execute() + err := initConfig(rootCmd) + if err != nil { + panic(err) + } + + err = executor.Execute() if err != nil { // handle with #870 panic(err) } } + +func initConfig(cmd *cobra.Command) error { + home, err := cmd.PersistentFlags().GetString(cli.HomeFlag) + if err != nil { + return err + } + + cfgFile := path.Join(home, "config", "config.toml") + if _, err := os.Stat(cfgFile); err == nil { + viper.SetConfigFile(cfgFile) + + if err := viper.ReadInConfig(); err != nil { + return err + } + } + + if err := viper.BindPFlag(cli.EncodingFlag, cmd.PersistentFlags().Lookup(cli.EncodingFlag)); err != nil { + return err + } + return viper.BindPFlag(cli.OutputFlag, cmd.PersistentFlags().Lookup(cli.OutputFlag)) +} diff --git a/cmd/irisdebug/hack.go b/cmd/irisdebug/hack.go index 99cd3cc50..41e41ca11 100644 --- a/cmd/irisdebug/hack.go +++ b/cmd/irisdebug/hack.go @@ -19,7 +19,7 @@ import ( bam "github.com/irisnet/irishub/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/ibc" @@ -127,24 +127,26 @@ var ( // Extended ABCI application type IrisApp struct { *bam.BaseApp - cdc *wire.Codec + cdc *codec.Codec // keys to access the substores keyMain *sdk.KVStoreKey keyAccount *sdk.KVStoreKey keyIBC *sdk.KVStoreKey keyStake *sdk.KVStoreKey + tkeyStake *sdk.TransientStoreKey keySlashing *sdk.KVStoreKey keyGov *sdk.KVStoreKey keyFeeCollection *sdk.KVStoreKey keyParams *sdk.KVStoreKey keyIparams *sdk.KVStoreKey + tkeyParams *sdk.TransientStoreKey keyUpgrade *sdk.KVStoreKey // Manage getting and setting accounts - accountMapper auth.AccountMapper + AccountKeeper auth.AccountKeeper feeCollectionKeeper auth.FeeCollectionKeeper - coinKeeper bank.Keeper + bankKeeper bank.Keeper ibcMapper ibc.Mapper stakeKeeper stake.Keeper slashingKeeper slashing.Keeper @@ -159,7 +161,7 @@ type IrisApp struct { func NewIrisApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.BaseApp)) *IrisApp { cdc := MakeCodec() - bApp := bam.NewBaseApp(appName, cdc, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...) + bApp := bam.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...) bApp.SetCommitMultiStoreTracer(os.Stdout) // create your application object @@ -175,30 +177,45 @@ func NewIrisApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.BaseAp keyFeeCollection: sdk.NewKVStoreKey("fee"), keyParams: sdk.NewKVStoreKey("params"), keyIparams: sdk.NewKVStoreKey("iparams"), + tkeyParams: sdk.NewTransientStoreKey("transient_params"), keyUpgrade: sdk.NewKVStoreKey("upgrade"), } - // define the accountMapper - app.accountMapper = auth.NewAccountMapper( + // define the AccountKeeper + app.AccountKeeper = auth.NewAccountKeeper( app.cdc, app.keyAccount, // target store auth.ProtoBaseAccount, // prototype ) // add handlers - app.paramsKeeper = params.NewKeeper(cdc, app.keyParams) - app.coinKeeper = bank.NewKeeper(app.accountMapper) + app.paramsKeeper = params.NewKeeper(cdc, app.keyParams, app.tkeyParams) + app.bankKeeper = bank.NewBaseKeeper(app.AccountKeeper) 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.paramsKeeper.Getter(), app.RegisterCodespace(slashing.DefaultCodespace)) + app.stakeKeeper = stake.NewKeeper( + app.cdc, + app.keyStake, app.tkeyStake, + app.bankKeeper, app.paramsKeeper.Subspace(stake.DefaultParamspace), + app.RegisterCodespace(stake.DefaultCodespace), + ) + app.slashingKeeper = slashing.NewKeeper( + app.cdc, + app.keySlashing, + app.stakeKeeper, app.paramsKeeper.Subspace(slashing.DefaultParamspace), + 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.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - + app.govKeeper = gov.NewKeeper( + app.cdc, + app.keyGov, + app.bankKeeper, app.stakeKeeper, + app.RegisterCodespace(gov.DefaultCodespace), + ) // register message routes 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("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.bankKeeper)). + AddRoute("ibc", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc.NewHandler(app.ibcMapper, app.bankKeeper)). 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)). @@ -208,7 +225,7 @@ func NewIrisApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.BaseAp app.SetInitChainer(app.initChainer) app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) - app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) + app.SetAnteHandler(auth.NewAnteHandler(app.AccountKeeper, app.feeCollectionKeeper)) app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing) err := app.LoadLatestVersion(app.keyMain) if err != nil { @@ -221,15 +238,15 @@ func NewIrisApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.BaseAp } // 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) +func MakeCodec() *codec.Codec { + var cdc = codec.New() + ibc.RegisterCodec(cdc) + bank.RegisterCodec(cdc) + stake.RegisterCodec(cdc) + slashing.RegisterCodec(cdc) + auth.RegisterCodec(cdc) + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) cdc.Seal() return cdc } @@ -267,7 +284,7 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci // load the accounts for _, gacc := range genesisState.Accounts { acc := gacc.ToAccount() - app.accountMapper.SetAccount(ctx, acc) + app.AccountKeeper.SetAccount(ctx, acc) } // load the initial stake information diff --git a/cmd/irisdebug/main.go b/cmd/irisdebug/main.go index 58220f82a..fbccde2aa 100644 --- a/cmd/irisdebug/main.go +++ b/cmd/irisdebug/main.go @@ -10,15 +10,22 @@ import ( "strconv" "strings" - iris "github.com/irisnet/irishub/app" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" + iris "github.com/irisnet/irishub/app" + irisInit "github.com/irisnet/irishub/init" "github.com/spf13/cobra" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" ) func init() { + config := sdk.GetConfig() + config.SetBech32PrefixForAccount(irisInit.Bech32PrefixAccAddr, irisInit.Bech32PrefixAccPub) + config.SetBech32PrefixForValidator(irisInit.Bech32PrefixValAddr, irisInit.Bech32PrefixValPub) + config.SetBech32PrefixForConsensusNode(irisInit.Bech32PrefixConsAddr, irisInit.Bech32PrefixConsPub) + config.Seal() + rootCmd.AddCommand(txCmd) rootCmd.AddCommand(pubkeyCmd) rootCmd.AddCommand(addrCmd) @@ -208,7 +215,7 @@ func runTxCmd(cmd *cobra.Command, args []string) error { var tx = auth.StdTx{} cdc := iris.MakeCodec() - err = cdc.UnmarshalBinary(txBytes, &tx) + err = cdc.UnmarshalBinaryLengthPrefixed(txBytes, &tx) if err != nil { return err } diff --git a/cmd/irislcd/main.go b/cmd/irislcd/main.go index 26e807d01..7116f8668 100644 --- a/cmd/irislcd/main.go +++ b/cmd/irislcd/main.go @@ -1,9 +1,11 @@ package main import ( + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/irisnet/irishub/app" "github.com/irisnet/irishub/client/lcd" _ "github.com/irisnet/irishub/client/lcd/statik" + irisInit "github.com/irisnet/irishub/init" "github.com/irisnet/irishub/version" "github.com/spf13/cobra" "github.com/tendermint/tendermint/libs/cli" @@ -18,6 +20,13 @@ var ( ) func main() { + + config := sdk.GetConfig() + config.SetBech32PrefixForAccount(irisInit.Bech32PrefixAccAddr, irisInit.Bech32PrefixAccPub) + config.SetBech32PrefixForValidator(irisInit.Bech32PrefixValAddr, irisInit.Bech32PrefixValPub) + config.SetBech32PrefixForConsensusNode(irisInit.Bech32PrefixConsAddr, irisInit.Bech32PrefixConsPub) + config.Seal() + cobra.EnableCommandSorting = false cdc := app.MakeCodec() diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 000000000..4df0896be --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,59 @@ +version: '3' + +services: + irisnode0: + container_name: irisnode0 + image: ubuntu:16.04 + ports: + - "26656-26657:26656-26657" + volumes: + - ./build:/home + command: /bin/bash -c 'cd /home/nodecluster/node0 && ../../iris start --home iris' + networks: + localnet: + ipv4_address: 192.168.10.2 + + irisnode1: + container_name: irisnode1 + image: ubuntu:16.04 + ports: + - "26659-26660:26656-26657" + volumes: + - ./build:/home + command: /bin/bash -c 'cd /home/nodecluster/node1 && ../../iris start --home iris' + networks: + localnet: + ipv4_address: 192.168.10.3 + + irisnode2: + container_name: irisnode2 + image: ubuntu:16.04 + ports: + - "26661-26662:26656-26657" + volumes: + - ./build:/home + command: /bin/bash -c 'cd /home/nodecluster/node2 && ../../iris start --home iris' + networks: + localnet: + ipv4_address: 192.168.10.4 + + irisnode3: + container_name: irisnode3 + image: ubuntu:16.04 + ports: + - "26663-26664:26656-26657" + volumes: + - ./build:/home + command: /bin/bash -c 'cd /home/nodecluster/node3 && ../../iris start --home iris' + networks: + localnet: + ipv4_address: 192.168.10.5 + +networks: + localnet: + driver: bridge + ipam: + driver: default + config: + - + subnet: 192.168.10.0/16 diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index ab504bbb6..2ed13bd45 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -1,55 +1,186 @@ 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/', 'Join the Testnet'], - ['/get-started/Install-Iris.md', 'Install'], - ['/get-started/Full-Node.md', 'Run a Full Node'], - ['/get-started/Validator-Node.md', 'Run a Validator Node'], - ['/get-started/Genesis-Generation-Process.md', 'Genesis Generation'], - ['/get-started/Bech32-on-IRISnet.md', 'Bech32 on IRISnet'], - ] - },{ - title: 'Modules', - collapsable: false, - children: [ - // ['/modules/coin/README.md', 'Coin Type'], - ['/modules/fee-token/', 'Fee Token'] - // ['/modules/gov/README.md', 'Governance'] - ] - },{ - title: 'Tools', - collapsable: false, - children: [ - ['/tools/Deploy-IRIS-Monitor.md', 'Monitor'] - ] - },{ - title: 'Validators', - collapsable: false, - children: [ - ['/validators/', 'Overview'], - ['/validators/Setup-Sentry-Node.md', 'Sentry Node'], - ['/validators/How-to-participate-in-onchain-governance.md', 'Onchain Governance'], - ['/validators/FAQ.md', 'FAQ'] - ] - } - ] - } -} + title: 'IRISnet Document', + description: '', + base: "/docs/", + themeConfig: { + displayAllHeaders: false, + nav: [ + {text: 'Back to IRISnet', link: 'https://www.irisnet.org'}, + {text: 'Introduction', link: '/introduction/'}, + {text: 'Software', link: '/software/'}, + {text: 'Getting Started', link: '/get-started/'}, + {text: 'Features', link: '/features/'}, + {text: 'CLI Client', link: '/cli-client/'}, + {text: 'Light Client', link: '/light-client/'}, + {text: 'Resources', link: '/resources/'}, + ], + sidebar: { + '/introduction/': [{ + title: 'The IRIS Hub', + collapsable: false, + children: [ + 'The-IRIS-Hub/Proof-of-Stake.md', + 'The-IRIS-Hub/IRIS-Tokens.md', + 'The-IRIS-Hub/Validators.md', + 'The-IRIS-Hub/Delegators.md' + ] + }, + { + title: 'The IRIS Service', + collapsable: false, + children: [ + 'The-IRIS-Service/Lifecycle.md', + 'The-IRIS-Service/Providers.md', + 'The-IRIS-Service/Consumers.md', + ] + }, + { + title: 'The IRIS Network', + collapsable: false, + children: [ + 'The-IRIS-Network/' + ] + }], + '/software/': [ + { + title: 'Node', + collapsable: false, + children: [ + ['node.md', 'Node'] + ] + }, { + title: 'CLI Client', + collapsable: false, + children: [ + ['cli-client.md', 'CLI Client'] + ] + }, { + title: 'Light Client', + collapsable: false, + children: [ + ['light-client.md', 'Light Client'] + ] + }, { + title: 'Monitor', + collapsable: false, + children: [ + ['monitor.md', 'Monitor'] + ] + }], + '/get-started/': [{ + title: 'Getting Started', + collapsable: false, + children: [ + ['Download-Rainbow.md', 'Download Rainbow'], + ['Install-the-Software.md', 'Install the Software'], + ['Join-the-Testnet.md', 'Join the Testnet'] + ] + }], + '/features/': [{ + title: 'Basic Concepts', + collapsable: false, + children: [ + ["basic-concepts/coin-type.md", 'Coin Type'], + ["basic-concepts/fee.md", 'Fee'], + ["basic-concepts/inflation.md", 'Infation'], + ["basic-concepts/bech32-prefix.md", 'Bech32 Prefix'], + ["basic-concepts/genesis-file.md", 'Genesis File'], + ["basic-concepts/gov-params.md", 'Gov Params'] + ] + },{ + title: 'Modules', + collapsable: false, + children: [ + ['bank.md', 'Bank'], + ['stake.md', 'Stake'], + ['service.md', 'Service'], + ['record.md', 'Record'], + ['governance.md', 'Governance'], + ['upgrade.md', 'Upgrade'], + ['distribution.md', 'Distribution'], + ] + }], + '/cli-client/': [{ + title: 'Status', + collapsable: false, + children: [ + ['status/', 'iriscli status'] + ] + }, + { + title: 'Tendermint', + collapsable: false, + children: [ + ['tendermint/', 'iriscli tendermint'] + ] + }, + { + title: 'Keys', + collapsable: false, + children: [ + ['keys/', 'iriscli keys'] + ] + }, + { + title: 'Bank', + collapsable: false, + children: [ + ['bank/', 'iriscli bank'] + ] + }, + { + title: 'Stake', + collapsable: false, + children: [ + ['stake/', 'iriscli stake'] + ] + }, + { + title: 'Gov', + collapsable: false, + children: [ + ['gov/', 'iriscli gov'] + ] + }, + { + title: 'Record', + collapsable: false, + children: [ + ['record/', 'iriscli record'] + ] + }, + { + title: 'Upgrade', + collapsable: false, + children: [ + ['upgrade/', 'iriscli upgrade'] + ] + }, + { + title: 'Service', + collapsable: false, + children: [ + ['service/', 'iriscli service'] + ] + }], + '/light-client/': [{ + title: 'Light Client', + collapsable: false, + children: [ + ['', 'Light Client'] + ] + }], + '/resources/': [{ + title: 'Resources', + collapsable: false, + children: [ + ['validator-faq.md', 'Validator FAQ'], + ['delegator-faq.md', 'Delegator FAQ'], + ['whitepaper-zh.md', 'Whitepaper ZH'], + ['whitepaper-en.md', 'Whitepaper EN'], + ['whitepaper-kr.md', 'Whitepaper KR'], + ] + }] + } + } +} \ No newline at end of file diff --git a/docs/cli-client/README.md b/docs/cli-client/README.md new file mode 100644 index 000000000..b2d562167 --- /dev/null +++ b/docs/cli-client/README.md @@ -0,0 +1,57 @@ +# Command Line Client + +## Global flags of query commands + +All query commands has these global flags. Their unique flags will be introduced later. + +| Name, shorthand | type | Required | Default Value | Description | +| --------------- | ---- | -------- | --------------------- | -------------------------------------------------------------------- | +| --chain-id | string | false | "" | Chain ID of tendermint node | +| --height | int | false | 0 | Block height to query, omit to get most recent provable block | +| --help, -h | string | false | | Print help message | +| --indent | bool | false | false | Add indent to JSON response | +| --ledger | bool | false | false | Use a connected Ledger device | +| --node | string | false | tcp://localhost:26657 | \<host>:\<port> to tendermint rpc interface for this chain | +| --trust-node | bool | false | true | Don't verify proofs for responses | + +## Global flags of commands to send transactions + +All commands which can be used to send transactions have these global flags. Their unique flags will be introduced later. + +| Name, shorthand | type | Required | Default | Description | +| -----------------| ----- | -------- | --------------------- | ------------------------------------------------------------------- | +| --account-number | int | false | 0 | AccountNumber number to sign the tx | +| --async | bool | false | false | broadcast transactions asynchronously | +| --chain-id | string | true | "" | Chain ID of tendermint node | +| --dry-run | bool | false | false | Ignore the --gas flag and perform a simulation of a transaction, but don't broadcast it | +| --fee | string | true | "" | Fee to pay along with transaction | +| --from | string | false | "" | Name of private key with which to sign | +| --from-addr | string | false | "" | Specify from address in generate-only mode | +| --gas | int | false | 200000 | Gas limit to set per-transaction; set to "simulate" to calculate required gas automatically | +| --gas-adjustment | int | false | 1 | Adjustment factor to be multiplied against the estimate returned by the tx simulation; if the gas limit is set | +| --generate-only | bool | false | false | Build an unsigned transaction and write it to STDOUT | +| --help, -h | string | false | | Print help message | +| --indent | bool | false | false | Add indent to JSON response | +| --json | string | false | false | Return output in json format | +| --ledger | bool | false | false | Use a connected Ledger device | +| --memo | string | false | "" | Memo to send along with transaction | +| --node | string | false | tcp://localhost:26657 | \<host>:\<port> to tendermint rpc interface for this chain | +| --print-response | bool | false | false | return tx response (only works with async = false)| +| --sequence int | int | false | 0 | Sequence number to sign the tx | +| --trust-node | bool | false | true | Don't verify proofs for responses | + +## Modules list + +Each modules provides a set of command line interfaces. Here we sort these commands by modules. + +1. [bank command](./bank/README.md) +2. [distribution command](./distribution/README.md) +3. [gov command](./gov/README.md) +4. [keys command](./keys/README.md) +5. [lcd command](./lcd/README.md) +6. [record command](./record/README.md) +7. [service command](./service/README.md) +8. [stake command](./stake/README.md) +9. [status command](./status/README.md) +10. [tendermint command](./tendermint/README.md) +11. [upgrade command](./upgrade/README.md) diff --git a/docs/cli-client/bank/README.md b/docs/cli-client/bank/README.md new file mode 100644 index 000000000..5083eb47f --- /dev/null +++ b/docs/cli-client/bank/README.md @@ -0,0 +1 @@ +# iriscli \ No newline at end of file diff --git a/docs/cli-client/distribution/README.md b/docs/cli-client/distribution/README.md new file mode 100644 index 000000000..768e90fcb --- /dev/null +++ b/docs/cli-client/distribution/README.md @@ -0,0 +1,28 @@ +# iriscli distribution + +## introduction + +This document describes how to use the the command line interfaces of distribution module. + +## Usage + +``` +iriscli distribution [subcommand] [flags] +``` + +Print all supported subcommands and flags: + +``` +iriscli distribution --help +``` + +## Available Subommands + +| Name | Description | +| --------------------------------| --------------------------------------------------------------| +| [delegation-distr-info](delegation-distr-info.md) | Query delegation distribution information | +| [delegator-distr-info](delegator-distr-info.md) | Query delegator distribution information | +| [validator-distr-info](validator-distr-info.md) | Query validator distribution information | +| [withdraw-address](withdraw-address.md) | Query withdraw address | +| [set-withdraw-address](set-withdraw-address.md) | change the default withdraw address for rewards associated with an address | +| [withdraw-rewards](withdraw-rewards.md) | withdraw rewards for either: all-delegations, a delegation, or a validator | diff --git a/docs/cli-client/distribution/delegation-distr-info.md b/docs/cli-client/distribution/delegation-distr-info.md new file mode 100644 index 000000000..c5734a0d8 --- /dev/null +++ b/docs/cli-client/distribution/delegation-distr-info.md @@ -0,0 +1,37 @@ +# iriscli distribution delegation-distr-info + +## introduction + +Query a delegation distribution information + +## Usage + +``` +iriscli distribution delegation-distr-info [flags] +``` + +Print help messages: +``` +iriscli distribution delegation-distr-info --help +``` + +## Unique Flags + +| Name, shorthand | type | Required | Default | Description | +| --------------------| ----- | -------- | -------- | ------------------------------------------------------------------- | +| --address-validator | string | true | "" | Bech address of the validator | +| --address-delegator | string | true | "" | Bech address of the delegator | + +## Examples + +``` +iriscli distribution delegation-distr-info --address-delegator=<delegator address> --address-validator=<validator address> +``` +Example response: +```json +{ + "delegator_addr": "faa1ezzh0humhy3329xg4avhcjtay985nll0zswc5j", + "val_operator_addr": "fva1ezzh0humhy3329xg4avhcjtay985nll0hpyhf4", + "del_pool_withdrawal_height": "4044" +} +``` \ No newline at end of file diff --git a/docs/cli-client/distribution/delegator-distr-info.md b/docs/cli-client/distribution/delegator-distr-info.md new file mode 100644 index 000000000..223a6cdbf --- /dev/null +++ b/docs/cli-client/distribution/delegator-distr-info.md @@ -0,0 +1,37 @@ +# iriscli distribution delegator-distr-info + +## Description + +Query a delegator distribution information + +## Usage + +``` +iriscli distribution delegator-distr-info [delegator address] [flags] +``` + +Print help messages: +``` +iriscli distribution delegator-distr-info --help +``` + +## Examples + +``` +iriscli distribution delegator-distr-info [delegator address] +``` +Example response: +```json +[ + { + "delegator_addr": "faa1ezzh0humhy3329xg4avhcjtay985nll0zswc5j", + "val_operator_addr": "fva14a70gzu0v2w8dlfx462c9sldvja24qaz6vv4sg", + "del_pool_withdrawal_height": "10859" + }, + { + "delegator_addr": "faa1ezzh0humhy3329xg4avhcjtay985nll0zswc5j", + "val_operator_addr": "fva1ezzh0humhy3329xg4avhcjtay985nll0hpyhf4", + "del_pool_withdrawal_height": "4044" + } +] +``` \ No newline at end of file diff --git a/docs/cli-client/distribution/set-withdraw-address.md b/docs/cli-client/distribution/set-withdraw-address.md new file mode 100644 index 000000000..6ed528b0b --- /dev/null +++ b/docs/cli-client/distribution/set-withdraw-address.md @@ -0,0 +1,23 @@ +# iriscli distribution set-withdraw-addr + +## Description + +Set withdraw address for delegator + +## Usage + +``` +iriscli distribution set-withdraw-addr [withdraw-address] [flags] +``` + +Print help messages: +``` +iriscli distribution set-withdraw-addr --help +``` + + +## Examples + +``` +iriscli distribution set-withdraw-addr [withdraw address] --from <key name> --fee=0.004iris --chain-id=<chain-id> +``` diff --git a/docs/cli-client/distribution/validator-distr-info.md b/docs/cli-client/distribution/validator-distr-info.md new file mode 100644 index 000000000..3bf7cd2db --- /dev/null +++ b/docs/cli-client/distribution/validator-distr-info.md @@ -0,0 +1,37 @@ +# iriscli distribution validator-distr-info + +## Description + +Query a validator distribution information + +## Usage + +``` +iriscli distribution validator-distr-info [validator address] [flags] +``` + +Print help messages: +``` +iriscli distribution validator-distr-info --help +``` + +## Examples + +``` +iriscli distribution validator-distr-info [validator address] +``` +Example response: +```json +[ + { + "delegator_addr": "faa1ezzh0humhy3329xg4avhcjtay985nll0zswc5j", + "val_operator_addr": "fva14a70gzu0v2w8dlfx462c9sldvja24qaz6vv4sg", + "del_pool_withdrawal_height": "10859" + }, + { + "delegator_addr": "faa1ezzh0humhy3329xg4avhcjtay985nll0zswc5j", + "val_operator_addr": "fva1ezzh0humhy3329xg4avhcjtay985nll0hpyhf4", + "del_pool_withdrawal_height": "4044" + } +] +``` \ No newline at end of file diff --git a/docs/cli-client/distribution/withdraw-address.md b/docs/cli-client/distribution/withdraw-address.md new file mode 100644 index 000000000..e46a1314e --- /dev/null +++ b/docs/cli-client/distribution/withdraw-address.md @@ -0,0 +1,27 @@ +# iriscli distribution withdraw-address + +## Description + +Query the withdraw address of a delegator + +## Usage +``` +iriscli distribution withdraw-address [delegator address] [flags] +``` + +Print help messages: + +``` +iriscli distribution withdraw-address --help +``` + +## Examples + +``` +iriscli distribution withdraw-address [delegator address] +``` +Example response: +```text +faa1ezzh0humhy3329xg4avhcjtay985nll0zswc5j +``` +If the given delegator didn't specify other withdraw address, the query result will be empty. \ No newline at end of file diff --git a/docs/cli-client/distribution/withdraw-rewards.md b/docs/cli-client/distribution/withdraw-rewards.md new file mode 100644 index 000000000..09da2a1e7 --- /dev/null +++ b/docs/cli-client/distribution/withdraw-rewards.md @@ -0,0 +1,41 @@ +# iriscli distribution withdraw-rewards + +## Description + +Withdraw rewards + +## Usage + +``` +iriscli distribution withdraw-rewards [flags] +``` + +Print help messages: + +``` +iriscli distribution withdraw-rewards --help +``` + +## Unique Flags + +| Name, shorthand | type | Required | Default | Description | +| --------------------- | ----- | -------- | -------- | ------------------------------------------------------------------- | +| --only-from-validator | string | false | "" | only withdraw from this validator address (in bech) | +| --is-validator | bool | false | false | Also withdraw validator's commission | + +Keep in mind, don't specify the above options both. + +## Examples + +1. Only withdraw a delegation rewards from a given validator + ``` + iriscli distribution withdraw-rewards --only-from-validator <validator address> --from <key name> --fee=0.004iris --chain-id=<chain-id> + ``` +2. Withdraw all delegation rewards of a delegator + ``` + iriscli distribution withdraw-rewards --from <key name> --fee=0.004iris --chain-id=<chain-id> + ``` +3. If the delegator is a onwer of a validator, withdraw all delegation rewards and validator commmission rewards: + ``` + iriscli distribution withdraw-rewards --is-validator=true --from <key name> --fee=0.004iris --chain-id=<chain-id> + ``` \ No newline at end of file diff --git a/docs/cli-client/gov/README.md b/docs/cli-client/gov/README.md new file mode 100644 index 000000000..9921f50e6 --- /dev/null +++ b/docs/cli-client/gov/README.md @@ -0,0 +1,43 @@ +# iriscli gov + +## Description + +This module provides the basic functions as described below: +1. On-chain governance proposals on text +2. On-chain governance proposals on parameter change +3. On-chain governance proposals on software upgrade + +## Usage + +```shell +iriscli gov [command] +``` +Print all supported subcommands and flags: +``` +iriscli distribution --help +``` + +## Available Commands + +| Name | Description | +| ------------------------------------- | --------------------------------------------------------------- | +| [query-proposal](query-proposal.md) | Query details of a single proposal | +| [query-proposals](query-proposals.md) | Query proposals with optional filters | +| [query-vote](query-vote.md) | Query vote | +| [query-votes](query-votes.md) | Query votes on a proposal | +| [query-deposit](query-deposit.md) | Query details of a deposit | +| [query-deposits](query-deposits.md) | Query deposits on a proposal | +| [query-tally](query-tally.md) | Get the tally of a proposal vote | +| [query-params](query-params.md) | Query parameter proposal's config | +| [pull-params](pull-params.md) | Generate param.json file | +| [submit-proposal](submit-proposal.md) | Create a new key, or import from seed | +| [deposit](deposit.md) | Deposit tokens for activing proposal | +| [vote](vote.md) | vote for an active proposal, options: Yes/No/NoWithVeto/Abstain | + + +## Extended description + +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) \ No newline at end of file diff --git a/docs/cli-client/gov/deposit.md b/docs/cli-client/gov/deposit.md new file mode 100644 index 000000000..5ebbad303 --- /dev/null +++ b/docs/cli-client/gov/deposit.md @@ -0,0 +1,45 @@ +# iriscli gov deposit + +## Description + +Deposit tokens for activing proposal + +## Usage + +``` +iriscli gov deposit [flags] +``` + +Print help messages: + +``` +iriscli gov deposit --help +``` +## Flags + +| Name, shorthand | Default | Description | Required | +| ---------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --deposit | | [string] Deposit of proposal | Yes | +| --proposal-id | | [string] ProposalID of proposal depositing on | Yes | +## Examples + +### Deposit + +```shell +iriscli gov deposit --chain-id=test --proposal-id=1 --deposit=50iris --from=node0 --fee=0.01iris +``` + +After you enter the correct password, you could deposit 50iris to make your proposal active which can be voted, after you enter the correct password, you're done with depositing iris tokens for an activing proposal. + +```txt +Password to sign with 'node0': +Committed at block 473 (tx hash: 0309E969589F19A9D9E4BFC9479720487FBF929ED6A88824414C5E7E91709206, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:6710 Tags:[{Key:[97 99 116 105 111 110] Value:[100 101 112 111 115 105 116] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[100 101 112 111 115 105 116 101 114] Value:[102 97 97 49 52 113 53 114 102 57 115 108 50 100 113 100 50 117 120 114 120 121 107 97 102 120 113 51 110 117 51 108 106 50 102 112 57 108 55 112 103 100] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[112 114 111 112 111 115 97 108 45 105 100] Value:[49] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 51 51 53 53 48 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "deposit", + "completeConsumedTxFee-iris-atto": "\"335500000000000\"", + "depositor": "faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd", + "proposal-id": "1" + } + } +``` diff --git a/docs/cli-client/gov/pull-params.md b/docs/cli-client/gov/pull-params.md new file mode 100644 index 000000000..1830b0fa5 --- /dev/null +++ b/docs/cli-client/gov/pull-params.md @@ -0,0 +1,86 @@ +# iriscli gov pull-params + +## Description + +Generate param.json file + +## Usage + +``` +iriscli gov pull-params [flags] +``` + +Print help messages: + +``` +iriscli gov pull-params --help +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --path | $HOME/.iris | [string] Directory of iris home | | + +## Examples + +### Pull params + +```shell +iriscli gov pull-params +``` + +Then you'll receive a message as described below: + +```txt +Save the parameter config file in /Users/trevorfu/.iris/config/params.json +``` + +If you open the params.json in the --path/config directory, you can see it's json format content. + +```txt +{ + "gov": { + "Gov/govDepositProcedure": { + "min_deposit": [ + { + "denom": "iris-atto", + "amount": "1000000000000000000000" + } + ], + "max_deposit_period": "172800000000000" + }, + "Gov/govVotingProcedure": { +: "gov": { + "Gov/govDepositProcedure": { + "min_deposit": [ + { + "denom": "iris-atto", + "amount": "1000000000000000000000" + } + ], + "max_deposit_period": "172800000000000" + }, + "Gov/govVotingProcedure": { + "voting_period": "172800000000000" +: "gov": { + "Gov/govDepositProcedure": { + "min_deposit": [ + { + "denom": "iris-atto", + "amount": "1000000000000000000000" + } + ], + "max_deposit_period": "172800000000000" + }, + "Gov/govVotingProcedure": { + "voting_period": "172800000000000" + }, + "Gov/govTallyingProcedure": { + "threshold": "0.5000000000", + "veto": "0.3340000000", + "participation": "0.6670000000" + } + } +} +``` diff --git a/docs/cli-client/gov/query-deposit.md b/docs/cli-client/gov/query-deposit.md new file mode 100644 index 000000000..6633eb4c4 --- /dev/null +++ b/docs/cli-client/gov/query-deposit.md @@ -0,0 +1,46 @@ +# iriscli gov query-deposit + +## Description + +Query details of a deposit + +## Usage + +``` +iriscli gov query-deposit [flags] +``` + +Print help messages: + +``` +iriscli gov query-deposit --help +``` +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --chain-id | | [string] Chain ID of tendermint node | Yes | +| --depositor | | [string] Bech32 depositor address | Yes | + +## Examples + +### Query deposit + +```shell +iriscli gov query-deposit --chain-id=test --proposal-id=1 --depositor=faa1c4kjt586r3t353ek9jtzwxum9x9fcgwetyca07 +``` + +You could query the deposited tokens on a specific proposal. + +```txt +{ + "depositor": "faa1c4kjt586r3t353ek9jtzwxum9x9fcgwetyca07", + "proposal_id": "1", + "amount": [ + { + "denom": "iris-atto", + "amount": "30000000000000000000" + } + ] +} +``` diff --git a/docs/cli-client/gov/query-deposits.md b/docs/cli-client/gov/query-deposits.md new file mode 100644 index 000000000..c2b183287 --- /dev/null +++ b/docs/cli-client/gov/query-deposits.md @@ -0,0 +1,48 @@ +# iriscli gov query-deposits + +## Description + +Query details of a deposits + +## Usage + +``` +iriscli gov query-deposits [flags] +``` + +Print help messages: + +``` +iriscli gov query-deposits --help +``` +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --proposal-id | | [string] ProposalID of proposal depositing on | Yes | + + +## Examples + +### Query deposits + +```shell +iriscli gov query-deposits --chain-id=test --proposal-id=1 +``` + +You could query all the deposited tokens on a specific proposal, includes deposit details for each depositor. + +```txt +[ + { + "depositor": "faa1c4kjt586r3t353ek9jtzwxum9x9fcgwetyca07", + "proposal_id": "1", + "amount": [ + { + "denom": "iris-atto", + "amount": "35000000000000000000" + } + ] + } +] +``` diff --git a/docs/cli-client/gov/query-params.md b/docs/cli-client/gov/query-params.md new file mode 100644 index 000000000..2f61348e8 --- /dev/null +++ b/docs/cli-client/gov/query-params.md @@ -0,0 +1,55 @@ +# iriscli gov query-params + +## Description + +Query parameter proposal's config + +## Usage + +``` +iriscli gov query-params [flags] +``` + +Print help messages: + +``` +iriscli gov query-params --help +``` +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --key | | [string] Key name of parameter | | +| --module | | [string] Module name | | + +## Examples + +### Query params by module + +```shell +iriscli gov query-params --module=gov +``` + +You'll get all the keys of gov module. + +```txt +[ + "Gov/govDepositProcedure", + "Gov/govTallyingProcedure", + "Gov/govVotingProcedure" +] +``` + +### Query params by key + +```shell +iriscli gov query-params --key=Gov/govDepositProcedure +``` + +You'll get all the details of the key specified in the gov module. + +```txt +{"key":"Gov/govDepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"1000000000000000000000\"}],\"max_deposit_period\":172800000000000}","op":""} +``` + +Note: --module and --key cannot be both empty. diff --git a/docs/cli-client/gov/query-proposal.md b/docs/cli-client/gov/query-proposal.md new file mode 100644 index 000000000..348052272 --- /dev/null +++ b/docs/cli-client/gov/query-proposal.md @@ -0,0 +1,64 @@ +# iriscli gov query-proposal + +## Description + +Query details of a single proposal + +## Usage + +``` +iriscli gov query-proposal [flags] +``` + +Print help messages: + +``` +iriscli gov query-proposal --help +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --proposal-id | | [string] ProposalID of proposal depositing on | Yes | + +## Examples + +### Query proposal + +```shell +iriscli gov query-proposal --chain-id=test --proposal-id=1 +``` + +You could query the details of a specific proposal. + +```txt +{ + "proposal_id": "1", + "title": "test proposal", + "description": "a new text proposal", + "proposal_type": "Text", + "proposal_status": "DepositPeriod", + "tally_result": { + "yes": "0.0000000000", + "abstain": "0.0000000000", + "no": "0.0000000000", + "no_with_veto": "0.0000000000" + }, + "submit_time": "2018-11-14T09:10:19.365363Z", + "deposit_end_time": "2018-11-16T09:10:19.365363Z", + "total_deposit": [ + { + "denom": "iris-atto", + "amount": "49000000000000000050" + } + ], + "voting_start_time": "0001-01-01T00:00:00Z", + "voting_end_time": "0001-01-01T00:00:00Z", + "param": { + "key": "", + "value": "", + "op": "" + } +} +``` diff --git a/docs/cli-client/gov/query-proposals.md b/docs/cli-client/gov/query-proposals.md new file mode 100644 index 000000000..21424ff87 --- /dev/null +++ b/docs/cli-client/gov/query-proposals.md @@ -0,0 +1,54 @@ +# iriscli gov query-proposals + +## Description + +Query proposals with optional filters + +## Usage + +``` +iriscli gov query-proposals [flags] +``` + + +Print help messages: + +``` +iriscli gov query-proposals --help +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --depositor | | [string] (optional) Filter by proposals deposited on by depositor | | +| --limit | | [string] (optional) Limit to latest [number] proposals. Defaults to all proposals | | +| --status | | [string] (optional) filter proposals by proposal status | | +| --voter | | [string] (optional) Filter by proposals voted on by voted | | + +## Examples + +### Query proposals + +```shell +iriscli gov query-proposals --chain-id=test +``` + +You could query all the proposals by default. + +```txt + 1 - test proposal + 2 - new proposal +``` + +Also you can query proposal by filters, such as: + +```shell +gov query-proposals --chain-id=test --depositor=faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd +``` + +Finally, here shows the proposal who's depositor address is faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd. + +```txt + 2 - new proposal +``` diff --git a/docs/cli-client/gov/query-tally.md b/docs/cli-client/gov/query-tally.md new file mode 100644 index 000000000..9a0331b50 --- /dev/null +++ b/docs/cli-client/gov/query-tally.md @@ -0,0 +1,41 @@ +# iriscli gov query-tally + +## Description + +Get the tally of a proposal vote + +## Usage + +``` +iriscli gov query-tally [flags] +``` + +Print help messages: + +``` +iriscli gov query-tally --help +``` + +## Flags +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --proposal-id | | [string] ProposalID of proposal depositing on | Yes | + +## Examples + +### Query tally + +```shell +iriscli gov query-tally --chain-id=test --proposal-id=1 +``` + +You could query the statistics of each voting option. + +```txt +{ + "yes": "100.0000000000", + "abstain": "0.0000000000", + "no": "0.0000000000", + "no_with_veto": "0.0000000000" +} +``` diff --git a/docs/cli-client/gov/query-vote.md b/docs/cli-client/gov/query-vote.md new file mode 100644 index 000000000..e7175f1c3 --- /dev/null +++ b/docs/cli-client/gov/query-vote.md @@ -0,0 +1,42 @@ +# iriscli gov query-vote + +## Description + +Query vote + +## Usage + +``` +iriscli gov query-vote [flags] +``` + +Print help messages: + +``` +iriscli gov query-vote --help +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --proposal-id | | [string] ProposalID of proposal depositing on | Yes | +| --voter | | [string] Bech32 voter address | Yes | + +## Examples + +### Query vote + +```shell +iriscli gov query-vote --chain-id=test --proposal-id=1 --voter=faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd +``` + +You could query the voting by specifying the proposal and the voter. + +```txt +{ + "voter": "faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd", + "proposal_id": "1", + "option": "Yes" +} +``` diff --git a/docs/cli-client/gov/query-votes.md b/docs/cli-client/gov/query-votes.md new file mode 100644 index 000000000..bed60f2cf --- /dev/null +++ b/docs/cli-client/gov/query-votes.md @@ -0,0 +1,42 @@ +# iriscli gov query-votes + +## Description + +Query votes on a proposal + +## Usage + +``` +iriscli gov query-votes [flags] +``` + +Print help messages: + +``` +iriscli gov query-votes --help +``` +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --proposal-id | | [string] ProposalID of proposal depositing on | Yes | + +## Examples + +### Query votes + +```shell +iriscli gov query-votes --chain-id=test --proposal-id=1 +``` + +You could query the voting of all the voters by specifying the proposal. + +```txt +[ + { + "voter": "faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd", + "proposal_id": "1", + "option": "Yes" + } +] +``` diff --git a/docs/cli-client/gov/submit-proposal.md b/docs/cli-client/gov/submit-proposal.md new file mode 100644 index 000000000..beaf29045 --- /dev/null +++ b/docs/cli-client/gov/submit-proposal.md @@ -0,0 +1,71 @@ +# iriscli gov submit-proposal + +## Description + +Submit a proposal along with an initial deposit + +## Usage + +``` +iriscli gov submit-proposal [flags] +``` + +Print help messages: + +``` +iriscli gov submit-proposal --help +``` +## Flags + +| Name, shorthand | Default | Description | Required | +| ---------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --deposit | | [string] Deposit of proposal | | +| --description | | [string] Description of proposal | Yes | +| --key | | The key of parameter | | +| --op | | [string] The operation of parameter | | +| --param | | [string] Parameter of proposal,eg. [{key:key,value:value,op:update}] | | +| --path | | [string] The path of param.json | | +| --title | | [string] Title of proposal | Yes | +| --type | | [string] ProposalType of proposal,eg:Text/ParameterChange/SoftwareUpgrade | Yes | + +## Examples + +### Submit a 'Text' type proposal + +```shell +iriscli gov submit-proposal --chain-id=test --title="notice proposal" --type=Text --description="a new text proposal" --from=node0 --fee=0.01iris +``` + +After you enter the correct password, you're done with submitting a new proposal, and then remember to back up your proposal-id, it's the only way to retrieve your proposal. + +```txt +Password to sign with 'node0': +Committed at block 44 (tx hash: 2C28A87A6262CACEDDB4EBBC60FE989D0DB2B7DEB1EC6795D2F4707DA32C7CBF, response: {Code:0 Data:[49] Log:Msg 0: Info: GasWanted:200000 GasUsed:8091 Tags:[{Key:[97 99 116 105 111 110] Value:[115 117 98 109 105 116 45 112 114 111 112 111 115 97 108] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[112 114 111 112 111 115 101 114] Value:[102 97 97 49 115 108 116 106 120 100 103 107 48 48 115 56 54 50 57 50 122 48 99 110 55 97 53 100 106 99 99 116 54 101 115 115 110 97 118 100 121 122] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[112 114 111 112 111 115 97 108 45 105 100] Value:[49] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[112 97 114 97 109] Value:[] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 52 48 52 53 53 48 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "submit-proposal", + "completeConsumedTxFee-iris-atto": "\"4045500000000000\"", + "param": "", + "proposal-id": "1", + "proposer": "faa1sltjxdgk00s86292z0cn7a5djcct6essnavdyz" + } + } +``` + +### Submit a 'ParameterChange' type proposal + +```shell +iriscli gov submit-proposal --chain-id=test --title="update MinDeposit proposal" --param='{"key":"Gov/gov/DepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":20}","op":"update"}' --type=ParameterChange --description="a new parameter change proposal" --from=node0 --fee=0.01iris +``` + +After that, you're done with submitting a new 'ParameterChange' proposal. +The details of changed parameters (get parameters through query-params, modify it and then add "update" on the "op", more details in usage scenarios)and other fields of proposal are similar with text proposal. +Note: in this case, --path and --param cannot be both empty. + +### Submit a 'SoftwareUpgrade' type proposal + +```shell +iriscli gov submit-proposal --chain-id=test --title="irishub0.7.0 upgrade proposal" --type=SoftwareUpgrade --description="a new software upgrade proposal" --from=node0 --fee=0.01iris +``` + +In this case, 'title'、 'type' and 'desciption' of the proposal is required parameters, also you should back up your proposal-id which is the only way to retrieve your proposal. diff --git a/docs/cli-client/gov/vote.md b/docs/cli-client/gov/vote.md new file mode 100644 index 000000000..a8b63e039 --- /dev/null +++ b/docs/cli-client/gov/vote.md @@ -0,0 +1,47 @@ +# iriscli gov vote + +## Description + +Vote for an active proposal, options: Yes/No/NoWithVeto/Abstain + +## Usage + +``` +iriscli gov vote [flags] +``` + +Print help messages: + +``` +iriscli gov vote --help +``` +## Flags + +| Name, shorthand | Default | Description | Required | +| ---------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --option | | [string] Vote option {Yes, No, NoWithVeto, Abstain} | Yes | +| --proposal-id | | [string] ProposalID of proposal voting on | Yes | + +## Examples + +### Vote for proposal + +```shell +iriscli gov vote --chain-id=test --proposal-id=1 --option=Yes --from node0 --fee=0.01iris +``` + +Validators and delegators can vote for proposals which enter voting period. +After you enter the correct password, you're done with voting for a 'VotingPeriod' proposal. + +```txt +Vote[Voter:faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd,ProposalID:1,Option:Yes]Password to sign with 'node0': +Committed at block 989 (tx hash: ABDD88AA3CA8F365AC499427477CCE83ADF09D7FC2D62643D0217107E489A483, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:2408 Tags:[{Key:[97 99 116 105 111 110] Value:[118 111 116 101] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[118 111 116 101 114] Value:[102 97 97 49 52 113 53 114 102 57 115 108 50 100 113 100 50 117 120 114 120 121 107 97 102 120 113 51 110 117 51 108 106 50 102 112 57 108 55 112 103 100] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[112 114 111 112 111 115 97 108 45 105 100] Value:[49] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 49 50 48 52 48 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "vote", + "completeConsumedTxFee-iris-atto": "\"120400000000000\"", + "proposal-id": "1", + "voter": "faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd" + } + } +``` diff --git a/docs/cli-client/keys/README.md b/docs/cli-client/keys/README.md new file mode 100644 index 000000000..1d486c368 --- /dev/null +++ b/docs/cli-client/keys/README.md @@ -0,0 +1,42 @@ +# iriscli keys + +## Description + +Keys allows you to manage your local keystore for tendermint. + +## Usage + +```shell +iriscli keys [command] +``` + +## Available Commands + +| Name | Description | +| ----------------------- | -------------------------------------------------------------------------------------------- | +| [mnemonic](mnemonic.md) | Create a bip39 mnemonic, sometimes called a seed phrase, by reading from the system entropy. | +| [new](new.md) | Derive a new private key using an interactive command that will prompt you for each input. | +| [add](add.md) | Create a new key, or import from seed | +| [list](list.md) | List all keys | +| [show](show.md) | Show key info for the given name | +| [delete](delete.md) | Delete the given key | +| [update](update.md) | Change the password used to protect private key | + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | ------- | ------------- | -------- | +| --help, -h | | Help for keys | | + +## Global Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------- | -------------------------------------- | -------- | +| --encoding, -e | hex | [string] Binary encoding (hex|b64|btc) | | +| --home | $HOME/.iriscli | [string] Directory for config and data | | +| --output, -o | text | [string] Output format (text|json) | | +| --trace | | Print out full stack trace on errors | | + +## Extended description + +These keys may be in any format supported by go-crypto and can be used by light-clients, full nodes, or any other application that needs to sign with a private key. diff --git a/docs/cli-client/keys/add.md b/docs/cli-client/keys/add.md new file mode 100644 index 000000000..78dd319a5 --- /dev/null +++ b/docs/cli-client/keys/add.md @@ -0,0 +1,69 @@ +# iriscli keys add + +## Description + +Create a new key, or import from seed + +## Usage + +``` +iriscli keys add <name> [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | --------- | ----------------------------------------------------------------- | -------- | +| --account | | [uint32] Account number for HD derivation | | +| --dry-run | | Perform action, but don't add key to local keystore | | +| --help, -h | | Help for add | | +| --index | | [uint32] Index number for HD derivation | | +| --ledger | | Store a local reference to a private key on a Ledger device | | +| --no-backup | | Don't print out seed phrase (if others are watching the terminal) | | +| --recover | | Provide seed phrase to recover existing key instead of creating | | +| --type, -t | secp256k1 | [string] Type of private key (secp256k\|ed25519) | | + +## Examples + +### Create a new key + +```shell +iriscli keys add MyKey +``` + +You'll be asked to enter a password for your key, note: password must be at least 8 characters. + +```txt +Enter a passphrase for your key: +Repeat the passphrase: +``` + +After that, you're done with creating a new key, but remember to backup your seed phrase, it is the only way to recover your account if you ever forget your password or lose your key. + +```txt +NAME: TYPE: ADDRESS: PUBKEY: +MyKey local faa1mmsm487rqkgktl2qgrjad0z3yaf9n8t5pkp33m fap1addwnpepq2g0u7cnxp5ew0yhqep8j4rth5ugq8ky7gjmunk8tkpze95ss23ak4svkjq +**Important** write this seed phrase in a safe place. +It is the only way to recover your account if you ever forget your password. + +oval green shrug term already arena pilot spirit jump gain useful symbol hover grid item concert kiss zero bleak farm capable peanut snack basket +``` + +The 24 words above is a seed phrase just for example, **DO NOT** use it in production. + +### Recover an existing key + +If you forget your password or lose your key, or you wanna use your key in another place, you can recover your key by your seed phrase. + +```txt +iriscli keys add MyKey --recover +``` + +You'll be asked to enter a new password for your key, and enter the seed phrase. Then you get your key back. + +```txt +Enter a passphrase for your key: +Repeat the passphrase: +Enter your recovery seed phrase: +``` + diff --git a/docs/cli-client/keys/delete.md b/docs/cli-client/keys/delete.md new file mode 100644 index 000000000..6d121621e --- /dev/null +++ b/docs/cli-client/keys/delete.md @@ -0,0 +1,37 @@ +# iriscli keys delete + +## Description + +Delete the given key + +## Usage + +``` +iriscli keys delete <name> [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | --------- | ------------------------------------------------------------ | -------- | +| --help, -h | | help for delete | | + +## Examples + +### Delete a given key + +```shell +iriscli keys delete MyKey +``` + +You'll receive a danger warning and be asked to enter a password for your key. + +```txt +DANGER - enter password to permanently delete key: +``` + +After you enter the correct password, you're done with deleting your key. + +```txt +Password deleted forever (uh oh!) +``` diff --git a/docs/cli-client/keys/list.md b/docs/cli-client/keys/list.md new file mode 100644 index 000000000..cfdb078ed --- /dev/null +++ b/docs/cli-client/keys/list.md @@ -0,0 +1,34 @@ +# iriscli keys list + +## Description + +Return a list of all public keys stored by this key manager +along with their associated name and address. + +## Usage + +``` +iriscli keys list [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | --------- | ------------------------------------------------------------ | -------- | +| --help, -h | | help for list | | + +## Examples + +### List all public keys + +```shell +iriscli keys list +``` + +You'll get all the local public keys with 'address' and 'pubkey' element. + +```txt +NAME: TYPE: ADDRESS: PUBKEY: +abc local faa1va2eu9qhwn5fx58kvl87x05ee4qrgh44yd8teh fap1addwnpepq02r0hts0yjhp4rsal627s2lqk4agy2g6tek5g9yq2tfrmkkehee2td75cs +test local faa1kkm4w5pvmcw0e3vjcxqtfxwqpm3k0zakl7lxn5 fap1addwnpepq0gsl90v9dgac3r9hzgz53ul5ml5ynq89ax9x8qs5jgv5z5vyssskww57lw +``` diff --git a/docs/cli-client/keys/mnemonic.md b/docs/cli-client/keys/mnemonic.md new file mode 100644 index 000000000..91f83e8d6 --- /dev/null +++ b/docs/cli-client/keys/mnemonic.md @@ -0,0 +1,32 @@ +# iriscli keys mnemonic + +## Description + +Create a bip39 mnemonic, sometimes called a seed phrase, by reading from the system entropy. To pass your own entropy, use --unsafe-entropy + +## Usage + +``` +iriscli keys mnemonic <name> [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| ---------------- | --------- | ----------------------------------------------------------------------------- | -------- | +| --help, -h | | help for mnemonic | | +| --unsafe-entropy | | Prompt the user to supply their own entropy, instead of relying on the system | | + +## Examples + +### Create a bip39 mnemonic + +```shell +iriscli keys mnemonic MyKey +``` + +You'll get a bip39 mnemonic with 24 words. + +```txt +police possible oval milk network indicate usual blossom spring wasp taste canal announce purpose rib mind river pet brown web response sting remain airport +``` diff --git a/docs/cli-client/keys/new.md b/docs/cli-client/keys/new.md new file mode 100644 index 000000000..0a82f3cfc --- /dev/null +++ b/docs/cli-client/keys/new.md @@ -0,0 +1,62 @@ +# iriscli keys new + +## Description + +Derive a new private key using an interactive command that will prompt you for each input. +Optionally specify a bip39 mnemonic, a bip39 passphrase to further secure the mnemonic, +and a bip32 HD path to derive a specific account. The key will be stored under the given name +and encrypted with the given password. The only input that is required is the encryption password. + +## Usage + +``` +iriscli keys new <name> [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | ----------------- | --------------------------------------------------------------- | -------- | +| --bip44-path | 44'/118'/0'/0/0 | BIP44 path from which to derive a private key | | +| --default | | Skip the prompts and just use the default values for everything | | +| --help, -h | | help for new | | +| --ledger | | Store a local reference to a private key on a Ledger device | | + +## Examples + +### Create a new key by the specified method + +```shell +iriscli keys new MyKey +``` + +You'll be asked to enter your bip44 path, default is 44'/118'/0'/0/0. + +```txt +> ------------------------------------- +> Enter your bip44 path. Default is 44'/118'/0'/0/0 +``` + +Then you'll be asked to enter your bip39 mnemonic, or hit enter to generate one. + +```txt +> Enter your bip39 mnemonic, or hit enter to generate one. +``` + +You could hit enter to generate bip39 mnemonic, then a new hint will be show to ask you to enter bip39 passphrase. + +```txt +> ------------------------------------- +> Enter your bip39 passphrase. This is combined with the mnemonic to derive the seed +> Most users should just hit enter to use the default, "" +``` + +Also you could hit enter to skip it, then you'll receive a hint to enter a password. + +```txt +> ------------------------------------- +> Enter a passphrase to encrypt your key to disk: +> Repeat the passphrase: +``` + +After that, you're done with creating a new key. diff --git a/docs/cli-client/keys/show.md b/docs/cli-client/keys/show.md new file mode 100644 index 000000000..75860c5e8 --- /dev/null +++ b/docs/cli-client/keys/show.md @@ -0,0 +1,36 @@ +# iriscli keys show + +## Description + +Return public details of one local key. + +## Usage + +``` +iriscli keys show <name> [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| -------------------- | ----------------- | -------------------------------------------------------------- | -------- | +| --address | | output the address only (overrides --output) | | +| --bech | acc | [string] The Bech32 prefix encoding for a key (acc|val|cons) | | +| --help, -h | | help for show | | +| --multisig-threshold | 1 | [uint] K out of N required signatures | | +| --pubkey | | output the public key only (overrides --output) | | + +## Examples + +### Show a given key + +```shell +iriscli keys show MyKey +``` + +You'll get the local public keys with 'address' and 'pubkey' element of a given key. + +```txt +NAME: TYPE: ADDRESS: PUBKEY: +MyKey local faa1kkm4w5pvmcw0e3vjcxqtfxwqpm3k0zakl7lxn5 fap1addwnpepq0gsl90v9dgac3r9hzgz53ul5ml5ynq89ax9x8qs5jgv5z5vyssskww57lw +``` diff --git a/docs/cli-client/keys/update.md b/docs/cli-client/keys/update.md new file mode 100644 index 000000000..eac14aff4 --- /dev/null +++ b/docs/cli-client/keys/update.md @@ -0,0 +1,44 @@ +# iriscli keys update + +## Description + +Change the password used to protect private key + +## Usage + +``` +iriscli keys update <name> [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | --------- | ------------------------------------------------------------ | -------- | +| --help, -h | | help for udpate | | + +## Examples + +### Change the password of a given key + +```shell +iriscli keys update MyKey +``` + +You'll be asked to enter the current password for your key. + +```txt +Enter the current passphrase: +``` + +Then you'll be asked to enter a new password and repeat it. + +```txt +Enter the new passphrase: +Repeat the new passphrase: +``` + +It will be done if you enter a new password that meets the criteria. + +```txt +Password successfully updated! +``` diff --git a/docs/get-started/irislcd.md b/docs/cli-client/lcd/README.md similarity index 61% rename from docs/get-started/irislcd.md rename to docs/cli-client/lcd/README.md index 557fd2fd4..352629f04 100644 --- a/docs/get-started/irislcd.md +++ b/docs/cli-client/lcd/README.md @@ -1,10 +1,17 @@ # 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 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 +## Irislcd usage -To start a irislcd, we need to specify the following parameters: +Irislcd has two subcommands: + +| subcommand | Description | Example command | +| --------------- | --------------------------- | --------------- | +| version | Print the IRISLCD version | IRISLCD version | +| start | Start a IRISLCD node | IRISLCD start --chain-id=<chain-id> | + +`start` subcommand has these options: | Parameter | Type | Default | Required | Description | | --------------- | --------- | ----------------------- | -------- | ---------------------------------------------------- | @@ -14,23 +21,16 @@ To start a irislcd, we need to specify the following parameters: | laddr | string | "tcp://localhost:1317" | false | Address for server to listen on | | trust-node | bool | false | false | Trust connected full nodes (Don't verify proofs for responses) | | max-open | int | 1000 | false | The number of maximum open connections | -| cors | string | "" | false |Set the domains that can make CORS requests | +| cors | string | "" | false | Set the domains that can make CORS requests | -## Start Irislcd +## Sample commands -Sample command to start irislcd: -``` -irislcd start --chain-id=<chain-id> -``` -Please visit the following url with in your internet explorer to open Swagger-UI: -``` -http://localhost:1317/swagger-ui/ -``` -Execute the following command to print the irislcd version. -``` -irislcd version +1. When the connected full node is trusted, then the proof is not necessary, so you can run IRISLCD with trust-node option: +```bash +irislcd start --chain-id=<chain-id> --trust-node ``` -When the connected full node is trusted, then the proof is not necessary, so you can run irislcd with trust-node option: -``` -irislcd start --chain-id=<chain-id> --trust-node \ No newline at end of file +2. If you want to access your IRISLCD in remote machine, you have to specify `--laddr`, for instance: +```bash +irislcd start --chain-id=<chain-id> --laddr=tcp://0.0.0.0:1317 +``` \ No newline at end of file diff --git a/docs/cli-client/record/README.md b/docs/cli-client/record/README.md new file mode 100644 index 000000000..078dfcc66 --- /dev/null +++ b/docs/cli-client/record/README.md @@ -0,0 +1,32 @@ +# iriscli record + +## Description + +Record allows you to submit, query and download your records on chain. + +## Usage + +```shell +iriscli record [command] +``` + +## Record Introduction + +1. Any users can initiate a record request. It will cost you some tokens. If there’s no record of the data on the existing chains, the request will be completed successfully and the relevant metadata will be recorded onchain. And you will be returned a record ID to confirm your ownership of the data. +2. If any others initiate a record request for the same data, the request will be directly rejected and it will hint that the relevant record data has already existed. +3. Any users can search/download on chain based on the record ID. +4. At present, the maximum amount of stored data at most 1K Bytes. In the future, the dynamic adjustment of parameters will be implemented in conjunction with the governance module. + +## Available Commands + +| Name | Description | +| ------------------------| --------------------------------------------------------------| +| [query](query.md) | Query specified record | +| [download](download.md) | Download related data with unique record ID to specified file | +| [submit](submit.md) | Submit a new record | + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | ------- | --------------- | -------- | +| --help, -h | | help for record | | diff --git a/docs/cli-client/record/download.md b/docs/cli-client/record/download.md new file mode 100644 index 000000000..f912c6e2d --- /dev/null +++ b/docs/cli-client/record/download.md @@ -0,0 +1,40 @@ +# iriscli record download + +## Description + +Download related data with unique record ID to specified file + +## Usage + +``` +iriscli record download [record ID] [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ----------------------------------------------------------------- | -------- | +| --chain-id | | [string] Chain ID of tendermint node | Yes | +| --file-name | | [string] Download file name | Yes | +| --height | most recent provable block | [int] block height to query | | +| --help, -h | | help for download | | +| --indent | | Add indent to JSON response | | +| --ledger | | Use a connected Ledger device | | +| --node | tcp://localhost:26657 | [string] \<host>:\<port> to tendermint rpc interface for this chain | | +| --record-id | | [string] record ID | | +| --trust-node | true | Don't verify proofs for responses | | + +## Examples + +### Download a record + +```shell +iriscli record download --chain-id=test --record-id=MyRecordID --file-name="download.txt" +``` + +After that, you will get download file under iriscli home directory with the specfied record ID info. + +```txt +[ONCHAIN] Downloading ~/.iriscli/download.txt from blockchain directly... +[ONCHAIN] Download file from blockchain complete. +``` diff --git a/docs/cli-client/record/query.md b/docs/cli-client/record/query.md new file mode 100644 index 000000000..766e06f53 --- /dev/null +++ b/docs/cli-client/record/query.md @@ -0,0 +1,46 @@ +# iriscli record query + +## Description + +Query details of the existing record + +## Usage + +``` +iriscli record query [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ----------------------------------------------------------------- | -------- | +| --chain-id | | [string] Chain ID of tendermint node | Yes | +| --height | most recent provable block | block height to query | | +| --help, -h | | help for query | | +| --indent | | Add indent to JSON response | | +| --ledger | | Use a connected Ledger device | | +| --node | tcp://localhost:26657 | [string] \<host>:\<port> to tendermint rpc interface for this chain | | +| --record-id | | [string] Record ID for query | Yes | +| --trust-node | true | Don't verify proofs for responses | | + +## Examples + +### Query a record + +```shell +iriscli record query --chain-id=test --record-id=MyRecordID +``` + +After that, you will get detail info for the record which has the specfied record ID. + +```json +{ + "submit_time": "2018-11-13 15:31:36", + "owner_addr": "faa122uzzpugtrzs09nf3uh8xfjaza59xvf9rvthdl", + "record_id": "record:ab5602bac13f11737e8798dd57869c468194efad2db37625795f1efd8d9d63c6", + "description": "description", + "data_hash": "ab5602bac13f11737e8798dd57869c468194efad2db37625795f1efd8d9d63c6", + "data_size": "24", + "data": "this is my on chain data" +} +``` diff --git a/docs/cli-client/record/submit.md b/docs/cli-client/record/submit.md new file mode 100644 index 000000000..87f2c1ad2 --- /dev/null +++ b/docs/cli-client/record/submit.md @@ -0,0 +1,61 @@ +# iriscli record submit + +## Description + +Submit a record on the chain + +## Usage + +``` +iriscli record submit [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ------------------------------------------------------------------------------------------- | -------- | +| --account-number | | [int] AccountNumber number to sign the tx | | +| --async | | Broadcast transactions asynchronously | | +| --chain-id | | [string] Chain ID of tendermint node | Yes | +| --description | description | [string] Uploaded file description | | +| --dry-run | | Ignore the --gas flag and perform a simulation of a transaction, but don't broadcast it | | +| --fee | | [string] Fee to pay along with transaction | Yes | +| --from | | [string] Name of private key with which to sign | Yes | +| --from-addr | | [string] Specify from address in generate-only mode | | +| --gas string | 200000 | Gas limit to set per-transaction; set to "simulate" to calculate required gas automatically | | +| --gas-adjustment | 1 | [float] Adjustment factor to be multiplied against the estimate returned by the tx simulation; if the gas limit is set manually this flag is ignored | | +| --generate-only | | Build an unsigned transaction and write it to STDOUT | | +| -h, --help | | help for submit | | +| --indent | | Add indent to JSON response | | +| --json | | return output in json format | | +| --ledger | | Use a connected Ledger device | | +| --memo | | [string] Memo to send along with transaction | | +| --node | tcp://localhost:26657 | [string] \<host>:\<port> to tendermint rpc interface for this chain | | +| --onchain-data | | [string] on chain data source | Yes | +| --print-response | | return tx response (only works with async = false) | | +| --sequence | | [int] Sequence number to sign the tx | | +| --trust-node | true | Don't verify proofs for responses | | + +## Examples + +### Submit a record + +```shell +iriscli record submit --chain-id="test" --onchain-data="this is my on chain data" --from=node0 --fee=0.1iris +``` + +After that, you're done with submitting a new record, but remember to back up your record id, it's the only way to retrieve your record. + +```txt +Password to sign with 'node0': +Committed at block 72 (tx hash: 7CCC8B4018D4447E6A496923944870E350A1A3AF9E15DB15B8943DAD7B5D782B, response: {Code:0 Data:[114 101 99 111 114 100 58 97 98 53 54 48 50 98 97 99 49 51 102 49 49 55 51 55 101 56 55 57 56 100 100 53 55 56 54 57 99 52 54 56 49 57 52 101 102 97 100 50 100 98 51 55 54 50 53 55 57 53 102 49 101 102 100 56 100 57 100 54 51 99 54] Log:Msg 0: Info: GasWanted:200000 GasUsed:4090 Tags:[{Key:[97 99 116 105 111 110] Value:[115 117 98 109 105 116 45 114 101 99 111 114 100] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[111 119 110 101 114 65 100 100 114 101 115 115] Value:[102 97 97 49 50 50 117 122 122 112 117 103 116 114 122 115 48 57 110 102 51 117 104 56 120 102 106 97 122 97 53 57 120 118 102 57 114 118 116 104 100 108] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[114 101 99 111 114 100 45 105 100] Value:[114 101 99 111 114 100 58 97 98 53 54 48 50 98 97 99 49 51 102 49 49 55 51 55 101 56 55 57 56 100 100 53 55 56 54 57 99 52 54 56 49 57 52 101 102 97 100 50 100 98 51 55 54 50 53 55 57 53 102 49 101 102 100 56 100 57 100 54 51 99 54] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 50 48 52 53 48 48 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "submit-record", + "completeConsumedTxFee-iris-atto": "\"2045000000000000\"", + "ownerAddress": "faa122uzzpugtrzs09nf3uh8xfjaza59xvf9rvthdl", + "record-id": "record:ab5602bac13f11737e8798dd57869c468194efad2db37625795f1efd8d9d63c6" + } + } +``` + diff --git a/docs/cli-client/service/README.md b/docs/cli-client/service/README.md new file mode 100644 index 000000000..62e207bcd --- /dev/null +++ b/docs/cli-client/service/README.md @@ -0,0 +1,30 @@ +# iriscli service + +## Description +Service allows you to define、bind、invocate a service on chain. + +## Usage + +```shell +iriscli service [command] +``` + +## Available Commands + +| Name | Description | +| ------------------------------------ | ----------------------------------------- | +| [define](define.md) | Create a new service definition | +| [definition](definition.md) | Query service definition | +| [bind](bind.md) | Create a new service binding | +| [binding](binding.md) | Query service binding | +| [bindings](bindings.md) | Query service bindings | +| [update-binding](update-binding.md) | Update a service binding | +| [disable](disable.md) | Disable a available service binding | +| [enable](enable.md) | Enable an unavailable service binding | +| [refund-deposit](refund-deposit.md) | Refund all deposit from a service binding | + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | ------- | ---------------- | -------- | +| --help, -h | | help for service | | \ No newline at end of file diff --git a/docs/cli-client/service/bind.md b/docs/cli-client/service/bind.md new file mode 100644 index 000000000..fc2a609ea --- /dev/null +++ b/docs/cli-client/service/bind.md @@ -0,0 +1,45 @@ +# iriscli service bind + +## Description + +Create a new service binding + +## Usage + +``` +iriscli service bind [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --avg-rsp-time | | [int] the average service response time in milliseconds | Yes | +| --bind-type | | [string] type of binding, valid values can be Local and Global | Yes | +| --def-chain-id | | [string] the ID of the blockchain defined of the service | Yes | +| --deposit | | [string] deposit of binding | Yes | +| --prices | | [strings] prices of binding, will contains all method | | +| --service-name | | [string] service name | Yes | +| --usable-time | | [int] an integer represents the number of usable service invocations per 10,000 | Yes | +| -h, --help | | help for bind | | + +## Examples + +### Add a binding to an existing service definition +```shell +iriscli service bind --chain-id=test --from=node0 --fee=0.004iris --service-name=test-service --def-chain-id=test --bind-type=Local --deposit=1iris --prices=1iris --avg-rsp-time=10000 --usable-time=100 +``` + +After that, you're done with adding a binding to an existing service definition. + +```txt +Password to sign with 'node0': +Committed at block 6 (tx hash: 87A477AEA41B22F7294084B4794837211C43A297D73EABA2F42F6436F3D975DD, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:5568 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 98 105 110 100] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 49 49 49 51 54 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-bind", + "completeConsumedTxFee-iris-atto": "\"111360000000000\"" + } + } +``` + diff --git a/docs/cli-client/service/binding.md b/docs/cli-client/service/binding.md new file mode 100644 index 000000000..8c5e2554a --- /dev/null +++ b/docs/cli-client/service/binding.md @@ -0,0 +1,62 @@ +# iriscli service binding + +## Description + +Query service binding + +## Usage + +``` +iriscli service binding [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ------------------------------------------------------------------- | -------- | +| --bind-chain-id | | [string] the ID of the blockchain bond of the service | Yes | +| --def-chain-id | | [string] the ID of the blockchain defined of the service | Yes | +| --provider | | [string] bech32 encoded account created the service binding | Yes | +| --service-name | | [string] service name | Yes | +| --help, -h | | help for binding | | + +## Examples + +### Query a service binding + +```shell +iriscli service binding --def-chain-id=test --service-name=test-service --bind-chain-id=test --provider=faa1ydhmma8l4m9dygsh7l08fgrwka6yczs0gkfnvd +``` + +After that, you will get detail info for the service binding. + +```json +{ + "type": "iris-hub/service/SvcBinding", + "value": { + "def_name": "test-service", + "def_chain_id": "test", + "bind_chain_id": "test", + "provider": "faa1ydhmma8l4m9dygsh7l08fgrwka6yczs0gkfnvd", + "binding_type": "Local", + "deposit": [ + { + "denom": "iris-atto", + "amount": "1000000000000000000000" + } + ], + "price": [ + { + "denom": "iris-atto", + "amount": "1000000000000000000" + } + ], + "level": { + "avg_rsp_time": "10000", + "usable_time": "100" + }, + "available": true, + "disable_height": "0" + } +} +``` \ No newline at end of file diff --git a/docs/cli-client/service/bindings.md b/docs/cli-client/service/bindings.md new file mode 100644 index 000000000..8634882e4 --- /dev/null +++ b/docs/cli-client/service/bindings.md @@ -0,0 +1,53 @@ +# iriscli service bindings + +## Description + +Query service bindings + +## Usage + +``` +iriscli service bindings [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ------------------------------------------------------------------- | -------- | +| --def-chain-id | | [string] the ID of the blockchain defined of the service | Yes | +| --service-name | | [string] service name | Yes | +| --help, -h | | help for bindings | | + +## Examples + +### Query service binding list + +```shell +iriscli service bindings --def-chain-id=test --service-name=test-service +``` + +After that, you will get a binding list of the service definition. + +```json +[{ + "def_name": "test-service", + "def_chain_id": "test", + "bind_chain_id": "test", + "provider": "faa1ydhmma8l4m9dygsh7l08fgrwka6yczs0gkfnvd", + "binding_type": "Local", + "deposit": [{ + "denom": "iris-atto", + "amount": "1000000000000000000000" + }], + "price": [{ + "denom": "iris-atto", + "amount": "1000000000000000000" + }], + "level": { + "avg_rsp_time": "10000", + "usable_time": "100" + }, + "available": true, + "disable_height": "0" +}] +``` \ No newline at end of file diff --git a/docs/cli-client/service/define.md b/docs/cli-client/service/define.md new file mode 100644 index 000000000..ff85b2f59 --- /dev/null +++ b/docs/cli-client/service/define.md @@ -0,0 +1,54 @@ +# iriscli service define + +## Description + +Create a new service definition + +## Usage + +``` +iriscli service define [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --service-description | | [string] service description | | +| --author-description | | [string] service author description | | +| --service-name | | [string] service name | Yes | +| --tags | | [strings] service tags | | +| --idl-content | | [string] content of service interface description language | | +| --file | | [string] path of file which contains service interface description language | | +| -h, --help | | help for define | | + +## Examples + +### define a service +```shell +iriscli service define --chain-id=test --from=node0 --fee=0.004iris --service-name=test-service --service-description=service-description --author-description=author-description --tags=tag1,tag2 --idl-content=<idl-content> --file=test.proto +``` +Idl-content can be replaced by file if the file item is not empty. [Example of IDL content](#idl-content-example). + +After that, you're done with defining a new service. + +```txt +Password to sign with 'node0': +Committed at block 65 (tx hash: 663B676E453F91BFCDC87B0308910501DD14DF79C88390FC15E06C4CC9612422, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:7968 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 100 101 102 105 110 101] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 49 53 57 51 54 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-define", + "completeConsumedTxFee-iris-atto": "\"159360000000000\"" + } + } +``` + +### IDL content example +* idl-content example + + > syntax = \\"proto3\\";\n\npackage helloworld;\n\n// The greeting service definition.\nservice Greeter {\n //@Attribute description: sayHello\n //@Attribute output_privacy: NoPrivacy\n //@Attribute output_cached: NoCached\n rpc SayHello (HelloRequest) returns (HelloReply) {}\n}\n\n// The request message containing the user's name.\nmessage HelloRequest {\n string name = 1;\n}\n\n// The response message containing the greetings\nmessage HelloReply {\n string message = 1;\n}\n + +* IDL file example + + [test.proto](../../features/test.proto) + diff --git a/docs/cli-client/service/definition.md b/docs/cli-client/service/definition.md new file mode 100644 index 000000000..6ad5e85ca --- /dev/null +++ b/docs/cli-client/service/definition.md @@ -0,0 +1,55 @@ +# iriscli service definition + +## Description + +Query service definition + +## Usage + +``` +iriscli service definition [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ------------------------------------------------------------------- | -------- | +| --def-chain-id | | [string] the ID of the blockchain defined of the service | Yes | +| --service-name | | [string] service name | Yes | +| --help, -h | | help for definition | | + +## Examples + +### Query a service definition + +```shell +iriscli service definition --def-chain-id=test --service-name=test-service +``` + +After that, you will get detail info for the service definition which has the specfied define chain id and service name. + +```json +{ + "SvcDef": { + "name": "test-service", + "chain_id": "test", + "description": "service-description", + "tags": [ + "tag1", + "tag2" + ], + "author": "faa1ydhmma8l4m9dygsh7l08fgrwka6yczs0gkfnvd", + "author_description": "author-description", + "idl_content": "syntax = \"proto3\";\n\npackage helloworld;\n\n// The greeting service definition.\nservice Greeter {\n //@Attribute description: sayHello\n //@Attribute output_privacy: NoPrivacy\n //@Attribute output_cached: NoCached\n rpc SayHello (HelloRequest) returns (HelloReply) {}\n}\n\n// The request message containing the user's name.\nmessage HelloRequest {\n string name = 1;\n}\n\n// The response message containing the greetings\nmessage HelloReply {\n string message = 1;\n}\n" + }, + "methods": [ + { + "id": "1", + "name": "SayHello", + "description": "sayHello", + "output_privacy": "NoPrivacy", + "output_cached": "NoCached" + } + ] +} +``` \ No newline at end of file diff --git a/docs/cli-client/service/disable.md b/docs/cli-client/service/disable.md new file mode 100644 index 000000000..fdaa07e32 --- /dev/null +++ b/docs/cli-client/service/disable.md @@ -0,0 +1,39 @@ +# iriscli service disable + +## Description + +Disable a available service binding + +## Usage + +``` +iriscli service disable [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --def-chain-id | | [string] the ID of the blockchain defined of the service | Yes | +| --service-name | | [string] service name | Yes | +| -h, --help | | help for disable | | + +## Examples + +### Disable a available service binding +```shell +iriscli service disable --chain-id=test --from=node0 --fee=0.004iris --def-chain-id=test --service-name=test-service +``` + +After that, you're done with disabling a available service binding. + +```txt +Password to sign with 'node0': +Committed at block 537 (tx hash: 66C5EE634339D168A07C073C6BF209D80081762EB8451974ABC33A41914A7158, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:3510 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 100 105 115 97 98 108 101] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 55 48 50 48 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-disable", + "completeConsumedTxFee-iris-atto": "\"70200000000000\"" + } + } +``` \ No newline at end of file diff --git a/docs/cli-client/service/enable.md b/docs/cli-client/service/enable.md new file mode 100644 index 000000000..91057770a --- /dev/null +++ b/docs/cli-client/service/enable.md @@ -0,0 +1,39 @@ +# iriscli service enable + +## Description + +Enable an unavailable service binding + +## Usage + +``` +iriscli service enable [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --def-chain-id | | [string] the ID of the blockchain defined of the service | Yes | +| --deposit string | | [string] deposit of binding, will add to the current deposit balance | | +| --service-name | | [string] service name | Yes | +| -h, --help | | help for enable | | + +## Examples + +### Enable a unavailable service binding +```shell +iriscli service enable --chain-id=test --from=node0 --fee=0.004iris --def-chain-id=test --service-name=test-service +``` + +After that, you're done with Enabling a available service binding. + +```txt +Committed at block 654 (tx hash: CF74E7629F0098AC3295F454F5C15BD5846A1F77C4E6C6FBA551606672B364DD, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:5036 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 101 110 97 98 108 101] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 49 48 48 55 50 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-enable", + "completeConsumedTxFee-iris-atto": "\"100720000000000\"" + } + } +``` \ No newline at end of file diff --git a/docs/cli-client/service/refund-deposit.md b/docs/cli-client/service/refund-deposit.md new file mode 100644 index 000000000..845c88b09 --- /dev/null +++ b/docs/cli-client/service/refund-deposit.md @@ -0,0 +1,39 @@ +# iriscli service refund-deposit + +## Description + +Refund all deposit from a service binding + +## Usage + +``` +iriscli service refund-deposit [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --def-chain-id | | [string] the ID of the blockchain defined of the service | Yes | +| --service-name | | [string] service name | Yes | +| -h, --help | | help for refund-deposit | | + +## Examples + +### Refund all deposit from an unavailable service binding +```shell +iriscli service refund-deposit --chain-id=test --from=node0 --fee=0.004iris --def-chain-id=test --service-name=test-service +``` + +After that, you're done with refunding all deposit from a service binding. + +```txt +Password to sign with 'node0': +Committed at block 991 (tx hash: 8A7F0EA61AB73A8B241945C8942EC8593774346B36BB70E36E138A23E7A473EE, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:4614 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 114 101 102 117 110 100 45 100 101 112 111 115 105 116] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 57 50 50 56 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-refund-deposit", + "completeConsumedTxFee-iris-atto": "\"92280000000000\"" + } + } +``` \ No newline at end of file diff --git a/docs/cli-client/service/update-binding.md b/docs/cli-client/service/update-binding.md new file mode 100644 index 000000000..f7c34f303 --- /dev/null +++ b/docs/cli-client/service/update-binding.md @@ -0,0 +1,44 @@ +# iriscli service update-binding + +## Description + +Update a service binding + +## Usage + +``` +iriscli service update-binding [flags] +``` + +## Flags +| Name, shorthand | Default | Description | Required | +| --------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --avg-rsp-time | | [int] the average service response time in milliseconds | | +| --bind-type | | [string] type of binding, valid values can be Local and Global | | +| --def-chain-id | | [string] the ID of the blockchain defined of the service | Yes | +| --deposit | | [string] deposit of binding, will add to the current deposit balance | | +| --prices | | [strings] prices of binding, will contains all method | | +| --service-name | | [string] service name | Yes | +| --usable-time | | [int] an integer represents the number of usable service invocations per 10,000 | | +| -h, --help | | help for update-binding | | + +## Examples + +### Update an existing service binding +```shell +iriscli service update-binding --chain-id=test --from=node0 --fee=0.004iris --service-name=test-service --def-chain-id=test --bind-type=Local --deposit=1iris --prices=1iris --avg-rsp-time=10000 --usable-time=100 +``` + +After that, you're done with updating an existing service binding. + +```txt +Password to sign with 'node0': +Committed at block 417 (tx hash: 8C9969A2BF3F7A8C13C2E0B57CE4FD7BE43454280559831D7E39B0FD3C1FCD28, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:5042 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 117 112 100 97 116 101 45 98 105 110 100 105 110 103] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 49 48 48 56 52 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-update-binding", + "completeConsumedTxFee-iris-atto": "\"100840000000000\"" + } + } +``` + diff --git a/docs/cli-client/stake/README.md b/docs/cli-client/stake/README.md new file mode 100644 index 000000000..883278ae2 --- /dev/null +++ b/docs/cli-client/stake/README.md @@ -0,0 +1,41 @@ +# iriscli stake + +## Introduction + +Stake module provides a set of subcommands to query staking state and send staking transactions. + +## Usage + +``` +iriscli stake [subcommand] [flags] +``` + +Print all supported subcommands and flags: +``` +iriscli stake --help +``` + +## Available Commands + +| Name | Description | +| --------------------------------| --------------------------------------------------------------| +| [validator](validator.md) | Query a validator | +| [validators](validators.md) | Query for all validators | +| [delegation](delegation.md) | Query a delegation based on address and validator address | +| [delegations](delegations.md) | Query all delegations made from one delegator | +| [unbonding-delegation](unbonding-delegation.md) | Query an unbonding-delegation record based on delegator and validator address | +| [unbonding-delegations](unbonding-delegations.md) | Query all unbonding-delegations records for one delegator | +| [unbonding-delegations-from](unbonding-delegations-from.md) | Query all unbonding delegatations from a validator | +| [redelegations-from](redelegations-from.md) | Query all outgoing redelegatations from a validator | +| [redelegation](redelegation.md) | Query a redelegation record based on delegator and a source and destination validator address | +| [redelegations](redelegations.md) | Query all redelegations records for one delegator | +| [pool](pool.md) | Query the current staking pool values | +| [parameters](parameters.md) | Query the current staking parameters information | +| [signing-info](signing-info.md) | Query a validator's signing information | +| [create-validator](create-validator.md) | Create new validator initialized with a self-delegation to it | +| [edit-validator](edit-validator.md) | Edit and existing validator account | +| [delegate](delegate.md) | Delegate liquid tokens to an validator | +| [unbond](unbond.md) | Unbond shares from a validator | +| [redelegate](redelegate.md) | Redelegate illiquid tokens from one validator to another | +| [unjail](unjail.md) | Unjail validator previously jailed for downtime | + diff --git a/docs/cli-client/stake/create-validator.md b/docs/cli-client/stake/create-validator.md new file mode 100644 index 000000000..bf9b36209 --- /dev/null +++ b/docs/cli-client/stake/create-validator.md @@ -0,0 +1,39 @@ +# iriscli stake create-validator + +## Introduction + +Send transaction to apply to be validator and delegate a certain amount tokens on it + +## Usage + +``` +iriscli stake create-validator [flags] +``` + +Print help messages: +``` +iriscli stake create-validator --help +``` + +## Unique Flags + +| Name, shorthand | type | Required | Default | Description | +| ---------------------------- | ----- | -------- | -------- | ------------------------------------------------------------------- | +| --amount | string | true | "" | Amount of coins to bond | +| --commission-max-change-rate | float | true | 0.0 | The maximum commission change rate percentage (per day)| +| --commission-max-rate | float | true | 0.0 | The maximum commission rate percentage | +| --commission-rate | float | true | 0.0 | The initial commission rate percentage | +| --details | string | false | "" | Optional details | +| --genesis-format | bool | false | false | Export the transaction in gen-tx format; it implies --generate-only | +| --identity | string | false | "" | Optional identity signature (ex. UPort or Keybase) | +| --ip | string | false | "" | Node's public IP. It takes effect only when used in combination with | +| --moniker | string | true | "" | Validator name | +| --pubkey | string | true | "" | Go-Amino encoded hex PubKey of the validator. For Ed25519 the go-amino prepend hex is 1624de6220 | +| --website | string | false | "" | Optional website | + +## Examples + +``` +iriscli stake create-validator --chain-id=<chain-id> --from=<key name> --fee=0.004iris --pubkey=<Validator PubKey> --commission-max-change-rate=0.01 --commission-max-rate=0.2 --commission-rate=0.1 --amount=100iris --moniker=<validator name> +``` + diff --git a/docs/cli-client/stake/delegate.md b/docs/cli-client/stake/delegate.md new file mode 100644 index 000000000..944692c31 --- /dev/null +++ b/docs/cli-client/stake/delegate.md @@ -0,0 +1,29 @@ +# iriscli stake delegate + +## Introduction + +Delegate tokens to a validator + +## Usage + +``` +iriscli stake delegate [flags] +``` + +Print help messages: +``` +iriscli stake delegate --help +``` + +## Unique Flags + +| Name, shorthand | type | Required | Default | Description | +| --------------------| ----- | -------- | -------- | ------------------------------------------------------------------- | +| --address-delegator | string | true | "" | Bech address of the delegator | +| --amount | string | true | "" | Amount of coins to bond | + +## Examples + +``` +iriscli stake delegate --chain-id=<chain-id> --from=<key name> --fee=0.004iris --amount=100iris --address-validator=<ValidatorAddress> +``` diff --git a/docs/cli-client/stake/delegation.md b/docs/cli-client/stake/delegation.md new file mode 100644 index 000000000..a15276594 --- /dev/null +++ b/docs/cli-client/stake/delegation.md @@ -0,0 +1,39 @@ +# iriscli stake delegation + +## Description + +Query a delegation based on address and validator address + +## Usage + +``` +iriscli stake delegation [flags] +``` +Print help messages: +``` +iriscli stake delegation --help +``` + +## Unique Flags + +| Name, shorthand | Default | Description | Required | +| --------------------- | -------------------------- | -------------------------------------------------------------------- | -------- | +| --address-delegator | | [string] Bech address of the delegator | Yes | +| --address-validator | | [string] Bech address of the validator | Yes | + +## Examples + +Query a validator +``` +iriscli stake delegation --address-validator=ValidatorAddress --address-delegator=DelegatorAddress + +``` + +After that, you will get detailed info of the delegation between specified validator and delegator. + +```txt +Delegation +Delegator: faa13lcwnxpyn2ea3skzmek64vvnp97jsk8qmhl6vx +Validator: fva15grv3xg3ekxh9xrf79zd0w077krgv5xf6d6thd +Shares: 0.2000000000Height: 290 +``` diff --git a/docs/cli-client/stake/delegations.md b/docs/cli-client/stake/delegations.md new file mode 100644 index 000000000..d59b1215f --- /dev/null +++ b/docs/cli-client/stake/delegations.md @@ -0,0 +1,35 @@ +# iriscli stake delegations + +## Description + +Query all delegations made from one delegator + +## Usage + +``` +iriscli stake delegations [delegator-address] [flags] +``` +Print help messages: +``` +iriscli stake delegations --help +``` + +## Examples + +Query all delegations made from one delegator +``` +iriscli stake delegations [delegator-address] +``` + +After that, you will get all detailed info of delegations from the specified delegator address. + +```json +[ + { + "delegator_addr": "faa13lcwnxpyn2ea3skzmek64vvnp97jsk8qmhl6vx", + "validator_addr": "fva15grv3xg3ekxh9xrf79zd0w077krgv5xf6d6thd", + "shares": "0.2000000000", + "height": "290" + } +] +``` diff --git a/docs/cli-client/stake/edit-validator.md b/docs/cli-client/stake/edit-validator.md new file mode 100644 index 000000000..0494db6ef --- /dev/null +++ b/docs/cli-client/stake/edit-validator.md @@ -0,0 +1,32 @@ +# iriscli stake edit-validator + +## Introduction + +Edit existing validator, such as commission rate, name and other description message. + +## Usage + +``` +iriscli stake edit-validator [flags] +``` +Print help messages: +``` +iriscli stake edit-validator --help +``` + +## Unique Flags + +| Name, shorthand | type | Required | Default | Description | +| --------------------| ----- | -------- | -------- | ------------------------------------------------------------------- | +| --commission-rate | string | float | 0.0 | Commission rate percentage | +| --moniker | string | false | "" | Validator name | +| --identity | string | false | "" | Optional identity signature (ex. UPort or Keybase) | +| --website | string | false | "" | Optional website | +| --details | string | false | "" | Optional details | + + +## Examples + +``` +iriscli stake edit-validator --from=<key name> --chain-id=<chain-id> --fee=0.004iris --commission-rate=0.15 +``` diff --git a/docs/cli-client/stake/parameters.md b/docs/cli-client/stake/parameters.md new file mode 100644 index 000000000..93a51c46a --- /dev/null +++ b/docs/cli-client/stake/parameters.md @@ -0,0 +1,31 @@ +# iriscli stake parameters + +## Description + +Query the current staking parameters information + +## Usage + +``` +iriscli stake parameters [flags] +``` +Print help messages: +``` +iriscli stake parameters --help +``` + +## Examples + +Query the current staking parameters information +``` +iriscli stake parameters +``` + +After that, you will get the current staking parameters information. + +```txt +Params +Unbonding Time: 10m0s +Max Validators: 100: +Bonded Coin Denomination: iris-atto +``` diff --git a/docs/cli-client/stake/pool.md b/docs/cli-client/stake/pool.md new file mode 100644 index 000000000..6f89128ad --- /dev/null +++ b/docs/cli-client/stake/pool.md @@ -0,0 +1,32 @@ +# iriscli stake pool + +## Description + +Query the current staking pool values + +## Usage + +``` +iriscli stake pool [flags] +``` +Print help messages: +``` +iriscli stake pool --help +``` + +## Examples + +Query the current staking pool values +``` +iriscli stake pool +``` + +After that, you will get the current staking pool values. + +```txt +Pool +Loose Tokens: 49.8289125612 +Bonded Tokens: 100.1800000000 +Token Supply: 150.0089125612 +Bonded Ratio: 0.6678269863 +``` diff --git a/docs/cli-client/stake/redelegate.md b/docs/cli-client/stake/redelegate.md new file mode 100644 index 000000000..a1c756f08 --- /dev/null +++ b/docs/cli-client/stake/redelegate.md @@ -0,0 +1,34 @@ +# iriscli stake redelegate + +## Introduction + +Transfer delegation from one validator to another one. + +## Usage + +``` +iriscli stake redelegate [flags] +``` + +Print help messages: + +``` +iriscli stake redelegate --help +``` + +## Unique Flags + +| Name, shorthand | type | Required | Default | Description | +| -------------------------- | ----- | -------- | -------- | ------------------------------------------------------------------- | +| --address-validator-dest | string | true | "" | Bech address of the destination validator | +| --address-validator-source | string | true | "" | Bech address of the source validator | +| --shares-amount | float | false | 0.0 | Amount of source-shares to either unbond or redelegate as a positive integer or decimal | +| --shares-percent | float | false | 0.0 | Percent of source-shares to either unbond or redelegate as a positive integer or decimal >0 and <=1 | + +Users must specify the redeleagtion token amount. There two options can do this: `--shares-amount` or `--shares-percent`. Keep in mind, don't specify both of them. + +## Examples + +``` +iriscli stake redelegate --chain-id=<chain-id> --from=<key name> --fee=0.004iris --address-validator-source=<SourceValidatorAddress> --address-validator-dest=<DestinationValidatorAddress> --shares-percent=0.1 +``` diff --git a/docs/cli-client/stake/redelegation.md b/docs/cli-client/stake/redelegation.md new file mode 100644 index 000000000..dc2c59ee6 --- /dev/null +++ b/docs/cli-client/stake/redelegation.md @@ -0,0 +1,43 @@ +# iriscli stake redelegation + +## Description + +Query a redelegation record based on delegator and a source and destination validator address + +## Usage + +``` +iriscli stake redelegation [flags] +``` +Print help messages: +``` +iriscli stake redelegation --help +``` + +## Unique Flags + +| Name, shorthand | Default | Description | Required | +| -------------------------- | -------------------------- | ------------------------------------------------------------------- | -------- | +| --address-delegator | | [string] Bech address of the delegator | Yes | +| --address-validator-dest | | [string] Bech address of the destination validator | Yes | +| --address-validator-source | | [string] Bech address of the source validator | Yes | + +## Examples + +Query a redelegation record +``` +iriscli stake redelegation --address-validator-source=SourceValidatorAddress --address-validator-dest=DestinationValidatorAddress --address-delegator=DelegatorAddress +``` + +After that, you will get specified redelegation's info based on delegator and a source and destination validator address + +```txt +Redelegation +Delegator: faa10s0arq9khpl0cfzng3qgxcxq0ny6hmc9sytjfk +Source Validator: fva1dayujdfnxjggd5ydlvvgkerp2supknthajpch2 +Destination Validator: fva1h27xdw6t9l5jgvun76qdu45kgrx9lqede8hpcd +Creation height: 1130 +Min time to unbond (unix): 2018-11-16 07:22:48.740311064 +0000 UTC +Source shares: 0.1000000000 +Destination shares: 0.1000000000 +``` diff --git a/docs/cli-client/stake/redelegations-from.md b/docs/cli-client/stake/redelegations-from.md new file mode 100644 index 000000000..bacdf391e --- /dev/null +++ b/docs/cli-client/stake/redelegations-from.md @@ -0,0 +1,46 @@ +# iriscli stake redelegations-from + +## Description + +Query all outgoing redelegatations from a validator + +## Usage + +``` +iriscli stake redelegations-from [validator-address] [flags] +``` +Print help messages: +``` +iriscli stake redelegations-from --help +``` + +## Examples + +Query all outgoing redelegatations +``` +iriscli stake redelegations-from [validator-address] +``` + +After that, you will get all outgoing redelegatations' from specified validator + +```json +[ + { + "delegator_addr": "faa10s0arq9khpl0cfzng3qgxcxq0ny6hmc9sytjfk", + "validator_src_addr": "fva1dayujdfnxjggd5ydlvvgkerp2supknthajpch2", + "validator_dst_addr": "fva1h27xdw6t9l5jgvun76qdu45kgrx9lqede8hpcd", + "creation_height": "1130", + "min_time": "2018-11-16T07:22:48.740311064Z", + "initial_balance": { + "denom": "iris-atto", + "amount": "100000000000000000" + }, + "balance": { + "denom": "iris-atto", + "amount": "100000000000000000" + }, + "shares_src": "100000000000000000.0000000000", + "shares_dst": "100000000000000000.0000000000" + } +] +``` diff --git a/docs/cli-client/stake/redelegations.md b/docs/cli-client/stake/redelegations.md new file mode 100644 index 000000000..5ef565bb8 --- /dev/null +++ b/docs/cli-client/stake/redelegations.md @@ -0,0 +1,40 @@ +# iriscli stake redelegations + +## Description + +Query all redelegations records for one delegator + +## Usage + +``` +iriscli stake redelegations [delegator-address] [flags] +``` +Print help messages: +``` +iriscli stake redelegations --help +``` + +## Examples + +Query all redelegations records +``` +iriscli stake redelegations [delegator-address] +``` + +After that, you will get all redelegations records' info for specified delegator + +```json +[ + { + "delegator_addr": "faa10s0arq9khpl0cfzng3qgxcxq0ny6hmc9sytjfk", + "validator_src_addr": "fva1dayujdfnxjggd5ydlvvgkerp2supknthajpch2", + "validator_dst_addr": "fva1h27xdw6t9l5jgvun76qdu45kgrx9lqede8hpcd", + "creation_height": "1130", + "min_time": "2018-11-16T07:22:48.740311064Z", + "initial_balance": "0.1iris", + "balance": "0.1iris", + "shares_src": "0.1000000000", + "shares_dst": "0.1000000000" + } +] +``` diff --git a/docs/cli-client/stake/signing-info.md b/docs/cli-client/stake/signing-info.md new file mode 100644 index 000000000..6747039d9 --- /dev/null +++ b/docs/cli-client/stake/signing-info.md @@ -0,0 +1,29 @@ +# iriscli stake signing-info + +## Description + +Query a validator's signing information + +## Usage + +``` +iriscli stake signing-info [validator-pubkey] [flags] +``` +Print help messages: +``` +iriscli stake signing-info --help +``` + +## Examples + +### Query specified validator's signing information + +``` +iriscli stake signing-info [validator-pubkey] +``` + +After that, you will get specified validator's signing information. + +```txt +Start height: 0, index offset: 2136, jailed until: 1970-01-01 00:00:00 +0000 UTC, missed blocks counter: 0 +``` diff --git a/docs/cli-client/stake/unbond.md b/docs/cli-client/stake/unbond.md new file mode 100644 index 000000000..a1f307de7 --- /dev/null +++ b/docs/cli-client/stake/unbond.md @@ -0,0 +1,32 @@ +# iriscli stake unbond + +## Introduction + +Unbond tokens from a validator + +## Usage + +``` +iriscli stake unbond [flags] +``` + +Print help messages: +``` +iriscli stake unbond --help +``` + +## Unique Flags + +| Name, shorthand | type | Required | Default | Description | +| --------------------| ----- | -------- | -------- | ------------------------------------------------------------------- | +| --address-validator | string | true | "" | Bech address of the validator | +| --shares-amount | float | false | 0.0 | Amount of source-shares to either unbond or redelegate as a positive integer or decimal | +| --shares-percent | float | false | 0.0 | Percent of source-shares to either unbond or redelegate as a positive integer or decimal >0 and <=1 | + +Users must specify the unbond amount. There two options can do this: `--shares-amount` or `--shares-percent`. Keep in mind, don't specify both of them. + +## Examples + +``` +iriscli stake unbond --address-validator=<ValidatorAddress> --shares-percent=0.1 --from=<key name> --chain-id=<chain-id> --fee=0.004iris +``` diff --git a/docs/cli-client/stake/unbonding-delegation.md b/docs/cli-client/stake/unbonding-delegation.md new file mode 100644 index 000000000..c5975b6f1 --- /dev/null +++ b/docs/cli-client/stake/unbonding-delegation.md @@ -0,0 +1,41 @@ +# iriscli stake unbonding-delegation + +## Description + +Query an unbonding-delegation record based on delegator and validator address + +## Usage + +``` +iriscli stake unbonding-delegation [flags] +``` +Print help messages: +``` +iriscli stake unbonding-delegation --help +``` + +## Unique Flags + +| Name, shorthand | Default | Description | Required | +| ------------------- | -------------------------- | ------------------------------------------------------------------- | -------- | +| --address-delegator | | [string] Bech address of the delegator | Yes | +| --address-validator | | [string] Bech address of the validator | Yes | + + +## Examples + +Query an unbonding-delegation +``` +iriscli stake unbonding-delegation --address-delegator=DelegatorAddress --address-validator=ValidatorAddress +``` + +After that, you will get unbonding delegation's detailed info between specified validator and delegator. + +```txt +Unbonding Delegation +Delegator: faa13lcwnxpyn2ea3skzmek64vvnp97jsk8qmhl6vx +Validator: fva15grv3xg3ekxh9xrf79zd0w077krgv5xf6d6thd +Creation height: 1310 +Min time to unbond (unix): 2018-11-15 06:24:22.754703377 +0000 UTC +Expected balance: 0.02iris +``` diff --git a/docs/cli-client/stake/unbonding-delegations-from.md b/docs/cli-client/stake/unbonding-delegations-from.md new file mode 100644 index 000000000..ebac8617a --- /dev/null +++ b/docs/cli-client/stake/unbonding-delegations-from.md @@ -0,0 +1,43 @@ +# iriscli stake unbonding-delegations-from + +## Description + +Query all unbonding delegatations from a validator + +## Usage + +``` +iriscli stake unbonding-delegations-from [validator-address] [flags] +``` +Print help messages: +``` +iriscli stake unbonding-delegations-from --help +``` + +## Examples + +Query all unbonding delegatations from a validator +``` +iriscli stake unbonding-delegations [validator-address] +``` + +After that, you will get unbonding delegation's detailed info from specified validator. + +```json +[ + { + "delegator_addr": "faa13lcwnxpyn2ea3skzmek64vvnp97jsk8qmhl6vx", + "validator_addr": "fva15grv3xg3ekxh9xrf79zd0w077krgv5xf6d6thd", + "creation_height": "1310", + "min_time": "2018-11-15T06:24:22.754703377Z", + "initial_balance": { + "denom": "iris-atto", + "amount": "20000000000000000" + }, + "balance": { + "denom": "iris-atto", + "amount": "20000000000000000" + } + } +] +``` diff --git a/docs/cli-client/stake/unbonding-delegations.md b/docs/cli-client/stake/unbonding-delegations.md new file mode 100644 index 000000000..6280ebdf3 --- /dev/null +++ b/docs/cli-client/stake/unbonding-delegations.md @@ -0,0 +1,37 @@ +# iriscli stake unbonding-delegations + +## Description + +Query all unbonding-delegations records for one delegator + +## Usage + +``` +iriscli stake unbonding-delegations [delegator-address] [flags] +``` +Print help messages: +``` +iriscli stake unbonding-delegations --help +``` + +## Examples + +Query an unbonding-delegation +``` +iriscli stake unbonding-delegations [delegator-address] +``` + +After that, you will get unbonding delegation's detailed info from specified delegator. + +```json +[ + { + "delegator_addr": "faa13lcwnxpyn2ea3skzmek64vvnp97jsk8qmhl6vx", + "validator_addr": "fva15grv3xg3ekxh9xrf79zd0w077krgv5xf6d6thd", + "creation_height": "1310", + "min_time": "2018-11-15T06:24:22.754703377Z", + "initial_balance": "0.02iris", + "balance": "0.02iris" + } +] +``` diff --git a/docs/cli-client/stake/unjail.md b/docs/cli-client/stake/unjail.md new file mode 100644 index 000000000..ccbb2c881 --- /dev/null +++ b/docs/cli-client/stake/unjail.md @@ -0,0 +1,24 @@ +# iriscli stake unjail + +## Introduction + +Unjail validator which may be jailed previously for downtime + +## Usage + +``` +iriscli stake unjail [flags] +``` + +Print help messages: +``` +iriscli stake unjail --help +``` + +## Examples + +### Unjail validator previously jailed for downtime + +``` +iriscli stake unjail --from=<key name> --fee=0.004iris --chain-id=<chain-id> +``` diff --git a/docs/cli-client/stake/validator.md b/docs/cli-client/stake/validator.md new file mode 100644 index 000000000..5ebc3df79 --- /dev/null +++ b/docs/cli-client/stake/validator.md @@ -0,0 +1,39 @@ +# iriscli stake validator + +## Description + +Query a validator + +## Usage + +``` +iriscli stake validator [validator-address] [flags] +``` +Print help messages: +``` +iriscli stake validator --help +``` + +## Examples + +Query a validator +``` +iriscli stake validator [validator-address] +``` + +After that, you will get the specified validator's info. + +```txt +Validator +Operator Address: fva15grv3xg3ekxh9xrf79zd0w077krgv5xf6d6thd +Validator Consensus Pubkey: fvp1zcjduepq47906n2zvq597vwyqdc0h35ve0fcl64hwqs9xw5fg67zj4g658aqyuhepj +Jailed: false +Status: Bonded +Tokens: 100.0000000000 +Delegator Shares: 100.0000000000 +Description: {node0 } +Bond Height: 0 +Unbonding Height: 0 +Minimum Unbonding Time: 1970-01-01 00:00:00 +0000 UTC +Commission: {{0.0000000000 0.0000000000 0.0000000000 0001-01-01 00:00:00 +0000 UTC}} +``` diff --git a/docs/cli-client/stake/validators.md b/docs/cli-client/stake/validators.md new file mode 100644 index 000000000..7187e7e74 --- /dev/null +++ b/docs/cli-client/stake/validators.md @@ -0,0 +1,39 @@ +# iriscli stake validators + +## Description + +Query for all validators + +## Usage + +``` +iriscli stake validators [flags] +``` +Print help messages: +``` +iriscli stake validators --help +``` + +## Examples + +Query a validator +``` +iriscli stake validators +``` + +After that, you will get all validators' info. + +```txt +Validator +Operator Address: fva15grv3xg3ekxh9xrf79zd0w077krgv5xf6d6thd +Validator Consensus Pubkey: fvp1zcjduepq47906n2zvq597vwyqdc0h35ve0fcl64hwqs9xw5fg67zj4g658aqyuhepj +Jailed: false +Status: Bonded +Tokens: 100.0000000000 +Delegator Shares: 100.0000000000 +Description: {node0 } +Bond Height: 0 +Unbonding Height: 0 +Minimum Unbonding Time: 1970-01-01 00:00:00 +0000 UTC +Commission: {{0.0000000000 0.0000000000 0.0000000000 0001-01-01 00:00:00 +0000 UTC}} +``` diff --git a/docs/cli-client/status/README.md b/docs/cli-client/status/README.md new file mode 100644 index 000000000..39f0403f2 --- /dev/null +++ b/docs/cli-client/status/README.md @@ -0,0 +1,32 @@ +# iriscli status + +## Description + +Query remote node for status + +## Usage + +```shell +iriscli status [flags] +``` + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------------- | --------------------- | ----------------------------------- | -------- | +| --help, -h | | Help for status | | +| --node, -n | tcp://localhost:26657 | [string] Node to connect to | | + +## Examples + +### Query remote node for status + +```shell +iriscli status +``` + +After that, you can get remote node status as follows: + +```json +{"node_info":{"protocol_version":{"p2p":"4","block":"7","app":"0"},"id":"959185fdc3d14bdc7be1af40c5290d25042a454c","listen_addr":"tcp://0.0.0.0:26656","network":"test","version":"0.26.0","channels":"4020212223303800","moniker":"node0","other":{"tx_index":"on","rpc_address":"tcp://0.0.0.0:26657"}},"sync_info":{"latest_block_hash":"04A6B890A61F503A64F254CF8479C8FB9012A9C9494249DC76F81B6453ADF6A1","latest_app_hash":"B3549258BBC34860630BB5721364104DAC241EB243A8B0BCA0AA4968A64A1A6B","latest_block_height":"2647","latest_block_time":"2018-11-16T03:12:46.701163933Z","catching_up":false},"validator_info":{"address":"91679AB00C0A09B006F9A812AAF686092657F658","pub_key":{"type":"tendermint/PubKeyEd25519","value":"r4r9TUJgKF8xxANw+8aMy9OP6rdwIFM6iUa8KVUaofo="},"voting_power":"100"}} +``` diff --git a/docs/cli-client/tendermint/README.md b/docs/cli-client/tendermint/README.md new file mode 100644 index 000000000..5083eb47f --- /dev/null +++ b/docs/cli-client/tendermint/README.md @@ -0,0 +1 @@ +# iriscli \ No newline at end of file diff --git a/docs/cli-client/upgrade/README.md b/docs/cli-client/upgrade/README.md new file mode 100644 index 000000000..29d783ecc --- /dev/null +++ b/docs/cli-client/upgrade/README.md @@ -0,0 +1,25 @@ +# iriscli upgrade + +## Description + +Be used to participate in the software upgrade process. + +## Usage + +```shell +iriscli upgrade [command] +``` + +## Available Commands + +| Name | Description | +| ------------- | ------------------------------------- | +| [submit-switch](submit-switch.md) | Submit a switch msg for a upgrade propsal| +| [query-switch](query-switch.md) | query switch detail | +| [info](info.md) | Query the information of upgrade module | + +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | ------- | ---------------- | -------- | +| --help, -h | | help for upgrade | | diff --git a/docs/cli-client/upgrade/info.md b/docs/cli-client/upgrade/info.md new file mode 100644 index 000000000..c2c69e31f --- /dev/null +++ b/docs/cli-client/upgrade/info.md @@ -0,0 +1,65 @@ +# iriscli upgrade info + +## Description + +Query the information of software version and upgrade module. + +## Usage + +``` +iriscli upgrade info +``` + +Print help messages: + +``` +iriscli upgrade info --help +``` +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ----------------------------------------------------------------- | -------- | + +## Example + +Query the current version information. + +``` +iriscli upgrade info +``` + +Then it will show + +``` +{ +"current_proposal_id": "0", +"current_proposal_accept_height": "-1", +"version": { +"Id": "0", +"ProposalID": "0", +"Start": "0", +"ModuleList": [ +{ +"Start": "0", +"End": "9223372036854775807", +"Handler": "bank", +"Store": [ +"acc" +] +}, +{ +"Start": "0", +"End": "9223372036854775807", +"Handler": "stake", +"Store": [ +"stake", +"acc", +"mint", +"distr" +] +}, +....... +] +} +} +``` diff --git a/docs/cli-client/upgrade/query-switch.md b/docs/cli-client/upgrade/query-switch.md new file mode 100644 index 000000000..7889df017 --- /dev/null +++ b/docs/cli-client/upgrade/query-switch.md @@ -0,0 +1,30 @@ +# iriscli upgrade query-switch + +## Description +Query the switch information to know if someone have send the switch message for the certain software upgrade proposal. + +## Usage + +``` +iriscli upgrade query-switch --proposal-id <proposalID> --voter <voter address> +``` + +Print help messages: + +``` +iriscli upgrade query-switch --help +``` +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ----------------------------------------------------------------- | -------- | +| --proposal-id | | proposalID of upgrade swtich being queried | Yes | +| --voter | | Address sign the switch msg | Yes | + +## Example + +Query if the address `faa1qvt2r6hh9vyg3kh4tnwgx8wh0kpa7q2lsk03fe` send the switch message for the software upgrade proposal whose ID is 5. + +``` +iriscli upgrade query-switch --proposal-id=5 --voter=faa1qvt2r6hh9vyg3kh4tnwgx8wh0kpa7q2lsk03fe +``` diff --git a/docs/cli-client/upgrade/submit-switch.md b/docs/cli-client/upgrade/submit-switch.md new file mode 100644 index 000000000..2e55457ec --- /dev/null +++ b/docs/cli-client/upgrade/submit-switch.md @@ -0,0 +1,31 @@ +# iriscli upgrade submit-switch + +## Description + +Submit a switch msg for a upgrade propsal after installing the new software and broadcast to the whole network. + +## Usage + +``` +iriscli upgrade submit-switch [flags] +``` + +Print help messages: + +``` +iriscli upgrade submit-switch --help +``` +## Flags + +| Name, shorthand | Default | Description | Required | +| --------------- | --------- | ------------------------------------------------------------ | -------- | +| --proposal-id | | proposalID of upgrade proposal | Yes | +| --title | | title of switch | | + +## Examples + +Send a switch message for the software upgrade proposal whose `proposalID` is 5. + +``` +iriscli upgrade submit-switch --chain-id=IRISnet --from=x --fee=0.004iris --proposalID 5 --title="Run new verison" +``` diff --git a/docs/features/README.md b/docs/features/README.md new file mode 100644 index 000000000..74212951c --- /dev/null +++ b/docs/features/README.md @@ -0,0 +1,13 @@ +# Features + +## Bank + +## Stake + +## Service + +## Record + +## Governance + +## Distribution \ No newline at end of file diff --git a/docs/features/bank.md b/docs/features/bank.md new file mode 100644 index 000000000..e64829ec9 --- /dev/null +++ b/docs/features/bank.md @@ -0,0 +1,197 @@ +# Bank User Guide + +## Introduction +This module is mainly used to transfer coins between accounts、query account balances, and provide a common offline transaction signing and broadcasting method. In addition, the available units of tokens in the IRIShub system are defined using [coin_type](./basic-concepts/coin-type.md). + +## Usage Scenario + +1. Query the coin_type configuration of a certain token: + ```bash + iriscli bank coin-type [coin-name] + ``` + For example, coin_type of iris will be returned if the coin-name is iris: + ```json + { + "name": "iris", + "min_unit": { + "denom": "iris-atto", + "decimal": "18" + }, + "units": [ + { + "denom": "iris", + "decimal": "0" + }, + { + "denom": "iris-milli", + "decimal": "3" + }, + { + "denom": "iris-micro", + "decimal": "6" + }, + { + "denom": "iris-nano", + "decimal": "9" + }, + { + "denom": "iris-pico", + "decimal": "12" + }, + { + "denom": "iris-femto", + "decimal": "15" + }, + { + "denom": "iris-atto", + "decimal": "18" + } + ], + "origin": 1, + "desc": "IRIS Network" + } + ``` + +2. Query account + + Query the account information of a certain account address, including the balance, the public key, the account number and the transaction number. + ```bash + iriscli bank account [account address] + ``` + +3. Transfer between accounts + + For example, transfer 10iris from account A to account B: + ```bash + iriscli bank send --to [address of wallet B] --amount=10iris --fee=0.004iris --from=[key name of wallet A] --chain-id=[chain-id] + ``` + IRISnet supports multiple tokens in circulation, and in the future IRISnet will be able to include multiple tokens in one transaction -- tokens can be any coin_type registered in IRISnet. + +4. Sign transactions generated offline + + To improve account security, IRISnet supports offline signing of transactions to protect the account's private key. In any transaction, you can build an unsigned transaction using the flag --generate-only=true. Use transfer transactions as an example: + ```bash + iriscli bank send --to [address of wallet B] --amount=10iris --fee=0.004iris --from=[key name of wallet A] --generate-only=true + ``` + Return the built transaction with empty signatures: + ```json + { + "type": "auth/StdTx", + "value": { + "msg": [ + { + "type": "cosmos-sdk/Send", + "value": { + "inputs": [ + { + "address": "faa1ydhmma8l4m9dygsh7l08fgrwka6yczs0gkfnvd", + "coins": [ + { + "denom": "iris-atto", + "amount": "100000000000000000000" + } + ] + } + ], + "outputs": [ + { + "address": "faa1ut8aues05kq0nkcj3lzkyhk7eyfasrdfnf7wph", + "coins": [ + { + "denom": "iris-atto", + "amount": "100000000000000000000" + } + ] + } + ] + } + } + ], + "fee": { + "amount": [ + { + "denom": "iris-atto", + "amount": "40000000000000000" + } + ], + "gas": "200000" + }, + "signatures": null, + "memo": "" + } + } + ``` + Save the result to a file. + + Send signature transaction: + ```bash + iriscli bank sign [file] --chain-id=[chain-id] --name [key name] + ``` + Return signed transactions: + ```json + { + "type": "auth/StdTx", + "value": { + "msg": [ + { + "type": "cosmos-sdk/Send", + "value": { + "inputs": [ + { + "address": "faa1ydhmma8l4m9dygsh7l08fgrwka6yczs0gkfnvd", + "coins": [ + { + "denom": "iris-atto", + "amount": "100000000000000000000" + } + ] + } + ], + "outputs": [ + { + "address": "faa1ut8aues05kq0nkcj3lzkyhk7eyfasrdfnf7wph", + "coins": [ + { + "denom": "iris-atto", + "amount": "100000000000000000000" + } + ] + } + ] + } + } + ], + "fee": { + "amount": [ + { + "denom": "iris-atto", + "amount": "40000000000000000" + } + ], + "gas": "200000" + }, + "signatures": [ + { + "pub_key": { + "type": "tendermint/PubKeySecp256k1", + "value": "A+qXW5isQDb7blT/KwEgQHepji8RfpzIstkHpKoZq0kr" + }, + "signature": "5hxk/R81SWmKAGi4kTW2OapezQZpp6zEnaJbVcyDiWRfgBm4Uejq8+CDk6uzk0aFSgAZzz06E014UkgGpelU7w==", + "account_number": "0", + "sequence": "11" + } + ], + "memo": "" + } + } + ``` + Save the result to a file. + +5. Broadcast transactions + + Broadcast offline signed transactions. Here you can just use the transaction generated by above sign command. Of course, you can generate your signed transaction by any methods, eg. [irisnet-crypto](https://github.com/irisnet/irisnet-crypto). + ```bash + iriscli bank broadcast [file] + ``` + The transaction will be broadcast and executed in IRISnet. + \ No newline at end of file diff --git a/docs/get-started/Bech32-on-IRISnet.md b/docs/features/basic-concepts/bech32-prefix.md similarity index 53% rename from docs/get-started/Bech32-on-IRISnet.md rename to docs/features/basic-concepts/bech32-prefix.md index a62927bb4..79dbb1fb3 100644 --- a/docs/get-started/Bech32-on-IRISnet.md +++ b/docs/features/basic-concepts/bech32-prefix.md @@ -1,21 +1,19 @@ # 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. +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. More details in [bip-0173](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki) ## 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. +| -----------|:-------------| +|faa| IRISnet Account Address| +|fap| IRISnet Account Public Key| +|fva| IRISnet Validator's Operator Address| +|fvp| IRISnet Validator's Operator Public Key| +|fca| IRISnet Consensus Address| +|fcp| IRISnet Consensus Public Key| ## Encoding @@ -28,9 +26,9 @@ To covert between other binary reprsentation of addresses and keys, it is import Once you create a new address, you should see the following: -` -NAME: TYPE: ADDRESS: PUBKEY: -test1 local faa18ekc4dswwrh2a6lfyev4tr25h5y76jkpqsz7kl fap1addwnpepqgxa40ww28uy9q46gg48g6ulqdzwupyjcwfumgfjpvz7krmg5mrnw6zv8uv -` +``` +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 +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`. diff --git a/docs/modules/coin/README.md b/docs/features/basic-concepts/coin-type.md similarity index 100% rename from docs/modules/coin/README.md rename to docs/features/basic-concepts/coin-type.md diff --git a/docs/modules/fee-token/Fee.md b/docs/features/basic-concepts/fee.md similarity index 100% rename from docs/modules/fee-token/Fee.md rename to docs/features/basic-concepts/fee.md diff --git a/docs/features/basic-concepts/genesis-file.md b/docs/features/basic-concepts/genesis-file.md new file mode 100644 index 000000000..ded17325a --- /dev/null +++ b/docs/features/basic-concepts/genesis-file.md @@ -0,0 +1,46 @@ +# Genesis File + +The Genesis file is the basis for the entire network initialization,which contains most info for creating a Genesis block (such as ChainID, consensus params,app state), initialize account balances, parameters for each module, and validators info. + +## Basic State + +* genesis_time The time to build Genesis file +* chain_id Blockchain’s ID + +## Consensus Params + +* block_size Block size and config params of the number of Gas in the block +* evidence The lifecycle of deception evidence in the block + +## App State + +* **accounts** Initialization account info + +* **stake** Params related to the staking consensus + * `loose_tokens` The sum of unbonded tokens in the entire network + * `unbonding_time` The time between the moment a validator begin to unbond until the moment it is unbonded successfully + * `max_validators` The max of validators + +* **mint** Params related to inflation + * `inflation_max` The max of inflation rate + * `inflation_min` The min of inflation rate + +* **distribution** Params related to distribution & commission + +* **gov** Params related to on-chain governance + * `DepositProcedure` Params in deposit period + * `VotingProcedure` Params in voting period + * `TallyingProcedure` Params in tallying period + +* **upgrade** Params related to upgrade + * `switch_period` After upgrade, a switch message needs to be sent in switch_perid + +* **slashing** Params related to slashing validators + +* **service** Params related to Service + * `MaxRequestTimeout` The max of waiting blocks for service invocation + * `MinProviderDeposit` The min deposit for service binding + +## Gentxs + +Gentxs contains the transaction set of creating validators in genesis block. \ No newline at end of file diff --git a/docs/features/basic-concepts/gov-params.md b/docs/features/basic-concepts/gov-params.md new file mode 100644 index 000000000..7b5a53761 --- /dev/null +++ b/docs/features/basic-concepts/gov-params.md @@ -0,0 +1,18 @@ +# Gov Params + +In IRISnet, there are some special parameters can be modified through on-chain governance. All the IRIS holders are able to modify. If the community is not satisfied with certain modifiable parameters, it is available to set the proper values in governance module. + +## Gov Module + +* `DepositProcedure` Parameters in deposit period (The minimum of deposit, deposit period) +* `VotingProcedure` Parameters in voting period(Voting period) +* `TallyingProcedure` Parameters in tallying period(The standards of voting) + +Details in [gov](gov.md) + +## Service Module + +* `MaxRequestTimeout` The maximum of waiting blocks for service invocation +* `MinProviderDeposit` The minimum deposit for service binding + +Details in [service](serivice.md) \ No newline at end of file diff --git a/docs/features/basic-concepts/inflation.md b/docs/features/basic-concepts/inflation.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/features/distribution.md b/docs/features/distribution.md new file mode 100644 index 000000000..917f51460 --- /dev/null +++ b/docs/features/distribution.md @@ -0,0 +1,44 @@ +# Distribution User Guide + +## Introduction + +This module is in charge of distributing collected transaction fee and inflated token to all validators and delegators. To reduce computation stress, a lazy distribution strategy is brought in. `lazy` means that the benefit won't be paid directly to contributors automatically. The contributors are required to explicitly send transactions to withdraw their benefit, otherwise, their benefit will be kept in the global pool. + +## Usage Scenario + +1. Set withdraw address + + A delegator may have multiple irishub wallet address. Suppose one of the wallets has many iris token and part of these tokens have been delegated to a validator. The delegator may hope the delegation reward can be paid to another wallet, thus the delegator will have explicit idea about how many tokens he/she has earned.However, by default, the reward will be paid to the wallet(marked as `A`) address which send the delegation transaction. To set another wallet(marked as `B`) as the paid address, delegator need to send another transaction from wallet `A`. The referenced command can be: + ```bash + iriscli distribution set-withdraw-addr [address of wallet B] --fee=0.004iris --from=[key name of wallet A] --chain-id=[chain-id] + ``` + To verify the whether the above operation take effect, delegator can execute the following command. + ```bash + iriscli distribution withdraw-address [address of wallet A] + ``` + If set withdraw operation is success, the query response must equal to the address of wallet B. + +2. Withdraw reward + + According to the introduction section, our delegation reward won't be paid to our wallet automatically, we have to send transactions to withdraw reward. + Suppose a delegator operate a validator(marked as `validatorA`), besides, it also has delegations on two other validators(marked as `validatorB` and `validatorC`). All delegations are created from wallet A. + + 1. Only withdraw the self-delegation reward of from validatorA: + ```bash + iriscli distribution withdraw-rewards --only-from-validator [address of validatorA] --from [key name of wallet A] --fee=0.004iris --chain-id=[chain-id] + ``` + 2. Withdraw all delegation reward: + ```bash + iriscli distribution withdraw-rewards --from [key name of wallet A] --fee=0.004iris --chain-id=[chain-id] + ``` + 3. Withdraw all delegation reward including commission benefit of `validatorA` : + ```bash + iriscli distribution withdraw-rewards --is-validator=true --from [key name of wallet A] --fee=0.004iris --chain-id=[chain-id] + ``` + +3. Query reward token + + Execute the command to get the earned tokens: + ```bash + iriscli bank account [withdraw address] + ``` \ No newline at end of file diff --git a/docs/features/governance.md b/docs/features/governance.md new file mode 100644 index 000000000..b90348f27 --- /dev/null +++ b/docs/features/governance.md @@ -0,0 +1,166 @@ +# Gov User Guide + +## Basic Function Description + +1. On-chain governance proposals on text +2. On-chain governance proposals on parameter change +3. On-chain governance proposals on software upgrade + +## 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 tallyed when reach `voting_period'. +3. Our tally have a limit on participation, Other details about voting for proposals: +[CosmosSDK-Gov-spec](https://github.com/cosmos/cosmos-sdk/blob/v0.26.0/docs/spec/governance/overview.md) + +## Usage Scenario + +### Usage scenario of parameter change + +Scenario 1:Change the parameters through the command lines + +``` +# Query parameters can be changed by the modules'name in gov +iriscli gov query-params --module=gov --trust-node + +# Results +[ +"Gov/govDepositProcedure", +"Gov/govTallyingProcedure", +"Gov/govVotingProcedure" +] + +# Query parameters can be modified by "key” +iriscli gov query-params --key=Gov/govDepositProcedure --trust-node + +# Results +{"key":"Gov/govDepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":172800000000000}","op":""} + +# Send proposals, return changed parameters +iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --param='{"key":"Gov/govDepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"20000000000000000000\"}],\"max_deposit_period\":172800000000000}","op":"update"}}' --from=x --chain-id=gov-test --fee=0.05iris --gas=200000 + +# Deposit for a proposal +iriscli gov deposit --proposal-id=1 --deposit=1iris --from=x --chain-id=gov-test --fee=0.05iris --gas=200000 + +# Vote for a proposal +echo 1234567890 | iriscli gov vote --proposal-id=1 --option=Yes --from=x --chain-id=gov-test --fee=0.05iris --gas=200000 + +# Query the state of a proposal +iriscli gov query-proposal --proposal-id=1 --trust-node + +``` + +Scenario 2: Change the parameters by the files + +``` +# Export profiles +iriscli gov pull-params --path=iris --trust-node + +# Query profiles' info +cat iris/config/params.json { +"gov": { +"Gov/govDepositProcedure": { +"min_deposit": [ +{ +"denom": "iris-atto", +"amount": "10000000000000000000" +} +], +"max_deposit_period": "172800000000000" +}, +"Gov/govVotingProcedure": { +"voting_period": "10000000000" +}, +"Gov/govTallyingProcedure": { +"threshold": "0.5000000000", +"veto": "0.3340000000", +"participation": "0.6670000000" +} +} + +# Modify profiles (TallyingProcedure的governance_penalty) +vi iris/config/params.json { +"gov": { +"Gov/govDepositProcedure": { +"min_deposit": [ +{ +"denom": "iris-atto", +"amount": "10000000000000000000" +} +], +"max_deposit_period": "172800000000000" +}, +"Gov/govVotingProcedure": { +"voting_period": "10000000000" +}, +"Gov/govTallyingProcedure": { +"threshold": "0.5000000000", +"veto": "0.3340000000", +"participation": "0.4990000000" +} +} + +# Change the parameters through files, return changed parameters +iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --path=iris --key=Gov/govTallyingProcedure --op=update --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# Deposit for a proposal +iriscli gov deposit --proposal-id=1 --deposit=1iris --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# Vote for a proposal +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 +``` + +### Proposals on software upgrade + +Detail in [Upgrade](upgrade.md) + +## Basic parameters + +``` +# DepositProcedure(The parameters in deposit period) +"Gov/govDepositProcedure": { +"min_deposit": [ +{ +"denom": "iris-atto", +"amount": "10000000000000000000" +} +], +"max_deposit_period": "172800000000000" +} +``` + +* 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:1000iris,(1iris,10000iris) +* `max_deposit_period` Window period for repaying deposit, default:172800000000000ns==2Days, scope(20s,3Day) + +``` +# VotingProcedure(The parameters in voting period) +"Gov/govVotingProcedure": { +"voting_period": "10000000000" +} +``` + +* Parameters can be changed +* `voting_perid` Window period for vote, default:172800000000000ns==2Days, scope(20s,3Days) + +``` +# TallyingProcedure (The parameters in Tallying period) +"Gov/govTallyingProcedure": { +"threshold": "0.5000000000", +"veto": "0.3340000000", +"participation": "0.6670000000" +} +``` + +* Parameters can be changed +* `veto` default: 0.334, scope(0,1) +* `threshold` default: 0.5, scope(0,1) +* `governance_penalty` default: 0.667, scope(0,1) +* Vote rules:If the ratio of all voters' `voting_power` to the total 'voting_power' in system less than “participation”, the proposal won't be passed. If the ratio of strongly opposed `voting_power` to all voters' `voting_power` more than “veto”, the proposal won't be passed. Then if the ratio of approved `voting_power` to all voter's `voting_power` except abstentions over “threshold”, the proposal will be passed. Otherwise, N/A. diff --git a/docs/features/lcd.md b/docs/features/lcd.md new file mode 100644 index 000000000..aff1767ba --- /dev/null +++ b/docs/features/lcd.md @@ -0,0 +1,112 @@ +# IRISLCD User Guide + +## Basic Functionality Description + +1. Provide restful APIs and swagger-ui to show these APIs +2. Verify query proof + +## Usage Scenario + +Suppose an IRISLCD node is running and its swagger-ui page url is `localhost:1317/swagger-ui/`. The default home folder of irislcd is `$HOME/.irislcd`. Once an IRISLCD is started, firstly it will create key store in its home folder. If the IRISLCD is running in distrust mode, then ir will fetch the latest block as its trust basis and the trust basis will be saved to folder `trust-base.db` under its home folder. The IRISLCD node always trust the basis. It will verify all query proof against the trust basis, which means IRISLCD can only verify the proof on later height. However, this is also a defect of IRISLCD. When it tries to verify some transactions or blocks on lower height, it will report error. So if you want to query transactions or block on lower height, please start IRISLCD in trust mode. For detailed proof verification algorithm please refer to this [document](https://github.com/tendermint/tendermint/blob/master/docs/tendermint-core/light-client-protocol.md). + +Once the IRISLCD node is started successfully, then you can open `localhost:1317/swagger-ui/` in your explorer and all restful APIs will be shown. + +1. Tendermint APIs, such as query blocks, transactions and validatorset + 1. `GET /node_info`: The properties of the connected node + 2. `GET /syncing`: Syncing state of node + 3. `GET /blocks/latest`: Get the latest block + 4. `GET /blocks/{height}`: Get a block at a certain height + 5. `GET /validatorsets/latest`: Get the latest validator set + 6. `GET /validatorsets/{height}`: Get a validator set a certain height + 7. `GET /txs/{hash}`: Get a Tx by hash + 8. `GET /txs`: Search transactions + 9. `POST /txs`: Broadcast Tx + +2. Key management APIs + + 1. `GET /keys`: List of accounts stored locally + 2. `POST /keys`: Create a new account locally + 3. `GET /keys/seed`: Create a new seed to create a new account with + 4. `GET /keys/{name}`: Get a certain locally stored account + 5. `PUT /keys/{name}`: Update the password for this account in the KMS + 6. `DELETE /keys/{name}`: Remove an account + 7. `GET /auth/accounts/{address}`: Get the account information on blockchain + +3. Create, sign and broadcast transactions + + 1. `POST /tx/sign`: Sign a transation + 2. `POST /tx/broadcast`: Broadcast a signed StdTx with amino encoding signature and public key + 3. `POST /txs/send`: Send non-amino encoding transaction + 4. `GET /bank/coin/{coin-type}`: Get coin type + 5. `GET /bank/balances/{address}`: Get the account information on blockchain + 6. `POST /bank/accounts/{address}/transfers`: Send coins (build -> sign -> send) + +4. Stake module APIs + + 1. `POST /stake/delegators/{delegatorAddr}/delegate`: Submit delegation transaction + 2. `POST /stake/delegators/{delegatorAddr}/redelegate`: Submit redelegation transaction + 3. `POST /stake/delegators/{delegatorAddr}/unbond`: Submit unbonding transaction + 4. `GET /stake/delegators/{delegatorAddr}/delegations`: Get all delegations from a delegator + 5. `GET /stake/delegators/{delegatorAddr}/unbonding_delegations`: Get all unbonding delegations from a delegator + 6. `GET /stake/delegators/{delegatorAddr}/redelegations`: Get all redelegations from a delegator + 7. `GET /stake/delegators/{delegatorAddr}/validators`: Query all validators that a delegator is bonded to + 8. `GET /stake/delegators/{delegatorAddr}/validators/{validatorAddr}`: Query a validator that a delegator is bonded to + 9. `GET /stake/delegators/{delegatorAddr}/txs` :Get all staking txs (i.e msgs) from a delegator + 10. `GET /stake/delegators/{delegatorAddr}/delegations/{validatorAddr}`: Query the current delegation between a delegator and a validator + 11. `GET /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}`: Query all unbonding delegations between a delegator and a validator + 12. `GET /stake/validators`: Get all validator candidates + 13. `GET /stake/validators/{validatorAddr}`: Query the information from a single validator + 14. `GET /stake/validators/{validatorAddr}/unbonding_delegations`: Get all unbonding delegations from a validator + 15. `GET /stake/validators/{validatorAddr}/redelegations`: Get all outgoing redelegations from a validator + 16. `GET /stake/pool`: Get the current state of the staking pool + 17. `GET /stake/parameters`: Get the current staking parameter values + +5. Governance module APIs + + 1. `POST /gov/proposal`: Submit a proposal + 2. `GET /gov/proposals`: Query proposals + 3. `POST /gov/proposals/{proposalId}/deposits`: Deposit tokens to a proposal + 4. `GET /gov/proposals/{proposalId}/deposits`: Query deposits + 5. `POST /gov/proposals/{proposalId}/votes`: Vote a proposal + 6. `GET /gov/proposals/{proposalId}/votes`: Query voters + 7. `GET /gov/proposals/{proposalId}`: Query a proposal + 8. `GET /gov/proposals/{proposalId}/deposits/{depositor}`: Query deposit + 9. `GET /gov/proposals/{proposalId}/votes/{voter}`: Query vote + 10. `GET/gov/params`: Query governance parameters + +6. Slashing module APIs + 1. `GET /slashing/validators/{validatorPubKey}/signing_info`: Get sign info of given validator + 2. `POST /slashing/validators/{validatorAddr}/unjail`: Unjail a jailed validator + +7. Distribution module APIs + + 1. `POST /distribution/{delegatorAddr}/withdrawAddress`: Set withdraw address + 2. `GET /distribution/{delegatorAddr}/withdrawAddress`: Query withdraw address + 3. `POST /distribution/{delegatorAddr}/withdrawReward`: Withdraw address + 4. `GET /distribution/{delegatorAddr}/distrInfo/{validatorAddr}`: Query distribution information for a delegation + 5. `GET /distribution/{delegatorAddr}/distrInfos`: Query distribution information list for a given delegator + 6. `GET /distribution/{validatorAddr}/valDistrInfo`: Query withdraw address + +8. Query app version + + 1. `GET /version`: Version of irislcd + 2. `GET /node_version`: Version of the connected node + +## Extra parameters for post apis + +1. `POST /bank/accounts/{address}/transfers`: Send tokens (build -> sign -> send) +2. `POST /stake/delegators/{delegatorAddr}/delegate`: Submit delegation transaction +3. `POST /stake/delegators/{delegatorAddr}/redelegate`: Submit redelegation transaction +4. `POST /stake/delegators/{delegatorAddr}/unbond`: Submit unbonding transaction +5. `POST /gov/proposal`: Submit a proposal +6. `POST /gov/proposals/{proposalId}/deposits`: Deposit tokens to a proposal +7. `POST /gov/proposals/{proposalId}/votes`: Vote a proposal +8. `POST /slashing/validators/{validatorAddr}/unjail`: Unjail a jailed validator + +| parameter name | Type | Default | Priority | Description | +| --------------- | ---- | ------- |--------- |--------------------------- | +| generate-only | bool | false | 0 | Build an unsigned transaction and write it back | +| simulate | bool | false | 1 | Ignore the gas field and perform a simulation of a transaction, but don’t broadcast it | +| async | bool | false | 2 | Broadcast transaction asynchronously | + +The above eight post APIs have three query parameter which are shown in the above table. By default, their values are all false. Each parameter has its unique priority( Here `0` is the top priority). If multiple parameters are specified, then the parameters with lower priority will be ignored. For instance, if `generate-only` is true, then other parameters, such as `simulate` and `async` will be ignored. \ No newline at end of file diff --git a/docs/features/mint.md b/docs/features/mint.md new file mode 100644 index 000000000..5c97a2d28 --- /dev/null +++ b/docs/features/mint.md @@ -0,0 +1,38 @@ +# IRISLCD User Guide + +## Introduction + +The incentive mechanism of POW is widely known and explicit: once a new block is produced, the block miner will acquire a certain amount of token as well as the accumulation of transaction fee in the block. As a POS blockchain network, the IRISHUB incentive mechanism is much different. + +As we all know, POW means proof of work. In each block producing period, all miners compete to calculate their work proof and the fastest one will be the winner. Actually, all loser miners don't offer any positive help or collaboration to the winner miner, and they are only the competitors. So it is reasonable to grant all reward to the winner miner. However, in POS blockchain network, we can't do that. Because each block producing process is the collaboration of all validators and delegators, which means the benefit should be share by all these contributors. There are two sources of revenue, one is the transaction fee of the packaged transaction in the block. The other is regular inflation, which will produce new tokens. + +As for how to distribute inflation token to contributors, we will document and implement it in distribution module. Here we mainly introduce how to figure out the inflation token and what is the impact to users. + +## Inflation Calculation + +Unlike POW network, the inflation token will not be paid to contributors in each block. Only when contributors explicitly send transactions to withdraw reward, then will the inflation token be transfered to users specified addresses. Besides, the token inflation is triggered once an hour, and the new produced token will be saved in global pool. + +### Block Time + +The block time is not the machine time, because different machines may not have exactly the same time. They must have some deviation more or less which will result in non-deterministic. So here the block time is the BFT time. Please refer to this [tendermint bft-time](https://github.com/tendermint/tendermint/blob/master/docs/spec/consensus/bft-time.md) for detailed description. + +### Inflation Rate + +The inflation rate depends on the bonded ratio which means it always changes. The desired bonded ratio 67%. If the ratio is higher, the inflation rate will decrease. In contrast, if the bonded ratio is lower, the inflation rate will increase. Besides, the inflation rate should no more than 20% and no less than 7%. Otherwise, it will be truncated. + +Suppose the inflation rate is 10%, and total token amount is 10000iris, then the inflation token will be 0.114iris(10000iris*10%/8766, one year has 8766 hours). After this inflation, the total token amount will be 10000.114iris. + +## Impact to users + +The inflation calculation is an automatically process. Users have no directly interface to this process. However, users can send delegation or unboud transactions to change the bonded ratio, therefore the inflation rate will change accordingly. + +Besides, the inflation process will increate the total token amount. Users can get the total token amount by this command: +``` +ubuntu@ubuntu:~$ iriscli stake pool --node=<iris node url> +Pool +Loose Tokens: 200.1186409166 +Bonded Tokens: 400.0000000000 +Token Supply: 600.1186409166 +Bonded Ratio: 0.6665348695 +``` + diff --git a/docs/features/record.md b/docs/features/record.md new file mode 100644 index 000000000..e71ffe356 --- /dev/null +++ b/docs/features/record.md @@ -0,0 +1,88 @@ +# Record User Guide + +## Basic Function Description + +1. On-Chain record for the text data +2. On-Chain record for the text file (TODO) +3. On-Chain governance for the record params (TODO) + +## Interaction + +### Record Introduction + +Record metadata components + +| Fields in record metadata | Description | +| ---------------------------- | ---------------------------------------- | +| record submit time | data submit time | +| record owner address | data owner's address on the target chain | +| record ID | record index ID | +| record description | data description | +| data hash | uploaded data hash | +| data size | uploaded data size | +| data | uploaded data itself | + +1. Record module generates related metadata from uploaded data on the target chain, and it has the obvious advantages such as efficiency, auditability and traceability over the traditional record technologies. +2. Any users can initiate a record request. It will cost you some tokens. If there’s no identical data on the targt chain, the request will be completed successfully and the metadata of record payload will be recorded on the target chain. And you will be returned a record ID to confirm your ownership of the data. +3. If any others initiate a record request for the same data, the request will be directly rejected and it will hint that the relevant record data has already existed. +4. Any users can search/download onchain based on the record ID. +5. At present, the maximum amount of stored data at most 1K Bytes. In the future, the dynamic adjustment of parameters will be implemented in conjunction with the governance module. + +## Usage Scenarios + +### Usage Scenarios of Record on Chains + +Scenario 1: Record the data through cli + +``` +# Specify the text data which needs to be recorded by --onchain-data + +iriscli record submit --description="test" --onchain-data=x --from=x --fee=0.04iris + +# Result +Committed at block 1845 (tx hash: E620F3CD62BD9128443BA168296FFECC9BE2AF8F45CF21FD8FDA609DEFA253ED, response: {Code:0 Data:[114 101 99 111 114 100 58 101 56 51 102 57 102 50 55 55 100 101 99 102 54 98 57 52 102 100 55 50 55 100 52 54 53 99 49 51 52 54 57 102 53 53 50 48 51 57 56 56 57 102 98 101 102 99 56 97 49 99 55 52 101 48 54 99 54 56 48 57 98 48 101] Log:Msg 0: Info: GasWanted:200000 GasUsed:3978 Tags:[{Key:[97 99 116 105 111 110] Value:[115 117 98 109 105 116 45 114 101 99 111 114 100] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[111 119 110 101 114 65 100 100 114 101 115 115] Value:[102 97 97 49 53 103 114 118 51 120 103 51 101 107 120 104 57 120 114 102 55 57 122 100 48 119 48 55 55 107 114 103 118 53 120 102 48 117 115 121 50 50] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[114 101 99 111 114 100 45 105 100] Value:[114 101 99 111 114 100 58 101 56 51 102 57 102 50 55 55 100 101 99 102 54 98 57 52 102 100 55 50 55 100 52 54 53 99 49 51 52 54 57 102 53 53 50 48 51 57 56 56 57 102 98 101 102 99 56 97 49 99 55 52 101 48 54 99 54 56 48 57 98 48 101] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 55 57 53 54 48 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "submit-record", + "completeConsumedTxFee-iris-atto": "\"795600000000000\"", + "ownerAddress": "faa15grv3xg3ekxh9xrf79zd0w077krgv5xf0usy22", + "record-id": "record:e83f9f277decf6b94fd727d465c13469f552039889fbefc8a1c74e06c6809b0e" + } +} + +# Query the Status of the Records +iriscli record query --record-id=x + +# Download the Record +iriscli record download --record-id=x --file-name="download" + +``` + +Scenario 2: Query the transactions including recorded data onchain through cli + +``` +# Query the status of the records onchain +iriscli tendermint txs --tag "action='submit-record'" +``` + +## Details of cli + +``` +iriscli record submit --description="test" --onchain-data=x --chain-id="record-test" --from=x --fee=0.04iris +``` + +* `--onchain-data` The data needs to be recorded + + +``` +iriscli record query --record-id=x --chain-id="record-test" +``` + +* `--record-id` Record ID to be queried + + +``` +iriscli record download --record-id=x --file-name="download" --chain-id="record-test" +``` + +* `--file-name` The filename of recorded data, in the directory specified by `--home` diff --git a/docs/features/service.md b/docs/features/service.md new file mode 100644 index 000000000..492f282d2 --- /dev/null +++ b/docs/features/service.md @@ -0,0 +1,209 @@ +# Service User Guide + +## Basic Function Description +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. The [Interface description language](https://en.wikipedia.org/wiki/Interface_description_language) (IDL) we introduced is +to work with the service standardized definitions to satisfy service invocations across different programming languages. +The currently supported IDL language is [protobuf](https://developers.google.com/protocol-buffers/). The main functions of this module are as follows: +1. Service Definition +2. Service Binding +3. Service Invocation (TODO) +4. Dispute Resolution (TODO) +5. Service Analysis (TODO) + +## Interactive process + +### Service definition process + +1. Any users can define a service. In service definition,use `protobuf` to standardize the definition of the service's method, its input and output parameters. + +## Usage Scenario +### Create an environment + +``` +rm -rf iris +rm -rf .iriscli +iris init gen-tx --name=x --home=iris +iris init --gen-txs --chain-id=service-test -o --home=iris +iris start --home=iris +``` + +### Service Definition + +``` +# Service definition +iriscli service define --chain-id=service-test --from=x --fee=0.004iris --service-name=test-service --service-description=service-description --author-description=author-description --tags=tag1,tag2 --idl-content=<idl-content> --file=test.proto + +# Result +Committed at block 92 (tx hash: A63241AA6666B8CFE6B1C092B707AB0FA350F108, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:8007 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 100 101 102 105 110 101]} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[49 54 48 49 52 48 48 48 48 48 48 48 48 48 48]}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-define", + "completeConsumedTxFee-iris-atto": "160140000000000" + } +} + +# Query service definition +iriscli service definition --def-chain-id=service-test --service-name=test-service + +``` + +### Service Binding +``` +# Service Binding +iriscli service bind --chain-id=service-test --from=x --fee=0.004iris --service-name=test-service --def-chain-id=service-test --bind-type=Local --deposit=1iris --prices=1iris --avg-rsp-time=10000 --usable-time=100 + +# Result +Committed at block 168 (tx hash: 02CAC60E75CD93465CAE10CE35F30B53C8A95574, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:5437 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 98 105 110 100]} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[49 48 56 55 52 48 48 48 48 48 48 48 48 48 48]}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-bind", + "completeConsumedTxFee-iris-atto": "108740000000000" + } +} + +# Query service binding +iriscli service binding --def-chain-id=service-test --service-name=test-service --bind-chain-id=service-test --provider=<your address> + +# Query service binding list +iriscli service bindings --def-chain-id=service-test --service-name=test-service + +# Service binding update +iriscli service update-binding --chain-id=service-test --from=x --fee=0.004iris --service-name=test-service --def-chain-id=service-test --bind-type=Local --deposit=1iris --prices=1iris,2iris --avg-rsp-time=10000 --usable-time=100 + +# Result +Committed at block 233 (tx hash: 2F5F44BAF09981D137EA667F9E872EB098A9B619, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:4989 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 98 105 110 100 105 110 103 45 117 112 100 97 116 101]} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[57 57 55 56 48 48 48 48 48 48 48 48 48 48]}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-binding-update", + "completeConsumedTxFee-iris-atto": "99780000000000" + } +} + +# Disable service binding +iriscli service disable --chain-id=service-test --from=x --fee=0.004iris --def-chain-id=service-test --service-name=test-service + +# Result +Committed at block 241 (tx hash: 0EF936E1228F9838D0343D0FB3613F5E938602B7, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:4861 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 100 105 115 97 98 108 101] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 57 55 50 50 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-disable", + "completeConsumedTxFee-iris-atto": "\"97220000000000\"" + } +} + +# Enable service binding +iriscli service enable --chain-id=service-test --from=x --fee=0.004iris --def-chain-id=service-test --service-name=test-service --deposit=1iris + +# Result +Committed at block 176 (tx hash: 74AE647B8A311501CA82DACE90AA28CDB4695803, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:6330 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 101 110 97 98 108 101] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 49 50 54 54 48 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-enable", + "completeConsumedTxFee-iris-atto": "\"126600000000000\"" + } +} + +# Refund Deposit +iriscli service refund-deposit --chain-id=service-test --from=x --fee=0.004iris --def-chain-id=service-test --service-name=test-service + +# Result +Committed at block 1563 (tx hash: 748CEA6EA9DEFB384FFCFBE68A3CB6D8B643361B, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:5116 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 114 101 102 117 110 100 45 100 101 112 111 115 105 116]} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[49 48 50 51 50 48 48 48 48 48 48 48 48 48 48]}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-refund-deposit", + "completeConsumedTxFee-iris-atto": "102320000000000" + } +} +``` + +## CLI Command Details + +``` +iriscli service define --chain-id=service-test --from=x --fee=0.004iris --service-name=test-service --service-description=service-description --author-description=author-description --tags=tag1,tag2 --idl-content=<idl-content> --file=test.proto +``` +* `--service-name` The name of service +* `--service-description` The description of this service +* `--author-description` The self-description of the service creator which is optional +* `--tags` The keywords of this service +* `--idl-content` The standardized definition of the methods for this service +* `--file` Idl-content can be replaced by files,if the item is not empty. + +``` +iriscli service definition --def-chain-id=service-test --service-name=test-service +``` +* `--def-chain-id` The ID of the blockchain defined of the service +* `--service-name` The name of service + +``` +iriscli service bind --chain-id=service-test --from=x --fee=0.004iris --service-name=test-service --def-chain-id=service-test --bind-type=Local --deposit=1iris --prices=1iris --avg-rsp-time=10000 --usable-time=100 +``` +* `--def-chain-id` The ID of the blockchain defined of the service +* `--service-name` The name of service +* `--bind-type` Set whether the service is local or global +* `--deposit` The deposit of service provider +* `--prices` Service prices, a list sorted by service method +* `--avg-rsp-time` The average service response time in milliseconds +* `--usable-time` An integer represents the number of usable service invocations per 10,000 + +``` +iriscli service binding --def-chain-id=service-test --service-name=test-service --bind-chain-id=service-test --provider=<your address> +``` +* `--def-chain-id` The ID of the blockchain defined of the service +* `--service-name` The name of service +* `--bind-chain-id` The ID of the blockchain bound of the service +* `--provider` The blockchain address of bech32 encoded account + +``` +iriscli service bindings --def-chain-id=service-test --service-name=test-service +``` +* Refer to iriscli service binding + +``` +iriscli service update-binding --chain-id=service-test --from=x --fee=0.004iris --service-name=test-service --def-chain-id=service-test --bind-type=Local --deposit=1iris --prices=1iris,2iris --avg-rsp-time=10000 --usable-time=100 +``` +* `--def-chain-id` The ID of the blockchain defined of the service +* `--service-name` The name of service +* `--bind-type` Set whether the service is local or global +* `--deposit` Add to the current deposit balance of service provider +* `--prices` Service prices, a list sorted by service method +* `--avg-rsp-time` The average service response time in milliseconds +* `--usable-time` An integer represents the number of usable service invocations per 10,000 + +``` +iriscli service disable --chain-id=service-test --from=x --fee=0.004iris --def-chain-id=service-test --service-name=test-service +``` +* `--def-chain-id` The ID of the blockchain defined of the service +* `--service-name` The name of service + +``` +iriscli service enable --chain-id=service-test --from=x --fee=0.004iris --def-chain-id=service-test --service-name=test-service --deposit=1iris +``` +* `--def-chain-id` The ID of the blockchain defined of the service +* `--service-name` The name of service +* `--deposit` Add to the current deposit balance of service provider + +``` +iriscli service refund-deposit --chain-id=service-test --from=x --fee=0.004iris --def-chain-id=service-test --service-name=test-service +``` +* `--def-chain-id` The ID of the blockchain defined of the service +* `--service-name` The name of service + +## IDL extension +When using proto file to standardize the definition of the service's method, its input and output parameters, the method attributes can be added through annotations. + +### Annotation standard +* If `//@Attribute attribute: value` wrote on top of `rpc method`,it will be added to the method attributes. Eg. +> //@Attribute description: sayHello + +### Currently supported attributes +* `description` The name of this method in the service +* `output_privacy` Whether the output of the method is encrypted,{`NoPrivacy`,`PubKeyEncryption`} +* `output_cached` Whether the output of the method is cached,{`OffChainCached`,`NoCached`} + +### IDL content example +* idl-content example +> syntax = \"proto3\";\n\npackage helloworld;\n\n// The greeting service definition.\nservice Greeter {\n //@Attribute description: sayHello\n //@Attribute output_privacy: NoPrivacy\n //@Attribute output_cached: NoCached\n rpc SayHello (HelloRequest) returns (HelloReply) {}\n}\n\n// The request message containing the user's name.\nmessage HelloRequest {\n string name = 1;\n}\n\n// The response message containing the greetings\nmessage HelloReply {\n string message = 1;\n}\n + +* IDL file example + +[test.proto](./test.proto) \ No newline at end of file diff --git a/docs/features/stake.md b/docs/features/stake.md new file mode 100644 index 000000000..34a847a42 --- /dev/null +++ b/docs/features/stake.md @@ -0,0 +1,121 @@ +# Stake User Guide + +## Introduction + +This specification briefly introduces the functionality of stake module and what user should do with the provided commands. + +## Core Concept + +1. Voting power + + Voting power is a consensus concept. IRISHUB is a Byzantine-fault-tolerant POS blockchain network. During the consensus process, a set of validators will vote the proposal block. If a validator thinks the proposal block is valid, it will vote `yes`, otherwise, it will vote nil. The votes from different validator don't have the same weight. The weight of a vote is called the voting power of the corresponding validator. + +2. Validator + + Validator is a full IRISHUB node. As a full nodes, it will sync all blocks and execute all transactions, which will consume much storage and computation resoure. If its voting power is zero, it is just a normal full node or a validator candidate. Once its voting power is positive, then it is a real validator. + +3. Delegator && Delegation + + People that cannot, or do not want to run validator nodes, can still participate in the staking process as delegators. After delegating some tokens to validators, delegators will gain delegations from corresponding validators. Delegating tokens is also called bonding tokens to validators. Later we will have detailed description on it. Besides, a validator operator is also a delegator. Usually, a validator operator only has delegation on its own validator. But it can also have delegation on other validators. + +4. Validator Candidates + + The quantity of validators can't increase without limit. Too many validators may result in inefficent consensus which slows down the blockchain TPS. So Byzantine-fault-tolerant POS blockchain network will have a limiation to the validator quantity. Usually, the value is 100. If more than 100 full nodes apply to join validator set. Then only these nodes with top 100 most bounded tokens will be real validators. Others will be validator candidates and will be descending sorted according to their bonded token amount. Once the one or more validators are kicked out from validator set, then the top candidates will be added into validator set automatically. + +5. Bond && Unbond && Unbonding Period + + Validator operators must bond their liquid tokens to their validators. The validator voting power is proportional to the bonded tokens including both self-bonded tokens and tokens from other delegators. Validator operators can lower their own bonded tokens by sending unbond transactions. Delegators can also lower bonded token by sending unbond transactions. However, these unbonded token won't become liquid tokens immediately. After the unbond transactions are executed, the corresponding validator operators or delegators can't sending unbond transactions on the same validators again until the unbonding period is end. Usually the unbonding period is three weeks. Once the unbonding period is end, the unbonded token will become liquid token automatically. The unbonding period mechanism makes great contribution to the security of POS blockchain network. Besides, if the self-bonded token equals to zero, then the corresponding validator will be removed out of validator set. + +6. Redelegate + + Delegators can transfer their delegation from one validator to another one. Redelegation can be devided into two steps: ubond from first validator and bond to another validator. As we have talked above, ubond operation can't be completed immediately until unbonding period is end, which means delegators can't send another redelegation transactions immediately. + +7. Evidence && Slash + + The Byzantine-fault-tolerant POS blockchain network can work well assume that the Byzantine nodes possess less than 1/3 of total voting power. These Byzantine nodes must be punished. So it is necessary to collect the evidence of Byzantine behavior. According to the evidence, stake module will aotumatically slash a certain mount of token from corresponding validators and delegators. The slashed tokens are just burned. Besides, the Byzantine validators will be removed from the validator set and put into jail, which means their voting power is zero. During the jail period, these nodes are not event validator candidates . Once the jail period is end, they can send transactions to unjail themselves and become validator candidates again. + +8. Rewards + + As a delegator, the more bonded tokens it has on validator, the more rewards it will earn. For a validator operator, it will have extra rewards: validator commission. The rewards comes from token inflation and transaction fee. As for how to calculate the rewards and how to get the rewards, please refer to [mint](mint.md) and [distribution](distribution.md). + +## What users can do + +1. Create a full node + + Please refer to [full node](../get-started/Full-Node.md) to create a full node. + +2. Apply to be validator + + Firstly, you must have a wallet which has a certain amount of iris tokens. Here we assume you have import your wallet to iriscli key store. + + Then just send a create-validator transaction. This is an example command. + ``` + iriscli stake create-validator --amount=100iris --pubkey=$(iris tendermint show-validator) --moniker=<validator name> --fee=0.004iris --chain-id=<chain-id> --from=<key name> --commission-max-change-rate=0.01 --commission-max-rate=0.2 --commission-rate=0.1 + ``` + The more tokens specified by `--amount`, the more probability your full node will be a real validator. Otherwise, it will just be validator candidate. + +3. Query your own validator + + Users can query their own validators by their wallet address. But firstly users have to convert their wallet addresses to validator operator address pattern: + ``` + iriscli keys show [key name] --bech=val + ``` + Example response: + ``` + NAME: TYPE: ADDRESS: PUBKEY: + faucet local fva1ljemm0yznz58qxxs8xyak7fashcfxf5l9pe40u fvp1addwnpepqtdme789cpm8zww058ndlhzpwst3s0mxnhdhu5uyps0wjucaufha605ek3w + ``` + Then, example command to query validator: + ``` + iriscli stake validator fva1ljemm0yznz58qxxs8xyak7fashcfxf5l9pe40u + ``` + Example response: + ```text + Validator + Operator Address: fva1ljemm0yznz58qxxs8xyak7fashcfxf5l9pe40u + Validator Consensus Pubkey: fvp1zcjduepq8fw9p4zfrl5fknrdd9tc2l24jnqel6waxlugn66y66dxasmeuzhsxl6m5e + Jailed: false + Status: Bonded + Tokens: 100.0000000000 + Delegator Shares: 100.0000000000 + Description: {node2 } + Bond Height: 0 + Unbonding Height: 0 + Minimum Unbonding Time: 1970-01-01 00:00:00 +0000 UTC + Commission: {{0.1000000000 0.2000000000 0.0100000000 0001-01-01 00:00:00 +0000 UTC}} + ``` + +4. Edit validator + + ``` + iriscli stake edit-validator --from=<key name> --chain-id=<chain-id> --fee=0.004iris --commission-rate=0.15 --moniker=<new name> + ``` + +5. Increase self-delegation + + ``` + iriscli stake delegate --address-validator=<self-address-validator> --chain-id=<chain-id> --from=<key name> --fee=0.004iris --amount=100iris + ``` + +6. Delegate tokens to other validators + + If you just want to be a delegator, you can skip the above steps. + ``` + iriscli stake delegate --address-validator=<other-address-validator> --chain-id=<chain-id> --from=<key name> --fee=0.004iris --amount=100iris + ``` + +7. Unbond tokens from a validator + + Unbond half of total bonded token on a given validator + ``` + iriscli stake unbond --address-validator=<address-validator> --chain-id=<chain-id> --from=<key name> --fee=0.004iris --amount=100iris --share-percent=0.5 + ``` + +8. Redelegate tokens to another validator + + Redelegate half of total bonded token on a given validator to another one + ``` + iriscli stake redelegate --chain-id=<chain-id> --from=<key name> --fee=0.004iris --address-validator-source=<source validator address> --address-validator-dest=<destination validator address> --shares-percent=0.5 + ``` + +For other query stake state commands, please refer to [stake cli client](../cli-client/stake/README.md) diff --git a/docs/modules/iservice/test.proto b/docs/features/test.proto similarity index 100% rename from docs/modules/iservice/test.proto rename to docs/features/test.proto diff --git a/docs/modules/upgrade/README.md b/docs/features/upgrade.md similarity index 97% rename from docs/modules/upgrade/README.md rename to docs/features/upgrade.md index 6882286e7..06a1035b8 100644 --- a/docs/modules/upgrade/README.md +++ b/docs/features/upgrade.md @@ -10,7 +10,6 @@ The module supports the infrastructure of the blockchain software upgrade. It wi 1. Submit a software upgrade proposal 2. More details about governance process is in GOV [User Guide](../gov/README.md) - ### The process of software upgrade 1. Install a new software, send a switch message, and broadcast to the whole network. 2. Once reach the limited time, it will be counted whether the proportion of voting power of upgraded software exceeds 95%. @@ -28,7 +27,9 @@ iris init gen-tx --name=x --home=iris iris init --gen-txs --chain-id=upgrade-test -o --home=iris iris start --home=iris ``` + ### Submit a software upgrade proposal + ``` # Send an upgrade proposal iriscli gov submit-proposal --title=Upgrade --description="SoftwareUpgrade" --type="SoftwareUpgrade" --deposit=10iris --from=x --chain-id=upgrade-test --fee=0.05iris --gas=20000 diff --git a/docs/get-started/Download-Rainbow.md b/docs/get-started/Download-Rainbow.md new file mode 100644 index 000000000..06f225a0b --- /dev/null +++ b/docs/get-started/Download-Rainbow.md @@ -0,0 +1,8 @@ +# IRISnet Mobile Client: Rainbow + +## What is Raibow + +First IRISnet mobile client that supports cross-chain +multi-asset transfers and iServices consumption + +https://www.rainbow.one \ No newline at end of file diff --git a/docs/get-started/Genesis-Generation-Process.md b/docs/get-started/Genesis-Generation-Process.md index 9cf6282d1..6c62ff68a 100644 --- a/docs/get-started/Genesis-Generation-Process.md +++ b/docs/get-started/Genesis-Generation-Process.md @@ -6,69 +6,84 @@ You must have follow this [guide](Install-Iris.md) to install the correct versio ## Gentx -Please run the `gen-tx` command to generate files. +Please run the `keys add` subcommand and run the `gen-tx` subcommand to generate files. ``` -iris init gen-tx --name=your_name --home=path_to_home --ip=Your_public_IP +iriscli keys add your_name +iris gentx --name=your_name --home=<path_to_home> --ip=Your_public_IP ``` -You could see the following output: +For example, ``` -{ - "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" - } - } -} +iriscli keys add alice +iris gentx --name=alice --home=iris --chain-id=irishub-stage --ip=1.1.1.1 ``` -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 at `$IRISHOME/config/gentx/`. 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=" + "type": "auth/StdTx", + "value": { + "msg": [ + { + "type": "cosmos-sdk/MsgCreateValidator", + "value": { + "Description": { + "moniker": "chenggedexiaokeai.local", + "identity": "", + "website": "", + "details": "" + }, + "Commission": { + "rate": "0.1000000000", + "max_rate": "0.2000000000", + "max_change_rate": "0.0100000000" + }, + "delegator_address": "faa1cf25tf4pfjdhkzx8lqnkajlse6jcpm2fyw4yme", + "validator_address": "fva1cf25tf4pfjdhkzx8lqnkajlse6jcpm2f3lltx7", + "pubkey": { + "type": "tendermint/PubKeyEd25519", + "value": "/JvLFsvyMgm2ND4QgN4JKyLxhL42dVgat67383Q+mPY=" + }, + "delegation": { + "denom": "iris-atto", + "amount": "100000000000000000000" + } + } + } + ], + "fee": { + "amount": null, + "gas": "200000" }, - "power": "100", - "name": "" - }, - "app_gen_tx": { - "name": "name", - "address": "faa1nnlmkvfmdvn7efwqz7eyur9rszdw723adx2mcx", - "pub_key": "fap1zcjduepq6q4hpfep97yrnhslhwg9p0j6l8hecn4zgtfvwgn9yfjdkkdgrlrqftg82c" + "signatures": [ + { + "pub_key": { + "type": "tendermint/PubKeySecp256k1", + "value": "AtfNRj0zYvffAQG+iad6SScfdl29ag9G3EI0JDSwKJmy" + }, + "signature": "BwTejBceK4M+3LzmNl62jVFUr9wVv//UO7iI/yWi5KFoez9eY43HSlaZJf+3rnKLjosn2tD79EIw55BJ6SbYzQ==", + "account_number": "0", + "sequence": "0" + } + ], + "memo": "0eb02fdabb96923ac1e855ac012a5a624793264a@1.1.1.1:26656" } +} ``` +This is the `CreateValidator` message. validator is generated by \$IRISHOME/config/priv_validator.json ## Submit Gentx -Submit your `gentx-<node-id>.json` to `https://github.com/irisnet/testnets/tree/master/fuxi/fuxi-4000/config/gentx/` by createing a pull request. +Submit your `gentx-<node-id>.json` to `https://github.com/irisnet/testnets/tree/master/fuxi/fuxi-4000/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/fuxi/fuxi-4000/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/Install-Iris.md b/docs/get-started/Install-the-Software.md similarity index 98% rename from docs/get-started/Install-Iris.md rename to docs/get-started/Install-the-Software.md index bf871a7f0..4e80d1861 100644 --- a/docs/get-started/Install-Iris.md +++ b/docs/get-started/Install-the-Software.md @@ -97,7 +97,7 @@ cd $GOPATH/src/github.com/irisnet git clone https://github.com/irisnet/irishub cd irishub && git checkout v0.6.0 curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh -make get_tools get_vendor_deps install +make get_tools && get_vendor_deps && make install ``` If your environment variables have set up correctly, you should not get any errors by running the above commands. diff --git a/docs/get-started/Join-the-Testnet.md b/docs/get-started/Join-the-Testnet.md new file mode 100644 index 000000000..52fccef53 --- /dev/null +++ b/docs/get-started/Join-the-Testnet.md @@ -0,0 +1,49 @@ +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 to get Iris installed locally. + +Step 2: Run a Full Node + +Please follow this instruction to get your full node running. + +Step 3: Upgrade to Validator Node + +Please follow this instruction to upgrade your full node to validator node. + +Deploy IRISHub Monitor + +Please follow this guide 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 to setup a sentry node to protect yourself. + +Fuxi Incentivized Testnet + +IRIS foundation plans to reward all the testnet participants who took part in the testnet. In Fuxi-3001 testnet,the community members have finished the tasks and they will receive their rewards in genesis allocation. + +- Task List for Fuxi-3001: https://github.com/irisnet/testnets/blob/master/fuxi/fuxi-3001/README.md +- Results:https://github.com/irisnet/testnets/issues/125 + To get more people involved, IRIS foundation decides to send out more tasks in the latest iteration of testnet:Fuxi-4001. +- Task List for Fuxi-4000: https://github.com/irisnet/testnets/blob/master/fuxi/fuxi-4000/README.md + +Useful Links + +- Riot chat: #irisvalidators:matrix.org +- Explorer: https://testnet.irisplorer.io/#/home diff --git a/docs/introduction/README.md b/docs/introduction/README.md new file mode 100644 index 000000000..857e7dd82 --- /dev/null +++ b/docs/introduction/README.md @@ -0,0 +1,8 @@ +# Introduction + +## The IRIS hub + +## The IRIS Service + +## The IRIS Network + diff --git a/docs/light-client/README.md b/docs/light-client/README.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/modules/fee-token/README.md b/docs/modules/fee-token/README.md deleted file mode 100644 index d5b1c6c4b..000000000 --- a/docs/modules/fee-token/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# Fee Token specification - -## Previous implementation in Cosmos-SDK - -* There is no any constrain to fee token, just ensure gas is enough. Gas has no explicit connection with fee token. -* All fee token will be deducted - -## Current implementation in Cosmos-SDK - -* In global parameter store, the native fee token name has been specified. In iris network, the native fee token is iris. Other tokens will be ignored. The native fee token can't be modified. -* Transactions should specify the max gas (gasLimit) to be consumed in transaction execution. If the gas is exhausted, the transaction execution will be terminated and return error. No fee will be charged. -* gasPrice = feeToken / gasLimit. gasPrice should be no less than gasPriceThreshold (default value: 2*10^(-8)iris, iris precision: 10^18). Otherwise the transactions will be considered as invalid. gasPriceThreshold is a global parameter which can be modified by governance. -* Normally, the fee token will not be deducted totally. The deducted quantity depends on how many the gas is consumed. If half of gas is consumed, then only half of fee token will be deducted. - -## How to specify fee for transactions - -Now we must specify fee for each transaction properly. Otherwise, your transaction will be rejected. Here we take sending token for example. Now we can send token by command line and rest API: - -For command Line: -``` -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":"iris","amount":"10"}], - "name":"moniker", - "password":"1234567890", - "chain_id":"test-chain-UieBV2", - "sequence":"9", - "account_number":"0", - "gas":"10000", - "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. - -The transaction senders should ensure the gas is enough for transaction execution and the gasPrice is no less than gasPriceThreshold. In addition, only specify iris as fee token. Other token will be ignored. - -## Suggestions for test - -For both command line and rest API: - -* Try to specify no fee. -* Try to specify other token instead of iris token as fee. -* Try to specify few iris token. -* Try to specify more gas so that the gas price is very low. -* Try different kinds of transaction. - -## Future improvement - -* Fee token whitelist will be brought in. All tokens in the whitelist can be used as fee token. The whitelist can be modified by governance. -* Currently, the transaction senders have no motivation to pay more fee, just ensure the gasPrice is no less than the gasPriceThreshold. Next new mechanisms will be brought in to encourage users to pay more fee. For example, proposals will tender to include transactions with higher gasPrice. Transactions with lower gasPrice have to wait for more time. -* When a proposal builds a block, it should check whether the sum of all transaction gas is greater than blockGasLimit. If so, remove some transactions the accommodate this rule. With blockGasLimit, transactions which will consumed too much resource, such as memory , disk space and execution time, will be rejected. These special transaction may cause crash or consensus failure. -* Consider to charge fee even if the transactions encounter execution failure. This is helpful for defencing DDos attack. diff --git a/docs/modules/gov/README.md b/docs/modules/gov/README.md deleted file mode 100644 index 7961541cc..000000000 --- a/docs/modules/gov/README.md +++ /dev/null @@ -1,260 +0,0 @@ -# Gov/Iparam User Guide - -## Basic Function Description - -1. On-chain governance proposals on text -2. On-chain governance proposals on parameter change -3. On-chain governance proposals on software upgrade - -## 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 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) - -## Usage Scenario -### Create an environment - -``` -rm -rf iris -rm -rf .iriscli -iris init gen-tx --name=x --home=iris -iris init --gen-txs --chain-id=gov-test -o --home=iris -iris start --home=iris -``` - -### Usage scenario of parameter change - -Scenario 1:Change the parameters through the command lines - -``` -# Query parameters can be changed 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 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 -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 - -``` - -Scenario 2: Change the parameters by the files - -``` -# 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" - } - } -} - -# 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 -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 -``` - -* `--proposal-id` The ID of the proposal in voting period -* `--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 - -``` -# 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 changed in the module - - -``` -# Query the parameters can be modified by "key" -iriscli gov query-params --key=Gov/gov/DepositProcedure --trust-node -``` - -* `--key` Query the parameter corresponding to the "key" - -``` -# Export profiles -iriscli gov pull-params --path=iris --trust-node -``` - -* `--path` The folder of node initialization - - - -``` -# 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 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 - -``` -# 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 changed parameters; only 'update' is implemented at present -* Other fields' proposals are similar with text proposal - -### Proposals on software upgrade - -## Basic parameters - -``` -# DepositProcedure(The parameters in deposit period) -"Gov/gov/DepositProcedure": { - "min_deposit": [ - { - "denom": "iris-atto", - "amount": "10000000000000000000" - } - ], - "max_deposit_period": "10" -} -``` - -* 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) -* `max_deposit_period` Window period for repaying deposit, default :10, scope(0,1) - -``` -# VotingProcedure(The parameters in voting period) -"Gov/gov/VotingProcedure": { - "voting_period": "10" -}, -``` - -* Parameters can be changed -* `voting_perid` Window period for vote, default:10, scope(20,20000) - -``` -# 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. - diff --git a/docs/modules/iservice/README.md b/docs/modules/iservice/README.md deleted file mode 100644 index fc4ddd255..000000000 --- a/docs/modules/iservice/README.md +++ /dev/null @@ -1,86 +0,0 @@ -# IService User Guide - -## Basic Function Description - -1. Service Definition -2. Service Binding (TODO) -3. Service Invocation (TODO) -4. Dispute Resolution (TODO) -5. Service Analysis (TODO) - -## Interactive process - -### Service definition process - -1. Any users can define a service. In service definition,Use [protobuf](https://developers.google.com/protocol-buffers/) to standardize the definition of the service's method, its input and output parameters. - -## Usage Scenario -### Create an environment - -``` -rm -rf iris -rm -rf .iriscli -iris init gen-tx --name=x --home=iris -iris init --gen-txs --chain-id=service-test -o --home=iris -iris start --home=iris -``` - -### Service Definition - -``` -# Service definition -iriscli iservice define --chain-id=service-test --from=x --fee=0.004iris --name=test-service --service-description=service-description --author-description=author-description --tags "tag1 tag2" --broadcast=Broadcast --idl-content=<idl-content> --file=test.proto - -# Result -Committed at block 1040 (tx hash: 58FD40B739F592F5BD9B904A661B8D7B19C63FA9, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:13601 Tags:[{Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[247 102 151 120 200 0]}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) -{ - "tags": { - "completeConsumedTxFee-iris-atto": "159740000000000" - } -} - -# Query service definition -iriscli iservice definition --def-chain-id=service-test --name=test-service --chain-id=service-test - -``` - -## CLI Command Details - -``` -iriscli iservice define --chain-id=service-test --from=x --fee=0.004iris --name=test-service --service-description=service-description --author-description=author-description --tags "tag1 tag2" --broadcast=Broadcast --idl-content=<idl-content> --file=test.proto -``` - -* `--name` The name of iService -* `--service-description` The description of this iService -* `--author-description` The self-description of the iService creator which is optional -* `--tags` The keywords of this iService -* `--broadcast` The Broadcast type of this iService{`Broadcast`,`Unicast`} -* `--idl-content` The standardized definition of the methods for this iService -* `--file` Idl-content can be replaced by files,if the item is not empty. - -``` -iriscli iservice definition --def-chain-id=service-test --name=test-service --chain-id=service-test -``` - -* `--def-chain-id` The ID of the blockchain defined of the iService -* `--name` The name of iService - -## IDL extension -When using proto file to standardize the definition of the service's method, its input and output parameters, the method attributes can be added through annotations. - -### Annotation standard -* If `//@Attribute attribute: value` wrote on top of `rpc method`,it will be added to the method attributes. Eg. -> //@Attribute description: sayHello - -### Currently supported attributes -* `description` The name of this method in the iService -* `output_privacy` Whether the output of the method is encrypted,{`NoPrivacy`,`PubKeyEncryption`} -* `output_cached` Whether the output of the method is cached,{`OffChainCached`,`NoCached`} - -### IDL content example -* idl-content example -> syntax = \"proto3\";\n\npackage helloworld;\n\n// The greeting service definition.\nservice Greeter {\n //@Attribute description: sayHello\n //@Attribute output_privacy: NoPrivacy\n //@Attribute output_cached: NoCached\n rpc SayHello (HelloRequest) returns (HelloReply) {}\n}\n\n// The request message containing the user's name.\nmessage HelloRequest {\n string name = 1;\n}\n\n// The response message containing the greetings\nmessage HelloReply {\n string message = 1;\n}\n - -* IDL file example - -[test.proto](./test.proto) diff --git a/docs/modules/record/README.md b/docs/modules/record/README.md deleted file mode 100644 index a7ea515fe..000000000 --- a/docs/modules/record/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# Record User Guide - -## Basic Function Description - -1. On-Chain record for the text data -2. On-Chain record for the text file (TODO) -3. On-Chain governance for the record params (TODO) - -## Interaction Process - -### Record process - -1. Any users can initiate a record request. It will cost you some tokens. If there’s no record of the data on the existing chains, the request will be completed successfully and the relevant metadata will be recorded onchain. And you will be returned a record ID to confirm your ownership of the data. -2. If any others initiate a record request for the same data, the request will be directly rejected and it will hint that the relevant record data has already existed. -3. Any users can search/download onchain based on the record ID. -4. At present, the maximum amount of stored data at most 1K Bytes. In the future, the dynamic adjustment of parameters will be implemented in conjunction with the governance module. - -## Usage Scenarios - -### Build Usage Scenarios - -``` -rm -rf iris -rm -rf .iriscli -iris init gen-tx --name=x --home=iris -iris init --gen-txs --chain-id=record-test -o --home=iris -iris start --home=iris -``` - -### Usage Scenarios of Record on Chains - -Scenario 1: Record the data through cli - -``` -# Specify the text data which needs to be recorded by --onchain-data - -iriscli record submit --description="test" --onchain-data=x --from=x --fee=0.04iris - -# Result -Committed at block 4 (tx hash: F649D5465A28842B50CAE1EE5950890E33379C45, response: {Code:0 Data:[114 101 99 111 114 100 58 97 98 57 100 57 57 100 48 99 102 102 54 53 51 100 99 54 101 56 53 52 53 99 56 99 99 55 50 101 53 53 51 51 100 101 97 97 97 49 50 53 53 50 53 52 97 100 102 100 54 98 48 48 55 52 101 50 56 54 57 54 54 49 98] Log:Msg 0: Info: GasWanted:200000 GasUsed:3857 Tags:[{Key:[97 99 116 105 111 110] Value:[115 117 98 109 105 116 45 114 101 99 111 114 100]} {Key:[111 119 110 101 114 65 100 100 114 101 115 115] Value:[102 97 97 49 109 57 51 99 103 57 54 51 56 121 115 104 116 116 100 109 119 54 57 97 121 118 51 103 106 53 102 116 116 109 108 120 51 99 102 121 107 109]} {Key:[114 101 99 111 114 100 45 105 100] Value:[114 101 99 111 114 100 58 97 98 57 100 57 57 100 48 99 102 102 54 53 51 100 99 54 101 56 53 52 53 99 56 99 99 55 50 101 53 53 51 51 100 101 97 97 97 49 50 53 53 50 53 52 97 100 102 100 54 98 48 48 55 52 101 50 56 54 57 54 54 49 98]} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[2 189 149 142 250 208 0]}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) -{ - "tags": { - "action": "submit-record", - "completeConsumedTxFee-iris-atto": "\u0002\ufffd\ufffd\ufffd\ufffd\ufffd\u0000", - "ownerAddress": "faa1m93cg9638yshttdmw69ayv3gj5fttmlx3cfykm", - "record-id": "record:ab9d99d0cff653dc6e8545c8cc72e5533deaaa1255254adfd6b0074e2869661b" - } - } - -# Query the Status of the Records -iriscli record query --record-id=x - -# Download the Record -iriscli record download --record-id=x --file-name="download" - -``` - -Scenario 2: Query the transactions including recorded data onchain through cli - -``` -# Query the status of the records onchain -iriscli tendermint txs --tag "action='submit-record'" -``` - -## Details of cli - -``` -iriscli record submit --description="test" --onchain-data=x --chain-id="record-test" --from=x --fee=0.04iris -``` - -* `--onchain-data` The data needs to be recorded - - -``` -iriscli record query --record-id=x --chain-id="record-test" -``` - -* `--record-id` Record ID to be queried - - -``` -iriscli record download --record-id=x --file-name="download" --chain-id="record-test" -``` - -* `--file-name` The filename of recorded data, in the directory specified by `--home` diff --git a/docs/resources/README.md b/docs/resources/README.md new file mode 100644 index 000000000..718032453 --- /dev/null +++ b/docs/resources/README.md @@ -0,0 +1,3 @@ +# Resources + +This is where you could find all the resources of IRISnet. \ No newline at end of file diff --git a/docs/delegators/README.md b/docs/resources/delegator-faq.md similarity index 100% rename from docs/delegators/README.md rename to docs/resources/delegator-faq.md diff --git a/docs/resources/validator-faq.md b/docs/resources/validator-faq.md new file mode 100644 index 000000000..e62b4e6cc --- /dev/null +++ b/docs/resources/validator-faq.md @@ -0,0 +1,26 @@ +# Fuxi测试网激励计划常见问题 + + +1.如何加入Fuxi测试网? + +你可以加入QQ工作群:834063323。团队将在群里及时通知有关测试网的消息。 + +有两种方式加入测试网: +* 以验证人的身份加入:你可以在自己的服务器上部署一个IRIShub节点。然后将其绑定成为一个验证人节点。如果你暂时没有服务器,你也可以申请免费试用BaaS的服务,我们将提供 +Wancloud和Zig-BaaS的免费试用机会。然后你就可以完成测试网的任务了。 + +* 以委托人的身份加入: +如果你对于部署一个验证人节点感到很困难,你可以只下载一个客户端,然后执行相关的测试网的任务交易。 + + +2.测试网的激励任务在哪里? + +每一个测试网迭代中,团队都会发布相关的测试网激励任务。例如,Fuxi-3001测试网激励任务在下面链接中:https://github.com/irisnet/testnets/tree/master/fuxi/fuxi-3001 + +3.怎样能知道我的任务完成情况? + +每当决定切换到下一个测试网的时候,团队会检查参与者的任务完成情况。例如,Fuxi-2000测试网任务完成情况在这里:https://github.com/irisnet/testnets/issues/51 + +4.如果我获得了测试网奖励,何时才能拿到? + +测试网的奖励将在主网上线后发放给社区成员。你需要用你的Keybase签名一个irishub的地址,然后将其发送给团队。 \ No newline at end of file diff --git a/docs/introduction/Whitepaper.md b/docs/resources/whitepaper-en.md similarity index 100% rename from docs/introduction/Whitepaper.md rename to docs/resources/whitepaper-en.md diff --git a/docs/resources/whitepaper-kr.md b/docs/resources/whitepaper-kr.md new file mode 100644 index 000000000..1911a7c8e --- /dev/null +++ b/docs/resources/whitepaper-kr.md @@ -0,0 +1 @@ +# IRIS \ No newline at end of file diff --git a/docs/introduction/Whitepaper_CN.md b/docs/resources/whitepaper-zh.md similarity index 100% rename from docs/introduction/Whitepaper_CN.md rename to docs/resources/whitepaper-zh.md diff --git a/docs/software/README.md b/docs/software/README.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/software/cli-client.md b/docs/software/cli-client.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/software/light-client.md b/docs/software/light-client.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/software/monitor.md b/docs/software/monitor.md new file mode 100644 index 000000000..e1d5ed132 --- /dev/null +++ b/docs/software/monitor.md @@ -0,0 +1,59 @@ +# How to deploy IRIS Monitor + +## Install IRIS Monitor +Please refer to this [document](https://github.com/irisnet/irishub/blob/master/docs/get-started/Install-Iris.md) for deatiled instructions. Besides, please make sure your machine has these commands(bash, wc, ps) installed. + +## Start IRIS Monitor + +``` +irismon --address=EAC535EC37EB3AE8D18C623BA4B4C8128BC082D2 \ +--account-address=faa1nwpzlrs35nawthal6vz2rjr4k8xjvn7k8l63st \ +--chain-id=irishub-stage --node=http://localhost:26657 +``` + +Parameters: + +- `address`:hex encoded validator address +- `account-address`:bech32 encoded account address +- `chain-id`:blockchain id that you want to monitor +- `node`:listening address of the node that you want to monitor (The rpc url of a irishub node, default value is tcp://localhost:26657. If you want to monitor other irishub nodes, please change this value.) + +Then you can visit `http://localhost:36660/` to see metrics data。 + +## Start Prometheus + +### Edit Prometheus config file + +You can visit [prometheus.yml](https://github.com/prometheus/prometheus/blob/master/documentation/examples/prometheus.yml) to download default `prometheus.yml`. + +Then edit `prometheus.yml` and add `jobs` : + +```yaml + - job_name: fuxi-4000 + static_configs: + - targets: ['localhost:36660'] + labels: + instance: fuxi-4000 +``` + +> Note:value of targets is ip:port which used by IRIS monitor + +### Start Prometheus + +```bash +docker run -d --name=prometheus -p 9090:9090 -v ~/volumes/prometheus:/etc/prometheus prom/prometheus +``` + +> The above example, you can save `prometheus.yml` at `~/volumes/prometheus` on your host machine + +You can visit `http://localhost:9090` to see prometheus data. + +## Start Grafana + +``` +docker run -d --name=grafana -p 3000:3000 grafana/grafana +``` + +You can visit `http://localhost:3000/` to open grafana and create your own dashboard. + +> Tips: The default username and password are both admin. We strongly recommend immediately changing your username & password after login \ No newline at end of file diff --git a/docs/software/node.md b/docs/software/node.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/tools/Deploy-IRIS-Monitor.md b/docs/tools/Deploy-IRIS-Monitor.md deleted file mode 100644 index a2f598566..000000000 --- a/docs/tools/Deploy-IRIS-Monitor.md +++ /dev/null @@ -1,62 +0,0 @@ -# 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. - -### Get Monitor Info - -* Address of validator - -``` --a= < hex-encoded-address-of-validator > -``` - -* Chain-ID -``` ---chain-id= < id-of-blockchain > -``` - -* Node - - -``` ---node= < localhost:26657 > -``` -### Start IRIS Monitor -Example: -``` -irismon --account-address=faa1nwpzlrs35nawthal6vz2rjr4k8xjvn7k8l63st --address=EAC535EC37EB3AE8D18C623BA4B4C8128BC082D2 --chain-id=irishub-stage --node=http://localhost:26657& -``` - -then, you can visit http://localhost:3660/ to see the metrics page. - -### Start Prometheus - -First, you need to edit the configuration file of prometheus. Add `jobs` : -```$xslt -- job_name: fuxi-4000 - - static_configs: - - - targets: ['localhost:36660'] - - labels: - - instance: fuxi-4000 -``` -Then, you could see in your browser that there are some data available at port 36660. - -### Start Grafana - -You could start grafana with docker by running: -```$xslt -sudo docker run -p 3000:3000 grafana/grafana 1>grafana.log 2>grafana.error & -``` - -The default username and password are both admin. We strongly recommend immediately changing your username & password after login. - -Then you could create your own dashboard. - -### Stop IRIS Monitor -``` -kill -9 <irismon-process-id> -``` \ No newline at end of file diff --git a/docs/validators/FAQ.md b/docs/validators/FAQ.md deleted file mode 100644 index 50576ac7f..000000000 --- a/docs/validators/FAQ.md +++ /dev/null @@ -1,58 +0,0 @@ -# FAQ - -1. What is IRISnet? - -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. IRISnet is designed to be the foundation for next generation distributed business applications. IRISnet will enhance Interblockchain Communication(IBC)protocol of Cosmos to introduce a service-oriented infrastructure into ecosystem to support more efficient building distributed business application chains. It will make services interoperable across blockchains: public, consortium & legacy systems. - -2. IRISnet and Cosmos - -Cosmos IBC 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.The IRIS network could provide the service infrastructure for handing and coordinating on-chain transaction processing with off-chain data processing and business logic execution - - -3. What is IRIS token? - -IRIS token is the native toke in IRISnet. It has two main usages: - -* Staking token: IRIS token holders could stake or delegate some IRIS to become a validator candidate -* Fee token: IRIS could be used to pay for network fee and service fee. - -iris precision: 10^18 - - - -3. Server Configuration - -Here is the recommanded configuration of the server. -* No. of CPUs: 2 -* Memory: 4GB -* Disk: 40GB SSD -* OS: Ubuntu 18.04 LTS/16.04 LTS -* Allow all incoming connections from TCP port 26656 and 26657 - - -4. What is a Validator? - - -The IRISHub is based on a consensus engine called Tendermint. It relies on a set of validators to secure the network. The role of validators is to run a full-node and participate in consensus by broadcasting votes which contain cryptographic signatures signed by their private key. Validators commit new blocks in the blockchain and receive revenue in exchange for their work. They must also participate in governance by voting on proposals. Validators are weighted according to their total stake. - -The reward for a validator is 3-fold: - -* Block provision -* Transaction fee -* Commission - - -5. What is a Delegator? - -Not every iris token holder is eligible to become a validator. Any iris token holder could choose to delegate their own iris token to one or more validators. In this way, they could still earn block provision and transaction fees. At the same time, some percent of commission needs to be paid to their validator. - - -6. How to understand different address formats in IRISnet? - -Please read this [doc](https://github.com/irisnet/testnets/blob/master/fuxi/docs/Bech32%20on%20IRISnet.md) to understand the address format in IRISnet. - -7. How to understand the notion of gas&fee in IRISHub? - -This is the tech spec for fee&gas is [here](../modules/fee-token/README.md) - - diff --git a/docs/validators/How-to-participate-in-onchain-governance.md b/docs/validators/How-to-participate-in-onchain-governance.md deleted file mode 100644 index bef0c3bc0..000000000 --- a/docs/validators/How-to-participate-in-onchain-governance.md +++ /dev/null @@ -1,198 +0,0 @@ -# Governance In IRISHub - -## What is Blockchain Governance? - -Generally, governance is about decisions that ultimately affect stakeholders of blockchain network. It’s about the processes -that community members in governance use to make decisions. -It’s also about how different groups coordinate around decisions and decision-making processes. -It includes the establishment, maintenance, and revocation of the legitimacy of decisions, decision making processes, norms, -and other mechanisms for coordination. - -### Stakeholder of Governance - -* Core Developers:a blockchain are software developers who work on the software that implement that protocol. -Developers have processes that are supposed to assure the quality of the software they release, - -* Validators/Delegators: Validators and delegators are responsible for securing the network. They need to actively involved in governance -proposals or their credit will be damaged. - -* Community Members: They could come up with interesting for improvement of network. block explorers and other low level service providers, exchanges, speculators, application developers, users, journalists and passive observers - - - -## Governance Process -![workflow](../pics/flow.jpg) - -The governance process is divided in a few steps that are outlined below: - -* Proposal submission: Proposal is submitted to the blockchain with a deposit. -* Vote: Once deposit reaches a certain value (MinDeposit), proposal is confirmed and vote opens. Bonded Atom holders can then send TxGovVote transactions to vote on the proposal. -* If the proposal is passed, then there sill be some changes. - - -For `System Parameter Change` proposals, the following parameters are eligible for change: - -* Mininimum Depost: `10IRIS` -* Deposit Period: 1440 blocks -* Penalty for non-voting validtors: 1% -* Pass Threshold: 50% -* Voting Period: 20000 blocks - - -### Types of Governance Proposal - -* Text -* System Parameter Change -* Protocol Upgrade - - -## How to submit a proposal? - -Anyone could submit a governance proposal, but you need to make the deposit for this proposal more than the minimium requirement. - -The following command is for submitting a `Text` proposal: - -``` -iriscli gov submit-proposal --title="Text" --description="name of the proposal" --type="Text" --deposit="100iris" --proposer=<account> --from=<name> --chain-id=fuxi-4000 --fee=0.05iris --gas=20000 --node=http://localhost:26657 -``` - -The `<account>` for `proposer` field should start with `faa` which corresponds to `<name>`. - - -## How to add deposit to a proposal? - -To add deposit to some proposal, you could execute this command to add `100IRIS` to the proposal's deposit: - -``` -iriscli gov deposit --proposalID=1 --depositer=<account> --deposit=1000000000000000000iris --from=<name> --chain-id=fuxi-4000 --fee=0.05iris --gas=20000 --node=http://localhost:36657 -``` -## How to query proposals? - -Run the following command will return all the existing proposals: -```$xslt -iriscli gov query-proposals -``` -Example output: -```$xslt - 1 - 78547 - 2 - 96866 - 3 - 46727 - 4 - 92454 - 5 - 57682 -``` - -You could also use IRISplorer to see all proposal. - -## 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 `<proposal_id>`.You could execute the following command to vote on proposal with ID = 1: - - -## How to get more information about a proposal? - -You could use the following command to get the first proposal: -``` -iriscli gov query-proposal --proposal-id=6 --chain-id=fuxi-3001 --node=http://localhost:26657 -``` - -Example output is the following: -```$xslt -{ - "proposal_id": "1", - "title": "text_proposal", - "description": "test_description", - "proposal_type": "Text", - "proposal_status": "VotingPeriod", - "tally_result": { - "yes": "0", - "abstain": "0", - "no": "0", - "no_with_veto": "0" - }, - "submit_block": "200981", - "total_deposit": [ - "20iris" - ], - "voting_start_block": "200981", - "param": { - "key": "", - "value": "", - "op": "" - } -} -``` -## Proposal Examples - -### Text Proposal - -A text proposal is just a notice. You could send one with the following command: -```$xslt -iriscli gov submit-proposal --title=text_proposal --description=test_description --type=Text --deposit=20iris --fee=0.1iris --from=bft --chain-id=fuxi-4000 -``` -You could vote on it with the following command: -```$xslt -iriscli gov vote --proposal-id=6 --option=Yes --from=bft --chain-id=fuxi-4000 --fee=0.05iris --gas=20000 -``` - - -### System Parameter Change Proposal - -First, you could query the flexible parameters with the following command: -``` -iriscli gov query-params --trust-node --module=gov - -``` - -The output is the shown below: -```$xslt -[ - "Gov/gov/DepositProcedure", - "Gov/gov/TallyingProcedure", - "Gov/gov/VotingProcedure" -] -``` -It corresponds to the following fields in genesis file: - -```json -gov: { -starting_proposalID: "1", -deposit_period: { -min_deposit: [ -{ -denom: "iris-atto", -amount: "10000000000000000000" -} -], -max_deposit_period: "50" -}, -voting_period: { -voting_period: "50" -}, -tallying_procedure: { -threshold: "1/2", -veto: "1/3", -governance_penalty: "1/100" -} -}, -``` - - -The default value of flexible parameters are shown above. - -You could submit a parameter change proposal, -```$xslt -iriscli gov submit-proposal --title="update VotingProcedure" --description="test" --type="ParameterChange" --deposit=10iris --param='{"key":"Gov/gov/VotingProcedure","value":"{\"voting_period\": 250}","op":"update"}' --from=bft --chain-id=fuxi-4000 --fee=0.05iris --gas=20000 -``` -This proposal will change the voting period from default to 250. - -### System Upgrade Proposal - -You could read more about it in the [doc](../modules/upgrade/README.md) \ No newline at end of file diff --git a/docs/validators/README.md b/docs/validators/README.md deleted file mode 100644 index cb4952187..000000000 --- a/docs/validators/README.md +++ /dev/null @@ -1,154 +0,0 @@ -# Validators - -## 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. - - -## States for Validator - - -After a validator is created with a `create-validator` transaction, it can be in the following states: - -![states](../pics/states.png) - -After a validator is created with a create-validator transaction, it can be in five states: - -* `unbonded` & `unjailed` : -* `bonded`: -* `unbonding`& `unjailed`: -* `unbonding`& `jailed`: -* `unbonded`&`jailed`: - -Validator is in the active set and participates in consensus. Validator is earning rewards and can be slashed for misbehaviour. -unbonding: Validator is not in the active set and does not participate in consensus. Validator is not earning rewards, but can still be -slashed for misbehaviour. This is a transition state from bonded to unbonded. If validator does not send a rebond transaction while in -* unbonding mode, it will take three weeks for the state transition to complete. -* unbonded: Validator is not in the active set, and therefore not signing blocs. -Validator cannot be slashed, and does not earn any reward. It is still possible to delegate Atoms to this validator. Un-delegating -from an unbonded validator is immediate. - -Once a user execute `create-validator` transaction with pubkey of a fully synced node, -its state become `unbonded` & `unjailed`. If it's voting power is in the top 100 of all the candidates, then the state will change to `Bonded`. -But if the voting power is not enough to make to top 100, then the state will change to `unbonding`& `unjailed`. If the state keeps unchange for 3 weeks, -then the state will change back to `unbonded` & `unjailed`. During this time, the validator could use additional delegations or add self-delegation. -If the validator get jailed for slashing or unbond all of his self-delegation, then his state will change to `unbonding`& `jailed`. The slashing conditions -are explained below. The validator could use a `unrevoke` command to unjailed himself. His voting power will be reduced by a portion. -If he could still remain in the top 100 validator candidates, then his state is `Bonded`, otherwise it's `unbonding`& `unjailed`. -However, if the validator doesn't unjail himself in 3 weeks, his state will be `unbonded`&`jailed`. But he could still unjail himself later. -If he unjailed himself from the state `unbonded`&`jailed`, his state will be `Bonded` if his voting power is within top 100. - -### Slashing conditions -While a validator’s goal is staying online, we will test slashing. Slashing is a punitive function that is triggered by a validator ’s bad actions. Getting slashed is losing voting power. Validators will be slashed for the actions below: - -* Going offline or unable to communicate with the network - -* Double sign a block - -## Common Operations for Validators - -* **Create Validator** - -All the participants could show that they want to become a validator by sending a `create-validator` transaction, the following parameters would be necessory: - -The following parameters are essential: - -* `Validator's PubKey`: With flag `--pubkey`, the private key associated with PubKey is used to sign blocks. -* `Validator's Address`: With flag `--address-validator`, the address of a participant who wants to become a validator. This is the address used to identify your validator publicly. Thhis address is used to bond, unbond, claim rewards, receive delegation and participate in governance. -* `Validator's name` : With flag `--pubkey`, default value: [do-not-modify] -* `Validator's self bond tokens`: With flag `--amount`, this value should be more than 0 and it's under unit `iris-atto` - - -The following parameters are optional: -* `Validator's website`: With flag `--website` -* `Validator's details`: With flag `--details` - -How to get the `PubKey` of your node? -``` -iris tendermint show_validator --home={path-to-your-home} -``` - -The example output is the following: -``` -fvp1zcjduepqcxd82mjnsnqfhwzja2d3y690ec6scw64xpg2uqkjx3rl0g0p2lwsprxnnf -``` - -In summary, an example of the `create-validator` command to bond 10IRIS is the following: -``` -iriscli stake create-validator --pubkey=pub-key --amount=XXiris --fee=0.05iris --gas=2000000 --node=tcp://localhost:26657 --chain-id=fuxi-4000 --from=name --moniker=name -``` -### Edit Validator Information - -Validators could edit its information. - -The following parameters are optional: - -* keybase signature of the validator key holder: With flag `--keybase-sig`,default value: [do-not-modify] -* the official website of the validator operator: With flag `--website`,default value: [do-not-modify] -* the name of validator: With flag `--moniker`,default value: [do-not-modify] - - -The command is the following: -```$xslt -iriscli stake edit-validator --chain-id=fuxi-4000 --from=name --details=details --gas=2000000 --fee=0.04iris -``` - -For each validator, the voting power is the sum of self-bonded token and delegated tokens. - - -### View Validator Description - -Anyone can view certain validator's information with the following command: -```$xslt -iriscli stake validator --address-validator={address-validator} --chain-id=fuxi-4000 -``` - -### Track Validator Signing Information -In order to keep track of a validator's signatures in the past you can do so by using the signing-info command: - -The command is the following: -``` -iriscli stake signing-information <validator-pubkey> --chain-id=fuxi-4000 -``` - -### Unrevoke Validator -When a validator is Revoked for downtime, you must submit an Unrevoke transaction in order to be able to get block rewards again. -In fuxi-3001, if your node missed the previous 5000 blocks in the last 10000 blocks, you will get revoked. -To query your validator's info: -```$xslt -Validator -Owner: -Validator: -Revoked: true -Status: Bonded -Tokens: 211.5500000000 -Delegator Shares: 2800.3740578441 -Description: {} -Bond Height: 642721 -Proposer Reward Pool: -Commission: 0/1 -Max Commission Rate: 0/1 -Commission Change Rate: 0/1 -Commission Change Today: 0/1 -Previous Bonded Tokens: 0/1 -``` - -The `Revoked` field of an offline validator will be `true`. - -To unrevoke your validator node, the command is the following: - -``` -iriscli stake unrevoke --from=name --chain-id=fuxi-4000 -``` \ No newline at end of file diff --git a/docs/validators/Setup-Sentry-Node.md b/docs/validators/Setup-Sentry-Node.md deleted file mode 100644 index 41d5612ef..000000000 --- a/docs/validators/Setup-Sentry-Node.md +++ /dev/null @@ -1,59 +0,0 @@ -# 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.toml` 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.toml` 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/zh/cli-client/README.md b/docs/zh/cli-client/README.md new file mode 100644 index 000000000..e6889113b --- /dev/null +++ b/docs/zh/cli-client/README.md @@ -0,0 +1,56 @@ +# 命令行客户端 + +## 查询命令的flags + +| 名称, 速记 | 类型 |必需 |默认值 | 描述 | +| --------------- | ---- | -------- | --------------------- | -------------------------------------------------------------------- | +| --chain-id | string | false | "" | Tendermint节点的Chain ID | +| --height | int | false | 0 | 查询某个高度的区块链数据,如果是0,这返回最新的区块链数据 | +| --help, -h | string | false | | 打印帮助信息 | +| --indent | bool | false | false | 格式化json字符串| +| --ledger | bool | false | false | 是否使用硬件钱包 | +| --node | string | false | tcp://localhost:26657 | tendermint节点的rpc地址| +| --trust-node | bool | false | true | 是否信任全节点返回的数据,如果不信任,客户端会验证查询结果的正确性 | + +每个区块链状态查询命令都包含上表中的flags,同时不同查询命令还可能会有自己独有的flags。 + +## 发送交易命令的flags + +| 名称, 速记 | 类型 |必需 |默认值 | 描述 | +| Name, shorthand | type | Required | Default | Description | +| -----------------| ----- | -------- | --------------------- | ------------------------------------------------------------------- | +| --account-number | int | false | 0 | 发起交易的账户的编号 | +| --async | bool | false | false | 是否异步广播交易 | +| --chain-id | string | true | "" | Tendermint节点的`Chain ID` | +| --dry-run | bool | false | false | 模拟执行交易,并返回消耗的`gas`。`--gas`指定的值会被忽略 | +| --fee | string | true | "" | 交易费 | +| --from | string | false | "" | 发送交易的账户名称 | +| --from-addr | string | false | "" | 签名地址,在`generate-only`为`true`的情况下有效 | +| --gas | int | false | 200000 | 交易的gas上限; 设置为"simulate"将自动计算相应的阈值 | +| --gas-adjustment | int | false | 1 | gas调整因子,这个值降乘以模拟执行消耗的`gas`,计算的结果返回给用户; 如果`--gas`的值不是`simulate`,这个标志将被忽略 | +| --generate-only | bool | false | false | 是否仅仅构建一个未签名的交易便返回 | +| --help, -h | string | false | | 打印帮助信息 | +| --indent | bool | false | false | 格式化json字符串 | +| --json | string | false | false | 指定返回结果的格式,`json`或者`text` | +| --ledger | bool | false | false | 是否使用硬件钱包| +| --memo | string | false | "" | 指定交易的memo字段 | +| --node | string | false | tcp://localhost:26657 | tendermint节点的rpc地址 | +| --print-response | bool | false | false | 是否打印交易返回结果,仅在`async`为true的情况下有效| +| --sequence int | int | false | 0 | 发起交易的账户的sequence | +| --trust-node | bool | false | true | 是否信任全节点返回的数据,如果不信任,客户端会验证查询结果的正确性 | + +每个发送交易的命令都包含上表中的flags,同时不同交易的命令还可能会有自己独有的flags。 + +## 模块列表 + +1. [bank command](./bank/README.md) +2. [distribution command](./distribution/README.md) +3. [gov command](./gov/README.md) +4. [keys command](./keys/README.md) +5. [lcd command](./lcd/README.md) +6. [record command](./record/README.md) +7. [service command](./service/README.md) +8. [stake command](./stake/README.md) +9. [status command](./status/README.md) +10. [tendermint command](./tendermint/README.md) +11. [upgrade command](./upgrade/README.md) diff --git a/docs/zh/cli-client/bank/README.md b/docs/zh/cli-client/bank/README.md new file mode 100644 index 000000000..5083eb47f --- /dev/null +++ b/docs/zh/cli-client/bank/README.md @@ -0,0 +1 @@ +# iriscli \ No newline at end of file diff --git a/docs/zh/cli-client/distribution/README.md b/docs/zh/cli-client/distribution/README.md new file mode 100644 index 000000000..39b9e0349 --- /dev/null +++ b/docs/zh/cli-client/distribution/README.md @@ -0,0 +1,28 @@ +# iriscli distribution + +## 介绍 + +这里主要介绍distribution模块提供的命令行接口 + +## 用法 + +``` +iriscli distribution [subcommand] +``` + +打印子命令和参数 + +``` +iriscli distribution --help +``` + +## 子命令 + +| 名称 | 功能 | +| --------------------------------| --------------------------------------------------------------| +| [delegation-distr-info](delegation-distr-info.md) | 查询委托(delegation)的收益分配记录 | +| [delegator-distr-info](delegator-distr-info.md) | 查询委托人所有的委托(delegation)的收益分配记录 | +| [validator-distr-info](validator-distr-info.md) | 查询验证人收益分配记录 | +| [withdraw-address](withdraw-address.md) | 查询收益取回地址 | +| [set-withdraw-address](set-withdraw-address.md) | 设置收益取回地址 | +| [withdraw-rewards](withdraw-rewards.md) | 发起取回收益的交易 | diff --git a/docs/zh/cli-client/distribution/delegation-distr-info.md b/docs/zh/cli-client/distribution/delegation-distr-info.md new file mode 100644 index 000000000..be15ef4d1 --- /dev/null +++ b/docs/zh/cli-client/distribution/delegation-distr-info.md @@ -0,0 +1,38 @@ +# iriscli distribution delegation-distr-info + +## 介绍 + +查询某个委托的收益分配信息 + +## 用法 + +``` +iriscli distribution delegation-distr-info [flags] +``` + +打印帮助信息 + +``` +iriscli distribution delegation-distr-info --help +``` + +## 特有的flags + +| 名称 | 类型 | 是否必填 | 默认值 | 功能描述 | +| --------------------| ----- | -------- | -------- | -------------- | +| --address-validator | string | true | "" | 验证人bech地址 | +| --address-delegator | string | true | "" | 委托人bech地址 | + +## 示例 + +``` +iriscli distribution delegation-distr-info --address-delegator=<delegator address> --address-validator=<validator address> +``` +执行结果示例 +```json +{ + "delegator_addr": "faa1ezzh0humhy3329xg4avhcjtay985nll0zswc5j", + "val_operator_addr": "fva1ezzh0humhy3329xg4avhcjtay985nll0hpyhf4", + "del_pool_withdrawal_height": "4044" +} +``` \ No newline at end of file diff --git a/docs/zh/cli-client/distribution/delegator-distr-info.md b/docs/zh/cli-client/distribution/delegator-distr-info.md new file mode 100644 index 000000000..d82c9eadb --- /dev/null +++ b/docs/zh/cli-client/distribution/delegator-distr-info.md @@ -0,0 +1,38 @@ +# iriscli distribution delegator-distr-info + +## 介绍 + +查询委托人全部委托的收益分配信息 + +## 用法 + +``` +iriscli distribution delegator-distr-info [delegator address] [flags] +``` + +打印帮助信息 + +``` +iriscli distribution delegator-distr-info --help +``` + +## 示例 + +``` +iriscli distribution delegation-distr-info [delegator address] +``` +执行结果示例 +```json +[ + { + "delegator_addr": "faa1ezzh0humhy3329xg4avhcjtay985nll0zswc5j", + "val_operator_addr": "fva14a70gzu0v2w8dlfx462c9sldvja24qaz6vv4sg", + "del_pool_withdrawal_height": "10859" + }, + { + "delegator_addr": "faa1ezzh0humhy3329xg4avhcjtay985nll0zswc5j", + "val_operator_addr": "fva1ezzh0humhy3329xg4avhcjtay985nll0hpyhf4", + "del_pool_withdrawal_height": "4044" + } +] +``` \ No newline at end of file diff --git a/docs/zh/cli-client/distribution/set-withdraw-address.md b/docs/zh/cli-client/distribution/set-withdraw-address.md new file mode 100644 index 000000000..0848d5d68 --- /dev/null +++ b/docs/zh/cli-client/distribution/set-withdraw-address.md @@ -0,0 +1,23 @@ +# iriscli distribution set-withdraw-addr + +## 介绍 + +设置取回收益时的收款地址 + +## 用法 + +``` +iriscli distribution set-withdraw-addr [withdraw-address] [flags] +``` + +打印帮助信息: + +``` +iriscli distribution set-withdraw-addr --help +``` + +## 示例 + +``` +iriscli distribution set-withdraw-addr [withdraw-address] --from <key name> --fee=0.004iris --chain-id=<chain-id> +``` diff --git a/docs/zh/cli-client/distribution/validator-distr-info.md b/docs/zh/cli-client/distribution/validator-distr-info.md new file mode 100644 index 000000000..f36c9703b --- /dev/null +++ b/docs/zh/cli-client/distribution/validator-distr-info.md @@ -0,0 +1,38 @@ +# iriscli distribution validator-distr-info + +## 介绍 + +查询验证人的收益分配信息 + +## 用法 + +``` +iriscli distribution validator-distr-info [flags] +``` + +打印帮助信息: + +``` +iriscli distribution validator-distr-info --help +``` + +## 示例 + +``` +iriscli distribution validator-distr-info <validator address> +``` +执行结果示例 +```json +[ + { + "delegator_addr": "faa1ezzh0humhy3329xg4avhcjtay985nll0zswc5j", + "val_operator_addr": "fva14a70gzu0v2w8dlfx462c9sldvja24qaz6vv4sg", + "del_pool_withdrawal_height": "10859" + }, + { + "delegator_addr": "faa1ezzh0humhy3329xg4avhcjtay985nll0zswc5j", + "val_operator_addr": "fva1ezzh0humhy3329xg4avhcjtay985nll0hpyhf4", + "del_pool_withdrawal_height": "4044" + } +] +``` \ No newline at end of file diff --git a/docs/zh/cli-client/distribution/withdraw-address.md b/docs/zh/cli-client/distribution/withdraw-address.md new file mode 100644 index 000000000..53abbd44a --- /dev/null +++ b/docs/zh/cli-client/distribution/withdraw-address.md @@ -0,0 +1,28 @@ +# iriscli distribution withdraw-address + +## 介绍 + +查收取回收益时的收款地址 + +## 用法 + +``` +iriscli distribution withdraw-address [delegator-address] [flags] +``` + +打印帮助信息: + +``` +iriscli distribution withdraw-address --help +``` + +## 示例 + +``` +iriscli distribution withdraw-address [delegator-address] +``` +执行结果示例 +``` +faa1ezzh0humhy3329xg4avhcjtay985nll0zswc5j +``` +If the given delegator didn't specify other withdraw address, the query result will be empty. \ No newline at end of file diff --git a/docs/zh/cli-client/distribution/withdraw-rewards.md b/docs/zh/cli-client/distribution/withdraw-rewards.md new file mode 100644 index 000000000..769c29233 --- /dev/null +++ b/docs/zh/cli-client/distribution/withdraw-rewards.md @@ -0,0 +1,41 @@ +# iriscli distribution withdraw-rewards + +## 介绍 + +取回收益 + +## 用法 + +``` +iriscli distribution withdraw-rewards [flags] +``` + +打印帮助信息: + +``` +iriscli distribution withdraw-rewards --help +``` + +## 特有的flags + +| 名称 | 类型 | 是否必填 | 默认值 | 功能描述 | +| --------------------- | ----- | -------- | -------- | ------------------------------------------------------------------- | +| --only-from-validator | string | false | "" | 验证人地址,仅取回在这个验证人上的委托收益 | +| --is-validator | bool | false | false | 取回验证人佣金收益 | + +不能同时使用两个flags。 + +## 示例 + +1. 仅取回某一个委托产生的收益 + ``` + iriscli distribution withdraw-rewards --only-from-validator fva134mhjjyyc7mehvaay0f3d4hj8qx3ee3w3eq5nq --from mykey --fee=0.004iris --chain-id=irishub-test + ``` +2. 取回所有委托产生的收益,不包含验证人的佣金收益: + ``` + iriscli distribution withdraw-rewards --from mykey --fee=0.004iris --chain-id=irishub-test + ``` +3. 取回所有委托产生的收益以及验证人的佣金收益: + ``` + iriscli distribution withdraw-rewards --is-validator=true --from mykey --fee=0.004iris --chain-id=irishub-test + ``` \ No newline at end of file diff --git a/docs/zh/cli-client/gov/README.md b/docs/zh/cli-client/gov/README.md new file mode 100644 index 000000000..fbdfd45e5 --- /dev/null +++ b/docs/zh/cli-client/gov/README.md @@ -0,0 +1,42 @@ +# iriscli gov + +## 描述 + +该模块提供如下所述的基本功能: +1.关于案文的连锁治理提案 +2.关于参数变化的链式治理建议 +3.关于软件升级的链式治理建议 + +## 使用方式 + +```shell +iriscli gov [command] +``` + +打印子命令和参数 +``` +iriscli distribution --help +``` + +## 相关命令 + +| 命令 | 描述 | +| ------------------------------------- | --------------------------------------------------------------- | +| [query-proposal](query-proposal.md) | 查询单个提议的详细信息 | +| [query-proposals](query-proposals.md) | 通过可选过滤器查询提议 | +| [query-vote](query-vote.md) | 查询投票信息 | +| [query-votes](query-votes.md) | 查询提议的投票情况 | +| [query-deposit](query-deposit.md) | 查询保证金详情 | +| [query-deposits](query-deposits.md) | 查询提议的保证金 | +| [query-tally](query-tally.md) | 查询提议投票的统计 | +| [query-params](query-params.md) | 查询参数提议的配置 | +| [pull-params](pull-params.md) | 生成param.json文件 | +| [submit-proposal](submit-proposal.md) | 创建新密钥,或者通过助记词导入恢复 | +| [deposit](deposit.md) | 充值保证金代币以激活提议 | +| [vote](vote.md) | 为有效的提议投票,选项:Yes/No/NoWithVeto/Abstain | + +## 补充描述 + +1.任何用户都可以存入一些令牌来发起提案。存款达到一定值min_deposit后,进入投票期,否则将保留存款期。其他人可以在存款期内存入提案。一旦存款总额达到min_deposit,输入投票期。但是,如果冻结时间超过存款期间的max_deposit_period,则提案将被关闭。 +2.进入投票期的提案只能由验证人和委托人投票。未投票的代理人的投票将与其验证人的投票相同,并且投票的代理人的投票将保留。到达“voting_period”时,票数将被计算在内。 +3.关于投票建议的更多细节:[CosmosSDK-Gov-spec](https://github.com/cosmos/cosmos-sdk/blob/develop/docs/spec/governance/overview.md) diff --git a/docs/zh/cli-client/gov/deposit.md b/docs/zh/cli-client/gov/deposit.md new file mode 100644 index 000000000..9799ca73a --- /dev/null +++ b/docs/zh/cli-client/gov/deposit.md @@ -0,0 +1,54 @@ +# iriscli gov deposit + +## 描述 + +充值保证金以激活提议 + +## 使用方式 + +``` +iriscli gov deposit [flags] +``` + +打印帮助信息: + +``` +iriscli gov deposit --help +``` +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| ---------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --deposit | | [string] 发起提议的保证金 | Yes | +| --proposal-id | | [string] 充值保证金的提议ID | Yes | + +## 例子 + +### 充值保证金 + +```shell +iriscli gov deposit --chain-id=test --proposal-id=1 --deposit=50iris --from=node0 --fee=0.01iris +``` + +输入正确的密码后,你就充值了50个iris用以激活提议的投票状态。 + +```txt +Password to sign with 'node0': +Committed at block 473 (tx hash: 0309E969589F19A9D9E4BFC9479720487FBF929ED6A88824414C5E7E91709206, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:6710 Tags:[{Key:[97 99 116 105 111 110] Value:[100 101 112 111 115 105 116] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[100 101 112 111 115 105 116 101 114] Value:[102 97 97 49 52 113 53 114 102 57 115 108 50 100 113 100 50 117 120 114 120 121 107 97 102 120 113 51 110 117 51 108 106 50 102 112 57 108 55 112 103 100] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[112 114 111 112 111 115 97 108 45 105 100] Value:[49] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 51 51 53 53 48 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "deposit", + "completeConsumedTxFee-iris-atto": "\"335500000000000\"", + "depositor": "faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd", + "proposal-id": "1" + } + } +``` + +如何查询保证金充值明细? + +请点击下述链接: + +[query-deposit](query-deposit.md) + +[query-deposits](query-deposits.md) diff --git a/docs/zh/cli-client/gov/pull-params.md b/docs/zh/cli-client/gov/pull-params.md new file mode 100644 index 000000000..ce7189ca0 --- /dev/null +++ b/docs/zh/cli-client/gov/pull-params.md @@ -0,0 +1,84 @@ +# iriscli gov pull-params + +## 描述 + +生成param.json文件 + +## 使用方式 + +``` +iriscli gov pull-params [flags] +``` +打印帮助信息: + +``` +iriscli gov pull-params --help +``` +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --path | $HOME/.iris | [string] iris home目录 + +## 例子 + +### 生成参数文件 + +```shell +iriscli gov pull-params +``` + +执行该指令,你会收到如下提示信息: + +```txt +Save the parameter config file in /Users/trevorfu/.iris/config/params.json +``` + +打开--path/config目录下的params.json文件,你可以看到json格式的文件内容。 + +```txt +{ + "gov": { + "Gov/govDepositProcedure": { + "min_deposit": [ + { + "denom": "iris-atto", + "amount": "1000000000000000000000" + } + ], + "max_deposit_period": "172800000000000" + }, + "Gov/govVotingProcedure": { +: "gov": { + "Gov/govDepositProcedure": { + "min_deposit": [ + { + "denom": "iris-atto", + "amount": "1000000000000000000000" + } + ], + "max_deposit_period": "172800000000000" + }, + "Gov/govVotingProcedure": { + "voting_period": "172800000000000" +: "gov": { + "Gov/govDepositProcedure": { + "min_deposit": [ + { + "denom": "iris-atto", + "amount": "1000000000000000000000" + } + ], + "max_deposit_period": "172800000000000" + }, + "Gov/govVotingProcedure": { + "voting_period": "172800000000000" + }, + "Gov/govTallyingProcedure": { + "threshold": "0.5000000000", + "veto": "0.3340000000", + "participation": "0.6670000000" + } + } +} +``` diff --git a/docs/zh/cli-client/gov/query-deposit.md b/docs/zh/cli-client/gov/query-deposit.md new file mode 100644 index 000000000..51437efab --- /dev/null +++ b/docs/zh/cli-client/gov/query-deposit.md @@ -0,0 +1,45 @@ +# iriscli gov query-deposit + +## 描述 + +查询保证金的充值明细 + +## 使用方式 + +``` +iriscli gov query-deposit [flags] +``` +打印帮助信息: + +``` +iriscli gov query-deposit --help +``` +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --depositor | | [string] bech32编码的存款人地址 | Yes | +| --proposal-id | | [string] 提议ID | Yes | + +## 例子 + +### 查询充值保证金 + +```shell +iriscli gov query-deposit --chain-id=test --proposal-id=1 --depositor=faa1c4kjt586r3t353ek9jtzwxum9x9fcgwetyca07 +``` + +通过指定提议、指定存款人查询保证金充值详情,得到结果如下: + +```txt +{ + "depositor": "faa1c4kjt586r3t353ek9jtzwxum9x9fcgwetyca07", + "proposal_id": "1", + "amount": [ + { + "denom": "iris-atto", + "amount": "30000000000000000000" + } + ] +} +``` diff --git a/docs/zh/cli-client/gov/query-deposits.md b/docs/zh/cli-client/gov/query-deposits.md new file mode 100644 index 000000000..ef0da3e43 --- /dev/null +++ b/docs/zh/cli-client/gov/query-deposits.md @@ -0,0 +1,46 @@ +# iriscli gov query-deposits + +## 描述 + +查询指定提议的保证金详细情况 + +## 使用方式 + +``` +iriscli gov query-deposits [flags] +``` +打印帮助信息: + +``` +iriscli gov query-deposits --help +``` +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --proposal-id | | [string] 提议ID | Yes | + +## 例子 + +### 查询所有保证金 + +```shell +iriscli gov query-deposits --chain-id=test --proposal-id=1 +``` + +你可以查询到指定提议的所有保证金代币,包括每个存款人的充值详情。 + +```txt +[ + { + "depositor": "faa1c4kjt586r3t353ek9jtzwxum9x9fcgwetyca07", + "proposal_id": "1", + "amount": [ + { + "denom": "iris-atto", + "amount": "35000000000000000000" + } + ] + } +] +``` diff --git a/docs/zh/cli-client/gov/query-params.md b/docs/zh/cli-client/gov/query-params.md new file mode 100644 index 000000000..1bffbcbe3 --- /dev/null +++ b/docs/zh/cli-client/gov/query-params.md @@ -0,0 +1,54 @@ +# iriscli gov query-params + +## 描述 + +查询参数型(ParameterChange)提议的配置 + +## 使用方式 + +``` +iriscli gov query-params [flags] +``` +打印帮助信息: + +``` +iriscli gov query-params --help +``` +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --key | | [string] 参数的键名称 | | +| --module | | [string] 模块名称 | | + +## 例子 + +### 通过module查参数 + +```shell +iriscli gov query-params --module=gov +``` + +可以检索得到gov模块的所有键值。 + +```txt +[ + "Gov/govDepositProcedure", + "Gov/govTallyingProcedure", + "Gov/govVotingProcedure" +] +``` + +### 通过key查参数 + +```shell +iriscli gov query-params --key=Gov/govDepositProcedure +``` + +可以得到gov模块中指定键值的参数详情。 + +```txt +{"key":"Gov/govDepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"1000000000000000000000\"}],\"max_deposit_period\":172800000000000}","op":""} +``` + +注意:--module和--key参数不能同时为空. diff --git a/docs/zh/cli-client/gov/query-proposal.md b/docs/zh/cli-client/gov/query-proposal.md new file mode 100644 index 000000000..a332a4b73 --- /dev/null +++ b/docs/zh/cli-client/gov/query-proposal.md @@ -0,0 +1,62 @@ +# iriscli gov query-proposal + +## 描述 + +查询单个提议的详情 + +## 使用方式 + +``` +iriscli gov query-proposal [flags] +``` +打印帮助信息: + +``` +iriscli gov query-proposal --help +``` + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --proposal-id | | [string] 提议ID | Yes | +## 例子 + +### 查询指定的提议 + +```shell +iriscli gov query-proposal --chain-id=test --proposal-id=1 +``` + +查询指定提议的详情,可以得到结果如下: + +```txt +{ + "proposal_id": "1", + "title": "test proposal", + "description": "a new text proposal", + "proposal_type": "Text", + "proposal_status": "DepositPeriod", + "tally_result": { + "yes": "0.0000000000", + "abstain": "0.0000000000", + "no": "0.0000000000", + "no_with_veto": "0.0000000000" + }, + "submit_time": "2018-11-14T09:10:19.365363Z", + "deposit_end_time": "2018-11-16T09:10:19.365363Z", + "total_deposit": [ + { + "denom": "iris-atto", + "amount": "49000000000000000050" + } + ], + "voting_start_time": "0001-01-01T00:00:00Z", + "voting_end_time": "0001-01-01T00:00:00Z", + "param": { + "key": "", + "value": "", + "op": "" + } +} +``` diff --git a/docs/zh/cli-client/gov/query-proposals.md b/docs/zh/cli-client/gov/query-proposals.md new file mode 100644 index 000000000..2d1a25b0c --- /dev/null +++ b/docs/zh/cli-client/gov/query-proposals.md @@ -0,0 +1,50 @@ +# iriscli gov query-proposals + +## 描述 + +通过可选项过滤查询满足条件的提议 + +## 使用方式 + +``` +iriscli gov query-proposals [flags] +``` +打印帮助信息: + +``` +iriscli gov query-proposals --help +``` +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --depositor | | [string] (可选)按存款人过滤 | | +| --limit | | [string] (可选)限制最新[数量]提议。 默认为所有提议 | | +| --status | | [string] (可选)按提议状态过滤提议 | | +| --voter | | [string] (可选)按投票人过滤 | | + +## 例子 + +### 查询提议 + +```shell +iriscli gov query-proposals --chain-id=test +``` + +默认查询所有的提议。 + +```txt + 1 - test proposal + 2 - new proposal +``` + +当然这里可以查询指定条件的提议。 + +```shell +gov query-proposals --chain-id=test --depositor=faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd +``` + +可以得到存款人是faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd地址的提议。 +```txt + 2 - new proposal +``` diff --git a/docs/zh/cli-client/gov/query-tally.md b/docs/zh/cli-client/gov/query-tally.md new file mode 100644 index 000000000..66a083a3b --- /dev/null +++ b/docs/zh/cli-client/gov/query-tally.md @@ -0,0 +1,41 @@ +# iriscli gov query-tally + +## 描述 + +查询指定提议的投票统计 + +## 使用方式 + +``` +iriscli gov query-tally [flags] +``` + +打印帮助信息: + +``` +iriscli gov query-tally --help +``` + +## 标志 +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --proposal-id | | [string] 提议ID | Yes | + +## 例子 + +### 查询投票统计 + +```shell +iriscli gov query-tally --chain-id=test --proposal-id=1 +``` + +可以查询指定提议每个投票选项的投票统计。 + +```txt +{ + "yes": "100.0000000000", + "abstain": "0.0000000000", + "no": "200.0000000000", + "no_with_veto": "0.0000000000" +} +``` diff --git a/docs/zh/cli-client/gov/query-vote.md b/docs/zh/cli-client/gov/query-vote.md new file mode 100644 index 000000000..b9e93a51c --- /dev/null +++ b/docs/zh/cli-client/gov/query-vote.md @@ -0,0 +1,40 @@ +# iriscli gov query-vote + +## 描述 + +查询指定提议、指定投票者的投票情况 + +## 使用方式 + +``` +iriscli gov query-vote [flags] +``` +打印帮助信息: + +``` +iriscli gov query-vote --help +``` +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --proposal-id | | [string] 提议ID | Yes | +| --voter | | [string] bech32编码的投票人地址 | Yes | + +## 例子 + +### 查询投票 + +```shell +iriscli gov query-vote --chain-id=test --proposal-id=1 --voter=faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd +``` + +通过指定提议、指定投票者查询投票情况。 + +```txt +{ + "voter": "faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd", + "proposal_id": "1", + "option": "Yes" +} +``` diff --git a/docs/zh/cli-client/gov/query-votes.md b/docs/zh/cli-client/gov/query-votes.md new file mode 100644 index 000000000..97bae4270 --- /dev/null +++ b/docs/zh/cli-client/gov/query-votes.md @@ -0,0 +1,42 @@ +# iriscli gov query-votes + +## 描述 + +查询指定提议的投票情况 + +## 使用方式 + +``` +iriscli gov query-votes [flags] +``` +打印帮助信息: + +``` +iriscli gov query-votes --help +``` + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --proposal-id | | [string] 提议ID | Yes | + +## 例子 + +### Query votes + +```shell +iriscli gov query-votes --chain-id=test --proposal-id=1 +``` + +通过指定的提议查询该提议所有投票者的投票详情。 + +```txt +[ + { + "voter": "faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd", + "proposal_id": "1", + "option": "Yes" + } +] +``` diff --git a/docs/zh/cli-client/gov/submit-proposal.md b/docs/zh/cli-client/gov/submit-proposal.md new file mode 100644 index 000000000..e05630d84 --- /dev/null +++ b/docs/zh/cli-client/gov/submit-proposal.md @@ -0,0 +1,79 @@ +# iriscli gov submit-proposal + +## 描述 + +提交区块链治理提议以及发起提议所涉及的初始保证金,其中提议的类型包括Text/ParameterChange/SoftwareUpgrade这三种类型。 + +## 使用方式 + +``` +iriscli gov submit-proposal [flags] +``` +打印帮助信息: + +``` +iriscli gov submit-proposal --help +``` +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| ---------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --deposit | | [string] 提议的保证金 | | +| --description | | [string] 提议的描述 | Yes | +| --key | | 参数的键名称 | | +| --op | | [string] 对参数的操作 | | +| --param | | [string] 提议参数,例如: [{key:key,value:value,op:update}] | | +| --path | | [string] param.json文件路径 | | +| --title | | [string] 提议标题 | Yes | +| --type | | [string] 提议类型,例如:Text/ParameterChange/SoftwareUpgrade | Yes | + +## 例子 + +### 提交一个'Text'类型的提议 + +```shell +iriscli gov submit-proposal --chain-id=test --title="notice proposal" --type=Text --description="a new text proposal" --from=node0 --fee=0.01iris +``` + +输入正确的密码之后,你就完成提交了一个提议,需要注意的是要记下你的提议ID,这是可以检索你的提议的唯一要素。 + +```txt +Password to sign with 'node0': +Committed at block 44 (tx hash: 2C28A87A6262CACEDDB4EBBC60FE989D0DB2B7DEB1EC6795D2F4707DA32C7CBF, response: {Code:0 Data:[49] Log:Msg 0: Info: GasWanted:200000 GasUsed:8091 Tags:[{Key:[97 99 116 105 111 110] Value:[115 117 98 109 105 116 45 112 114 111 112 111 115 97 108] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[112 114 111 112 111 115 101 114] Value:[102 97 97 49 115 108 116 106 120 100 103 107 48 48 115 56 54 50 57 50 122 48 99 110 55 97 53 100 106 99 99 116 54 101 115 115 110 97 118 100 121 122] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[112 114 111 112 111 115 97 108 45 105 100] Value:[49] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[112 97 114 97 109] Value:[] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 52 48 52 53 53 48 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "submit-proposal", + "completeConsumedTxFee-iris-atto": "\"4045500000000000\"", + "param": "", + "proposal-id": "1", + "proposer": "faa1sltjxdgk00s86292z0cn7a5djcct6essnavdyz" + } + } +``` + +### 提交一个'ParameterChange'类型的提议 + +```shell +iriscli gov submit-proposal --chain-id=test --title="update MinDeposit proposal" --param='{"key":"Gov/gov/DepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":20}","op":"update"}' --type=ParameterChange --description="a new parameter change proposal" --from=node0 --fee=0.01iris +``` + +提交之后,您完成了提交新的“ParameterChange”提议。 +更改参数的详细信息(通过查询参数获取参数,修改它,然后在“操作”上添加“更新”,使用方案中的更多详细信息)和其他类型的提议字段与文本提议类似。 +注意:在这个例子中, --path 和 --param 不能同时为空。 + +### 提交一个'SoftwareUpgrade'类型的提议 + +```shell +iriscli gov submit-proposal --chain-id=test --title="irishub0.7.0 upgrade proposal" --type=SoftwareUpgrade --description="a new software upgrade proposal" --from=node0 --fee=0.01iris +``` + +在这种场景下,提议的 --title、--type 和--description参数必不可少,另外你也应该保留好提议ID,这是检索所提交提议的唯一方法。 + + +如何查询提议详情? + +请点击下述链接: + +[query-proposal](query-proposal.md) + +[query-proposals](query-proposals.md) diff --git a/docs/zh/cli-client/gov/vote.md b/docs/zh/cli-client/gov/vote.md new file mode 100644 index 000000000..47d0162eb --- /dev/null +++ b/docs/zh/cli-client/gov/vote.md @@ -0,0 +1,57 @@ +# iriscli gov vote + +## 描述 + +给VotingPeriod状态的提议投票, 可选项包括: Yes/No/NoWithVeto/Abstain + +## 使用方式 + +``` +iriscli gov vote [flags] +``` + +打印帮助信息: + +``` +iriscli gov vote --help +``` +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| ---------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| --option | | [string] 投票选项 {Yes, No, NoWithVeto, Abstain} | Yes | +| --proposal-id | | [string] 投票的提议ID | Yes | + +## 例子 + +### 给提议投票 + +```shell +iriscli gov vote --chain-id=test --proposal-id=1 --option=Yes --from node0 --fee=0.01iris +``` + +输入正确的密码之后,你就完成了对于所指定的提议投票。 +注意:验证人和委托人才能对指定提议投票,并且可投票的提议必须是'VotingPeriod'状态。 + +```txt +Vote[Voter:faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd,ProposalID:1,Option:Yes]Password to sign with 'node0': +Committed at block 989 (tx hash: ABDD88AA3CA8F365AC499427477CCE83ADF09D7FC2D62643D0217107E489A483, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:2408 Tags:[{Key:[97 99 116 105 111 110] Value:[118 111 116 101] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[118 111 116 101 114] Value:[102 97 97 49 52 113 53 114 102 57 115 108 50 100 113 100 50 117 120 114 120 121 107 97 102 120 113 51 110 117 51 108 106 50 102 112 57 108 55 112 103 100] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[112 114 111 112 111 115 97 108 45 105 100] Value:[49] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 49 50 48 52 48 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "vote", + "completeConsumedTxFee-iris-atto": "\"120400000000000\"", + "proposal-id": "1", + "voter": "faa14q5rf9sl2dqd2uxrxykafxq3nu3lj2fp9l7pgd" + } + } +``` + +如何查询投票详情? + +请点击下述链接: + +[query-vote](query-vote.md) + +[query-votes](query-votes.md) + +[query-tally](query-tally.md) diff --git a/docs/zh/cli-client/keys/README.md b/docs/zh/cli-client/keys/README.md new file mode 100644 index 000000000..b3429a3ec --- /dev/null +++ b/docs/zh/cli-client/keys/README.md @@ -0,0 +1,42 @@ +# iriscli keys + +## 描述 + +Keys模块用于管理本地密钥库。 + +## 使用方式 + +```shell +iriscli keys [command] +``` + +## 相关命令 + +| 命令 | 描述 | +| ----------------------- | -------------------------------------------------------------------------------------------- | +| [mnemonic](mnemonic.md) | 通过读取系统熵来创建bip39助记词,也可以称为种子短语。 | +| [new](new.md) | 使用交互式命令派生新的私钥,该命令将提示你每个输入。 | +| [add](add.md) | 创建新密钥,或从助记词导入已有密钥 | +| [list](list.md) | 列出所有密钥 | +| [show](show.md) | 显示指定名称的关键信息 | +| [delete](delete.md) | 删除指定的密钥 | +| [update](update.md) | 更改用于保护私钥的密码 | + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | ------- | ------------- | -------- | +| --help, -h | | help for keys | | + +## 全局标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | -------------- | -------------------------------------- | -------- | +| --encoding, -e | hex | [string] Binary encoding (hex|b64|btc) | | +| --home | $HOME/.iriscli | [string] directory for config and data | | +| --output, -o | text | [string] Output format (text|json) | | +| --trace | | print out full stack trace on errors | | + +## 补充说明 + +这些密钥可以是go-crypto支持的任何格式,并且可以由轻客户端,完整节点或需要使用私钥签名的任何其他应用程序使用。 diff --git a/docs/zh/cli-client/keys/add.md b/docs/zh/cli-client/keys/add.md new file mode 100644 index 000000000..654798a70 --- /dev/null +++ b/docs/zh/cli-client/keys/add.md @@ -0,0 +1,69 @@ +# iriscli keys add + +## 描述 + +创建一个新密钥,或通过助记词导入已有密钥 + +## 使用方式 + +``` +iriscli keys add <name> [flags] +``` + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | --------- | ----------------------------------------------------------------- | -------- | +| --account | | [uint32] HD推导的账号 | | +| --dry-run | | 忽略--gas标志并进行本地的交易仿真 | | +| --help, -h | | 查询命令帮助 | | +| --index | | [uint32] HD推导的索引号 | | +| --ledger | | 使用连接的硬件记账设备 | | +| --no-backup | | 不输出助记词(如果其他人正在看着操作终端) | | +| --recover | | 提供助记词以恢复现有密钥而不是新建 | | +| --type, -t | secp256k1 | [string] 私钥类型 (secp256k\|ed25519) | | + +## 例子 + +### 创建密钥 + +```shell +iriscli keys add MyKey +``` + +执行命令后,系统会要求你输入密钥密码,注意:密码必须至少为8个字符。 + +```txt +Enter a passphrase for your key: +Repeat the passphrase: +``` + +之后,你已经完成了创建新密钥的工作,但请记住备份你的助记词短语,如果你不慎忘记密码或丢失了密钥,这是唯一能恢复帐户的方法。 + +```txt +NAME: TYPE: ADDRESS: PUBKEY: +MyKey local faa1mmsm487rqkgktl2qgrjad0z3yaf9n8t5pkp33m fap1addwnpepq2g0u7cnxp5ew0yhqep8j4rth5ugq8ky7gjmunk8tkpze95ss23ak4svkjq +**Important** write this seed phrase in a safe place. +It is the only way to recover your account if you ever forget your password. + +oval green shrug term already arena pilot spirit jump gain useful symbol hover grid item concert kiss zero bleak farm capable peanut snack basket +``` + +上面24个单词只是助记词的示例,**不要**在生产环境中使用。 + +### 通过助记词恢复密钥 + +如果你忘记了密码或丢失了密钥,或者你想在其他地方使用密钥,则可以通过助记词短语来恢复。 + +```txt +iriscli keys add MyKey --recover +``` + +系统会要求你输入并确认密钥的新密码,然后输入助记词。这样就能恢复你的密钥。 + +```txt +Enter a passphrase for your key: +Repeat the passphrase: +Enter your recovery seed phrase: +``` + diff --git a/docs/zh/cli-client/keys/delete.md b/docs/zh/cli-client/keys/delete.md new file mode 100644 index 000000000..fa74acd64 --- /dev/null +++ b/docs/zh/cli-client/keys/delete.md @@ -0,0 +1,37 @@ +# iriscli keys delete + +## 描述 + +删除指定的密钥 + +## 使用方式 + +``` +iriscli keys delete <name> [flags] +``` + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | --------- | ------------------------------------------------------------ | -------- | +| --help, -h | | 查询命令帮助 | | + +## 例子 + +### 删除指定的密钥 + +```shell +iriscli keys delete MyKey +``` + +执行命令后,你会收到一个危险警告,并且要求你输入密码用于执行删除指令。 + +```txt +DANGER - enter password to permanently delete key: +``` + +输入正确的密码之后,你就完成了删除操作。 + +```txt +Password deleted forever (uh oh!) +``` \ No newline at end of file diff --git a/docs/zh/cli-client/keys/list.md b/docs/zh/cli-client/keys/list.md new file mode 100644 index 000000000..ed0e1b3f3 --- /dev/null +++ b/docs/zh/cli-client/keys/list.md @@ -0,0 +1,35 @@ +# iriscli keys list + +## 描述 + +返回此密钥管理器存储的所有公钥的列表以及他们的相关名称和地址。 + +## 使用方式 + +``` +iriscli keys list [flags] +``` + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | --------- | ------------------------------------------------------------ | -------- | +| --help, -h | | 查询命令帮助 | | + +## 例子 + +### 列出所有的密钥 + +```shell +iriscli keys list +``` + +执行命令后,你会得到所有存于本地客户端存储的密钥,包括它们的地址和公钥信息。 + +```txt +NAME: TYPE: ADDRESS: PUBKEY: +abc local faa1va2eu9qhwn5fx58kvl87x05ee4qrgh44yd8teh fap1addwnpepq02r0hts0yjhp4rsal627s2lqk4agy2g6tek5g9yq2tfrmkkehee2td75cs +test local faa1kkm4w5pvmcw0e3vjcxqtfxwqpm3k0zakl7lxn5 fap1addwnpepq0gsl90v9dgac3r9hzgz53ul5ml5ynq89ax9x8qs5jgv5z5vyssskww57lw +``` + +需要注意的是,如果本地有多个.iriscli存储,需要通过--home 参数来定位查询源。 \ No newline at end of file diff --git a/docs/zh/cli-client/keys/mnemonic.md b/docs/zh/cli-client/keys/mnemonic.md new file mode 100644 index 000000000..8b6fc19a6 --- /dev/null +++ b/docs/zh/cli-client/keys/mnemonic.md @@ -0,0 +1,32 @@ +# iriscli keys mnemonic + +## 描述 + +通过读取系统熵来创建24个单词组成的bip39助记词,有时称为种子短语。如果需要传递自定义的熵,请使用--unsafe-entropy参数。 + +## 使用方式 + +``` +iriscli keys mnemonic <name> [flags] +``` + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| ---------------- | --------- | ----------------------------------------------------------------------------- | -------- | +| --help, -h | | 查询命令帮助 | | +| --unsafe-entropy | | 提示用户提供自己的熵,而不是依赖于系统生成 | | + +## 例子 + +### 创建指定密钥的助记词 + +```shell +iriscli keys mnemonic MyKey +``` + +执行命令就可以得到24个单词组成的助记词。为了安全考虑,请注意保存,比如将单词手抄纸并将纸张妥善保存。 + +```txt +police possible oval milk network indicate usual blossom spring wasp taste canal announce purpose rib mind river pet brown web response sting remain airport +``` \ No newline at end of file diff --git a/docs/zh/cli-client/keys/new.md b/docs/zh/cli-client/keys/new.md new file mode 100644 index 000000000..66f53bc71 --- /dev/null +++ b/docs/zh/cli-client/keys/new.md @@ -0,0 +1,59 @@ +# iriscli keys new + +## 描述 + +使用交互式命令派生新的私钥,该命令将提示您输入每个输入。可选择指定bip39助记符,bip39密码短语以进一步保护助记符,和bip32 HD路径,以获得特定帐户。密钥将以给定名称存储并使用给定的密码加密。这里唯一需要的输入是加密密码。 + +## 使用方式 + +``` +iriscli keys new <name> [flags] +``` + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | ----------------- | --------------------------------------------------------------- | -------- | +| --bip44-path | 44'/118'/0'/0/0 | 从中导出私钥的BIP44路径 | | +| --default | | 跳过提示,只使用默认值 | | +| --help, -h | | 查询命令帮助 | | +| --ledger | | 使用连接的硬件记账设备 | | + +## 例子 + +### Create a new key by the specified method + +```shell +iriscli keys new MyKey +``` + +执行命令后,系统提示你输入 bip44 路径, 直接回车的默认值是 44'/118'/0'/0/0. + +```txt +> ------------------------------------- +> Enter your bip44 path. Default is 44'/118'/0'/0/0 +``` + +然后你会被要求输入你的bip39助记词,或者直接敲回车键生成一个。注意保存好助记词。 + +```txt +> Enter your bip39 mnemonic, or hit enter to generate one. +``` + +直接按回车键生成bip39助记符,会显示一个新提示,要求您输入bip39密码。 + +```txt +> ------------------------------------- +> Enter your bip39 passphrase. This is combined with the mnemonic to derive the seed +> Most users should just hit enter to use the default, "" +``` + +你也可以直接回车键跳过,然后你会收到一个输入并确认密码的提示: + +```txt +> ------------------------------------- +> Enter a passphrase to encrypt your key to disk: +> Repeat the passphrase: +``` + +设置密码完成这些步骤,你就创建了一个自定义的密钥。 \ No newline at end of file diff --git a/docs/zh/cli-client/keys/show.md b/docs/zh/cli-client/keys/show.md new file mode 100644 index 000000000..a7c6e1e84 --- /dev/null +++ b/docs/zh/cli-client/keys/show.md @@ -0,0 +1,36 @@ +# iriscli keys show + +## 描述 + +查询本地密钥的详细信息 + +## 使用方式 + +``` +iriscli keys show <name> [flags] +``` + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| -------------------- | ----------------- | -------------------------------------------------------------- | -------- | +| --address | | 仅输出地址 | | +| --bech | acc | [string] 密钥的Bech32前缀编码 (acc|val|cons) | | +| --help, -h | | 查询命令帮助 | | +| --multisig-threshold | 1 | [uint] K out of N required signatures | | +| --pubkey | | 仅输出公钥 | | + +## 例子 + +### 查询指定密钥 + +```shell +iriscli keys show MyKey +``` + +执行命令后,你会得到本地客户端存储的指定密钥详情。 + +```txt +NAME: TYPE: ADDRESS: PUBKEY: +MyKey local faa1kkm4w5pvmcw0e3vjcxqtfxwqpm3k0zakl7lxn5 fap1addwnpepq0gsl90v9dgac3r9hzgz53ul5ml5ynq89ax9x8qs5jgv5z5vyssskww57lw +``` \ No newline at end of file diff --git a/docs/zh/cli-client/keys/update.md b/docs/zh/cli-client/keys/update.md new file mode 100644 index 000000000..eec10a472 --- /dev/null +++ b/docs/zh/cli-client/keys/update.md @@ -0,0 +1,44 @@ +# iriscli keys update + +## 描述 + +更改用于保护私钥的密码 + +## 使用方式 + +``` +iriscli keys update <name> [flags] +``` + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 是否必须 | +| --------------- | --------- | ------------------------------------------------------------ | -------- | +| --help, -h | | 查询命令帮助 | | + +## 例子 + +### 修改密码 + +```shell +iriscli keys update MyKey +``` + +执行命令后,系统会要求你输入指定密钥的当前密码。 + +```txt +Enter the current passphrase: +``` + +然后系统会要求你输入新密码并重复输入确认密码。 + +```txt +Enter the new passphrase: +Repeat the new passphrase: +``` + +如果你输入新密码符合要求,则会执行更新操作。 + +```txt +Password successfully updated! +``` \ No newline at end of file diff --git a/docs/zh/cli-client/lcd/README.md b/docs/zh/cli-client/lcd/README.md new file mode 100644 index 000000000..493ea54e8 --- /dev/null +++ b/docs/zh/cli-client/lcd/README.md @@ -0,0 +1,36 @@ +# 介绍 + +IRISLCD节点是一个提供REST APIs接口的服务器,它可以连接到任何IRISHUB的全节点。通过这些REST APIs,用户可以发送交易和查询区块链数据。对于从链上返回的数据,IRISLCD可以独立验证数据的有效性。因此,它可以提供与全节点相同的安全性,同时对带宽,计算和存储资源的要求最低。此外,它还提供了swagger-ui,它详细描述了它提供的API以及如何使用它们。 + +## IRISLCD的用法 + +IRISLCD有两个子命令: + +| 子命令 | 功能 | 示例命令 | +| --------------- | --------------------------- | --------------- | +| version | 打印版本信息 | irislcd version | +| start | 启动一个IRISLCD节点 | irislcd start --chain-id=<chain-id> | + +`start`子命令有如下参数可配置 + +| 参数名称 | 类型 | 默认值 | 是否必填 | 功能描述 | +| --------------- | --------- | ----------------------- | -------- | ---------------------------------------------------- | +| chain-id | string | null | true | Tendermint节点的chain ID | +| home | string | "$HOME/.irislcd" | false | 配置home目录,key和proof相关的信息都存于此 | +| node | string | "tcp://localhost:26657" | false | 全节点的rpc地址 | +| laddr | string | "tcp://localhost:1317" | false | 侦听的地址和端口 | +| trust-node | bool | false | false | 是否信任全节点 | +| max-open | int | 1000 | false | 最大连接数 | +| cors | string | "" | false | 允许跨域访问的地址 | + +## 示例命令 + +1. 如果所连接的全节点是可信的,那么可以使能信任模式;如果不可行,那么要关闭信任模式。默认是非信任模式,打开信任模式的方法是加上`--trust-node`: +```bash +irislcd start --chain-id=<chain-id> --trust-node +``` + +2. 如果需要在其他机器上访问此IRISLCD节点,还需要配置`--laddr`参数,例如: +```bash +irislcd start --chain-id=<chain-id> --laddr=tcp://0.0.0.0:1317 +``` \ No newline at end of file diff --git a/docs/zh/cli-client/record/README.md b/docs/zh/cli-client/record/README.md new file mode 100644 index 000000000..920233f89 --- /dev/null +++ b/docs/zh/cli-client/record/README.md @@ -0,0 +1,32 @@ +# iriscli record + +## 描述 + +存证模块允许你来提交,查询和下载链上存证。 + +## 用法 + +```shell +iriscli record [command] +``` + +## 存证模块的介绍 + +1. 任何用户可以发起存证请求,存证过程会花费用户一部分token,如果该数据的存证之前在链上并不存在,则该请求可以成功完成,并且链上会记录相关元数据,并返还给用户一个存证ID以确认该用户对这份数据的所有权。 +2. 其他人若对完全相同的数据发起存证请求,则该请求会被直接否决,并提示相关存证数据已经存在。 +3. 任何用户都可以根据存证ID在链上进行检索/下载操作。 +4. 目前每次存证数据最大不超过1K,未来将结合治理模块实现参数的动态调整。 + +## 相关命令 + +| 命令 | 描述 | +| ------------------------| -------------------------------------------------- | +| [query](query.md) | 查询特定的存证 | +| [download](download.md) | 根据record ID下载相关存证到指定的文件 | +| [submit](submit.md) | 提交一个新的存证 | + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 必需 | +| --------------- | ------- | --------------- | -------- | +| --help, -h | | 存证命令帮助 | | diff --git a/docs/zh/cli-client/record/download.md b/docs/zh/cli-client/record/download.md new file mode 100644 index 000000000..f66acd8f4 --- /dev/null +++ b/docs/zh/cli-client/record/download.md @@ -0,0 +1,40 @@ +# iriscli record download + +## 描述 + +下载存证ID指定的存证 + +## 用法 + +``` +iriscli record download [record ID] [flags] +``` + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 必需 | +| --------------- | -------------------------- | --------------------------------------------------------- | -------- | +| --chain-id | | [string] tendermint节点的链ID | 是 | +| --file-name | | [string] 下载文件名 | 是 | +| --height | 最近可证明区块高度 | [int] 查询的区块高度 | | +| --help, -h | | 下载命令帮助 | | +| --indent | | 在JSON响应中添加缩进 | | +| --ledger | | 使用连接的硬件记账设备 | | +| --node | tcp://localhost:26657 | [string] tendermint节点开启的远程过程调用接口\<主机>:\<端口> | | +| --record-id | | [string] 存证ID | 是 | +| --trust-node | true | 关闭响应结果校验 | | + +## 例子 + +### 下载存证 + +```shell +iriscli record download --chain-id=test --record-id=MyRecordID --file-name="download.txt" +``` + +iriscli会先在home目录(default: ~/.irislci)中创建一个用户指定的文件(download.txt),然后把从链上下载的数据保存在此文件中。 + +```txt +[ONCHAIN] Downloading ~/.iriscli/download.txt from blockchain directly... +[ONCHAIN] Download file from blockchain complete. +``` diff --git a/docs/zh/cli-client/record/query.md b/docs/zh/cli-client/record/query.md new file mode 100644 index 000000000..3ccd4ebed --- /dev/null +++ b/docs/zh/cli-client/record/query.md @@ -0,0 +1,46 @@ +# iriscli record query + +## 描述 + +查询存证信息 + +## 用法 + +``` +iriscli record query [flags] +``` + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 必需 | +| --------------- | -------------------------- | ---------------------------------------------------------- | -------- | +| --chain-id | | [string] tendermint节点的链ID | 是 | +| --height | 最近可证明区块高度 | [int] 查询的区块高度 | | +| --help, -h | | 查询命令帮助 | | +| --indent | | 在JSON格式的应答中添加缩进 | | +| --ledger | | 使用连接的硬件记账设备 | | +| --node | tcp://localhost:26657 | [string] tendermint节点开启的远程过程调用接口\<主机>:\<端口> | | +| --record-id | | [string] 存证ID | 是 | +| --trust-node | true | 关闭响应结果校验 | | + +## 例子 + +### 查询存证 + +```shell +iriscli record query --chain-id=test --record-id=MyRecordID +``` + +查询到的结果如下所示: + +```json +{ + "submit_time": "2018-11-13 15:31:36", + "owner_addr": "faa122uzzpugtrzs09nf3uh8xfjaza59xvf9rvthdl", + "record_id": "record:ab5602bac13f11737e8798dd57869c468194efad2db37625795f1efd8d9d63c6", + "description": "description", + "data_hash": "ab5602bac13f11737e8798dd57869c468194efad2db37625795f1efd8d9d63c6", + "data_size": "24", + "data": "this is my on chain data" +} +``` diff --git a/docs/zh/cli-client/record/submit.md b/docs/zh/cli-client/record/submit.md new file mode 100644 index 000000000..bd746daea --- /dev/null +++ b/docs/zh/cli-client/record/submit.md @@ -0,0 +1,68 @@ +# iriscli record submit + +## 描述 + +向链上提交一个存证 + +## 用法 + +``` +iriscli record submit [flags] +``` + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 必需 | +| --------------- | -------------------------- | ---------------------------------------------------------------------------------- | -------- | +| --account-number | | [int] 用来签名交易的AccountNumber | | +| --async | | 异步广播交易 | | +| --chain-id | | [string] tendermint节点的链ID | 是 | +| --description | description | [string] 上传文件的描述信息 | | +| --dry-run | | 忽略--gas标志并进行本地的交易仿真 | | +| --fee | | [string] 支付的交易费用 | 是 | +| --from | | [string] 用来签名的私钥名 | 是 | +| --from-addr | | [string] 指定generate-only模式下的from address | | +| --gas string | 200000 | 单次交易的gas上限; 设置为"simulate"将自动计算相应的阈值 | | +| --gas-adjustment | 1 | [float] 这个调整因子将乘以交易仿真返回的估计值; 如果手动设置了gas的上限,这个标志将被忽略 | | +| --generate-only | | 构建一个未签名交易并将其打印到标准输出 | | +| -h, --help | | 提交命令帮助 | | +| --indent | | 在JSON响应中添加缩进 | | +| --json | | 输出将以json格式返回 | | +| --ledger | | 使用连接的硬件记账设备 | | +| --memo | | [string] 发送交易的备忘录 | | +| --node | tcp://localhost:26657 | [string] [string] tendermint节点开启的远程过程调用接口\<主机>:\<端口> | | +| --onchain-data | | [string] 上链数据 | 是 | +| --print-response | | 返回交易响应 (当且仅当同步模式下使用) | | +| --sequence | | [int] 用来签名交易的sequence number | | +| --trust-node | true | 关闭响应结果校验 | | + +## 例子 + +### 提交存证 + +```shell +iriscli record submit --chain-id="test" --onchain-data="this is my on chain data" --from=node0 --fee=0.1iris +``` + +运行成功以后,返回的结果如下: + +```txt +Password to sign with 'node0': +Committed at block 72 (tx hash: 7CCC8B4018D4447E6A496923944870E350A1A3AF9E15DB15B8943DAD7B5D782B, response: {Code:0 Data:[114 101 99 111 114 100 58 97 98 53 54 48 50 98 97 99 49 51 102 49 49 55 51 55 101 56 55 57 56 100 100 53 55 56 54 57 99 52 54 56 49 57 52 101 102 97 100 50 100 98 51 55 54 50 53 55 57 53 102 49 101 102 100 56 100 57 100 54 51 99 54] Log:Msg 0: Info: GasWanted:200000 GasUsed:4090 Tags:[{Key:[97 99 116 105 111 110] Value:[115 117 98 109 105 116 45 114 101 99 111 114 100] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[111 119 110 101 114 65 100 100 114 101 115 115] Value:[102 97 97 49 50 50 117 122 122 112 117 103 116 114 122 115 48 57 110 102 51 117 104 56 120 102 106 97 122 97 53 57 120 118 102 57 114 118 116 104 100 108] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[114 101 99 111 114 100 45 105 100] Value:[114 101 99 111 114 100 58 97 98 53 54 48 50 98 97 99 49 51 102 49 49 55 51 55 101 56 55 57 56 100 100 53 55 56 54 57 99 52 54 56 49 57 52 101 102 97 100 50 100 98 51 55 54 50 53 55 57 53 102 49 101 102 100 56 100 57 100 54 51 99 54] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 50 48 52 53 48 48 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "submit-record", + "completeConsumedTxFee-iris-atto": "\"2045000000000000\"", + "ownerAddress": "faa122uzzpugtrzs09nf3uh8xfjaza59xvf9rvthdl", + "record-id": "record:ab5602bac13f11737e8798dd57869c468194efad2db37625795f1efd8d9d63c6" + } + } +``` + +本次存证操作的record-id如下: + +```txt +"record-id": "record:ab5602bac13f11737e8798dd57869c468194efad2db37625795f1efd8d9d63c6" +``` + +请务必备份record-id,以备将来查询本次存证。若丢失record-id,本次存证再也无法查询到。 diff --git a/docs/zh/cli-client/service/README.md b/docs/zh/cli-client/service/README.md new file mode 100644 index 000000000..1c48ac1cb --- /dev/null +++ b/docs/zh/cli-client/service/README.md @@ -0,0 +1,30 @@ +# iriscli service + +## 描述 +Service 允许你通过区块链定义、绑定、调用服务。 + +## 用法 + +```shell +iriscli service [command] +``` + +## 相关命令 + +| Name | Description | +| ------------------------------------ | ---------------------- | +| [define](define.md) | 创建一个新的服务定义 | +| [definition](definition.md) | 查询服务定义 | +| [bind](bind.md) | 创建一个新的服务绑定 | +| [binding](binding.md) | 查询服务绑定 | +| [bindings](bindings.md) | 查询服务绑定列表 | +| [update-binding](update-binding.md) | 更新一个存在的服务绑定 | +| [disable](disable.md) | 禁用一个可用的服务绑定 | +| [enable](enable.md) | 启用一个不可用的服务绑定 | +| [refund-deposit](refund-deposit.md) | 取回所有押金 | + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 必需 | +| --------------- | ------- | ---------------- | -------- | +| --help, -h | | 服务命令帮助 | | \ No newline at end of file diff --git a/docs/zh/cli-client/service/bind.md b/docs/zh/cli-client/service/bind.md new file mode 100644 index 000000000..00a68b866 --- /dev/null +++ b/docs/zh/cli-client/service/bind.md @@ -0,0 +1,45 @@ +# iriscli service bind + +## 描述 + +创建一个新的服务绑定 + +## 用法 + +``` +iriscli service bind [flags] +``` + +## 标志 + +| Name, shorthand | Default | Description | Required | +| --------------------- | ----------------------- | ---------------------------------------------------------------------------------- | -------- | +| --avg-rsp-time | | [int] 服务平均返回时间的毫秒数表示 | Yes | +| --bind-type | | [string] 对服务是本地还是全局的设置,可选值Local/Global | Yes | +| --def-chain-id | | [string] 定义该服务的区块链ID | Yes | +| --deposit | | [string] 服务提供者的保证金 | Yes | +| --prices | | [strings] 服务定价,按照服务方法排序的定价列表 | | +| --service-name | | [string] 服务名称 | Yes | +| --usable-time | | [int] 每一万次服务调用的可用性的整数表示 | Yes | +| -h, --help | | 绑定命令帮助 | | + +## 例子 + +### 添加服务绑定到已存在的服务定义 +```shell +iriscli service bind --chain-id=test --from=node0 --fee=0.004iris --service-name=test-service --def-chain-id=test --bind-type=Local --deposit=1iris --prices=1iris --avg-rsp-time=10000 --usable-time=100 +``` + +运行成功以后,返回的结果如下: + +```txt +Password to sign with 'node0': +Committed at block 6 (tx hash: 87A477AEA41B22F7294084B4794837211C43A297D73EABA2F42F6436F3D975DD, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:5568 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 98 105 110 100] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 49 49 49 51 54 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-bind", + "completeConsumedTxFee-iris-atto": "\"111360000000000\"" + } + } +``` + diff --git a/docs/zh/cli-client/service/binding.md b/docs/zh/cli-client/service/binding.md new file mode 100644 index 000000000..6cbfd598c --- /dev/null +++ b/docs/zh/cli-client/service/binding.md @@ -0,0 +1,62 @@ +# iriscli service binding + +## 描述 + +查询服务绑定 + +## 用法 + +``` +iriscli service binding [flags] +``` + +## 标志 + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ---------------------------------------------------- | -------- | +| --bind-chain-id | | [string] 绑定该服务的区块链ID | 是 | +| --def-chain-id | | [string] 定义该服务的区块链ID | 是 | +| --provider | | [string] 服务提供者的区块链地址(bech32编码) | 是 | +| --service-name | | [string] 服务名称 | 是 | +| --help, -h | | 查询绑定命令帮助 | | + +## 例子 + +### 查询服务绑定 + +```shell +iriscli service binding --def-chain-id=test --service-name=test-service --bind-chain-id=test --provider=faa1ydhmma8l4m9dygsh7l08fgrwka6yczs0gkfnvd +``` + +运行成功以后,返回的结果如下: + +```json +{ + "type": "iris-hub/service/SvcBinding", + "value": { + "def_name": "test-service", + "def_chain_id": "test", + "bind_chain_id": "test", + "provider": "faa1ydhmma8l4m9dygsh7l08fgrwka6yczs0gkfnvd", + "binding_type": "Local", + "deposit": [ + { + "denom": "iris-atto", + "amount": "1000000000000000000000" + } + ], + "price": [ + { + "denom": "iris-atto", + "amount": "1000000000000000000" + } + ], + "level": { + "avg_rsp_time": "10000", + "usable_time": "100" + }, + "available": true, + "disable_height": "0" + } +} +``` \ No newline at end of file diff --git a/docs/zh/cli-client/service/bindings.md b/docs/zh/cli-client/service/bindings.md new file mode 100644 index 000000000..dbb40811a --- /dev/null +++ b/docs/zh/cli-client/service/bindings.md @@ -0,0 +1,53 @@ +# iriscli service bindings + +## 描述 + +查询服务绑定列表 + +## 用法 + +``` +iriscli service bindings [flags] +``` + +## 标志 + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ------------------------------------------------------ | -------- | +| --def-chain-id | | [string] 定义该服务的区块链ID | 是 | +| --service-name | | [string] 服务名称 | 是 | +| --help, -h | | 查询绑定列表命令帮助 | | + +## 例子 + +### 查询服务绑定列表 + +```shell +iriscli service bindings --def-chain-id=test --service-name=test-service +``` + +运行成功以后,返回的结果如下: + +```json +[{ + "def_name": "test-service", + "def_chain_id": "test", + "bind_chain_id": "test", + "provider": "faa1ydhmma8l4m9dygsh7l08fgrwka6yczs0gkfnvd", + "binding_type": "Local", + "deposit": [{ + "denom": "iris-atto", + "amount": "1000000000000000000000" + }], + "price": [{ + "denom": "iris-atto", + "amount": "1000000000000000000" + }], + "level": { + "avg_rsp_time": "10000", + "usable_time": "100" + }, + "available": true, + "disable_height": "0" +}] +``` \ No newline at end of file diff --git a/docs/zh/cli-client/service/define.md b/docs/zh/cli-client/service/define.md new file mode 100644 index 000000000..176541cdb --- /dev/null +++ b/docs/zh/cli-client/service/define.md @@ -0,0 +1,54 @@ +# iriscli service define + +## 描述 + +创建一个新的服务定义 + +## 用法 + +``` +iriscli service define [flags] +``` + +## 标志 + +| Name, shorthand | Default | Description | Required | +| --------------------- | ----------------------- | --------------------------------------------------------------------------------- | -------- | +| --service-description | | [string] 服务的描述 | | +| --author-description | | [string] 服务创建者的描述 | | +| --service-name | | [string] 服务名称 | Yes | +| --tags | | [strings] 该服务的关键字 | | +| --idl-content | | [string] 对该服务描述的接口定义语言内容 | | +| --file | | [string] 对该服务描述的接口定义语言内容的文件路径 | | +| -h, --help | | 服务定义命令帮助 | | + +## 例子 + +### 创建一个新的服务定义 +```shell +iriscli service define --chain-id=test --from=node0 --fee=0.004iris --service-name=test-service --service-description=service-description --author-description=author-description --tags=tag1,tag2 --idl-content=<idl-content> --file=test.proto +``` +如果文件项不是空的,将会替换Idl-content. [IDL内容示例](#idl-content-example). + +运行成功以后,返回的结果如下: + +```txt +Password to sign with 'node0': +Committed at block 65 (tx hash: 663B676E453F91BFCDC87B0308910501DD14DF79C88390FC15E06C4CC9612422, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:7968 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 100 101 102 105 110 101] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 49 53 57 51 54 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-define", + "completeConsumedTxFee-iris-atto": "\"159360000000000\"" + } + } +``` + +### IDL内容示例 +* IDL内容示例 + + > syntax = \\"proto3\\";\n\npackage helloworld;\n\n// The greeting service definition.\nservice Greeter {\n //@Attribute description: sayHello\n //@Attribute output_privacy: NoPrivacy\n //@Attribute output_cached: NoCached\n rpc SayHello (HelloRequest) returns (HelloReply) {}\n}\n\n// The request message containing the user's name.\nmessage HelloRequest {\n string name = 1;\n}\n\n// The response message containing the greetings\nmessage HelloReply {\n string message = 1;\n}\n + +* IDL文件示例 + + [test.proto](../../../features/test.proto) + diff --git a/docs/zh/cli-client/service/definition.md b/docs/zh/cli-client/service/definition.md new file mode 100644 index 000000000..30814f420 --- /dev/null +++ b/docs/zh/cli-client/service/definition.md @@ -0,0 +1,55 @@ +# iriscli service definition + +## 描述 + +查询服务定义 + +## 用法 + +``` +iriscli service definition [flags] +``` + +## 标志 + +| Name, shorthand | Default | Description | Required | +| --------------- | -------------------------- | ------------------------------------------------------ | -------- | +| --def-chain-id | | [string] 定义该服务的区块链ID | 是 | +| --service-name | | [string] 服务名称 | 是 | +| --help, -h | | 查询定义命令帮助 | | + +## 例子 + +### 查询服务定义 + +```shell +iriscli service definition --def-chain-id=test --service-name=test-service +``` + +运行成功以后,返回的结果如下: + +```json +{ + "SvcDef": { + "name": "test-service", + "chain_id": "test", + "description": "service-description", + "tags": [ + "tag1", + "tag2" + ], + "author": "faa1ydhmma8l4m9dygsh7l08fgrwka6yczs0gkfnvd", + "author_description": "author-description", + "idl_content": "syntax = \"proto3\";\n\npackage helloworld;\n\n// The greeting service definition.\nservice Greeter {\n //@Attribute description: sayHello\n //@Attribute output_privacy: NoPrivacy\n //@Attribute output_cached: NoCached\n rpc SayHello (HelloRequest) returns (HelloReply) {}\n}\n\n// The request message containing the user's name.\nmessage HelloRequest {\n string name = 1;\n}\n\n// The response message containing the greetings\nmessage HelloReply {\n string message = 1;\n}\n" + }, + "methods": [ + { + "id": "1", + "name": "SayHello", + "description": "sayHello", + "output_privacy": "NoPrivacy", + "output_cached": "NoCached" + } + ] +} +``` \ No newline at end of file diff --git a/docs/zh/cli-client/service/disable.md b/docs/zh/cli-client/service/disable.md new file mode 100644 index 000000000..f1b866d4d --- /dev/null +++ b/docs/zh/cli-client/service/disable.md @@ -0,0 +1,39 @@ +# iriscli service disable + +## 描述 + +禁用一个可用的服务绑定 + +## 用法 + +``` +iriscli service disable [flags] +``` + +## 标志 + +| Name, shorthand | Default | Description | Required | +| --------------------- | ----------------------- | --------------------------------------------------------------------------------- | -------- | +| --def-chain-id | | [string] 定义该服务的区块链ID | Yes | +| --service-name | | [string] 服务名称 | Yes | +| -h, --help | | 禁用命令帮助 | | + +## 例子 + +### 禁用一个可用的服务绑定 +```shell +iriscli service disable --chain-id=test --from=node0 --fee=0.004iris --def-chain-id=test --service-name=test-service +``` + +运行成功以后,返回的结果如下: + +```txt +Password to sign with 'node0': +Committed at block 537 (tx hash: 66C5EE634339D168A07C073C6BF209D80081762EB8451974ABC33A41914A7158, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:3510 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 100 105 115 97 98 108 101] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 55 48 50 48 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-disable", + "completeConsumedTxFee-iris-atto": "\"70200000000000\"" + } + } +``` \ No newline at end of file diff --git a/docs/zh/cli-client/service/enable.md b/docs/zh/cli-client/service/enable.md new file mode 100644 index 000000000..e9c2bb8d7 --- /dev/null +++ b/docs/zh/cli-client/service/enable.md @@ -0,0 +1,39 @@ +# iriscli service enable + +## 描述 + +启用一个不可用的服务绑定 + +## 用法 + +``` +iriscli service enable [flags] +``` + +## 标志 + +| Name, shorthand | Default | Description | Required | +| --------------------- | ----------------------- | --------------------------------------------------------------------------------- | -------- | +| --def-chain-id | | [string] 定义该服务的区块链ID | Yes | +| --deposit string | | [string] 绑定押金, 将会增加当前服务绑定押金 | | +| --service-name | | [string] 服务名称 | Yes | +| -h, --help | | 启用命令帮助 | | + +## 例子 + +### 启用一个不可用的服务绑定 +```shell +iriscli service enable --chain-id=test --from=node0 --fee=0.004iris --def-chain-id=test --service-name=test-service +``` + +运行成功以后,返回的结果如下: + +```txt +Committed at block 654 (tx hash: CF74E7629F0098AC3295F454F5C15BD5846A1F77C4E6C6FBA551606672B364DD, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:5036 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 101 110 97 98 108 101] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 49 48 48 55 50 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-enable", + "completeConsumedTxFee-iris-atto": "\"100720000000000\"" + } + } +``` \ No newline at end of file diff --git a/docs/zh/cli-client/service/refund-deposit.md b/docs/zh/cli-client/service/refund-deposit.md new file mode 100644 index 000000000..e056cc943 --- /dev/null +++ b/docs/zh/cli-client/service/refund-deposit.md @@ -0,0 +1,39 @@ +# iriscli service refund-deposit + +## 描述 + +取回所有押金 + +## 用法 + +``` +iriscli service refund-deposit [flags] +``` + +## 标志 + +| Name, shorthand | Default | Description | Required | +| --------------------- | ----------------------- | ---------------------------------------------------------------------------------- | -------- | +| --def-chain-id | | [string] 定义该服务的区块链ID | Yes | +| --service-name | | [string] 服务名称 | Yes | +| -h, --help | | 取回押金命令帮助 | | + +## 例子 + +### 取回所有押金 +```shell +iriscli service refund-deposit --chain-id=test --from=node0 --fee=0.004iris --def-chain-id=test --service-name=test-service +``` + +运行成功以后,返回的结果如下: + +```txt +Password to sign with 'node0': +Committed at block 991 (tx hash: 8A7F0EA61AB73A8B241945C8942EC8593774346B36BB70E36E138A23E7A473EE, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:4614 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 114 101 102 117 110 100 45 100 101 112 111 115 105 116] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 57 50 50 56 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-refund-deposit", + "completeConsumedTxFee-iris-atto": "\"92280000000000\"" + } + } +``` \ No newline at end of file diff --git a/docs/zh/cli-client/service/update-binding.md b/docs/zh/cli-client/service/update-binding.md new file mode 100644 index 000000000..4d3e6343e --- /dev/null +++ b/docs/zh/cli-client/service/update-binding.md @@ -0,0 +1,44 @@ +# iriscli service update-binding + +## 描述 + +更新一个存在的服务绑定 + +## 用法 + +``` +iriscli service update-binding [flags] +``` + +## 标志 +| Name, shorthand | Default | Description | Required | +| --------------------- | ----------------------- | ---------------------------------------------------------------------------------- | -------- | +| --avg-rsp-time | | [int] 服务平均返回时间的毫秒数表示 | Yes | +| --bind-type | | [string] 对服务是本地还是全局的设置,可选值Local/Global | Yes | +| --def-chain-id | | [string] 定义该服务的区块链ID | Yes | +| --deposit | | [string] 绑定押金, 将会增加当前服务绑定押金 | | +| --prices | | [strings] 服务定价,按照服务方法排序的定价列表 | | +| --service-name | | [string] 服务名称 | Yes | +| --usable-time | | [int] 每一万次服务调用的可用性的整数表示 | Yes | +| -h, --help | | 绑定更新命令帮助 | | + +## 例子 + +### 更新一个存在的服务绑定 +```shell +iriscli service update-binding --chain-id=test --from=node0 --fee=0.004iris --service-name=test-service --def-chain-id=test --bind-type=Local --deposit=1iris --prices=1iris --avg-rsp-time=10000 --usable-time=100 +``` + +运行成功以后,返回的结果如下: + +```txt +Password to sign with 'node0': +Committed at block 417 (tx hash: 8C9969A2BF3F7A8C13C2E0B57CE4FD7BE43454280559831D7E39B0FD3C1FCD28, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:5042 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 117 112 100 97 116 101 45 98 105 110 100 105 110 103] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 49 48 48 56 52 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] Codespace: XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-update-binding", + "completeConsumedTxFee-iris-atto": "\"100840000000000\"" + } + } +``` + diff --git a/docs/zh/cli-client/stake/README.md b/docs/zh/cli-client/stake/README.md new file mode 100644 index 000000000..35af9ff4f --- /dev/null +++ b/docs/zh/cli-client/stake/README.md @@ -0,0 +1,41 @@ +# iriscli stake + +## 介绍 + +Stake模块提供了一系列查询staking状态和发送staking交易的命令 + +## 用法 + +``` +iriscli stake [subcommand] +``` + +打印子命令和flags: +``` +iriscli stake --help +``` + +## 子命令 + +| 子命令 | 功能 | +| ------------------------------------------------------------- | --------------------------------------------------------------| +| [validator](validator.md) | 查询某个验证者 | +| [validators](validators.md) | 查询所有的验证者 | +| [delegation](delegation.md) | 基于委托者地址和验证者地址的委托查询 | +| [delegations](delegations.md) | 基于委托者地址的所有委托查询 | +| [unbonding-delegation](unbonding-delegation.md) | 基于委托者地址和验证者地址的unbonding-delegation记录查询 | +| [unbonding-delegations](unbonding-delegations.md) | 基于委托者地址的所有unbonding-delegation记录查询 | +| [unbonding-delegations-from](unbonding-delegations-from.md) | 基于验证者地址的所有unbonding-delegation记录查询| +| [redelegations-from](redelegations-from.md) | 基于某一验证者的所有重新委托查询 | +| [redelegation](redelegation.md) | 基于委托者地址,原源验证者地址和目标验证者地址的重新委托记录查询 | +| [redelegations](redelegations.md) | 基于委托者地址的所有重新委托记录查询 | +| [pool](pool.md) | 查询最新的权益池 | +| [parameters](parameters.md) | 查询最新的权益参数信息 | +| [signing-info](signing-info.md) | 查询验证者签名信息 | +| [create-validator](create-validator.md) | 以自委托的方式创建一个新的验证者 | +| [edit-validator](edit-validator.md) | 编辑已存在的验证者信息 | +| [delegate](delegate.md) | 委托一定代币到某个验证者 | +| [unbond](unbond.md) | 从指定的验证者解绑一定的股份 | +| [redelegate](redelegate.md) | 重新委托一定的token从一个验证者到另一个验证者 | +| [unjail](unjail.md) | 恢复之前由于宕机被惩罚的验证者的身份 | + diff --git a/docs/zh/cli-client/stake/create-validator.md b/docs/zh/cli-client/stake/create-validator.md new file mode 100644 index 000000000..d9d7f3212 --- /dev/null +++ b/docs/zh/cli-client/stake/create-validator.md @@ -0,0 +1,40 @@ +# iriscli stake create-validator + +## 介绍 + +发送交易申请成为验证人,并在在此验证人上委托一定数额的token + +## 用法 + +``` +iriscli stake create-validator [flags] +``` + +打印帮助信息 +``` +iriscli stake create-validator --help +``` + +## 特有的flags + +| 名称 | 类型 | 是否必填 | 默认值 | 功能描述 | +| ---------------------------- | ----- | -------- | -------- | ------------------------------------ | +| --amount | string | true | "" | 委托token的数量 | +| --commission-max-change-rate | float | true | 0.0 | 佣金比率每天变化的最大数量 | +| --commission-max-rate | float | true | 0.0 | 最大佣金比例 | +| --commission-rate | float | true | 0.0 | 初始佣金比例 | +| --details | string | false | "" | 验证人节点的详细信息 | +| --genesis-format | bool | false | false | 是否已genesis transaction的方式倒出 | +| --identity | string | false | "" | 身份信息的签名 | +| --ip | string | false | "" | 验证人节点的IP | +| --moniker | string | true | "" | 验证人节点名称 | +| --pubkey | string | true | "" | Amino编码的验证人公钥 | +| --website | string | false | "" | 验证人节点的网址 | + +## 示例 + +``` +iriscli stake create-validator --chain-id=<chain-id> --from=<key name> --fee=0.004iris --pubkey=<Validator PubKey> --commission-max-change-rate=0.01 --commission-max-rate=0.2 --commission-rate=0.1 --amount=100iris --moniker=<validator name> +``` + + diff --git a/docs/zh/cli-client/stake/delegate.md b/docs/zh/cli-client/stake/delegate.md new file mode 100644 index 000000000..fe0935904 --- /dev/null +++ b/docs/zh/cli-client/stake/delegate.md @@ -0,0 +1,29 @@ +# iriscli stake delegate + +## 介绍 + +发送委托交易 + +## 用法 + +``` +iriscli stake delegate [flags] +``` + +打印帮助信息 +``` +iriscli stake delegate --help +``` + +## 特有的flags + +| 名称 | 类型 | 是否必填 | 默认值 | 功能描述 | +| --------------------| ----- | -------- | -------- | ---------------- | +| --address-delegator | string | true | "" | 验证人地址 | +| --amount | string | true | "" | 委托的token数量 | + +## 示例 + +``` +iriscli stake delegate --chain-id=ChainID --from=KeyName --fee=Fee --amount=CoinstoBond --address-validator=ValidatorOwnerAddress +``` diff --git a/docs/zh/cli-client/stake/delegation.md b/docs/zh/cli-client/stake/delegation.md new file mode 100644 index 000000000..e4a6d1d07 --- /dev/null +++ b/docs/zh/cli-client/stake/delegation.md @@ -0,0 +1,39 @@ +# iriscli stake delegation + +## 描述 + +基于委托者和验证者地址查询委托交易 + +## 用法 + +``` +iriscli stake delegation [flags] +``` +打印帮助信息 +``` +iriscli stake delegation --help +``` +## 特有的flags + +| 名称, 速记 | 默认值 | 描述 | 必需 | +| --------------------- | -------------------------- | -------------------------------------------------------------------- | -------- | +| --address-delegator | | [string] 委托者bech地址 | Yes | +| --address-validator | | [string] 验证者bech地址 | Yes | + +## 示例 + +### 查询验证者 + +``` +iriscli stake delegation --address-validator=ValidatorAddress --address-delegator=DelegatorAddress + +``` + +运行成功以后,返回的结果如下: + +```txt +Delegation +Delegator: faa13lcwnxpyn2ea3skzmek64vvnp97jsk8qmhl6vx +Validator: fva15grv3xg3ekxh9xrf79zd0w077krgv5xf6d6thd +Shares: 0.2000000000Height: 290 +``` diff --git a/docs/zh/cli-client/stake/delegations.md b/docs/zh/cli-client/stake/delegations.md new file mode 100644 index 000000000..f4cbbeaac --- /dev/null +++ b/docs/zh/cli-client/stake/delegations.md @@ -0,0 +1,36 @@ +# iriscli stake delegations + +## 描述 + +查询某个委托者发起的所有委托记录 + +## 用法 + +``` +iriscli stake delegations [delegator-address] [flags] +``` +打印帮助信息 +``` +iriscli stake delegations --help +``` + +## 示例 + +### 查询某个委托者发起的所有委托记录 + +``` +iriscli stake delegations [delegator-address] +``` + +运行成功以后,返回的结果如下: + +```json +[ + { + "delegator_addr": "faa13lcwnxpyn2ea3skzmek64vvnp97jsk8qmhl6vx", + "validator_addr": "fva15grv3xg3ekxh9xrf79zd0w077krgv5xf6d6thd", + "shares": "0.2000000000", + "height": "290" + } +] +``` diff --git a/docs/zh/cli-client/stake/edit-validator.md b/docs/zh/cli-client/stake/edit-validator.md new file mode 100644 index 000000000..ec70763e4 --- /dev/null +++ b/docs/zh/cli-client/stake/edit-validator.md @@ -0,0 +1,32 @@ +# iriscli stake edit-validator + +## 介绍 + +修改验证的的参数,包括佣金比率,验证人节点名称以及其他描述信息 + +## 用法 + +``` +iriscli stake edit-validator [flags] +``` +打印帮助信息 +``` +iriscli stake edit-validator --help +``` + +## 特有flags + +| 名称 | 类型 | 是否必填 | 默认值 | 功能描述 | +| --------------------| ----- | -------- | -------- | ------------------------------------------------------------------- | +| --commission-rate | string | float | 0.0 | 佣金比率 | +| --moniker | string | false | "" | 验证人名称 | +| --identity | string | false | "" | 身份签名 | +| --website | string | false | "" | 网址 | +| --details | string | false | "" | 验证人节点详细信息 | + + +## 示例 + +``` +iriscli stake edit-validator --from=<key name> --chain-id=<chain-id> --fee=0.004iris --commission-rate=0.15 +``` diff --git a/docs/zh/cli-client/stake/parameters.md b/docs/zh/cli-client/stake/parameters.md new file mode 100644 index 000000000..027913019 --- /dev/null +++ b/docs/zh/cli-client/stake/parameters.md @@ -0,0 +1,31 @@ +# iriscli stake parameters + +## 描述 + +查询最新的权益参数信息 + +## 用法 + +``` +iriscli stake parameters [flags] +``` +打印帮助信息 +``` +iriscli stake parameters --help +``` + +## 示例 + +查询最新的权益参数信息 +``` +iriscli stake parameters +``` + +运行成功以后,返回的结果如下: + +```txt +Params +Unbonding Time: 10m0s +Max Validators: 100: +Bonded Coin Denomination: iris-atto +``` diff --git a/docs/zh/cli-client/stake/pool.md b/docs/zh/cli-client/stake/pool.md new file mode 100644 index 000000000..5788748b7 --- /dev/null +++ b/docs/zh/cli-client/stake/pool.md @@ -0,0 +1,32 @@ +# iriscli stake pool + +## 描述 + +查询最新的权益池 + +## 用法 + +``` +iriscli stake pool [flags] +``` +打印帮助信息 +``` +iriscli stake pool --help +``` + +## 示例 + +查询最新的权益池 +``` +iriscli stake pool +``` + +运行成功以后,返回的结果如下: + +```txt +Pool +Loose Tokens: 49.8289125612 +Bonded Tokens: 100.1800000000 +Token Supply: 150.0089125612 +Bonded Ratio: 0.6678269863 +``` diff --git a/docs/zh/cli-client/stake/redelegate.md b/docs/zh/cli-client/stake/redelegate.md new file mode 100644 index 000000000..385c17ab8 --- /dev/null +++ b/docs/zh/cli-client/stake/redelegate.md @@ -0,0 +1,34 @@ +# iriscli stake redelegate + +## 介绍 + +把某个委托的一部分或者全部从一个验证人转移到另外一个验证人 + +## 用法 + +``` +iriscli stake redelegate [flags] +``` + +打印帮助信息 +``` +iriscli stake redelegate --help +``` + +## 特有的flags + +| 名称 | 类型 | 是否必填 | 默认值 | 功能描述 | +| -------------------------- | ----- | -------- | -------- | ------------------------------------------------------------------- | +| --address-validator-dest | string | true | "" | 目标验证人地址 | +| --address-validator-source | string | true | "" | 源验证人地址 | +| --shares-amount | float | false | 0.0 | 转移的share数量,正数 | +| --shares-percent | float | false | 0.0 | 转移的比率,0到1之间的正数 | + +用户可以用`--shares-amount`或者`--shares-percent`指定装委托的token数量。记住,这两个参数不可同时使用。 + +## 示例 + +``` +iriscli stake redelegate --chain-id=<chain-id> --from=<key name> --fee=0.004iris --address-validator-source=<SourceValidatorAddress> --address-validator-dest=<DestinationValidatorAddress> --shares-percent=0.1 +``` + diff --git a/docs/zh/cli-client/stake/redelegation.md b/docs/zh/cli-client/stake/redelegation.md new file mode 100644 index 000000000..b78169e5f --- /dev/null +++ b/docs/zh/cli-client/stake/redelegation.md @@ -0,0 +1,43 @@ +# iriscli stake redelegation + +## 描述 + +基于委托者地址,原源验证者地址和目标验证者地址的重新委托记录查询 + +## 用法 + +``` +iriscli stake redelegation [flags] +``` +打印帮助信息 +``` +iriscli stake redelegation --help +``` + +## 特有的flags + +| 名称, 速记 | 默认值 | 描述 | 必需 | +| -------------------------- | -------------------------- | ------------------------------------------------------------------- | -------- | +| --address-delegator | | [string] 委托者bech地址 | Yes | +| --address-validator-dest | | [string] 目标验证者bech地址 | Yes | +| --address-validator-source | | [string] 源验证者bech地址 | Yes | + +## 示例 + +查询重新委托记录 +``` +iriscli stake redelegation --address-validator-source=SourceValidatorAddress --address-validator-dest=DestinationValidatorAddress --address-delegator=DelegatorAddress +``` + +运行成功以后,返回的结果如下: + +```txt +Redelegation +Delegator: faa10s0arq9khpl0cfzng3qgxcxq0ny6hmc9sytjfk +Source Validator: fva1dayujdfnxjggd5ydlvvgkerp2supknthajpch2 +Destination Validator: fva1h27xdw6t9l5jgvun76qdu45kgrx9lqede8hpcd +Creation height: 1130 +Min time to unbond (unix): 2018-11-16 07:22:48.740311064 +0000 UTC +Source shares: 0.1000000000 +Destination shares: 0.1000000000 +``` diff --git a/docs/zh/cli-client/stake/redelegations-from.md b/docs/zh/cli-client/stake/redelegations-from.md new file mode 100644 index 000000000..ee9f286e5 --- /dev/null +++ b/docs/zh/cli-client/stake/redelegations-from.md @@ -0,0 +1,46 @@ +# iriscli stake redelegations-from + +## 描述 + +基于某一验证者的所有重新委托查询 + +## 用法 + +``` +iriscli stake redelegations-from [validator-address] [flags] +``` +打印帮助信息 +``` +iriscli stake redelegations-from --help +``` + +## 示例 + +基于某一验证者的所有重新委托查询 +``` +iriscli stake redelegations-from [validator-address] +``` + +运行成功以后,返回的结果如下: + +```json +[ + { + "delegator_addr": "faa10s0arq9khpl0cfzng3qgxcxq0ny6hmc9sytjfk", + "validator_src_addr": "fva1dayujdfnxjggd5ydlvvgkerp2supknthajpch2", + "validator_dst_addr": "fva1h27xdw6t9l5jgvun76qdu45kgrx9lqede8hpcd", + "creation_height": "1130", + "min_time": "2018-11-16T07:22:48.740311064Z", + "initial_balance": { + "denom": "iris-atto", + "amount": "100000000000000000" + }, + "balance": { + "denom": "iris-atto", + "amount": "100000000000000000" + }, + "shares_src": "100000000000000000.0000000000", + "shares_dst": "100000000000000000.0000000000" + } +] +``` diff --git a/docs/zh/cli-client/stake/redelegations.md b/docs/zh/cli-client/stake/redelegations.md new file mode 100644 index 000000000..e7b74cea7 --- /dev/null +++ b/docs/zh/cli-client/stake/redelegations.md @@ -0,0 +1,40 @@ +# iriscli stake redelegations + +## 描述 + +基于委托者地址的所有重新委托记录查询 + +## 用法 + +``` +iriscli stake redelegations [delegator-address] [flags] +``` +打印帮助信息 +``` +iriscli stake redelegations --help +``` + +## 示例 + +基于委托者地址的所有重新委托记录查询 +``` +iriscli stake redelegations [delegator-address] +``` + +运行成功以后,返回的结果如下: + +```json +[ + { + "delegator_addr": "faa10s0arq9khpl0cfzng3qgxcxq0ny6hmc9sytjfk", + "validator_src_addr": "fva1dayujdfnxjggd5ydlvvgkerp2supknthajpch2", + "validator_dst_addr": "fva1h27xdw6t9l5jgvun76qdu45kgrx9lqede8hpcd", + "creation_height": "1130", + "min_time": "2018-11-16T07:22:48.740311064Z", + "initial_balance": "0.1iris", + "balance": "0.1iris", + "shares_src": "0.1000000000", + "shares_dst": "0.1000000000" + } +] +``` diff --git a/docs/zh/cli-client/stake/signing-info.md b/docs/zh/cli-client/stake/signing-info.md new file mode 100644 index 000000000..67590838f --- /dev/null +++ b/docs/zh/cli-client/stake/signing-info.md @@ -0,0 +1,28 @@ +# iriscli stake signing-info + +## 描述 + +查询验证者签名信息 + +## 用法 + +``` +iriscli stake signing-info [validator-pubkey] [flags] +``` +打印帮助信息 +``` +iriscli stake signing-info --help +``` + +## 示例 + +查询验证者签名信息 +``` +iriscli stake signing-info [validator-pubkey] +``` + +运行成功以后,返回的结果如下: + +```txt +Start height: 0, index offset: 2136, jailed until: 1970-01-01 00:00:00 +0000 UTC, missed blocks counter: 0 +``` diff --git a/docs/zh/cli-client/stake/unbond.md b/docs/zh/cli-client/stake/unbond.md new file mode 100644 index 000000000..043693757 --- /dev/null +++ b/docs/zh/cli-client/stake/unbond.md @@ -0,0 +1,33 @@ +# iriscli stake unbond + +## 介绍 + +Unbond shares from a validator + +## 用法 + +``` +iriscli stake unbond [flags] +``` + +打印帮助信息 + +``` +iriscli stake unbond --help +``` + +## 特有flags + +| 名称 | 类型 | 是否必填 | 默认值 | 功能描述 | +| --------------------| ----- | -------- | -------- | ------------------------------------------------------------------- | +| --address-validator | string | true | "" | 验证人地址 | +| --shares-amount | float | false | 0.0 | 解绑的share数量,正数 | +| --shares-percent | float | false | 0.0 | 解绑的比率,0到1之间的正数 | + +用户可以用`--shares-amount`或者`--shares-percent`指定解绑定的token数量,这两个参数不可同时使用。 + +## 示例 + +``` +iriscli stake unbond --address-validator=<ValidatorAddress> --shares-percent=0.1 --from=<key name> --chain-id=<chain-id> --fee=0.004iris +``` diff --git a/docs/zh/cli-client/stake/unbonding-delegation.md b/docs/zh/cli-client/stake/unbonding-delegation.md new file mode 100644 index 000000000..b46190aa9 --- /dev/null +++ b/docs/zh/cli-client/stake/unbonding-delegation.md @@ -0,0 +1,40 @@ +# iriscli stake unbonding-delegation + +## 描述 + +基于委托者地址和验证者地址的unbonding-delegation记录查询 + +## 用法 + +``` +iriscli stake unbonding-delegation [flags] +``` +打印帮助信息 +``` +iriscli stake unbonding-delegation --help +``` + +## 特有的flags + +| 名称, 速记 | 默认值 | 描述 | 必需 | +| ------------------- | -------------------------- | ------------------------------------------------------------------- | -------- | +| --address-delegator | | [string] 委托者bech地址 | Yes | +| --address-validator | | [string] 验证者bech地址 | Yes | + +## 示例 + +查询unbonding-delegation +``` +iriscli stake unbonding-delegation --address-delegator=DelegatorAddress --address-validator=ValidatorAddress +``` + +运行成功以后,返回的结果如下: + +```txt +Unbonding Delegation +Delegator: faa13lcwnxpyn2ea3skzmek64vvnp97jsk8qmhl6vx +Validator: fva15grv3xg3ekxh9xrf79zd0w077krgv5xf6d6thd +Creation height: 1310 +Min time to unbond (unix): 2018-11-15 06:24:22.754703377 +0000 UTC +Expected balance: 0.02iris +``` diff --git a/docs/zh/cli-client/stake/unbonding-delegations-from.md b/docs/zh/cli-client/stake/unbonding-delegations-from.md new file mode 100644 index 000000000..072f384d5 --- /dev/null +++ b/docs/zh/cli-client/stake/unbonding-delegations-from.md @@ -0,0 +1,43 @@ +# iriscli stake unbonding-delegations-from + +## 描述 + +基于验证者地址的所有unbonding-delegation记录查询 + +## 用法 + +``` +iriscli stake unbonding-delegations-from [validator-address] [flags] +``` +打印帮助信息 +``` +iriscli stake unbonding-delegations-from --help +``` + +## 示例 + +基于验证者地址的所有unbonding-delegation记录查询 +``` +iriscli stake unbonding-delegations [validator-address] +``` + +运行成功以后,返回的结果如下: + +```json +[ + { + "delegator_addr": "faa13lcwnxpyn2ea3skzmek64vvnp97jsk8qmhl6vx", + "validator_addr": "fva15grv3xg3ekxh9xrf79zd0w077krgv5xf6d6thd", + "creation_height": "1310", + "min_time": "2018-11-15T06:24:22.754703377Z", + "initial_balance": { + "denom": "iris-atto", + "amount": "20000000000000000" + }, + "balance": { + "denom": "iris-atto", + "amount": "20000000000000000" + } + } +] +``` diff --git a/docs/zh/cli-client/stake/unbonding-delegations.md b/docs/zh/cli-client/stake/unbonding-delegations.md new file mode 100644 index 000000000..6ba055aeb --- /dev/null +++ b/docs/zh/cli-client/stake/unbonding-delegations.md @@ -0,0 +1,37 @@ +# iriscli stake unbonding-delegations + +## 描述 + +基于委托者地址的所有unbonding-delegation记录查询 + +## 用法 + +``` +iriscli stake unbonding-delegations [delegator-address] [flags] +``` +打印帮助信息 +``` +iriscli stake unbonding-delegations --help +``` + +## 示例 + +查询unbonding-delegation +``` +iriscli stake unbonding-delegations [delegator-address] +``` + +运行成功以后,返回的结果如下: + +```json +[ + { + "delegator_addr": "faa13lcwnxpyn2ea3skzmek64vvnp97jsk8qmhl6vx", + "validator_addr": "fva15grv3xg3ekxh9xrf79zd0w077krgv5xf6d6thd", + "creation_height": "1310", + "min_time": "2018-11-15T06:24:22.754703377Z", + "initial_balance": "0.02iris", + "balance": "0.02iris" + } +] +``` diff --git a/docs/zh/cli-client/stake/unjail.md b/docs/zh/cli-client/stake/unjail.md new file mode 100644 index 000000000..abbad5ca5 --- /dev/null +++ b/docs/zh/cli-client/stake/unjail.md @@ -0,0 +1,27 @@ +# iriscli stake unjail + +## 介绍 + +Unjail validator previously jailed for downtime + +## 用法 + +``` +iriscli stake unjail [flags] +``` + +打印帮助信息 + +``` +iriscli stake unjail --help +``` + +## 特有flags + +没有特有的flags + +## 示例 + +``` +iriscli stake unjail --from=<key name> --fee=0.004iris --chain-id=<chain-id> +``` diff --git a/docs/zh/cli-client/stake/validator.md b/docs/zh/cli-client/stake/validator.md new file mode 100644 index 000000000..c232ff93b --- /dev/null +++ b/docs/zh/cli-client/stake/validator.md @@ -0,0 +1,39 @@ +# iriscli stake validator + +## 描述 + +查询验证者 + +## 用法 + +``` +iriscli stake validator [validator-address] [flags] +``` +打印帮助信息 +``` +iriscli stake validator --help +``` + +## 示例 + +查询验证者 +``` +iriscli stake validator [validator-address] +``` + +运行成功以后,返回的结果如下: + +```txt +Validator +Operator Address: fva15grv3xg3ekxh9xrf79zd0w077krgv5xf6d6thd +Validator Consensus Pubkey: fvp1zcjduepq47906n2zvq597vwyqdc0h35ve0fcl64hwqs9xw5fg67zj4g658aqyuhepj +Jailed: false +Status: Bonded +Tokens: 100.0000000000 +Delegator Shares: 100.0000000000 +Description: {node0 } +Bond Height: 0 +Unbonding Height: 0 +Minimum Unbonding Time: 1970-01-01 00:00:00 +0000 UTC +Commission: {{0.0000000000 0.0000000000 0.0000000000 0001-01-01 00:00:00 +0000 UTC}} +``` diff --git a/docs/zh/cli-client/stake/validators.md b/docs/zh/cli-client/stake/validators.md new file mode 100644 index 000000000..28dc0c17f --- /dev/null +++ b/docs/zh/cli-client/stake/validators.md @@ -0,0 +1,39 @@ +# iriscli stake validators + +## 描述 + +查询所有验证者 + +## 用法 + +``` +iriscli stake validators [flags] +``` +打印帮助信息 +``` +iriscli stake validators --help +``` + +## 示例 + +查询验证者 +``` +iriscli stake validators +``` + +运行成功以后,返回的结果如下: + +```txt +Validator +Operator Address: fva15grv3xg3ekxh9xrf79zd0w077krgv5xf6d6thd +Validator Consensus Pubkey: fvp1zcjduepq47906n2zvq597vwyqdc0h35ve0fcl64hwqs9xw5fg67zj4g658aqyuhepj +Jailed: false +Status: Bonded +Tokens: 100.0000000000 +Delegator Shares: 100.0000000000 +Description: {node0 } +Bond Height: 0 +Unbonding Height: 0 +Minimum Unbonding Time: 1970-01-01 00:00:00 +0000 UTC +Commission: {{0.0000000000 0.0000000000 0.0000000000 0001-01-01 00:00:00 +0000 UTC}} +``` diff --git a/docs/zh/cli-client/status/README.md b/docs/zh/cli-client/status/README.md new file mode 100644 index 000000000..3c6dabf22 --- /dev/null +++ b/docs/zh/cli-client/status/README.md @@ -0,0 +1,32 @@ +# iriscli status + +## 描述 + +查询远端节点状态 + +## 用法 + +```shell +iriscli status [flags] +``` + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 必需 | +| --------------------- | --------------------- | ----------------------------------- | -------- | +| --help, -h | | 状态命令帮助 | | +| --node, -n | tcp://localhost:26657 | [string] 连接的节点 | | + +## 例子 + +### 查询远端节点状态 + +```shell +iriscli status +``` + +查询到的结果如下所示: + +```json +{"node_info":{"protocol_version":{"p2p":"4","block":"7","app":"0"},"id":"959185fdc3d14bdc7be1af40c5290d25042a454c","listen_addr":"tcp://0.0.0.0:26656","network":"test","version":"0.26.0","channels":"4020212223303800","moniker":"node0","other":{"tx_index":"on","rpc_address":"tcp://0.0.0.0:26657"}},"sync_info":{"latest_block_hash":"04A6B890A61F503A64F254CF8479C8FB9012A9C9494249DC76F81B6453ADF6A1","latest_app_hash":"B3549258BBC34860630BB5721364104DAC241EB243A8B0BCA0AA4968A64A1A6B","latest_block_height":"2647","latest_block_time":"2018-11-16T03:12:46.701163933Z","catching_up":false},"validator_info":{"address":"91679AB00C0A09B006F9A812AAF686092657F658","pub_key":{"type":"tendermint/PubKeyEd25519","value":"r4r9TUJgKF8xxANw+8aMy9OP6rdwIFM6iUa8KVUaofo="},"voting_power":"100"}} +``` diff --git a/docs/zh/cli-client/tendermint/README.md b/docs/zh/cli-client/tendermint/README.md new file mode 100644 index 000000000..5083eb47f --- /dev/null +++ b/docs/zh/cli-client/tendermint/README.md @@ -0,0 +1 @@ +# iriscli \ No newline at end of file diff --git a/docs/zh/cli-client/upgrade/README.md b/docs/zh/cli-client/upgrade/README.md new file mode 100644 index 000000000..bdde59d82 --- /dev/null +++ b/docs/zh/cli-client/upgrade/README.md @@ -0,0 +1,25 @@ +# iriscli upgrade + +## 描述 + +用来参与软件升级的流程,并可查看当前版本的信息。 + +## 用法 + +```shell +iriscli upgrade [command] +``` + +## 相关命令 + +| 命令 | 描述 | +| ------------- | ------------------------------------- | +| [submit-switch](submit-switch.md) | 针对软件升级提议发送switch消息| +| [query-switch](query-switch.md) | 查询switch信息 | +| [info](info.md) | 查询软件升级模块的信息| + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 必需 | +| --------------- | ------- | ---------------- | -------- | +| --help, -h | | 升级命令帮助 | | diff --git a/docs/zh/cli-client/upgrade/info.md b/docs/zh/cli-client/upgrade/info.md new file mode 100644 index 000000000..7a8013050 --- /dev/null +++ b/docs/zh/cli-client/upgrade/info.md @@ -0,0 +1,65 @@ +# iriscli upgrade info + +## 描述 + +查询软件版本信息和升级模块的信息 + +## 用法 + +``` +iriscli upgrade info +``` + +打印帮助信息: + +``` +iriscli upgrade info --help +``` +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 必需 | +| --------------- | -------------------------- | ----------------------------------------------------------------- | -------- | + +## 例子 + +查询当前版本信息 + +``` +iriscli upgrade info +``` + +然后它会打印如下内容: + +``` +{ + "current_proposal_id": "0", + "current_proposal_accept_height": "-1", + "version": { + "Id": "0", + "ProposalID": "0", + "Start": "0", + "ModuleList": [ + { + "Start": "0", + "End": "9223372036854775807", + "Handler": "bank", + "Store": [ + "acc" + ] + }, + { + "Start": "0", + "End": "9223372036854775807", + "Handler": "stake", + "Store": [ + "stake", + "acc", + "mint", + "distr" + ] + }, + ....... + ] + } +} +``` diff --git a/docs/zh/cli-client/upgrade/query-switch.md b/docs/zh/cli-client/upgrade/query-switch.md new file mode 100644 index 000000000..a263c0e89 --- /dev/null +++ b/docs/zh/cli-client/upgrade/query-switch.md @@ -0,0 +1,31 @@ +# iriscli upgrade query-switch + +## 描述 + +查询switch信息来知道某人对某升级提议是否发送了switch消息。 + +## 用法 + +``` +iriscli upgrade query-switch --proposal-id <proposalID> --voter <voter address> +``` +打印帮助信息: + +``` +iriscli upgrade query-switch --help +``` + +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 必需 | +| --------------- | -------------------------- | ----------------------------------------------------------------- | -------- | +| --proposal-id | | 软件升级提议的ID | 是 | +| --voter | | 签名switch消息的地址 | 是 | + +## 例子 + +查询用户`faa1qvt2r6hh9vyg3kh4tnwgx8wh0kpa7q2lsk03fe`是否对升级提议(ID为5)发送了switch消息 + +``` +iriscli upgrade query-switch --proposal-id=5 --voter=faa1qvt2r6hh9vyg3kh4tnwgx8wh0kpa7q2lsk03fe +``` diff --git a/docs/zh/cli-client/upgrade/submit-switch.md b/docs/zh/cli-client/upgrade/submit-switch.md new file mode 100644 index 000000000..a1ef824bc --- /dev/null +++ b/docs/zh/cli-client/upgrade/submit-switch.md @@ -0,0 +1,30 @@ +# iriscli upgrade submit-switch + +## 描述 + +安装完新软件后,向这次升级相关的提议发送switch消息,表明自己已经安装新软件并把消息广播到全网。 + +## 用例 + +``` +iriscli upgrade submit-switch [flags] +``` +打印帮助信息: + +``` +iriscli upgrade submit-switch --help +``` +## 标志 + +| 名称, 速记 | 默认值 | 描述 | 必需 | +| --------------- | --------- | ------------------------------------------------------------ | -------- | +| --proposal-id | | 软件升级提议的ID | 是 | +| --title | | switch消息对标题 | | + +## 用例 + +发送对软件升级提议(ID为5)switch消息 + +``` +iriscli upgrade submit-switch --chain-id=IRISnet --from=x --fee=0.004iris --proposalID 5 --title="Run new verison" +``` diff --git a/docs/zh/features/README.md b/docs/zh/features/README.md new file mode 100644 index 000000000..74212951c --- /dev/null +++ b/docs/zh/features/README.md @@ -0,0 +1,13 @@ +# Features + +## Bank + +## Stake + +## Service + +## Record + +## Governance + +## Distribution \ No newline at end of file diff --git a/docs/zh/features/bank.md b/docs/zh/features/bank.md new file mode 100644 index 000000000..7da520a5c --- /dev/null +++ b/docs/zh/features/bank.md @@ -0,0 +1,197 @@ +# Bank模块用户文档 + +## 简介 +该模块主要用于账户之间转账、查询账户余额,同时提供了通用的离线签名与交易广播方法,此外,使用[coin_type](./basic-concepts/coin-type.md)定义了IRIShub系统中代币的可用单位。 + +## 使用场景 + +1. 查询某一代币coin_type: + ```bash + iriscli bank coin-type [coin-name] + ``` + 如coin-name为iris,将返回iris的coin_type: + ```json + { + "name": "iris", + "min_unit": { + "denom": "iris-atto", + "decimal": "18" + }, + "units": [ + { + "denom": "iris", + "decimal": "0" + }, + { + "denom": "iris-milli", + "decimal": "3" + }, + { + "denom": "iris-micro", + "decimal": "6" + }, + { + "denom": "iris-nano", + "decimal": "9" + }, + { + "denom": "iris-pico", + "decimal": "12" + }, + { + "denom": "iris-femto", + "decimal": "15" + }, + { + "denom": "iris-atto", + "decimal": "18" + } + ], + "origin": 1, + "desc": "IRIS Network" + } + ``` + +2. 账户查询 + + 可以通过账户地址查询该账户的信息,包括账户余额、账户公钥、账户编号和交易序号。 + ```bash + iriscli bank account [account address] + ``` + +3. 账户间转账 + + 如从账户A转账给账户B10iris: + ```bash + iriscli bank send --to [address of wallet B] --amount=10iris --fee=0.004iris --from=[key name of wallet A] --chain-id=[chain-id] + ``` + IRISnet支持多种代币流通,将来IRISnet可以在一个交易中包含多种代币交换——代币种类可以为任意在IRISnet中注册过的coin_type。 + +4. 交易签名 + + 为了提高账户安全性,IRISnet支持交易离线签名保护账户的私钥。在任意交易中,使用参数--generate-only=true可以构建一个未签名的交易。使用转账交易作为示例: + ```bash + iriscli bank send --to [address of wallet B] --amount=10iris --fee=0.004iris --from=[key name of wallet A] --generate-only=true + ``` + 将构建一个signatures为空的交易返回: + ```json + { + "type": "auth/StdTx", + "value": { + "msg": [ + { + "type": "cosmos-sdk/Send", + "value": { + "inputs": [ + { + "address": "faa1ydhmma8l4m9dygsh7l08fgrwka6yczs0gkfnvd", + "coins": [ + { + "denom": "iris-atto", + "amount": "100000000000000000000" + } + ] + } + ], + "outputs": [ + { + "address": "faa1ut8aues05kq0nkcj3lzkyhk7eyfasrdfnf7wph", + "coins": [ + { + "denom": "iris-atto", + "amount": "100000000000000000000" + } + ] + } + ] + } + } + ], + "fee": { + "amount": [ + { + "denom": "iris-atto", + "amount": "40000000000000000" + } + ], + "gas": "200000" + }, + "signatures": null, + "memo": "" + } + } + ``` + 将结果保存到文件。 + + 发送签名交易: + ```bash + iriscli bank sign [file] --chain-id=[chain-id] --name [key name] + ``` + 将返回已签名的交易: + ```json + { + "type": "auth/StdTx", + "value": { + "msg": [ + { + "type": "cosmos-sdk/Send", + "value": { + "inputs": [ + { + "address": "faa1ydhmma8l4m9dygsh7l08fgrwka6yczs0gkfnvd", + "coins": [ + { + "denom": "iris-atto", + "amount": "100000000000000000000" + } + ] + } + ], + "outputs": [ + { + "address": "faa1ut8aues05kq0nkcj3lzkyhk7eyfasrdfnf7wph", + "coins": [ + { + "denom": "iris-atto", + "amount": "100000000000000000000" + } + ] + } + ] + } + } + ], + "fee": { + "amount": [ + { + "denom": "iris-atto", + "amount": "40000000000000000" + } + ], + "gas": "200000" + }, + "signatures": [ + { + "pub_key": { + "type": "tendermint/PubKeySecp256k1", + "value": "A+qXW5isQDb7blT/KwEgQHepji8RfpzIstkHpKoZq0kr" + }, + "signature": "5hxk/R81SWmKAGi4kTW2OapezQZpp6zEnaJbVcyDiWRfgBm4Uejq8+CDk6uzk0aFSgAZzz06E014UkgGpelU7w==", + "account_number": "0", + "sequence": "11" + } + ], + "memo": "" + } + } + ``` + 将结果保存到文件。 + +5. 广播交易 + + 广播离线产生的已签名的交易,在这里,你可以使用上面的sign命令生成的交易。当然,您可以通过任何方法生成已签名的交易,例如:[irisnet-crypto](https://github.com/irisnet/irisnet-crypto)。 + ```bash + iriscli bank broadcast [file] + ``` + 该交易将在IRISnet中广播并执行。 + \ No newline at end of file diff --git a/docs/zh/features/basic-concepts/bech32-prefix.md b/docs/zh/features/basic-concepts/bech32-prefix.md new file mode 100644 index 000000000..a77c5140a --- /dev/null +++ b/docs/zh/features/basic-concepts/bech32-prefix.md @@ -0,0 +1,30 @@ +# Bech32 on IRISnet + +Bech32是由Pieter Wuille和Greg Maxwel提出的新比特币地址格式。除了比特币之外,bech32可以编码任何短二进制数据。在IRISnet里,私钥和地址可能指的是一些在网络中不同的角色,例如普通账户和验证人账户等。IRISnet设计使用Bech32地址格式来提供对数据鲁棒的完整性检查。 用户可读部分(human readable part) 使得用户更有效率的理解地址和阅读错误信息。Bech32更多细节见 [bip-0173](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki) + + +## 用户可读部分表 + +| HRP | Definition | +| -----------|:-------------| +|faa| IRISnet Account Address| +|fap| IRISnet Account Public Key| +|fva| IRISnet Validator's Operator Address| +|fvp| IRISnet Validator's Operator Public Key| +|fca| IRISnet Consensus Address| +|fcp| IRISnet Consensus Public Key| + +## 编码 + +不是所有IRISnet的用户地址都会以bech32的格式暴露出来。许多地址仍然是hex编码或者base64编码。 在bech32编码之前,首先要使用amino对其他地址私钥二进制表示进行编码。 + +## 例子 + +一旦创建一个新的账户,你将会看到以下信息: + +``` +NAME: TYPE: ADDRESS: PUBKEY: +test1 local faa18ekc4dswwrh2a6lfyev4tr25h5y76jkpqsz7kl fap1addwnpepqgxa40ww28uy9q46gg48g6ulqdzwupyjcwfumgfjpvz7krmg5mrnw6zv8uv +``` + +这意味着你创建了一个新账户地址 `faa18ekc4dswwrh2a6lfyev4tr25h5y76jkpqsz7kl`, 他的用户可读部分是 `faa`。他的公钥被密码成 `fap1addwnpepqgxa40ww28uy9q46gg48g6ulqdzwupyjcwfumgfjpvz7krmg5mrnw6zv8uv`, 他的用户可读部分是 `fap`。 diff --git a/docs/zh/modules/coin/README.md b/docs/zh/features/basic-concepts/coin-type.md similarity index 100% rename from docs/zh/modules/coin/README.md rename to docs/zh/features/basic-concepts/coin-type.md diff --git a/docs/zh/modules/fee-token/Fee.md b/docs/zh/features/basic-concepts/fee.md similarity index 100% rename from docs/zh/modules/fee-token/Fee.md rename to docs/zh/features/basic-concepts/fee.md diff --git a/docs/zh/features/basic-concepts/genesis-file.md b/docs/zh/features/basic-concepts/genesis-file.md new file mode 100644 index 000000000..ed88418e5 --- /dev/null +++ b/docs/zh/features/basic-concepts/genesis-file.md @@ -0,0 +1,46 @@ +# Genesis + +Genesis文件是整个网络初始化的基础。它包含了创建创世块的大部分信息(比如ChainID,共识的参数),初始化账户余额,每个模块的参数,validators信息。 + +## Basic State + +* genesis_time Genesis文件创建时间 +* chain_id 区块链的ID + +## Consensus Params + +* block_size 区块大小和区块内Gas数量的配置参数 +* evidence 区块内作恶证据的生命周期 + +## App State + +* **accounts** 初始化账户信息 + +* **stake** 与抵押共识相关的参数 + * `loose_tokens` 全网未绑定的通证总和 + * `unbonding_time` 开始解绑到解绑成功需要的时间 + * `max_validators` 最大验证人数目 + +* **mint** 与通货膨胀相关的参数 + * `inflation_max` 最大通货膨胀率 + * `inflation_min` 最小通货膨胀率 + +* **distribution** 与分配收益有关的参数 + +* **gov** 与链上治理相关的参数 + * `DepositProcedure` 抵押阶段的参数 + * `VotingProcedure` 投票阶段的参数 + * `TallyingProcedure` 统计阶段的参数 + +* **upgrade** 与升级相关的参数 + * `switch_period` 软件升级通过后需要在switch_perid内发送switch消息 + +* **slashing** 与惩罚validator相关的参数 + +* **service** 与Service相关的参数 + * `MaxRequestTimeout` 服务调用最大等待区块个数 + * `MinProviderDeposit` 服务绑定最小抵押金额 + +## Gentxs + +Gentxs中包含了创世区块中创建validators的交易集合。 \ No newline at end of file diff --git a/docs/zh/features/basic-concepts/gov-params.md b/docs/zh/features/basic-concepts/gov-params.md new file mode 100644 index 000000000..5b653387b --- /dev/null +++ b/docs/zh/features/basic-concepts/gov-params.md @@ -0,0 +1,18 @@ +# Gov Params + +在IRISnet中,存在一些特殊的参数,它们可通过链上治理被修改。持有IRIS通证的用户都可以参与到参数修改的链上治理。如果社区对某些可修改的参数不满意,完全可以通过治理模块设置合适的值。 + +## Gov Module + +* `DepositProcedure` 抵押阶段的参数(最小抵押金额,抵押期) +* `VotingProcedure` 投票阶段的参数(投票期) +* `TallyingProcedure` 统计阶段的参数(投票是否通过的标准) + +详细见[gov](gov.md) + +## Service Module + +* `MaxRequestTimeout` 服务调用最大等待区块个数 +* `MinProviderDeposit` 服务绑定最小抵押金额 + +详细见[service](serivice.md) diff --git a/docs/zh/features/basic-concepts/inflation.md b/docs/zh/features/basic-concepts/inflation.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/zh/features/distribution.md b/docs/zh/features/distribution.md new file mode 100644 index 000000000..398edd9e6 --- /dev/null +++ b/docs/zh/features/distribution.md @@ -0,0 +1,42 @@ +# distribution模块的用户手册 + +## 简介 + +该模块负责将收集的交易费和虚增的令牌分发给所有验证员和委托人。为了减少计算压力,引入了一种惰性分配策略。`惰性`意味着不会直接向贡献者自动支付利益。贡委托人或者验证人必须手动发送交易以取回其收益,否则,他们的收益将保留在全局收益池中。 + +## 使用场景 + +1. 设置收益取回地址 + + 委托人可能有多个irishub钱包地址。假设其中一个钱包(标记为`B`)有许多token,并且一部分token已被委托给验证人。委托人可能希望所得收益可以支付给另一个钱包,因此委托人可以清楚明白的知道有多少收益。但是,默认情况下,收益将支付给发送委托交易的钱包。如果要将另一个钱包(标记为`B`)设置为支付收益的地址,委托人需要从钱包`A`发送另一个交易。参考命令: + ```bash + iriscli distribution set-withdraw-addr [address of wallet B] --fee=0.004iris --from=[key name of wallet A] --chain-id=[chain-id] + ``` + 如果想验证设置取回地址是否成功,可以查询一下收益地址:参考命令: + ```bash + iriscli distribution withdraw-address [address of wallet A] + ``` + 如果返回结果就是钱包`B`的地址,那么设置取回地址成功。 + +2. 取回收益 + + 根据之前的叙述,我们的收益不会自动支付给我们的钱包,我们必须发送交易以提取收益。假设一个委托人自己有一个一个验证节点(标记为`validatorA`),也就是说这个委托人也是验证人;此外,它在其它两个验证人上还有委托(两个验证人标记为`validatorB`和`validatorC`)。所有委托均由钱包A创建。 + 1. 仅取回在验证人`validatorA`上的委托收益: + ```bash + iriscli distribution withdraw-rewards --only-from-validator [address of validatorA] --from [key name of wallet A] --fee=0.004iris --chain-id=[chain-id] + ``` + 2. 仅取回在所有验证人上的委托收益: + ```bash + iriscli distribution withdraw-rewards --from [key name of wallet A] --fee=0.004iris --chain-id=[chain-id] + ``` + 3. 仅取回在所有委托收益和验证人赚取的佣金: + ```bash + iriscli distribution withdraw-rewards --is-validator=true --from [key name of wallet A] --fee=0.004iris --chain-id=[chain-id] + ``` + +3. 查询收益 + + Execute the command to get the earned tokens: + ```bash + iriscli bank account [withdraw address] + ``` \ No newline at end of file diff --git a/docs/zh/features/governance.md b/docs/zh/features/governance.md new file mode 100644 index 000000000..b8a5ec07b --- /dev/null +++ b/docs/zh/features/governance.md @@ -0,0 +1,164 @@ +# Gov User Guide + +## 基本功能描述 + +1. 文本提议的链上治理 +2. 参数修改提议的链上治理 +3. 软件升级提议的链上治理 + +## 交互流程 + +### 治理流程 + +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/v0.26.0/docs/spec/governance/overview.md) + +## 使用场景 + +### 参数修改的使用场景 + +场景一:通过命令行带入参数修改信息进行参数修改 + +``` +# 根据gov模块名查询的可修改的参数 +iriscli gov query-params --module=gov --trust-node + +# 结果 +[ +"Gov/govDepositProcedure", +"Gov/govTallyingProcedure", +"Gov/govVotingProcedure" +] + +# 根据Key查询可修改参数的内容 +iriscli gov query-params --key=Gov/govDepositProcedure --trust-node + +# 结果 +{"key":"Gov/govDepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":172800000000000}","op":""} + +# 发送提议,返回参数修改的内容 +iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --param='{"key":"Gov/govDepositProcedure","value":"{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"20000000000000000000\"}],\"max_deposit_period\":172800000000000}","op":"update"}}' --from=x --chain-id=gov-test --fee=0.05iris --gas=200000 + +# 对提议进行抵押 +iriscli gov deposit --proposal-id=1 --deposit=1iris --from=x --chain-id=gov-test --fee=0.05iris --gas=200000 + +# 对提议投票 +iriscli gov vote --proposal-id=1 --option=Yes --from=x --chain-id=gov-test --fee=0.05iris --gas=200000 + +# 查询提议情况 +iriscli gov query-proposal --proposal-id=1 --trust-node + +``` + +场景二,通过文件修改参数 + +``` +# 导出配置文件 +iriscli gov pull-params --path=iris --trust-node + +# 查询配置文件信息 +cat iris/config/params.json { +"gov": { +"Gov/govDepositProcedure": { +"min_deposit": [ +{ +"denom": "iris-atto", +"amount": "10000000000000000000" +} +], +"max_deposit_period": "172800000000000" +}, +"Gov/govVotingProcedure": { +"voting_period": "10000000000" +}, +"Gov/govTallyingProcedure": { +"threshold": "0.5000000000", +"veto": "0.3340000000", +"participation": "0.6670000000" +} +} + +# 修改配置文件 (TallyingProcedure的governance_penalty) +vi iris/config/params.json { +"gov": { +"Gov/govDepositProcedure": { +"min_deposit": [ +{ +"denom": "iris-atto", +"amount": "10000000000000000000" +} +], +"max_deposit_period": "172800000000000" +}, +"Gov/govVotingProcedure": { +"voting_period": "10000000000" +}, +"Gov/govTallyingProcedure": { +"threshold": "0.5000000000", +"veto": "0.3340000000", +"participation": "0.4990000000" +} +} + +# 通过文件修改参数的命令,返回参数修改的内容 +iriscli gov submit-proposal --title="update MinDeposit" --description="test" --type="ParameterChange" --deposit="10iris" --path=iris --key=Gov/govTallyingProcedure --op=update --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# 对提议进行抵押 +iriscli gov deposit --proposal-id=1 --deposit=1iris --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 + +# 对提议投票 +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 +``` + +### 软件升级提议部分 + +详细参考[Upgrade](upgrade.md) + +## 基本参数 + + +``` +# DepositProcedure(抵押阶段的参数) +"Gov/govDepositProcedure": { +"min_deposit": [ +{ +"denom": "iris-atto", +"amount": "10000000000000000000" +} +], +"max_deposit_period": "172800000000000" +} +``` + +* 可修改参数 +* 参数的key:"Gov/gov/DepositProcedure" +* `min_deposit[0].denom` 最小抵押token只能是单位是iris-atto的iris通证。 +* `min_deposit[0].amount` 最小抵押token数量,默认:10iris,范围(1iris,200iris) +* `max_deposit_period` 补交抵押token的窗口期,默认:172800000000000纳秒==2天,范围(20秒,3天) + +``` +# VotingProcedure(投票阶段的参数) +"Gov/govVotingProcedure": { +"voting_period": "10000000000" +} +``` +* 可修改参数 +* `voting_perid` 投票的窗口期,默认:172800000000000纳秒==2天,范围(20秒,3天) + +``` +# TallyingProcedure (统计阶段段参数) +"Gov/govTallyingProcedure": { +"threshold": "0.5000000000", +"veto": "0.3340000000", +"participation": "0.6670000000" +} +``` +* 可修改参数 +* `veto` 默认:0.334,范围(0,1) +* `threshold` 默认:0.500,范围(0,1) +* `participation` 默认:0.667,范围(0,1) +* 投票统计逻辑:如果所有投票者的`voting_power`占系统总的`voting_power`的比例没有超过participation,投票不通过。如果强烈反对的`voting_power`占所有投票者的`voting_power` 超过 veto,提议不通过。然后再看赞同的`voting_power`占排除投弃权以外的投票者的总`voting_power` 是否超过 threshold, 超过则提议通过,不超过则不通过。 diff --git a/docs/zh/features/lcd.md b/docs/zh/features/lcd.md new file mode 100644 index 000000000..c335a59d8 --- /dev/null +++ b/docs/zh/features/lcd.md @@ -0,0 +1,113 @@ +# IRISLCD用户文档 + +## 基本功能介绍 + +1.提供restful API以及swagger-ui +2.验证查询结果的有效性 + +## 使用场景 + +假设有一个正在运行的IRISLCD节点,其swagger-ui页面url是`localhost:1317/swagger-ui/`。IRISLCD用户文档的默认home目录是`$HOME/.irislcd`。IRISLCD启动以后,首先它将在其主文件夹中创建存储密钥的文件。如果IRISLCD运行在非信任模式下,它将获取当前区块作为其信任基础,并且将其保存到其home目录下的`trust-base.db`。IRISLCD节点始终无条件信任这个区块。它将根据这个区块的验证人集合来验证此后所有查询结果,这意味着IRISLCD只能验证其信任区块之后的区块信息和交易。这也是IRISLCD的缺陷。当它尝试验证较低高度的某些交易和区块时,会有错误返回。因此,如果您想查询早期的区块和交易时,请以信任模式启动IRISLCD。有关详细的查询结果的验证算法,请参阅此[文档](https://github.com/tendermint/tendermint/blob/master/docs/tendermint-core/light-client-protocol.md)。 + +IRISLCD节点成功启动后,在浏览器中打开`localhost1317/swagger-ui/`,您可以看到所有REST APIs。 + +1. Tendermint相关APIs, 例如查询区块,交易和验证人集 + 1. `GET /node_info`: 查询所连接全节点的信息 + 2. `GET /syncing`: 查询所连接全节点是否处于追赶区块的状态 + 3. `GET /blocks/latest`: 获取最新区块 + 4. `GET /blocks/{height}`: 获取某一高度的区块 + 5. `GET /validatorsets/latest`: 获取最新的验证人集合 + 6. `GET /validatorsets/{height}`: 获取某一高度的验证人集合 + 7. `GET /txs/{hash}`: 通过交易hash查询交易 + 8. `GET /txs`: 搜索交易 + 9. `POST /txs`: 广播交易 + +2. Key management APIs + + 1. `GET /keys`: 列出所有本地的秘钥 + 2. `POST /keys`: 创建新的秘钥 + 3. `GET /keys/seed`: 创建新的助记词 + 4. `GET /keys/{name}`: 根据秘钥名称查询秘钥 + 5. `PUT /keys/{name}`: 更新秘钥的密码 + 6. `DELETE /keys/{name}`: 删除秘钥 + 7. `GET /auth/accounts/{address}`: 查询秘钥对象账户的信息 + +3. Create, sign and broadcast transactions + + 1. `POST /tx/sign`: 签名交易 + 2. `POST /tx/broadcast`: 广播一个amino编码的交易 + 3. `POST /txs/send`: 广播一个非amino编码的交易 + 4. `GET /bank/coin/{coin-type}`: 查询coin的类型信息 + 5. `GET /bank/balances/{address}`: 查询账户的token数量 + 6. `POST /bank/accounts/{address}/transfers`: 发起转账交易 + +4. Stake module APIs + + 1. `POST /stake/delegators/{delegatorAddr}/delegate`: 发起委托交易 + 2. `POST /stake/delegators/{delegatorAddr}/redelegate`: 发起转委托交易 + 3. `POST /stake/delegators/{delegatorAddr}/unbond`: 发起解委托交易 + 4. `GET /stake/delegators/{delegatorAddr}/delegations`: 查询委托人的所有委托记录 + 5. `GET /stake/delegators/{delegatorAddr}/unbonding_delegations`: 查询委托人的所有解委托记录 + 6. `GET /stake/delegators/{delegatorAddr}/redelegations`: 查询委托人的所有转委托记录 + 7. `GET /stake/delegators/{delegatorAddr}/validators`: 查询委托人的所委托的所有验证人 + 8. `GET /stake/delegators/{delegatorAddr}/validators/{validatorAddr}`: 查询某个被委托的验证人上信息 + 9. `GET /stake/delegators/{delegatorAddr}/txs`: 查询所有委托人相关的委托交易 + 10. `GET /stake/delegators/{delegatorAddr}/delegations/{validatorAddr}`: 查询委托人在某个验证人上的委托记录 + 11. `GET /stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}`: 查询委托人在某个验证人上所有的解委托记录 + 12. `GET /stake/validators`: 获取所有委托人信息 + 13. `GET /stake/validators/{validatorAddr}`: 获取某个委托人信息 + 14. `GET /stake/validators/{validatorAddr}/unbonding_delegations`: 获取某个验证人上的所有解委托记录 + 15. `GET /stake/validators/{validatorAddr}/redelegations`: 获取某个验证人上的所有转委托记录 + 16. `GET /stake/pool`: 获取权益池信息 + 17. `GET /stake/parameters`: 获取权益证明的参数 + +5. Governance module APIs + + 1. `POST /gov/proposal`: 发起提交提议交易 + 2. `GET /gov/proposals`: 查询提议 + 3. `POST /gov/proposals/{proposalId}/deposits`: 发起缴纳押金的交易 + 4. `GET /gov/proposals/{proposalId}/deposits`: 查询缴纳的押金 + 5. `POST /gov/proposals/{proposalId}/votes`: 发起投票交易 + 6. `GET /gov/proposals/{proposalId}/votes`: 查询投票 + 7. `GET /gov/proposals/{proposalId}`: 查询某个提议 + 8. `GET /gov/proposals/{proposalId}/deposits/{depositor}`:查询押金 + 9. `GET /gov/proposals/{proposalId}/votes/{voter}`: 查询投票 + 10. `GET/gov/params`: 查询可供治理的参数 + +6. Slashing module APIs + + 1. `GET /slashing/validators/{validatorPubKey}/signing_info`: 获取验证人的签名记录 + 2. `POST /slashing/validators/{validatorAddr}/unjail`: 赦免某个作恶的验证人节点 + +7. Distribution module APIs + + 1. `POST /distribution/{delegatorAddr}/withdrawAddress`: 设置收益取回地址 + 2. `GET /distribution/{delegatorAddr}/withdrawAddress`: 查询收益取回地址 + 3. `POST /distribution/{delegatorAddr}/withdrawReward`: 取回收益 + 4. `GET /distribution/{delegatorAddr}/distrInfo/{validatorAddr}`: 查询某个委托的收益分配信息 + 5. `GET /distribution/{delegatorAddr}/distrInfos`: 查询委托人所有委托的收益分配信息 + 6. `GET /distribution/{validatorAddr}/valDistrInfo`: 查询验证人的收益分配信息 + +8. Query app version + + 1. `GET /version`: 获取IRISHUB的版本 + 2. `GET /node_version`: 查询全节点版本 + +## Options for post apis + +1. `POST /bank/accounts/{address}/transfers` +2. `POST /stake/delegators/{delegatorAddr}/delegate` +3. `POST /stake/delegators/{delegatorAddr}/redelegate` +4. `POST /stake/delegators/{delegatorAddr}/unbond` +5. `POST /gov/proposal` +6. `POST /gov/proposals/{proposalId}/deposits` +7. `POST /gov/proposals/{proposalId}/votes` +8. `POST /slashing/validators/{validatorAddr}/unjail` + +| 参数名字 | 类型 | 默认值 | 优先级 | 功能描述 | +| --------------- | ---- | ------- |--------- |--------------------------- | +| generate-only | bool | false | 0 | 构建一个未签名的交易并返回 | +| simulate | bool | false | 1 | 用仿真的方式去执行交易 | +| async | bool | false | 2 | 用异步地方式广播交易 | + +以上八个APIs都有三个额外的查询参数,如上表所示。默认情况下,它们的值都是false。每个参数都有其唯一的优先级(这里`0`是最高优先级)。 如果指定了多个参数,则将忽略优先级较低的参数。 例如,如果`generate-only`为真,那么其他参数,例如`simulate`和`async`将被忽略。 \ No newline at end of file diff --git a/docs/zh/features/mint.md b/docs/zh/features/mint.md new file mode 100644 index 000000000..15a73855c --- /dev/null +++ b/docs/zh/features/mint.md @@ -0,0 +1,36 @@ +# IRISLCD用户文档 + +## 介绍 + +POW共识网络的激励机制十分简明:一旦新的区块产生,那么区块的产生者将会获得一定数量的token作为出块奖励。我们IRISHUB是POS区块链网络,这里的激励机制相对复杂很多。 + +按照字面意思,POW就是工作量证明。在每个区块生成期间,所有矿工竞争计算工作证明,最快计算出结果的矿工将成为赢家。实际上,所有失败的矿工都没有向优胜者矿工提供任何积极的帮助或合作,他们只是竞争对手。因此,向获胜者矿工授予所有奖励是合理的。但是,在POS区块链网络中,我们不能这样做。因为每个块生成过程都是所有验证人和委托人的协作,这意味着所有这些贡献者应该共享出块收益。出块收益有两个来源,一个是区块中打包的交易的交易费;另一个就是定时的通胀,通胀多出来的token作为出块奖励。 + +至于如何将通胀的token分发给贡献者,我们将在distribution模块中详细解说。在这里,我们主要介绍如何计算通胀的数量以及对用户的影响。 + +## 计算通胀 + +与POW网络不同,我们这里的收益不会直接支付给贡献者。有当贡献者明确发送交易以提取奖励时,才会将通胀令牌转移到用户指定的地址。此外,token通胀每小时触发一次,新生成的token将保存在全局池中。 + +### 区块时间 + +区块时间不是机器时间,因为不同机器的时间不可能完全相同。 他们必须或多或少地有一些偏差,这将导致不确定性。 这里的时间是指BFT时间。 有关详细说明,请参阅[tendermint bft-time](https://github.com/tendermint/tendermint/blob/master/docs/spec/consensus/bft-time.md)。 + +### 通胀率 + +通胀率取决于有多大比例的token被绑定,被绑定的token的比例一直会变,那么这个通胀的比例也会一直在变。理想的绑定比率是67%,如果这个比率更高,通胀率将下降。相反,如果绑定比率较低,通胀率将会增加。此外,通胀率不应超过20%且不低于7%。例如,当计算出的通胀率高于20%,那么我们强制把通胀率置为20%。 + +假设计算出的通胀率为10%,总token金额为10000iris,则通胀token为0.114iris(10000iris*10%/8766,一年有8766小时)。在此通胀之后,总token金额将为10000.114iris。 + +## 对用户的影响 + +通胀计算是一个自动过程。没有接口可用用户来干预此过程。但是,用户可以发送委托或解委托交易来改变绑定比率,从而改变通胀率会。此外,通胀过程将增加总token金额。用户可以通过此命令获取总token数量: +``` +ubuntu@ubuntu:~$ iriscli stake pool --node=<iris node url> +Pool +Loose Tokens: 200.1186409166 +Bonded Tokens: 400.0000000000 +Token Supply: 600.1186409166 +Bonded Ratio: 0.6665348695 +``` + diff --git a/docs/zh/modules/record/README.md b/docs/zh/features/record.md similarity index 100% rename from docs/zh/modules/record/README.md rename to docs/zh/features/record.md diff --git a/docs/zh/features/service.md b/docs/zh/features/service.md new file mode 100644 index 000000000..66752cb68 --- /dev/null +++ b/docs/zh/features/service.md @@ -0,0 +1,210 @@ +# Service User Guide + +## 基本功能描述 +IRIS Services(又名“iServices”)旨在对链下服务从定义、绑定(服务提供方注册)、调用到治理(分析和争端解决)的全生命周期传递,来跨越区块链世界和传统业务应用世界之间的鸿沟。 +IRIS SDK通过增强的IBC处理逻辑来支持服务语义,以允许分布式商业服务在区块链互联网上可用。我们引入接口描述语言([Interface description language](https://en.wikipedia.org/wiki/Interface_description_language), +简称IDL)对服务进行进行标准化的定义来满足跨语言的服务调用。目前支持的IDL语言为[protobuf](https://developers.google.com/protocol-buffers/)。该模块的主要功能点如下: +1. 服务定义 +2. 服务绑定 +3. 服务调用 (TODO) +4. 争议解决 (TODO) +5. 服务分析 (TODO) + +## 交互流程 + +### 服务定义流程 + +1. 任何用户可以发起服务定义请求,在服务定义中,使用`protobuf`对该服务的方法,方法的输入、输出参数进行标准化定义。 + +## 使用场景 +### 创建使用环境 + +``` +rm -rf iris +rm -rf .iriscli +iris init gen-tx --name=x --home=iris +iris init --gen-txs --chain-id=service-test -o --home=iris +iris start --home=iris +``` + +### 服务定义 + +``` +# 服务定义 +iriscli service define --chain-id=service-test --from=x --fee=0.004iris --service-name=test-service --service-description=service-description --author-description=author-description --tags=tag1,tag2 --idl-content=<idl-content> --file=test.proto + +# 结果 +Committed at block 92 (tx hash: A63241AA6666B8CFE6B1C092B707AB0FA350F108, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:8007 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 100 101 102 105 110 101]} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[49 54 48 49 52 48 48 48 48 48 48 48 48 48 48]}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-define", + "completeConsumedTxFee-iris-atto": "160140000000000" + } +} + +# 查询服务定义 +iriscli service definition --def-chain-id=service-test --service-name=test-service + +``` + +### 服务绑定 +``` +# 服务绑定 +iriscli service bind --chain-id=service-test --from=x --fee=0.004iris --service-name=test-service --def-chain-id=service-test --bind-type=Local --deposit=1iris --prices=1iris --avg-rsp-time=10000 --usable-time=100 + +# 结果 +Committed at block 168 (tx hash: 02CAC60E75CD93465CAE10CE35F30B53C8A95574, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:5437 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 98 105 110 100]} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[49 48 56 55 52 48 48 48 48 48 48 48 48 48 48]}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-bind", + "completeConsumedTxFee-iris-atto": "108740000000000" + } +} + +# 查询服务绑定 +iriscli service binding --def-chain-id=service-test --service-name=test-service --bind-chain-id=service-test --provider=<your address> + +# 查询服务绑定列表 +iriscli service bindings --def-chain-id=service-test --service-name=test-service + +# 服务绑定更新 +iriscli service update-binding --chain-id=service-test --from=x --fee=0.004iris --service-name=test-service --def-chain-id=service-test --bind-type=Local --deposit=1iris --prices=1iris,2iris --avg-rsp-time=10000 --usable-time=100 + +# 结果 +Committed at block 233 (tx hash: 2F5F44BAF09981D137EA667F9E872EB098A9B619, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:4989 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 98 105 110 100 105 110 103 45 117 112 100 97 116 101]} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[57 57 55 56 48 48 48 48 48 48 48 48 48 48]}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-binding-update", + "completeConsumedTxFee-iris-atto": "99780000000000" + } +} + +# 禁用服务绑定 +iriscli service disable --chain-id=service-test --from=x --fee=0.004iris --def-chain-id=service-test --service-name=test-service + +# 结果 +Committed at block 241 (tx hash: 0EF936E1228F9838D0343D0FB3613F5E938602B7, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:4861 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 100 105 115 97 98 108 101] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 57 55 50 50 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-disable", + "completeConsumedTxFee-iris-atto": "\"97220000000000\"" + } +} + +# 开启服务绑定 +iriscli service enable --chain-id=service-test --from=x --fee=0.004iris --def-chain-id=service-test --service-name=test-service --deposit=1iris + +# 结果 +Committed at block 176 (tx hash: 74AE647B8A311501CA82DACE90AA28CDB4695803, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:6330 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 101 110 97 98 108 101] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[34 49 50 54 54 48 48 48 48 48 48 48 48 48 48 48 34] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-enable", + "completeConsumedTxFee-iris-atto": "\"126600000000000\"" + } +} + + +# 取回押金 +iriscli service refund-deposit --chain-id=service-test --from=x --fee=0.004iris --def-chain-id=service-test --service-name=test-service + +# 结果 +Committed at block 1563 (tx hash: 748CEA6EA9DEFB384FFCFBE68A3CB6D8B643361B, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:5116 Tags:[{Key:[97 99 116 105 111 110] Value:[115 101 114 118 105 99 101 45 114 101 102 117 110 100 45 100 101 112 111 115 105 116]} {Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[49 48 50 51 50 48 48 48 48 48 48 48 48 48 48]}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) +{ + "tags": { + "action": "service-refund-deposit", + "completeConsumedTxFee-iris-atto": "102320000000000" + } +} +``` + +## 命令详情 + +``` +iriscli service define --chain-id=service-test --from=x --fee=0.004iris --service-name=test-service --service-description=service-description --author-description=author-description --tags=tag1,tag2 --idl-content=<idl-content> --file=test.proto +``` +* `--service-name` 该服务名称 +* `--service-description` 该服务的描述 +* `--author-description` 该服务创建者的描述. 可选 +* `--tags` 该服务的关键字 +* `--idl-content` 对该服务的methods的标准化定义内容 +* `--file` 可使用文件代替idl-content,当该项不为空时,覆盖`idl-content`内容 + +``` +iriscli service definition --def-chain-id=service-test --service-name=test-service +``` +* `--def-chain-id` 定义该服务的区块链ID +* `--service-name` 服务名称 + +``` +iriscli service bind --chain-id=service-test --from=x --fee=0.004iris --service-name=test-service --def-chain-id=service-test --bind-type=Local --deposit=1iris --prices=1iris --avg-rsp-time=10000 --usable-time=100 +``` +* `--def-chain-id` 定义该服务的区块链ID +* `--service-name` 服务名称 +* `--bind-type` 对服务是本地还是全局的设置,可选值Local/Global +* `--deposit` 服务提供者的保证金 +* `--prices` 服务定价,按照服务方法排序的定价列表 +* `--avg-rsp-time` 服务平均返回时间的毫秒数表示 +* `--usable-time` 每一万次服务调用的可用性的整数表示 + +``` +iriscli service binding --def-chain-id=service-test --service-name=test-service --bind-chain-id=service-test --provider=<your address> +``` +* `--def-chain-id` 定义该服务的区块链ID +* `--service-name` 服务名称 +* `--bind-chain-id` 绑定该服务的区块链ID +* `--provider` 服务提供者的区块链地址(bech32编码) + +``` +iriscli service bindings --def-chain-id=service-test --service-name=test-service +``` +* 参照iriscli service binding + +``` +iriscli service update-binding --chain-id=service-test --from=x --fee=0.004iris --service-name=test-service --def-chain-id=service-test --bind-type=Local --deposit=1iris --prices=1iris,2iris --avg-rsp-time=10000 --usable-time=100 +``` +* `--def-chain-id` 定义该服务的区块链ID +* `--service-name` 服务名称 +* `--bind-type` 对服务是本地还是全局的设置,可选值Local/Global +* `--deposit` 追加的服务提供者保证金 +* `--prices` 服务定价,按照服务方法排序的定价列表 +* `--avg-rsp-time` 服务平均返回时间的毫秒数表示 +* `--usable-time` 每一万次服务调用可用次数的整数表示 + +``` +iriscli service disable --chain-id=service-test --from=x --fee=0.004iris --def-chain-id=service-test --service-name=test-service +``` +* `--def-chain-id` 定义该服务的区块链ID +* `--service-name` 服务名称 + +``` +iriscli service enable --chain-id=service-test --from=x --fee=0.004iris --def-chain-id=service-test --service-name=test-service --deposit=1iris +``` +* `--def-chain-id` 定义该服务的区块链ID +* `--service-name` 服务名称 +* `--deposit` 追加的服务提供者保证金 + +``` +iriscli service refund-deposit --chain-id=service-test --from=x --fee=0.004iris --def-chain-id=service-test --service-name=test-service +``` +* `--def-chain-id` 定义该服务的区块链ID +* `--service-name` 服务名称 + +## IDL文件扩展 +在使用proto文件对服务的方法,输入、输出参数进行标准化定义时,可通过注释的方式增加method属性。 + +### 注释标准 +* 使用 `//@Attribute 属性: 值`的方式添加在rpc方法上,即可将该属性添加为方法的属性。例如: +> //@Attribute description: sayHello + +### 目前支持的属性 +* `description` 对该方法的描述 +* `output_privacy` 是否对该方法的输出进行加密处理,{`NoPrivacy`,`PubKeyEncryption`} +* `output_cached` 是否对该方法的输出进行缓存,{`OffChainCached`,`NoCached`} + +### IDL content参照 +* IDL content参照 +> syntax = \"proto3\";\n\npackage helloworld;\n\n// The greeting service definition.\nservice Greeter {\n //@Attribute description: sayHello\n //@Attribute output_privacy: NoPrivacy\n //@Attribute output_cached: NoCached\n rpc SayHello (HelloRequest) returns (HelloReply) {}\n}\n\n// The request message containing the user's name.\nmessage HelloRequest {\n string name = 1;\n}\n\n// The response message containing the greetings\nmessage HelloReply {\n string message = 1;\n}\n + +* IDL文件参照 + +[test.proto](../../features/test.proto) \ No newline at end of file diff --git a/docs/zh/features/stake.md b/docs/zh/features/stake.md new file mode 100644 index 000000000..ca8014141 --- /dev/null +++ b/docs/zh/features/stake.md @@ -0,0 +1,7 @@ +# Stake用户手册 + +## 介绍 + +本文简要介绍了stake模块的功能以及常见用户接口。 + +## 核心概念 (TODO) \ No newline at end of file diff --git a/docs/zh/modules/upgrade/README.md b/docs/zh/features/upgrade.md similarity index 100% rename from docs/zh/modules/upgrade/README.md rename to docs/zh/features/upgrade.md diff --git a/docs/zh/get-started/Bech32-on-IRISnet.md b/docs/zh/get-started/Bech32-on-IRISnet.md deleted file mode 100644 index a62927bb4..000000000 --- a/docs/zh/get-started/Bech32-on-IRISnet.md +++ /dev/null @@ -1,36 +0,0 @@ -# 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/get-started/Download-Rainbow.md b/docs/zh/get-started/Download-Rainbow.md new file mode 100644 index 000000000..1dd243942 --- /dev/null +++ b/docs/zh/get-started/Download-Rainbow.md @@ -0,0 +1,7 @@ +# IRISnet 钱包: Rainbow + +## Raibow是什么? + +第一个支持跨链多资产转移及服务消费的IRISnet移动客户端公测即将开启,敬请期待... + +https://www.rainbow.one \ 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 index 367a75e74..e4909b0fd 100644 --- a/docs/zh/get-started/Genesis-Generation-Process.md +++ b/docs/zh/get-started/Genesis-Generation-Process.md @@ -1,70 +1,81 @@ -# 参与Genesis文件生成 +# 参与到Genesis文件生成流程中 -1. 每个希望成为验证人的参与者确保请根据一下[教程](Install-Iris.md) 在服务器上完成**Iris**的安装。 +1. 每个希望成为验证人的参与者确保安装了对应版本的软件:iris v0.7.0 -2. 执行gentx命令,获得一个node-id.json的文件。这个操作将默认生成一个余额为200IRIS的账户,该账户默认绑定100IRIS成为一个验证人候选人。 +2. 先创建账户,再执行gentx命令,获得一个gentx-node-ID.json的文件。这个操作将默认生成一个余额为150IRIS的账户,该账户默认绑定100IRIS成为一个验证人候选人。 ``` -iris init gen-tx --name=your_name --home=<path_to_home> --ip=Your_public_IP -``` -* 代码示例: -``` -iris init gen-tx --name=alice +iriscli keys add your_name +iris gentx --name=your_name --home=<path_to_home> --ip=Your_public_IP ``` +代码示例: + +``` +iriscli keys add alice +iris gentx --name=alice --home=iris --chain-id=irishub-stage --ip=1.1.1.1 ``` - { - "app_message": { - "secret": "village venue about lend pause popular vague swarm blue unusual level drastic field broken moral north repair blue accident miss essay loan rail harbor" - }, - "gen_tx_file": { - "node_id": "1b45f5bb7ba1e00be01e8795dcaa0e8008f28cb5", - "ip": "192.168.150.206", - "validator": { - "pub_key": { - "type": "tendermint/PubKeyEd25519", - "value": "NlMcGgz05K45ukGY10R8DApp8A0N0Jv4F2/OKtq9fCU=" - }, - "power": "100", - "name": "" - }, - "app_gen_tx": { - "name": "tom", - "address": "faa1mmnaknf87p7uu80m6uthyssd2ge0s73hcfr05h", - "pub_key": "fap1zcjduepqxef3cxsv7nj2uwd6gxvdw3rups9xnuqdphgfh7qhdl8z4k4a0sjsxh3kgg" - } - } - } - ``` 然后你可以发现在$IRISHOME/config目录下生成了一个gentx文件夹。里面存在一个gentx-node-ID.json文件。这个文件包含了如下信息: ``` { - "node_id": "612db83e7facdd9abab879f7e465ed829f3f3487", - "ip": "192.168.150.223", - "validator": { - "pub_key": { - "type": "tendermint/PubKeyEd25519", - "value": "bzLIySQ4YDwBIkTgeyrnBx7VEoQ23zDnWhIV4FEEOZ4=" - }, - "power": "100", - "name": "" + "type": "auth/StdTx", + "value": { + "msg": [ + { + "type": "cosmos-sdk/MsgCreateValidator", + "value": { + "Description": { + "moniker": "chenggedexiaokeai.local", + "identity": "", + "website": "", + "details": "" + }, + "Commission": { + "rate": "0.1000000000", + "max_rate": "0.2000000000", + "max_change_rate": "0.0100000000" + }, + "delegator_address": "faa1cf25tf4pfjdhkzx8lqnkajlse6jcpm2fyw4yme", + "validator_address": "fva1cf25tf4pfjdhkzx8lqnkajlse6jcpm2f3lltx7", + "pubkey": { + "type": "tendermint/PubKeyEd25519", + "value": "/JvLFsvyMgm2ND4QgN4JKyLxhL42dVgat67383Q+mPY=" + }, + "delegation": { + "denom": "iris-atto", + "amount": "100000000000000000000" + } + } + } + ], + "fee": { + "amount": null, + "gas": "200000" }, - "app_gen_tx": { - "name": "haoyang-virtualbox2", - "address": "faa1k96h5cyppg6q2meftv6epuw39u5dd0sa8t84fv", - "pub_key": "fap1zcjduepqduev3jfy8psrcqfzgns8k2h8qu0d2y5yxm0npe66zg27q5gy8x0qh7wt9l" - } + "signatures": [ + { + "pub_key": { + "type": "tendermint/PubKeySecp256k1", + "value": "AtfNRj0zYvffAQG+iad6SScfdl29ag9G3EI0JDSwKJmy" + }, + "signature": "BwTejBceK4M+3LzmNl62jVFUr9wVv//UO7iI/yWi5KFoez9eY43HSlaZJf+3rnKLjosn2tD79EIw55BJ6SbYzQ==", + "account_number": "0", + "sequence": "0" + } + ], + "memo": "0eb02fdabb96923ac1e855ac012a5a624793264a@1.1.1.1:26656" } +} ``` -validator字段对应了home/config下的节点信息 -`app_gen_tx`中说明了拥有这个节点的账户信息。这个账户的助记词就是刚刚的secret +`msg` 是创建验证人节点的交易 + +3. 将上述提到的json文件以提交Pull Request的形式上传到`https://github.com/irisnet/testnets/tree/master/testnets/fuxi-5000/config/gentx`目录下: + + 注意⚠️:json文中的IP改成公网IP -3. 将上述提到的json文件以提交Pull Request的形式上传到`https://github.com/irisnet/testnets/tree/master/fuxi/fuxi-4000/config/gentx`目录下: -> 注意:json文中的IP改成公网IP -4. 在收集完参与者的gentx文件后,团队将在一下目录公布fuxi-4000测试网的配置文件:`https://github.com/irisnet/testnets/tree/master/fuxi/fuxi-4000/config`。然后你就可以下载genesis.json和config.toml文件了。 diff --git a/docs/zh/get-started/Install-Iris.md b/docs/zh/get-started/Install-the-Software.md similarity index 100% rename from docs/zh/get-started/Install-Iris.md rename to docs/zh/get-started/Install-the-Software.md diff --git a/docs/zh/get-started/Join-the-Testnet.md b/docs/zh/get-started/Join-the-Testnet.md new file mode 100644 index 000000000..247de4868 --- /dev/null +++ b/docs/zh/get-started/Join-the-Testnet.md @@ -0,0 +1,52 @@ +IRISnet测试网 + +IRIShub 简介 + +IRIS Hub是在Cosmos生态中的区域性枢纽,提供iService服务 + +如何加入fuxi测试网 + +第一步: 安装IRIShub + +请根据一下教程 在服务器上完成Iris的安装。 + +第二步: 运行一个全节点 + +请根据一下步骤 完成初始化并开始在服务器上运行一个全节点。 + +第三步: 将全节点升级成为一个验证人节点 + +请根据以下步骤 将一个全节点升级成为验证人节点。 + +部署IRISHub Monitor监控 + +请根据以下链接 在服务器上部署一个Monitor监控。 + +如何成为一个验证人节点 + +如何你的节点已经完全同步了,那么要如何才能升级成为一个验证人节点你? + +如果你参与到了genesis文件的生成过程中,那么只要你的节点与网络同时启动,它就会保持验证人的状态。 + +如果你并没有参与到genesis文件的生成过程中,那么你依然可以通过执行相关操作升级成为一个验证人。目前IRIShub的验证人上限是100。升级的流程在这里. + +部署哨兵节点 + +验证人有遭受攻击的风险。你可以根据以下教程部署一个哨兵节点来保护验证人。 + +Fuxi测试网激励计划 + +IRIS基金会通过推出测试网激励计划来鼓励更多的人加入到Fuxi测试网中。在Fuxi-2000中,我们针对中国社区发布了测试网激励任务。一共有14位社区成员完成了任务。 + +Fuxi-2000 任务列表: https://github.com/irisnet/testnets/blob/master/fuxi/fuxi-2000/README.md + +Fuxi-2000 任务完成情况:https://github.com/irisnet/testnets/issues/51 + +在Fuxi-3001测试网中, IRIS基金会决定推出更多的测试网激励计划。 + +Fuxi-3001任务列表: https://github.com/irisnet/testnets/blob/master/fuxi/fuxi-3001/README.md + +更多链接 + +- Explorer: https://testnet.irisplorer.io/#/home +- Riot chat: #irisvalidators:matrix.org diff --git a/docs/zh/get-started/Validator-Node.md b/docs/zh/get-started/Validator-Node.md index f837b7291..d45a23218 100644 --- a/docs/zh/get-started/Validator-Node.md +++ b/docs/zh/get-started/Validator-Node.md @@ -124,4 +124,4 @@ iriscli stake validator < address-validator-operator > --chain-id=fuxi-4000 ### 部署IRISHub Monitor监控 -请根据以下[链接](../tools/Deploy-IRIS-Monitor.md) 部署一个Monitor监控验证人。 +请根据以下[链接](../../tools/Deploy-IRIS-Monitor.md) 部署一个Monitor监控验证人。 diff --git a/docs/zh/get-started/irislcd.md b/docs/zh/get-started/irislcd.md deleted file mode 100644 index 5012ecb95..000000000 --- a/docs/zh/get-started/irislcd.md +++ /dev/null @@ -1,36 +0,0 @@ -# 介绍 - -irislcd是一个能连接到任何全节点并且提供rest API接口的服务。通过这些API接口,用户可以发起交易或者查询区块链上的数据。irislcd可以验证全节点返回数据的完整性和有效性,因此irislcd可以以最小的带宽资源,最小的计算需求和最小的存储消耗来获取可全节点一样的数据安全。另外,irislcd还提供swagger-ui页面,这个页面列出来所以得API接口并且附有详细的说明文档。 - -## Irislcd options - -irislcd有如下这些参数可以配置 - -| 参数名 | 类型 | 默认值 | 是否必须 | 功能介绍 | -| --------------- | --------- | ----------------------- | -------- | ---------------------------------------------------- | -| chain-id | 字符串 | null | true | 所连接的tendermint区块链网络的ID | -| home | 字符串 | "$HOME/.irislcd" | false | irislcd的home目录,用来存储秘钥和历史验证信息 | -| node | 字符串 | "tcp://localhost:26657" | false | 所要连接的全节点的url | -| laddr | 字符串 | "tcp://localhost:1317" | false | 侦听的网络端口 | -| trust-node | 布尔型 | false | false | 是否信任全节点 | -| max-open | 整型 | 1000 | false | 最大支持的连接数 | -| cors | 字符串 | "" | false | 是否支持跨域请求 | - -## Start Irislcd - -启动irislcd: -``` -irislcd start --chain-id=<chain-id> -``` -在浏览器中访问以下的url就可以打开Swagger-UI: -``` -http://localhost:1317/swagger-ui/ -``` -打印版本号. -``` -irislcd version -``` -如果所连接的全节点是可信的,可以加上`trust-node`: -``` -irislcd start --chain-id=<chain-id> --trust-node -``` diff --git a/docs/zh/introduction/README.md b/docs/zh/introduction/README.md new file mode 100644 index 000000000..857e7dd82 --- /dev/null +++ b/docs/zh/introduction/README.md @@ -0,0 +1,8 @@ +# Introduction + +## The IRIS hub + +## The IRIS Service + +## The IRIS Network + diff --git a/docs/zh/introduction/The-IRIS-Hub/Delegators.md b/docs/zh/introduction/The-IRIS-Hub/Delegators.md new file mode 100644 index 000000000..c8b484c90 --- /dev/null +++ b/docs/zh/introduction/The-IRIS-Hub/Delegators.md @@ -0,0 +1 @@ +# Delegators diff --git a/docs/zh/introduction/The-IRIS-Hub/IRIS-Tokens.md b/docs/zh/introduction/The-IRIS-Hub/IRIS-Tokens.md new file mode 100644 index 000000000..61d1755e3 --- /dev/null +++ b/docs/zh/introduction/The-IRIS-Hub/IRIS-Tokens.md @@ -0,0 +1 @@ +# IRIS Tokens diff --git a/docs/zh/introduction/The-IRIS-Hub/Proof-of-Stake.md b/docs/zh/introduction/The-IRIS-Hub/Proof-of-Stake.md new file mode 100644 index 000000000..7ec980837 --- /dev/null +++ b/docs/zh/introduction/The-IRIS-Hub/Proof-of-Stake.md @@ -0,0 +1 @@ +# Proof of Stake diff --git a/docs/zh/introduction/The-IRIS-Hub/Validators.md b/docs/zh/introduction/The-IRIS-Hub/Validators.md new file mode 100644 index 000000000..e41e267fe --- /dev/null +++ b/docs/zh/introduction/The-IRIS-Hub/Validators.md @@ -0,0 +1 @@ +# Validators diff --git a/docs/zh/introduction/The-IRIS-Network/README.md b/docs/zh/introduction/The-IRIS-Network/README.md new file mode 100644 index 000000000..8756dfd6a --- /dev/null +++ b/docs/zh/introduction/The-IRIS-Network/README.md @@ -0,0 +1 @@ +# The IRIS Network diff --git a/docs/zh/introduction/The-IRIS-Service/Consumers.md b/docs/zh/introduction/The-IRIS-Service/Consumers.md new file mode 100644 index 000000000..3476d964e --- /dev/null +++ b/docs/zh/introduction/The-IRIS-Service/Consumers.md @@ -0,0 +1 @@ +# Consumers diff --git a/docs/zh/introduction/The-IRIS-Service/Lifecycle.md b/docs/zh/introduction/The-IRIS-Service/Lifecycle.md new file mode 100644 index 000000000..75a17e1af --- /dev/null +++ b/docs/zh/introduction/The-IRIS-Service/Lifecycle.md @@ -0,0 +1 @@ +# Lifecycle diff --git a/docs/zh/introduction/The-IRIS-Service/Providers.md b/docs/zh/introduction/The-IRIS-Service/Providers.md new file mode 100644 index 000000000..ae4c68601 --- /dev/null +++ b/docs/zh/introduction/The-IRIS-Service/Providers.md @@ -0,0 +1 @@ +# Providers diff --git a/docs/zh/light-client/README.md b/docs/zh/light-client/README.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/zh/modules/gov/README.md b/docs/zh/modules/gov/README.md deleted file mode 100644 index 8678c4cc4..000000000 --- a/docs/zh/modules/gov/README.md +++ /dev/null @@ -1,255 +0,0 @@ -# Gov/Iparam User Guide - -## 基本功能描述 - -1. 文本提议的链上治理 -2. 参数修改提议的链上治理 -3. 软件升级提议的链上治理 - -## 交互流程 - -### 治理流程 - -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) - -## 使用场景 -### 创建使用环境 - -``` -rm -rf iris -rm -rf .iriscli -iris init gen-tx --name=x --home=iris -iris init --gen-txs --chain-id=gov-test -o --home=iris -iris start --home=iris -``` - -### 参数修改的使用场景 - -场景一:通过命令行带入参数修改信息进行参数修改 - -``` -# 根据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 - -``` - -场景二,通过文件修改参数 - -``` -# 导出配置文件 -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 -``` - -## 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 -``` - -* `--title` 提议的标题 -* `--description` 提议的描述 -* `--type` 提议的类型 {'Text','ParameterChange','SoftwareUpgrade'} -* `--deposit` 抵押的token数量 -* 上面就是典型的文本类提议 - -``` -iriscli gov deposit --proposal-id=1 --deposit=1iris --from=x --chain-id=gov-test --fee=0.05iris --gas=20000 -``` - -* `--propsal-id` 抵押提议ID -* `--deposit` 抵押的token数量 - -``` -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'强烈不同意} - - -``` -# 查询提议情况 -iriscli gov query-proposal --proposal-id=1 --trust-node -``` - -* `--proposal-id` 查询提议ID - - - -### 参数修改提议部分 - -``` -# 根据gov模块名查询的可修改的参数 -iriscli gov query-params --module=gov --trust-node -``` - -* `--module` 查询module可修改参数的key的列表 - - -``` -# 根据Key查询可修改参数的内容 -iriscli gov query-params --key=Gov/gov/DepositProcedure --trust-node -``` - -* `--key` 查询key对应的参数值 - -``` -# 导出配置文件 -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` 最小抵押token数量,默认:10iris,范围(1iris,200iris) -* `max_deposit_period` 补交抵押token的窗口期,默认: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` 未投票的验证人惩罚token的比例 默认:1/100,范围(0,1) -* 投票统计逻辑:如果强烈反对的voting_power占总的voting_power 超过 veto,提议不通过。然后再看赞同的voting_power占总的投票的voting_power 是否超过 veto,超过则提议不通过,不超过则不通过。 \ No newline at end of file diff --git a/docs/zh/modules/iservice/README.md b/docs/zh/modules/iservice/README.md deleted file mode 100644 index ea5a85792..000000000 --- a/docs/zh/modules/iservice/README.md +++ /dev/null @@ -1,86 +0,0 @@ -# IService User Guide - -## 基本功能描述 - -1. 服务定义 -2. 服务绑定 (TODO) -3. 服务调用 (TODO) -4. 争议解决 (TODO) -5. 服务分析 (TODO) - -## 交互流程 - -### 服务定义流程 - -1. 任何用户可以发起服务定义请求,在服务定义中,使用 [protobuf](https://developers.google.com/protocol-buffers/) 对该服务的方法,方法的输入、输出参数进行标准化定义。 - -## 使用场景 -### 创建使用环境 - -``` -rm -rf iris -rm -rf .iriscli -iris init gen-tx --name=x --home=iris -iris init --gen-txs --chain-id=service-test -o --home=iris -iris start --home=iris -``` - -### 服务定义 - -``` -# 服务定义 -iriscli iservice define --chain-id=service-test --from=x --fee=0.004iris --name=test-service --service-description=service-description --author-description=author-description --tags "tag1 tag2" --broadcast=Broadcast --idl-content=<idl-content> --file=test.proto - -# 结果 -Committed at block 1040 (tx hash: 58FD40B739F592F5BD9B904A661B8D7B19C63FA9, response: {Code:0 Data:[] Log:Msg 0: Info: GasWanted:200000 GasUsed:13601 Tags:[{Key:[99 111 109 112 108 101 116 101 67 111 110 115 117 109 101 100 84 120 70 101 101 45 105 114 105 115 45 97 116 116 111] Value:[247 102 151 120 200 0]}] XXX_NoUnkeyedLiteral:{} XXX_unrecognized:[] XXX_sizecache:0}) -{ - "tags": { - "completeConsumedTxFee-iris-atto": "159740000000000" - } -} - -# 查询服务定义 -iriscli iservice definition --def-chain-id=service-test --name=test-service --chain-id=service-test - -``` - -## 命令详情 - -``` -iriscli iservice define --chain-id=service-test --from=x --fee=0.004iris --name=test-service --service-description=service-description --author-description=author-description --tags "tag1 tag2" --broadcast=Broadcast --idl-content=<idl-content> --file=test.proto -``` - -* `--name` 该iService服务的名称 -* `--service-description` 该iService服务的描述 -* `--author-description` 该iService服务创建者的描述. 可选 -* `--tags` 该iService服务的关键字 -* `--broadcast` 此服务消息广播类型{`Broadcast`,`Unicast`} -* `--idl-content` 对该iService服务的methods的标准化定义内容 -* `--file` 可使用文件代替idl-content,当该项不为空时,覆盖`idl-content`内容 - -``` -iriscli iservice definition --def-chain-id=service-test --name=test-service --chain-id=service-test -``` - -* `--def-chain-id` 定义该iservice服务的区块链ID -* `--name` iService服务的名称 - -## IDL文件扩展 -在使用proto文件对服务的方法,输入、输出参数进行标准化定义时,可通过注释的方式增加method属性。 - -### 注释标准 -* 使用 `//@Attribute 属性: 值`的方式添加在rpc方法上,即可将该属性添加为方法的属性。例如: -> //@Attribute description: sayHello - -### 目前支持的属性 -* `description` 对该方法的描述 -* `output_privacy` 是否对该方法的输出进行加密处理,{`NoPrivacy`,`PubKeyEncryption`} -* `output_cached` 是否对该方法的输出进行缓存,{`OffChainCached`,`NoCached`} - -### IDL content参照 -* IDL content参照 -> syntax = \"proto3\";\n\npackage helloworld;\n\n// The greeting service definition.\nservice Greeter {\n //@Attribute description: sayHello\n //@Attribute output_privacy: NoPrivacy\n //@Attribute output_cached: NoCached\n rpc SayHello (HelloRequest) returns (HelloReply) {}\n}\n\n// The request message containing the user's name.\nmessage HelloRequest {\n string name = 1;\n}\n\n// The response message containing the greetings\nmessage HelloReply {\n string message = 1;\n}\n - -* IDL文件参照 - -[test.proto](../../../modules/iservice/test.proto) \ No newline at end of file diff --git a/docs/zh/pics/flow.jpg b/docs/zh/pics/flow.jpg new file mode 100644 index 000000000..06101664b Binary files /dev/null and b/docs/zh/pics/flow.jpg differ diff --git a/docs/zh/pics/iris.jpg b/docs/zh/pics/iris.jpg new file mode 100644 index 000000000..8d9686a45 Binary files /dev/null and b/docs/zh/pics/iris.jpg differ diff --git a/docs/zh/pics/states.png b/docs/zh/pics/states.png new file mode 100644 index 000000000..3dbfbac08 Binary files /dev/null and b/docs/zh/pics/states.png differ diff --git a/docs/zh/resources/README.md b/docs/zh/resources/README.md new file mode 100644 index 000000000..ec15572d2 --- /dev/null +++ b/docs/zh/resources/README.md @@ -0,0 +1,3 @@ +# 相关资源 + +本目录将包含与IRISnet有关的资源。 \ No newline at end of file diff --git a/docs/zh/resources/delegator-faq.md b/docs/zh/resources/delegator-faq.md new file mode 100644 index 000000000..2189c8edd --- /dev/null +++ b/docs/zh/resources/delegator-faq.md @@ -0,0 +1,94 @@ +# Delegators + +## 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. + +## States for a Delegator + +Delegators have the same state as their validator. + + +Note that delegation are not necessarily bonded. Tokens of each delegator can be delegated and bonded, delegated and unbonding, delegated and unbonded, or loose. + +## Common operation for Delegators + +* Delegation + +To delegate some IRIS token to a validator, you could run the following command: +```$xslt +iriscli stake delegate --address-delegator=<address-delegator> --address-validator=<address-validator> --chain-id=fuxi-3001 --from=name --gas=2000000 --fee=40000000000000000iris --amount=10000000000000000000iris +``` +> Please notice that the amount is under unit iris-atto, 1iris=10^18 iris-atto + +* Query Delegations + +You could query your delegation amount with the following command: + +```$xslt +iriscli stake delegation --address-delegator=<address-delegator> --address-validator=<address-validator> --chain-id=fuxi-3001 +``` + +The example output is the following: +```$xslt +Delegation +Delegator: faa1je9qyff4qate4e0kthum0p8v7q7z8lr7eczsv6 +Validator: faa1dmp6eyjw94u0wzc67qa03cmgl92qwqaph28lxq +Shares: 10000000000000000000/1Height: 215307 +``` + +> Please notice that the share amount is also correspond to iris-atto, 1iris=10^18 iris-atto + + +* Re-delegate + +Once a delegator has delegated his own IRIS to certain validator, he/she could change the destination of delegation at anytime. If the transaction is executed, the +delegation will be placed at the other's pool after 10 minutes. + +The redelegation operation is composed of two phases: + * redelegate begin + * redelegate complete + + To start, you should run the following command: +```$xslt +iriscli stake redelegate begin --addr-validator-dest=<addr-validator-dest> --addr-validator-source=<addr-validator> --address-delegator=<address-delegator> --chain-id=fuxi-3001 --from=name --gas=2000000 --fee=40000000000000000iris --shares-percent=1.0 +``` + +Please note that you have to wait 10 minute to run the next command: + +```$xslt +iriscli stake redelegate complete --addr-validator-dest=<addr-validator-dest> --addr-validator-source=<addr-validator-source> --address-delegator=<address-delegator> --chain-id=fuxi-3001 --from=name --gas=2000000 --fee=40000000000000000iris +``` + +The example output is the following: +```$xslt +Delegation +Delegator: faa1je9qyff4qate4e0kthum0p8v7q7z8lr7eczsv6 +Validator: faa1kepndxvjr6gnc8tjcnelp9hqz8jdcs8mvz7m86 +Shares: 10000000000000000000/1Height: 215459 +``` + +* Unbond Delegation + + +Once a delegator has delegated his own IRIS to certain validator, he/she could withdraw the delegation at anytime. If the transaction is executed, the +delegation will become liquid after 10 minutes. + +The redelegation operation is composed of two phases: + * unbond begin + * unbond complete + + To start, you should run the following command: +```$xslt +iriscli stake unbond begin --address-validator=<address-validator> --address-delegator=<address-delegator> --chain-id=fuxi-3001 --from=name --gas=2000000 --fee=40000000000000000iris --shares-percent=1.0 +``` + +Please note that you have to wait 10 minute to run the next command: + +```$xslt +iriscli stake unbond complete --address-validator=<address-validator> --address-delegator=<address-delegator> --chain-id=fuxi-3001 --from=name --gas=2000000 --fee=40000000000000000iris +``` + +You could check that the balance of delegator has increased. \ No newline at end of file diff --git a/docs/zh/resources/validator-faq.md b/docs/zh/resources/validator-faq.md new file mode 100644 index 000000000..e62b4e6cc --- /dev/null +++ b/docs/zh/resources/validator-faq.md @@ -0,0 +1,26 @@ +# Fuxi测试网激励计划常见问题 + + +1.如何加入Fuxi测试网? + +你可以加入QQ工作群:834063323。团队将在群里及时通知有关测试网的消息。 + +有两种方式加入测试网: +* 以验证人的身份加入:你可以在自己的服务器上部署一个IRIShub节点。然后将其绑定成为一个验证人节点。如果你暂时没有服务器,你也可以申请免费试用BaaS的服务,我们将提供 +Wancloud和Zig-BaaS的免费试用机会。然后你就可以完成测试网的任务了。 + +* 以委托人的身份加入: +如果你对于部署一个验证人节点感到很困难,你可以只下载一个客户端,然后执行相关的测试网的任务交易。 + + +2.测试网的激励任务在哪里? + +每一个测试网迭代中,团队都会发布相关的测试网激励任务。例如,Fuxi-3001测试网激励任务在下面链接中:https://github.com/irisnet/testnets/tree/master/fuxi/fuxi-3001 + +3.怎样能知道我的任务完成情况? + +每当决定切换到下一个测试网的时候,团队会检查参与者的任务完成情况。例如,Fuxi-2000测试网任务完成情况在这里:https://github.com/irisnet/testnets/issues/51 + +4.如果我获得了测试网奖励,何时才能拿到? + +测试网的奖励将在主网上线后发放给社区成员。你需要用你的Keybase签名一个irishub的地址,然后将其发送给团队。 \ No newline at end of file diff --git a/docs/zh/resources/whitepaper-en.md b/docs/zh/resources/whitepaper-en.md new file mode 100644 index 000000000..a1916bd21 --- /dev/null +++ b/docs/zh/resources/whitepaper-en.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<br/> +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!_ +<div STYLE="page-break-after: always;"></div> + +## 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) + +<div STYLE="page-break-after: always;"></div> + +## 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 <https://www.irisnet.org/> 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. + +<div STYLE="page-break-after: always;"></div> + +## 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. + +<div STYLE="page-break-after: always;"></div> + +## 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 | + +<div STYLE="page-break-after: always;"></div> + +## 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. + +<div STYLE="page-break-after: always;"></div> + +## 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. + +<div STYLE="page-break-after: always;"></div> + +## 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) + + +<div STYLE="page-break-after: always;"></div> + +## 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. + +<div STYLE="page-break-after: always;"></div> + +## 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. + +<div STYLE="page-break-after: always;"></div> + +## 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/zh/resources/whitepaper-kr.md b/docs/zh/resources/whitepaper-kr.md new file mode 100644 index 000000000..1911a7c8e --- /dev/null +++ b/docs/zh/resources/whitepaper-kr.md @@ -0,0 +1 @@ +# IRIS \ No newline at end of file diff --git a/docs/zh/resources/whitepaper-zh.md b/docs/zh/resources/whitepaper-zh.md new file mode 100644 index 000000000..661f69bfd --- /dev/null +++ b/docs/zh/resources/whitepaper-zh.md @@ -0,0 +1,616 @@ +# IRIS 网络白皮书 + +**用于构建可信分布式商业应用的跨链服务基础设施及协议** + +Harriet Cao harriet@bianjie.ai<br/>Haifeng Xi haifeng@bianjie.ai + +_NOTE:如果你可以在GitHub上阅读,那么我们仍然在积极完善这个文档。 请定期检查更新!_<div STYLE="page-break-after: always;"></div> + +## 目录 + +- [免责声明](#disclaimer) +- [IRIS 概览](#iris-概览) + - [Cosmos 和 Tendermint](#cosmos-和-tendermint) + - [IRIS 技术创新](#iris-技术创新) +- [IRIS网络设计](#iris-网络设计) + - [网络参与者](#网络参与者) + - [IRIS服务](#iris-服务) + - [IBC 改进](#ibc-改进) +- [用例](#用例) +- [通证经济](#通证经济) +- [初始通证分配](#初始通证分配) +- [路线图](#路线图) +- [团队](#团队) + - [核心成员](#核心成员) + - [顾问](#顾问) +- [参考文献](#参考文献) + +<div STYLE="page-break-after: always;"></div> + +## 免责声明 + +本白皮书及其相关文档用于接下来对IRIS网络的开发和应用。仅做信息传播之用并可能更改。 + +### 本文介绍了一个开发中的项目 + +本文基于IRIS 基金会有限公司(IRIS Foundation Limited)提供的已知信息及假设,包含了符合该基金会理念的前瞻性声明。 + +本文所设想的IRIS网络尚在开发中,并将不断更新,这些更新包括但不限于关键治理和关键技术。 开发使用IRIS通证或与之相关的测试平台(软件)以及技术,可能无法实现或无法完全实现本白皮书所述的目标。 + +如果IRIS网络得以完成,可能与本文所述有所不同。本文不对未来的任何计划、预测或前景的成功性或者合理性做出陈述或保证,本文的任何内容都不应被视为对未来的承诺或陈述。 + +### 并非监管类产品的要约 + +IRIS通证不代表任何一种有价证券或者任何其它司法监管下的产品。 + +本文不构成对任何有价证券或其他受监管产品的出价要约或询价邀请,也不构成以投资为目的的促销、邀请或询价。其购买条款并非提供金融服务的文件或任何类型的招股说明书。 + +IRIS通证不代表任何平台或软件系统、或IRIS 基金会有限公司以及其他任何公司的股权、股份、单位、资本权益或版权使用费、利润、回报或收入,不代表任何与平台有关的公有或私有企业、公司、基金会以及其他受监管实体的知识产权。 + +### 并非建议 + +本白皮书不构成任何对IRIS通证的购买建议。请不要依赖本白皮书去达成任何合同或购买的决策。 + +### 风险警告 + +购买IRIS通证并参与IRIS网络伴随着极大的风险。 + +在购买IRIS通证之前,您应该仔细评估并考虑风险,包括在<https://www.irisnet.org/>上和其他任何文档中列出的风险。 + +### 仅代表IRIS基金会有限公司的意见 + +本白皮书所表达的观点为IRIS 基金会有限公司的观点,并不一定反映任何政府、准政府、当局或公共机构(包括但不限于任何管辖范围内的任何管辖机构)的官方政策或立场。 + +本白皮书中的信息基于IRIS 基金会认为可靠的来源,但并不能保证其准确性或完整性。 + +### 英文是本白皮书的授权语言 + +本白皮书和相关材料仅以英文发行。任何翻译并未经IRIS 基金会有限公司或其他人员认证,其准确性和完整性无法保证,仅供参考。如果翻译与本白皮书的英文版本之间有任何不一致之处,则以英文版本为准。 + +### 非第三方从属关联或背书 + +本白皮书中提及的特定公司和平台仅供参考。使用任何公司和/或平台名称和商标并不意味着与其有任何的从属关联或背书。 + +### 您必须获得所有必要的专业建议 + +您有必要在决定是否购买IRIS通证或参与IRIS网络项目之前,必须咨询律师、会计师和/或税务专业人员,以及其他专业顾问。 + +<div STYLE="page-break-after: always;"></div> + +## 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将生成服务提供方的框架以及服务消费方的模块。 + +<div STYLE="page-break-after: always;"></div> + +## 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 | + +<div STYLE="page-break-after: always;"></div> + +## 用例 + +在本节中,我们为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项目计划之一还包括与此类应用程序项目团队展开密切合作,以支持并使他们能够拥有所需的区块链基础架构,让他们专注于更高效地交付预期的业务价值。 + +<div STYLE="page-break-after: always;"></div> + +## 通证经济 + +与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预言机的潜在信息中获取市场价格数据。 + +权益通证和费用通证都会进一步细化以确保符合法律和监管规定的义务。 + +<div STYLE="page-break-after: always;"></div> + +## 初始通证分配 + +最开始,系统预计发放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% (包括业务发展,社区发展和推广,以及出差、交流、出版、发行和其他费用等) + +<div STYLE="page-break-after: always;"></div> + +## 路线图 + +预期的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和移动客户端的技术创新,以及开发者的参与。 + +<div STYLE="page-break-after: always;"></div> + +## 团队 + +**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等大型开源项目中的活跃代码提交者。 他是企业应用软件和移动软件方面的专家,也是参与了多个由美国政府资助的研究项目。 + +<div STYLE="page-break-after: always;"></div> + +## 参考文献 + +[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 DistributedLedgers", <https://cosmos.network/whitepaper> +* [4] Gavin Wood, "Polkadot: Vision For a Heterogeneous Muilti-chainFramework", <https://polkadot.io/> +* [5] Tendermint, <https://tendermint.readthedocs.io/en/master/> +* [6] Ethermint, <https://ethermint.zone/> +* [7] Oracle International Corporation, "Accountability and Trust inDistributed Ledger Systems", USA Patent Application 20170236120, August17, 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 SmartContracts", 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 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, <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/zh/software/README.md b/docs/zh/software/README.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/zh/software/cli-client.md b/docs/zh/software/cli-client.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/zh/software/light-client.md b/docs/zh/software/light-client.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/zh/software/monitor.md b/docs/zh/software/monitor.md new file mode 100644 index 000000000..0edf5e241 --- /dev/null +++ b/docs/zh/software/monitor.md @@ -0,0 +1,61 @@ +# 如何部署 IRIS Monitor + +## 安装 IRIS Monitor + +你可以参考这个页面来安装 IRIS 及 IRIS Monitor : https://github.com/irisnet/irishub/blob/master/docs/get-started/Install-Iris.md。 +另外,系统中需要有/bin/bash、wc、ps等命令。 + +## 启动 IRIS Monitor + +``` +irismon --address=EAC535EC37EB3AE8D18C623BA4B4C8128BC082D2 \ +--account-address=faa1nwpzlrs35nawthal6vz2rjr4k8xjvn7k8l63st \ +--chain-id=irishub-stage --node=http://localhost:36657 +``` + +参数说明: + +- `address`:要监测的验证人地址(hex编码) +- `account-address`:要监测的账户地址(bech32 编码) +- `chain-id`:要监测的链 id +- `node`:要监控的节点地址(默认为 tcp://localhost:26657) + +启动之后, 你可以通过 `http://localhost:36660/` 能看到 Metrics 数据页面。 + +## 启动 Prometheus + +### 编辑配置文件 + +从 [https://github.com/prometheus/prometheus/blob/master/documentation/examples/prometheus.yml](https://github.com/prometheus/prometheus/blob/master/documentation/examples/prometheus.yml) 下载默认配置文件到本地: + +在配置文件 `prometheus.yml` 中添加以下 `jobs` : + +```yaml + - job_name: fuxi-4000 + static_configs: + - targets: ['localhost:36660'] + labels: + instance: fuxi-4000 +``` + +> Note:targets 配置项的值为 IRIS Monitor 启动后所占用的 ip 和 port。 + +### 启动 Prometheus + +```bashg +docker run -d --name=prometheus -p 9090:9090 -v ~/volumes/prometheus:/etc/prometheus prom/prometheus +``` + +将编辑好的配置文件 `prometheus.yml` 放在宿主机的目录下并映射到容器中。 +例如在上例中配置文件位于宿主机的 `~/volumes/prometheus` 中。 + + +## 启动 Grafana + +``` +docker run -d --name=grafana -p 3000:3000 grafana/grafana +``` + +接下来就可以访问 `http://localhost:3000/` 来查看 grafana 监控。 + +> Tips: 打开网页后使用默认用户名 admin,默认密码 admin 登录。建议登录之后立即修改密码。 \ No newline at end of file diff --git a/docs/zh/software/node.md b/docs/zh/software/node.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/zh/tools/Deploy-IRIS-Monitor.md b/docs/zh/tools/Deploy-IRIS-Monitor.md deleted file mode 100644 index 7e1c7cd2a..000000000 --- a/docs/zh/tools/Deploy-IRIS-Monitor.md +++ /dev/null @@ -1,62 +0,0 @@ -# 如何部署monitor - -确保已经安装了iris等工具,系统中需要有/bin/bash、wc、ps等命令。 你可以参考这个页面来安装iris工具:https://github.com/irisnet/irishub - -## 获得修改运行参数 - -* 验证人地址的hex编码 - -``` --a=<你的验证人地址的hex编码> -``` - -* 确定Chain-ID - -``` ---chain-id=<你要监控的网络的ID> -``` - -* 确定监控的节点 - - -``` ---node=<你要监控的节点监听的rpc端口(默认为26657)> -``` - -## 启动IRIS Monitor - -``` -irismon --account-address=faa1nwpzlrs35nawthal6vz2rjr4k8xjvn7k8l63st --address=EAC535EC37EB3AE8D18C623BA4B4C8128BC082D2 --chain-id=irishub-stage --node=http://localhost:36657& -``` - - -### 启动Prometheus - -在配置文件中添加 `jobs` : -```$xslt - - job_name: fuxi-4000 - - static_configs: - - - targets: ['localhost:36660'] - - labels: - - instance: fuxi-4000 -``` - -启动Prometheus后可以在本地36660端口看到监控数据。 - -### 启动Grafana - -通过Docker启动Grafana -```$xslt -sudo docker run -p 3000:3000 grafana/grafana 1>grafana.log 2>grafana.error & -``` - -接下来就可以访问localhost:3000来查看grafana监控。打开网页后使用默认用户名admin,默认密码admin登录。建议登录之后立即修改密码。 - -5. 关闭监控 -```$xslt -killl -9 <process-ID> -``` \ No newline at end of file diff --git a/docs/zh/validators/How-to-participate-in-onchain-governance.md b/docs/zh/validators/How-to-participate-in-onchain-governance.md deleted file mode 100644 index 72d9a1ab8..000000000 --- a/docs/zh/validators/How-to-participate-in-onchain-governance.md +++ /dev/null @@ -1,68 +0,0 @@ -# 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=<account> --from=<name> --chain-id=fuxi-3001 --fee=400000000000000iris --gas=20000 --node=http://localhost:36657 -``` - -The `<account>` for `proposer` field should start with `faa` which corresponds to `<name>`. - - -## 如何增加投票的抵押金额? - -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=<account> --deposit=1000000000000000000iris --from=<name> --chain-id=fuxi-3001 --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 `<proposal_id>`.You could execute the following command to vote on proposal with ID = 1: -``` -iriscli vote --from=jerry --voter=<account> --proposalID=1 --option=Yes --chain-id=fuxi-3001 --fee=2000000000000000iris --gas=20000 --node=http://localhost:36657 -``` - -## 如何查询投票信息? - -例如,查询第一个提案的信息: - -``` -iriscli gov query-proposal --proposalID=1 --chain-id=fuxi-3001 --node=http://localhost:26657 - -`````` -也可以在浏览器上查询。 diff --git a/docs/zh/validators/Setup-Sentry-Node.md b/docs/zh/validators/Setup-Sentry-Node.md deleted file mode 100644 index e1ba22465..000000000 --- a/docs/zh/validators/Setup-Sentry-Node.md +++ /dev/null @@ -1,54 +0,0 @@ -# 哨兵节点及其搭建 - -为了保证验证人节点的安全性和可用性,我们建议为验证人节点配置2个以上的哨兵节点。使用哨兵节点的好处在于可以有效地防止DoS攻击等其他针对验证人节点的攻击。 - -## 初始化一个全节点 - -为了搭建哨兵节点,首先我们需要初始化一些全节点。执行以下命令创建一个全节点(建议在多台不同的服务器上创建多个哨兵节点以提高可用性和安全性) -``` -iris init --name=<your name> --home=<sentry 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.toml进行编辑。需要进行如下修改: -``` -private_peers_ids="validator_node_id" -``` - -这里的`<validator node id>`可以在验证人节点上使用iriscli status命令获得。经过这样设置之后然后使用 - -``` -iris init --home=<sentry home> -``` - -启动哨兵节点。对每个哨兵节点都需要进行这些操作。 - -## 修改验证人节点的配置 - -接下来需要对验证人节点的`<validator home>/config/`目录下的config.toml进行修改: - -``` -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/examples/irishub-bugfix-2/app/app.go b/examples/irishub-bugfix-2/app/app.go index 69b89dad1..9cdee0e73 100644 --- a/examples/irishub-bugfix-2/app/app.go +++ b/examples/irishub-bugfix-2/app/app.go @@ -2,42 +2,37 @@ package app import ( "encoding/json" + "fmt" "io" "os" + "sort" + "strings" - 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" - + "github.com/cosmos/cosmos-sdk/codec" 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" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + ibcbugfix "github.com/irisnet/irishub/examples/irishub-bugfix-2/ibc" + "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/stake" - ibcbugfix "github.com/irisnet/irishub/examples/irishub-bugfix-2/ibc" + bam "github.com/irisnet/irishub/baseapp" + "github.com/irisnet/irishub/iparam" "github.com/irisnet/irishub/modules/gov" - "github.com/irisnet/irishub/modules/upgrade" - - "errors" - "fmt" - "github.com/cosmos/cosmos-sdk/server" "github.com/irisnet/irishub/modules/gov/params" - "github.com/irisnet/irishub/modules/iparam" + "github.com/irisnet/irishub/modules/service" + "github.com/irisnet/irishub/modules/service/params" "github.com/irisnet/irishub/modules/record" + "github.com/irisnet/irishub/modules/upgrade" "github.com/irisnet/irishub/modules/upgrade/params" - "github.com/irisnet/irishub/modules/iservice" "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" + abci "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" + tmtypes "github.com/tendermint/tendermint/types" ) const ( @@ -47,6 +42,7 @@ const ( // default home directories for expected binaries var ( + DefaultLCDHome = os.ExpandEnv("$HOME/.irislcd") DefaultCLIHome = os.ExpandEnv("$HOME/.iriscli") DefaultNodeHome = os.ExpandEnv("$HOME/.iris") ) @@ -54,33 +50,39 @@ var ( // Extended ABCI application type IrisApp struct { *bam.BaseApp - cdc *wire.Codec + cdc *codec.Codec // keys to access the substores keyMain *sdk.KVStoreKey keyAccount *sdk.KVStoreKey keyIBC *sdk.KVStoreKey keyStake *sdk.KVStoreKey + tkeyStake *sdk.TransientStoreKey keySlashing *sdk.KVStoreKey + keyMint *sdk.KVStoreKey + keyDistr *sdk.KVStoreKey + tkeyDistr *sdk.TransientStoreKey keyGov *sdk.KVStoreKey keyFeeCollection *sdk.KVStoreKey keyParams *sdk.KVStoreKey + tkeyParams *sdk.TransientStoreKey keyUpgrade *sdk.KVStoreKey - keyIservice *sdk.KVStoreKey + keyService *sdk.KVStoreKey keyRecord *sdk.KVStoreKey // Manage getting and setting accounts - accountMapper auth.AccountMapper + accountMapper auth.AccountKeeper feeCollectionKeeper auth.FeeCollectionKeeper - coinKeeper bank.Keeper - ibcMapper ibc.Mapper + bankKeeper bank.Keeper ibc1Mapper ibcbugfix.Mapper stakeKeeper stake.Keeper slashingKeeper slashing.Keeper - paramsKeeper params.Keeper + mintKeeper mint.Keeper + distrKeeper distr.Keeper govKeeper gov.Keeper + paramsKeeper params.Keeper upgradeKeeper upgrade.Keeper - iserviceKeeper iservice.Keeper + serviceKeeper service.Keeper recordKeeper record.Keeper // fee manager @@ -90,7 +92,7 @@ type IrisApp struct { 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 := bam.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...) bApp.SetCommitMultiStoreTracer(traceStore) // create your application object @@ -101,63 +103,127 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio keyAccount: sdk.NewKVStoreKey("acc"), keyIBC: sdk.NewKVStoreKey("ibc"), keyStake: sdk.NewKVStoreKey("stake"), + tkeyStake: sdk.NewTransientStoreKey("transient_stake"), + keyMint: sdk.NewKVStoreKey("mint"), + keyDistr: sdk.NewKVStoreKey("distr"), + tkeyDistr: sdk.NewTransientStoreKey("transient_distr"), keySlashing: sdk.NewKVStoreKey("slashing"), keyGov: sdk.NewKVStoreKey("gov"), keyRecord: sdk.NewKVStoreKey("record"), keyFeeCollection: sdk.NewKVStoreKey("fee"), keyParams: sdk.NewKVStoreKey("params"), + tkeyParams: sdk.NewTransientStoreKey("transient_params"), keyUpgrade: sdk.NewKVStoreKey("upgrade"), - keyIservice: sdk.NewKVStoreKey("iservice"), + keyService: sdk.NewKVStoreKey("service"), } var lastHeight int64 if viper.GetBool(FlagReplay) { - lastHeight = app.replay() + lastHeight = bam.Replay(app.Logger) } - // define the accountMapper - app.accountMapper = auth.NewAccountMapper( + // define the AccountKeeper + app.accountMapper = auth.NewAccountKeeper( app.cdc, app.keyAccount, // target store auth.ProtoBaseAccount, // prototype ) // add handlers - app.paramsKeeper = params.NewKeeper(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.bankKeeper = bank.NewBaseKeeper(app.accountMapper) + app.feeCollectionKeeper = auth.NewFeeCollectionKeeper( + app.cdc, + app.keyFeeCollection, + ) + app.paramsKeeper = params.NewKeeper( + app.cdc, + app.keyParams, app.tkeyParams, + ) + stakeKeeper := stake.NewKeeper( + app.cdc, + app.keyStake, app.tkeyStake, + app.bankKeeper, app.paramsKeeper.Subspace(stake.DefaultParamspace), + app.RegisterCodespace(stake.DefaultCodespace), + ) + app.mintKeeper = mint.NewKeeper(app.cdc, app.keyMint, + app.paramsKeeper.Subspace(mint.DefaultParamspace), + &stakeKeeper, app.feeCollectionKeeper, + ) + app.distrKeeper = distr.NewKeeper( + app.cdc, + app.keyDistr, + app.paramsKeeper.Subspace(distr.DefaultParamspace), + app.bankKeeper, &stakeKeeper, app.feeCollectionKeeper, + app.RegisterCodespace(stake.DefaultCodespace), + ) + app.slashingKeeper = slashing.NewKeeper( + app.cdc, + app.keySlashing, + &stakeKeeper, app.paramsKeeper.Subspace(slashing.DefaultParamspace), + app.RegisterCodespace(slashing.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.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - app.recordKeeper = record.NewKeeper(app.cdc, app.keyRecord, app.RegisterCodespace(record.DefaultCodespace)) - app.iserviceKeeper = iservice.NewKeeper(app.cdc, app.keyIservice, app.RegisterCodespace(iservice.DefaultCodespace)) + app.govKeeper = gov.NewKeeper( + app.cdc, + app.keyGov, + app.bankKeeper, &stakeKeeper, + app.RegisterCodespace(gov.DefaultCodespace), + ) + + app.recordKeeper = record.NewKeeper( + app.cdc, + app.keyRecord, + app.RegisterCodespace(record.DefaultCodespace), + ) + app.serviceKeeper = service.NewKeeper( + app.cdc, + app.keyService, + app.bankKeeper, + app.RegisterCodespace(service.DefaultCodespace), + ) + + // register the staking hooks + // NOTE: stakeKeeper above are passed by reference, + // so that it can be modified like below: + app.stakeKeeper = *stakeKeeper.SetHooks( + NewHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks())) + + app.upgradeKeeper = upgrade.NewKeeper( + app.cdc, + app.keyUpgrade, app.stakeKeeper, + ) + + app.ibc1Mapper = ibcbugfix.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibcbugfix.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("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.bankKeeper)). + AddRoute("ibc-1", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibcbugfix.NewHandler(app.ibc1Mapper, app.bankKeeper,app.upgradeKeeper)). + AddRoute("stake", []*sdk.KVStoreKey{app.keyStake, app.keyAccount, app.keyMint, app.keyDistr}, stake.NewHandler(app.stakeKeeper)). AddRoute("slashing", []*sdk.KVStoreKey{app.keySlashing, app.keyStake}, slashing.NewHandler(app.slashingKeeper)). + AddRoute("distr", []*sdk.KVStoreKey{app.keyDistr}, distr.NewHandler(app.distrKeeper)). 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("record", []*sdk.KVStoreKey{app.keyRecord}, record.NewHandler(app.recordKeeper)). - AddRoute("iservice", []*sdk.KVStoreKey{app.keyIservice}, iservice.NewHandler(app.iserviceKeeper)) + AddRoute("service", []*sdk.KVStoreKey{app.keyService}, service.NewHandler(app.serviceKeeper)) + + app.QueryRouter(). + AddRoute("gov", gov.NewQuerier(app.govKeeper)). + AddRoute("stake", stake.NewQuerier(app.stakeKeeper, app.cdc)) + + app.feeManager = bam.NewFeeManager(app.paramsKeeper.Subspace("Fee")) - app.feeManager = bam.NewFeeManager(app.paramsKeeper.Setter()) // initialize BaseApp + app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing, app.keyGov, app.keyMint, app.keyDistr, + app.keyFeeCollection, app.keyParams, app.keyUpgrade, app.keyRecord, app.keyService) app.SetInitChainer(app.initChainer) app.SetBeginBlocker(app.BeginBlocker) - app.SetEndBlocker(app.EndBlocker) app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) + app.MountStoresTransient(app.tkeyParams, app.tkeyStake, app.tkeyDistr) 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.keyRecord, app.keyIservice) + app.SetEndBlocker(app.EndBlocker) app.SetRunMsg(app.runMsgs) var err error @@ -173,15 +239,32 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio upgrade.RegisterModuleList(app.Router()) app.upgradeKeeper.RefreshVersionList(app.GetKVStore(app.keyUpgrade)) - iparam.SetParamReadWriter(app.paramsKeeper.Setter(), - &govparams.DepositProcedureParameter, - &govparams.VotingProcedureParameter, - &govparams.TallyingProcedureParameter, + iparam.SetParamReadWriter(app.paramsKeeper.Subspace(iparam.SignalParamspace).WithTypeTable( + params.NewTypeTable( + upgradeparams.CurrentUpgradeProposalIdParameter.GetStoreKey(), uint64((0)), + upgradeparams.ProposalAcceptHeightParameter.GetStoreKey(), int64(0), + upgradeparams.SwitchPeriodParameter.GetStoreKey(), int64(0), + )), &upgradeparams.CurrentUpgradeProposalIdParameter, &upgradeparams.ProposalAcceptHeightParameter, &upgradeparams.SwitchPeriodParameter) - iparam.RegisterGovParamMapping(&govparams.DepositProcedureParameter, + iparam.SetParamReadWriter(app.paramsKeeper.Subspace(iparam.GovParamspace).WithTypeTable( + params.NewTypeTable( + govparams.DepositProcedureParameter.GetStoreKey(), govparams.DepositProcedure{}, + govparams.VotingProcedureParameter.GetStoreKey(), govparams.VotingProcedure{}, + govparams.TallyingProcedureParameter.GetStoreKey(), govparams.TallyingProcedure{}, + serviceparams.MaxRequestTimeoutParameter.GetStoreKey(), int64(0), + serviceparams.MinProviderDepositParameter.GetStoreKey(), sdk.Coins{}, + )), + &govparams.DepositProcedureParameter, + &govparams.VotingProcedureParameter, + &govparams.TallyingProcedureParameter, + &serviceparams.MaxRequestTimeoutParameter, + &serviceparams.MinProviderDepositParameter) + + iparam.RegisterGovParamMapping( + &govparams.DepositProcedureParameter, &govparams.VotingProcedureParameter, &govparams.TallyingProcedureParameter) @@ -189,20 +272,20 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio } // 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) - record.RegisterWire(cdc) - auth.RegisterWire(cdc) - upgrade.RegisterWire(cdc) - iservice.RegisterWire(cdc) - sdk.RegisterWire(cdc) - wire.RegisterCrypto(cdc) +func MakeCodec() *codec.Codec { + var cdc = codec.New() + ibcbugfix.RegisterCodec(cdc) + bank.RegisterCodec(cdc) + stake.RegisterCodec(cdc) + distr.RegisterCodec(cdc) + slashing.RegisterCodec(cdc) + gov.RegisterCodec(cdc) + record.RegisterCodec(cdc) + upgrade.RegisterCodec(cdc) + service.RegisterCodec(cdc) + auth.RegisterCodec(cdc) + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) return cdc } @@ -210,6 +293,12 @@ func MakeCodec() *wire.Codec { func (app *IrisApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) + // distribute rewards from previous block + distr.BeginBlocker(ctx, req, app.distrKeeper) + + // mint new tokens for this new block + mint.BeginBlocker(ctx, app.mintKeeper) + return abci.ResponseBeginBlock{ Tags: tags.ToKVPairs(), } @@ -220,8 +309,6 @@ func (app *IrisApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.R tags := gov.EndBlocker(ctx, app.govKeeper) validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) tags.AppendTags(upgrade.EndBlocker(ctx, app.upgradeKeeper)) - // Add these new validators to the addr -> pubkey map. - app.slashingKeeper.AddValidators(ctx, validatorUpdates) return abci.ResponseEndBlock{ ValidatorUpdates: validatorUpdates, Tags: tags, @@ -237,6 +324,10 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci if err != nil { panic(err) } + // sort by account number to maintain consistency + sort.Slice(genesisState.Accounts, func(i, j int) bool { + return genesisState.Accounts[i].AccountNumber < genesisState.Accounts[j].AccountNumber + }) // load the accounts for _, gacc := range genesisState.Accounts { @@ -257,12 +348,52 @@ 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.paramsKeeper.Setter(), feeTokenGensisConfig) + bam.InitGenesis(ctx, app.feeManager, feeTokenGensisConfig) // load the address to pubkey map - slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.StakeData) + auth.InitGenesis(ctx, app.feeCollectionKeeper, genesisState.AuthData) + slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.SlashingData, genesisState.StakeData) + mint.InitGenesis(ctx, app.mintKeeper, genesisState.MintData) + distr.InitGenesis(ctx, app.distrKeeper, genesisState.DistrData) + err = IrisValidateGenesisState(genesisState) + if err != nil { + panic(err) // TODO find a way to do this w/o panics + } + + if len(genesisState.GenTxs) > 0 { + for _, genTx := range genesisState.GenTxs { + var tx auth.StdTx + err = app.cdc.UnmarshalJSON(genTx, &tx) + if err != nil { + panic(err) + } + bz := app.cdc.MustMarshalBinaryLengthPrefixed(tx) + res := app.BaseApp.DeliverTx(bz) + if !res.IsOK() { + panic(res.Log) + } + } + + validators = app.stakeKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + } + + // sanity check + if len(req.Validators) > 0 { + if len(req.Validators) != len(validators) { + panic(fmt.Errorf("len(RequestInitChain.Validators) != len(validators) (%d != %d)", + len(req.Validators), len(validators))) + } + sort.Sort(abci.ValidatorUpdates(req.Validators)) + sort.Sort(abci.ValidatorUpdates(validators)) + for i, val := range validators { + if !val.Equal(req.Validators[i]) { + panic(fmt.Errorf("validators[%d] != req.Validators[%d] ", i, i)) + } + } + } upgrade.InitGenesis(ctx, app.upgradeKeeper, app.Router(), genesisState.UpgradeData) + service.InitGenesis(ctx, genesisState.ServiceData) return abci.ResponseInitChain{ Validators: validators, @@ -281,12 +412,18 @@ func (app *IrisApp) ExportAppStateAndValidators() (appState json.RawMessage, val return false } app.accountMapper.IterateAccounts(ctx, appendAccount) - - genState := GenesisState{ - Accounts: accounts, - StakeData: stake.WriteGenesis(ctx, app.stakeKeeper), - } - appState, err = wire.MarshalJSONIndent(app.cdc, genState) + genState := NewGenesisState( + accounts, + auth.ExportGenesis(ctx, app.feeCollectionKeeper), + stake.ExportGenesis(ctx, app.stakeKeeper), + mint.ExportGenesis(ctx, app.mintKeeper), + distr.ExportGenesis(ctx, app.distrKeeper), + gov.ExportGenesis(ctx, app.govKeeper), + upgrade.WriteGenesis(ctx, app.upgradeKeeper), + service.WriteGenesis(ctx), + slashing.ExportGenesis(ctx, app.slashingKeeper), + ) + appState, err = codec.MarshalJSONIndent(app.cdc, genState) if err != nil { return nil, nil, err } @@ -303,9 +440,17 @@ func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg, mode bam.RunTxMode) var code sdk.ABCICodeType for msgIdx, msg := range msgs { // Match route. - msgType, err := app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) - if err != nil { - return err.Result() + var msgType string + var err sdk.Error + if ctx.BlockHeight() != 0 { + msgType, err = app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) + + if err != nil { + return err.Result() + } + + } else { + msgType = msg.Route() } handler := app.Router().Route(msgType) @@ -349,36 +494,61 @@ func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg, mode bam.RunTxMode) 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 +// Combined Staking Hooks +type Hooks struct { + dh distr.Hooks + sh slashing.Hooks } + +func NewHooks(dh distr.Hooks, sh slashing.Hooks) Hooks { + return Hooks{dh, sh} +} + +var _ sdk.StakingHooks = Hooks{} + +func (h Hooks) OnValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { + h.dh.OnValidatorCreated(ctx, valAddr) + h.sh.OnValidatorCreated(ctx, valAddr) +} +func (h Hooks) OnValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { + h.dh.OnValidatorModified(ctx, valAddr) + h.sh.OnValidatorModified(ctx, valAddr) +} + +func (h Hooks) OnValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.OnValidatorRemoved(ctx, consAddr, valAddr) + h.sh.OnValidatorRemoved(ctx, consAddr, valAddr) +} + +func (h Hooks) OnValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.OnValidatorBonded(ctx, consAddr, valAddr) + h.sh.OnValidatorBonded(ctx, consAddr, valAddr) +} + +func (h Hooks) OnValidatorPowerDidChange(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.OnValidatorPowerDidChange(ctx, consAddr, valAddr) + h.sh.OnValidatorPowerDidChange(ctx, consAddr, valAddr) +} + +func (h Hooks) OnValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.OnValidatorBeginUnbonding(ctx, consAddr, valAddr) + h.sh.OnValidatorBeginUnbonding(ctx, consAddr, valAddr) +} + +func (h Hooks) OnDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.OnDelegationCreated(ctx, delAddr, valAddr) + h.sh.OnDelegationCreated(ctx, delAddr, valAddr) +} + +func (h Hooks) OnDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.OnDelegationSharesModified(ctx, delAddr, valAddr) + h.sh.OnDelegationSharesModified(ctx, delAddr, valAddr) +} + +func (h Hooks) OnDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.OnDelegationRemoved(ctx, delAddr, valAddr) + h.sh.OnDelegationRemoved(ctx, delAddr, valAddr) +} + diff --git a/examples/irishub-bugfix-2/app/genesis.go b/examples/irishub-bugfix-2/app/genesis.go index 2067a1d8d..8350a4af0 100644 --- a/examples/irishub-bugfix-2/app/genesis.go +++ b/examples/irishub-bugfix-2/app/genesis.go @@ -3,242 +3,344 @@ package app import ( "encoding/json" "errors" - - "github.com/spf13/pflag" - "github.com/tendermint/tendermint/crypto" - tmtypes "github.com/tendermint/tendermint/types" - "fmt" + "io/ioutil" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/cosmos/cosmos-sdk/codec" "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" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/stake" "github.com/irisnet/irishub/modules/gov" + "github.com/irisnet/irishub/modules/service" "github.com/irisnet/irishub/modules/upgrade" "github.com/irisnet/irishub/types" - "time" + tmtypes "github.com/tendermint/tendermint/types" ) -// DefaultKeyPass contains the default key password for genesis transactions -const DefaultKeyPass = "1234567890" +var ( + Denom = "iris" + StakeDenom = Denom + "-" + types.Atto + FeeAmt = int64(100) + IrisCt = types.NewDefaultCoinType(Denom) + FreeFermionVal, _ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", FeeAmt, Denom)) + FreeFermionAcc, _ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", int64(150), Denom)) +) + +const ( + defaultUnbondingTime time.Duration = 60 * 10 * time.Second + // DefaultKeyPass contains the default key password for genesis transactions + DefaultKeyPass = "1234567890" +) // State to Unmarshal type GenesisState struct { - Accounts []GenesisAccount `json:"accounts"` - StakeData stake.GenesisState `json:"stake"` - GovData gov.GenesisState `json:"gov"` - UpgradeData upgrade.GenesisState `json:"upgrade"` + Accounts []GenesisAccount `json:"accounts"` + AuthData auth.GenesisState `json:"auth"` + StakeData stake.GenesisState `json:"stake"` + MintData mint.GenesisState `json:"mint"` + DistrData distr.GenesisState `json:"distr"` + GovData gov.GenesisState `json:"gov"` + UpgradeData upgrade.GenesisState `json:"upgrade"` + SlashingData slashing.GenesisState `json:"slashing"` + ServiceData service.GenesisState `json:"service"` + GenTxs []json.RawMessage `json:"gentxs"` +} + +func NewGenesisState(accounts []GenesisAccount, authData auth.GenesisState, stakeData stake.GenesisState, mintData mint.GenesisState, + distrData distr.GenesisState, govData gov.GenesisState, upgradeData upgrade.GenesisState, serviceData service.GenesisState, slashingData slashing.GenesisState) GenesisState { + + return GenesisState{ + Accounts: accounts, + AuthData: authData, + StakeData: stakeData, + MintData: mintData, + DistrData: distrData, + GovData: govData, + UpgradeData: upgradeData, + ServiceData: serviceData, + SlashingData: slashingData, + } } // GenesisAccount doesn't need pubkey or sequence type GenesisAccount struct { - Address sdk.AccAddress `json:"address"` - Coins sdk.Coins `json:"coins"` + Address sdk.AccAddress `json:"address"` + Coins sdk.Coins `json:"coins"` + Sequence int64 `json:"sequence_number"` + AccountNumber int64 `json:"account_number"` } func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount { return GenesisAccount{ - Address: acc.Address, - Coins: acc.Coins, + Address: acc.Address, + Coins: acc.Coins, + AccountNumber: acc.AccountNumber, + Sequence: acc.Sequence, } } func NewGenesisAccountI(acc auth.Account) GenesisAccount { return GenesisAccount{ - Address: acc.GetAddress(), - Coins: acc.GetCoins(), + Address: acc.GetAddress(), + Coins: acc.GetCoins(), + AccountNumber: acc.GetAccountNumber(), + Sequence: acc.GetSequence(), } } // convert GenesisAccount to auth.BaseAccount func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { return &auth.BaseAccount{ - Address: ga.Address, - Coins: ga.Coins.Sort(), + Address: ga.Address, + Coins: ga.Coins.Sort(), + AccountNumber: ga.AccountNumber, + Sequence: ga.Sequence, } } -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 +// NewDefaultGenesisState generates the default state for gaia. +func NewDefaultGenesisState() GenesisState { + return GenesisState{ + Accounts: nil, + StakeData: createStakeGenesisState(), + MintData: createMintGenesisState(), + DistrData: distr.DefaultGenesisState(), + GovData: gov.DefaultGenesisState(), + UpgradeData: upgrade.DefaultGenesisState(), + SlashingData: slashing.DefaultGenesisState(), + GenTxs: nil, + } +} // 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, + AppGenState: IrisAppGenStateJSON, } } -// simple genesis tx -type IrisGenTx struct { - Name string `json:"name"` - Address sdk.AccAddress `json:"address"` - PubKey string `json:"pub_key"` -} +// Create the core parameters for genesis initialization for iris +// note that the pubkey input is this machines pubkey +func IrisAppGenState(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []json.RawMessage) ( + genesisState GenesisState, err error) { + if err = cdc.UnmarshalJSON(genDoc.AppState, &genesisState); err != nil { + return genesisState, err + } -// 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 there are no gen txs to be processed, return the default empty state + if len(appGenTxs) == 0 { + return genesisState, errors.New("there must be at least one genesis tx") + } - if genTxConfig.Name == "" { - return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)") + stakeData := genesisState.StakeData + for i, genTx := range appGenTxs { + var tx auth.StdTx + if err := cdc.UnmarshalJSON(genTx, &tx); err != nil { + return genesisState, err + } + msgs := tx.GetMsgs() + if len(msgs) != 1 { + return genesisState, errors.New( + "must provide genesis StdTx with exactly 1 CreateValidator message") + } + if _, ok := msgs[0].(stake.MsgCreateValidator); !ok { + return genesisState, fmt.Errorf( + "Genesis transaction %v does not contain a MsgCreateValidator", i) + } } - var addr sdk.AccAddress - var secret string - addr, secret, err = server.GenerateSaveCoinKey(genTxConfig.CliRoot, genTxConfig.Name, DefaultKeyPass, genTxConfig.Overwrite) - if err != nil { - return + for _, acc := range genesisState.Accounts { + // create the genesis account, give'm few iris-atto and a buncha token with there name + for _, coin := range acc.Coins { + if coin.Denom == StakeDenom { + stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens. + Add(sdk.NewDecFromInt(coin.Amount)) // increase the supply + } + } } - mm := map[string]string{"secret": secret} - var bz []byte - bz, err = cdc.MarshalJSON(mm) + genesisState.StakeData = stakeData + genesisState.GenTxs = appGenTxs + genesisState.UpgradeData = genesisState.UpgradeData + return genesisState, nil +} + +func genesisAccountFromMsgCreateValidator(msg stake.MsgCreateValidator, amount sdk.Int) GenesisAccount { + accAuth := auth.NewBaseAccountWithAddress(sdk.AccAddress(msg.ValidatorAddr)) + accAuth.Coins = []sdk.Coin{ + {StakeDenom, amount}, + } + return NewGenesisAccount(&accAuth) +} + +// IrisValidateGenesisState ensures that the genesis state obeys the expected invariants +// TODO: No validators are both bonded and jailed (#2088) +// TODO: Error if there is a duplicate validator (#1708) +// TODO: Ensure all state machine parameters are in genesis (#1704) +func IrisValidateGenesisState(genesisState GenesisState) (err error) { + err = validateGenesisStateAccounts(genesisState.Accounts) if err != nil { return } - cliPrint = json.RawMessage(bz) - appGenTx, _, validator, err = IrisAppGenTxNF(cdc, pk, addr, genTxConfig.Name) + // skip stakeData validation as genesis is created from txs + if len(genesisState.GenTxs) > 0 { + return nil + } + return stake.ValidateGenesis(genesisState.StakeData) +} + +// Ensures that there are no duplicate accounts in the genesis state, +func validateGenesisStateAccounts(accs []GenesisAccount) (err error) { + addrMap := make(map[string]bool, len(accs)) + for i := 0; i < len(accs); i++ { + acc := accs[i] + strAddr := string(acc.Address) + if _, ok := addrMap[strAddr]; ok { + return fmt.Errorf("Duplicate account in genesis state: Address %v", acc.Address) + } + addrMap[strAddr] = true + } 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) { +// IrisAppGenState but with JSON +func IrisAppGenStateJSON(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []json.RawMessage) ( + appState json.RawMessage, err error) { - var bz []byte - gaiaGenTx := IrisGenTx{ - Name: name, - Address: addr, - PubKey: sdk.MustBech32ifyAccPub(pk), - } - bz, err = wire.MarshalJSONIndent(cdc, gaiaGenTx) + // create the final app state + genesisState, err := IrisAppGenState(cdc, genDoc, appGenTxs) if err != nil { - return - } - appGenTx = json.RawMessage(bz) - - validator = tmtypes.GenesisValidator{ - PubKey: pk, - Power: feeAmt, + return nil, err } + appState, err = codec.MarshalJSONIndent(cdc, genesisState) 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) { +// CollectStdTxs processes and validates application's genesis StdTxs and returns +// the list of appGenTxs, and persistent peers required to generate genesis.json. +func CollectStdTxs(cdc *codec.Codec, moniker string, genTxsDir string, genDoc tmtypes.GenesisDoc) ( + appGenTxs []auth.StdTx, persistentPeers string, err error) { - if len(appGenTxs) == 0 { - err = errors.New("must provide at least genesis transaction") - return + var fos []os.FileInfo + fos, err = ioutil.ReadDir(genTxsDir) + if err != nil { + return appGenTxs, persistentPeers, err } - stakeData := createGenesisState() - genaccs := make([]GenesisAccount, len(appGenTxs)) - for i, appGenTx := range appGenTxs { + // prepare a map of all accounts in genesis state to then validate + // against the validators addresses + var appState GenesisState + if err := cdc.UnmarshalJSON(genDoc.AppState, &appState); err != nil { + return appGenTxs, persistentPeers, err + } + addrMap := make(map[string]GenesisAccount, len(appState.Accounts)) + for i := 0; i < len(appState.Accounts); i++ { + acc := appState.Accounts[i] + strAddr := string(acc.Address) + addrMap[strAddr] = acc + } + + // addresses and IPs (and port) validator server info + var addressesIPs []string - var genTx IrisGenTx - err = cdc.UnmarshalJSON(appGenTx, &genTx) - if err != nil { - return + for _, fo := range fos { + filename := filepath.Join(genTxsDir, fo.Name()) + if !fo.IsDir() && (filepath.Ext(filename) != ".json") { + continue } - // 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, + // get the genStdTx + var jsonRawTx []byte + if jsonRawTx, err = ioutil.ReadFile(filename); err != nil { + return appGenTxs, persistentPeers, err } - 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, - } + var genStdTx auth.StdTx + if err = cdc.UnmarshalJSON(jsonRawTx, &genStdTx); err != nil { + return appGenTxs, persistentPeers, err + } + appGenTxs = append(appGenTxs, genStdTx) + + // the memo flag is used to store + // the ip and node-id, for example this may be: + // "528fd3df22b31f4969b05652bfe8f0fe921321d5@192.168.2.37:26656" + nodeAddrIP := genStdTx.GetMemo() + if len(nodeAddrIP) == 0 { + return appGenTxs, persistentPeers, fmt.Errorf( + "couldn't find node's address and IP in %s", fo.Name()) + } + + // genesis transactions must be single-message + msgs := genStdTx.GetMsgs() + if len(msgs) != 1 { - stakeData.Bonds = append(stakeData.Bonds, delegation) + return appGenTxs, persistentPeers, errors.New( + "each genesis transaction must provide a single genesis message") } - } - // create the final app state - genesisState = GenesisState{ - Accounts: genaccs, - StakeData: stakeData, - GovData: gov.DefaultGenesisState(), - UpgradeData: upgrade.DefaultGenesisState(), + // validate the validator address and funds against the accounts in the state + msg := msgs[0].(stake.MsgCreateValidator) + addr := string(sdk.AccAddress(msg.ValidatorAddr)) + acc, ok := addrMap[addr] + if !ok { + return appGenTxs, persistentPeers, fmt.Errorf( + "account %v not in genesis.json: %+v", addr, addrMap) + } + if acc.Coins.AmountOf(msg.Delegation.Denom).LT(msg.Delegation.Amount) { + err = fmt.Errorf("insufficient fund for the delegation: %s < %s", + acc.Coins.AmountOf(msg.Delegation.Denom), msg.Delegation.Amount) + } + + // exclude itself from persistent peers + if msg.Description.Moniker != moniker { + addressesIPs = append(addressesIPs, nodeAddrIP) + } } - return -} -// IrisAppGenState but with JSON -func IrisAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) { + sort.Strings(addressesIPs) + persistentPeers = strings.Join(addressesIPs, ",") - // create the final app state - genesisState, err := IrisAppGenState(cdc, appGenTxs) - if err != nil { - return nil, err + return appGenTxs, persistentPeers, nil +} + +func NewDefaultGenesisAccount(addr sdk.AccAddress) GenesisAccount { + accAuth := auth.NewBaseAccountWithAddress(addr) + accAuth.Coins = []sdk.Coin{ + FreeFermionAcc, } - appState, err = wire.MarshalJSONIndent(cdc, genesisState) - return + return NewGenesisAccount(&accAuth) } -func createGenesisState() stake.GenesisState { +func createStakeGenesisState() 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(), + LooseTokens: sdk.ZeroDec(), + BondedTokens: sdk.ZeroDec(), }, 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, + UnbondingTime: defaultUnbondingTime, + MaxValidators: 100, + BondDenom: StakeDenom, + }, + } +} + +func createMintGenesisState() mint.GenesisState { + return mint.GenesisState{ + Minter: mint.InitialMinter(), + Params: mint.Params{ + MintDenom: StakeDenom, + InflationRateChange: sdk.NewDecWithPrec(13, 2), + InflationMax: sdk.NewDecWithPrec(20, 2), + InflationMin: sdk.NewDecWithPrec(7, 2), + GoalBonded: sdk.NewDecWithPrec(67, 2), }, } } diff --git a/examples/irishub-bugfix-2/cmd/iris2-bugfix/main.go b/examples/irishub-bugfix-2/cmd/iris2-bugfix/main.go index c0a94138a..d794655c7 100644 --- a/examples/irishub-bugfix-2/cmd/iris2-bugfix/main.go +++ b/examples/irishub-bugfix-2/cmd/iris2-bugfix/main.go @@ -6,12 +6,11 @@ import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" + "github.com/irisnet/irishub/client" "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/tools/prometheus" "github.com/irisnet/irishub/version" "github.com/spf13/viper" abci "github.com/tendermint/tendermint/abci/types" @@ -19,9 +18,18 @@ import ( dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" tmtypes "github.com/tendermint/tendermint/types" + irisInit "github.com/irisnet/irishub/init" + sdk "github.com/cosmos/cosmos-sdk/types" ) func main() { + config := sdk.GetConfig() + config.SetBech32PrefixForAccount(irisInit.Bech32PrefixAccAddr, irisInit.Bech32PrefixAccPub) + config.SetBech32PrefixForValidator(irisInit.Bech32PrefixValAddr, irisInit.Bech32PrefixValPub) + config.SetBech32PrefixForConsensusNode(irisInit.Bech32PrefixConsAddr, irisInit.Bech32PrefixConsPub) + config.Seal() + + cdc := app.MakeCodec() ctx := server.NewDefaultContext() cobra.EnableCommandSorting = false @@ -41,18 +49,21 @@ func main() { tendermintCmd.AddCommand( server.ShowNodeIDCmd(ctx), server.ShowValidatorCmd(ctx), + server.ShowAddressCmd(ctx), ) - startCmd := server.StartCmd(ctx, server.ConstructAppCreator(newApp, "iris")) + startCmd := server.StartCmd(ctx, newApp) startCmd.Flags().Bool(app.FlagReplay, false, "Replay the last block") rootCmd.AddCommand( - server.InitCmd(ctx, cdc, app.IrisAppInit()), + irisInit.InitCmd(ctx, cdc, app.IrisAppInit()), + irisInit.GenTxCmd(ctx,cdc), + irisInit.TestnetFilesCmd(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")), + server.ExportCmd(ctx, cdc, exportAppStateAndTMValidators), client.LineBreak, ) @@ -60,8 +71,6 @@ func main() { version.ServeVersionCommand(cdc), ) - rootCmd.AddCommand(prometheus.MonitorCommand(cdc)) - // prepare and add flags executor := cli.PrepareBaseCmd(rootCmd, "IRIS", app.DefaultNodeHome) executor.Execute() diff --git a/examples/irishub-bugfix-2/cmd/iriscli2-bugfix/main.go b/examples/irishub-bugfix-2/cmd/iriscli2-bugfix/main.go index 32e66e668..8dc88f3c3 100644 --- a/examples/irishub-bugfix-2/cmd/iriscli2-bugfix/main.go +++ b/examples/irishub-bugfix-2/cmd/iriscli2-bugfix/main.go @@ -16,6 +16,8 @@ import ( "github.com/irisnet/irishub/version" "github.com/spf13/cobra" "github.com/tendermint/tendermint/libs/cli" + sdk "github.com/cosmos/cosmos-sdk/types" + irisInit "github.com/irisnet/irishub/init" ) // rootCmd is the entry point for this binary @@ -29,7 +31,11 @@ var ( func main() { cobra.EnableCommandSorting = false cdc := app.MakeCodec() - + config := sdk.GetConfig() + config.SetBech32PrefixForAccount(irisInit.Bech32PrefixAccAddr, irisInit.Bech32PrefixAccPub) + config.SetBech32PrefixForValidator(irisInit.Bech32PrefixValAddr, irisInit.Bech32PrefixValPub) + config.SetBech32PrefixForConsensusNode(irisInit.Bech32PrefixConsAddr, irisInit.Bech32PrefixConsPub) + config.Seal() rootCmd.AddCommand(tendermintrpccmd.StatusCommand()) //Add state commands tendermintCmd := &cobra.Command{ @@ -141,7 +147,6 @@ func main() { } ibcCmd.AddCommand( client.PostCommands( - ibccmd.IBCTransferCmd(cdc), ibccmd.IBCSetCmd(cdc), ibccmd.IBCGetCmd(cdc), )...) 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 8a729b697..000000000 --- a/examples/irishub-bugfix-2/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-2/ibc/client/cli/tx.go b/examples/irishub-bugfix-2/ibc/client/cli/tx.go index 1fbe5dd96..1730c0993 100644 --- a/examples/irishub-bugfix-2/ibc/client/cli/tx.go +++ b/examples/irishub-bugfix-2/ibc/client/cli/tx.go @@ -5,14 +5,14 @@ import ( "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" + "github.com/cosmos/cosmos-sdk/codec" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/irisnet/irishub/examples/irishub-bugfix-2/ibc" "os" ) // IBC transfer command -func IBCGetCmd(cdc *wire.Codec) *cobra.Command { +func IBCGetCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "get", RunE: func(cmd *cobra.Command, args []string) error { @@ -40,7 +40,7 @@ func IBCGetCmd(cdc *wire.Codec) *cobra.Command { // IBC transfer command -func IBCSetCmd(cdc *wire.Codec) *cobra.Command { +func IBCSetCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "set", RunE: func(cmd *cobra.Command, args []string) error { diff --git a/examples/irishub-bugfix-2/ibc/handler.go b/examples/irishub-bugfix-2/ibc/handler.go index de1ecfa27..e12905d85 100644 --- a/examples/irishub-bugfix-2/ibc/handler.go +++ b/examples/irishub-bugfix-2/ibc/handler.go @@ -11,10 +11,6 @@ import ( 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: @@ -26,41 +22,6 @@ func NewHandler(ibcm Mapper, ck bank.Keeper, uk upgrade.Keeper) sdk.Handler { } } -// 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 { diff --git a/examples/irishub-bugfix-2/ibc/mapper.go b/examples/irishub-bugfix-2/ibc/mapper.go index 2ccc93d1a..8a05fdfa8 100644 --- a/examples/irishub-bugfix-2/ibc/mapper.go +++ b/examples/irishub-bugfix-2/ibc/mapper.go @@ -4,19 +4,19 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" + codec "github.com/cosmos/cosmos-sdk/codec" ) // IBC Mapper type Mapper struct { key sdk.StoreKey - cdc *wire.Codec + cdc *codec.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 { +func NewMapper(cdc *codec.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) Mapper { // XXX: How are these codecs supposed to work? return Mapper{ key: key, @@ -33,13 +33,13 @@ 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) + bz, err := ibcm.cdc.MarshalBinaryLengthPrefixed(packet) if err != nil { panic(err) } store.Set(EgressKey(packet.DestChain, index), bz) - bz, err = ibcm.cdc.MarshalBinary(index + 1) + bz, err = ibcm.cdc.MarshalBinaryLengthPrefixed(index + 1) if err != nil { panic(err) } @@ -60,16 +60,16 @@ func (ibcm Mapper) ReceiveIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error // -------------------------- // Functions for accessing the underlying KVStore. -func marshalBinaryPanic(cdc *wire.Codec, value interface{}) []byte { - res, err := cdc.MarshalBinary(value) +func MarshalBinaryLengthPrefixedPanic(cdc *codec.Codec, value interface{}) []byte { + res, err := cdc.MarshalBinaryLengthPrefixed(value) if err != nil { panic(err) } return res } -func unmarshalBinaryPanic(cdc *wire.Codec, bz []byte, ptr interface{}) { - err := cdc.UnmarshalBinary(bz, ptr) +func unMarshalBinaryLengthPrefixedPanic(cdc *codec.Codec, bz []byte, ptr interface{}) { + err := cdc.UnmarshalBinaryLengthPrefixed(bz, ptr) if err != nil { panic(err) } @@ -82,13 +82,13 @@ func (ibcm Mapper) GetIngressSequence(ctx sdk.Context, srcChain string) int64 { bz := store.Get(key) if bz == nil { - zero := marshalBinaryPanic(ibcm.cdc, int64(0)) + zero := MarshalBinaryLengthPrefixedPanic(ibcm.cdc, int64(0)) store.Set(key, zero) return 0 } var res int64 - unmarshalBinaryPanic(ibcm.cdc, bz, &res) + unMarshalBinaryLengthPrefixedPanic(ibcm.cdc, bz, &res) return res } @@ -97,7 +97,7 @@ func (ibcm Mapper) SetIngressSequence(ctx sdk.Context, srcChain string, sequence store := ctx.KVStore(ibcm.key) key := IngressSequenceKey(srcChain) - bz := marshalBinaryPanic(ibcm.cdc, sequence) + bz := MarshalBinaryLengthPrefixedPanic(ibcm.cdc, sequence) store.Set(key, bz) } @@ -105,12 +105,12 @@ func (ibcm Mapper) SetIngressSequence(ctx sdk.Context, srcChain string, sequence func (ibcm Mapper) getEgressLength(store sdk.KVStore, destChain string) int64 { bz := store.Get(EgressLengthKey(destChain)) if bz == nil { - zero := marshalBinaryPanic(ibcm.cdc, int64(0)) + zero := MarshalBinaryLengthPrefixedPanic(ibcm.cdc, int64(0)) store.Set(EgressLengthKey(destChain), zero) return 0 } var res int64 - unmarshalBinaryPanic(ibcm.cdc, bz, &res) + unMarshalBinaryLengthPrefixedPanic(ibcm.cdc, bz, &res) return res } @@ -138,12 +138,12 @@ func (ibcm Mapper) Get(ctx sdk.Context) (string, bool) { return " ", false } var Addr string - ibcm.cdc.MustUnmarshalBinary(bz, &Addr) + ibcm.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &Addr) return Addr, true } func (ibcm Mapper) Set(ctx sdk.Context,Addr string) { store := ctx.KVStore(ibcm.key) - bz := ibcm.cdc.MustMarshalBinary(Addr) + bz := ibcm.cdc.MustMarshalBinaryLengthPrefixed(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 index 0537ff816..8417c1307 100644 --- a/examples/irishub-bugfix-2/ibc/types.go +++ b/examples/irishub-bugfix-2/ibc/types.go @@ -4,15 +4,15 @@ import ( "encoding/json" sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" + codec "github.com/cosmos/cosmos-sdk/codec" ) var ( - msgCdc *wire.Codec + msgCdc *codec.Codec ) func init() { - msgCdc = wire.NewCodec() + msgCdc = codec.New() } // ------------------------------ @@ -127,6 +127,8 @@ type IBCSetMsg struct { Addr sdk.AccAddress } +var _ sdk.Msg = (*IBCSetMsg)(nil) + func NewIBCSetMsg(addr sdk.AccAddress) IBCSetMsg { return IBCSetMsg{ Addr:addr, @@ -134,6 +136,10 @@ func NewIBCSetMsg(addr sdk.AccAddress) IBCSetMsg { } func (msg IBCSetMsg) Type() string { + return "ibc-set" +} + +func (msg IBCSetMsg) Route() string { return "ibc-1" } @@ -157,6 +163,8 @@ type IBCGetMsg struct { Addr sdk.AccAddress } +var _ sdk.Msg = (*IBCGetMsg)(nil) + func NewIBCGetMsg(addr sdk.AccAddress) IBCGetMsg { return IBCGetMsg{ Addr:addr, @@ -164,6 +172,10 @@ func NewIBCGetMsg(addr sdk.AccAddress) IBCGetMsg { } func (msg IBCGetMsg) Type() string { + return "ibc-get" +} + +func (msg IBCGetMsg) Route() string { return "ibc-1" } diff --git a/examples/irishub-bugfix-2/ibc/wire.go b/examples/irishub-bugfix-2/ibc/wire.go index 821a527ab..5811cf389 100644 --- a/examples/irishub-bugfix-2/ibc/wire.go +++ b/examples/irishub-bugfix-2/ibc/wire.go @@ -1,11 +1,11 @@ package ibc import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" ) -// Register concrete types on wire codec -func RegisterWire(cdc *wire.Codec) { +// Register concrete types on codec codec +func RegisterCodec(cdc *codec.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) diff --git a/examples/irishub1/app/app.go b/examples/irishub1/app/app.go index 8fead84f1..6923b456f 100644 --- a/examples/irishub1/app/app.go +++ b/examples/irishub1/app/app.go @@ -2,40 +2,37 @@ package app import ( "encoding/json" + "fmt" "io" "os" + "sort" + "strings" - "errors" - "fmt" - "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/codec" 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" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + ibc1 "github.com/irisnet/irishub/examples/irishub1/ibc" + "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/stake" bam "github.com/irisnet/irishub/baseapp" - ibc1 "github.com/irisnet/irishub/examples/irishub1/ibc" + "github.com/irisnet/irishub/iparam" "github.com/irisnet/irishub/modules/gov" "github.com/irisnet/irishub/modules/gov/params" - "github.com/irisnet/irishub/modules/iparam" + "github.com/irisnet/irishub/modules/service" + "github.com/irisnet/irishub/modules/service/params" "github.com/irisnet/irishub/modules/record" "github.com/irisnet/irishub/modules/upgrade" "github.com/irisnet/irishub/modules/upgrade/params" - "github.com/irisnet/irishub/modules/iservice" "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" tmtypes "github.com/tendermint/tendermint/types" - "strings" ) const ( @@ -45,6 +42,7 @@ const ( // default home directories for expected binaries var ( + DefaultLCDHome = os.ExpandEnv("$HOME/.irislcd") DefaultCLIHome = os.ExpandEnv("$HOME/.iriscli") DefaultNodeHome = os.ExpandEnv("$HOME/.iris") ) @@ -52,33 +50,39 @@ var ( // Extended ABCI application type IrisApp struct { *bam.BaseApp - cdc *wire.Codec + cdc *codec.Codec // keys to access the substores keyMain *sdk.KVStoreKey keyAccount *sdk.KVStoreKey keyIBC *sdk.KVStoreKey keyStake *sdk.KVStoreKey + tkeyStake *sdk.TransientStoreKey keySlashing *sdk.KVStoreKey + keyMint *sdk.KVStoreKey + keyDistr *sdk.KVStoreKey + tkeyDistr *sdk.TransientStoreKey keyGov *sdk.KVStoreKey keyFeeCollection *sdk.KVStoreKey keyParams *sdk.KVStoreKey + tkeyParams *sdk.TransientStoreKey keyUpgrade *sdk.KVStoreKey - keyIservice *sdk.KVStoreKey + keyService *sdk.KVStoreKey keyRecord *sdk.KVStoreKey // Manage getting and setting accounts - accountMapper auth.AccountMapper + accountMapper auth.AccountKeeper feeCollectionKeeper auth.FeeCollectionKeeper - coinKeeper bank.Keeper - ibcMapper ibc.Mapper + bankKeeper bank.Keeper ibc1Mapper ibc1.Mapper stakeKeeper stake.Keeper slashingKeeper slashing.Keeper - paramsKeeper params.Keeper + mintKeeper mint.Keeper + distrKeeper distr.Keeper govKeeper gov.Keeper + paramsKeeper params.Keeper upgradeKeeper upgrade.Keeper - iserviceKeeper iservice.Keeper + serviceKeeper service.Keeper recordKeeper record.Keeper // fee manager @@ -88,7 +92,7 @@ type IrisApp struct { 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 := bam.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...) bApp.SetCommitMultiStoreTracer(traceStore) // create your application object @@ -99,62 +103,127 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio keyAccount: sdk.NewKVStoreKey("acc"), keyIBC: sdk.NewKVStoreKey("ibc"), keyStake: sdk.NewKVStoreKey("stake"), + tkeyStake: sdk.NewTransientStoreKey("transient_stake"), + keyMint: sdk.NewKVStoreKey("mint"), + keyDistr: sdk.NewKVStoreKey("distr"), + tkeyDistr: sdk.NewTransientStoreKey("transient_distr"), keySlashing: sdk.NewKVStoreKey("slashing"), keyGov: sdk.NewKVStoreKey("gov"), keyRecord: sdk.NewKVStoreKey("record"), keyFeeCollection: sdk.NewKVStoreKey("fee"), keyParams: sdk.NewKVStoreKey("params"), + tkeyParams: sdk.NewTransientStoreKey("transient_params"), keyUpgrade: sdk.NewKVStoreKey("upgrade"), - keyIservice: sdk.NewKVStoreKey("iservice"), + keyService: sdk.NewKVStoreKey("service"), } var lastHeight int64 if viper.GetBool(FlagReplay) { - lastHeight = app.replay() + lastHeight = bam.Replay(app.Logger) } - // define the accountMapper - app.accountMapper = auth.NewAccountMapper( + // define the AccountKeeper + app.accountMapper = auth.NewAccountKeeper( app.cdc, app.keyAccount, // target store auth.ProtoBaseAccount, // prototype ) // add handlers - app.paramsKeeper = params.NewKeeper(cdc, app.keyParams) - app.coinKeeper = bank.NewKeeper(app.accountMapper) - app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace)) + app.bankKeeper = bank.NewBaseKeeper(app.accountMapper) + app.feeCollectionKeeper = auth.NewFeeCollectionKeeper( + app.cdc, + app.keyFeeCollection, + ) + app.paramsKeeper = params.NewKeeper( + app.cdc, + app.keyParams, app.tkeyParams, + ) + stakeKeeper := stake.NewKeeper( + app.cdc, + app.keyStake, app.tkeyStake, + app.bankKeeper, app.paramsKeeper.Subspace(stake.DefaultParamspace), + app.RegisterCodespace(stake.DefaultCodespace), + ) + app.mintKeeper = mint.NewKeeper(app.cdc, app.keyMint, + app.paramsKeeper.Subspace(mint.DefaultParamspace), + &stakeKeeper, app.feeCollectionKeeper, + ) + app.distrKeeper = distr.NewKeeper( + app.cdc, + app.keyDistr, + app.paramsKeeper.Subspace(distr.DefaultParamspace), + app.bankKeeper, &stakeKeeper, app.feeCollectionKeeper, + app.RegisterCodespace(stake.DefaultCodespace), + ) + app.slashingKeeper = slashing.NewKeeper( + app.cdc, + app.keySlashing, + &stakeKeeper, app.paramsKeeper.Subspace(slashing.DefaultParamspace), + app.RegisterCodespace(slashing.DefaultCodespace), + ) + + app.govKeeper = gov.NewKeeper( + app.cdc, + app.keyGov, + app.bankKeeper, &stakeKeeper, + app.RegisterCodespace(gov.DefaultCodespace), + ) + + app.recordKeeper = record.NewKeeper( + app.cdc, + app.keyRecord, + app.RegisterCodespace(record.DefaultCodespace), + ) + app.serviceKeeper = service.NewKeeper( + app.cdc, + app.keyService, + app.bankKeeper, + app.RegisterCodespace(service.DefaultCodespace), + ) + + // register the staking hooks + // NOTE: stakeKeeper above are passed by reference, + // so that it can be modified like below: + app.stakeKeeper = *stakeKeeper.SetHooks( + NewHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks())) + + app.upgradeKeeper = upgrade.NewKeeper( + app.cdc, + app.keyUpgrade, app.stakeKeeper, + ) + 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.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.coinKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace)) - app.recordKeeper = record.NewKeeper(app.cdc, app.keyRecord, app.RegisterCodespace(record.DefaultCodespace)) - app.iserviceKeeper = iservice.NewKeeper(app.cdc, app.keyIservice, app.RegisterCodespace(iservice.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("bank", []*sdk.KVStoreKey{app.keyAccount}, bank.NewHandler(app.bankKeeper)). + AddRoute("ibc-1", []*sdk.KVStoreKey{app.keyIBC, app.keyAccount}, ibc1.NewHandler(app.ibc1Mapper, app.bankKeeper)). + AddRoute("stake", []*sdk.KVStoreKey{app.keyStake, app.keyAccount, app.keyMint, app.keyDistr}, stake.NewHandler(app.stakeKeeper)). AddRoute("slashing", []*sdk.KVStoreKey{app.keySlashing, app.keyStake}, slashing.NewHandler(app.slashingKeeper)). + AddRoute("distr", []*sdk.KVStoreKey{app.keyDistr}, distr.NewHandler(app.distrKeeper)). 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("record", []*sdk.KVStoreKey{app.keyRecord}, record.NewHandler(app.recordKeeper)). - AddRoute("iservice", []*sdk.KVStoreKey{app.keyIservice}, iservice.NewHandler(app.iserviceKeeper)) + AddRoute("service", []*sdk.KVStoreKey{app.keyService}, service.NewHandler(app.serviceKeeper)) + + app.QueryRouter(). + AddRoute("gov", gov.NewQuerier(app.govKeeper)). + AddRoute("stake", stake.NewQuerier(app.stakeKeeper, app.cdc)) + + app.feeManager = bam.NewFeeManager(app.paramsKeeper.Subspace("Fee")) - app.feeManager = bam.NewFeeManager(app.paramsKeeper.Setter()) // initialize BaseApp + app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake, app.keySlashing, app.keyGov, app.keyMint, app.keyDistr, + app.keyFeeCollection, app.keyParams, app.keyUpgrade, app.keyRecord, app.keyService) app.SetInitChainer(app.initChainer) app.SetBeginBlocker(app.BeginBlocker) - app.SetEndBlocker(app.EndBlocker) app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) + app.MountStoresTransient(app.tkeyParams, app.tkeyStake, app.tkeyDistr) 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.keyRecord, app.keyIservice) + app.SetEndBlocker(app.EndBlocker) app.SetRunMsg(app.runMsgs) var err error @@ -170,15 +239,32 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio upgrade.RegisterModuleList(app.Router()) app.upgradeKeeper.RefreshVersionList(app.GetKVStore(app.keyUpgrade)) - iparam.SetParamReadWriter(app.paramsKeeper.Setter(), - &govparams.DepositProcedureParameter, - &govparams.VotingProcedureParameter, - &govparams.TallyingProcedureParameter, + iparam.SetParamReadWriter(app.paramsKeeper.Subspace(iparam.SignalParamspace).WithTypeTable( + params.NewTypeTable( + upgradeparams.CurrentUpgradeProposalIdParameter.GetStoreKey(), uint64((0)), + upgradeparams.ProposalAcceptHeightParameter.GetStoreKey(), int64(0), + upgradeparams.SwitchPeriodParameter.GetStoreKey(), int64(0), + )), &upgradeparams.CurrentUpgradeProposalIdParameter, &upgradeparams.ProposalAcceptHeightParameter, &upgradeparams.SwitchPeriodParameter) - iparam.RegisterGovParamMapping(&govparams.DepositProcedureParameter, + iparam.SetParamReadWriter(app.paramsKeeper.Subspace(iparam.GovParamspace).WithTypeTable( + params.NewTypeTable( + govparams.DepositProcedureParameter.GetStoreKey(), govparams.DepositProcedure{}, + govparams.VotingProcedureParameter.GetStoreKey(), govparams.VotingProcedure{}, + govparams.TallyingProcedureParameter.GetStoreKey(), govparams.TallyingProcedure{}, + serviceparams.MaxRequestTimeoutParameter.GetStoreKey(), int64(0), + serviceparams.MinProviderDepositParameter.GetStoreKey(), sdk.Coins{}, + )), + &govparams.DepositProcedureParameter, + &govparams.VotingProcedureParameter, + &govparams.TallyingProcedureParameter, + &serviceparams.MaxRequestTimeoutParameter, + &serviceparams.MinProviderDepositParameter) + + iparam.RegisterGovParamMapping( + &govparams.DepositProcedureParameter, &govparams.VotingProcedureParameter, &govparams.TallyingProcedureParameter) @@ -186,21 +272,20 @@ func NewIrisApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio } // 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) - record.RegisterWire(cdc) - auth.RegisterWire(cdc) - upgrade.RegisterWire(cdc) - iservice.RegisterWire(cdc) - sdk.RegisterWire(cdc) - wire.RegisterCrypto(cdc) +func MakeCodec() *codec.Codec { + var cdc = codec.New() + ibc1.RegisterCodec(cdc) + bank.RegisterCodec(cdc) + stake.RegisterCodec(cdc) + distr.RegisterCodec(cdc) + slashing.RegisterCodec(cdc) + gov.RegisterCodec(cdc) + record.RegisterCodec(cdc) + upgrade.RegisterCodec(cdc) + service.RegisterCodec(cdc) + auth.RegisterCodec(cdc) + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) return cdc } @@ -208,6 +293,12 @@ func MakeCodec() *wire.Codec { func (app *IrisApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { tags := slashing.BeginBlocker(ctx, req, app.slashingKeeper) + // distribute rewards from previous block + distr.BeginBlocker(ctx, req, app.distrKeeper) + + // mint new tokens for this new block + mint.BeginBlocker(ctx, app.mintKeeper) + return abci.ResponseBeginBlock{ Tags: tags.ToKVPairs(), } @@ -218,8 +309,6 @@ func (app *IrisApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.R tags := gov.EndBlocker(ctx, app.govKeeper) validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) tags.AppendTags(upgrade.EndBlocker(ctx, app.upgradeKeeper)) - // Add these new validators to the addr -> pubkey map. - app.slashingKeeper.AddValidators(ctx, validatorUpdates) return abci.ResponseEndBlock{ ValidatorUpdates: validatorUpdates, Tags: tags, @@ -235,6 +324,10 @@ func (app *IrisApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci if err != nil { panic(err) } + // sort by account number to maintain consistency + sort.Slice(genesisState.Accounts, func(i, j int) bool { + return genesisState.Accounts[i].AccountNumber < genesisState.Accounts[j].AccountNumber + }) // load the accounts for _, gacc := range genesisState.Accounts { @@ -255,12 +348,52 @@ 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.paramsKeeper.Setter(), feeTokenGensisConfig) + bam.InitGenesis(ctx, app.feeManager, feeTokenGensisConfig) // load the address to pubkey map - slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.StakeData) + auth.InitGenesis(ctx, app.feeCollectionKeeper, genesisState.AuthData) + slashing.InitGenesis(ctx, app.slashingKeeper, genesisState.SlashingData, genesisState.StakeData) + mint.InitGenesis(ctx, app.mintKeeper, genesisState.MintData) + distr.InitGenesis(ctx, app.distrKeeper, genesisState.DistrData) + err = IrisValidateGenesisState(genesisState) + if err != nil { + panic(err) // TODO find a way to do this w/o panics + } + + if len(genesisState.GenTxs) > 0 { + for _, genTx := range genesisState.GenTxs { + var tx auth.StdTx + err = app.cdc.UnmarshalJSON(genTx, &tx) + if err != nil { + panic(err) + } + bz := app.cdc.MustMarshalBinaryLengthPrefixed(tx) + res := app.BaseApp.DeliverTx(bz) + if !res.IsOK() { + panic(res.Log) + } + } + + validators = app.stakeKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + } + + // sanity check + if len(req.Validators) > 0 { + if len(req.Validators) != len(validators) { + panic(fmt.Errorf("len(RequestInitChain.Validators) != len(validators) (%d != %d)", + len(req.Validators), len(validators))) + } + sort.Sort(abci.ValidatorUpdates(req.Validators)) + sort.Sort(abci.ValidatorUpdates(validators)) + for i, val := range validators { + if !val.Equal(req.Validators[i]) { + panic(fmt.Errorf("validators[%d] != req.Validators[%d] ", i, i)) + } + } + } upgrade.InitGenesis(ctx, app.upgradeKeeper, app.Router(), genesisState.UpgradeData) + service.InitGenesis(ctx, genesisState.ServiceData) return abci.ResponseInitChain{ Validators: validators, @@ -279,12 +412,18 @@ func (app *IrisApp) ExportAppStateAndValidators() (appState json.RawMessage, val return false } app.accountMapper.IterateAccounts(ctx, appendAccount) - - genState := GenesisState{ - Accounts: accounts, - StakeData: stake.WriteGenesis(ctx, app.stakeKeeper), - } - appState, err = wire.MarshalJSONIndent(app.cdc, genState) + genState := NewGenesisState( + accounts, + auth.ExportGenesis(ctx, app.feeCollectionKeeper), + stake.ExportGenesis(ctx, app.stakeKeeper), + mint.ExportGenesis(ctx, app.mintKeeper), + distr.ExportGenesis(ctx, app.distrKeeper), + gov.ExportGenesis(ctx, app.govKeeper), + upgrade.WriteGenesis(ctx, app.upgradeKeeper), + service.WriteGenesis(ctx), + slashing.ExportGenesis(ctx, app.slashingKeeper), + ) + appState, err = codec.MarshalJSONIndent(app.cdc, genState) if err != nil { return nil, nil, err } @@ -301,9 +440,17 @@ func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg, mode bam.RunTxMode) var code sdk.ABCICodeType for msgIdx, msg := range msgs { // Match route. - msgType, err := app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) - if err != nil { - return err.Result() + var msgType string + var err sdk.Error + if ctx.BlockHeight() != 0 { + msgType, err = app.upgradeKeeper.GetMsgTypeInCurrentVersion(ctx, msg) + + if err != nil { + return err.Result() + } + + } else { + msgType = msg.Route() } handler := app.Router().Route(msgType) @@ -347,36 +494,61 @@ func (app *IrisApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg, mode bam.RunTxMode) 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 +// Combined Staking Hooks +type Hooks struct { + dh distr.Hooks + sh slashing.Hooks } + +func NewHooks(dh distr.Hooks, sh slashing.Hooks) Hooks { + return Hooks{dh, sh} +} + +var _ sdk.StakingHooks = Hooks{} + +func (h Hooks) OnValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { + h.dh.OnValidatorCreated(ctx, valAddr) + h.sh.OnValidatorCreated(ctx, valAddr) +} +func (h Hooks) OnValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) { + h.dh.OnValidatorModified(ctx, valAddr) + h.sh.OnValidatorModified(ctx, valAddr) +} + +func (h Hooks) OnValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.OnValidatorRemoved(ctx, consAddr, valAddr) + h.sh.OnValidatorRemoved(ctx, consAddr, valAddr) +} + +func (h Hooks) OnValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.OnValidatorBonded(ctx, consAddr, valAddr) + h.sh.OnValidatorBonded(ctx, consAddr, valAddr) +} + +func (h Hooks) OnValidatorPowerDidChange(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.OnValidatorPowerDidChange(ctx, consAddr, valAddr) + h.sh.OnValidatorPowerDidChange(ctx, consAddr, valAddr) +} + +func (h Hooks) OnValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { + h.dh.OnValidatorBeginUnbonding(ctx, consAddr, valAddr) + h.sh.OnValidatorBeginUnbonding(ctx, consAddr, valAddr) +} + +func (h Hooks) OnDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.OnDelegationCreated(ctx, delAddr, valAddr) + h.sh.OnDelegationCreated(ctx, delAddr, valAddr) +} + +func (h Hooks) OnDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.OnDelegationSharesModified(ctx, delAddr, valAddr) + h.sh.OnDelegationSharesModified(ctx, delAddr, valAddr) +} + +func (h Hooks) OnDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { + h.dh.OnDelegationRemoved(ctx, delAddr, valAddr) + h.sh.OnDelegationRemoved(ctx, delAddr, valAddr) +} + diff --git a/examples/irishub1/app/genesis.go b/examples/irishub1/app/genesis.go index 2067a1d8d..4da26e9a9 100644 --- a/examples/irishub1/app/genesis.go +++ b/examples/irishub1/app/genesis.go @@ -3,242 +3,345 @@ package app import ( "encoding/json" "errors" - - "github.com/spf13/pflag" - "github.com/tendermint/tendermint/crypto" - tmtypes "github.com/tendermint/tendermint/types" - "fmt" + "io/ioutil" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/cosmos/cosmos-sdk/codec" "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" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/stake" "github.com/irisnet/irishub/modules/gov" "github.com/irisnet/irishub/modules/upgrade" + "github.com/irisnet/irishub/modules/service" "github.com/irisnet/irishub/types" - "time" + tmtypes "github.com/tendermint/tendermint/types" ) -// DefaultKeyPass contains the default key password for genesis transactions -const DefaultKeyPass = "1234567890" +var ( + Denom = "iris" + StakeDenom = Denom + "-" + types.Atto + FeeAmt = int64(100) + IrisCt = types.NewDefaultCoinType(Denom) + FreeFermionVal, _ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", FeeAmt, Denom)) + FreeFermionAcc, _ = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", int64(150), Denom)) +) + +const ( + defaultUnbondingTime time.Duration = 60 * 10 * time.Second + // DefaultKeyPass contains the default key password for genesis transactions + DefaultKeyPass = "1234567890" +) // State to Unmarshal type GenesisState struct { - Accounts []GenesisAccount `json:"accounts"` - StakeData stake.GenesisState `json:"stake"` - GovData gov.GenesisState `json:"gov"` - UpgradeData upgrade.GenesisState `json:"upgrade"` + Accounts []GenesisAccount `json:"accounts"` + AuthData auth.GenesisState `json:"auth"` + StakeData stake.GenesisState `json:"stake"` + MintData mint.GenesisState `json:"mint"` + DistrData distr.GenesisState `json:"distr"` + GovData gov.GenesisState `json:"gov"` + UpgradeData upgrade.GenesisState `json:"upgrade"` + SlashingData slashing.GenesisState `json:"slashing"` + ServiceData service.GenesisState `json:"service"` + GenTxs []json.RawMessage `json:"gentxs"` +} + +func NewGenesisState(accounts []GenesisAccount, authData auth.GenesisState, stakeData stake.GenesisState, mintData mint.GenesisState, + distrData distr.GenesisState, govData gov.GenesisState, upgradeData upgrade.GenesisState, serviceData service.GenesisState, slashingData slashing.GenesisState) GenesisState { + + return GenesisState{ + Accounts: accounts, + AuthData: authData, + StakeData: stakeData, + MintData: mintData, + DistrData: distrData, + GovData: govData, + UpgradeData: upgradeData, + ServiceData: serviceData, + SlashingData: slashingData, + } } // GenesisAccount doesn't need pubkey or sequence type GenesisAccount struct { - Address sdk.AccAddress `json:"address"` - Coins sdk.Coins `json:"coins"` + Address sdk.AccAddress `json:"address"` + Coins sdk.Coins `json:"coins"` + Sequence int64 `json:"sequence_number"` + AccountNumber int64 `json:"account_number"` } func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount { return GenesisAccount{ - Address: acc.Address, - Coins: acc.Coins, + Address: acc.Address, + Coins: acc.Coins, + AccountNumber: acc.AccountNumber, + Sequence: acc.Sequence, } } func NewGenesisAccountI(acc auth.Account) GenesisAccount { return GenesisAccount{ - Address: acc.GetAddress(), - Coins: acc.GetCoins(), + Address: acc.GetAddress(), + Coins: acc.GetCoins(), + AccountNumber: acc.GetAccountNumber(), + Sequence: acc.GetSequence(), } } // convert GenesisAccount to auth.BaseAccount func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount) { return &auth.BaseAccount{ - Address: ga.Address, - Coins: ga.Coins.Sort(), + Address: ga.Address, + Coins: ga.Coins.Sort(), + AccountNumber: ga.AccountNumber, + Sequence: ga.Sequence, } } -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 +// NewDefaultGenesisState generates the default state for gaia. +func NewDefaultGenesisState() GenesisState { + return GenesisState{ + Accounts: nil, + StakeData: createStakeGenesisState(), + MintData: createMintGenesisState(), + DistrData: distr.DefaultGenesisState(), + GovData: gov.DefaultGenesisState(), + UpgradeData: upgrade.DefaultGenesisState(), + ServiceData: service.DefaultGenesisState(), + SlashingData: slashing.DefaultGenesisState(), + GenTxs: nil, + } +} // 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, + AppGenState: IrisAppGenStateJSON, } } -// simple genesis tx -type IrisGenTx struct { - Name string `json:"name"` - Address sdk.AccAddress `json:"address"` - PubKey string `json:"pub_key"` -} +// Create the core parameters for genesis initialization for iris +// note that the pubkey input is this machines pubkey +func IrisAppGenState(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []json.RawMessage) ( + genesisState GenesisState, err error) { + if err = cdc.UnmarshalJSON(genDoc.AppState, &genesisState); err != nil { + return genesisState, err + } -// 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 there are no gen txs to be processed, return the default empty state + if len(appGenTxs) == 0 { + return genesisState, errors.New("there must be at least one genesis tx") + } - if genTxConfig.Name == "" { - return nil, nil, tmtypes.GenesisValidator{}, errors.New("Must specify --name (validator moniker)") + stakeData := genesisState.StakeData + for i, genTx := range appGenTxs { + var tx auth.StdTx + if err := cdc.UnmarshalJSON(genTx, &tx); err != nil { + return genesisState, err + } + msgs := tx.GetMsgs() + if len(msgs) != 1 { + return genesisState, errors.New( + "must provide genesis StdTx with exactly 1 CreateValidator message") + } + if _, ok := msgs[0].(stake.MsgCreateValidator); !ok { + return genesisState, fmt.Errorf( + "Genesis transaction %v does not contain a MsgCreateValidator", i) + } } - var addr sdk.AccAddress - var secret string - addr, secret, err = server.GenerateSaveCoinKey(genTxConfig.CliRoot, genTxConfig.Name, DefaultKeyPass, genTxConfig.Overwrite) - if err != nil { - return + for _, acc := range genesisState.Accounts { + // create the genesis account, give'm few iris-atto and a buncha token with there name + for _, coin := range acc.Coins { + if coin.Denom == StakeDenom { + stakeData.Pool.LooseTokens = stakeData.Pool.LooseTokens. + Add(sdk.NewDecFromInt(coin.Amount)) // increase the supply + } + } } - mm := map[string]string{"secret": secret} - var bz []byte - bz, err = cdc.MarshalJSON(mm) + genesisState.StakeData = stakeData + genesisState.GenTxs = appGenTxs + genesisState.UpgradeData = genesisState.UpgradeData + return genesisState, nil +} + +func genesisAccountFromMsgCreateValidator(msg stake.MsgCreateValidator, amount sdk.Int) GenesisAccount { + accAuth := auth.NewBaseAccountWithAddress(sdk.AccAddress(msg.ValidatorAddr)) + accAuth.Coins = []sdk.Coin{ + {StakeDenom, amount}, + } + return NewGenesisAccount(&accAuth) +} + +// IrisValidateGenesisState ensures that the genesis state obeys the expected invariants +// TODO: No validators are both bonded and jailed (#2088) +// TODO: Error if there is a duplicate validator (#1708) +// TODO: Ensure all state machine parameters are in genesis (#1704) +func IrisValidateGenesisState(genesisState GenesisState) (err error) { + err = validateGenesisStateAccounts(genesisState.Accounts) if err != nil { return } - cliPrint = json.RawMessage(bz) - appGenTx, _, validator, err = IrisAppGenTxNF(cdc, pk, addr, genTxConfig.Name) + // skip stakeData validation as genesis is created from txs + if len(genesisState.GenTxs) > 0 { + return nil + } + return stake.ValidateGenesis(genesisState.StakeData) +} + +// Ensures that there are no duplicate accounts in the genesis state, +func validateGenesisStateAccounts(accs []GenesisAccount) (err error) { + addrMap := make(map[string]bool, len(accs)) + for i := 0; i < len(accs); i++ { + acc := accs[i] + strAddr := string(acc.Address) + if _, ok := addrMap[strAddr]; ok { + return fmt.Errorf("Duplicate account in genesis state: Address %v", acc.Address) + } + addrMap[strAddr] = true + } 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) { +// IrisAppGenState but with JSON +func IrisAppGenStateJSON(cdc *codec.Codec, genDoc tmtypes.GenesisDoc, appGenTxs []json.RawMessage) ( + appState json.RawMessage, err error) { - var bz []byte - gaiaGenTx := IrisGenTx{ - Name: name, - Address: addr, - PubKey: sdk.MustBech32ifyAccPub(pk), - } - bz, err = wire.MarshalJSONIndent(cdc, gaiaGenTx) + // create the final app state + genesisState, err := IrisAppGenState(cdc, genDoc, appGenTxs) if err != nil { - return - } - appGenTx = json.RawMessage(bz) - - validator = tmtypes.GenesisValidator{ - PubKey: pk, - Power: feeAmt, + return nil, err } + appState, err = codec.MarshalJSONIndent(cdc, genesisState) 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) { +// CollectStdTxs processes and validates application's genesis StdTxs and returns +// the list of appGenTxs, and persistent peers required to generate genesis.json. +func CollectStdTxs(cdc *codec.Codec, moniker string, genTxsDir string, genDoc tmtypes.GenesisDoc) ( + appGenTxs []auth.StdTx, persistentPeers string, err error) { - if len(appGenTxs) == 0 { - err = errors.New("must provide at least genesis transaction") - return + var fos []os.FileInfo + fos, err = ioutil.ReadDir(genTxsDir) + if err != nil { + return appGenTxs, persistentPeers, err } - stakeData := createGenesisState() - genaccs := make([]GenesisAccount, len(appGenTxs)) - for i, appGenTx := range appGenTxs { + // prepare a map of all accounts in genesis state to then validate + // against the validators addresses + var appState GenesisState + if err := cdc.UnmarshalJSON(genDoc.AppState, &appState); err != nil { + return appGenTxs, persistentPeers, err + } + addrMap := make(map[string]GenesisAccount, len(appState.Accounts)) + for i := 0; i < len(appState.Accounts); i++ { + acc := appState.Accounts[i] + strAddr := string(acc.Address) + addrMap[strAddr] = acc + } + + // addresses and IPs (and port) validator server info + var addressesIPs []string - var genTx IrisGenTx - err = cdc.UnmarshalJSON(appGenTx, &genTx) - if err != nil { - return + for _, fo := range fos { + filename := filepath.Join(genTxsDir, fo.Name()) + if !fo.IsDir() && (filepath.Ext(filename) != ".json") { + continue } - // 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, + // get the genStdTx + var jsonRawTx []byte + if jsonRawTx, err = ioutil.ReadFile(filename); err != nil { + return appGenTxs, persistentPeers, err } - 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, - } + var genStdTx auth.StdTx + if err = cdc.UnmarshalJSON(jsonRawTx, &genStdTx); err != nil { + return appGenTxs, persistentPeers, err + } + appGenTxs = append(appGenTxs, genStdTx) + + // the memo flag is used to store + // the ip and node-id, for example this may be: + // "528fd3df22b31f4969b05652bfe8f0fe921321d5@192.168.2.37:26656" + nodeAddrIP := genStdTx.GetMemo() + if len(nodeAddrIP) == 0 { + return appGenTxs, persistentPeers, fmt.Errorf( + "couldn't find node's address and IP in %s", fo.Name()) + } + + // genesis transactions must be single-message + msgs := genStdTx.GetMsgs() + if len(msgs) != 1 { - stakeData.Bonds = append(stakeData.Bonds, delegation) + return appGenTxs, persistentPeers, errors.New( + "each genesis transaction must provide a single genesis message") } - } - // create the final app state - genesisState = GenesisState{ - Accounts: genaccs, - StakeData: stakeData, - GovData: gov.DefaultGenesisState(), - UpgradeData: upgrade.DefaultGenesisState(), + // validate the validator address and funds against the accounts in the state + msg := msgs[0].(stake.MsgCreateValidator) + addr := string(sdk.AccAddress(msg.ValidatorAddr)) + acc, ok := addrMap[addr] + if !ok { + return appGenTxs, persistentPeers, fmt.Errorf( + "account %v not in genesis.json: %+v", addr, addrMap) + } + if acc.Coins.AmountOf(msg.Delegation.Denom).LT(msg.Delegation.Amount) { + err = fmt.Errorf("insufficient fund for the delegation: %s < %s", + acc.Coins.AmountOf(msg.Delegation.Denom), msg.Delegation.Amount) + } + + // exclude itself from persistent peers + if msg.Description.Moniker != moniker { + addressesIPs = append(addressesIPs, nodeAddrIP) + } } - return -} -// IrisAppGenState but with JSON -func IrisAppGenStateJSON(cdc *wire.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) { + sort.Strings(addressesIPs) + persistentPeers = strings.Join(addressesIPs, ",") - // create the final app state - genesisState, err := IrisAppGenState(cdc, appGenTxs) - if err != nil { - return nil, err + return appGenTxs, persistentPeers, nil +} + +func NewDefaultGenesisAccount(addr sdk.AccAddress) GenesisAccount { + accAuth := auth.NewBaseAccountWithAddress(addr) + accAuth.Coins = []sdk.Coin{ + FreeFermionAcc, } - appState, err = wire.MarshalJSONIndent(cdc, genesisState) - return + return NewGenesisAccount(&accAuth) } -func createGenesisState() stake.GenesisState { +func createStakeGenesisState() 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(), + LooseTokens: sdk.ZeroDec(), + BondedTokens: sdk.ZeroDec(), }, 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, + UnbondingTime: defaultUnbondingTime, + MaxValidators: 100, + BondDenom: StakeDenom, + }, + } +} + +func createMintGenesisState() mint.GenesisState { + return mint.GenesisState{ + Minter: mint.InitialMinter(), + Params: mint.Params{ + MintDenom: StakeDenom, + InflationRateChange: sdk.NewDecWithPrec(13, 2), + InflationMax: sdk.NewDecWithPrec(20, 2), + InflationMin: sdk.NewDecWithPrec(7, 2), + GoalBonded: sdk.NewDecWithPrec(67, 2), }, } } diff --git a/examples/irishub1/cmd/iris1/main.go b/examples/irishub1/cmd/iris1/main.go index 4bd702f9c..b6f7a8c64 100644 --- a/examples/irishub1/cmd/iris1/main.go +++ b/examples/irishub1/cmd/iris1/main.go @@ -6,12 +6,11 @@ import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" + "github.com/irisnet/irishub/client" "github.com/cosmos/cosmos-sdk/server" "github.com/irisnet/irishub/examples/irishub1/app" bam "github.com/irisnet/irishub/baseapp" - "github.com/irisnet/irishub/tools/prometheus" "github.com/irisnet/irishub/version" "github.com/spf13/viper" abci "github.com/tendermint/tendermint/abci/types" @@ -19,9 +18,16 @@ import ( dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" tmtypes "github.com/tendermint/tendermint/types" + irisInit "github.com/irisnet/irishub/init" + sdk "github.com/cosmos/cosmos-sdk/types" ) func main() { + config := sdk.GetConfig() + config.SetBech32PrefixForAccount(irisInit.Bech32PrefixAccAddr, irisInit.Bech32PrefixAccPub) + config.SetBech32PrefixForValidator(irisInit.Bech32PrefixValAddr, irisInit.Bech32PrefixValPub) + config.SetBech32PrefixForConsensusNode(irisInit.Bech32PrefixConsAddr, irisInit.Bech32PrefixConsPub) + config.Seal() cdc := app.MakeCodec() ctx := server.NewDefaultContext() cobra.EnableCommandSorting = false @@ -41,18 +47,21 @@ func main() { tendermintCmd.AddCommand( server.ShowNodeIDCmd(ctx), server.ShowValidatorCmd(ctx), + server.ShowAddressCmd(ctx), ) - startCmd := server.StartCmd(ctx, server.ConstructAppCreator(newApp, "iris")) + startCmd := server.StartCmd(ctx, newApp) startCmd.Flags().Bool(app.FlagReplay, false, "Replay the last block") rootCmd.AddCommand( - server.InitCmd(ctx, cdc, app.IrisAppInit()), + irisInit.InitCmd(ctx, cdc, app.IrisAppInit()), + irisInit.GenTxCmd(ctx,cdc), + irisInit.TestnetFilesCmd(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")), + server.ExportCmd(ctx, cdc, exportAppStateAndTMValidators), client.LineBreak, ) @@ -60,8 +69,6 @@ func main() { version.ServeVersionCommand(cdc), ) - rootCmd.AddCommand(prometheus.MonitorCommand(cdc)) - // prepare and add flags executor := cli.PrepareBaseCmd(rootCmd, "IRIS", app.DefaultNodeHome) executor.Execute() diff --git a/examples/irishub1/cmd/iriscli1/main.go b/examples/irishub1/cmd/iriscli1/main.go index ddfba88ba..9270cf7b2 100644 --- a/examples/irishub1/cmd/iriscli1/main.go +++ b/examples/irishub1/cmd/iriscli1/main.go @@ -16,6 +16,8 @@ import ( "github.com/irisnet/irishub/version" "github.com/spf13/cobra" "github.com/tendermint/tendermint/libs/cli" + sdk "github.com/cosmos/cosmos-sdk/types" + irisInit "github.com/irisnet/irishub/init" ) // rootCmd is the entry point for this binary @@ -27,6 +29,11 @@ var ( ) func main() { + config := sdk.GetConfig() + config.SetBech32PrefixForAccount(irisInit.Bech32PrefixAccAddr, irisInit.Bech32PrefixAccPub) + config.SetBech32PrefixForValidator(irisInit.Bech32PrefixValAddr, irisInit.Bech32PrefixValPub) + config.SetBech32PrefixForConsensusNode(irisInit.Bech32PrefixConsAddr, irisInit.Bech32PrefixConsPub) + config.Seal() cobra.EnableCommandSorting = false cdc := app.MakeCodec() @@ -142,7 +149,6 @@ func main() { ibcCmd.AddCommand( client.PostCommands( - ibccmd.IBCTransferCmd(cdc), ibccmd.IBCSetCmd(cdc), ibccmd.IBCGetCmd(cdc), )...) diff --git a/examples/irishub1/ibc/client/cli/ibctx.go b/examples/irishub1/ibc/client/cli/ibctx.go deleted file mode 100644 index 8a729b697..000000000 --- a/examples/irishub1/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/irishub1/ibc/client/cli/tx.go b/examples/irishub1/ibc/client/cli/tx.go index 7029de652..7d143bacf 100644 --- a/examples/irishub1/ibc/client/cli/tx.go +++ b/examples/irishub1/ibc/client/cli/tx.go @@ -5,14 +5,14 @@ import ( "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" + "github.com/cosmos/cosmos-sdk/codec" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/irisnet/irishub/examples/irishub1/ibc" "os" ) // IBC transfer command -func IBCGetCmd(cdc *wire.Codec) *cobra.Command { +func IBCGetCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "get", RunE: func(cmd *cobra.Command, args []string) error { @@ -40,7 +40,7 @@ func IBCGetCmd(cdc *wire.Codec) *cobra.Command { // IBC transfer command -func IBCSetCmd(cdc *wire.Codec) *cobra.Command { +func IBCSetCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "set", RunE: func(cmd *cobra.Command, args []string) error { diff --git a/examples/irishub1/ibc/handler.go b/examples/irishub1/ibc/handler.go index c277e0a4b..cbfcd1aec 100644 --- a/examples/irishub1/ibc/handler.go +++ b/examples/irishub1/ibc/handler.go @@ -10,10 +10,6 @@ import ( 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: @@ -25,44 +21,6 @@ func NewHandler(ibcm Mapper, ck bank.Keeper) sdk.Handler { } } -// 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()) diff --git a/examples/irishub1/ibc/mapper.go b/examples/irishub1/ibc/mapper.go index 56cc10e79..7e983b5e5 100644 --- a/examples/irishub1/ibc/mapper.go +++ b/examples/irishub1/ibc/mapper.go @@ -4,19 +4,19 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" + codec "github.com/cosmos/cosmos-sdk/codec" ) // IBC Mapper type Mapper struct { key sdk.StoreKey - cdc *wire.Codec + cdc *codec.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 { +func NewMapper(cdc *codec.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) Mapper { // XXX: How are these codecs supposed to work? return Mapper{ key: key, @@ -25,51 +25,19 @@ func NewMapper(cdc *wire.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) M } } -// 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) +func MarshalBinaryLengthPrefixedPanic(cdc *codec.Codec, value interface{}) []byte { + res, err := cdc.MarshalBinaryLengthPrefixed(value) if err != nil { panic(err) } return res } -func unmarshalBinaryPanic(cdc *wire.Codec, bz []byte, ptr interface{}) { - err := cdc.UnmarshalBinary(bz, ptr) +func unMarshalBinaryLengthPrefixedPanic(cdc *codec.Codec, bz []byte, ptr interface{}) { + err := cdc.UnmarshalBinaryLengthPrefixed(bz, ptr) if err != nil { panic(err) } @@ -82,13 +50,13 @@ func (ibcm Mapper) GetIngressSequence(ctx sdk.Context, srcChain string) int64 { bz := store.Get(key) if bz == nil { - zero := marshalBinaryPanic(ibcm.cdc, int64(0)) + zero := MarshalBinaryLengthPrefixedPanic(ibcm.cdc, int64(0)) store.Set(key, zero) return 0 } var res int64 - unmarshalBinaryPanic(ibcm.cdc, bz, &res) + unMarshalBinaryLengthPrefixedPanic(ibcm.cdc, bz, &res) return res } @@ -97,7 +65,7 @@ func (ibcm Mapper) SetIngressSequence(ctx sdk.Context, srcChain string, sequence store := ctx.KVStore(ibcm.key) key := IngressSequenceKey(srcChain) - bz := marshalBinaryPanic(ibcm.cdc, sequence) + bz := MarshalBinaryLengthPrefixedPanic(ibcm.cdc, sequence) store.Set(key, bz) } @@ -105,12 +73,12 @@ func (ibcm Mapper) SetIngressSequence(ctx sdk.Context, srcChain string, sequence func (ibcm Mapper) getEgressLength(store sdk.KVStore, destChain string) int64 { bz := store.Get(EgressLengthKey(destChain)) if bz == nil { - zero := marshalBinaryPanic(ibcm.cdc, int64(0)) + zero := MarshalBinaryLengthPrefixedPanic(ibcm.cdc, int64(0)) store.Set(EgressLengthKey(destChain), zero) return 0 } var res int64 - unmarshalBinaryPanic(ibcm.cdc, bz, &res) + unMarshalBinaryLengthPrefixedPanic(ibcm.cdc, bz, &res) return res } @@ -137,12 +105,12 @@ func (ibcm Mapper) Get(ctx sdk.Context) (string, bool) { return " ", false } var Addr string - ibcm.cdc.MustUnmarshalBinary(bz, &Addr) + ibcm.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &Addr) return Addr, true } func (ibcm Mapper) Set(ctx sdk.Context,Addr string) { store := ctx.KVStore(ibcm.key) - bz := ibcm.cdc.MustMarshalBinary(Addr) + bz := ibcm.cdc.MustMarshalBinaryLengthPrefixed(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 index 0537ff816..294e50893 100644 --- a/examples/irishub1/ibc/types.go +++ b/examples/irishub1/ibc/types.go @@ -1,132 +1,24 @@ package ibc import ( - "encoding/json" - sdk "github.com/cosmos/cosmos-sdk/types" - wire "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" ) var ( - msgCdc *wire.Codec + msgCdc *codec.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 + msgCdc = codec.New() } -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 } +var _ sdk.Msg = (*IBCSetMsg)(nil) + func NewIBCSetMsg(addr sdk.AccAddress) IBCSetMsg { return IBCSetMsg{ Addr:addr, @@ -134,6 +26,10 @@ func NewIBCSetMsg(addr sdk.AccAddress) IBCSetMsg { } func (msg IBCSetMsg) Type() string { + return "ibc-set" +} + +func (msg IBCSetMsg) Route() string { return "ibc-1" } @@ -157,6 +53,8 @@ type IBCGetMsg struct { Addr sdk.AccAddress } +var _ sdk.Msg = (*IBCGetMsg)(nil) + func NewIBCGetMsg(addr sdk.AccAddress) IBCGetMsg { return IBCGetMsg{ Addr:addr, @@ -164,6 +62,10 @@ func NewIBCGetMsg(addr sdk.AccAddress) IBCGetMsg { } func (msg IBCGetMsg) Type() string { + return "ibc-get" +} + +func (msg IBCGetMsg) Route() string { return "ibc-1" } diff --git a/examples/irishub1/ibc/wire.go b/examples/irishub1/ibc/wire.go index 3d4bc334e..8d6e5ebb3 100644 --- a/examples/irishub1/ibc/wire.go +++ b/examples/irishub1/ibc/wire.go @@ -1,13 +1,11 @@ package ibc import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" ) -// 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) +// Register concrete types on codec codec +func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(IBCSetMsg{},"cosmos-sdk/IBCSetMsg/1",nil) cdc.RegisterConcrete(IBCGetMsg{},"cosmos-sdk/IBCGetMsg/1",nil) } diff --git a/init/collect.go b/init/collect.go new file mode 100644 index 000000000..651d6e12b --- /dev/null +++ b/init/collect.go @@ -0,0 +1,118 @@ +package init + +import ( + "encoding/json" + "path/filepath" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/spf13/cobra" + "github.com/spf13/viper" + cfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/libs/cli" + "github.com/tendermint/tendermint/types" + "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/client" +) + +type initConfig struct { + ChainID string + GenTxsDir string + Name string + NodeID string + ValPubKey crypto.PubKey +} + +// nolint +func CollectGenTxsCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "collect-gentxs", + Short: "Collect genesis txs and output a genesis.json file", + RunE: func(_ *cobra.Command, _ []string) error { + config := ctx.Config + config.SetRoot(viper.GetString(cli.HomeFlag)) + name := viper.GetString(client.FlagName) + + nodeID, valPubKey, err := InitializeNodeValidatorFiles(config) + if err != nil { + return err + } + + genDoc, err := loadGenesisDoc(cdc, config.GenesisFile()) + if err != nil { + return err + } + + toPrint := printInfo{ + Moniker: config.Moniker, + ChainID: genDoc.ChainID, + NodeID: nodeID, + } + + initCfg := initConfig{ + ChainID: genDoc.ChainID, + GenTxsDir: filepath.Join(config.RootDir, "config", "gentx"), + Name: name, + NodeID: nodeID, + ValPubKey: valPubKey, + } + + appMessage, err := genAppStateFromConfig(cdc, config, initCfg, genDoc) + if err != nil { + return err + } + + toPrint.AppMessage = appMessage + + // print out some key information + return displayInfo(cdc, toPrint) + }, + } + + cmd.Flags().String(cli.HomeFlag, app.DefaultNodeHome, "node's home directory") + return cmd +} + +func genAppStateFromConfig( + cdc *codec.Codec, config *cfg.Config, initCfg initConfig, genDoc types.GenesisDoc, +) (appState json.RawMessage, err error) { + + genFile := config.GenesisFile() + var ( + appGenTxs []auth.StdTx + persistentPeers string + genTxs []json.RawMessage + jsonRawTx json.RawMessage + ) + + // process genesis transactions, else create default genesis.json + appGenTxs, persistentPeers, err = app.CollectStdTxs( + cdc, config.Moniker, initCfg.GenTxsDir, genDoc, + ) + if err != nil { + return + } + + genTxs = make([]json.RawMessage, len(appGenTxs)) + config.P2P.PersistentPeers = persistentPeers + + for i, stdTx := range appGenTxs { + jsonRawTx, err = cdc.MarshalJSON(stdTx) + if err != nil { + return + } + genTxs[i] = jsonRawTx + } + + cfg.WriteConfigFile(filepath.Join(config.RootDir, "config", "config.toml"), config) + + appState, err = app.IrisAppGenStateJSON(cdc, genDoc, genTxs) + if err != nil { + return + } + + err = ExportGenesisFile(genFile, initCfg.ChainID, nil, appState) + return +} diff --git a/init/gentx.go b/init/gentx.go new file mode 100644 index 000000000..66d28ce62 --- /dev/null +++ b/init/gentx.go @@ -0,0 +1,150 @@ +package init + +import ( + "fmt" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/server" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/spf13/cobra" + "github.com/spf13/viper" + cfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tendermint/crypto" + tmcli "github.com/tendermint/tendermint/libs/cli" + "github.com/tendermint/tendermint/libs/common" + "io/ioutil" + "os" + "path/filepath" + stakecmd "github.com/irisnet/irishub/client/stake/cli" + "github.com/irisnet/irishub/client/stake/cli" + "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/client" + signcmd "github.com/irisnet/irishub/client/bank/cli" + authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" +) + +const ( + defaultAmount = "100iris" + defaultCommissionRate = "0.1" + defaultCommissionMaxRate = "0.2" + defaultCommissionMaxChangeRate = "0.01" +) + +// GenTxCmd builds the gaiad gentx command. +// nolint: errcheck +func GenTxCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "gentx", + Short: "Generate a genesis tx carrying a self delegation", + Long: fmt.Sprintf(`This command is an alias of the 'gaiad tx create-validator' command'. + +It creates a genesis piece carrying a self delegation with the +following delegation and commission default parameters: + + delegation amount: %s + commission rate: %s + commission max rate: %s + commission max change rate: %s +`, defaultAmount, defaultCommissionRate, defaultCommissionMaxRate, defaultCommissionMaxChangeRate), + RunE: func(cmd *cobra.Command, args []string) error { + + config := ctx.Config + config.SetRoot(viper.GetString(tmcli.HomeFlag)) + nodeID, valPubKey, err := InitializeNodeValidatorFiles(ctx.Config) + if err != nil { + return err + } + ip := viper.GetString(stakecmd.FlagIP) + if ip == "" { + ip, err = server.ExternalIP() + if err != nil { + return err + } + } + genDoc, err := loadGenesisDoc(cdc, config.GenesisFile()) + if err != nil { + return err + } + + // Read --pubkey, if empty take it from priv_validator.json + if valPubKeyString := viper.GetString(cli.FlagPubKey); valPubKeyString != "" { + valPubKey, err = sdk.GetConsPubKeyBech32(valPubKeyString) + if err != nil { + return err + } + } + // Run gaiad tx create-validator + prepareFlagsForTxCreateValidator(config, nodeID, ip, genDoc.ChainID, valPubKey) + createValidatorCmd := stakecmd.GetCmdCreateValidator(cdc) + + w, err := ioutil.TempFile("", "gentx") + if err != nil { + return err + } + unsignedGenTxFilename := w.Name() + defer os.Remove(unsignedGenTxFilename) + os.Stdout = w + if err = createValidatorCmd.RunE(nil, args); err != nil { + return err + } + w.Close() + + prepareFlagsForTxSign() + signCmd := signcmd.GetSignCommand(cdc, authcmd.GetAccountDecoder(cdc)) + if w, err = prepareOutputFile(config.RootDir, nodeID); err != nil { + return err + } + os.Stdout = w + return signCmd.RunE(nil, []string{unsignedGenTxFilename}) + }, + } + + cmd.Flags().String(tmcli.HomeFlag, app.DefaultNodeHome, "node's home directory") + cmd.Flags().String(flagClientHome, app.DefaultCLIHome, "client's home directory") + cmd.Flags().String(client.FlagName, "", "name of private key with which to sign the gentx") + cmd.Flags().String(stakecmd.FlagIP,"",fmt.Sprintf("Node's public IP. It takes effect only when used in combination with --%s", stakecmd.FlagGenesisFormat)) + cmd.Flags().AddFlagSet(stakecmd.FsCommissionCreate) + cmd.Flags().AddFlagSet(stakecmd.FsAmount) + cmd.Flags().AddFlagSet(stakecmd.FsPk) + cmd.MarkFlagRequired(client.FlagName) + return cmd +} + +func prepareFlagsForTxCreateValidator(config *cfg.Config, nodeID, ip, chainID string, + valPubKey crypto.PubKey) { + viper.Set(tmcli.HomeFlag, viper.GetString(flagClientHome)) // --home + viper.Set(client.FlagChainID, chainID) + viper.Set(client.FlagFrom, viper.GetString(client.FlagName)) // --from + viper.Set(stakecmd.FlagNodeID, nodeID) // --node-id + viper.Set(stakecmd.FlagIP, ip) // --ip + viper.Set(stakecmd.FlagPubKey, sdk.MustBech32ifyConsPub(valPubKey)) // --pubkey + viper.Set(stakecmd.FlagGenesisFormat, true) // --genesis-format + viper.Set(stakecmd.FlagMoniker, config.Moniker) // --moniker + if config.Moniker == "" { + viper.Set(stakecmd.FlagMoniker, viper.GetString(client.FlagName)) + } + if viper.GetString(stakecmd.FlagAmount) == "" { + viper.Set(stakecmd.FlagAmount, defaultAmount) + } + if viper.GetString(stakecmd.FlagCommissionRate) == "" { + viper.Set(stakecmd.FlagCommissionRate, defaultCommissionRate) + } + if viper.GetString(stakecmd.FlagCommissionMaxRate) == "" { + viper.Set(stakecmd.FlagCommissionMaxRate, defaultCommissionMaxRate) + } + if viper.GetString(stakecmd.FlagCommissionMaxChangeRate) == "" { + viper.Set(stakecmd.FlagCommissionMaxChangeRate, defaultCommissionMaxChangeRate) + } +} + +func prepareFlagsForTxSign() { + viper.Set("offline", true) +} + +func prepareOutputFile(rootDir, nodeID string) (w *os.File, err error) { + writePath := filepath.Join(rootDir, "config", "gentx") + if err = common.EnsureDir(writePath, 0700); err != nil { + return + } + filename := filepath.Join(writePath, fmt.Sprintf("gentx-%v.json", nodeID)) + return os.Create(filename) +} diff --git a/init/init.go b/init/init.go new file mode 100644 index 000000000..56a072d31 --- /dev/null +++ b/init/init.go @@ -0,0 +1,95 @@ +package init + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/server" + "github.com/spf13/cobra" + "github.com/spf13/viper" + cfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tendermint/libs/cli" + "github.com/tendermint/tendermint/libs/common" + "github.com/irisnet/irishub/client" + "github.com/irisnet/irishub/app" +) + +const ( + flagOverwrite = "overwrite" + flagClientHome = "home-client" + flagMoniker = "moniker" +) + +type printInfo struct { + Moniker string `json:"moniker"` + ChainID string `json:"chain_id"` + NodeID string `json:"node_id"` + AppMessage json.RawMessage `json:"app_message"` +} + +// nolint: errcheck +func displayInfo(cdc *codec.Codec, info printInfo) error { + out, err := codec.MarshalJSONIndent(cdc, info) + if err != nil { + return err + } + fmt.Fprintf(os.Stderr, "%s\n", string(out)) + return nil +} + +// get cmd to initialize all files for tendermint and application +// nolint +func InitCmd(ctx *server.Context, cdc *codec.Codec, appInit server.AppInit) *cobra.Command { + cmd := &cobra.Command{ + Use: "init", + Short: "Initialize private validator, p2p, genesis, and application configuration files", + Long: `Initialize validators's and node's configuration files.`, + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + config := ctx.Config + config.SetRoot(viper.GetString(cli.HomeFlag)) + chainID := viper.GetString(client.FlagChainID) + if chainID == "" { + chainID = fmt.Sprintf("test-chain-%v", common.RandStr(6)) + } + nodeID, _, err := InitializeNodeValidatorFiles(config) + if err != nil { + return err + } + + if viper.GetString(flagMoniker) != "" { + config.Moniker = viper.GetString(flagMoniker) + } + + var appState json.RawMessage + genFile := config.GenesisFile() + if appState, err = initializeEmptyGenesis(cdc, genFile, chainID, + viper.GetBool(flagOverwrite)); err != nil { + return err + } + if err = ExportGenesisFile(genFile, chainID, nil, appState); err != nil { + return err + } + + toPrint := printInfo{ + ChainID: chainID, + Moniker: config.Moniker, + NodeID: nodeID, + AppMessage: appState, + } + + cfg.WriteConfigFile(filepath.Join(config.RootDir, "config", "config.toml"), config) + + return displayInfo(cdc, toPrint) + }, + } + + cmd.Flags().String(cli.HomeFlag, app.DefaultNodeHome, "node's home directory") + cmd.Flags().BoolP(flagOverwrite, "o", false, "overwrite the genesis.json file") + cmd.Flags().String(client.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") + cmd.Flags().String(flagMoniker, "", "set the validator's moniker") + return cmd +} diff --git a/init/init_test.go b/init/init_test.go new file mode 100644 index 000000000..cc512aecd --- /dev/null +++ b/init/init_test.go @@ -0,0 +1,145 @@ +package init + +import ( + "bytes" + "github.com/tendermint/tendermint/libs/cli" + "io" + "io/ioutil" + "os" + "testing" + "time" + + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/server/mock" + "github.com/stretchr/testify/require" + abciServer "github.com/tendermint/tendermint/abci/server" + tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" + "github.com/tendermint/tendermint/libs/log" + + "github.com/spf13/viper" + "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/client" +) + +func TestInitCmd(t *testing.T) { + defer server.SetupViper(t)() + defer setupClientHome(t)() + + logger := log.NewNopLogger() + cfg, err := tcmd.ParseConfig() + require.Nil(t, err) + ctx := server.NewContext(cfg, logger) + cdc := app.MakeCodec() + appInit := server.AppInit{ + AppGenState: mock.AppGenState, + } + cmd := InitCmd(ctx, cdc, appInit) + err = cmd.RunE(nil, nil) + require.NoError(t, err) +} + +func setupClientHome(t *testing.T) func() { + clientDir, err := ioutil.TempDir("", "mock-sdk-cmd") + require.Nil(t, err) + viper.Set(flagClientHome, clientDir) + return func() { + if err := os.RemoveAll(clientDir); err != nil { + // TODO: Handle with #870 + panic(err) + } + } +} + +func TestEmptyState(t *testing.T) { + defer server.SetupViper(t)() + defer setupClientHome(t)() + logger := log.NewNopLogger() + cfg, err := tcmd.ParseConfig() + require.Nil(t, err) + ctx := server.NewContext(cfg, logger) + cdc := app.MakeCodec() + appInit := server.AppInit{ + AppGenState: mock.AppGenStateEmpty, + } + cmd := InitCmd(ctx, cdc, appInit) + err = cmd.RunE(nil, nil) + require.NoError(t, err) + + old := os.Stdout + r, w, _ := os.Pipe() + os.Stdout = w + cmd = server.ExportCmd(ctx, cdc, nil) + err = cmd.RunE(nil, nil) + require.NoError(t, err) + + outC := make(chan string) + go func() { + var buf bytes.Buffer + io.Copy(&buf, r) + outC <- buf.String() + }() + + w.Close() + os.Stdout = old + out := <-outC + require.Contains(t, out, "WARNING: State is not initialized") + require.Contains(t, out, "genesis_time") + require.Contains(t, out, "chain_id") + require.Contains(t, out, "consensus_params") + require.Contains(t, out, "validators") + require.Contains(t, out, "app_hash") +} + +func TestStartStandAlone(t *testing.T) { + home, err := ioutil.TempDir("", "mock-sdk-cmd") + require.Nil(t, err) + defer func() { + os.RemoveAll(home) + }() + viper.Set(cli.HomeFlag, home) + viper.Set(client.FlagName, "moniker") + defer setupClientHome(t)() + + logger := log.NewNopLogger() + cfg, err := tcmd.ParseConfig() + require.Nil(t, err) + ctx := server.NewContext(cfg, logger) + cdc := app.MakeCodec() + appInit := server.AppInit{ + AppGenState: mock.AppGenState, + } + initCmd := InitCmd(ctx, cdc, appInit) + err = initCmd.RunE(nil, nil) + require.NoError(t, err) + + app, err := mock.NewApp(home, logger) + require.Nil(t, err) + svrAddr, _, err := server.FreeTCPAddr() + require.Nil(t, err) + svr, err := abciServer.NewServer(svrAddr, "socket", app) + require.Nil(t, err, "error creating listener") + svr.SetLogger(logger.With("module", "abci-server")) + svr.Start() + + timer := time.NewTimer(time.Duration(2) * time.Second) + select { + case <-timer.C: + svr.Stop() + } +} + +func TestInitNodeValidatorFiles(t *testing.T) { + home, err := ioutil.TempDir("", "mock-sdk-cmd") + require.Nil(t, err) + defer func() { + os.RemoveAll(home) + }() + viper.Set(cli.HomeFlag, home) + viper.Set(client.FlagName, "moniker") + cfg, err := tcmd.ParseConfig() + require.Nil(t, err) + nodeID, valPubKey, err := InitializeNodeValidatorFiles(cfg) + require.Nil(t, err) + require.NotEqual(t, "", nodeID) + require.NotEqual(t, 0, len(valPubKey.Bytes())) +} diff --git a/init/prefix.go b/init/prefix.go new file mode 100644 index 000000000..3864afdd7 --- /dev/null +++ b/init/prefix.go @@ -0,0 +1,16 @@ +package init + +const ( + // Bech32PrefixAccAddr defines the Bech32 prefix of an account's address + Bech32PrefixAccAddr = "faa" + // Bech32PrefixAccPub defines the Bech32 prefix of an account's public key + Bech32PrefixAccPub = "fap" + // Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address + Bech32PrefixValAddr = "fva" + // Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key + Bech32PrefixValPub = "fvp" + // Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address + Bech32PrefixConsAddr = "fca" + // Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key + Bech32PrefixConsPub = "fcp" +) \ No newline at end of file diff --git a/init/testnet.go b/init/testnet.go new file mode 100644 index 000000000..5fc79e5e1 --- /dev/null +++ b/init/testnet.go @@ -0,0 +1,393 @@ +package init + +import ( + "encoding/json" + "fmt" + "net" + "os" + "path/filepath" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys" + "github.com/cosmos/cosmos-sdk/server" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/irisnet/irishub/app" + "github.com/irisnet/irishub/client" + "github.com/irisnet/irishub/client/context" + clkeys "github.com/irisnet/irishub/client/keys" + "github.com/spf13/cobra" + "github.com/spf13/viper" + cfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tendermint/crypto" + cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/types" + tmtime "github.com/tendermint/tendermint/types/time" +) + +var ( + flagNodeDirPrefix = "node-dir-prefix" + flagNumValidators = "v" + flagOutputDir = "output-dir" + flagNodeDaemonHome = "node-daemon-home" + flagNodeCliHome = "node-cli-home" + flagStartingIPAddress = "starting-ip-address" + flagChainID = "chain-id" +) + +const nodeDirPerm = 0755 + +// get cmd to initialize all files for tendermint testnet and application +func TestnetFilesCmd(ctx *server.Context, cdc *codec.Codec, + appInit server.AppInit) *cobra.Command { + + cmd := &cobra.Command{ + Use: "testnet", + Short: "Initialize files for a Irishub testnet", + Long: `testnet will create "v" number of directories and populate each with +necessary files (private validator, genesis, config, etc.). + +Note, strict routability for addresses is turned off in the config file. + +Example: + iris testnet --v 4 --output-dir ./output --chain-id irishub-test --starting-ip-address 127.0.0.1 + `, + RunE: func(_ *cobra.Command, _ []string) error { + config := ctx.Config + return initTestnet(config, cdc) + }, + } + + cmd.Flags().String(flagChainID, "", "Chain ID of tendermint node") + + cmd.Flags().Int(flagNumValidators, 4, + "Number of validators to initialize the testnet with", + ) + cmd.Flags().StringP(flagOutputDir, "o", "./mytestnet", + "Directory to store initialization data for the testnet", + ) + cmd.Flags().String(flagNodeDirPrefix, "node", + "Prefix the directory name for each node with (node results in node0, node1, ...)", + ) + cmd.Flags().String(flagNodeDaemonHome, "iris", + "Home directory of the node's daemon configuration", + ) + cmd.Flags().String(flagNodeCliHome, "iriscli", + "Home directory of the node's cli configuration", + ) + cmd.Flags().String(flagStartingIPAddress, "192.168.0.1", + "Starting IP address (192.168.0.1 results in persistent peers list ID0@192.168.0.1:46656, ID1@192.168.0.2:46656, ...)") + + return cmd +} + +func initTestnet(config *cfg.Config, cdc *codec.Codec) error { + outDir := viper.GetString(flagOutputDir) + numValidators := viper.GetInt(flagNumValidators) + + chainID := viper.GetString(flagChainID) + if chainID == "" { + chainID = "chain-" + cmn.RandStr(6) + } + + monikers := make([]string, numValidators) + nodeIDs := make([]string, numValidators) + valPubKeys := make([]crypto.PubKey, numValidators) + + var ( + accs []app.GenesisAccount + genFiles []string + ) + + // generate private keys, node IDs, and initial transactions + for i := 0; i < numValidators; i++ { + nodeDirName := fmt.Sprintf("%s%d", viper.GetString(flagNodeDirPrefix), i) + nodeDaemonHomeName := viper.GetString(flagNodeDaemonHome) + nodeCliHomeName := viper.GetString(flagNodeCliHome) + nodeDir := filepath.Join(outDir, nodeDirName, nodeDaemonHomeName) + clientDir := filepath.Join(outDir, nodeDirName, nodeCliHomeName) + gentxsDir := filepath.Join(outDir, "gentxs") + + config.SetRoot(nodeDir) + + err := os.MkdirAll(filepath.Join(nodeDir, "config"), nodeDirPerm) + if err != nil { + _ = os.RemoveAll(outDir) + return err + } + + err = os.MkdirAll(clientDir, nodeDirPerm) + if err != nil { + _ = os.RemoveAll(outDir) + return err + } + + monikers = append(monikers, nodeDirName) + config.Moniker = nodeDirName + + ip, err := getIP(i, viper.GetString(flagStartingIPAddress)) + if err != nil { + _ = os.RemoveAll(outDir) + return err + } + + nodeIDs[i], valPubKeys[i], err = InitializeNodeValidatorFiles(config) + if err != nil { + _ = os.RemoveAll(outDir) + return err + } + + memo := fmt.Sprintf("%s@%s:26656", nodeIDs[i], ip) + genFiles = append(genFiles, config.GenesisFile()) + + buf := client.BufferStdin() + prompt := fmt.Sprintf( + "Password for account '%s' (default %s):", nodeDirName, app.DefaultKeyPass, + ) + + keyPass, err := client.GetPassword(prompt, buf) + if err != nil && keyPass != "" { + // An error was returned that either failed to read the password from + // STDIN or the given password is not empty but failed to meet minimum + // length requirements. + return err + } + + if keyPass == "" { + keyPass = app.DefaultKeyPass + } + + addr, secret, err := generateSaveCoinKey(clientDir, nodeDirName, keyPass, true) + if err != nil { + _ = os.RemoveAll(outDir) + return err + } + + info := map[string]string{"secret": secret} + + cliPrint, err := json.Marshal(info) + if err != nil { + return err + } + + // save private key seed words + err = writeFile(fmt.Sprintf("%v.json", "key_seed"), clientDir, cliPrint) + if err != nil { + return err + } + + accs = append(accs, app.GenesisAccount{ + Address: addr, + Coins: sdk.Coins{ + app.FreeFermionAcc, + }, + }) + + msg := stake.NewMsgCreateValidator( + sdk.ValAddress(addr), + valPubKeys[i], + app.FreeFermionVal, + stake.NewDescription(nodeDirName, "", "", ""), + stake.NewCommissionMsg(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), + ) + tx := auth.NewStdTx([]sdk.Msg{msg}, auth.StdFee{}, []auth.StdSignature{}, memo) + txCtx := context.NewTxContextFromCLI().WithChainID(chainID).WithMemo(memo) + + signedTx, err := txCtx.SignStdTx(nodeDirName, app.DefaultKeyPass, tx, false) + if err != nil { + _ = os.RemoveAll(outDir) + return err + } + + txBytes, err := cdc.MarshalJSON(signedTx) + if err != nil { + _ = os.RemoveAll(outDir) + return err + } + + // gather gentxs folder + err = writeFile(fmt.Sprintf("%v.json", nodeDirName), gentxsDir, txBytes) + if err != nil { + _ = os.RemoveAll(outDir) + return err + } + } + + if err := initGenFiles(cdc, chainID, accs, genFiles, numValidators); err != nil { + return err + } + + err := collectGenFiles( + cdc, config, chainID, monikers, nodeIDs, valPubKeys, numValidators, + outDir, viper.GetString(flagNodeDirPrefix), viper.GetString(flagNodeDaemonHome), + ) + if err != nil { + return err + } + + fmt.Printf("Successfully initialized %d node directories\n", numValidators) + return nil +} + +func initGenFiles( + cdc *codec.Codec, chainID string, accs []app.GenesisAccount, + genFiles []string, numValidators int, +) error { + + appGenState := app.NewDefaultGenesisState() + appGenState.Accounts = accs + + appGenStateJSON, err := codec.MarshalJSONIndent(cdc, appGenState) + if err != nil { + return err + } + + genDoc := types.GenesisDoc{ + ChainID: chainID, + AppState: appGenStateJSON, + Validators: nil, + } + + // generate empty genesis files for each validator and save + for i := 0; i < numValidators; i++ { + if err := genDoc.SaveAs(genFiles[i]); err != nil { + return err + } + } + + return nil +} + +func collectGenFiles( + cdc *codec.Codec, config *cfg.Config, chainID string, + monikers, nodeIDs []string, valPubKeys []crypto.PubKey, + numValidators int, outDir, nodeDirPrefix, nodeDaemonHomeName string, +) error { + + var appState json.RawMessage + genTime := tmtime.Now() + + for i := 0; i < numValidators; i++ { + nodeDirName := fmt.Sprintf("%s%d", nodeDirPrefix, i) + nodeDir := filepath.Join(outDir, nodeDirName, nodeDaemonHomeName) + gentxsDir := filepath.Join(outDir, "gentxs") + moniker := monikers[i] + config.Moniker = nodeDirName + + config.SetRoot(nodeDir) + + nodeID, valPubKey := nodeIDs[i], valPubKeys[i] + initCfg := initConfig{ + ChainID: chainID, + GenTxsDir: gentxsDir, + Name: moniker, + NodeID: nodeID, + ValPubKey: valPubKey, + } + + genDoc, err := loadGenesisDoc(cdc, config.GenesisFile()) + if err != nil { + return err + } + + nodeAppState, err := genAppStateFromConfig(cdc, config, initCfg, genDoc) + if err != nil { + return err + } + + if appState == nil { + // set the canonical application state (they should not differ) + appState = nodeAppState + } + + genFile := config.GenesisFile() + + // overwrite each validator's genesis file to have a canonical genesis time + err = ExportGenesisFileWithTime(genFile, chainID, nil, appState, genTime) + if err != nil { + return err + } + } + + return nil +} + +func getIP(i int, startingIPAddr string) (string, error) { + var ( + ip string + err error + ) + + if len(startingIPAddr) == 0 { + ip, err = server.ExternalIP() + if err != nil { + return "", err + } + } else { + ip, err = calculateIP(startingIPAddr, i) + if err != nil { + return "", err + } + } + + return ip, nil +} + +func writeFile(name string, dir string, contents []byte) error { + writePath := filepath.Join(dir) + file := filepath.Join(writePath, name) + + err := cmn.EnsureDir(writePath, 0700) + if err != nil { + return err + } + + err = cmn.WriteFile(file, contents, 0600) + if err != nil { + return err + } + + return nil +} + +func calculateIP(ip string, i int) (string, error) { + ipv4 := net.ParseIP(ip).To4() + if ipv4 == nil { + return "", fmt.Errorf("%v: non ipv4 address", ip) + } + + for j := 0; j < i; j++ { + ipv4[3]++ + } + + return ipv4.String(), nil +} + +// generateSaveCoinKey returns the address of a public key, along with the secret +// phrase to recover the private key. +func generateSaveCoinKey(clientRoot, keyName, keyPass string, overwrite bool) (sdk.AccAddress, string, error) { + + // get the keystore from the client + keybase, err := clkeys.GetKeyBaseFromDirWithWritePerm(clientRoot) + if err != nil { + return sdk.AccAddress([]byte{}), "", err + } + + // ensure no overwrite + if !overwrite { + _, err := keybase.Get(keyName) + if err == nil { + return sdk.AccAddress([]byte{}), "", fmt.Errorf( + "key already exists, overwrite is disabled (clientRoot: %s)", clientRoot) + } + } + + // generate a private key, with recovery phrase + info, secret, err := keybase.CreateMnemonic(keyName, keys.English, keyPass, keys.Secp256k1) + if err != nil { + return sdk.AccAddress([]byte{}), "", err + } + addr := info.GetPubKey().Address() + return sdk.AccAddress(addr), secret, nil +} diff --git a/init/utils.go b/init/utils.go new file mode 100644 index 000000000..8d41996d0 --- /dev/null +++ b/init/utils.go @@ -0,0 +1,112 @@ +package init + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "time" + + "github.com/cosmos/cosmos-sdk/codec" + amino "github.com/tendermint/go-amino" + cfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/p2p" + "github.com/tendermint/tendermint/privval" + "github.com/tendermint/tendermint/types" + "github.com/irisnet/irishub/app" +) + +// ExportGenesisFile creates and writes the genesis configuration to disk. An +// error is returned if building or writing the configuration to file fails. +func ExportGenesisFile( + genFile, chainID string, validators []types.GenesisValidator, appState json.RawMessage, +) error { + + genDoc := types.GenesisDoc{ + ChainID: chainID, + Validators: validators, + AppState: appState, + } + + if err := genDoc.ValidateAndComplete(); err != nil { + return err + } + + return genDoc.SaveAs(genFile) +} + +// ExportGenesisFileWithTime creates and writes the genesis configuration to disk. +// An error is returned if building or writing the configuration to file fails. +func ExportGenesisFileWithTime( + genFile, chainID string, validators []types.GenesisValidator, + appState json.RawMessage, genTime time.Time, +) error { + + genDoc := types.GenesisDoc{ + GenesisTime: genTime, + ChainID: chainID, + Validators: validators, + AppState: appState, + } + + if err := genDoc.ValidateAndComplete(); err != nil { + return err + } + + return genDoc.SaveAs(genFile) +} + +// read of create the private key file for this config +func ReadOrCreatePrivValidator(privValFile string) crypto.PubKey { + var privValidator *privval.FilePV + + if common.FileExists(privValFile) { + privValidator = privval.LoadFilePV(privValFile) + } else { + privValidator = privval.GenFilePV(privValFile) + privValidator.Save() + } + + return privValidator.GetPubKey() +} + +// InitializeNodeValidatorFiles creates private validator and p2p configuration files. +func InitializeNodeValidatorFiles( + config *cfg.Config) (nodeID string, valPubKey crypto.PubKey, err error, +) { + + nodeKey, err := p2p.LoadOrGenNodeKey(config.NodeKeyFile()) + if err != nil { + return nodeID, valPubKey, err + } + + nodeID = string(nodeKey.ID()) + valPubKey = ReadOrCreatePrivValidator(config.PrivValidatorFile()) + + return nodeID, valPubKey, nil +} + +func loadGenesisDoc(cdc *amino.Codec, genFile string) (genDoc types.GenesisDoc, err error) { + genContents, err := ioutil.ReadFile(genFile) + if err != nil { + return genDoc, err + } + + if err := cdc.UnmarshalJSON(genContents, &genDoc); err != nil { + return genDoc, err + } + + return genDoc, err +} + +func initializeEmptyGenesis( + cdc *codec.Codec, genFile, chainID string, overwrite bool, +) (appState json.RawMessage, err error) { + + if !overwrite && common.FileExists(genFile) { + return nil, fmt.Errorf("genesis.json file already exists: %v", genFile) + } + + return codec.MarshalJSONIndent(cdc, app.NewDefaultGenesisState()) +} diff --git a/modules/iparam/errors.go b/iparam/errors.go similarity index 94% rename from modules/iparam/errors.go rename to iparam/errors.go index 2f6ee4350..5ed92aca7 100644 --- a/modules/iparam/errors.go +++ b/iparam/errors.go @@ -14,7 +14,7 @@ const ( CodeInvalidVotingPeriod sdk.CodeType = 105 CodeInvalidVotingProcedure sdk.CodeType = 106 CodeInvalidThreshold sdk.CodeType = 107 - CodeInvalidGovernancePenalty sdk.CodeType = 108 + CodeInvalidParticipation sdk.CodeType = 108 CodeInvalidVeto sdk.CodeType = 109 CodeInvalidTallyingProcedure sdk.CodeType = 110 CodeInvalidKey sdk.CodeType = 111 diff --git a/modules/iparam/helper.go b/iparam/helper.go similarity index 75% rename from modules/iparam/helper.go rename to iparam/helper.go index fe71c785b..911b003de 100644 --- a/modules/iparam/helper.go +++ b/iparam/helper.go @@ -10,7 +10,7 @@ var ParamMapping = make(map[string]GovParameter) func RegisterGovParamMapping(gps ...GovParameter) { for _, gp := range gps { if gp != nil { - ParamMapping[gp.GetStoreKey()] = gp + ParamMapping[GovParamspace+"/"+string(gp.GetStoreKey())] = gp } } } @@ -25,10 +25,10 @@ func InitGenesisParameter(p Parameter, ctx sdk.Context, genesisData interface{}) } } -func SetParamReadWriter(setter params.Setter, ps ...Parameter) { +func SetParamReadWriter(paramSpace params.Subspace, ps ...Parameter) { for _, p := range ps { if p != nil { - p.SetReadWriter(setter) + p.SetReadWriter(paramSpace) } } -} +} \ No newline at end of file diff --git a/modules/iparam/parameter.go b/iparam/parameter.go similarity index 70% rename from modules/iparam/parameter.go rename to iparam/parameter.go index 3bcb3afed..e51ce8e9f 100644 --- a/modules/iparam/parameter.go +++ b/iparam/parameter.go @@ -1,17 +1,22 @@ package iparam import ( + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/params" ) +const ( + SignalParamspace = "Sig" + GovParamspace = "Gov" +) + type Parameter interface { InitGenesis(interface{}) - GetStoreKey() string + GetStoreKey() []byte - SetReadWriter(setter params.Setter) + SetReadWriter(paramSpace params.Subspace) SaveValue(ctx sdk.Context) @@ -27,7 +32,7 @@ type GovParameter interface { Valid(json string) sdk.Error - GetValueFromRawData(cdc *wire.Codec, res []byte) interface{} + GetValueFromRawData(cdc *codec.Codec, res []byte) interface{} Update(ctx sdk.Context, json string) diff --git a/modules/gov/wire.go b/modules/gov/codec.go similarity index 62% rename from modules/gov/wire.go rename to modules/gov/codec.go index 6f953da4d..5a484bfc9 100644 --- a/modules/gov/wire.go +++ b/modules/gov/codec.go @@ -1,12 +1,12 @@ package gov import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/irisnet/irishub/modules/gov/params" ) -// Register concrete types on wire codec -func RegisterWire(cdc *wire.Codec) { +// Register concrete types on codec codec +func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(MsgSubmitProposal{}, "cosmos-sdk/MsgSubmitProposal", nil) cdc.RegisterConcrete(MsgDeposit{}, "cosmos-sdk/MsgDeposit", nil) @@ -16,12 +16,12 @@ func RegisterWire(cdc *wire.Codec) { cdc.RegisterConcrete(&TextProposal{}, "gov/TextProposal", nil) //////////////////// iris begin /////////////////////////// - cdc.RegisterConcrete(govparams.DepositProcedure{},"cosmos-sdk/DepositProcedure",nil) - cdc.RegisterConcrete(govparams.TallyingProcedure{},"cosmos-sdk/TallyingProcedure",nil) - cdc.RegisterConcrete(govparams.VotingProcedure{},"cosmos-sdk/VotingProcedure",nil) + cdc.RegisterConcrete(&govparams.DepositProcedure{},"cosmos-sdk/DepositProcedure",nil) + cdc.RegisterConcrete(&govparams.TallyingProcedure{},"cosmos-sdk/TallyingProcedure",nil) + cdc.RegisterConcrete(&govparams.VotingProcedure{},"cosmos-sdk/VotingProcedure",nil) cdc.RegisterConcrete(&ParameterProposal{}, "gov/ParameterProposal", nil) cdc.RegisterConcrete(&SoftwareUpgradeProposal{}, "gov/SoftwareUpgradeProposal", nil) //////////////////// iris end /////////////////////////// } -var msgCdc = wire.NewCodec() +var msgCdc = codec.New() diff --git a/modules/gov/config_file.go b/modules/gov/config_file.go index 34ae97a1a..90d238c78 100644 --- a/modules/gov/config_file.go +++ b/modules/gov/config_file.go @@ -2,11 +2,11 @@ package gov import ( "fmt" - "github.com/irisnet/irishub/modules/iparam" + "github.com/irisnet/irishub/iparam" "encoding/json" sdk "github.com/cosmos/cosmos-sdk/types" "path" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" cmn "github.com/tendermint/tendermint/libs/common" "github.com/irisnet/irishub/modules/gov/params" ) @@ -15,7 +15,7 @@ type ParameterConfigFile struct { Govparams govparams.ParamSet `json:"gov"` } -func (pd *ParameterConfigFile) ReadFile(cdc *wire.Codec, pathStr string) error { +func (pd *ParameterConfigFile) ReadFile(cdc *codec.Codec, pathStr string) error { pathStr = path.Join(pathStr, "config/params.json") jsonBytes, err := cmn.ReadFile(pathStr) @@ -29,19 +29,28 @@ func (pd *ParameterConfigFile) ReadFile(cdc *wire.Codec, pathStr string) error { err = cdc.UnmarshalJSON(jsonBytes, &pd) return err } -func (pd *ParameterConfigFile) WriteFile(cdc *wire.Codec, res []sdk.KVPair , pathStr string) error { +func (pd *ParameterConfigFile) WriteFile(cdc *codec.Codec, res []sdk.KVPair , pathStr string) error { for _, kv := range res { switch string(kv.Key) { - case "Gov/gov/DepositProcedure": - cdc.MustUnmarshalBinary(kv.Value, &pd.Govparams.DepositProcedure) - case "Gov/gov/VotingProcedure": - cdc.MustUnmarshalBinary(kv.Value, &pd.Govparams.VotingProcedure) - case "Gov/gov/TallyingProcedure": - cdc.MustUnmarshalBinary(kv.Value, &pd.Govparams.TallyingProcedure) - default: - return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidTallyingProcedure, fmt.Sprintf(string(kv.Key)+" is not found")) + case "Gov/govDepositProcedure": + err := cdc.UnmarshalJSON(kv.Value, &pd.Govparams.DepositProcedure) + if err != nil { + return err + } + case "Gov/govVotingProcedure": + err := cdc.UnmarshalJSON(kv.Value, &pd.Govparams.VotingProcedure) + if err != nil { + return err + } + case "Gov/govTallyingProcedure": + err := cdc.UnmarshalJSON(kv.Value, &pd.Govparams.TallyingProcedure) + if err != nil { + return err + } } } + + output, err := cdc.MarshalJSONIndent(pd, "", " ") if err != nil { @@ -69,11 +78,11 @@ func (pd *ParameterConfigFile) GetParamFromKey(keyStr string, opStr string) (Par } switch keyStr { - case "Gov/gov/DepositProcedure": + case "Gov/govDepositProcedure": jsonBytes, err = json.Marshal(pd.Govparams.DepositProcedure) - case "Gov/gov/VotingProcedure": + case "Gov/govVotingProcedure": jsonBytes, err = json.Marshal(pd.Govparams.VotingProcedure) - case "Gov/gov/TallyingProcedure": + case "Gov/govTallyingProcedure": jsonBytes, err = json.Marshal(pd.Govparams.TallyingProcedure) default: return param, sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidKey, fmt.Sprintf(keyStr+" is not found")) diff --git a/modules/gov/depositsvotes.go b/modules/gov/depositsvotes.go index 19ed97f69..412456842 100644 --- a/modules/gov/depositsvotes.go +++ b/modules/gov/depositsvotes.go @@ -11,17 +11,39 @@ import ( // Vote type Vote struct { Voter sdk.AccAddress `json:"voter"` // address of the voter - ProposalID int64 `json:"proposal_id"` // proposalID of the proposal + ProposalID uint64 `json:"proposal_id"` // proposalID of the proposal Option VoteOption `json:"option"` // option from OptionSet chosen by the voter } +// Returns whether 2 votes are equal +func (voteA Vote) Equals(voteB Vote) bool { + return voteA.Voter.Equals(voteB.Voter) && voteA.ProposalID == voteB.ProposalID && voteA.Option == voteB.Option +} + +// Returns whether a vote is empty +func (voteA Vote) Empty() bool { + voteB := Vote{} + return voteA.Equals(voteB) +} + // Deposit type Deposit struct { - Depositer sdk.AccAddress `json:"depositer"` // Address of the depositer - ProposalID int64 `json:"proposal_id"` // proposalID of the proposal + Depositor sdk.AccAddress `json:"depositor"` // Address of the depositor + ProposalID uint64 `json:"proposal_id"` // proposalID of the proposal Amount sdk.Coins `json:"amount"` // Deposit amount } +// Returns whether 2 deposits are equal +func (depositA Deposit) Equals(depositB Deposit) bool { + return depositA.Depositor.Equals(depositB.Depositor) && depositA.ProposalID == depositB.ProposalID && depositA.Amount.IsEqual(depositB.Amount) +} + +// Returns whether a deposit is empty +func (depositA Deposit) Empty() bool { + depositB := Deposit{} + return depositA.Equals(depositB) +} + // Type that represents VoteOption as a byte type VoteOption byte @@ -110,6 +132,7 @@ func (vo VoteOption) String() string { } // For Printf / Sprintf, returns bech32 when using %s +// nolint: errcheck func (vo VoteOption) Format(s fmt.State, verb rune) { switch verb { case 's': diff --git a/modules/gov/errors.go b/modules/gov/errors.go index 45e32b14a..0ea96d2dc 100644 --- a/modules/gov/errors.go +++ b/modules/gov/errors.go @@ -21,26 +21,28 @@ const ( CodeInvalidVote sdk.CodeType = 9 CodeInvalidGenesis sdk.CodeType = 10 CodeInvalidProposalStatus sdk.CodeType = 11 + //////////////////// iris begin /////////////////////////// CodeInvalidParam sdk.CodeType = 12 CodeInvalidParamOp sdk.CodeType = 13 + //////////////////// iris end ///////////////////////////// ) //---------------------------------------- // Error constructors -func ErrUnknownProposal(codespace sdk.CodespaceType, proposalID int64) sdk.Error { - return sdk.NewError(codespace, CodeUnknownProposal, fmt.Sprintf("Unknown proposal - %d", proposalID)) +func ErrUnknownProposal(codespace sdk.CodespaceType, proposalID uint64) sdk.Error { + return sdk.NewError(codespace, CodeUnknownProposal, fmt.Sprintf("Unknown proposal with id %d", proposalID)) } -func ErrInactiveProposal(codespace sdk.CodespaceType, proposalID int64) sdk.Error { - return sdk.NewError(codespace, CodeInactiveProposal, fmt.Sprintf("Inactive proposal - %d", proposalID)) +func ErrInactiveProposal(codespace sdk.CodespaceType, proposalID uint64) sdk.Error { + return sdk.NewError(codespace, CodeInactiveProposal, fmt.Sprintf("Inactive proposal with id %d", proposalID)) } -func ErrAlreadyActiveProposal(codespace sdk.CodespaceType, proposalID int64) sdk.Error { +func ErrAlreadyActiveProposal(codespace sdk.CodespaceType, proposalID uint64) sdk.Error { return sdk.NewError(codespace, CodeAlreadyActiveProposal, fmt.Sprintf("Proposal %d has been already active", proposalID)) } -func ErrAlreadyFinishedProposal(codespace sdk.CodespaceType, proposalID int64) sdk.Error { +func ErrAlreadyFinishedProposal(codespace sdk.CodespaceType, proposalID uint64) sdk.Error { return sdk.NewError(codespace, CodeAlreadyFinishedProposal, fmt.Sprintf("Proposal %d has already passed its voting period", proposalID)) } @@ -68,10 +70,12 @@ func ErrInvalidGenesis(codespace sdk.CodespaceType, msg string) sdk.Error { return sdk.NewError(codespace, CodeInvalidVote, msg) } +//////////////////// iris begin /////////////////////////// func ErrInvalidParam(codespace sdk.CodespaceType) sdk.Error { return sdk.NewError(codespace, CodeInvalidParam, fmt.Sprintf("Param is not valid")) } func ErrInvalidParamOp(codespace sdk.CodespaceType, opStr string) sdk.Error { return sdk.NewError(codespace, CodeInvalidParamOp, fmt.Sprintf("Op '%s' is not valid", opStr)) -} \ No newline at end of file +} +//////////////////// iris end ///////////////////////////// diff --git a/modules/gov/genesis.go b/modules/gov/genesis.go index f8f8715bf..760f0aac0 100644 --- a/modules/gov/genesis.go +++ b/modules/gov/genesis.go @@ -1,22 +1,37 @@ package gov import ( + "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/irisnet/irishub/iparam" "github.com/irisnet/irishub/modules/gov/params" - "github.com/irisnet/irishub/modules/iparam" - "fmt" "github.com/irisnet/irishub/types" + "time" ) // GenesisState - all gov state that must be provided at genesis type GenesisState struct { - StartingProposalID int64 `json:"starting_proposalID"` - DepositProcedure govparams.DepositProcedure `json:"deposit_period"` - VotingProcedure govparams.VotingProcedure `json:"voting_period"` - TallyingProcedure govparams.TallyingProcedure `json:"tallying_procedure"` + StartingProposalID uint64 `json:"starting_proposalID"` + Deposits []DepositWithMetadata `json:"deposits"` + Votes []VoteWithMetadata `json:"votes"` + Proposals []Proposal `json:"proposals"` + DepositProcedure govparams.DepositProcedure `json:"deposit_period"` + VotingProcedure govparams.VotingProcedure `json:"voting_period"` + TallyingProcedure govparams.TallyingProcedure `json:"tallying_procedure"` +} + +type DepositWithMetadata struct { + ProposalID uint64 `json:"proposal_id"` + Deposit Deposit `json:"deposit"` +} + +// VoteWithMetadata (just for genesis) +type VoteWithMetadata struct { + ProposalID uint64 `json:"proposal_id"` + Vote Vote `json:"vote"` } -func NewGenesisState(startingProposalID int64, dp govparams.DepositProcedure, vp govparams.VotingProcedure, tp govparams.TallyingProcedure) GenesisState { +func NewGenesisState(startingProposalID uint64, dp govparams.DepositProcedure, vp govparams.VotingProcedure, tp govparams.TallyingProcedure) GenesisState { return GenesisState{ StartingProposalID: startingProposalID, DepositProcedure: dp, @@ -33,21 +48,54 @@ func InitGenesis(ctx sdk.Context, k Keeper, data GenesisState) { panic(err) } //k.setDepositProcedure(ctx, data.DepositProcedure) + //////////////////// iris begin /////////////////////////// iparam.InitGenesisParameter(&govparams.DepositProcedureParameter, ctx, data.DepositProcedure) iparam.InitGenesisParameter(&govparams.VotingProcedureParameter, ctx, data.VotingProcedure) iparam.InitGenesisParameter(&govparams.TallyingProcedureParameter, ctx, data.TallyingProcedure) - + //////////////////// iris end ///////////////////////////// + for _, deposit := range data.Deposits { + k.setDeposit(ctx, deposit.ProposalID, deposit.Deposit.Depositor, deposit.Deposit) + } + for _, vote := range data.Votes { + k.setVote(ctx, vote.ProposalID, vote.Vote.Voter, vote.Vote) + } + for _, proposal := range data.Proposals { + k.SetProposal(ctx, proposal) + } } -// WriteGenesis - output genesis parameters -func WriteGenesis(ctx sdk.Context, k Keeper) GenesisState { - startingProposalID, _ := k.getNewProposalID(ctx) +// ExportGenesis - output genesis parameters +func ExportGenesis(ctx sdk.Context, k Keeper) GenesisState { + startingProposalID, _ := k.peekCurrentProposalID(ctx) + //////////////////// iris begin /////////////////////////// depositProcedure := govparams.GetDepositProcedure(ctx) votingProcedure := govparams.GetVotingProcedure(ctx) tallyingProcedure := govparams.GetTallyingProcedure(ctx) + //////////////////// iris end ///////////////////////////// + var deposits []DepositWithMetadata + var votes []VoteWithMetadata + proposals := k.GetProposalsFiltered(ctx, nil, nil, StatusNil, 0) + for _, proposal := range proposals { + proposalID := proposal.GetProposalID() + depositsIterator := k.GetDeposits(ctx, proposalID) + for ; depositsIterator.Valid(); depositsIterator.Next() { + var deposit Deposit + k.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), &deposit) + deposits = append(deposits, DepositWithMetadata{proposalID, deposit}) + } + votesIterator := k.GetVotes(ctx, proposalID) + for ; votesIterator.Valid(); votesIterator.Next() { + var vote Vote + k.cdc.MustUnmarshalBinaryLengthPrefixed(votesIterator.Value(), &vote) + votes = append(votes, VoteWithMetadata{proposalID, vote}) + } + } return GenesisState{ StartingProposalID: startingProposalID, + Deposits: deposits, + Votes: votes, + Proposals: proposals, DepositProcedure: depositProcedure, VotingProcedure: votingProcedure, TallyingProcedure: tallyingProcedure, @@ -56,7 +104,7 @@ func WriteGenesis(ctx sdk.Context, k Keeper) GenesisState { // get raw genesis raw message for testing func DefaultGenesisState() GenesisState { - Denom := "iris" + Denom := "iris" IrisCt := types.NewDefaultCoinType(Denom) minDeposit, err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", 1000, Denom)) if err != nil { @@ -66,22 +114,22 @@ func DefaultGenesisState() GenesisState { StartingProposalID: 1, DepositProcedure: govparams.DepositProcedure{ MinDeposit: sdk.Coins{minDeposit}, - MaxDepositPeriod: 20000, + MaxDepositPeriod: time.Duration(172800) * time.Second, }, VotingProcedure: govparams.VotingProcedure{ - VotingPeriod: 20000, + VotingPeriod: time.Duration(172800) * time.Second, }, TallyingProcedure: govparams.TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 100), + Threshold: sdk.NewDecWithPrec(5, 1), + Veto: sdk.NewDecWithPrec(334, 3), + Participation: sdk.NewDecWithPrec(667, 3), }, } } // get raw genesis raw message for testing func DefaultGenesisStateForCliTest() GenesisState { - Denom := "iris" + Denom := "iris" IrisCt := types.NewDefaultCoinType(Denom) minDeposit, err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", 10, Denom)) if err != nil { @@ -91,22 +139,22 @@ func DefaultGenesisStateForCliTest() GenesisState { StartingProposalID: 1, DepositProcedure: govparams.DepositProcedure{ MinDeposit: sdk.Coins{minDeposit}, - MaxDepositPeriod: 10, + MaxDepositPeriod: time.Duration(60) * time.Second, }, VotingProcedure: govparams.VotingProcedure{ - VotingPeriod: 10, + VotingPeriod: time.Duration(60) * time.Second, }, TallyingProcedure: govparams.TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 100), + Threshold: sdk.NewDecWithPrec(5, 1), + Veto: sdk.NewDecWithPrec(334, 3), + Participation: sdk.NewDecWithPrec(667, 3), }, } } // get raw genesis raw message for testing func DefaultGenesisStateForLCDTest() GenesisState { - Denom := "iris" + Denom := "iris" IrisCt := types.NewDefaultCoinType(Denom) minDeposit, err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", 10, Denom)) if err != nil { @@ -116,15 +164,15 @@ func DefaultGenesisStateForLCDTest() GenesisState { StartingProposalID: 1, DepositProcedure: govparams.DepositProcedure{ MinDeposit: sdk.Coins{minDeposit}, - MaxDepositPeriod: 30, + MaxDepositPeriod: time.Duration(172800) * time.Second, }, VotingProcedure: govparams.VotingProcedure{ - VotingPeriod: 30, + VotingPeriod: time.Duration(172800) * time.Second, }, TallyingProcedure: govparams.TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 100), + Threshold: sdk.NewDecWithPrec(5, 1), + Veto: sdk.NewDecWithPrec(334, 3), + Participation: sdk.NewDecWithPrec(667, 3), }, } } diff --git a/modules/gov/handler.go b/modules/gov/handler.go index 007a12ec4..031d832ef 100644 --- a/modules/gov/handler.go +++ b/modules/gov/handler.go @@ -3,11 +3,11 @@ package gov import ( "fmt" - "encoding/json" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/irisnet/irishub/modules/gov/params" "github.com/irisnet/irishub/modules/gov/tags" "strconv" + "encoding/json" + "github.com/irisnet/irishub/modules/gov/params" ) // Handle all "gov" type messages. @@ -28,36 +28,34 @@ func NewHandler(keeper Keeper) sdk.Handler { } func handleMsgSubmitProposal(ctx sdk.Context, keeper Keeper, msg MsgSubmitProposal) sdk.Result { + //////////////////// iris begin /////////////////////////// + proposal := keeper.NewProposal(ctx, msg.Title, msg.Description, msg.ProposalType,msg.Param) + //////////////////// iris end ///////////////////////////// - err := msg.ValidateBasic() - - if err != nil { - return err.Result() - } - - proposal := keeper.NewProposal(ctx, msg.Title, msg.Description, msg.ProposalType, msg.Param) err, votingStarted := keeper.AddDeposit(ctx, proposal.GetProposalID(), msg.Proposer, msg.InitialDeposit) if err != nil { return err.Result() } - - proposalIDBytes := []byte(strconv.FormatInt(proposal.GetProposalID(), 10)) + //////////////////// iris begin /////////////////////////// + proposalIDBytes := []byte(strconv.FormatUint(proposal.GetProposalID(), 10)) var paramBytes []byte if msg.ProposalType == ProposalTypeParameterChange { paramBytes, _ = json.Marshal(proposal.(*ParameterProposal).Param) } - + //////////////////// iris end ///////////////////////////// resTags := sdk.NewTags( tags.Action, tags.ActionSubmitProposal, tags.Proposer, []byte(msg.Proposer.String()), tags.ProposalID, proposalIDBytes, + //////////////////// iris begin /////////////////////////// tags.Param, paramBytes, + //////////////////// iris end ///////////////////////////// ) if votingStarted { - resTags.AppendTag(tags.VotingPeriodStart, proposalIDBytes) + resTags = resTags.AppendTag(tags.VotingPeriodStart, proposalIDBytes) } return sdk.Result{ @@ -68,22 +66,25 @@ func handleMsgSubmitProposal(ctx sdk.Context, keeper Keeper, msg MsgSubmitPropos func handleMsgDeposit(ctx sdk.Context, keeper Keeper, msg MsgDeposit) sdk.Result { - err, votingStarted := keeper.AddDeposit(ctx, msg.ProposalID, msg.Depositer, msg.Amount) + err, votingStarted := keeper.AddDeposit(ctx, msg.ProposalID, msg.Depositor, msg.Amount) if err != nil { return err.Result() } - proposalIDBytes := keeper.cdc.MustMarshalBinaryBare(msg.ProposalID) + //////////////////// iris begin /////////////////////////// + proposalIDBytes := []byte(strconv.FormatUint(msg.ProposalID, 10)) + //////////////////// iris end ///////////////////////////// + // TODO: Add tag for if voting period started resTags := sdk.NewTags( tags.Action, tags.ActionDeposit, - tags.Depositer, []byte(msg.Depositer.String()), + tags.Depositor, []byte(msg.Depositor.String()), tags.ProposalID, proposalIDBytes, ) if votingStarted { - resTags.AppendTag(tags.VotingPeriodStart, proposalIDBytes) + resTags = resTags.AppendTag(tags.VotingPeriodStart, proposalIDBytes) } return sdk.Result{ @@ -98,7 +99,9 @@ func handleMsgVote(ctx sdk.Context, keeper Keeper, msg MsgVote) sdk.Result { return err.Result() } - proposalIDBytes := keeper.cdc.MustMarshalBinaryBare(msg.ProposalID) + //////////////////// iris begin /////////////////////////// + proposalIDBytes := []byte(strconv.FormatUint(msg.ProposalID, 10)) + //////////////////// iris end ///////////////////////////// resTags := sdk.NewTags( tags.Action, tags.ActionVote, @@ -113,44 +116,45 @@ func handleMsgVote(ctx sdk.Context, keeper Keeper, msg MsgVote) sdk.Result { // Called every block, process inflation, update validator set func EndBlocker(ctx sdk.Context, keeper Keeper) (resTags sdk.Tags) { - logger := ctx.Logger().With("module", "x/gov") + logger := ctx.Logger().With("module", "gov") resTags = sdk.NewTags() - // Delete proposals that haven't met minDeposit - for shouldPopInactiveProposalQueue(ctx, keeper) { - inactiveProposal := keeper.InactiveProposalQueuePop(ctx) - if inactiveProposal.GetStatus() != StatusDepositPeriod { - continue - } - - proposalIDBytes := keeper.cdc.MustMarshalBinaryBare(inactiveProposal.GetProposalID()) - keeper.DeleteProposal(ctx, inactiveProposal) - resTags.AppendTag(tags.Action, tags.ActionProposalDropped) - resTags.AppendTag(tags.ProposalID, proposalIDBytes) - - logger.Info("Proposal %d - \"%s\" - didn't mean minimum deposit (had only %s), deleted", - inactiveProposal.GetProposalID(), inactiveProposal.GetTitle(), inactiveProposal.GetTotalDeposit()) + inactiveIterator := keeper.InactiveProposalQueueIterator(ctx, ctx.BlockHeader().Time) + for ; inactiveIterator.Valid(); inactiveIterator.Next() { + var proposalID uint64 + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(inactiveIterator.Value(), &proposalID) + inactiveProposal := keeper.GetProposal(ctx, proposalID) + keeper.DeleteProposal(ctx, proposalID) + keeper.DeleteDeposits(ctx, proposalID) // delete any associated deposits (burned) + + resTags = resTags.AppendTag(tags.Action, tags.ActionProposalDropped) + resTags = resTags.AppendTag(tags.ProposalID, []byte(string(proposalID))) + + logger.Info( + fmt.Sprintf("proposal %d (%s) didn't meet minimum deposit of %s (had only %s); deleted", + inactiveProposal.GetProposalID(), + inactiveProposal.GetTitle(), + govparams.GetDepositProcedure(ctx).MinDeposit, + inactiveProposal.GetTotalDeposit(), + ), + ) } + inactiveIterator.Close() - // Check if earliest Active Proposal ended voting period yet - for shouldPopActiveProposalQueue(ctx, keeper) { - activeProposal := keeper.ActiveProposalQueuePop(ctx) - - proposalStartBlock := activeProposal.GetVotingStartBlock() - votingPeriod := govparams.GetVotingProcedure(ctx).VotingPeriod - if ctx.BlockHeight() < proposalStartBlock+votingPeriod { - continue - } + activeIterator := keeper.ActiveProposalQueueIterator(ctx, ctx.BlockHeader().Time) + for ; activeIterator.Valid(); activeIterator.Next() { + var proposalID uint64 + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(activeIterator.Value(), &proposalID) + activeProposal := keeper.GetProposal(ctx, proposalID) + passes, tallyResults := tally(ctx, keeper, activeProposal) - passes, tallyResults, nonVotingVals := tally(ctx, keeper, activeProposal) - proposalIDBytes := keeper.cdc.MustMarshalBinaryBare(activeProposal.GetProposalID()) var action []byte if passes { keeper.RefundDeposits(ctx, activeProposal.GetProposalID()) activeProposal.SetStatus(StatusPassed) action = tags.ActionProposalPassed - activeProposal.Execute(ctx, keeper) + activeProposal.Execute(ctx,keeper) } else { keeper.DeleteDeposits(ctx, activeProposal.GetProposalID()) activeProposal.SetStatus(StatusRejected) @@ -159,49 +163,15 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (resTags sdk.Tags) { activeProposal.SetTallyResult(tallyResults) keeper.SetProposal(ctx, activeProposal) - logger.Info("Proposal %d - \"%s\" - tallied, passed: %v", - activeProposal.GetProposalID(), activeProposal.GetTitle(), passes) + keeper.RemoveFromActiveProposalQueue(ctx, activeProposal.GetVotingEndTime(), activeProposal.GetProposalID()) - for _, valAddr := range nonVotingVals { - val := keeper.ds.GetValidatorSet().Validator(ctx, valAddr) - keeper.ds.GetValidatorSet().Slash(ctx, - val.GetPubKey(), - ctx.BlockHeight(), - val.GetPower().RoundInt64(), - govparams.GetTallyingProcedure(ctx).GovernancePenalty) + logger.Info(fmt.Sprintf("proposal %d (%s) tallied; passed: %v", + activeProposal.GetProposalID(), activeProposal.GetTitle(), passes)) - logger.Info(fmt.Sprintf("Validator %s failed to vote on proposal %d, slashing", - val.GetOwner(), activeProposal.GetProposalID())) - } - - resTags.AppendTag(tags.Action, action) - resTags.AppendTag(tags.ProposalID, proposalIDBytes) + resTags = resTags.AppendTag(tags.Action, action) + resTags = resTags.AppendTag(tags.ProposalID, []byte(string(proposalID))) } + activeIterator.Close() return resTags -} -func shouldPopInactiveProposalQueue(ctx sdk.Context, keeper Keeper) bool { - depositProcedure := govparams.GetDepositProcedure(ctx) - peekProposal := keeper.InactiveProposalQueuePeek(ctx) - - if peekProposal == nil { - return false - } else if peekProposal.GetStatus() != StatusDepositPeriod { - return true - } else if ctx.BlockHeight() >= peekProposal.GetSubmitBlock()+depositProcedure.MaxDepositPeriod { - return true - } - return false -} - -func shouldPopActiveProposalQueue(ctx sdk.Context, keeper Keeper) bool { - votingProcedure := govparams.GetVotingProcedure(ctx) - peekProposal := keeper.ActiveProposalQueuePeek(ctx) - - if peekProposal == nil { - return false - } else if ctx.BlockHeight() >= peekProposal.GetVotingStartBlock()+votingProcedure.VotingPeriod { - return true - } - return false -} +} \ No newline at end of file diff --git a/modules/gov/keeper.go b/modules/gov/keeper.go index 8ffa4f9b3..af7247458 100644 --- a/modules/gov/keeper.go +++ b/modules/gov/keeper.go @@ -1,14 +1,20 @@ package gov import ( + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/irisnet/irishub/iparam" "github.com/irisnet/irishub/modules/gov/params" - "github.com/irisnet/irishub/modules/iparam" + "github.com/tendermint/tendermint/crypto" + "time" ) // nolint +var ( + DepositedCoinsAccAddr = sdk.AccAddress(crypto.AddressHash([]byte("govDepositedCoins"))) + BurnedDepositCoinsAccAddr = sdk.AccAddress(crypto.AddressHash([]byte("govBurnedDepositCoins"))) +) // Governance Keeper type Keeper struct { @@ -25,15 +31,19 @@ type Keeper struct { // The (unexposed) keys used to access the stores from the Context. storeKey sdk.StoreKey - // The wire codec for binary encoding/decoding. - cdc *wire.Codec + // The codec codec for binary encoding/decoding. + cdc *codec.Codec // Reserved codespace codespace sdk.CodespaceType } -// NewGovernanceMapper returns a mapper that uses go-wire to (binary) encode and decode gov types. -func NewKeeper(cdc *wire.Codec, key sdk.StoreKey, ck bank.Keeper, ds sdk.DelegationSet, codespace sdk.CodespaceType) Keeper { +// NewKeeper returns a governance keeper. It handles: +// - submitting governance proposals +// - depositing funds into proposals, and activating upon sufficient funds being deposited +// - users voting on proposals, with weight proportional to stake in the system +// - and tallying the result of the vote. +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, ck bank.Keeper, ds sdk.DelegationSet, codespace sdk.CodespaceType) Keeper { return Keeper{ storeKey: key, ck: ck, @@ -44,14 +54,10 @@ func NewKeeper(cdc *wire.Codec, key sdk.StoreKey, ck bank.Keeper, ds sdk.Delegat } } -// Returns the go-wire codec. -func (keeper Keeper) WireCodec() *wire.Codec { - return keeper.cdc -} - // ===================================================== // Proposals +//////////////////// iris begin /////////////////////////// func (keeper Keeper) NewProposal(ctx sdk.Context, title string, description string, proposalType ProposalKind, param Param) Proposal { switch proposalType { case ProposalTypeText: @@ -64,6 +70,11 @@ func (keeper Keeper) NewProposal(ctx sdk.Context, title string, description stri return nil } +//////////////////// iris end ///////////////////////////// + +// ===================================================== +// Proposals + // Creates a NewProposal func (keeper Keeper) NewTextProposal(ctx sdk.Context, title string, description string, proposalType ProposalKind) Proposal { proposalID, err := keeper.getNewProposalID(ctx) @@ -71,35 +82,38 @@ func (keeper Keeper) NewTextProposal(ctx sdk.Context, title string, description return nil } var proposal Proposal = &TextProposal{ - ProposalID: proposalID, - Title: title, - Description: description, - ProposalType: proposalType, - Status: StatusDepositPeriod, - TallyResult: EmptyTallyResult(), - TotalDeposit: sdk.Coins{}, - SubmitBlock: ctx.BlockHeight(), - VotingStartBlock: -1, // TODO: Make Time + ProposalID: proposalID, + Title: title, + Description: description, + ProposalType: proposalType, + Status: StatusDepositPeriod, + TallyResult: EmptyTallyResult(), + TotalDeposit: sdk.Coins{}, + SubmitTime: ctx.BlockHeader().Time, } keeper.SetProposal(ctx, proposal) - keeper.InactiveProposalQueuePush(ctx, proposal) + depositPeriod := govparams.GetDepositProcedure(ctx).MaxDepositPeriod + proposal.SetDepositEndTime(proposal.GetSubmitTime().Add(depositPeriod)) + keeper.SetProposal(ctx, proposal) + keeper.InsertInactiveProposalQueue(ctx, proposal.GetDepositEndTime(), proposalID) return proposal } +//////////////////// iris begin /////////////////////////// func (keeper Keeper) NewParametersProposal(ctx sdk.Context, title string, description string, proposalType ProposalKind, param Param) Proposal { proposalID, err := keeper.getNewProposalID(ctx) if err != nil { return nil } var textProposal = TextProposal{ - ProposalID: proposalID, - Title: title, - Description: description, - ProposalType: proposalType, - Status: StatusDepositPeriod, - TotalDeposit: sdk.Coins{}, - SubmitBlock: ctx.BlockHeight(), - VotingStartBlock: -1, // TODO: Make Time + ProposalID: proposalID, + Title: title, + Description: description, + ProposalType: proposalType, + Status: StatusDepositPeriod, + TallyResult: EmptyTallyResult(), + TotalDeposit: sdk.Coins{}, + SubmitTime: ctx.BlockHeader().Time, } param.Value = iparam.ParamMapping[param.Key].ToJson(param.Value) @@ -108,8 +122,11 @@ func (keeper Keeper) NewParametersProposal(ctx sdk.Context, title string, descri textProposal, param, } + + depositPeriod := govparams.GetDepositProcedure(ctx).MaxDepositPeriod + proposal.SetDepositEndTime(proposal.GetSubmitTime().Add(depositPeriod)) keeper.SetProposal(ctx, proposal) - keeper.InactiveProposalQueuePush(ctx, proposal) + keeper.InsertInactiveProposalQueue(ctx, proposal.GetDepositEndTime(), proposalID) return proposal } @@ -119,25 +136,30 @@ func (keeper Keeper) NewUpgradeProposal(ctx sdk.Context, title string, descripti return nil } var textProposal = TextProposal{ - ProposalID: proposalID, - Title: title, - Description: description, - ProposalType: proposalType, - Status: StatusDepositPeriod, - TotalDeposit: sdk.Coins{}, - SubmitBlock: ctx.BlockHeight(), - VotingStartBlock: -1, // TODO: Make Time + ProposalID: proposalID, + Title: title, + Description: description, + ProposalType: proposalType, + Status: StatusDepositPeriod, + TallyResult: EmptyTallyResult(), + TotalDeposit: sdk.Coins{}, + SubmitTime: ctx.BlockHeader().Time, } var proposal Proposal = &SoftwareUpgradeProposal{ textProposal, } + + depositPeriod := govparams.GetDepositProcedure(ctx).MaxDepositPeriod + proposal.SetDepositEndTime(proposal.GetSubmitTime().Add(depositPeriod)) keeper.SetProposal(ctx, proposal) - keeper.InactiveProposalQueuePush(ctx, proposal) + keeper.InsertInactiveProposalQueue(ctx, proposal.GetDepositEndTime(), proposalID) return proposal } +//////////////////// iris end ///////////////////////////// + // Get Proposal from store by ProposalID -func (keeper Keeper) GetProposal(ctx sdk.Context, proposalID int64) Proposal { +func (keeper Keeper) GetProposal(ctx sdk.Context, proposalID uint64) Proposal { store := ctx.KVStore(keeper.storeKey) bz := store.Get(KeyProposal(proposalID)) if bz == nil { @@ -145,71 +167,133 @@ func (keeper Keeper) GetProposal(ctx sdk.Context, proposalID int64) Proposal { } var proposal Proposal - keeper.cdc.MustUnmarshalBinary(bz, &proposal) + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposal) return proposal } -// Implements sdk.AccountMapper. +// Implements sdk.AccountKeeper. func (keeper Keeper) SetProposal(ctx sdk.Context, proposal Proposal) { store := ctx.KVStore(keeper.storeKey) - bz := keeper.cdc.MustMarshalBinary(proposal) + bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(proposal) store.Set(KeyProposal(proposal.GetProposalID()), bz) } -// Implements sdk.AccountMapper. -func (keeper Keeper) DeleteProposal(ctx sdk.Context, proposal Proposal) { +// Implements sdk.AccountKeeper. +func (keeper Keeper) DeleteProposal(ctx sdk.Context, proposalID uint64) { store := ctx.KVStore(keeper.storeKey) - store.Delete(KeyProposal(proposal.GetProposalID())) + proposal := keeper.GetProposal(ctx, proposalID) + keeper.RemoveFromInactiveProposalQueue(ctx, proposal.GetDepositEndTime(), proposalID) + keeper.RemoveFromActiveProposalQueue(ctx, proposal.GetVotingEndTime(), proposalID) + store.Delete(KeyProposal(proposalID)) +} + +// Get Proposal from store by ProposalID +func (keeper Keeper) GetProposalsFiltered(ctx sdk.Context, voterAddr sdk.AccAddress, depositorAddr sdk.AccAddress, status ProposalStatus, numLatest uint64) []Proposal { + + maxProposalID, err := keeper.peekCurrentProposalID(ctx) + if err != nil { + return nil + } + + matchingProposals := []Proposal{} + + if numLatest == 0 || maxProposalID < numLatest { + numLatest = maxProposalID + } + + for proposalID := maxProposalID - numLatest; proposalID < maxProposalID; proposalID++ { + if voterAddr != nil && len(voterAddr) != 0 { + _, found := keeper.GetVote(ctx, proposalID, voterAddr) + if !found { + continue + } + } + + if depositorAddr != nil && len(depositorAddr) != 0 { + _, found := keeper.GetDeposit(ctx, proposalID, depositorAddr) + if !found { + continue + } + } + + proposal := keeper.GetProposal(ctx, proposalID) + if proposal == nil { + continue + } + + if validProposalStatus(status) { + if proposal.GetStatus() != status { + continue + } + } + + matchingProposals = append(matchingProposals, proposal) + } + return matchingProposals } -func (keeper Keeper) setInitialProposalID(ctx sdk.Context, proposalID int64) sdk.Error { +func (keeper Keeper) setInitialProposalID(ctx sdk.Context, proposalID uint64) sdk.Error { store := ctx.KVStore(keeper.storeKey) bz := store.Get(KeyNextProposalID) if bz != nil { return ErrInvalidGenesis(keeper.codespace, "Initial ProposalID already set") } - bz = keeper.cdc.MustMarshalBinary(proposalID) + bz = keeper.cdc.MustMarshalBinaryLengthPrefixed(proposalID) store.Set(KeyNextProposalID, bz) return nil } // Get the last used proposal ID -func (keeper Keeper) GetLastProposalID(ctx sdk.Context) (proposalID int64) { - store := ctx.KVStore(keeper.storeKey) - bz := store.Get(KeyNextProposalID) - if bz == nil { +func (keeper Keeper) GetLastProposalID(ctx sdk.Context) (proposalID uint64) { + proposalID, err := keeper.peekCurrentProposalID(ctx) + if err != nil { return 0 } - keeper.cdc.MustUnmarshalBinary(bz, &proposalID) proposalID-- return } -func (keeper Keeper) getNewProposalID(ctx sdk.Context) (proposalID int64, err sdk.Error) { +// Gets the next available ProposalID and increments it +func (keeper Keeper) getNewProposalID(ctx sdk.Context) (proposalID uint64, err sdk.Error) { store := ctx.KVStore(keeper.storeKey) bz := store.Get(KeyNextProposalID) if bz == nil { - return -1, ErrInvalidGenesis(keeper.codespace, "InitialProposalID never set") + return 0, ErrInvalidGenesis(keeper.codespace, "InitialProposalID never set") } - keeper.cdc.MustUnmarshalBinary(bz, &proposalID) - bz = keeper.cdc.MustMarshalBinary(proposalID + 1) + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID) + bz = keeper.cdc.MustMarshalBinaryLengthPrefixed(proposalID + 1) store.Set(KeyNextProposalID, bz) return proposalID, nil } +// Peeks the next available ProposalID without incrementing it +func (keeper Keeper) peekCurrentProposalID(ctx sdk.Context) (proposalID uint64, err sdk.Error) { + store := ctx.KVStore(keeper.storeKey) + bz := store.Get(KeyNextProposalID) + if bz == nil { + return 0, ErrInvalidGenesis(keeper.codespace, "InitialProposalID never set") + } + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID) + return proposalID, nil +} + func (keeper Keeper) activateVotingPeriod(ctx sdk.Context, proposal Proposal) { - proposal.SetVotingStartBlock(ctx.BlockHeight()) + proposal.SetVotingStartTime(ctx.BlockHeader().Time) + votingPeriod := govparams.GetVotingProcedure(ctx).VotingPeriod + proposal.SetVotingEndTime(proposal.GetVotingStartTime().Add(votingPeriod)) proposal.SetStatus(StatusVotingPeriod) keeper.SetProposal(ctx, proposal) - keeper.ActiveProposalQueuePush(ctx, proposal) + + keeper.RemoveFromInactiveProposalQueue(ctx, proposal.GetDepositEndTime(), proposal.GetProposalID()) + keeper.InsertActiveProposalQueue(ctx, proposal.GetVotingEndTime(), proposal.GetProposalID()) } // ===================================================== // Votes // Adds a vote on a specific proposal -func (keeper Keeper) AddVote(ctx sdk.Context, proposalID int64, voterAddr sdk.AccAddress, option VoteOption) sdk.Error { +func (keeper Keeper) AddVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress, option VoteOption) sdk.Error { proposal := keeper.GetProposal(ctx, proposalID) if proposal == nil { return ErrUnknownProposal(keeper.codespace, proposalID) @@ -233,30 +317,30 @@ func (keeper Keeper) AddVote(ctx sdk.Context, proposalID int64, voterAddr sdk.Ac } // Gets the vote of a specific voter on a specific proposal -func (keeper Keeper) GetVote(ctx sdk.Context, proposalID int64, voterAddr sdk.AccAddress) (Vote, bool) { +func (keeper Keeper) GetVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress) (Vote, bool) { store := ctx.KVStore(keeper.storeKey) bz := store.Get(KeyVote(proposalID, voterAddr)) if bz == nil { return Vote{}, false } var vote Vote - keeper.cdc.MustUnmarshalBinary(bz, &vote) + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &vote) return vote, true } -func (keeper Keeper) setVote(ctx sdk.Context, proposalID int64, voterAddr sdk.AccAddress, vote Vote) { +func (keeper Keeper) setVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress, vote Vote) { store := ctx.KVStore(keeper.storeKey) - bz := keeper.cdc.MustMarshalBinary(vote) + bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(vote) store.Set(KeyVote(proposalID, voterAddr), bz) } // Gets all the votes on a specific proposal -func (keeper Keeper) GetVotes(ctx sdk.Context, proposalID int64) sdk.Iterator { +func (keeper Keeper) GetVotes(ctx sdk.Context, proposalID uint64) sdk.Iterator { store := ctx.KVStore(keeper.storeKey) return sdk.KVStorePrefixIterator(store, KeyVotesSubspace(proposalID)) } -func (keeper Keeper) deleteVote(ctx sdk.Context, proposalID int64, voterAddr sdk.AccAddress) { +func (keeper Keeper) deleteVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress) { store := ctx.KVStore(keeper.storeKey) store.Delete(KeyVote(proposalID, voterAddr)) } @@ -264,27 +348,27 @@ func (keeper Keeper) deleteVote(ctx sdk.Context, proposalID int64, voterAddr sdk // ===================================================== // Deposits -// Gets the deposit of a specific depositer on a specific proposal -func (keeper Keeper) GetDeposit(ctx sdk.Context, proposalID int64, depositerAddr sdk.AccAddress) (Deposit, bool) { +// Gets the deposit of a specific depositor on a specific proposal +func (keeper Keeper) GetDeposit(ctx sdk.Context, proposalID uint64, depositorAddr sdk.AccAddress) (Deposit, bool) { store := ctx.KVStore(keeper.storeKey) - bz := store.Get(KeyDeposit(proposalID, depositerAddr)) + bz := store.Get(KeyDeposit(proposalID, depositorAddr)) if bz == nil { return Deposit{}, false } var deposit Deposit - keeper.cdc.MustUnmarshalBinary(bz, &deposit) + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &deposit) return deposit, true } -func (keeper Keeper) setDeposit(ctx sdk.Context, proposalID int64, depositerAddr sdk.AccAddress, deposit Deposit) { +func (keeper Keeper) setDeposit(ctx sdk.Context, proposalID uint64, depositorAddr sdk.AccAddress, deposit Deposit) { store := ctx.KVStore(keeper.storeKey) - bz := keeper.cdc.MustMarshalBinary(deposit) - store.Set(KeyDeposit(proposalID, depositerAddr), bz) + bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(deposit) + store.Set(KeyDeposit(proposalID, depositorAddr), bz) } -// Adds or updates a deposit of a specific depositer on a specific proposal +// Adds or updates a deposit of a specific depositor on a specific proposal // Activates voting period when appropriate -func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID int64, depositerAddr sdk.AccAddress, depositAmount sdk.Coins) (sdk.Error, bool) { +func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID uint64, depositorAddr sdk.AccAddress, depositAmount sdk.Coins) (sdk.Error, bool) { // Checks to see if proposal exists proposal := keeper.GetProposal(ctx, proposalID) if proposal == nil { @@ -296,8 +380,8 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID int64, depositerAddr return ErrAlreadyFinishedProposal(keeper.codespace, proposalID), false } - // Subtract coins from depositer's account - _, _, err := keeper.ck.SubtractCoins(ctx, depositerAddr, depositAmount) + // Send coins from depositor's account to DepositedCoinsAccAddr account + _, err := keeper.ck.SendCoins(ctx, depositorAddr, DepositedCoinsAccAddr, depositAmount) if err != nil { return err, false } @@ -309,40 +393,40 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID int64, depositerAddr // Check if deposit tipped proposal into voting period // Active voting period if so activatedVotingPeriod := false - if proposal.GetStatus() == StatusDepositPeriod && proposal.GetTotalDeposit().IsGTE(govparams.GetDepositProcedure(ctx).MinDeposit) { + if proposal.GetStatus() == StatusDepositPeriod && proposal.GetTotalDeposit().IsAllGTE(govparams.GetDepositProcedure(ctx).MinDeposit) { keeper.activateVotingPeriod(ctx, proposal) activatedVotingPeriod = true } // Add or update deposit object - currDeposit, found := keeper.GetDeposit(ctx, proposalID, depositerAddr) + currDeposit, found := keeper.GetDeposit(ctx, proposalID, depositorAddr) if !found { - newDeposit := Deposit{depositerAddr, proposalID, depositAmount} - keeper.setDeposit(ctx, proposalID, depositerAddr, newDeposit) + newDeposit := Deposit{depositorAddr, proposalID, depositAmount} + keeper.setDeposit(ctx, proposalID, depositorAddr, newDeposit) } else { currDeposit.Amount = currDeposit.Amount.Plus(depositAmount) - keeper.setDeposit(ctx, proposalID, depositerAddr, currDeposit) + keeper.setDeposit(ctx, proposalID, depositorAddr, currDeposit) } return nil, activatedVotingPeriod } // Gets all the deposits on a specific proposal -func (keeper Keeper) GetDeposits(ctx sdk.Context, proposalID int64) sdk.Iterator { +func (keeper Keeper) GetDeposits(ctx sdk.Context, proposalID uint64) sdk.Iterator { store := ctx.KVStore(keeper.storeKey) return sdk.KVStorePrefixIterator(store, KeyDepositsSubspace(proposalID)) } // Returns and deletes all the deposits on a specific proposal -func (keeper Keeper) RefundDeposits(ctx sdk.Context, proposalID int64) { +func (keeper Keeper) RefundDeposits(ctx sdk.Context, proposalID uint64) { store := ctx.KVStore(keeper.storeKey) depositsIterator := keeper.GetDeposits(ctx, proposalID) for ; depositsIterator.Valid(); depositsIterator.Next() { deposit := &Deposit{} - keeper.cdc.MustUnmarshalBinary(depositsIterator.Value(), deposit) + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), deposit) - _, _, err := keeper.ck.AddCoins(ctx, deposit.Depositer, deposit.Amount) + _, err := keeper.ck.SendCoins(ctx, DepositedCoinsAccAddr, deposit.Depositor, deposit.Amount) if err != nil { panic("should not happen") } @@ -354,11 +438,19 @@ func (keeper Keeper) RefundDeposits(ctx sdk.Context, proposalID int64) { } // Deletes all the deposits on a specific proposal without refunding them -func (keeper Keeper) DeleteDeposits(ctx sdk.Context, proposalID int64) { +func (keeper Keeper) DeleteDeposits(ctx sdk.Context, proposalID uint64) { store := ctx.KVStore(keeper.storeKey) depositsIterator := keeper.GetDeposits(ctx, proposalID) for ; depositsIterator.Valid(); depositsIterator.Next() { + deposit := &Deposit{} + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), deposit) + + _, err := keeper.ck.SendCoins(ctx, DepositedCoinsAccAddr, BurnedDepositCoinsAccAddr, deposit.Amount) + if err != nil { + panic("should not happen") + } + store.Delete(depositsIterator.Key()) } @@ -368,93 +460,40 @@ func (keeper Keeper) DeleteDeposits(ctx sdk.Context, proposalID int64) { // ===================================================== // ProposalQueues -func (keeper Keeper) getActiveProposalQueue(ctx sdk.Context) ProposalQueue { +// Returns an iterator for all the proposals in the Active Queue that expire by endTime +func (keeper Keeper) ActiveProposalQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator { store := ctx.KVStore(keeper.storeKey) - bz := store.Get(KeyActiveProposalQueue) - if bz == nil { - return nil - } - - var proposalQueue ProposalQueue - keeper.cdc.MustUnmarshalBinary(bz, &proposalQueue) - - return proposalQueue + return store.Iterator(PrefixActiveProposalQueue, sdk.PrefixEndBytes(PrefixActiveProposalQueueTime(endTime))) } -func (keeper Keeper) setActiveProposalQueue(ctx sdk.Context, proposalQueue ProposalQueue) { +// Inserts a ProposalID into the active proposal queue at endTime +func (keeper Keeper) InsertActiveProposalQueue(ctx sdk.Context, endTime time.Time, proposalID uint64) { store := ctx.KVStore(keeper.storeKey) - bz := keeper.cdc.MustMarshalBinary(proposalQueue) - store.Set(KeyActiveProposalQueue, bz) + bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(proposalID) + store.Set(KeyActiveProposalQueueProposal(endTime, proposalID), bz) } -// Return the Proposal at the front of the ProposalQueue -func (keeper Keeper) ActiveProposalQueuePeek(ctx sdk.Context) Proposal { - proposalQueue := keeper.getActiveProposalQueue(ctx) - if len(proposalQueue) == 0 { - return nil - } - return keeper.GetProposal(ctx, proposalQueue[0]) -} - -// Remove and return a Proposal from the front of the ProposalQueue -func (keeper Keeper) ActiveProposalQueuePop(ctx sdk.Context) Proposal { - proposalQueue := keeper.getActiveProposalQueue(ctx) - if len(proposalQueue) == 0 { - return nil - } - frontElement, proposalQueue := proposalQueue[0], proposalQueue[1:] - keeper.setActiveProposalQueue(ctx, proposalQueue) - return keeper.GetProposal(ctx, frontElement) -} - -// Add a proposalID to the back of the ProposalQueue -func (keeper Keeper) ActiveProposalQueuePush(ctx sdk.Context, proposal Proposal) { - proposalQueue := append(keeper.getActiveProposalQueue(ctx), proposal.GetProposalID()) - keeper.setActiveProposalQueue(ctx, proposalQueue) -} - -func (keeper Keeper) getInactiveProposalQueue(ctx sdk.Context) ProposalQueue { +// removes a proposalID from the Active Proposal Queue +func (keeper Keeper) RemoveFromActiveProposalQueue(ctx sdk.Context, endTime time.Time, proposalID uint64) { store := ctx.KVStore(keeper.storeKey) - bz := store.Get(KeyInactiveProposalQueue) - if bz == nil { - return nil - } - - var proposalQueue ProposalQueue - - keeper.cdc.MustUnmarshalBinary(bz, &proposalQueue) - - return proposalQueue + store.Delete(KeyActiveProposalQueueProposal(endTime, proposalID)) } -func (keeper Keeper) setInactiveProposalQueue(ctx sdk.Context, proposalQueue ProposalQueue) { +// Returns an iterator for all the proposals in the Inactive Queue that expire by endTime +func (keeper Keeper) InactiveProposalQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator { store := ctx.KVStore(keeper.storeKey) - bz := keeper.cdc.MustMarshalBinary(proposalQueue) - store.Set(KeyInactiveProposalQueue, bz) -} - -// Return the Proposal at the front of the ProposalQueue -func (keeper Keeper) InactiveProposalQueuePeek(ctx sdk.Context) Proposal { - proposalQueue := keeper.getInactiveProposalQueue(ctx) - if len(proposalQueue) == 0 { - return nil - } - return keeper.GetProposal(ctx, proposalQueue[0]) + return store.Iterator(PrefixInactiveProposalQueue, sdk.PrefixEndBytes(PrefixInactiveProposalQueueTime(endTime))) } -// Remove and return a Proposal from the front of the ProposalQueue -func (keeper Keeper) InactiveProposalQueuePop(ctx sdk.Context) Proposal { - proposalQueue := keeper.getInactiveProposalQueue(ctx) - if len(proposalQueue) == 0 { - return nil - } - frontElement, proposalQueue := proposalQueue[0], proposalQueue[1:] - keeper.setInactiveProposalQueue(ctx, proposalQueue) - return keeper.GetProposal(ctx, frontElement) +// Inserts a ProposalID into the inactive proposal queue at endTime +func (keeper Keeper) InsertInactiveProposalQueue(ctx sdk.Context, endTime time.Time, proposalID uint64) { + store := ctx.KVStore(keeper.storeKey) + bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(proposalID) + store.Set(KeyInactiveProposalQueueProposal(endTime, proposalID), bz) } -// Add a proposalID to the back of the ProposalQueue -func (keeper Keeper) InactiveProposalQueuePush(ctx sdk.Context, proposal Proposal) { - proposalQueue := append(keeper.getInactiveProposalQueue(ctx), proposal.GetProposalID()) - keeper.setInactiveProposalQueue(ctx, proposalQueue) +// removes a proposalID from the Inactive Proposal Queue +func (keeper Keeper) RemoveFromInactiveProposalQueue(ctx sdk.Context, endTime time.Time, proposalID uint64) { + store := ctx.KVStore(keeper.storeKey) + store.Delete(KeyInactiveProposalQueueProposal(endTime, proposalID)) } diff --git a/modules/gov/keeper_keys.go b/modules/gov/keeper_keys.go index 7b1bf43f2..b1a5d7761 100644 --- a/modules/gov/keeper_keys.go +++ b/modules/gov/keeper_keys.go @@ -1,7 +1,9 @@ package gov import ( + "bytes" "fmt" + "time" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -10,32 +12,68 @@ import ( // Key for getting a the next available proposalID from the store var ( - KeyNextProposalID = []byte("newProposalID") - KeyActiveProposalQueue = []byte("activeProposalQueue") - KeyInactiveProposalQueue = []byte("inactiveProposalQueue") + KeyDelimiter = []byte(":") + + KeyNextProposalID = []byte("newProposalID") + PrefixActiveProposalQueue = []byte("activeProposalQueue") + PrefixInactiveProposalQueue = []byte("inactiveProposalQueue") ) // Key for getting a specific proposal from the store -func KeyProposal(proposalID int64) []byte { +func KeyProposal(proposalID uint64) []byte { return []byte(fmt.Sprintf("proposals:%d", proposalID)) } // Key for getting a specific deposit from the store -func KeyDeposit(proposalID int64, depositerAddr sdk.AccAddress) []byte { - return []byte(fmt.Sprintf("deposits:%d:%d", proposalID, depositerAddr)) +func KeyDeposit(proposalID uint64, depositorAddr sdk.AccAddress) []byte { + return []byte(fmt.Sprintf("deposits:%d:%d", proposalID, depositorAddr)) } // Key for getting a specific vote from the store -func KeyVote(proposalID int64, voterAddr sdk.AccAddress) []byte { +func KeyVote(proposalID uint64, voterAddr sdk.AccAddress) []byte { return []byte(fmt.Sprintf("votes:%d:%d", proposalID, voterAddr)) } // Key for getting all deposits on a proposal from the store -func KeyDepositsSubspace(proposalID int64) []byte { +func KeyDepositsSubspace(proposalID uint64) []byte { return []byte(fmt.Sprintf("deposits:%d:", proposalID)) } // Key for getting all votes on a proposal from the store -func KeyVotesSubspace(proposalID int64) []byte { +func KeyVotesSubspace(proposalID uint64) []byte { return []byte(fmt.Sprintf("votes:%d:", proposalID)) } + +// Returns the key for a proposalID in the activeProposalQueue +func PrefixActiveProposalQueueTime(endTime time.Time) []byte { + return bytes.Join([][]byte{ + PrefixActiveProposalQueue, + sdk.FormatTimeBytes(endTime), + }, KeyDelimiter) +} + +// Returns the key for a proposalID in the activeProposalQueue +func KeyActiveProposalQueueProposal(endTime time.Time, proposalID uint64) []byte { + return bytes.Join([][]byte{ + PrefixActiveProposalQueue, + sdk.FormatTimeBytes(endTime), + sdk.Uint64ToBigEndian(proposalID), + }, KeyDelimiter) +} + +// Returns the key for a proposalID in the activeProposalQueue +func PrefixInactiveProposalQueueTime(endTime time.Time) []byte { + return bytes.Join([][]byte{ + PrefixInactiveProposalQueue, + sdk.FormatTimeBytes(endTime), + }, KeyDelimiter) +} + +// Returns the key for a proposalID in the activeProposalQueue +func KeyInactiveProposalQueueProposal(endTime time.Time, proposalID uint64) []byte { + return bytes.Join([][]byte{ + PrefixInactiveProposalQueue, + sdk.FormatTimeBytes(endTime), + sdk.Uint64ToBigEndian(proposalID), + }, KeyDelimiter) +} diff --git a/modules/gov/keeper_test.go b/modules/gov/keeper_test.go deleted file mode 100644 index 0454554f9..000000000 --- a/modules/gov/keeper_test.go +++ /dev/null @@ -1,248 +0,0 @@ -package gov - -import ( - "testing" - - "github.com/stretchr/testify/require" - - abci "github.com/tendermint/tendermint/abci/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/irisnet/irishub/types" - "fmt" -) - -func TestGetSetProposal(t *testing.T) { - mapp, keeper, _, _, _, _ := getMockApp(t, 0) - mapp.BeginBlock(abci.RequestBeginBlock{}) - ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - - proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) - proposalID := proposal.GetProposalID() - keeper.SetProposal(ctx, proposal) - - gotProposal := keeper.GetProposal(ctx, proposalID) - require.True(t, ProposalEqual(proposal, gotProposal)) -} - -func TestIncrementProposalNumber(t *testing.T) { - mapp, keeper, _, _, _, _ := getMockApp(t, 0) - mapp.BeginBlock(abci.RequestBeginBlock{}) - ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - - keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) - keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) - keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) - keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) - keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) - proposal6 := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) - - require.Equal(t, int64(6), proposal6.GetProposalID()) -} - -func TestActivateVotingPeriod(t *testing.T) { - mapp, keeper, _, _, _, _ := getMockApp(t, 0) - mapp.BeginBlock(abci.RequestBeginBlock{}) - ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - - proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) - - require.Equal(t, int64(-1), proposal.GetVotingStartBlock()) - require.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) - - keeper.activateVotingPeriod(ctx, proposal) - - require.Equal(t, proposal.GetVotingStartBlock(), ctx.BlockHeight()) - require.Equal(t, proposal.GetProposalID(), keeper.ActiveProposalQueuePeek(ctx).GetProposalID()) -} - -func TestDeposits(t *testing.T) { - mapp, keeper, _, addrs, _, _ := getMockApp(t, 2) - SortAddresses(addrs) - mapp.BeginBlock(abci.RequestBeginBlock{}) - ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - - proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) - proposalID := proposal.GetProposalID() - - fourSteak, _ := types.NewDefaultCoinType("iris").ConvertToMinCoin(fmt.Sprintf("%d%s", 4, "iris")) - fiveSteak, _ := types.NewDefaultCoinType("iris").ConvertToMinCoin(fmt.Sprintf("%d%s", 5, "iris")) - thousand, _ := types.NewDefaultCoinType("iris").ConvertToMinCoin(fmt.Sprintf("%d%s", 1042, "iris")) - thousandSteak, _ := types.NewDefaultCoinType("iris").ConvertToMinCoin(fmt.Sprintf("%d%s", 1000, "iris")) - - addr0Initial := keeper.ck.GetCoins(ctx, addrs[0]) - addr1Initial := keeper.ck.GetCoins(ctx, addrs[1]) - - require.Equal(t, sdk.Coins{thousand}, addr0Initial) - require.True(t, proposal.GetTotalDeposit().IsEqual(sdk.Coins{})) - - // Check no deposits at beginning - deposit, found := keeper.GetDeposit(ctx, proposalID, addrs[1]) - require.False(t, found) - require.Equal(t, keeper.GetProposal(ctx, proposalID).GetVotingStartBlock(), int64(-1)) - require.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) - - // Check first deposit - err, votingStarted := keeper.AddDeposit(ctx, proposalID, addrs[0], sdk.Coins{fourSteak}) - require.Nil(t, err) - require.False(t, votingStarted) - deposit, found = keeper.GetDeposit(ctx, proposalID, addrs[0]) - require.True(t, found) - require.Equal(t, fourSteak.String(), deposit.Amount.String()) - require.Equal(t, addrs[0], deposit.Depositer) - require.Equal(t, fourSteak.String(), keeper.GetProposal(ctx, proposalID).GetTotalDeposit().String()) - require.Equal(t, addr0Initial.Minus(sdk.Coins{fourSteak}), keeper.ck.GetCoins(ctx, addrs[0])) - - // Check a second deposit from same address - err, votingStarted = keeper.AddDeposit(ctx, proposalID, addrs[0], sdk.Coins{fiveSteak}) - require.Nil(t, err) - require.False(t, votingStarted) - deposit, found = keeper.GetDeposit(ctx, proposalID, addrs[0]) - require.True(t, found) - require.Equal(t, fourSteak.Plus(fiveSteak).String(), deposit.Amount.String()) - require.Equal(t, addrs[0], deposit.Depositer) - require.Equal(t, fourSteak.Plus(fiveSteak).String(), keeper.GetProposal(ctx, proposalID).GetTotalDeposit().String()) - require.Equal(t, addr0Initial.Minus(sdk.Coins{fourSteak}).Minus(sdk.Coins{fiveSteak}), keeper.ck.GetCoins(ctx, addrs[0])) - - // Check third deposit from a new address - err, votingStarted = keeper.AddDeposit(ctx, proposalID, addrs[1], sdk.Coins{thousandSteak}) - require.Nil(t, err) - require.True(t, votingStarted) - deposit, found = keeper.GetDeposit(ctx, proposalID, addrs[1]) - require.True(t, found) - require.Equal(t, addrs[1], deposit.Depositer) - require.Equal(t, fourSteak.Plus(fiveSteak).Plus(thousandSteak).String(), keeper.GetProposal(ctx, proposalID).GetTotalDeposit().String()) - require.Equal(t, addr1Initial.Minus(sdk.Coins{thousandSteak}).String(), keeper.ck.GetCoins(ctx, addrs[1]).String()) - - // Check that proposal moved to voting period - require.Equal(t, ctx.BlockHeight(), keeper.GetProposal(ctx, proposalID).GetVotingStartBlock()) - require.NotNil(t, keeper.ActiveProposalQueuePeek(ctx)) - require.Equal(t, proposalID, keeper.ActiveProposalQueuePeek(ctx).GetProposalID()) - - // Test deposit iterator - depositsIterator := keeper.GetDeposits(ctx, proposalID) - require.True(t, depositsIterator.Valid()) - keeper.cdc.MustUnmarshalBinary(depositsIterator.Value(), &deposit) - require.Equal(t, addrs[0], deposit.Depositer) - require.Equal(t, fourSteak.Plus(fiveSteak).String(), deposit.Amount.String()) - depositsIterator.Next() - keeper.cdc.MustUnmarshalBinary(depositsIterator.Value(), &deposit) - require.Equal(t, addrs[1], deposit.Depositer) - require.Equal(t, thousandSteak.String(), deposit.Amount.String()) - depositsIterator.Next() - require.False(t, depositsIterator.Valid()) - - // Test Refund Deposits - deposit, found = keeper.GetDeposit(ctx, proposalID, addrs[1]) - require.True(t, found) - require.Equal(t, thousandSteak.String(), deposit.Amount.String()) - keeper.RefundDeposits(ctx, proposalID) - deposit, found = keeper.GetDeposit(ctx, proposalID, addrs[1]) - require.False(t, found) - require.Equal(t, addr0Initial, keeper.ck.GetCoins(ctx, addrs[0])) - require.Equal(t, addr1Initial, keeper.ck.GetCoins(ctx, addrs[1])) - -} - -func TestVotes(t *testing.T) { - mapp, keeper, _, addrs, _, _ := getMockApp(t, 2) - SortAddresses(addrs) - mapp.BeginBlock(abci.RequestBeginBlock{}) - ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - - proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) - proposalID := proposal.GetProposalID() - - proposal.SetStatus(StatusVotingPeriod) - keeper.SetProposal(ctx, proposal) - - // Test first vote - keeper.AddVote(ctx, proposalID, addrs[0], OptionAbstain) - vote, found := keeper.GetVote(ctx, proposalID, addrs[0]) - require.True(t, found) - require.Equal(t, addrs[0], vote.Voter) - require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, OptionAbstain, vote.Option) - - // Test change of vote - keeper.AddVote(ctx, proposalID, addrs[0], OptionYes) - vote, found = keeper.GetVote(ctx, proposalID, addrs[0]) - require.True(t, found) - require.Equal(t, addrs[0], vote.Voter) - require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, OptionYes, vote.Option) - - // Test second vote - keeper.AddVote(ctx, proposalID, addrs[1], OptionNoWithVeto) - vote, found = keeper.GetVote(ctx, proposalID, addrs[1]) - require.True(t, found) - require.Equal(t, addrs[1], vote.Voter) - require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, OptionNoWithVeto, vote.Option) - - // Test vote iterator - votesIterator := keeper.GetVotes(ctx, proposalID) - require.True(t, votesIterator.Valid()) - keeper.cdc.MustUnmarshalBinary(votesIterator.Value(), &vote) - require.True(t, votesIterator.Valid()) - require.Equal(t, addrs[0], vote.Voter) - require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, OptionYes, vote.Option) - votesIterator.Next() - require.True(t, votesIterator.Valid()) - keeper.cdc.MustUnmarshalBinary(votesIterator.Value(), &vote) - require.True(t, votesIterator.Valid()) - require.Equal(t, addrs[1], vote.Voter) - require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, OptionNoWithVeto, vote.Option) - votesIterator.Next() - require.False(t, votesIterator.Valid()) -} - -func TestProposalQueues(t *testing.T) { - mapp, keeper, _, _, _, _ := getMockApp(t, 0) - mapp.BeginBlock(abci.RequestBeginBlock{}) - ctx := mapp.BaseApp.NewContext(false, abci.Header{}) - mapp.InitChainer(ctx, abci.RequestInitChain{}) - - require.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) - require.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) - - // create test proposals - proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) - proposal2 := keeper.NewTextProposal(ctx, "Test2", "description", ProposalTypeText) - proposal3 := keeper.NewTextProposal(ctx, "Test3", "description", ProposalTypeText) - proposal4 := keeper.NewTextProposal(ctx, "Test4", "description", ProposalTypeText) - - // test pushing to inactive proposal queue - keeper.InactiveProposalQueuePush(ctx, proposal) - keeper.InactiveProposalQueuePush(ctx, proposal2) - keeper.InactiveProposalQueuePush(ctx, proposal3) - keeper.InactiveProposalQueuePush(ctx, proposal4) - - // test peeking and popping from inactive proposal queue - require.Equal(t, keeper.InactiveProposalQueuePeek(ctx).GetProposalID(), proposal.GetProposalID()) - require.Equal(t, keeper.InactiveProposalQueuePop(ctx).GetProposalID(), proposal.GetProposalID()) - require.Equal(t, keeper.InactiveProposalQueuePeek(ctx).GetProposalID(), proposal2.GetProposalID()) - require.Equal(t, keeper.InactiveProposalQueuePop(ctx).GetProposalID(), proposal2.GetProposalID()) - require.Equal(t, keeper.InactiveProposalQueuePeek(ctx).GetProposalID(), proposal3.GetProposalID()) - require.Equal(t, keeper.InactiveProposalQueuePop(ctx).GetProposalID(), proposal3.GetProposalID()) - require.Equal(t, keeper.InactiveProposalQueuePeek(ctx).GetProposalID(), proposal4.GetProposalID()) - require.Equal(t, keeper.InactiveProposalQueuePop(ctx).GetProposalID(), proposal4.GetProposalID()) - - // test pushing to active proposal queue - keeper.ActiveProposalQueuePush(ctx, proposal) - keeper.ActiveProposalQueuePush(ctx, proposal2) - keeper.ActiveProposalQueuePush(ctx, proposal3) - keeper.ActiveProposalQueuePush(ctx, proposal4) - - // test peeking and popping from active proposal queue - require.Equal(t, keeper.ActiveProposalQueuePeek(ctx).GetProposalID(), proposal.GetProposalID()) - require.Equal(t, keeper.ActiveProposalQueuePop(ctx).GetProposalID(), proposal.GetProposalID()) - require.Equal(t, keeper.ActiveProposalQueuePeek(ctx).GetProposalID(), proposal2.GetProposalID()) - require.Equal(t, keeper.ActiveProposalQueuePop(ctx).GetProposalID(), proposal2.GetProposalID()) - require.Equal(t, keeper.ActiveProposalQueuePeek(ctx).GetProposalID(), proposal3.GetProposalID()) - require.Equal(t, keeper.ActiveProposalQueuePop(ctx).GetProposalID(), proposal3.GetProposalID()) - require.Equal(t, keeper.ActiveProposalQueuePeek(ctx).GetProposalID(), proposal4.GetProposalID()) - require.Equal(t, keeper.ActiveProposalQueuePop(ctx).GetProposalID(), proposal4.GetProposalID()) -} diff --git a/modules/gov/msgs.go b/modules/gov/msgs.go index 2203a93fa..d06d5d766 100644 --- a/modules/gov/msgs.go +++ b/modules/gov/msgs.go @@ -4,21 +4,25 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/irisnet/irishub/modules/iparam" + "github.com/irisnet/irishub/iparam" ) // name to idetify transaction types -const MsgType = "gov" +const MsgRoute = "gov" + +var _, _, _ sdk.Msg = MsgSubmitProposal{}, MsgDeposit{}, MsgVote{} //----------------------------------------------------------- // MsgSubmitProposal 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. + 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} + Proposer sdk.AccAddress `json:"proposer"` // Address of the proposer + InitialDeposit sdk.Coins `json:"initial_deposit"` // Initial deposit paid by sender. Must be strictly positive. + //////////////////// iris begin /////////////////////////// Param Param + //////////////////// iris end ///////////////////////////// } func NewMsgSubmitProposal(title string, description string, proposalType ProposalKind, proposer sdk.AccAddress, initialDeposit sdk.Coins, param Param) MsgSubmitProposal { @@ -28,12 +32,15 @@ func NewMsgSubmitProposal(title string, description string, proposalType Proposa ProposalType: proposalType, Proposer: proposer, InitialDeposit: initialDeposit, + //////////////////// iris begin /////////////////////////// Param: param, + //////////////////// iris end ///////////////////////////// } } -// Implements Msg. -func (msg MsgSubmitProposal) Type() string { return MsgType } +//nolint +func (msg MsgSubmitProposal) Route() string { return MsgRoute } +func (msg MsgSubmitProposal) Type() string { return "submit_proposal" } // Implements Msg. func (msg MsgSubmitProposal) ValidateBasic() sdk.Error { @@ -55,7 +62,7 @@ func (msg MsgSubmitProposal) ValidateBasic() sdk.Error { if !msg.InitialDeposit.IsNotNegative() { return sdk.ErrInvalidCoins(msg.InitialDeposit.String()) } - + //////////////////// iris begin /////////////////////////// if msg.ProposalType == ProposalTypeParameterChange { if msg.Param.Op != Update && msg.Param.Op != Insert { @@ -69,7 +76,7 @@ func (msg MsgSubmitProposal) ValidateBasic() sdk.Error { } } - + //////////////////// iris end ///////////////////////////// return nil } @@ -99,26 +106,28 @@ func (msg MsgSubmitProposal) GetSigners() []sdk.AccAddress { //----------------------------------------------------------- // MsgDeposit 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 + ProposalID uint64 `json:"proposal_id"` // ID of the proposal + Depositor sdk.AccAddress `json:"depositor"` // Address of the depositor + Amount sdk.Coins `json:"amount"` // Coins to add to the proposal's deposit } -func NewMsgDeposit(depositer sdk.AccAddress, proposalID int64, amount sdk.Coins) MsgDeposit { +func NewMsgDeposit(depositor sdk.AccAddress, proposalID uint64, amount sdk.Coins) MsgDeposit { return MsgDeposit{ ProposalID: proposalID, - Depositer: depositer, + Depositor: depositor, Amount: amount, } } // Implements Msg. -func (msg MsgDeposit) Type() string { return MsgType } +// nolint +func (msg MsgDeposit) Route() string { return MsgRoute } +func (msg MsgDeposit) Type() string { return "deposit" } // Implements Msg. func (msg MsgDeposit) ValidateBasic() sdk.Error { - if len(msg.Depositer) == 0 { - return sdk.ErrInvalidAddress(msg.Depositer.String()) + if len(msg.Depositor) == 0 { + return sdk.ErrInvalidAddress(msg.Depositor.String()) } if !msg.Amount.IsValid() { return sdk.ErrInvalidCoins(msg.Amount.String()) @@ -133,7 +142,7 @@ func (msg MsgDeposit) ValidateBasic() sdk.Error { } func (msg MsgDeposit) String() string { - return fmt.Sprintf("MsgDeposit{%s=>%v: %v}", msg.Depositer, msg.ProposalID, msg.Amount) + return fmt.Sprintf("MsgDeposit{%s=>%v: %v}", msg.Depositor, msg.ProposalID, msg.Amount) } // Implements Msg. @@ -152,18 +161,18 @@ func (msg MsgDeposit) GetSignBytes() []byte { // Implements Msg. func (msg MsgDeposit) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Depositer} + return []sdk.AccAddress{msg.Depositor} } //----------------------------------------------------------- // MsgVote 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 + ProposalID uint64 `json:"proposal_id"` // ID of the proposal + Voter sdk.AccAddress `json:"voter"` // address of the voter + Option VoteOption `json:"option"` // option from OptionSet chosen by the voter } -func NewMsgVote(voter sdk.AccAddress, proposalID int64, option VoteOption) MsgVote { +func NewMsgVote(voter sdk.AccAddress, proposalID uint64, option VoteOption) MsgVote { return MsgVote{ ProposalID: proposalID, Voter: voter, @@ -172,7 +181,9 @@ func NewMsgVote(voter sdk.AccAddress, proposalID int64, option VoteOption) MsgVo } // Implements Msg. -func (msg MsgVote) Type() string { return MsgType } +// nolint +func (msg MsgVote) Route() string { return MsgRoute } +func (msg MsgVote) Type() string { return "vote" } // Implements Msg. func (msg MsgVote) ValidateBasic() sdk.Error { diff --git a/modules/gov/msgs_test.go b/modules/gov/msgs_test.go deleted file mode 100644 index 453637366..000000000 --- a/modules/gov/msgs_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package gov - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/mock" -) - -var ( - coinsPos = sdk.Coins{sdk.NewInt64Coin("steak", 1000)} - coinsZero = sdk.Coins{} - coinsNeg = sdk.Coins{sdk.NewInt64Coin("steak", -10000)} - coinsPosNotAtoms = sdk.Coins{sdk.NewInt64Coin("foo", 10000)} - coinsMulti = sdk.Coins{sdk.NewInt64Coin("foo", 10000), sdk.NewInt64Coin("steak", 1000)} - - paramNil = Param{ - Key: "", - Value: "", - Op: "", - } - - param = Param{ - Key: "Gov/gov/DepositProcedure", - Value: "{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":1440}", - Op: "update", - } -) - -// test ValidateBasic for MsgCreateValidator -func TestMsgSubmitProposal(t *testing.T) { - _, _, _, addrs, _, _ := getMockApp(t, 1) - - tests := []struct { - title, description string - proposalType ProposalKind - proposerAddr sdk.AccAddress - initialDeposit sdk.Coins - param Param - expectPass bool - }{ - {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsPos, param, true}, - {"", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsPos, paramNil, false}, - {"Test Proposal", "", ProposalTypeText, addrs[0], coinsPos, paramNil, false}, - {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeParameterChange, addrs[0], coinsPos, param, true}, - {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeSoftwareUpgrade, addrs[0], coinsPos, param, true}, - {"Test Proposal", "the purpose of this proposal is to test", 0x05, addrs[0], coinsPos, paramNil, false}, - {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, sdk.AccAddress{}, coinsPos, paramNil, false}, - {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsZero, param, true}, - {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsNeg, paramNil, false}, - {"Test Proposal", "the purpose of this proposal is to test", ProposalTypeText, addrs[0], coinsMulti, param, true}, - } - - for i, tc := range tests { - msg := NewMsgSubmitProposal(tc.title, tc.description, tc.proposalType, tc.proposerAddr, tc.initialDeposit, tc.param) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test: %v", i) - } - } -} - -// test ValidateBasic for MsgDeposit -func TestMsgDeposit(t *testing.T) { - _, addrs, _, _ := mock.CreateGenAccounts(1, sdk.Coins{}) - tests := []struct { - proposalID int64 - depositerAddr sdk.AccAddress - depositAmount sdk.Coins - expectPass bool - }{ - {0, addrs[0], coinsPos, true}, - {-1, addrs[0], coinsPos, false}, - {1, sdk.AccAddress{}, coinsPos, false}, - {1, addrs[0], coinsZero, true}, - {1, addrs[0], coinsNeg, false}, - {1, addrs[0], coinsMulti, true}, - } - - for i, tc := range tests { - msg := NewMsgDeposit(tc.depositerAddr, tc.proposalID, tc.depositAmount) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test: %v", i) - } - } -} - -// test ValidateBasic for MsgDeposit -func TestMsgVote(t *testing.T) { - _, addrs, _, _ := mock.CreateGenAccounts(1, sdk.Coins{}) - tests := []struct { - proposalID int64 - voterAddr sdk.AccAddress - option VoteOption - expectPass bool - }{ - {0, addrs[0], OptionYes, true}, - {-1, addrs[0], OptionYes, false}, - {0, sdk.AccAddress{}, OptionYes, false}, - {0, addrs[0], OptionNo, true}, - {0, addrs[0], OptionNoWithVeto, true}, - {0, addrs[0], OptionAbstain, true}, - {0, addrs[0], VoteOption(0x13), false}, - } - - for i, tc := range tests { - msg := NewMsgVote(tc.voterAddr, tc.proposalID, tc.option) - if tc.expectPass { - require.Nil(t, msg.ValidateBasic(), "test: %v", i) - } else { - require.NotNil(t, msg.ValidateBasic(), "test: %v", i) - } - } -} diff --git a/modules/gov/params/gov_params.go b/modules/gov/params/gov_params.go index 6c6f8c80d..c63ac158d 100644 --- a/modules/gov/params/gov_params.go +++ b/modules/gov/params/gov_params.go @@ -4,40 +4,40 @@ import ( "encoding/json" "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/irisnet/irishub/modules/iparam" + "github.com/irisnet/irishub/iparam" "github.com/irisnet/irishub/types" "strconv" + "time" ) var DepositProcedureParameter DepositProcedureParam -const LOWER_BOUND_AMOUNT = 1 -const UPPER_BOUND_AMOUNT = 200 - +const LOWER_BOUND_AMOUNT = 10 +const UPPER_BOUND_AMOUNT = 10000 +const THREE_DAYS = 3*3600*24 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/govDepositProcedure"` + VotingProcedure VotingProcedure `json:"Gov/govVotingProcedure"` + TallyingProcedure TallyingProcedure `json:"Gov/govTallyingProcedure"` } // Procedure around Deposits for governance 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 + MinDeposit sdk.Coins `json:"min_deposit"` // Minimum deposit for a proposal to enter voting period. + MaxDepositPeriod time.Duration `json:"max_deposit_period"` // Maximum period for Atom holders to deposit on a proposal. Initial value: 2 months } type DepositProcedureParam struct { Value DepositProcedure - psetter params.Setter - pgetter params.Getter + paramSpace params.Subspace } -func (param *DepositProcedureParam) GetValueFromRawData(cdc *wire.Codec, res []byte) interface{} { - cdc.MustUnmarshalBinary(res, ¶m.Value) +func (param *DepositProcedureParam) GetValueFromRawData(cdc *codec.Codec, res []byte) interface{} { + cdc.UnmarshalJSON(res, ¶m.Value) return param.Value } @@ -49,28 +49,27 @@ func (param *DepositProcedureParam) InitGenesis(genesisState interface{}) { param.Value = DepositProcedure{ MinDeposit: sdk.Coins{minDeposit}, - MaxDepositPeriod: 1440} + MaxDepositPeriod: time.Duration(172800) * time.Second} } } -func (param *DepositProcedureParam) SetReadWriter(setter params.Setter) { - param.psetter = setter - param.pgetter = setter.Getter +func (param *DepositProcedureParam) SetReadWriter(paramSpace params.Subspace) { + param.paramSpace = paramSpace } -func (param *DepositProcedureParam) GetStoreKey() string { - return "Gov/gov/DepositProcedure" +func (param *DepositProcedureParam) GetStoreKey() []byte { + return []byte("govDepositProcedure") } func (param *DepositProcedureParam) SaveValue(ctx sdk.Context) { - param.psetter.Set(ctx, param.GetStoreKey(), param.Value) + param.paramSpace.Set(ctx, param.GetStoreKey(), param.Value) } func (param *DepositProcedureParam) LoadValue(ctx sdk.Context) bool { - err := param.pgetter.Get(ctx, param.GetStoreKey(), ¶m.Value) - if err != nil { + if param.paramSpace.Has(ctx, param.GetStoreKey()) == false { return false } + param.paramSpace.Get(ctx, param.GetStoreKey(), ¶m.Value) return true } @@ -110,12 +109,12 @@ func (param *DepositProcedureParam) Valid(jsonStr string) sdk.Error { UpperBound, _ := types.NewDefaultCoinType("iris").ConvertToMinCoin(fmt.Sprintf("%d%s", UPPER_BOUND_AMOUNT, "iris")) if param.Value.MinDeposit[0].Amount.LT(LowerBound.Amount) || param.Value.MinDeposit[0].Amount.GT(UpperBound.Amount) { - return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidMinDepositAmount, fmt.Sprintf("MinDepositAmount"+param.Value.MinDeposit[0].String()+" should be larger than 1iris and less than 20000iris")) + return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidMinDepositAmount, fmt.Sprintf("MinDepositAmount"+param.Value.MinDeposit[0].String()+" should be larger than 10iris and less than 10000iris")) } - if param.Value.MaxDepositPeriod < 20 || param.Value.MaxDepositPeriod > 20000 { - return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidDepositPeriod, fmt.Sprintf("MaxDepositPeriod ("+strconv.Itoa(int(param.Value.MaxDepositPeriod))+") should be larger than 20 and less than 20000")) + if param.Value.MaxDepositPeriod.Seconds() < 20 || param.Value.MaxDepositPeriod.Seconds() > THREE_DAYS { + return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidDepositPeriod, fmt.Sprintf("MaxDepositPeriod (%s) should be larger than 20s and less than %ds",strconv.Itoa(int(param.Value.MaxDepositPeriod.Seconds())), THREE_DAYS)) } return nil @@ -129,17 +128,16 @@ var _ iparam.GovParameter = (*VotingProcedureParam)(nil) // Procedure around Voting in governance type VotingProcedure struct { - VotingPeriod int64 `json:"voting_period"` // Length of the voting period. + VotingPeriod time.Duration `json:"voting_period"` // Length of the voting period. } type VotingProcedureParam struct { Value VotingProcedure - psetter params.Setter - pgetter params.Getter + paramSpace params.Subspace } -func (param *VotingProcedureParam) GetValueFromRawData(cdc *wire.Codec, res []byte) interface{} { - cdc.MustUnmarshalBinary(res, ¶m.Value) +func (param *VotingProcedureParam) GetValueFromRawData(cdc *codec.Codec, res []byte) interface{} { + cdc.UnmarshalJSON(res, ¶m.Value) return param.Value } @@ -147,28 +145,27 @@ 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: time.Duration(172800) * time.Second} } } -func (param *VotingProcedureParam) SetReadWriter(setter params.Setter) { - param.psetter = setter - param.pgetter = setter.Getter +func (param *VotingProcedureParam) SetReadWriter(paramSpace params.Subspace) { + param.paramSpace = paramSpace } -func (param *VotingProcedureParam) GetStoreKey() string { - return "Gov/gov/VotingProcedure" +func (param *VotingProcedureParam) GetStoreKey() []byte { + return []byte("govVotingProcedure") } func (param *VotingProcedureParam) SaveValue(ctx sdk.Context) { - param.psetter.Set(ctx, param.GetStoreKey(), param.Value) + param.paramSpace.Set(ctx, param.GetStoreKey(), param.Value) } func (param *VotingProcedureParam) LoadValue(ctx sdk.Context) bool { - err := param.pgetter.Get(ctx, param.GetStoreKey(), ¶m.Value) - if err != nil { + if param.paramSpace.Has(ctx, param.GetStoreKey()) == false { return false } + param.paramSpace.Get(ctx, param.GetStoreKey(), ¶m.Value) return true } @@ -199,8 +196,8 @@ func (param *VotingProcedureParam) Valid(jsonStr string) sdk.Error { if err = json.Unmarshal([]byte(jsonStr), ¶m.Value); err == nil { - if param.Value.VotingPeriod < 20 || param.Value.VotingPeriod > 20000 { - return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidVotingPeriod, fmt.Sprintf("VotingPeriod ("+strconv.Itoa(int(param.Value.VotingPeriod))+") should be larger than 20 and less than 20000")) + if param.Value.VotingPeriod.Seconds() < 20 || param.Value.VotingPeriod.Seconds() > THREE_DAYS { + return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidVotingPeriod, fmt.Sprintf("VotingPeriod (%s) should be larger than 20s and less than %ds",strconv.Itoa(int(param.Value.VotingPeriod.Seconds())), THREE_DAYS)) } return nil @@ -214,19 +211,18 @@ var _ iparam.GovParameter = (*TallyingProcedureParam)(nil) // 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 + Threshold sdk.Dec `json:"threshold"` // Minimum propotion of Yes votes for proposal to pass. Initial value: 0.5 + Veto sdk.Dec `json:"veto"` // Minimum value of Veto votes to Total votes ratio for proposal to be vetoed. Initial value: 1/3 + Participation sdk.Dec `json:"participation"` // } type TallyingProcedureParam struct { Value TallyingProcedure - psetter params.Setter - pgetter params.Getter + paramSpace params.Subspace } -func (param *TallyingProcedureParam) GetValueFromRawData(cdc *wire.Codec, res []byte) interface{} { - cdc.MustUnmarshalBinary(res, ¶m.Value) +func (param *TallyingProcedureParam) GetValueFromRawData(cdc *codec.Codec, res []byte) interface{} { + cdc.UnmarshalJSON(res, ¶m.Value) return param.Value } @@ -235,31 +231,30 @@ func (param *TallyingProcedureParam) InitGenesis(genesisState interface{}) { param.Value = value } else { param.Value = TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 100), + Threshold: sdk.NewDecWithPrec(5, 1), + Veto: sdk.NewDecWithPrec(334, 3), + Participation: sdk.NewDecWithPrec(667, 3), } } } -func (param *TallyingProcedureParam) SetReadWriter(setter params.Setter) { - param.psetter = setter - param.pgetter = setter.Getter +func (param *TallyingProcedureParam) SetReadWriter(paramSpace params.Subspace) { + param.paramSpace = paramSpace } -func (param *TallyingProcedureParam) GetStoreKey() string { - return "Gov/gov/TallyingProcedure" +func (param *TallyingProcedureParam) GetStoreKey() []byte { + return []byte("govTallyingProcedure") } func (param *TallyingProcedureParam) SaveValue(ctx sdk.Context) { - param.psetter.Set(ctx, param.GetStoreKey(), param.Value) + param.paramSpace.Set(ctx, param.GetStoreKey(), param.Value) } func (param *TallyingProcedureParam) LoadValue(ctx sdk.Context) bool { - err := param.pgetter.Get(ctx, param.GetStoreKey(), ¶m.Value) - if err != nil { + if param.paramSpace.Has(ctx, param.GetStoreKey()) == false { return false } + param.paramSpace.Get(ctx, param.GetStoreKey(), ¶m.Value) return true } @@ -290,13 +285,13 @@ func (param *TallyingProcedureParam) Valid(jsonStr string) sdk.Error { if err = json.Unmarshal([]byte(jsonStr), ¶m.Value); err == nil { - if param.Value.Threshold.LTE(sdk.NewRat(0)) || param.Value.Threshold.GTE(sdk.NewRat(1)) { + if param.Value.Threshold.LTE(sdk.ZeroDec()) || param.Value.Threshold.GTE(sdk.NewDec(1)) { return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidThreshold, fmt.Sprintf("Invalid Threshold ( "+param.Value.Threshold.String()+" ) should be between 0 and 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("Invalid Penalty ( "+param.Value.GovernancePenalty.String()+" ) should be between 0 and 1")) + if param.Value.Participation.LTE(sdk.ZeroDec()) || param.Value.Participation.GTE(sdk.NewDec(1)) { + return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidParticipation, fmt.Sprintf("Invalid participation ( "+param.Value.Participation.String()+" ) should be between 0 and 1")) } - if param.Value.Veto.LTE(sdk.NewRat(0)) || param.Value.Veto.GTE(sdk.NewRat(1)) { + if param.Value.Veto.LTE(sdk.ZeroDec()) || param.Value.Veto.GTE(sdk.NewDec(1)) { return sdk.NewError(iparam.DefaultCodespace, iparam.CodeInvalidVeto, fmt.Sprintf("Invalid Veto ( "+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 6543cb1e1..ba3f72a10 100644 --- a/modules/gov/params/gov_params_test.go +++ b/modules/gov/params/gov_params_test.go @@ -2,147 +2,186 @@ package govparams import ( "fmt" + "github.com/cosmos/cosmos-sdk/codec" "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/iparam" "github.com/irisnet/irishub/types" - "github.com/irisnet/irishub/modules/iparam" "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" + "time" ) -func defaultContext(key sdk.StoreKey) sdk.Context { +func defaultContext(key sdk.StoreKey, tkeyParams *sdk.TransientStoreKey) sdk.Context { db := dbm.NewMemDB() cms := store.NewCommitMultiStore(db) cms.MountStoreWithDB(key, sdk.StoreTypeIAVL, db) + cms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) + cms.LoadLatestVersion() ctx := sdk.NewContext(cms, abci.Header{}, false, log.NewNopLogger()) return ctx } func TestInitGenesisParameter(t *testing.T) { - skey := sdk.NewKVStoreKey("params") - ctx := defaultContext(skey) - paramKeeper := params.NewKeeper(wire.NewCodec(), skey) + tkeyParams := sdk.NewTransientStoreKey("transient_params") + + ctx := defaultContext(skey, tkeyParams) + cdc := codec.New() - Denom := "iris" - IrisCt := types.NewDefaultCoinType(Denom) + paramKeeper := params.NewKeeper( + cdc, + skey, tkeyParams, + ) + + Denom := "iris" + IrisCt := types.NewDefaultCoinType(Denom) minDeposit, err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", 10, Denom)) require.NoError(t, err) p1 := DepositProcedure{ MinDeposit: sdk.Coins{minDeposit}, - MaxDepositPeriod: 1440} + MaxDepositPeriod: time.Duration(172800) * time.Second} minDeposit, err = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", 20, Denom)) require.NoError(t, err) p2 := DepositProcedure{ MinDeposit: sdk.Coins{minDeposit}, - MaxDepositPeriod: 1440} - - iparam.SetParamReadWriter(paramKeeper.Setter(), &DepositProcedureParameter, &DepositProcedureParameter) - + MaxDepositPeriod: time.Duration(172800) * time.Second} + + subspace := paramKeeper.Subspace("Gov").WithTypeTable( + params.NewTypeTable( + DepositProcedureParameter.GetStoreKey(), DepositProcedure{}, + VotingProcedureParameter.GetStoreKey(), VotingProcedure{}, + TallyingProcedureParameter.GetStoreKey(), TallyingProcedure{}, + )) + iparam.SetParamReadWriter(subspace, &DepositProcedureParameter, &DepositProcedureParameter) iparam.InitGenesisParameter(&DepositProcedureParameter, ctx, nil) require.Equal(t, p1, DepositProcedureParameter.Value) - - require.Equal(t, DepositProcedureParameter.ToJson(""), "{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":1440}") + require.Equal(t, DepositProcedureParameter.ToJson(""), "{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":172800000000000}") iparam.InitGenesisParameter(&DepositProcedureParameter, ctx, p2) - require.Equal(t, p1, DepositProcedureParameter.Value) } func TestRegisterParamMapping(t *testing.T) { - skey := sdk.NewKVStoreKey("params") - ctx := defaultContext(skey) - paramKeeper := params.NewKeeper(wire.NewCodec(), skey) + tkeyParams := sdk.NewTransientStoreKey("transient_params") - Denom := "iris" - IrisCt := types.NewDefaultCoinType(Denom) + ctx := defaultContext(skey, tkeyParams) + cdc := codec.New() + + paramKeeper := params.NewKeeper( + cdc, + skey, tkeyParams, + ) + + Denom := "iris" + IrisCt := types.NewDefaultCoinType(Denom) minDeposit, err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", 10, Denom)) require.NoError(t, err) p1 := DepositProcedure{ MinDeposit: sdk.Coins{minDeposit}, - MaxDepositPeriod: 1440} + MaxDepositPeriod: time.Duration(172800) * time.Second} minDeposit, err = IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", 30, Denom)) require.NoError(t, err) p2 := DepositProcedure{ MinDeposit: sdk.Coins{minDeposit}, - MaxDepositPeriod: 1440} - - iparam.SetParamReadWriter(paramKeeper.Setter(), &DepositProcedureParameter, &DepositProcedureParameter) + MaxDepositPeriod: time.Duration(172800) * time.Second} + + subspace := paramKeeper.Subspace("Gov").WithTypeTable( + params.NewTypeTable( + DepositProcedureParameter.GetStoreKey(), DepositProcedure{}, + VotingProcedureParameter.GetStoreKey(), VotingProcedure{}, + TallyingProcedureParameter.GetStoreKey(), TallyingProcedure{}, + )) + iparam.SetParamReadWriter(subspace, &DepositProcedureParameter, &DepositProcedureParameter) iparam.RegisterGovParamMapping(&DepositProcedureParameter) iparam.InitGenesisParameter(&DepositProcedureParameter, ctx, nil) - require.Equal(t, iparam.ParamMapping[DepositProcedureParameter.GetStoreKey()].ToJson(""), "{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":1440}") + require.Equal(t, iparam.ParamMapping["Gov/"+string(DepositProcedureParameter.GetStoreKey())].ToJson(""), "{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":172800000000000}") require.Equal(t, p1, DepositProcedureParameter.Value) - iparam.ParamMapping[DepositProcedureParameter.GetStoreKey()].Update(ctx, "{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"30000000000000000000\"}],\"max_deposit_period\":1440}") + iparam.ParamMapping["Gov/"+string(DepositProcedureParameter.GetStoreKey())].Update(ctx, "{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"30000000000000000000\"}],\"max_deposit_period\":172800000000000}") DepositProcedureParameter.LoadValue(ctx) require.Equal(t, p2, DepositProcedureParameter.Value) } func TestDepositProcedureParam(t *testing.T) { skey := sdk.NewKVStoreKey("params") - ctx := defaultContext(skey) - paramKeeper := params.NewKeeper(wire.NewCodec(), skey) + tkeyParams := sdk.NewTransientStoreKey("transient_params") + + ctx := defaultContext(skey, tkeyParams) + cdc := codec.New() + + paramKeeper := params.NewKeeper( + cdc, + skey, tkeyParams, + ) p1deposit, _ := types.NewDefaultCoinType("iris").ConvertToMinCoin(fmt.Sprintf("%d%s", 10, "iris")) p2Deposit, _ := types.NewDefaultCoinType("iris").ConvertToMinCoin(fmt.Sprintf("%d%s", 200, "iris")) p1 := DepositProcedure{ MinDeposit: sdk.Coins{p1deposit}, - MaxDepositPeriod: 1440} + MaxDepositPeriod: time.Duration(172800) * time.Second} p2 := DepositProcedure{ MinDeposit: sdk.Coins{p2Deposit}, - MaxDepositPeriod: 1440} + MaxDepositPeriod: time.Duration(172800) * time.Second} + + subspace := paramKeeper.Subspace("Gov").WithTypeTable( + params.NewTypeTable( + DepositProcedureParameter.GetStoreKey(), DepositProcedure{}, + VotingProcedureParameter.GetStoreKey(), VotingProcedure{}, + TallyingProcedureParameter.GetStoreKey(), TallyingProcedure{}, + )) - DepositProcedureParameter.SetReadWriter(paramKeeper.Setter()) + DepositProcedureParameter.SetReadWriter(subspace) find := DepositProcedureParameter.LoadValue(ctx) require.Equal(t, find, false) DepositProcedureParameter.InitGenesis(nil) require.Equal(t, p1, DepositProcedureParameter.Value) - require.Equal(t, DepositProcedureParameter.ToJson(""), "{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":1440}") + require.Equal(t, DepositProcedureParameter.ToJson(""), "{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"10000000000000000000\"}],\"max_deposit_period\":172800000000000}") - DepositProcedureParameter.Update(ctx, "{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"200000000000000000000\"}],\"max_deposit_period\":1440}") + DepositProcedureParameter.Update(ctx, "{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"200000000000000000000\"}],\"max_deposit_period\":172800000000000}") require.NotEqual(t, p1, DepositProcedureParameter.Value) require.Equal(t, p2, DepositProcedureParameter.Value) - result := DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"atom\",\"amount\":\"200000000000000000000\"}],\"max_deposit_period\":1440}") + result := DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"atom\",\"amount\":\"200000000000000000000\"}],\"max_deposit_period\":172800000000000}") require.Error(t, result) - result = DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"2000000000000000000\"}],\"max_deposit_period\":1440}") - require.NoError(t, result) + result = DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"2000000000000000000\"}],\"max_deposit_period\":172800000000000}") + require.Error(t, result) - result = DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"2000000000000000000000\"}],\"max_deposit_period\":1440}") + result = DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"20000000000000000000000000\"}],\"max_deposit_period\":172800000000000}") require.Error(t, result) - result = DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"200000000000000000\"}],\"max_deposit_period\":1440}") + + result = DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"200000000000000000\"}],\"max_deposit_period\":172800000000000}") require.Error(t, result) - result = DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"iris-att\",\"amount\":\"2000000000000000000\"}],\"max_deposit_period\":1440}") + result = DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"iris-att\",\"amount\":\"2000000000000000000\"}],\"max_deposit_period\":172800000000000}") require.Error(t, result) - result = DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"2000000000000000000\"}],\"max_deposit_period\":1440}") + result = DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"20000000000000000000\"}],\"max_deposit_period\":172800000000000}") require.NoError(t, result) result = DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"2000000000000000000\"}],\"max_deposit_period\":1}") require.Error(t, result) - result = DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"2000000000000000000\"}],\"max_deposit_period\":1440000}") + result = DepositProcedureParameter.Valid("{\"min_deposit\":[{\"denom\":\"iris-atto\",\"amount\":\"2000000000000000000\"}],\"max_deposit_period\":172800000000000}") require.Error(t, result) DepositProcedureParameter.InitGenesis(p2) @@ -157,27 +196,41 @@ func TestDepositProcedureParam(t *testing.T) { func TestVotingProcedureParam(t *testing.T) { skey := sdk.NewKVStoreKey("params") - ctx := defaultContext(skey) - paramKeeper := params.NewKeeper(wire.NewCodec(), skey) + tkeyParams := sdk.NewTransientStoreKey("transient_params") + + ctx := defaultContext(skey, tkeyParams) + cdc := codec.New() + + paramKeeper := params.NewKeeper( + cdc, + skey, tkeyParams, + ) p1 := VotingProcedure{ - VotingPeriod: 1000, + VotingPeriod: time.Duration(172800) * time.Second, } p2 := VotingProcedure{ - VotingPeriod: 2000, + VotingPeriod: time.Duration(192800) * time.Second, } - VotingProcedureParameter.SetReadWriter(paramKeeper.Setter()) + subspace := paramKeeper.Subspace("Gov").WithTypeTable( + params.NewTypeTable( + DepositProcedureParameter.GetStoreKey(), DepositProcedure{}, + VotingProcedureParameter.GetStoreKey(), VotingProcedure{}, + TallyingProcedureParameter.GetStoreKey(), TallyingProcedure{}, + )) + + VotingProcedureParameter.SetReadWriter(subspace) find := VotingProcedureParameter.LoadValue(ctx) require.Equal(t, find, false) VotingProcedureParameter.InitGenesis(nil) require.Equal(t, p1, VotingProcedureParameter.Value) - require.Equal(t, VotingProcedureParameter.ToJson(""), "{\"voting_period\":1000}") + require.Equal(t, VotingProcedureParameter.ToJson(""), "{\"voting_period\":172800000000000}") - VotingProcedureParameter.Update(ctx, "{\"voting_period\":2000}") + VotingProcedureParameter.Update(ctx, "{\"voting_period\":192800000000000}") require.NotEqual(t, p1, VotingProcedureParameter.Value) require.Equal(t, p2, VotingProcedureParameter.Value) @@ -197,38 +250,52 @@ func TestVotingProcedureParam(t *testing.T) { func TestTallyingProcedureParam(t *testing.T) { skey := sdk.NewKVStoreKey("params") - ctx := defaultContext(skey) - paramKeeper := params.NewKeeper(wire.NewCodec(), skey) + tkeyParams := sdk.NewTransientStoreKey("transient_params") + + ctx := defaultContext(skey, tkeyParams) + cdc := codec.New() + + paramKeeper := params.NewKeeper( + cdc, + skey, tkeyParams, + ) p1 := TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 100), + Threshold: sdk.NewDecWithPrec(5, 1), + Veto: sdk.NewDecWithPrec(334, 3), + Participation: sdk.NewDecWithPrec(667, 3), } p2 := TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 50), + Threshold: sdk.NewDecWithPrec(5, 1), + Veto: sdk.NewDecWithPrec(334, 3), + Participation: sdk.NewDecWithPrec(2, 2), } - TallyingProcedureParameter.SetReadWriter(paramKeeper.Setter()) + subspace := paramKeeper.Subspace("Gov").WithTypeTable( + params.NewTypeTable( + DepositProcedureParameter.GetStoreKey(), DepositProcedure{}, + VotingProcedureParameter.GetStoreKey(), VotingProcedure{}, + TallyingProcedureParameter.GetStoreKey(), TallyingProcedure{}, + )) + + TallyingProcedureParameter.SetReadWriter(subspace) find := TallyingProcedureParameter.LoadValue(ctx) require.Equal(t, find, false) TallyingProcedureParameter.InitGenesis(nil) require.Equal(t, p1, TallyingProcedureParameter.Value) - require.Equal(t, TallyingProcedureParameter.ToJson(""), "{\"threshold\":\"1/2\",\"veto\":\"1/3\",\"governance_penalty\":\"1/100\"}") + require.Equal(t, "{\"threshold\":\"0.5000000000\",\"veto\":\"0.3340000000\",\"participation\":\"0.6670000000\"}", TallyingProcedureParameter.ToJson("")) - TallyingProcedureParameter.Update(ctx, "{\"threshold\":\"0.5\",\"veto\":\"1/3\",\"governance_penalty\":\"1/50\"}") + TallyingProcedureParameter.Update(ctx, "{\"threshold\":\"0.5\",\"veto\":\"0.3340000000\",\"participation\":\"0.0200000000\"}") require.NotEqual(t, p1, TallyingProcedureParameter.Value) require.Equal(t, p2, TallyingProcedureParameter.Value) - result := TallyingProcedureParameter.Valid("{\"threshold\":\"1/1\",\"veto\":\"1/3\",\"governance_penalty\":\"1/100\"}") + result := TallyingProcedureParameter.Valid("{\"threshold\":\"1/1\",\"veto\":\"1/3\",\"participation\":\"1/100\"}") require.Error(t, result) - result = TallyingProcedureParameter.Valid("{\"threshold\":\"abcd\",\"veto\":\"1/3\",\"governance_penalty\":\"1/100\"}") + result = TallyingProcedureParameter.Valid("{\"threshold\":\"abcd\",\"veto\":\"1/3\",\"participation\":\"1/100\"}") require.Error(t, result) TallyingProcedureParameter.InitGenesis(p2) diff --git a/modules/gov/proposal_params.go b/modules/gov/proposal_params.go index 3c27741ec..00d6ae001 100644 --- a/modules/gov/proposal_params.go +++ b/modules/gov/proposal_params.go @@ -3,7 +3,7 @@ package gov import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/irisnet/irishub/modules/iparam" + "github.com/irisnet/irishub/iparam" ) const ( diff --git a/modules/gov/proposals.go b/modules/gov/proposals.go index d87dc40f4..9735b91d5 100644 --- a/modules/gov/proposals.go +++ b/modules/gov/proposals.go @@ -3,6 +3,7 @@ package gov import ( "encoding/json" "fmt" + "time" "github.com/pkg/errors" @@ -12,8 +13,8 @@ import ( //----------------------------------------------------------- // Proposal interface type Proposal interface { - GetProposalID() int64 - SetProposalID(int64) + GetProposalID() uint64 + SetProposalID(uint64) GetTitle() string SetTitle(string) @@ -30,18 +31,23 @@ type Proposal interface { GetTallyResult() TallyResult SetTallyResult(TallyResult) - GetSubmitBlock() int64 - SetSubmitBlock(int64) + GetSubmitTime() time.Time + SetSubmitTime(time.Time) + + GetDepositEndTime() time.Time + SetDepositEndTime(time.Time) GetTotalDeposit() sdk.Coins SetTotalDeposit(sdk.Coins) - GetVotingStartBlock() int64 - SetVotingStartBlock(int64) + GetVotingStartTime() time.Time + SetVotingStartTime(time.Time) + GetVotingEndTime() time.Time + SetVotingEndTime(time.Time) //////////////////// iris begin /////////////////////////// Execute(ctx sdk.Context, k Keeper) error - //////////////////// iris end /////////////////////////// +//////////////////// iris end /////////////////////////// } // checks if two proposals are equal @@ -52,9 +58,11 @@ func ProposalEqual(proposalA Proposal, proposalB Proposal) bool { proposalA.GetProposalType() == proposalB.GetProposalType() && proposalA.GetStatus() == proposalB.GetStatus() && proposalA.GetTallyResult().Equals(proposalB.GetTallyResult()) && - proposalA.GetSubmitBlock() == proposalB.GetSubmitBlock() && + proposalA.GetSubmitTime().Equal(proposalB.GetSubmitTime()) && + proposalA.GetDepositEndTime().Equal(proposalB.GetDepositEndTime()) && proposalA.GetTotalDeposit().IsEqual(proposalB.GetTotalDeposit()) && - proposalA.GetVotingStartBlock() == proposalB.GetVotingStartBlock() { + proposalA.GetVotingStartTime().Equal(proposalB.GetVotingStartTime()) && + proposalA.GetVotingEndTime().Equal(proposalB.GetVotingEndTime()) { return true } return false @@ -63,7 +71,7 @@ func ProposalEqual(proposalA Proposal, proposalB Proposal) bool { //----------------------------------------------------------- // Text Proposals type TextProposal struct { - ProposalID int64 `json:"proposal_id"` // ID of the proposal + ProposalID uint64 `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} @@ -71,18 +79,20 @@ type TextProposal struct { Status ProposalStatus `json:"proposal_status"` // Status of the Proposal {Pending, Active, Passed, Rejected} TallyResult TallyResult `json:"tally_result"` // Result of Tallys - 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 + SubmitTime time.Time `json:"submit_time"` // Time of the block where TxGovSubmitProposal was included + DepositEndTime time.Time `json:"deposit_end_time"` // Time that the Proposal would expire if deposit amount isn't met + 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 + VotingStartTime time.Time `json:"voting_start_time"` // Time of the block where MinDeposit was reached. -1 if MinDeposit is not reached + VotingEndTime time.Time `json:"voting_end_time"` // Time that the VotingPeriod for this proposal will end and votes will be tallied } // Implements Proposal Interface var _ Proposal = (*TextProposal)(nil) // nolint -func (tp TextProposal) GetProposalID() int64 { return tp.ProposalID } -func (tp *TextProposal) SetProposalID(proposalID int64) { tp.ProposalID = proposalID } +func (tp TextProposal) GetProposalID() uint64 { return tp.ProposalID } +func (tp *TextProposal) SetProposalID(proposalID uint64) { tp.ProposalID = proposalID } func (tp TextProposal) GetTitle() string { return tp.Title } func (tp *TextProposal) SetTitle(title string) { tp.Title = title } func (tp TextProposal) GetDescription() string { return tp.Description } @@ -93,19 +103,30 @@ func (tp TextProposal) GetStatus() ProposalStatus { return tp.S func (tp *TextProposal) SetStatus(status ProposalStatus) { tp.Status = status } func (tp TextProposal) GetTallyResult() TallyResult { return tp.TallyResult } func (tp *TextProposal) SetTallyResult(tallyResult TallyResult) { tp.TallyResult = tallyResult } -func (tp TextProposal) GetSubmitBlock() int64 { return tp.SubmitBlock } -func (tp *TextProposal) SetSubmitBlock(submitBlock int64) { tp.SubmitBlock = submitBlock } -func (tp TextProposal) GetTotalDeposit() sdk.Coins { return tp.TotalDeposit } -func (tp *TextProposal) SetTotalDeposit(totalDeposit sdk.Coins) { tp.TotalDeposit = totalDeposit } -func (tp TextProposal) GetVotingStartBlock() int64 { return tp.VotingStartBlock } -func (tp *TextProposal) SetVotingStartBlock(votingStartBlock int64) { - tp.VotingStartBlock = votingStartBlock +func (tp TextProposal) GetSubmitTime() time.Time { return tp.SubmitTime } +func (tp *TextProposal) SetSubmitTime(submitTime time.Time) { tp.SubmitTime = submitTime } +func (tp TextProposal) GetDepositEndTime() time.Time { return tp.DepositEndTime } +func (tp *TextProposal) SetDepositEndTime(depositEndTime time.Time) { + tp.DepositEndTime = depositEndTime +} +func (tp TextProposal) GetTotalDeposit() sdk.Coins { return tp.TotalDeposit } +func (tp *TextProposal) SetTotalDeposit(totalDeposit sdk.Coins) { tp.TotalDeposit = totalDeposit } +func (tp TextProposal) GetVotingStartTime() time.Time { return tp.VotingStartTime } +func (tp *TextProposal) SetVotingStartTime(votingStartTime time.Time) { + tp.VotingStartTime = votingStartTime } -func (tp *TextProposal) Execute(ctx sdk.Context, k Keeper) error { return nil } +func (tp TextProposal) GetVotingEndTime() time.Time { return tp.VotingEndTime } +func (tp *TextProposal) SetVotingEndTime(votingEndTime time.Time) { + tp.VotingEndTime = votingEndTime +} + +//////////////////// iris begin /////////////////////////// +func (pp *TextProposal) Execute(ctx sdk.Context, k Keeper) (err error) {return nil} +//////////////////// iris end ///////////////////////////// //----------------------------------------------------------- // ProposalQueue -type ProposalQueue []int64 +type ProposalQueue []uint64 //----------------------------------------------------------- // ProposalKind @@ -115,6 +136,7 @@ type ProposalKind byte //nolint const ( + ProposalTypeNil ProposalKind = 0x00 ProposalTypeText ProposalKind = 0x01 ProposalTypeParameterChange ProposalKind = 0x02 ProposalTypeSoftwareUpgrade ProposalKind = 0x03 @@ -191,11 +213,13 @@ func (pt ProposalKind) String() string { } // For Printf / Sprintf, returns bech32 when using %s +// nolint: errcheck func (pt ProposalKind) Format(s fmt.State, verb rune) { switch verb { case 's': - s.Write([]byte(fmt.Sprintf("%s", pt.String()))) + s.Write([]byte(pt.String())) default: + // TODO: Do this conversion more directly s.Write([]byte(fmt.Sprintf("%v", byte(pt)))) } } @@ -208,6 +232,7 @@ type ProposalStatus byte //nolint const ( + StatusNil ProposalStatus = 0x00 StatusDepositPeriod ProposalStatus = 0x01 StatusVotingPeriod ProposalStatus = 0x02 StatusPassed ProposalStatus = 0x03 @@ -225,6 +250,8 @@ func ProposalStatusFromString(str string) (ProposalStatus, error) { return StatusPassed, nil case "Rejected": return StatusRejected, nil + case "": + return StatusNil, nil default: return ProposalStatus(0xff), errors.Errorf("'%s' is not a valid proposal status", str) } @@ -290,11 +317,13 @@ func (status ProposalStatus) String() string { } // For Printf / Sprintf, returns bech32 when using %s +// nolint: errcheck func (status ProposalStatus) Format(s fmt.State, verb rune) { switch verb { case 's': - s.Write([]byte(fmt.Sprintf("%s", status.String()))) + s.Write([]byte(status.String())) default: + // TODO: Do this conversion more directly s.Write([]byte(fmt.Sprintf("%v", byte(status)))) } } @@ -302,29 +331,26 @@ func (status ProposalStatus) Format(s fmt.State, verb rune) { //----------------------------------------------------------- // Tally Results type TallyResult struct { - Yes sdk.Rat `json:"yes"` - Abstain sdk.Rat `json:"abstain"` - No sdk.Rat `json:"no"` - NoWithVeto sdk.Rat `json:"no_with_veto"` + Yes sdk.Dec `json:"yes"` + Abstain sdk.Dec `json:"abstain"` + No sdk.Dec `json:"no"` + NoWithVeto sdk.Dec `json:"no_with_veto"` } // checks if two proposals are equal func EmptyTallyResult() TallyResult { return TallyResult{ - Yes: sdk.ZeroRat(), - Abstain: sdk.ZeroRat(), - No: sdk.ZeroRat(), - NoWithVeto: sdk.ZeroRat(), + Yes: sdk.ZeroDec(), + Abstain: sdk.ZeroDec(), + No: sdk.ZeroDec(), + NoWithVeto: sdk.ZeroDec(), } } // checks if two proposals are equal func (resultA TallyResult) Equals(resultB TallyResult) bool { - if resultA.Yes.Equal(resultB.Yes) && + return (resultA.Yes.Equal(resultB.Yes) && resultA.Abstain.Equal(resultB.Abstain) && resultA.No.Equal(resultB.No) && - resultA.NoWithVeto.Equal(resultB.NoWithVeto) { - return true - } - return false + resultA.NoWithVeto.Equal(resultB.NoWithVeto)) } diff --git a/modules/gov/queryable.go b/modules/gov/queryable.go new file mode 100644 index 000000000..737a9ece5 --- /dev/null +++ b/modules/gov/queryable.go @@ -0,0 +1,289 @@ +package gov + +import ( + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" + "time" +) + +// query endpoints supported by the governance Querier +const ( + QueryProposals = "proposals" + QueryProposal = "proposal" + QueryDeposits = "deposits" + QueryDeposit = "deposit" + QueryVotes = "votes" + QueryVote = "vote" + QueryTally = "tally" +) + +func NewQuerier(keeper Keeper) sdk.Querier { + return func(ctx sdk.Context, path []string, req abci.RequestQuery) (res []byte, err sdk.Error) { + switch path[0] { + case QueryProposals: + return queryProposals(ctx, path[1:], req, keeper) + case QueryProposal: + return queryProposal(ctx, path[1:], req, keeper) + case QueryDeposits: + return queryDeposits(ctx, path[1:], req, keeper) + case QueryDeposit: + return queryDeposit(ctx, path[1:], req, keeper) + case QueryVotes: + return queryVotes(ctx, path[1:], req, keeper) + case QueryVote: + return queryVote(ctx, path[1:], req, keeper) + case QueryTally: + return queryTally(ctx, path[1:], req, keeper) + default: + return nil, sdk.ErrUnknownRequest("unknown gov query endpoint") + } + } +} + +type ProposalOutput struct { + ProposalID uint64 `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} + TallyResult TallyResult `json:"tally_result"` // Result of Tallys + + SubmitTime time.Time `json:"submit_time"` // Time of the block where TxGovSubmitProposal was included + DepositEndTime time.Time `json:"deposit_end_time"` // Time that the Proposal would expire if deposit amount isn't met + TotalDeposit sdk.Coins `json:"total_deposit"` // Current deposit on this proposal. Initial value is set at InitialDeposit + + VotingStartTime time.Time `json:"voting_start_time"` // Time of the block where MinDeposit was reached. -1 if MinDeposit is not reached + VotingEndTime time.Time `json:"voting_end_time"` // Time that the VotingPeriod for this proposal will end and votes will be tallied + Param Param `json:"param"` +} + +type ProposalOutputs []ProposalOutput + +func ConvertProposalToProposalOutput(proposal Proposal) ProposalOutput { + + proposalOutput := ProposalOutput{ + ProposalID: proposal.GetProposalID(), + Title: proposal.GetTitle(), + Description: proposal.GetDescription(), + ProposalType: proposal.GetProposalType(), + + Status: proposal.GetStatus(), + TallyResult: proposal.GetTallyResult(), + + SubmitTime: proposal.GetSubmitTime(), + DepositEndTime: proposal.GetDepositEndTime(), + TotalDeposit: proposal.GetTotalDeposit(), + + VotingStartTime: proposal.GetVotingStartTime(), + VotingEndTime: proposal.GetVotingEndTime(), + Param: Param{}, + } + + if proposal.GetProposalType() == ProposalTypeParameterChange { + proposalOutput.Param = proposal.(*ParameterProposal).Param + } + return proposalOutput +} + +func ConvertProposalsToProposalOutputs(proposals []Proposal) ProposalOutputs { + + var proposalOutputs ProposalOutputs + for _,proposal :=range proposals{ + proposalOutputs= append(proposalOutputs,ConvertProposalToProposalOutput(proposal)) + } + return proposalOutputs +} + +// Params for query 'custom/gov/proposal' +type QueryProposalParams struct { + ProposalID uint64 +} + +// nolint: unparam +func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) (res []byte, err sdk.Error) { + var params QueryProposalParams + err2 := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) + if err2 != nil { + return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err2.Error())) + } + + proposal := keeper.GetProposal(ctx, params.ProposalID) + if proposal == nil { + return nil, ErrUnknownProposal(DefaultCodespace, params.ProposalID) + } + + proposalOutput := ConvertProposalToProposalOutput(proposal) + + bz, err2 := codec.MarshalJSONIndent(keeper.cdc, proposalOutput) + if err2 != nil { + return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err2.Error())) + } + return bz, nil +} + +// Params for query 'custom/gov/deposit' +type QueryDepositParams struct { + ProposalID uint64 + Depositor sdk.AccAddress +} + +// nolint: unparam +func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) (res []byte, err sdk.Error) { + var params QueryDepositParams + err2 := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) + if err2 != nil { + return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err2.Error())) + } + + deposit, _ := keeper.GetDeposit(ctx, params.ProposalID, params.Depositor) + bz, err2 := codec.MarshalJSONIndent(keeper.cdc, deposit) + if err2 != nil { + return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err2.Error())) + } + return bz, nil +} + +// Params for query 'custom/gov/vote' +type QueryVoteParams struct { + ProposalID uint64 + Voter sdk.AccAddress +} + +// nolint: unparam +func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) (res []byte, err sdk.Error) { + var params QueryVoteParams + err2 := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) + if err2 != nil { + return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err2.Error())) + } + + vote, _ := keeper.GetVote(ctx, params.ProposalID, params.Voter) + bz, err2 := codec.MarshalJSONIndent(keeper.cdc, vote) + if err2 != nil { + return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err2.Error())) + } + return bz, nil +} + +// Params for query 'custom/gov/deposits' +type QueryDepositsParams struct { + ProposalID uint64 +} + +// nolint: unparam +func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) (res []byte, err sdk.Error) { + var params QueryDepositsParams + err2 := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) + if err2 != nil { + return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err2.Error())) + } + + var deposits []Deposit + depositsIterator := keeper.GetDeposits(ctx, params.ProposalID) + for ; depositsIterator.Valid(); depositsIterator.Next() { + deposit := Deposit{} + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), &deposit) + deposits = append(deposits, deposit) + } + + bz, err2 := codec.MarshalJSONIndent(keeper.cdc, deposits) + if err2 != nil { + return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err2.Error())) + } + return bz, nil +} + +// Params for query 'custom/gov/votes' +type QueryVotesParams struct { + ProposalID uint64 +} + +// nolint: unparam +func queryVotes(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) (res []byte, err sdk.Error) { + var params QueryVotesParams + err2 := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) + + if err2 != nil { + return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err2.Error())) + } + + var votes []Vote + votesIterator := keeper.GetVotes(ctx, params.ProposalID) + for ; votesIterator.Valid(); votesIterator.Next() { + vote := Vote{} + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(votesIterator.Value(), &vote) + votes = append(votes, vote) + } + + bz, err2 := codec.MarshalJSONIndent(keeper.cdc, votes) + if err2 != nil { + return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err2.Error())) + } + return bz, nil +} + +// Params for query 'custom/gov/proposals' +type QueryProposalsParams struct { + Voter sdk.AccAddress + Depositor sdk.AccAddress + ProposalStatus ProposalStatus + Limit uint64 +} + +// nolint: unparam +func queryProposals(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) (res []byte, err sdk.Error) { + var params QueryProposalsParams + err2 := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) + if err2 != nil { + return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err2.Error())) + } + + proposals := keeper.GetProposalsFiltered(ctx, params.Voter, params.Depositor, params.ProposalStatus, params.Limit) + + proposalOutputs := ConvertProposalsToProposalOutputs(proposals) + + bz, err2 := codec.MarshalJSONIndent(keeper.cdc, proposalOutputs) + if err2 != nil { + return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err2.Error())) + } + return bz, nil +} + +// Params for query 'custom/gov/tally' +type QueryTallyParams struct { + ProposalID uint64 +} + +// nolint: unparam +func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) (res []byte, err sdk.Error) { + // TODO: Dependant on #1914 + + var param QueryTallyParams + err2 := keeper.cdc.UnmarshalJSON(req.Data, ¶m) + if err2 != nil { + return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err2.Error())) + } + + proposal := keeper.GetProposal(ctx, param.ProposalID) + if proposal == nil { + return nil, ErrUnknownProposal(DefaultCodespace, param.ProposalID) + } + + var tallyResult TallyResult + + if proposal.GetStatus() == StatusDepositPeriod { + tallyResult = EmptyTallyResult() + } else if proposal.GetStatus() == StatusPassed || proposal.GetStatus() == StatusRejected { + tallyResult = proposal.GetTallyResult() + } else { + _, tallyResult = tally(ctx, keeper, proposal) + } + + bz, err2 := codec.MarshalJSONIndent(keeper.cdc, tallyResult) + if err2 != nil { + return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err2.Error())) + } + return bz, nil +} diff --git a/modules/gov/store_key.go b/modules/gov/store_key.go index c8fe256e7..40337ba07 100644 --- a/modules/gov/store_key.go +++ b/modules/gov/store_key.go @@ -1,11 +1,5 @@ package gov const ( - ParamStoreKeyDepositProcedureDeposit = "depositprocedure/deposit" - ParamStoreKeyDepositProcedureMaxDepositPeriod = "depositprocedure/maxDepositPeriod" - ParamStoreKeyVotingProcedureVotingPeriod = "votingprocedure/votingPeriod" - ParamStoreKeyTallyingProcedureThreshold = "tallyingprocedure/threshold" - ParamStoreKeyTallyingProcedureVeto = "tallyingprocedure/veto" - ParamStoreKeyTallyingProcedurePenalty = "tallyingprocedure/penalty" Prefix = "gov/" ) diff --git a/modules/gov/tags/tags.go b/modules/gov/tags/tags.go index dadef0a2c..8842e4a7c 100644 --- a/modules/gov/tags/tags.go +++ b/modules/gov/tags/tags.go @@ -17,7 +17,9 @@ var ( Proposer = "proposer" ProposalID = "proposal-id" VotingPeriodStart = "voting-period-start" - Depositer = "depositer" + Depositor = "depositor" Voter = "voter" + //////////////////// iris begin /////////////////////////// Param = "param" + //////////////////// iris end ///////////////////////////// ) diff --git a/modules/gov/tally.go b/modules/gov/tally.go index a3c5e988f..bb7da00fe 100644 --- a/modules/gov/tally.go +++ b/modules/gov/tally.go @@ -7,73 +7,78 @@ import ( // validatorGovInfo used for tallying type validatorGovInfo struct { - Address sdk.AccAddress // sdk.AccAddress of the validator owner - Power sdk.Rat // Power of a Validator - DelegatorShares sdk.Rat // Total outstanding delegator shares - Minus sdk.Rat // Minus of validator, used to compute validator's voting power + Address sdk.ValAddress // address of the validator operator + Power sdk.Dec // Power of a Validator + DelegatorShares sdk.Dec // Total outstanding delegator shares + Minus sdk.Dec // Minus of validator, used to compute validator's voting power Vote VoteOption // Vote of the validator } -func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tallyResults TallyResult, nonVoting []sdk.AccAddress) { - results := make(map[VoteOption]sdk.Rat) - results[OptionYes] = sdk.ZeroRat() - results[OptionAbstain] = sdk.ZeroRat() - results[OptionNo] = sdk.ZeroRat() - results[OptionNoWithVeto] = sdk.ZeroRat() +func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tallyResults TallyResult) { + results := make(map[VoteOption]sdk.Dec) + results[OptionYes] = sdk.ZeroDec() + results[OptionAbstain] = sdk.ZeroDec() + results[OptionNo] = sdk.ZeroDec() + results[OptionNoWithVeto] = sdk.ZeroDec() - totalVotingPower := sdk.ZeroRat() + totalVotingPower := sdk.ZeroDec() + systemVotingPower := sdk.ZeroDec() currValidators := make(map[string]validatorGovInfo) - keeper.vs.IterateValidatorsBonded(ctx, func(index int64, validator sdk.Validator) (stop bool) { - currValidators[validator.GetOwner().String()] = validatorGovInfo{ - Address: validator.GetOwner(), + keeper.vs.IterateBondedValidatorsByPower(ctx, func(index int64, validator sdk.Validator) (stop bool) { + currValidators[validator.GetOperator().String()] = validatorGovInfo{ + Address: validator.GetOperator(), Power: validator.GetPower(), DelegatorShares: validator.GetDelegatorShares(), - Minus: sdk.ZeroRat(), + Minus: sdk.ZeroDec(), Vote: OptionEmpty, } + systemVotingPower = systemVotingPower.Add(validator.GetPower()) return false }) // iterate over all the votes votesIterator := keeper.GetVotes(ctx, proposal.GetProposalID()) + defer votesIterator.Close() for ; votesIterator.Valid(); votesIterator.Next() { vote := &Vote{} - keeper.cdc.MustUnmarshalBinary(votesIterator.Value(), vote) + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(votesIterator.Value(), vote) // if validator, just record it in the map // if delegator tally voting power - if val, ok := currValidators[vote.Voter.String()]; ok { + valAddrStr := sdk.ValAddress(vote.Voter).String() + if val, ok := currValidators[valAddrStr]; ok { val.Vote = vote.Option - currValidators[vote.Voter.String()] = val + currValidators[valAddrStr] = val } else { keeper.ds.IterateDelegations(ctx, vote.Voter, func(index int64, delegation sdk.Delegation) (stop bool) { - if val, ok := currValidators[delegation.GetValidator().String()]; ok { - val.Minus = val.Minus.Add(delegation.GetBondShares()) - currValidators[delegation.GetValidator().String()] = val + valAddrStr := delegation.GetValidatorAddr().String() - delegatorShare := delegation.GetBondShares().Quo(val.DelegatorShares) + if val, ok := currValidators[valAddrStr]; ok { + val.Minus = val.Minus.Add(delegation.GetShares()) + currValidators[valAddrStr] = val + + delegatorShare := delegation.GetShares().Quo(val.DelegatorShares) votingPower := val.Power.Mul(delegatorShare) results[vote.Option] = results[vote.Option].Add(votingPower) totalVotingPower = totalVotingPower.Add(votingPower) } + return false }) } keeper.deleteVote(ctx, vote.ProposalID, vote.Voter) } - votesIterator.Close() - // Iterate over the validators again to tally their voting power and see who didn't vote - nonVoting = []sdk.AccAddress{} + // iterate over the validators again to tally their voting power for _, val := range currValidators { if val.Vote == OptionEmpty { - nonVoting = append(nonVoting, val.Address) continue } + sharesAfterMinus := val.DelegatorShares.Sub(val.Minus) percentAfterMinus := sharesAfterMinus.Quo(val.DelegatorShares) votingPower := val.Power.Mul(percentAfterMinus) @@ -82,7 +87,9 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tall totalVotingPower = totalVotingPower.Add(votingPower) } + //////////////////// iris begin /////////////////////////// tallyingProcedure := govparams.GetTallyingProcedure(ctx) + //////////////////// iris end ///////////////////////////// tallyResults = TallyResult{ Yes: results[OptionYes], @@ -92,17 +99,26 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, tall } // If no one votes, proposal fails - if totalVotingPower.Sub(results[OptionAbstain]).Equal(sdk.ZeroRat()) { - return false, tallyResults, nonVoting + if totalVotingPower.Sub(results[OptionAbstain]).Equal(sdk.ZeroDec()) { + return false, tallyResults + } + //////////////////// iris begin /////////////////////////// + //if more than 1/3 of voters abstain, proposal fails + if tallyingProcedure.Participation.GT(totalVotingPower.Quo(systemVotingPower)) { + return false, tallyResults } + //////////////////// iris end /////////////////////////// + // If more than 1/3 of voters veto, proposal fails if results[OptionNoWithVeto].Quo(totalVotingPower).GT(tallyingProcedure.Veto) { - return false, tallyResults, nonVoting + return false, tallyResults } + // If more than 1/2 of non-abstaining voters vote Yes, proposal passes if results[OptionYes].Quo(totalVotingPower.Sub(results[OptionAbstain])).GT(tallyingProcedure.Threshold) { - return true, tallyResults, nonVoting + return true, tallyResults } // If more than 1/2 of non-abstaining voters vote No, proposal fails - return false, tallyResults, nonVoting + + return false, tallyResults } diff --git a/modules/gov/test_common.go b/modules/gov/test_common.go index d83f8d77c..31757cd78 100644 --- a/modules/gov/test_common.go +++ b/modules/gov/test_common.go @@ -17,44 +17,31 @@ import ( "github.com/cosmos/cosmos-sdk/x/stake" "github.com/irisnet/irishub/modules/gov/params" "github.com/irisnet/irishub/types" - sdkParams "github.com/cosmos/cosmos-sdk/x/params" - "github.com/irisnet/irishub/modules/iparam" - "github.com/irisnet/irishub/modules/upgrade/params" ) // initialize the mock application for this module func getMockApp(t *testing.T, numGenAccs int) (*mock.App, Keeper, stake.Keeper, []sdk.AccAddress, []crypto.PubKey, []crypto.PrivKey) { mapp := mock.NewApp() - stake.RegisterWire(mapp.Cdc) - RegisterWire(mapp.Cdc) + stake.RegisterCodec(mapp.Cdc) + RegisterCodec(mapp.Cdc) - keyGlobalParams := sdk.NewKVStoreKey("params") - keyStake := sdk.NewKVStoreKey("stake") keyGov := sdk.NewKVStoreKey("gov") - ck := bank.NewKeeper(mapp.AccountMapper) - sk := stake.NewKeeper(mapp.Cdc, keyStake, ck, mapp.RegisterCodespace(stake.DefaultCodespace)) + ck := bank.NewBaseKeeper(mapp.AccountKeeper) + sk := stake.NewKeeper( + mapp.Cdc, + mapp.KeyStake, mapp.TkeyStake, + mapp.BankKeeper, mapp.ParamsKeeper.Subspace(stake.DefaultParamspace), + mapp.RegisterCodespace(stake.DefaultCodespace)) gk := NewKeeper(mapp.Cdc, keyGov, ck, sk, DefaultCodespace) - pk := sdkParams.NewKeeper(mapp.Cdc, keyGlobalParams) mapp.Router().AddRoute("gov", []*sdk.KVStoreKey{keyGov}, NewHandler(gk)) - iparam.SetParamReadWriter(pk.Setter(), - &govparams.DepositProcedureParameter, - &govparams.VotingProcedureParameter, - &govparams.TallyingProcedureParameter, - &upgradeparams.CurrentUpgradeProposalIdParameter, - &upgradeparams.ProposalAcceptHeightParameter) - - iparam.RegisterGovParamMapping(&govparams.DepositProcedureParameter, - &govparams.VotingProcedureParameter, - &govparams.TallyingProcedureParameter,) - mapp.SetEndBlocker(getEndBlocker(gk)) mapp.SetInitChainer(getInitChainer(mapp, gk, sk)) - require.NoError(t, mapp.CompleteSetup([]*sdk.KVStoreKey{keyStake, keyGov, keyGlobalParams})) + require.NoError(t, mapp.CompleteSetup(keyGov)) coin, _ := types.NewDefaultCoinType("iris").ConvertToMinCoin(fmt.Sprintf("%d%s", 1042, "iris")) genAccs, addrs, pubKeys, privKeys := mock.CreateGenAccounts(numGenAccs, sdk.Coins{coin}) @@ -81,7 +68,7 @@ func getInitChainer(mapp *mock.App, keeper Keeper, stakeKeeper stake.Keeper) sdk stakeGenesis := stake.DefaultGenesisState() stakeGenesis.Params.BondDenom = "iris-atto" - stakeGenesis.Pool.LooseTokens = sdk.NewRat(100000) + stakeGenesis.Pool.LooseTokens = sdk.NewDecFromInt(sdk.NewInt(100000)) validators, err := stake.InitGenesis(ctx, stakeKeeper, stakeGenesis) if err != nil { @@ -99,9 +86,9 @@ func getInitChainer(mapp *mock.App, keeper Keeper, stakeKeeper stake.Keeper) sdk VotingPeriod: 30, }, TallyingProcedure: govparams.TallyingProcedure{ - Threshold: sdk.NewRat(1, 2), - Veto: sdk.NewRat(1, 3), - GovernancePenalty: sdk.NewRat(1, 100), + Threshold: sdk.NewDecWithPrec(5, 1), + Veto: sdk.NewDecWithPrec(334, 3), + Participation: sdk.NewDecWithPrec(667, 3), }, }) return abci.ResponseInitChain{ diff --git a/modules/iservice/error.go b/modules/iservice/error.go deleted file mode 100644 index e94cb2786..000000000 --- a/modules/iservice/error.go +++ /dev/null @@ -1,87 +0,0 @@ -package iservice - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "fmt" -) - -const ( - DefaultCodespace sdk.CodespaceType = 6 - - CodeInvalidIDL sdk.CodeType = 100 - CodeSvcDefExists sdk.CodeType = 101 - CodeInvalidOutputPrivacyEnum sdk.CodeType = 102 - CodeInvalidOutputCachedEnum sdk.CodeType = 103 - CodeInvalidServiceName sdk.CodeType = 104 - CodeInvalidChainId sdk.CodeType = 105 - CodeInvalidAuthor sdk.CodeType = 106 - CodeInvalidMethodName sdk.CodeType = 107 - CodeInvalidBroadcastEnum sdk.CodeType = 108 - CodeMoreTags sdk.CodeType = 109 - CodeDuplicateTags sdk.CodeType = 110 -) - -func codeToDefaultMsg(code sdk.CodeType) string { - switch code { - case CodeInvalidIDL: - return "The IDL file cannot be parsed" - default: - return sdk.CodeToDefaultMsg(code) - } -} - -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) -} - -func ErrSvcDefExists(codespace sdk.CodespaceType, svcDefName string) sdk.Error { - return sdk.NewError(codespace, CodeSvcDefExists, fmt.Sprintf("service definition name %s already exist,must use new name", svcDefName)) -} - -func ErrInvalidIDL(codespace sdk.CodespaceType, msg string) sdk.Error { - return sdk.NewError(codespace, CodeInvalidIDL, fmt.Sprintf("The IDL content cannot be parsed, err: %s", msg)) -} - -func ErrInvalidOutputPrivacyEnum(codespace sdk.CodespaceType, value string) sdk.Error { - return sdk.NewError(codespace, CodeInvalidOutputPrivacyEnum, fmt.Sprintf("invalid OutputPrivacyEnum %s", value)) -} - -func ErrInvalidOutputCachedEnum(codespace sdk.CodespaceType, value string) sdk.Error { - return sdk.NewError(codespace, CodeInvalidOutputCachedEnum, fmt.Sprintf("invalid OutputCachedEnum %s", value)) -} - -func ErrInvalidServiceName(codespace sdk.CodespaceType) sdk.Error { - return sdk.NewError(codespace, CodeInvalidServiceName, fmt.Sprintf("service name is empty")) -} - -func ErrInvalidChainId(codespace sdk.CodespaceType) sdk.Error { - return sdk.NewError(codespace, CodeInvalidChainId, fmt.Sprintf("chainId is empty")) -} - -func ErrInvalidAuthor(codespace sdk.CodespaceType) sdk.Error { - return sdk.NewError(codespace, CodeInvalidAuthor, fmt.Sprintf("author is empty")) -} - -func ErrInvalidMethodName(codespace sdk.CodespaceType) sdk.Error { - return sdk.NewError(codespace, CodeInvalidMethodName, fmt.Sprintf("method name is empty")) -} - -func ErrInvalidBroadcastEnum(codespace sdk.CodespaceType, value BroadcastEnum) sdk.Error { - return sdk.NewError(codespace, CodeInvalidBroadcastEnum, fmt.Sprintf("invalid BroadcastEnum %s", value)) -} - -func ErrMoreTags(codespace sdk.CodespaceType) sdk.Error { - return sdk.NewError(codespace, CodeMoreTags, fmt.Sprintf("tags are limited to %d", maxTagsNum)) -} - -func ErrDuplicateTags(codespace sdk.CodespaceType) sdk.Error { - return sdk.NewError(codespace, CodeDuplicateTags, "tags contains duplicate tag") -} diff --git a/modules/iservice/handler.go b/modules/iservice/handler.go deleted file mode 100644 index e06654236..000000000 --- a/modules/iservice/handler.go +++ /dev/null @@ -1,29 +0,0 @@ -package iservice - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// handle all "iservice" type messages. -func NewHandler(k Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { - switch msg := msg.(type) { - case MsgSvcDef: - return handleMsgSvcDef(ctx, k, msg) - default: - return sdk.ErrTxDecode("invalid message parse in staking module").Result() - } - } -} -func handleMsgSvcDef(ctx sdk.Context, k Keeper, msg MsgSvcDef) sdk.Result { - _, found := k.GetServiceDefinition(ctx, msg.ChainId, msg.Name) - if found { - return ErrSvcDefExists(k.Codespace(), msg.Name).Result() - } - k.AddServiceDefinition(ctx, msg) - err := k.AddMethods(ctx, msg) - if err != nil { - return err.Result() - } - return sdk.Result{} -} diff --git a/modules/iservice/keeper.go b/modules/iservice/keeper.go deleted file mode 100644 index 228f90d1b..000000000 --- a/modules/iservice/keeper.go +++ /dev/null @@ -1,75 +0,0 @@ -package iservice - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/irisnet/irishub/tools/protoidl" -) - -type Keeper struct { - storeKey sdk.StoreKey - cdc *wire.Codec - - // codespace - codespace sdk.CodespaceType -} - -func NewKeeper(cdc *wire.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) Keeper { - keeper := Keeper{ - storeKey: key, - cdc: cdc, - codespace: codespace, - } - return keeper -} - -// return the codespace -func (k Keeper) Codespace() sdk.CodespaceType { - return k.codespace -} - -func (k Keeper) AddServiceDefinition(ctx sdk.Context, serviceDef MsgSvcDef) { - kvStore := ctx.KVStore(k.storeKey) - - serviceDefBytes, err := k.cdc.MarshalBinary(serviceDef) - if err != nil { - panic(err) - } - - kvStore.Set(GetServiceDefinitionKey(serviceDef.ChainId, serviceDef.Name), serviceDefBytes) -} - -func (k Keeper) AddMethods(ctx sdk.Context, serviceDef MsgSvcDef) sdk.Error { - methods, err := protoidl.GetMethods(serviceDef.IDLContent) - if err != nil { - panic(err) - } - kvStore := ctx.KVStore(k.storeKey) - for _, method := range methods { - methodProperty, err := methodToMethodProperty(method) - if err != nil { - return err - } - methodBytes := k.cdc.MustMarshalBinary(methodProperty) - kvStore.Set(GetMethodPropertyKey(serviceDef.ChainId, serviceDef.Name, method.Name), methodBytes) - } - return nil -} - -func (k Keeper) GetServiceDefinition(ctx sdk.Context, chainId, name string) (msgSvcDef MsgSvcDef, found bool) { - kvStore := ctx.KVStore(k.storeKey) - - serviceDefBytes := kvStore.Get(GetServiceDefinitionKey(chainId, name)) - if serviceDefBytes != nil { - var serviceDef MsgSvcDef - k.cdc.MustUnmarshalBinary(serviceDefBytes, &serviceDef) - return serviceDef, true - } - return msgSvcDef, false -} - -// Gets all the methods in a specific service -func (k Keeper) GetMethods(ctx sdk.Context, chainId, name string) sdk.Iterator { - store := ctx.KVStore(k.storeKey) - return sdk.KVStorePrefixIterator(store, GetMethodsSubspaceKey(chainId, name)) -} diff --git a/modules/iservice/keeper_keys.go b/modules/iservice/keeper_keys.go deleted file mode 100644 index d4dadf5be..000000000 --- a/modules/iservice/keeper_keys.go +++ /dev/null @@ -1,38 +0,0 @@ -package iservice - -var ( - // the separator for string key - emptyByte = []byte{0x00} - - // Keys for store prefixes - serviceDefinitionKey = []byte{0x01} - methodPropertyKey = []byte{0x02} -) - -func GetServiceDefinitionKey(chainId, name string) []byte { - return append(append(append( - serviceDefinitionKey, - []byte(chainId)...), - emptyByte...), - []byte(name)...) -} - -func GetMethodPropertyKey(chainId, serviceName, methodName string) []byte { - return append(append(append(append(append( - methodPropertyKey, - []byte(chainId)...), - emptyByte...), - []byte(serviceName)...), - emptyByte...), - []byte(methodName)...) -} - -// Key for getting all methods on a service from the store -func GetMethodsSubspaceKey(chainId, serviceName string) []byte { - return append(append(append(append( - methodPropertyKey, - []byte(chainId)...), - emptyByte...), - []byte(serviceName)...), - emptyByte...) -} diff --git a/modules/iservice/keeper_test.go b/modules/iservice/keeper_test.go deleted file mode 100644 index 75e0e4342..000000000 --- a/modules/iservice/keeper_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package iservice - -import ( - "github.com/stretchr/testify/require" - "testing" -) - -const idlContent = ` - syntax = "proto3"; - - // The greeting service definition. - service Greeter { - //@Attribute description:sayHello - //@Attribute output_privacy:NoPrivacy - //@Attribute output_cached:NoCached - rpc SayHello (HelloRequest) returns (HelloReply) {} - } - - // The request message containing the user's name. - message HelloRequest { - string name = 1; - } - - // The response message containing the greetings - message HelloReply { - string message = 1; - }` - -func TestKeeper_IService_Definition(t *testing.T) { - ctx, keeper := createTestInput(t) - - serviceDef := NewMsgSvcDef("myService", - "testnet", - "the iservice for unit test", - []string{"test", "tutorial"}, - addrs[0], - "unit test author", - idlContent, - Broadcast) - - keeper.AddServiceDefinition(ctx, serviceDef) - serviceDefB, _ := keeper.GetServiceDefinition(ctx, "testnet", "myService") - - require.Equal(t, serviceDefB.IDLContent, idlContent) - require.Equal(t, serviceDefB.Name, "myService") - require.Equal(t, serviceDefB.Broadcast, Broadcast) - - keeper.AddMethods(ctx, serviceDef) - iterator := keeper.GetMethods(ctx, "testnet", "myService") - for ; ; iterator.Next() { - var method MethodProperty - if !iterator.Valid() { - break - } - keeper.cdc.MustUnmarshalBinary(iterator.Value(), &method) - require.Equal(t, method.Name, "SayHello") - require.Equal(t, method.Description, "sayHello") - require.Equal(t, method.OutputPrivacy.String(), "NoPrivacy") - require.Equal(t, method.OutputCached.String(), "NoCached") - } - -} diff --git a/modules/iservice/msgs.go b/modules/iservice/msgs.go deleted file mode 100644 index 3347b6a4c..000000000 --- a/modules/iservice/msgs.go +++ /dev/null @@ -1,152 +0,0 @@ -package iservice - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/irisnet/irishub/tools/protoidl" -) - -// name to idetify transaction types -const ( - MsgType = "iservice" - outputPrivacy = "output_privacy" - outputCached = "output_cached" - description = "description" - maxTagsNum = 5 -) - -var _ sdk.Msg = MsgSvcDef{} - -type MsgSvcDef struct { - Name string `json:"name"` - ChainId string `json:"chain_id"` - Description string `json:"description"` - Tags []string `json:"tags"` - Author sdk.AccAddress `json:"author"` - AuthorDescription string `json:"author_description"` - IDLContent string `json:"idl_content"` - Broadcast BroadcastEnum `json:"broadcast"` -} - -func NewMsgSvcDef(name, chainId, description string, tags []string, author sdk.AccAddress, authorDescription, idlContent string, broadcast BroadcastEnum) MsgSvcDef { - return MsgSvcDef{ - Name: name, - ChainId: chainId, - Description: description, - Tags: tags, - Author: author, - AuthorDescription: authorDescription, - IDLContent: idlContent, - Broadcast: broadcast, - } -} - -func (msg MsgSvcDef) Type() string { - return MsgType -} - -func (msg MsgSvcDef) GetSignBytes() []byte { - b, err := msgCdc.MarshalJSON(msg) - if err != nil { - panic(err) - } - return sdk.MustSortJSON(b) -} - -func (msg MsgSvcDef) ValidateBasic() sdk.Error { - if len(msg.ChainId) == 0 { - return ErrInvalidChainId(DefaultCodespace) - } - if len(msg.Name) == 0 { - return ErrInvalidServiceName(DefaultCodespace) - } - if valid, err := validateTags(msg.Tags); !valid { - return err - } - if len(msg.Author) == 0 { - return ErrInvalidAuthor(DefaultCodespace) - } - if !validBroadcastEnum(msg.Broadcast) { - return ErrInvalidBroadcastEnum(DefaultCodespace, msg.Broadcast) - } - - if len(msg.IDLContent) == 0 { - return ErrInvalidIDL(DefaultCodespace, "content is empty") - } - methods, err := protoidl.GetMethods(msg.IDLContent) - if err != nil { - return ErrInvalidIDL(DefaultCodespace, err.Error()) - } - if valid, err := validateMethods(methods); !valid { - return err - } - - return nil -} - -func (msg MsgSvcDef) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Author} -} - -func validateMethods(methods []protoidl.Method) (bool, sdk.Error) { - for _, method := range methods { - if len(method.Name) == 0 { - return false, ErrInvalidMethodName(DefaultCodespace) - } - if _, ok := method.Attributes[outputPrivacy]; ok { - _, err := OutputPrivacyEnumFromString(method.Attributes[outputPrivacy]) - if err != nil { - return false, ErrInvalidOutputPrivacyEnum(DefaultCodespace, method.Attributes[outputPrivacy]) - } - } - if _, ok := method.Attributes[outputCached]; ok { - _, err := OutputCachedEnumFromString(method.Attributes[outputCached]) - if err != nil { - return false, ErrInvalidOutputCachedEnum(DefaultCodespace, method.Attributes[outputCached]) - } - } - } - return true, nil -} - -func validateTags(tags []string) (bool, sdk.Error) { - if len(tags) > maxTagsNum { - return false, ErrMoreTags(DefaultCodespace) - } - if len(tags) > 0 { - for i, tag := range tags { - for _, tag1 := range tags[i+1:] { - if tag == tag1 { - return false, ErrDuplicateTags(DefaultCodespace) - } - } - } - } - return true, nil -} - -func methodToMethodProperty(method protoidl.Method) (methodProperty MethodProperty, err sdk.Error) { - // set default value - opp := NoPrivacy - opc := NoCached - - var err1 error - if _, ok := method.Attributes[outputPrivacy]; ok { - opp, err1 = OutputPrivacyEnumFromString(method.Attributes[outputPrivacy]) - if err1 != nil { - return methodProperty, ErrInvalidOutputPrivacyEnum(DefaultCodespace, method.Attributes[outputPrivacy]) - } - } - if _, ok := method.Attributes[outputCached]; ok { - opc, err1 = OutputCachedEnumFromString(method.Attributes[outputCached]) - if err != nil { - return methodProperty, ErrInvalidOutputCachedEnum(DefaultCodespace, method.Attributes[outputCached]) - } - } - methodProperty = MethodProperty{ - Name: method.Name, - Description: method.Attributes[description], - OutputPrivacy: opp, - OutputCached: opc, - } - return -} diff --git a/modules/iservice/test_common.go b/modules/iservice/test_common.go deleted file mode 100644 index 196ed0b8a..000000000 --- a/modules/iservice/test_common.go +++ /dev/null @@ -1,78 +0,0 @@ -package iservice - -import ( - "testing" - "github.com/cosmos/cosmos-sdk/store" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/libs/log" - "os" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/stake" - sdk "github.com/cosmos/cosmos-sdk/types" - dbm "github.com/tendermint/tendermint/libs/db" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/tendermint/tendermint/crypto" - "encoding/hex" - "github.com/tendermint/tendermint/crypto/ed25519" -) - -var ( - pks = []crypto.PubKey{ - newPubKey("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AFB50"), - newPubKey("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AFB51"), - newPubKey("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AFB52"), - } - addrs = []sdk.AccAddress{ - sdk.AccAddress(pks[0].Address()), - sdk.AccAddress(pks[1].Address()), - sdk.AccAddress(pks[2].Address()), - } - initCoins sdk.Int = sdk.NewInt(200) -) - -func newPubKey(pk string) (res crypto.PubKey) { - pkBytes, err := hex.DecodeString(pk) - if err != nil { - panic(err) - } - var pkEd ed25519.PubKeyEd25519 - copy(pkEd[:], pkBytes[:]) - return pkEd -} - -func createTestCodec() *wire.Codec { - cdc := wire.NewCodec() - sdk.RegisterWire(cdc) - RegisterWire(cdc) - auth.RegisterWire(cdc) - bank.RegisterWire(cdc) - stake.RegisterWire(cdc) - wire.RegisterCrypto(cdc) - return cdc -} - -func createTestInput(t *testing.T) (sdk.Context, Keeper) { - keyAcc := sdk.NewKVStoreKey("acc") - keyStake := sdk.NewKVStoreKey("stake") - keyUpdate := sdk.NewKVStoreKey("update") - keyParams := sdk.NewKVStoreKey("params") - keyIService := sdk.NewKVStoreKey("iservice") - - db := dbm.NewMemDB() - ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(keyAcc, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyStake, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyUpdate, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyIService, sdk.StoreTypeIAVL, db) - - err := ms.LoadLatestVersion() - require.Nil(t, err) - ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewTMLogger(os.Stdout)) - cdc := createTestCodec() - - keeper := NewKeeper(cdc, keyIService, DefaultCodespace) - return ctx, keeper -} diff --git a/modules/iservice/wire.go b/modules/iservice/wire.go deleted file mode 100644 index d3bcf88f7..000000000 --- a/modules/iservice/wire.go +++ /dev/null @@ -1,16 +0,0 @@ -package iservice - -import ( - "github.com/cosmos/cosmos-sdk/wire" -) - -// Register concrete types on wire codec -func RegisterWire(cdc *wire.Codec) { - cdc.RegisterConcrete(MsgSvcDef{}, "iris-hub/iservice/MsgSvcDef", nil) -} - -var msgCdc = wire.NewCodec() - -func init() { - RegisterWire(msgCdc) -} diff --git a/modules/record/keeper.go b/modules/record/keeper.go index 362e9356c..cc581b75b 100644 --- a/modules/record/keeper.go +++ b/modules/record/keeper.go @@ -4,7 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" ) // nolint @@ -15,15 +15,15 @@ type Keeper struct { // The (unexposed) keys used to access the stores from the Context. storeKey sdk.StoreKey - // The wire codec for binary encoding/decoding. - cdc *wire.Codec + // The codec codec for binary encoding/decoding. + cdc *codec.Codec // Reserved codespace codespace sdk.CodespaceType } -// NewKeeper returns a mapper that uses go-wire to (binary) encode and decode record types. -func NewKeeper(cdc *wire.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) Keeper { +// NewKeeper returns a mapper that uses go-codec to (binary) encode and decode record types. +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) Keeper { return Keeper{ storeKey: key, cdc: cdc, @@ -31,8 +31,8 @@ func NewKeeper(cdc *wire.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) K } } -// Returns the go-wire codec. -func (keeper Keeper) WireCodec() *wire.Codec { +// Returns the go-codec codec. +func (keeper Keeper) WireCodec() *codec.Codec { return keeper.cdc } @@ -43,6 +43,6 @@ func KeyRecord(dataHash string) []byte { func (keeper Keeper) AddRecord(ctx sdk.Context, msg MsgSubmitRecord) { store := ctx.KVStore(keeper.storeKey) - bz := keeper.cdc.MustMarshalBinary(msg) + bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(msg) store.Set(KeyRecord(msg.DataHash), bz) } diff --git a/modules/record/msgs.go b/modules/record/msgs.go index 3a898743c..da93fb1d9 100644 --- a/modules/record/msgs.go +++ b/modules/record/msgs.go @@ -45,7 +45,8 @@ func NewMsgSubmitRecord(description string, } // Implements Msg. -func (msg MsgSubmitRecord) Type() string { return MsgType } +func (msg MsgSubmitRecord) Route() string { return MsgType } +func (msg MsgSubmitRecord) Type() string { return "submit_record" } // Implements Msg. func (msg MsgSubmitRecord) ValidateBasic() sdk.Error { diff --git a/modules/record/test_common.go b/modules/record/test_common.go index 583281085..390e62863 100644 --- a/modules/record/test_common.go +++ b/modules/record/test_common.go @@ -8,7 +8,6 @@ import ( "testing" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/stake" "github.com/irisnet/irishub/simulation/mock" "github.com/irisnet/irishub/types" @@ -36,7 +35,7 @@ func getRecord(ctx sdk.Context, keeper Keeper, hash string) (error, MsgSubmitRec store := ctx.KVStore(keeper.storeKey) bz := store.Get(KeyRecord(hash)) msg := MsgSubmitRecord{} - err := keeper.cdc.UnmarshalBinary(bz, &msg) + err := keeper.cdc.UnmarshalBinaryLengthPrefixed(bz, &msg) return err, msg } @@ -59,20 +58,22 @@ func recordEqual(recordA MsgSubmitRecord, recordB MsgSubmitRecord) bool { func getMockApp(t *testing.T, numGenAccs int) (*mock.App, Keeper, stake.Keeper, []sdk.AccAddress, []crypto.PubKey, []crypto.PrivKey) { mapp := mock.NewApp() - stake.RegisterWire(mapp.Cdc) - RegisterWire(mapp.Cdc) + stake.RegisterCodec(mapp.Cdc) + RegisterCodec(mapp.Cdc) - keyStake := sdk.NewKVStoreKey("stake") keyGov := sdk.NewKVStoreKey("gov") keyRecord := sdk.NewKVStoreKey("record") - ck := bank.NewKeeper(mapp.AccountMapper) - sk := stake.NewKeeper(mapp.Cdc, keyStake, ck, mapp.RegisterCodespace(stake.DefaultCodespace)) + sk := stake.NewKeeper( + mapp.Cdc, + mapp.KeyStake, mapp.TkeyStake, + mapp.BankKeeper, mapp.ParamsKeeper.Subspace(stake.DefaultParamspace), + mapp.RegisterCodespace(stake.DefaultCodespace)) rk := NewKeeper(mapp.Cdc, keyRecord, mapp.RegisterCodespace(DefaultCodespace)) mapp.Router().AddRoute("record", []*sdk.KVStoreKey{keyRecord}, NewHandler(rk)) - require.NoError(t, mapp.CompleteSetup([]*sdk.KVStoreKey{keyStake, keyGov, keyRecord})) + require.NoError(t, mapp.CompleteSetup(keyGov, keyRecord)) coin, _ := types.NewDefaultCoinType("iris").ConvertToMinCoin(fmt.Sprintf("%d%s", 1042, "iris")) genAccs, addrs, pubKeys, privKeys := mock.CreateGenAccounts(numGenAccs, sdk.Coins{coin}) diff --git a/modules/record/wire.go b/modules/record/wire.go index 0fa299934..22f2a7c93 100644 --- a/modules/record/wire.go +++ b/modules/record/wire.go @@ -1,13 +1,13 @@ package record import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" ) -// Register concrete types on wire codec -func RegisterWire(cdc *wire.Codec) { +// Register concrete types on codec codec +func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(MsgSubmitRecord{}, "cosmos-sdk/MsgSubmitRecord", nil) } -var msgCdc = wire.NewCodec() +var msgCdc = codec.New() diff --git a/modules/service/binding.go b/modules/service/binding.go new file mode 100644 index 000000000..5fb02b138 --- /dev/null +++ b/modules/service/binding.go @@ -0,0 +1,159 @@ +package service + +import ( + "encoding/json" + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/pkg/errors" +) + +type SvcBinding struct { + DefName string `json:"def_name"` + DefChainID string `json:"def_chain_id"` + BindChainID string `json:"bind_chain_id"` + Provider sdk.AccAddress `json:"provider"` + BindingType BindingType `json:"binding_type"` + Deposit sdk.Coins `json:"deposit"` + Prices []sdk.Coin `json:"price"` + Level Level `json:"level"` + Available bool `json:"available"` + DisableHeight int64 `json:"disable_height"` +} + +type Level struct { + AvgRspTime int64 `json:"avg_rsp_time"` + UsableTime int64 `json:"usable_time"` +} + +// NewSvcBinding returns a new SvcBinding with the provided values. +func NewSvcBinding(defChainID, defName, bindChainID string, provider sdk.AccAddress, bindingType BindingType, deposit sdk.Coins, prices []sdk.Coin, level Level, available bool, disableHeight int64) SvcBinding { + return SvcBinding{ + DefChainID: defChainID, + DefName: defName, + BindChainID: bindChainID, + Provider: provider, + BindingType: bindingType, + Deposit: deposit, + Prices: prices, + Level: level, + Available: available, + DisableHeight: disableHeight, + } +} + +func SvcBindingEqual(bindingA, bindingB SvcBinding) bool { + if bindingA.DefChainID == bindingB.DefChainID && + bindingA.DefName == bindingB.DefName && + bindingA.BindChainID == bindingB.BindChainID && + bindingA.Provider.String() == bindingB.Provider.String() && + bindingA.BindingType == bindingB.BindingType && + bindingA.Deposit.IsEqual(bindingB.Deposit) && + bindingA.Level.AvgRspTime == bindingB.Level.AvgRspTime && + bindingA.Level.UsableTime == bindingB.Level.UsableTime && + len(bindingA.Prices) == len(bindingB.Prices) && + bindingA.Available == bindingB.Available && + bindingA.DisableHeight == bindingB.DisableHeight { + for j, prices := range bindingA.Prices { + if !prices.IsEqual(bindingB.Prices[j]) { + return false + } + } + return true + } + return false +} + +// is valid level? +func validLevel(lv Level) bool { + if lv.AvgRspTime > 0 && lv.UsableTime > 0 && lv.UsableTime <= 10000 { + return true + } + return false +} + +// is valid update level? +func validUpdateLevel(lv Level) bool { + if lv.AvgRspTime < 0 { + return false + } + if lv.UsableTime < 0 || lv.UsableTime > 10000 { + return false + } + return true +} + +func (svcBind SvcBinding) isValid() bool { + return svcBind.Available +} + +type BindingType byte + +const ( + Global BindingType = 0x01 + Local BindingType = 0x02 +) + +// String to BindingType byte, Returns ff if invalid. +func BindingTypeFromString(str string) (BindingType, error) { + switch str { + case "Local": + return Local, nil + case "Global": + return Global, nil + default: + return BindingType(0xff), errors.Errorf("'%s' is not a valid binding type", str) + } +} + +// is defined BindingType? +func validBindingType(bt BindingType) bool { + if bt == Local || + bt == Global { + return true + } + return false +} + +// For Printf / Sprintf, returns bech32 when using %s +func (bt BindingType) Format(s fmt.State, verb rune) { + switch verb { + case 's': + s.Write([]byte(fmt.Sprintf("%s", bt.String()))) + default: + s.Write([]byte(fmt.Sprintf("%v", byte(bt)))) + } +} + +// Turns BindingType byte to String +func (bt BindingType) String() string { + switch bt { + case Local: + return "Local" + case Global: + return "Global" + default: + return "" + } +} + +// Marshals to JSON using string +func (bt BindingType) MarshalJSON() ([]byte, error) { + return json.Marshal(bt.String()) +} + +// Unmarshals from JSON assuming Bech32 encoding +func (bt *BindingType) UnmarshalJSON(data []byte) error { + var s string + err := json.Unmarshal(data, &s) + if err != nil { + return nil + } + + bz2, err := BindingTypeFromString(s) + if err != nil { + return err + } + *bt = bz2 + return nil +} diff --git a/modules/iservice/types.go b/modules/service/definition.go similarity index 68% rename from modules/iservice/types.go rename to modules/service/definition.go index c56c9c27c..a808f8935 100644 --- a/modules/iservice/types.go +++ b/modules/service/definition.go @@ -1,11 +1,43 @@ -package iservice +package service import ( - "github.com/pkg/errors" "fmt" "encoding/json" + + "github.com/pkg/errors" + sdk "github.com/cosmos/cosmos-sdk/types" ) +type SvcDef struct { + Name string `json:"name"` + ChainId string `json:"chain_id"` + Description string `json:"description"` + Tags []string `json:"tags"` + Author sdk.AccAddress `json:"author"` + AuthorDescription string `json:"author_description"` + IDLContent string `json:"idl_content"` +} + +type MethodProperty struct { + ID int `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + OutputPrivacy OutputPrivacyEnum `json:"output_privacy"` + OutputCached OutputCachedEnum `json:"output_cached"` +} + +func NewSvcDef(name, chainId, description string, tags []string, author sdk.AccAddress, authorDescription, idlContent string) SvcDef { + return SvcDef{ + Name: name, + ChainId: chainId, + Description: description, + Tags: tags, + Author: author, + AuthorDescription: authorDescription, + IDLContent: idlContent, + } +} + type OutputPrivacyEnum byte const ( @@ -20,56 +52,49 @@ const ( NoCached OutputCachedEnum = 0x02 ) -type BroadcastEnum byte +type MessagingType byte const ( - Broadcast BroadcastEnum = 0x01 - Unicast BroadcastEnum = 0x02 + Unicast MessagingType = 0x01 + Multicast MessagingType = 0x02 ) -type MethodProperty struct { - Name string `json:"name"` - Description string `json:"description"` - OutputPrivacy OutputPrivacyEnum `json:"output_privacy"` - OutputCached OutputCachedEnum `json:"output_cached"` -} - -// String to broadcastEnum byte, Returns ff if invalid. -func BroadcastEnumFromString(str string) (BroadcastEnum, error) { +// String to messagingType byte, Returns ff if invalid. +func MessagingTypeFromString(str string) (MessagingType, error) { switch str { - case "Broadcast": - return Broadcast, nil + case "Multicast": + return Multicast, nil case "Unicast": return Unicast, nil default: - return BroadcastEnum(0xff), errors.Errorf("'%s' is not a valid broadcastEnum type", str) + return MessagingType(0xff), errors.Errorf("'%s' is not a valid messaging type", str) } } -// is defined BroadcastEnum? -func validBroadcastEnum(be BroadcastEnum) bool { - if be == Broadcast || - be == Unicast { +// is defined messagingType? +func validMessagingType(mt MessagingType) bool { + if mt == Multicast || + mt == Unicast { return true } return false } // For Printf / Sprintf, returns bech32 when using %s -func (be BroadcastEnum) Format(s fmt.State, verb rune) { +func (mt MessagingType) Format(s fmt.State, verb rune) { switch verb { case 's': - s.Write([]byte(fmt.Sprintf("%s", be.String()))) + s.Write([]byte(fmt.Sprintf("%s", mt.String()))) default: - s.Write([]byte(fmt.Sprintf("%v", byte(be)))) + s.Write([]byte(fmt.Sprintf("%v", byte(mt)))) } } -// Turns BroadcastEnum byte to String -func (be BroadcastEnum) String() string { - switch be { - case Broadcast: - return "Broadcast" +// Turns MessagingType byte to String +func (mt MessagingType) String() string { + switch mt { + case Multicast: + return "Multicast" case Unicast: return "Unicast" default: @@ -78,23 +103,23 @@ func (be BroadcastEnum) String() string { } // Marshals to JSON using string -func (be BroadcastEnum) MarshalJSON() ([]byte, error) { - return json.Marshal(be.String()) +func (mt MessagingType) MarshalJSON() ([]byte, error) { + return json.Marshal(mt.String()) } // Unmarshals from JSON assuming Bech32 encoding -func (be *BroadcastEnum) UnmarshalJSON(data []byte) error { +func (mt *MessagingType) UnmarshalJSON(data []byte) error { var s string err := json.Unmarshal(data, &s) if err != nil { return nil } - bz2, err := BroadcastEnumFromString(s) + bz2, err := MessagingTypeFromString(s) if err != nil { return err } - *be = bz2 + *mt = bz2 return nil } diff --git a/modules/service/error.go b/modules/service/error.go new file mode 100644 index 000000000..b65c9c6f1 --- /dev/null +++ b/modules/service/error.go @@ -0,0 +1,128 @@ +package service + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "fmt" +) + +const ( + DefaultCodespace sdk.CodespaceType = 6 + + CodeInvalidIDL sdk.CodeType = 100 + CodeSvcDefExists sdk.CodeType = 101 + CodeSvcDefNotExists sdk.CodeType = 102 + CodeInvalidOutputPrivacyEnum sdk.CodeType = 103 + CodeInvalidOutputCachedEnum sdk.CodeType = 104 + CodeInvalidServiceName sdk.CodeType = 105 + CodeInvalidChainId sdk.CodeType = 106 + CodeInvalidAuthor sdk.CodeType = 107 + CodeInvalidMethodName sdk.CodeType = 108 + + CodeSvcBindingExists sdk.CodeType = 109 + CodeSvcBindingNotExists sdk.CodeType = 110 + CodeInvalidDefChainId sdk.CodeType = 111 + CodeInvalidBindingType sdk.CodeType = 112 + CodeInvalidLevel sdk.CodeType = 113 + CodeInvalidPriceCount sdk.CodeType = 114 + CodeInvalidRefundDeposit sdk.CodeType = 115 + CodeLtMinProviderDeposit sdk.CodeType = 116 + CodeInvalidDisable sdk.CodeType = 117 + CodeInvalidEnable sdk.CodeType = 118 +) + +func codeToDefaultMsg(code sdk.CodeType) string { + switch code { + case CodeInvalidIDL: + return "The IDL file cannot be parsed" + default: + return sdk.CodeToDefaultMsg(code) + } +} + +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) +} + +func ErrSvcDefExists(codespace sdk.CodespaceType, defChainId, svcDefName string) sdk.Error { + return sdk.NewError(codespace, CodeSvcDefExists, fmt.Sprintf("service definition name %s already exists in %s", svcDefName, defChainId)) +} + +func ErrSvcDefNotExists(codespace sdk.CodespaceType, defChainId, svcDefName string) sdk.Error { + return sdk.NewError(codespace, CodeSvcDefNotExists, fmt.Sprintf("service definition name %s is not existed in %s", svcDefName, defChainId)) +} + +func ErrInvalidIDL(codespace sdk.CodespaceType, msg string) sdk.Error { + return sdk.NewError(codespace, CodeInvalidIDL, fmt.Sprintf("The IDL content cannot be parsed, %s", msg)) +} + +func ErrInvalidOutputPrivacyEnum(codespace sdk.CodespaceType, value string) sdk.Error { + return sdk.NewError(codespace, CodeInvalidOutputPrivacyEnum, fmt.Sprintf("invalid OutputPrivacyEnum %s", value)) +} + +func ErrInvalidOutputCachedEnum(codespace sdk.CodespaceType, value string) sdk.Error { + return sdk.NewError(codespace, CodeInvalidOutputCachedEnum, fmt.Sprintf("invalid OutputCachedEnum %s", value)) +} + +func ErrInvalidServiceName(codespace sdk.CodespaceType, msg string) sdk.Error { + return sdk.NewError(codespace, CodeInvalidServiceName, fmt.Sprintf("invalid service name %s, must contain alphanumeric characters, _ and - only,length greater than 0 and less than or equal to 128", msg)) +} + +func ErrInvalidChainId(codespace sdk.CodespaceType) sdk.Error { + return sdk.NewError(codespace, CodeInvalidChainId, fmt.Sprintf("chainId is empty")) +} + +func ErrInvalidAuthor(codespace sdk.CodespaceType) sdk.Error { + return sdk.NewError(codespace, CodeInvalidAuthor, fmt.Sprintf("author is empty")) +} + +func ErrInvalidMethodName(codespace sdk.CodespaceType) sdk.Error { + return sdk.NewError(codespace, CodeInvalidMethodName, fmt.Sprintf("method name is empty")) +} + +func ErrInvalidDefChainId(codespace sdk.CodespaceType) sdk.Error { + return sdk.NewError(codespace, CodeInvalidDefChainId, fmt.Sprintf("def-chain-id is empty")) +} + +func ErrSvcBindingExists(codespace sdk.CodespaceType) sdk.Error { + return sdk.NewError(codespace, CodeSvcBindingExists, fmt.Sprintf("service binding already exists")) +} + +func ErrSvcBindingNotExists(codespace sdk.CodespaceType) sdk.Error { + return sdk.NewError(codespace, CodeSvcBindingNotExists, fmt.Sprintf("service binding is not existed")) +} + +func ErrInvalidBindingType(codespace sdk.CodespaceType, bindingType BindingType) sdk.Error { + return sdk.NewError(codespace, CodeInvalidBindingType, fmt.Sprintf("invalid binding type %s", bindingType)) +} + +func ErrInvalidLevel(codespace sdk.CodespaceType, level Level) sdk.Error { + return sdk.NewError(codespace, CodeInvalidLevel, fmt.Sprintf("invalid level %v, avg_rsp_time and usable_time must be positive integer and usable_time limit to 10000", level)) +} + +func ErrInvalidPriceCount(codespace sdk.CodespaceType, priceCount int, methodCount int) sdk.Error { + return sdk.NewError(codespace, CodeInvalidPriceCount, fmt.Sprintf("invalid prices count %d, but methods count is %d", priceCount, methodCount)) +} + +func ErrRefundDeposit(codespace sdk.CodespaceType, msg string) sdk.Error { + return sdk.NewError(codespace, CodeInvalidRefundDeposit, fmt.Sprintf("can't refund deposit, %s", msg)) +} + +func ErrDisable(codespace sdk.CodespaceType, msg string) sdk.Error { + return sdk.NewError(codespace, CodeInvalidDisable, fmt.Sprintf("can't disable, %s", msg)) +} + +func ErrEnable(codespace sdk.CodespaceType, msg string) sdk.Error { + return sdk.NewError(codespace, CodeInvalidEnable, fmt.Sprintf("can't enable, %s", msg)) +} + +func ErrLtMinProviderDeposit(codespace sdk.CodespaceType, coins sdk.Coins) sdk.Error { + return sdk.NewError(codespace, CodeLtMinProviderDeposit, fmt.Sprintf("deposit amount must be equal or greater than %s", coins.String())) +} diff --git a/modules/service/genesis.go b/modules/service/genesis.go new file mode 100644 index 000000000..f842662bc --- /dev/null +++ b/modules/service/genesis.go @@ -0,0 +1,67 @@ +package service + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "fmt" + "github.com/irisnet/irishub/types" + "github.com/irisnet/irishub/iparam" + "github.com/irisnet/irishub/modules/service/params" +) + +// GenesisState - all service state that must be provided at genesis +type GenesisState struct { + MaxRequestTimeout int64 + MinProviderDeposit sdk.Coins +} + +func NewGenesisState(maxRequestTimeout int64, minProviderDeposit sdk.Coins) GenesisState { + return GenesisState{ + MaxRequestTimeout: maxRequestTimeout, + MinProviderDeposit: minProviderDeposit, + } +} + +// InitGenesis - store genesis parameters +func InitGenesis(ctx sdk.Context, data GenesisState) { + iparam.InitGenesisParameter(&serviceparams.MaxRequestTimeoutParameter, ctx, data.MaxRequestTimeout) + iparam.InitGenesisParameter(&serviceparams.MinProviderDepositParameter, ctx, data.MinProviderDeposit) +} + +// WriteGenesis - output genesis parameters +func WriteGenesis(ctx sdk.Context) GenesisState { + maxRequestTimeout := serviceparams.GetMaxRequestTimeout(ctx) + minProviderDeposit := serviceparams.GetMinProviderDeposit(ctx) + + return GenesisState{ + MaxRequestTimeout: maxRequestTimeout, + MinProviderDeposit: minProviderDeposit, + } +} + +// get raw genesis raw message for testing +func DefaultGenesisState() GenesisState { + Denom := "iris" + IrisCt := types.NewDefaultCoinType(Denom) + minDeposit, err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", 1000, Denom)) + if err != nil { + panic(err) + } + return GenesisState{ + MaxRequestTimeout: 100, + MinProviderDeposit: sdk.Coins{minDeposit}, + } +} + +// get raw genesis raw message for testing +func DefaultGenesisStateForTest() GenesisState { + Denom := "iris" + IrisCt := types.NewDefaultCoinType(Denom) + minDeposit, err := IrisCt.ConvertToMinCoin(fmt.Sprintf("%d%s", 10, Denom)) + if err != nil { + panic(err) + } + return GenesisState{ + MaxRequestTimeout: 10, + MinProviderDeposit: sdk.Coins{minDeposit}, + } +} diff --git a/modules/service/handler.go b/modules/service/handler.go new file mode 100644 index 000000000..b64647758 --- /dev/null +++ b/modules/service/handler.go @@ -0,0 +1,114 @@ +package service + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/irisnet/irishub/modules/service/tags" +) + +// handle all "service" type messages. +func NewHandler(k Keeper) sdk.Handler { + return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { + switch msg := msg.(type) { + case MsgSvcDef: + return handleMsgSvcDef(ctx, k, msg) + case MsgSvcBind: + return handleMsgSvcBind(ctx, k, msg) + case MsgSvcBindingUpdate: + return handleMsgSvcBindUpdate(ctx, k, msg) + case MsgSvcDisable: + return handleMsgSvcDisable(ctx, k, msg) + case MsgSvcEnable: + return handleMsgSvcEnable(ctx, k, msg) + case MsgSvcRefundDeposit: + return handleMsgSvcRefundDeposit(ctx, k, msg) + default: + return sdk.ErrTxDecode("invalid message parse in service module").Result() + } + } +} +func handleMsgSvcDef(ctx sdk.Context, k Keeper, msg MsgSvcDef) sdk.Result { + _, found := k.GetServiceDefinition(ctx, msg.ChainId, msg.Name) + if found { + return ErrSvcDefExists(k.Codespace(), msg.ChainId, msg.Name).Result() + } + k.AddServiceDefinition(ctx, msg.SvcDef) + err := k.AddMethods(ctx, msg.SvcDef) + if err != nil { + return err.Result() + } + resTags := sdk.NewTags( + tags.Action, tags.ActionSvcDef, + ) + return sdk.Result{ + Tags: resTags, + } +} + +func handleMsgSvcBind(ctx sdk.Context, k Keeper, msg MsgSvcBind) sdk.Result { + svcBinding := NewSvcBinding(msg.DefChainID, msg.DefName, msg.BindChainID, msg.Provider, msg.BindingType, + msg.Deposit, msg.Prices, msg.Level, true, 0) + err, _ := k.AddServiceBinding(ctx, svcBinding) + if err != nil { + return err.Result() + } + resTags := sdk.NewTags( + tags.Action, tags.ActionSvcBind, + ) + return sdk.Result{ + Tags: resTags, + } +} + +func handleMsgSvcBindUpdate(ctx sdk.Context, k Keeper, msg MsgSvcBindingUpdate) sdk.Result { + svcBinding := NewSvcBinding(msg.DefChainID, msg.DefName, msg.BindChainID, msg.Provider, msg.BindingType, + msg.Deposit, msg.Prices, msg.Level, false, 0) + err, _ := k.UpdateServiceBinding(ctx, svcBinding) + if err != nil { + return err.Result() + } + resTags := sdk.NewTags( + tags.Action, tags.ActionSvcBindUpdate, + ) + return sdk.Result{ + Tags: resTags, + } +} + +func handleMsgSvcDisable(ctx sdk.Context, k Keeper, msg MsgSvcDisable) sdk.Result { + err, _ := k.Disable(ctx, msg.DefChainID, msg.DefName, msg.BindChainID, msg.Provider) + if err != nil { + return err.Result() + } + resTags := sdk.NewTags( + tags.Action, tags.ActionSvcDisable, + ) + return sdk.Result{ + Tags: resTags, + } +} + +func handleMsgSvcEnable(ctx sdk.Context, k Keeper, msg MsgSvcEnable) sdk.Result { + err, _ := k.Enable(ctx, msg.DefChainID, msg.DefName, msg.BindChainID, msg.Provider, msg.Deposit) + if err != nil { + return err.Result() + } + resTags := sdk.NewTags( + tags.Action, tags.ActionSvcEnable, + ) + return sdk.Result{ + Tags: resTags, + } +} + +func handleMsgSvcRefundDeposit(ctx sdk.Context, k Keeper, msg MsgSvcRefundDeposit) sdk.Result { + err, _ := k.RefundDeposit(ctx, msg.DefChainID, msg.DefName, msg.BindChainID, msg.Provider) + if err != nil { + return err.Result() + } + resTags := sdk.NewTags( + tags.Action, tags.ActionSvcRefundDeposit, + ) + return sdk.Result{ + Tags: resTags, + } +} diff --git a/modules/service/keeper.go b/modules/service/keeper.go new file mode 100644 index 000000000..bd6bbc557 --- /dev/null +++ b/modules/service/keeper.go @@ -0,0 +1,267 @@ +package service + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/irisnet/irishub/tools/protoidl" + "github.com/cosmos/cosmos-sdk/x/bank" + "fmt" + "github.com/irisnet/irishub/modules/service/params" +) + +type Keeper struct { + storeKey sdk.StoreKey + cdc *codec.Codec + ck bank.Keeper + + // codespace + codespace sdk.CodespaceType +} + +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, ck bank.Keeper, codespace sdk.CodespaceType) Keeper { + keeper := Keeper{ + storeKey: key, + cdc: cdc, + ck: ck, + codespace: codespace, + } + return keeper +} + +// return the codespace +func (k Keeper) Codespace() sdk.CodespaceType { + return k.codespace +} + +func (k Keeper) AddServiceDefinition(ctx sdk.Context, svcDef SvcDef) { + kvStore := ctx.KVStore(k.storeKey) + + svcDefBytes, err := k.cdc.MarshalBinaryLengthPrefixed(svcDef) + if err != nil { + panic(err) + } + + kvStore.Set(GetServiceDefinitionKey(svcDef.ChainId, svcDef.Name), svcDefBytes) +} + +func (k Keeper) AddMethods(ctx sdk.Context, svcDef SvcDef) sdk.Error { + methods, err := protoidl.GetMethods(svcDef.IDLContent) + if err != nil { + panic(err) + } + kvStore := ctx.KVStore(k.storeKey) + for index, method := range methods { + methodProperty, err := methodToMethodProperty(index+1, method) + if err != nil { + return err + } + methodBytes := k.cdc.MustMarshalBinaryLengthPrefixed(methodProperty) + kvStore.Set(GetMethodPropertyKey(svcDef.ChainId, svcDef.Name, methodProperty.ID), methodBytes) + } + return nil +} + +func (k Keeper) GetServiceDefinition(ctx sdk.Context, chainId, name string) (svcDef SvcDef, found bool) { + kvStore := ctx.KVStore(k.storeKey) + + serviceDefBytes := kvStore.Get(GetServiceDefinitionKey(chainId, name)) + if serviceDefBytes != nil { + var serviceDef SvcDef + k.cdc.MustUnmarshalBinaryLengthPrefixed(serviceDefBytes, &serviceDef) + return serviceDef, true + } + return svcDef, false +} + +// Gets all the methods in a specific service +func (k Keeper) GetMethods(ctx sdk.Context, chainId, name string) sdk.Iterator { + store := ctx.KVStore(k.storeKey) + return sdk.KVStorePrefixIterator(store, GetMethodsSubspaceKey(chainId, name)) +} + +func (k Keeper) AddServiceBinding(ctx sdk.Context, svcBinding SvcBinding) (sdk.Error, bool) { + kvStore := ctx.KVStore(k.storeKey) + _, found := k.GetServiceDefinition(ctx, svcBinding.DefChainID, svcBinding.DefName) + if !found { + return ErrSvcDefNotExists(k.Codespace(), svcBinding.DefChainID, svcBinding.DefName), false + } + + _, found = k.GetServiceBinding(ctx, svcBinding.DefChainID, svcBinding.DefName, svcBinding.BindChainID, svcBinding.Provider) + if found { + return ErrSvcBindingExists(k.Codespace()), false + } + + minDeposit := serviceparams.GetMinProviderDeposit(ctx) + if !svcBinding.Deposit.IsAllGTE(minDeposit) { + return ErrLtMinProviderDeposit(k.Codespace(), minDeposit), false + } + + err := k.validateMethodPrices(ctx, svcBinding) + if err != nil { + return err, false + } + + // Subtract coins from provider's account + _, _, err = k.ck.SubtractCoins(ctx, svcBinding.Provider, svcBinding.Deposit) + if err != nil { + return err, false + } + + svcBindingBytes := k.cdc.MustMarshalBinaryLengthPrefixed(svcBinding) + kvStore.Set(GetServiceBindingKey(svcBinding.DefChainID, svcBinding.DefName, svcBinding.BindChainID, svcBinding.Provider), svcBindingBytes) + return nil, true +} + +func (k Keeper) GetServiceBinding(ctx sdk.Context, defChainID, defName, bindChainID string, provider sdk.AccAddress) (svcBinding SvcBinding, found bool) { + kvStore := ctx.KVStore(k.storeKey) + + svcBindingBytes := kvStore.Get(GetServiceBindingKey(defChainID, defName, bindChainID, provider)) + if svcBindingBytes != nil { + var svcBinding SvcBinding + k.cdc.MustUnmarshalBinaryLengthPrefixed(svcBindingBytes, &svcBinding) + return svcBinding, true + } + return svcBinding, false +} + +func (k Keeper) UpdateServiceBinding(ctx sdk.Context, svcBinding SvcBinding) (sdk.Error, bool) { + kvStore := ctx.KVStore(k.storeKey) + oldBinding, found := k.GetServiceBinding(ctx, svcBinding.DefChainID, svcBinding.DefName, svcBinding.BindChainID, svcBinding.Provider) + if !found { + return ErrSvcBindingNotExists(k.Codespace()), false + } + + if len(svcBinding.Prices) > 0 { + err := k.validateMethodPrices(ctx, svcBinding) + if err != nil { + return err, false + } + oldBinding.Prices = svcBinding.Prices + } + + if svcBinding.BindingType != 0x00 { + oldBinding.BindingType = svcBinding.BindingType + } + + // Add coins to svcBinding deposit + if svcBinding.Deposit.IsNotNegative() { + oldBinding.Deposit = oldBinding.Deposit.Plus(svcBinding.Deposit) + } + + // Subtract coins from provider's account + _, _, err := k.ck.SubtractCoins(ctx, svcBinding.Provider, svcBinding.Deposit) + if err != nil { + return err, false + } + + if svcBinding.Level.UsableTime != 0 { + oldBinding.Level.UsableTime = svcBinding.Level.UsableTime + } + if svcBinding.Level.AvgRspTime != 0 { + oldBinding.Level.AvgRspTime = svcBinding.Level.AvgRspTime + } + + svcBindingBytes := k.cdc.MustMarshalBinaryLengthPrefixed(oldBinding) + kvStore.Set(GetServiceBindingKey(svcBinding.DefChainID, svcBinding.DefName, svcBinding.BindChainID, svcBinding.Provider), svcBindingBytes) + return nil, true +} + +func (k Keeper) Disable(ctx sdk.Context, defChainID, defName, bindChainID string, provider sdk.AccAddress) (sdk.Error, bool) { + kvStore := ctx.KVStore(k.storeKey) + binding, found := k.GetServiceBinding(ctx, defChainID, defName, bindChainID, provider) + if !found { + return ErrSvcBindingNotExists(k.Codespace()), false + } + + if !binding.Available { + return ErrDisable(k.Codespace(), "service binding is unavailable"), false + } + binding.Available = false + binding.DisableHeight = ctx.BlockHeader().Height + svcBindingBytes := k.cdc.MustMarshalBinaryLengthPrefixed(binding) + kvStore.Set(GetServiceBindingKey(binding.DefChainID, binding.DefName, binding.BindChainID, binding.Provider), svcBindingBytes) + return nil, true +} + +func (k Keeper) Enable(ctx sdk.Context, defChainID, defName, bindChainID string, provider sdk.AccAddress, deposit sdk.Coins) (sdk.Error, bool) { + kvStore := ctx.KVStore(k.storeKey) + binding, found := k.GetServiceBinding(ctx, defChainID, defName, bindChainID, provider) + if !found { + return ErrSvcBindingNotExists(k.Codespace()), false + } + + if binding.Available { + return ErrEnable(k.Codespace(), "service binding is available"), false + } + + // Add coins to svcBinding deposit + if deposit.IsNotNegative() { + binding.Deposit = binding.Deposit.Plus(deposit) + } + + minDeposit := serviceparams.GetMinProviderDeposit(ctx) + if !binding.Deposit.IsAllGTE(minDeposit) { + return ErrLtMinProviderDeposit(k.Codespace(), minDeposit.Minus(binding.Deposit).Plus(deposit)), false + } + + // Subtract coins from provider's account + _, _, err := k.ck.SubtractCoins(ctx, binding.Provider, deposit) + if err != nil { + return err, false + } + + binding.Available = true + binding.DisableHeight = 0 + svcBindingBytes := k.cdc.MustMarshalBinaryLengthPrefixed(binding) + kvStore.Set(GetServiceBindingKey(binding.DefChainID, binding.DefName, binding.BindChainID, binding.Provider), svcBindingBytes) + return nil, true +} + +func (k Keeper) RefundDeposit(ctx sdk.Context, defChainID, defName, bindChainID string, provider sdk.AccAddress) (sdk.Error, bool) { + kvStore := ctx.KVStore(k.storeKey) + binding, found := k.GetServiceBinding(ctx, defChainID, defName, bindChainID, provider) + if !found { + return ErrSvcBindingNotExists(k.Codespace()), false + } + + if binding.Available { + return ErrRefundDeposit(k.Codespace(), "can't refund from a available service binding"), false + } + + if binding.Deposit.IsZero() { + return ErrRefundDeposit(k.Codespace(), "service binding deposit is zero"), false + } + + height := ctx.BlockHeader().Height + refundHeight := binding.DisableHeight + int64(serviceparams.GetMaxRequestTimeout(ctx)) + if refundHeight >= height { + return ErrRefundDeposit(k.Codespace(), fmt.Sprintf("you can refund deposit util block height greater than %d", refundHeight)), false + } + + // Add coins to provider's account + _, _, err := k.ck.AddCoins(ctx, binding.Provider, binding.Deposit) + if err != nil { + return err, false + } + + binding.Deposit = sdk.Coins{} + + svcBindingBytes := k.cdc.MustMarshalBinaryLengthPrefixed(binding) + kvStore.Set(GetServiceBindingKey(binding.DefChainID, binding.DefName, binding.BindChainID, binding.Provider), svcBindingBytes) + return nil, true +} + +func (k Keeper) validateMethodPrices(ctx sdk.Context, svcBinding SvcBinding) sdk.Error { + methodIterator := k.GetMethods(ctx, svcBinding.DefChainID, svcBinding.DefName) + var methods []MethodProperty + for ; methodIterator.Valid(); methodIterator.Next() { + var method MethodProperty + k.cdc.MustUnmarshalBinaryLengthPrefixed(methodIterator.Value(), &method) + methods = append(methods, method) + } + + if len(methods) != len(svcBinding.Prices) { + return ErrInvalidPriceCount(k.Codespace(), len(svcBinding.Prices), len(methods)) + } + return nil +} diff --git a/modules/service/keeper_keys.go b/modules/service/keeper_keys.go new file mode 100644 index 000000000..f1fcefbd1 --- /dev/null +++ b/modules/service/keeper_keys.go @@ -0,0 +1,66 @@ +package service + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var ( + // the separator for string key + emptyByte = []byte{0x00} + + // Keys for store prefixes + serviceDefinitionKey = []byte{0x01} + methodPropertyKey = []byte{0x02} + bindingPropertyKey = []byte{0x03} +) + +func GetServiceDefinitionKey(chainId, name string) []byte { + return append(append(append( + serviceDefinitionKey, + []byte(chainId)...), + emptyByte...), + []byte(name)...) +} + +// id can not zero +func GetMethodPropertyKey(chainId, serviceName string, id int) []byte { + return append(append(append(append(append( + methodPropertyKey, + []byte(chainId)...), + emptyByte...), + []byte(serviceName)...), + emptyByte...), + []byte(string(id))...) +} + +// Key for getting all methods on a service from the store +func GetMethodsSubspaceKey(chainId, serviceName string) []byte { + return append(append(append(append( + methodPropertyKey, + []byte(chainId)...), + emptyByte...), + []byte(serviceName)...), + emptyByte...) +} + +func GetServiceBindingKey(defChainId, name, bindChainId string, provider sdk.AccAddress) []byte { + return append(append(append(append(append(append(append( + bindingPropertyKey, + []byte(defChainId)...), + emptyByte...), + []byte(name)...), + emptyByte...), + []byte(bindChainId)...), + emptyByte...), + []byte(provider.String())...) +} + +// Key for getting all methods on a service from the store +func GetBindingsSubspaceKey(chainId, serviceName string) []byte { + return append(append(append(append( + bindingPropertyKey, + []byte(chainId)...), + emptyByte...), + []byte(serviceName)...), + emptyByte...) +} diff --git a/modules/service/keeper_test.go b/modules/service/keeper_test.go new file mode 100644 index 000000000..744d3654b --- /dev/null +++ b/modules/service/keeper_test.go @@ -0,0 +1,97 @@ +package service + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/stretchr/testify/require" +) + +func TestKeeper_service_Definition(t *testing.T) { + mapp, keeper, _, addrs, _, _ := getMockApp(t, 3) + SortAddresses(addrs) + mapp.BeginBlock(abci.RequestBeginBlock{}) + ctx := mapp.BaseApp.NewContext(false, abci.Header{}) + amount, _ := sdk.NewIntFromString("1100000000000000000000") + keeper.ck.AddCoins(ctx, addrs[1], sdk.Coins{sdk.NewCoin("iris-atto", amount)}) + + serviceDef := NewSvcDef("myService", + "testnet", + "the service for unit test", + []string{"test", "tutorial"}, + addrs[0], + "unit test author", + idlContent) + + keeper.AddServiceDefinition(ctx, serviceDef) + serviceDefB, _ := keeper.GetServiceDefinition(ctx, "testnet", "myService") + + require.Equal(t, serviceDefB.IDLContent, idlContent) + require.Equal(t, serviceDefB.Name, "myService") + + // test methods + keeper.AddMethods(ctx, serviceDef) + iterator := keeper.GetMethods(ctx, "testnet", "myService") + require.True(t, iterator.Valid()) + for ; ; iterator.Next() { + var method MethodProperty + if !iterator.Valid() { + break + } + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &method) + require.Equal(t, method.Name, "SayHello") + require.Equal(t, method.Description, "sayHello") + require.Equal(t, method.OutputPrivacy.String(), "NoPrivacy") + require.Equal(t, method.OutputCached.String(), "NoCached") + } + + // test binding + amount1, _ := sdk.NewIntFromString("1000000000000000000000") + svcBinding := NewSvcBinding("testnet", "myService", "testnet", + addrs[1], Global, sdk.Coins{sdk.NewCoin("iris-atto", amount1)}, []sdk.Coin{{"iris", sdk.NewInt(100)}}, + Level{AvgRspTime: 10000, UsableTime: 9999}, true, 0) + err, _ := keeper.AddServiceBinding(ctx, svcBinding) + require.NoError(t, err) + + amount2, _ := sdk.NewIntFromString("100000000000000000000") + require.True(t, keeper.ck.HasCoins(ctx, addrs[1], sdk.Coins{sdk.NewCoin("iris-atto", amount2)})) + + gotSvcBinding, found := keeper.GetServiceBinding(ctx, svcBinding.DefChainID, svcBinding.DefName, svcBinding.BindChainID, svcBinding.Provider) + require.True(t, found) + require.True(t, SvcBindingEqual(svcBinding, gotSvcBinding)) + + // test binding update + svcBindingUpdate := NewSvcBinding("testnet", "myService", "testnet", + addrs[1], Global, sdk.Coins{sdk.NewCoin("iris-atto", sdk.NewInt(100))}, []sdk.Coin{{"iris", sdk.NewInt(100)}}, + Level{AvgRspTime: 10000, UsableTime: 9999},true,0) + err, _ = keeper.UpdateServiceBinding(ctx, svcBindingUpdate) + require.NoError(t, err) + + require.True(t, keeper.ck.HasCoins(ctx, addrs[1], sdk.Coins{sdk.NewCoin("iris", sdk.NewInt(0))})) + + upSvcBinding, found := keeper.GetServiceBinding(ctx, svcBinding.DefChainID, svcBinding.DefName, svcBinding.BindChainID, svcBinding.Provider) + require.True(t, found) + require.True(t, upSvcBinding.Deposit.IsEqual(gotSvcBinding.Deposit.Plus(svcBindingUpdate.Deposit))) +} + +const idlContent = ` + syntax = "proto3"; + + // The greeting service definition. + service Greeter { + //@Attribute description:sayHello + //@Attribute output_privacy:NoPrivacy + //@Attribute output_cached:NoCached + rpc SayHello (HelloRequest) returns (HelloReply) {} + } + + // The request message containing the user's name. + message HelloRequest { + string name = 1; + } + + // The response message containing the greetings + message HelloReply { + string message = 1; + }` diff --git a/modules/service/msgs.go b/modules/service/msgs.go new file mode 100644 index 000000000..fdddb3c7b --- /dev/null +++ b/modules/service/msgs.go @@ -0,0 +1,440 @@ +package service + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/irisnet/irishub/tools/protoidl" + "regexp" +) + +const ( + // name to idetify transaction types + MsgType = "service" + outputPrivacy = "output_privacy" + outputCached = "output_cached" + description = "description" +) + +var _ sdk.Msg = MsgSvcDef{} + +//______________________________________________________________________ + +// MsgSvcDef - struct for define a service +type MsgSvcDef struct { + SvcDef +} + +func NewMsgSvcDef(name, chainId, description string, tags []string, author sdk.AccAddress, authorDescription, idlContent string) MsgSvcDef { + return MsgSvcDef{ + SvcDef{ + Name: name, + ChainId: chainId, + Description: description, + Tags: tags, + Author: author, + AuthorDescription: authorDescription, + IDLContent: idlContent, + }, + } +} + +func (msg MsgSvcDef) Route() string { return MsgType } +func (msg MsgSvcDef) Type() string { return "service definition" } + +func (msg MsgSvcDef) GetSignBytes() []byte { + if len(msg.Tags) == 0 { + msg.Tags = nil + } + b, err := msgCdc.MarshalJSON(msg) + if err != nil { + panic(err) + } + return sdk.MustSortJSON(b) +} + +func (msg MsgSvcDef) ValidateBasic() sdk.Error { + if len(msg.ChainId) == 0 { + return ErrInvalidChainId(DefaultCodespace) + } + if !validServiceName(msg.Name) { + return ErrInvalidServiceName(DefaultCodespace, msg.Name) + } + if len(msg.Author) == 0 { + return ErrInvalidAuthor(DefaultCodespace) + } + if len(msg.IDLContent) == 0 { + return ErrInvalidIDL(DefaultCodespace, "content is empty") + } + methods, err := protoidl.GetMethods(msg.IDLContent) + if err != nil { + return ErrInvalidIDL(DefaultCodespace, err.Error()) + } + if valid, err := validateMethods(methods); !valid { + return err + } + + return nil +} + +func (msg MsgSvcDef) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{msg.Author} +} + +func validateMethods(methods []protoidl.Method) (bool, sdk.Error) { + for _, method := range methods { + if len(method.Name) == 0 { + return false, ErrInvalidMethodName(DefaultCodespace) + } + if _, ok := method.Attributes[outputPrivacy]; ok { + _, err := OutputPrivacyEnumFromString(method.Attributes[outputPrivacy]) + if err != nil { + return false, ErrInvalidOutputPrivacyEnum(DefaultCodespace, method.Attributes[outputPrivacy]) + } + } + if _, ok := method.Attributes[outputCached]; ok { + _, err := OutputCachedEnumFromString(method.Attributes[outputCached]) + if err != nil { + return false, ErrInvalidOutputCachedEnum(DefaultCodespace, method.Attributes[outputCached]) + } + } + } + return true, nil +} + +func methodToMethodProperty(index int, method protoidl.Method) (methodProperty MethodProperty, err sdk.Error) { + // set default value + opp := NoPrivacy + opc := NoCached + + var err1 error + if _, ok := method.Attributes[outputPrivacy]; ok { + opp, err1 = OutputPrivacyEnumFromString(method.Attributes[outputPrivacy]) + if err1 != nil { + return methodProperty, ErrInvalidOutputPrivacyEnum(DefaultCodespace, method.Attributes[outputPrivacy]) + } + } + if _, ok := method.Attributes[outputCached]; ok { + opc, err1 = OutputCachedEnumFromString(method.Attributes[outputCached]) + if err != nil { + return methodProperty, ErrInvalidOutputCachedEnum(DefaultCodespace, method.Attributes[outputCached]) + } + } + methodProperty = MethodProperty{ + ID: index, + Name: method.Name, + Description: method.Attributes[description], + OutputPrivacy: opp, + OutputCached: opc, + } + return +} + +//______________________________________________________________________ + +// MsgSvcBinding - struct for bind a service +type MsgSvcBind struct { + DefName string `json:"def_name"` + DefChainID string `json:"def_chain_id"` + BindChainID string `json:"bind_chain_id"` + Provider sdk.AccAddress `json:"provider"` + BindingType BindingType `json:"binding_type"` + Deposit sdk.Coins `json:"deposit"` + Prices []sdk.Coin `json:"price"` + Level Level `json:"level"` +} + +func NewMsgSvcBind(defChainID, defName, bindChainID string, provider sdk.AccAddress, bindingType BindingType, deposit sdk.Coins, prices []sdk.Coin, level Level) MsgSvcBind { + return MsgSvcBind{ + DefChainID: defChainID, + DefName: defName, + BindChainID: bindChainID, + Provider: provider, + BindingType: bindingType, + Deposit: deposit, + Prices: prices, + Level: level, + } +} + +func (msg MsgSvcBind) Route() string { return MsgType } +func (msg MsgSvcBind) Type() string { return "service binding" } + +func (msg MsgSvcBind) GetSignBytes() []byte { + b, err := msgCdc.MarshalJSON(msg) + if err != nil { + panic(err) + } + return sdk.MustSortJSON(b) +} + +func (msg MsgSvcBind) ValidateBasic() sdk.Error { + if len(msg.DefChainID) == 0 { + return ErrInvalidDefChainId(DefaultCodespace) + } + if len(msg.BindChainID) == 0 { + return ErrInvalidChainId(DefaultCodespace) + } + if !validServiceName(msg.DefName) { + return ErrInvalidServiceName(DefaultCodespace, msg.DefName) + } + if !validBindingType(msg.BindingType) { + return ErrInvalidBindingType(DefaultCodespace, msg.BindingType) + } + if len(msg.Provider) == 0 { + sdk.ErrInvalidAddress(msg.Provider.String()) + } + if !msg.Deposit.IsValid() { + return sdk.ErrInvalidCoins(msg.Deposit.String()) + } + if !msg.Deposit.IsNotNegative() { + return sdk.ErrInvalidCoins(msg.Deposit.String()) + } + for _, price := range msg.Prices { + if !price.IsNotNegative() { + return sdk.ErrInvalidCoins(price.String()) + } + } + if !validLevel(msg.Level) { + return ErrInvalidLevel(DefaultCodespace, msg.Level) + } + return nil +} + +func (msg MsgSvcBind) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{msg.Provider} +} + +//______________________________________________________________________ + +// MsgSvcBindingUpdate - struct for update a service binding +type MsgSvcBindingUpdate struct { + DefName string `json:"def_name"` + DefChainID string `json:"def_chain_id"` + BindChainID string `json:"bind_chain_id"` + Provider sdk.AccAddress `json:"provider"` + BindingType BindingType `json:"binding_type"` + Deposit sdk.Coins `json:"deposit"` + Prices []sdk.Coin `json:"price"` + Level Level `json:"level"` +} + +func NewMsgSvcBindingUpdate(defChainID, defName, bindChainID string, provider sdk.AccAddress, bindingType BindingType, deposit sdk.Coins, prices []sdk.Coin, level Level) MsgSvcBindingUpdate { + return MsgSvcBindingUpdate{ + DefChainID: defChainID, + DefName: defName, + BindChainID: bindChainID, + Provider: provider, + BindingType: bindingType, + Deposit: deposit, + Prices: prices, + Level: level, + } +} +func (msg MsgSvcBindingUpdate) Route() string { return MsgType } +func (msg MsgSvcBindingUpdate) Type() string { return "service binding update" } + +func (msg MsgSvcBindingUpdate) GetSignBytes() []byte { + b, err := msgCdc.MarshalJSON(msg) + if err != nil { + panic(err) + } + return sdk.MustSortJSON(b) +} + +func (msg MsgSvcBindingUpdate) ValidateBasic() sdk.Error { + if len(msg.DefChainID) == 0 { + return ErrInvalidDefChainId(DefaultCodespace) + } + if len(msg.BindChainID) == 0 { + return ErrInvalidChainId(DefaultCodespace) + } + if !validServiceName(msg.DefName) { + return ErrInvalidServiceName(DefaultCodespace, msg.DefName) + } + if len(msg.Provider) == 0 { + sdk.ErrInvalidAddress(msg.Provider.String()) + } + if msg.BindingType != 0x00 && !validBindingType(msg.BindingType) { + return ErrInvalidBindingType(DefaultCodespace, msg.BindingType) + } + if !msg.Deposit.IsNotNegative() { + return sdk.ErrInvalidCoins(msg.Deposit.String()) + } + for _, price := range msg.Prices { + if !price.IsNotNegative() { + return sdk.ErrInvalidCoins(price.String()) + } + } + if !validUpdateLevel(msg.Level) { + return ErrInvalidLevel(DefaultCodespace, msg.Level) + } + return nil +} + +func (msg MsgSvcBindingUpdate) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{msg.Provider} +} + +//______________________________________________________________________ + +// MsgSvcDisable - struct for disable a service binding +type MsgSvcDisable struct { + DefName string `json:"def_name"` + DefChainID string `json:"def_chain_id"` + BindChainID string `json:"bind_chain_id"` + Provider sdk.AccAddress `json:"provider"` +} + +func NewMsgSvcDisable(defChainID, defName, bindChainID string, provider sdk.AccAddress) MsgSvcDisable { + return MsgSvcDisable{ + DefChainID: defChainID, + DefName: defName, + BindChainID: bindChainID, + Provider: provider, + } +} + +func (msg MsgSvcDisable) Route() string { return MsgType } +func (msg MsgSvcDisable) Type() string { return "service disable" } + +func (msg MsgSvcDisable) GetSignBytes() []byte { + b, err := msgCdc.MarshalJSON(msg) + if err != nil { + panic(err) + } + return sdk.MustSortJSON(b) +} + +func (msg MsgSvcDisable) ValidateBasic() sdk.Error { + if len(msg.DefChainID) == 0 { + return ErrInvalidDefChainId(DefaultCodespace) + } + if len(msg.BindChainID) == 0 { + return ErrInvalidChainId(DefaultCodespace) + } + if !validServiceName(msg.DefName) { + return ErrInvalidServiceName(DefaultCodespace, msg.DefName) + } + if len(msg.Provider) == 0 { + sdk.ErrInvalidAddress(msg.Provider.String()) + } + return nil +} + +func (msg MsgSvcDisable) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{msg.Provider} +} + +//______________________________________________________________________ + +// MsgSvcEnable - struct for enable a service binding +type MsgSvcEnable struct { + DefName string `json:"def_name"` + DefChainID string `json:"def_chain_id"` + BindChainID string `json:"bind_chain_id"` + Provider sdk.AccAddress `json:"provider"` + Deposit sdk.Coins `json:"deposit"` +} + +func NewMsgSvcEnable(defChainID, defName, bindChainID string, provider sdk.AccAddress, deposit sdk.Coins) MsgSvcEnable { + return MsgSvcEnable{ + DefChainID: defChainID, + DefName: defName, + BindChainID: bindChainID, + Provider: provider, + Deposit: deposit, + } +} + +func (msg MsgSvcEnable) Route() string { return MsgType } +func (msg MsgSvcEnable) Type() string { return "service enable" } + +func (msg MsgSvcEnable) GetSignBytes() []byte { + b, err := msgCdc.MarshalJSON(msg) + if err != nil { + panic(err) + } + return sdk.MustSortJSON(b) +} + +func (msg MsgSvcEnable) ValidateBasic() sdk.Error { + if len(msg.DefChainID) == 0 { + return ErrInvalidDefChainId(DefaultCodespace) + } + if len(msg.BindChainID) == 0 { + return ErrInvalidChainId(DefaultCodespace) + } + if !validServiceName(msg.DefName) { + return ErrInvalidServiceName(DefaultCodespace, msg.DefName) + } + if !msg.Deposit.IsNotNegative() { + return sdk.ErrInvalidCoins(msg.Deposit.String()) + } + if len(msg.Provider) == 0 { + sdk.ErrInvalidAddress(msg.Provider.String()) + } + return nil +} + +func (msg MsgSvcEnable) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{msg.Provider} +} + +//______________________________________________________________________ + +// MsgSvcRefundDeposit - struct for refund deposit from a service binding +type MsgSvcRefundDeposit struct { + DefName string `json:"def_name"` + DefChainID string `json:"def_chain_id"` + BindChainID string `json:"bind_chain_id"` + Provider sdk.AccAddress `json:"provider"` +} + +func NewMsgSvcRefundDeposit(defChainID, defName, bindChainID string, provider sdk.AccAddress) MsgSvcRefundDeposit { + return MsgSvcRefundDeposit{ + DefChainID: defChainID, + DefName: defName, + BindChainID: bindChainID, + Provider: provider, + } +} + +func (msg MsgSvcRefundDeposit) Route() string { return MsgType } +func (msg MsgSvcRefundDeposit) Type() string { return "service refund deposit" } + +func (msg MsgSvcRefundDeposit) GetSignBytes() []byte { + b, err := msgCdc.MarshalJSON(msg) + if err != nil { + panic(err) + } + return sdk.MustSortJSON(b) +} + +func (msg MsgSvcRefundDeposit) ValidateBasic() sdk.Error { + if len(msg.DefChainID) == 0 { + return ErrInvalidDefChainId(DefaultCodespace) + } + if len(msg.BindChainID) == 0 { + return ErrInvalidChainId(DefaultCodespace) + } + if !validServiceName(msg.DefName) { + return ErrInvalidServiceName(DefaultCodespace, msg.DefName) + } + if len(msg.Provider) == 0 { + sdk.ErrInvalidAddress(msg.Provider.String()) + } + return nil +} + +func (msg MsgSvcRefundDeposit) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{msg.Provider} +} + +func validServiceName(name string) bool { + if len(name) == 0 || len(name) > 128 { + return false + } + + // Must contain alphanumeric characters, _ and - only + reg := regexp.MustCompile(`[^a-zA-Z0-9_-]`) + return !reg.Match([]byte(name)) +} diff --git a/modules/service/params/service_params.go b/modules/service/params/service_params.go new file mode 100644 index 000000000..3cff74b72 --- /dev/null +++ b/modules/service/params/service_params.go @@ -0,0 +1,72 @@ +package serviceparams + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/irisnet/irishub/iparam" +) + +var MaxRequestTimeoutParameter MaxRequestTimeoutParam + +var _ iparam.SignalParameter = (*MaxRequestTimeoutParam)(nil) + +type MaxRequestTimeoutParam struct { + Value int64 + paramSpace params.Subspace +} + +func (param *MaxRequestTimeoutParam) InitGenesis(genesisState interface{}) { + param.Value = genesisState.(int64) +} + +func (param *MaxRequestTimeoutParam) SetReadWriter(paramSpace params.Subspace) { + param.paramSpace = paramSpace +} + +func (param *MaxRequestTimeoutParam) GetStoreKey() []byte { + return []byte("serviceMaxRequestTimeout") +} + +func (param *MaxRequestTimeoutParam) SaveValue(ctx sdk.Context) { + param.paramSpace.Set(ctx, param.GetStoreKey(), param.Value) +} + +func (param *MaxRequestTimeoutParam) LoadValue(ctx sdk.Context) bool { + if param.paramSpace.Has(ctx, param.GetStoreKey()) == false { + return false + } + param.paramSpace.Get(ctx, param.GetStoreKey(), ¶m.Value) + return true +} + +var MinProviderDepositParameter MinProviderDepositParam +var _ iparam.SignalParameter = (*MinProviderDepositParam)(nil) + +type MinProviderDepositParam struct { + Value sdk.Coins + paramSpace params.Subspace +} + +func (param *MinProviderDepositParam) InitGenesis(genesisState interface{}) { + param.Value = genesisState.(sdk.Coins) +} + +func (param *MinProviderDepositParam) SetReadWriter(paramSpace params.Subspace) { + param.paramSpace = paramSpace +} + +func (param *MinProviderDepositParam) GetStoreKey() []byte { + return []byte("serviceMinProviderDeposit") +} + +func (param *MinProviderDepositParam) SaveValue(ctx sdk.Context) { + param.paramSpace.Set(ctx, param.GetStoreKey(), param.Value) +} + +func (param *MinProviderDepositParam) LoadValue(ctx sdk.Context) bool { + if param.paramSpace.Has(ctx, param.GetStoreKey()) == false { + return false + } + param.paramSpace.Get(ctx, param.GetStoreKey(), ¶m.Value) + return true +} diff --git a/modules/service/params/service_params_test.go b/modules/service/params/service_params_test.go new file mode 100644 index 000000000..e48f9e4c1 --- /dev/null +++ b/modules/service/params/service_params_test.go @@ -0,0 +1,96 @@ +package serviceparams + +import ( + "github.com/cosmos/cosmos-sdk/store" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/params" + "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" + "github.com/irisnet/irishub/types" + "fmt" +) + +func defaultContext(key sdk.StoreKey, tkeyParams *sdk.TransientStoreKey) sdk.Context { + db := dbm.NewMemDB() + cms := store.NewCommitMultiStore(db) + cms.MountStoreWithDB(key, sdk.StoreTypeIAVL, db) + cms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) + + cms.LoadLatestVersion() + ctx := sdk.NewContext(cms, abci.Header{}, false, log.NewNopLogger()) + return ctx +} + +func TestMaxRequestTimeoutParameter(t *testing.T) { + skey := sdk.NewKVStoreKey("params") + tkeyParams := sdk.NewTransientStoreKey("transient_params") + + ctx := defaultContext(skey, tkeyParams) + cdc := codec.New() + + paramKeeper := params.NewKeeper( + cdc, + skey, tkeyParams, + ) + + subspace := paramKeeper.Subspace("Service").WithTypeTable(params.NewTypeTable( + MaxRequestTimeoutParameter.GetStoreKey(), int64(0), + MinProviderDepositParameter.GetStoreKey(), sdk.Coins{}, + )) + + MaxRequestTimeoutParameter.SetReadWriter(subspace) + find := MaxRequestTimeoutParameter.LoadValue(ctx) + require.Equal(t, find, false) + + MaxRequestTimeoutParameter.InitGenesis(int64(12345)) + require.Equal(t, int64(12345), MaxRequestTimeoutParameter.Value) + + MaxRequestTimeoutParameter.LoadValue(ctx) + require.Equal(t, int64(12345), MaxRequestTimeoutParameter.Value) + + MaxRequestTimeoutParameter.Value = 30 + MaxRequestTimeoutParameter.SaveValue(ctx) + + MaxRequestTimeoutParameter.LoadValue(ctx) + require.Equal(t, int64(30), MaxRequestTimeoutParameter.Value) +} + +func TestMinProviderDepositParameter(t *testing.T) { + skey := sdk.NewKVStoreKey("params") + tkeyParams := sdk.NewTransientStoreKey("transient_params") + + ctx := defaultContext(skey, tkeyParams) + cdc := codec.New() + + paramKeeper := params.NewKeeper( + cdc, + skey, tkeyParams, + ) + + subspace := paramKeeper.Subspace("Sig").WithTypeTable(params.NewTypeTable( + MaxRequestTimeoutParameter.GetStoreKey(), int64(0), + MinProviderDepositParameter.GetStoreKey(), sdk.Coins{}, + )) + + MinProviderDepositParameter.SetReadWriter(subspace) + find := MinProviderDepositParameter.LoadValue(ctx) + require.Equal(t, find, false) + + p1deposit, _ := types.NewDefaultCoinType("iris").ConvertToMinCoin(fmt.Sprintf("%d%s", 10, "iris")) + p2deposit, _ := types.NewDefaultCoinType("iris").ConvertToMinCoin(fmt.Sprintf("%d%s", 1000, "iris")) + MinProviderDepositParameter.InitGenesis(sdk.Coins{p1deposit}) + require.Equal(t, sdk.Coins{p1deposit}, MinProviderDepositParameter.Value) + + MinProviderDepositParameter.LoadValue(ctx) + require.Equal(t, sdk.Coins{p1deposit}, MinProviderDepositParameter.Value) + + MinProviderDepositParameter.Value = sdk.Coins{p2deposit} + MinProviderDepositParameter.SaveValue(ctx) + + MinProviderDepositParameter.LoadValue(ctx) + require.Equal(t, sdk.Coins{p2deposit}, MinProviderDepositParameter.Value) +} diff --git a/modules/service/params/util.go b/modules/service/params/util.go new file mode 100644 index 000000000..52943e656 --- /dev/null +++ b/modules/service/params/util.go @@ -0,0 +1,25 @@ +package serviceparams + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func GetMaxRequestTimeout(ctx sdk.Context) int64 { + MaxRequestTimeoutParameter.LoadValue(ctx) + return MaxRequestTimeoutParameter.Value +} + +func GetMinProviderDeposit(ctx sdk.Context) sdk.Coins { + MinProviderDepositParameter.LoadValue(ctx) + return MinProviderDepositParameter.Value +} + +func SetMinProviderDeposit(ctx sdk.Context, i sdk.Coins) { + MinProviderDepositParameter.Value = i + MinProviderDepositParameter.SaveValue(ctx) +} + +func SetMaxRequestTimeout(ctx sdk.Context, i int64) { + MaxRequestTimeoutParameter.Value = i + MaxRequestTimeoutParameter.SaveValue(ctx) +} diff --git a/modules/service/tags/tags.go b/modules/service/tags/tags.go new file mode 100644 index 000000000..97d3d8670 --- /dev/null +++ b/modules/service/tags/tags.go @@ -0,0 +1,16 @@ +package tags + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var ( + ActionSvcDef = []byte("service-define") + ActionSvcBind = []byte("service-bind") + ActionSvcBindUpdate = []byte("service-update-binding") + ActionSvcRefundDeposit = []byte("service-refund-deposit") + ActionSvcDisable = []byte("service-disable") + ActionSvcEnable = []byte("service-enable") + + Action = sdk.TagAction +) diff --git a/modules/service/test_common.go b/modules/service/test_common.go new file mode 100644 index 000000000..892eef97b --- /dev/null +++ b/modules/service/test_common.go @@ -0,0 +1,122 @@ +package service + +import ( + "bytes" + "log" + "sort" + "testing" + + "github.com/stretchr/testify/require" + + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/crypto" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/irisnet/irishub/simulation/mock" + "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/irisnet/irishub/types" + "fmt" +) + +// initialize the mock application for this module +func getMockApp(t *testing.T, numGenAccs int) (*mock.App, Keeper, stake.Keeper, []sdk.AccAddress, []crypto.PubKey, []crypto.PrivKey) { + mapp := mock.NewApp() + + stake.RegisterCodec(mapp.Cdc) + RegisterCodec(mapp.Cdc) + + keyService := sdk.NewKVStoreKey("service") + + ck := bank.NewBaseKeeper(mapp.AccountKeeper) + sk := stake.NewKeeper( + mapp.Cdc, + mapp.KeyStake, mapp.TkeyStake, + mapp.BankKeeper, mapp.ParamsKeeper.Subspace(stake.DefaultParamspace), + mapp.RegisterCodespace(stake.DefaultCodespace)) + ik := NewKeeper(mapp.Cdc, keyService, ck, DefaultCodespace) + + mapp.Router().AddRoute("service", []*sdk.KVStoreKey{keyService}, NewHandler(ik)) + + mapp.SetEndBlocker(getEndBlocker()) + mapp.SetInitChainer(getInitChainer(mapp, sk)) + + require.NoError(t, mapp.CompleteSetup(keyService)) + + coin, _ := types.NewDefaultCoinType("iris").ConvertToMinCoin(fmt.Sprintf("%d%s", 1042, "iris")) + genAccs, addrs, pubKeys, privKeys := mock.CreateGenAccounts(numGenAccs, sdk.Coins{coin}) + + mock.SetGenesis(mapp, genAccs) + + return mapp, ik, sk, addrs, pubKeys, privKeys +} + +// gov and stake endblocker +func getEndBlocker() sdk.EndBlocker { + return func(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { + return abci.ResponseEndBlock{ + } + } +} + +// gov and stake initchainer +func getInitChainer(mapp *mock.App, stakeKeeper stake.Keeper) sdk.InitChainer { + return func(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { + mapp.InitChainer(ctx, req) + + stakeGenesis := stake.DefaultGenesisState() + stakeGenesis.Pool.LooseTokens = sdk.NewDec(100000) + + validators, err := stake.InitGenesis(ctx, stakeKeeper, stakeGenesis) + if err != nil { + panic(err) + } + InitGenesis(ctx, DefaultGenesisState()) + return abci.ResponseInitChain{ + Validators: validators, + } + } +} + +// Sorts Addresses +func SortAddresses(addrs []sdk.AccAddress) { + var byteAddrs [][]byte + for _, addr := range addrs { + byteAddrs = append(byteAddrs, addr.Bytes()) + } + SortByteArrays(byteAddrs) + for i, byteAddr := range byteAddrs { + addrs[i] = byteAddr + } +} + +// implement `Interface` in sort package. +type sortByteArrays [][]byte + +func (b sortByteArrays) Len() int { + return len(b) +} + +func (b sortByteArrays) Less(i, j int) bool { + // bytes package already implements Comparable for []byte. + switch bytes.Compare(b[i], b[j]) { + case -1: + return true + case 0, 1: + return false + default: + log.Panic("not fail-able with `bytes.Comparable` bounded [-1, 1].") + return false + } +} + +func (b sortByteArrays) Swap(i, j int) { + b[j], b[i] = b[i], b[j] +} + +// Public +func SortByteArrays(src [][]byte) [][]byte { + sorted := sortByteArrays(src) + sort.Sort(sorted) + return sorted +} diff --git a/modules/service/wire.go b/modules/service/wire.go new file mode 100644 index 000000000..3fb0ccefb --- /dev/null +++ b/modules/service/wire.go @@ -0,0 +1,24 @@ +package service + +import ( + "github.com/cosmos/cosmos-sdk/codec" +) + +// Register concrete types on codec codec +func RegisterCodec(cdc *codec.Codec) { + cdc.RegisterConcrete(MsgSvcDef{}, "iris-hub/service/MsgSvcDef", nil) + cdc.RegisterConcrete(MsgSvcBind{}, "iris-hub/service/MsgSvcBinding", nil) + cdc.RegisterConcrete(MsgSvcBindingUpdate{}, "iris-hub/service/MsgSvcBindingUpdate", nil) + cdc.RegisterConcrete(MsgSvcDisable{}, "iris-hub/service/MsgSvcDisable", nil) + cdc.RegisterConcrete(MsgSvcEnable{}, "iris-hub/service/MsgSvcEnable", nil) + cdc.RegisterConcrete(MsgSvcRefundDeposit{}, "iris-hub/service/MsgSvcRefundDeposit", nil) + + cdc.RegisterConcrete(SvcDef{}, "iris-hub/service/SvcDef", nil) + cdc.RegisterConcrete(SvcBinding{}, "iris-hub/service/SvcBinding", nil) +} + +var msgCdc = codec.New() + +func init() { + RegisterCodec(msgCdc) +} diff --git a/modules/upgrade/genesis.go b/modules/upgrade/genesis.go index 430019d4b..33ed9b343 100644 --- a/modules/upgrade/genesis.go +++ b/modules/upgrade/genesis.go @@ -4,7 +4,7 @@ import ( bam "github.com/irisnet/irishub/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "fmt" - "github.com/irisnet/irishub/modules/iparam" + "github.com/irisnet/irishub/iparam" "github.com/irisnet/irishub/modules/upgrade/params" ) @@ -28,12 +28,21 @@ func InitGenesis(ctx sdk.Context, k Keeper, router bam.Router, data GenesisState k.AddNewVersion(ctx, genesisVersion) iparam.InitGenesisParameter(&upgradeparams.ProposalAcceptHeightParameter, ctx, -1) - iparam.InitGenesisParameter(&upgradeparams.CurrentUpgradeProposalIdParameter, ctx, -1) + iparam.InitGenesisParameter(&upgradeparams.CurrentUpgradeProposalIdParameter, ctx, 0) iparam.InitGenesisParameter(&upgradeparams.SwitchPeriodParameter, ctx, data.SwitchPeriod) InitGenesis_commitID(ctx, k) } + +// WriteGenesis - output genesis parameters +func WriteGenesis(ctx sdk.Context, k Keeper) GenesisState { + + return GenesisState{ + SwitchPeriod: upgradeparams.GetSwitchPeriod(ctx), + } +} + // get raw genesis raw message for testing func DefaultGenesisState() GenesisState { return GenesisState{ diff --git a/modules/upgrade/handler.go b/modules/upgrade/handler.go index e5e93e8b6..abe9f3c43 100644 --- a/modules/upgrade/handler.go +++ b/modules/upgrade/handler.go @@ -31,14 +31,13 @@ func handlerSwitch(ctx sdk.Context, msg sdk.Msg, k Keeper) sdk.Result { CurrentProposalID := upgradeparams.GetCurrentUpgradeProposalId(ctx) if proposalID != CurrentProposalID { - return NewError(DefaultCodespace, CodeNotCurrentProposal, "It isn't the current SoftwareUpgradeProposal").Result() } voter := msgSwitch.Voter - - if _, ok := k.sk.GetValidator(ctx, voter); !ok { + valAcc := sdk.ValAddress(voter) + if _, ok := k.sk.GetValidator(ctx, valAcc); !ok { return NewError(DefaultCodespace, CodeNotValidator, "Not a validator").Result() } @@ -62,7 +61,7 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (tags sdk.Tags) { proposalID := upgradeparams.GetCurrentUpgradeProposalId(ctx) switchPeriod := upgradeparams.GetSwitchPeriod(ctx) - if (proposalID != -1) && (ctx.BlockHeight() == height + switchPeriod) { + if (proposalID != 0) && (ctx.BlockHeight() == height + switchPeriod) { switchPasses := tally(ctx, keeper) if switchPasses { tags.AppendTag("action", []byte("switchPassed")) @@ -71,7 +70,7 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (tags sdk.Tags) { } else { tags.AppendTag("action", []byte("switchDropped")) - upgradeparams.SetCurrentUpgradeProposalId(ctx,-1) + upgradeparams.SetCurrentUpgradeProposalId(ctx,0) } } diff --git a/modules/upgrade/keep_test.go b/modules/upgrade/keep_test.go index b1f0f513a..20cbc1a10 100644 --- a/modules/upgrade/keep_test.go +++ b/modules/upgrade/keep_test.go @@ -8,6 +8,7 @@ import ( "strings" "testing" "github.com/irisnet/irishub/modules/upgrade/params" + "github.com/cosmos/cosmos-sdk/x/params" ) func TestUpdateKeeper(t *testing.T) { @@ -137,10 +138,15 @@ func TestSetKVStoreKeylist(t *testing.T) { router.AddRoute("stake-0", []*sdk.KVStoreKey{sdk.NewKVStoreKey("stake")}, nil) router.AddRoute("upgrade-0", []*sdk.KVStoreKey{sdk.NewKVStoreKey("upgrade")}, nil) + subspace := paramKeeper.Subspace("Sig").WithTypeTable(params.NewTypeTable( + upgradeparams.CurrentUpgradeProposalIdParameter.GetStoreKey(), uint64((0)), + upgradeparams.ProposalAcceptHeightParameter.GetStoreKey(), int64(0), + upgradeparams.SwitchPeriodParameter.GetStoreKey(), int64(0), + )) - upgradeparams.ProposalAcceptHeightParameter.SetReadWriter(paramKeeper.Setter()) - upgradeparams.CurrentUpgradeProposalIdParameter.SetReadWriter(paramKeeper.Setter()) - upgradeparams.SwitchPeriodParameter.SetReadWriter(paramKeeper.Setter()) + upgradeparams.ProposalAcceptHeightParameter.SetReadWriter(subspace) + upgradeparams.CurrentUpgradeProposalIdParameter.SetReadWriter(subspace) + upgradeparams.SwitchPeriodParameter.SetReadWriter(subspace) InitGenesis(ctx, keeper, router, DefaultGenesisStateForTest()) keeper.SetKVStoreKeylist(ctx) @@ -178,7 +184,13 @@ func TestKeeper_InitGenesis_commidID(t *testing.T) { InitGenesis_commitID(ctx, keeper) fmt.Println(keeper.GetKVStoreKeylist(ctx)) - upgradeparams.ProposalAcceptHeightParameter.SetReadWriter(paramKeeper.Setter()) + subspace := paramKeeper.Subspace("Sig").WithTypeTable(params.NewTypeTable( + upgradeparams.CurrentUpgradeProposalIdParameter.GetStoreKey(), uint64((0)), + upgradeparams.ProposalAcceptHeightParameter.GetStoreKey(), int64(0), + upgradeparams.SwitchPeriodParameter.GetStoreKey(), int64(0), + )) + + upgradeparams.ProposalAcceptHeightParameter.SetReadWriter(subspace) upgradeparams.SetProposalAcceptHeight(ctx, 1234234000) fmt.Println(upgradeparams.GetProposalAcceptHeight(ctx)) diff --git a/modules/upgrade/keeper.go b/modules/upgrade/keeper.go index 24ce0ad50..8c131b815 100644 --- a/modules/upgrade/keeper.go +++ b/modules/upgrade/keeper.go @@ -2,7 +2,7 @@ package upgrade import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/stake" "math" "fmt" @@ -10,14 +10,14 @@ import ( type Keeper struct { storeKey sdk.StoreKey - cdc *wire.Codec + cdc *codec.Codec // The ValidatorSet to get information about validators sk stake.Keeper } var VersionListCached VersionList -func NewKeeper(cdc *wire.Codec, key sdk.StoreKey, sk stake.Keeper) Keeper { +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, sk stake.Keeper) Keeper { keeper := Keeper{ storeKey: key, cdc: cdc, @@ -35,7 +35,7 @@ func (k Keeper) GetCurrentVersionByStore(kvStore sdk.KVStore) *Version { versionIDBytes := kvStore.Get(GetCurrentVersionKey()) if versionIDBytes != nil { var versionID int64 - err := k.cdc.UnmarshalBinary(versionIDBytes, &versionID) + err := k.cdc.UnmarshalBinaryLengthPrefixed(versionIDBytes, &versionID) if err != nil { panic(err) } @@ -44,7 +44,7 @@ func (k Keeper) GetCurrentVersionByStore(kvStore sdk.KVStore) *Version { return nil } var version Version - err = k.cdc.UnmarshalBinary(curVersionBytes, &version) + err = k.cdc.UnmarshalBinaryLengthPrefixed(curVersionBytes, &version) if err != nil { panic(err) } @@ -70,7 +70,7 @@ func (k Keeper) AddNewVersion(ctx sdk.Context, version Version) { module.Start = version.Start } - versionBytes, err := k.cdc.MarshalBinary(version) + versionBytes, err := k.cdc.MarshalBinaryLengthPrefixed(version) if err != nil { panic(err) } @@ -78,7 +78,7 @@ func (k Keeper) AddNewVersion(ctx sdk.Context, version Version) { kvStore.Set(GetVersionIDKey(version.Id), versionBytes) VersionListCached = append(VersionListCached, version) - versionIDBytes, err := k.cdc.MarshalBinary(version.Id) + versionIDBytes, err := k.cdc.MarshalBinaryLengthPrefixed(version.Id) if err != nil { panic(err) } @@ -99,7 +99,7 @@ func (k Keeper) GetVersionByHeight(ctx sdk.Context, blockHeight int64) *Version return nil } var versionID int64 - err := k.cdc.UnmarshalBinary(versionIDBytes, &versionID) + err := k.cdc.UnmarshalBinaryLengthPrefixed(versionIDBytes, &versionID) if err != nil { panic(err) } @@ -108,7 +108,7 @@ func (k Keeper) GetVersionByHeight(ctx sdk.Context, blockHeight int64) *Version return nil } var version Version - err = k.cdc.UnmarshalBinary(versionBytes, &version) + err = k.cdc.UnmarshalBinaryLengthPrefixed(versionBytes, &version) if err != nil { panic(err) } @@ -117,21 +117,21 @@ func (k Keeper) GetVersionByHeight(ctx sdk.Context, blockHeight int64) *Version return nil } -func (k Keeper) GetVersionByProposalId(ctx sdk.Context, proposalId int64) *Version { +func (k Keeper) GetVersionByProposalId(ctx sdk.Context, proposalId uint64) *Version { kvStore := ctx.KVStore(k.storeKey) versionIDBytes := kvStore.Get(GetProposalIDKey(proposalId)) if versionIDBytes == nil { return nil } var versionID int64 - err := k.cdc.UnmarshalBinary(versionIDBytes, &versionID) + err := k.cdc.UnmarshalBinaryLengthPrefixed(versionIDBytes, &versionID) if err != nil { panic(err) } versionBytes := kvStore.Get(GetVersionIDKey(versionID)) if versionBytes != nil { var version Version - err := k.cdc.UnmarshalBinary(versionBytes, &version) + err := k.cdc.UnmarshalBinaryLengthPrefixed(versionBytes, &version) if err != nil { panic(err) } @@ -171,7 +171,7 @@ func (k Keeper) GetVersionListByStore(kvStore sdk.KVStore) VersionList { continue } var version Version - err := k.cdc.UnmarshalBinary(versionBytes, &version) + err := k.cdc.UnmarshalBinaryLengthPrefixed(versionBytes, &version) if err != nil { panic(err) } @@ -186,21 +186,21 @@ func (k Keeper) GetMsgTypeInCurrentVersion(ctx sdk.Context, msg sdk.Msg) (string return currentVersion.getMsgType(msg) } -func (k Keeper) SetSwitch(ctx sdk.Context, propsalID int64, address sdk.AccAddress, cmsg MsgSwitch) { +func (k Keeper) SetSwitch(ctx sdk.Context, propsalID uint64, address sdk.AccAddress, cmsg MsgSwitch) { kvStore := ctx.KVStore(k.storeKey) - cmsgBytes, err := k.cdc.MarshalBinary(cmsg) + cmsgBytes, err := k.cdc.MarshalBinaryLengthPrefixed(cmsg) if err != nil { panic(err) } kvStore.Set(GetSwitchKey(propsalID, address), cmsgBytes) } -func (k Keeper) GetSwitch(ctx sdk.Context, propsalID int64, address sdk.AccAddress) (MsgSwitch, bool) { +func (k Keeper) GetSwitch(ctx sdk.Context, propsalID uint64, address sdk.AccAddress) (MsgSwitch, bool) { kvStore := ctx.KVStore(k.storeKey) cmsgBytes := kvStore.Get(GetSwitchKey(propsalID, address)) if cmsgBytes != nil { var cmsg MsgSwitch - err := k.cdc.UnmarshalBinary(cmsgBytes, &cmsg) + err := k.cdc.UnmarshalBinaryLengthPrefixed(cmsgBytes, &cmsg) if err != nil { panic(err) } diff --git a/modules/upgrade/keeper_keys.go b/modules/upgrade/keeper_keys.go index b1a67cb32..011cbc75d 100644 --- a/modules/upgrade/keeper_keys.go +++ b/modules/upgrade/keeper_keys.go @@ -21,22 +21,22 @@ func GetCurrentVersionKey() []byte { } func GetVersionIDKey(versionID int64) []byte { - return []byte(fmt.Sprintf(versionIDKey, ToHexString(versionID))) + return []byte(fmt.Sprintf(versionIDKey, IntToHexString(versionID))) } -func GetProposalIDKey(proposalID int64) []byte { - return []byte(fmt.Sprintf(proposalIDKey, ToHexString(proposalID))) +func GetProposalIDKey(proposalID uint64) []byte { + return []byte(fmt.Sprintf(proposalIDKey, UintToHexString(proposalID))) } func GetStartHeightKey(height int64) []byte { - return []byte(fmt.Sprintf(startHeightKey, ToHexString(height))) + return []byte(fmt.Sprintf(startHeightKey, IntToHexString(height))) } -func GetSwitchKey(proposalID int64, switchVoterAddr sdk.AccAddress) []byte { - return []byte(fmt.Sprintf(switchKey, ToHexString(proposalID), switchVoterAddr.String())) +func GetSwitchKey(proposalID uint64, switchVoterAddr sdk.AccAddress) []byte { + return []byte(fmt.Sprintf(switchKey, UintToHexString(proposalID), switchVoterAddr.String())) } -func ToHexString(i int64) string { +func IntToHexString(i int64) string { hex := strconv.FormatInt(i, 16) var stringBuild bytes.Buffer for i:=0 ;i < 16 - len(hex); i++ { @@ -45,7 +45,15 @@ func ToHexString(i int64) string { stringBuild.Write([]byte(hex)) return stringBuild.String() } - +func UintToHexString(i uint64) string { + hex := strconv.FormatUint(i, 16) + var stringBuild bytes.Buffer + for i:=0 ;i < 16 - len(hex); i++ { + stringBuild.Write([]byte("0")) + } + stringBuild.Write([]byte(hex)) + return stringBuild.String() +} func GetDoingSwitchKey() []byte { return DoingSwitchKey } diff --git a/modules/upgrade/keeper_switch.go b/modules/upgrade/keeper_switch.go index 4561ad2f7..c33b9a9aa 100644 --- a/modules/upgrade/keeper_switch.go +++ b/modules/upgrade/keeper_switch.go @@ -153,7 +153,7 @@ func (k Keeper) DoSwitchEnd(ctx sdk.Context) { k.AddNewVersion(ctx, VersionToBeSwitched) k.SetDoingSwitch(ctx, false) - upgradeparams.SetCurrentUpgradeProposalId(ctx, -1) + upgradeparams.SetCurrentUpgradeProposalId(ctx, 0) k.SetKVStoreKeylist(ctx) } diff --git a/modules/upgrade/msgs.go b/modules/upgrade/msgs.go index cde002c20..cc80fb8d5 100644 --- a/modules/upgrade/msgs.go +++ b/modules/upgrade/msgs.go @@ -4,13 +4,18 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// name to idetify transaction types +const MsgRoute = "upgrade" + +var _ sdk.Msg = MsgSwitch{} + type MsgSwitch struct { Title string - ProposalID int64 + ProposalID uint64 Voter sdk.AccAddress } -func NewMsgSwitch( title string, proposalID int64, voter sdk.AccAddress) MsgSwitch { +func NewMsgSwitch( title string, proposalID uint64, voter sdk.AccAddress) MsgSwitch { return MsgSwitch{ Title:title, ProposalID: proposalID, @@ -18,9 +23,8 @@ func NewMsgSwitch( title string, proposalID int64, voter sdk.AccAddress) MsgSwit } } -func (msg MsgSwitch) Type() string { - return "upgrade" -} +func (msg MsgSwitch) Route() string { return MsgRoute } +func (msg MsgSwitch) Type() string { return "submit_switch" } func (msg MsgSwitch) GetSignBytes() []byte { b, err := msgCdc.MarshalJSON(msg) diff --git a/modules/upgrade/params/upgrade_params.go b/modules/upgrade/params/upgrade_params.go index 6cc229d71..a03207ba3 100644 --- a/modules/upgrade/params/upgrade_params.go +++ b/modules/upgrade/params/upgrade_params.go @@ -3,7 +3,7 @@ package upgradeparams import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/irisnet/irishub/modules/iparam" + "github.com/irisnet/irishub/iparam" ) var CurrentUpgradeProposalIdParameter CurrentUpgradeProposalIdParam @@ -11,104 +11,96 @@ var CurrentUpgradeProposalIdParameter CurrentUpgradeProposalIdParam var _ iparam.SignalParameter = (*CurrentUpgradeProposalIdParam)(nil) type CurrentUpgradeProposalIdParam struct { - Value int64 - psetter params.Setter - pgetter params.Getter + Value uint64 + paramSpace params.Subspace } func (param *CurrentUpgradeProposalIdParam) InitGenesis(genesisState interface{}) { - param.Value = -1 + param.Value = 0 } -func (param *CurrentUpgradeProposalIdParam) SetReadWriter(setter params.Setter) { - param.psetter = setter - param.pgetter = setter.Getter +func (param *CurrentUpgradeProposalIdParam) SetReadWriter(paramSpace params.Subspace) { + param.paramSpace = paramSpace } -func (param *CurrentUpgradeProposalIdParam) GetStoreKey() string { - return "Sig/upgrade/proposalId" +func (param *CurrentUpgradeProposalIdParam) GetStoreKey() []byte { + return []byte("upgradeProposalId") } func (param *CurrentUpgradeProposalIdParam) SaveValue(ctx sdk.Context) { - param.psetter.Set(ctx, param.GetStoreKey(), param.Value) + param.paramSpace.Set(ctx, param.GetStoreKey(), param.Value) } func (param *CurrentUpgradeProposalIdParam) LoadValue(ctx sdk.Context) bool { - err := param.pgetter.Get(ctx, param.GetStoreKey(), ¶m.Value) - if err != nil { + if param.paramSpace.Has(ctx, param.GetStoreKey()) == false { return false } + param.paramSpace.Get(ctx, param.GetStoreKey(), ¶m.Value) return true } - var ProposalAcceptHeightParameter ProposalAcceptHeightParam var _ iparam.SignalParameter = (*ProposalAcceptHeightParam)(nil) type ProposalAcceptHeightParam struct { - Value int64 - psetter params.Setter - pgetter params.Getter + Value int64 + paramSpace params.Subspace } func (param *ProposalAcceptHeightParam) InitGenesis(genesisState interface{}) { param.Value = -1 } -func (param *ProposalAcceptHeightParam) SetReadWriter(setter params.Setter) { - param.psetter = setter - param.pgetter = setter.Getter +func (param *ProposalAcceptHeightParam) SetReadWriter(paramSpace params.Subspace) { + param.paramSpace = paramSpace } -func (param *ProposalAcceptHeightParam) GetStoreKey() string { - return "Sig/upgrade/proposalAcceptHeight" +func (param *ProposalAcceptHeightParam) GetStoreKey() []byte { + return []byte("upgradeProposalAcceptHeight") } func (param *ProposalAcceptHeightParam) SaveValue(ctx sdk.Context) { - param.psetter.Set(ctx, param.GetStoreKey(), param.Value) + param.paramSpace.Set(ctx, param.GetStoreKey(), param.Value) } func (param *ProposalAcceptHeightParam) LoadValue(ctx sdk.Context) bool { - err := param.pgetter.Get(ctx, param.GetStoreKey(), ¶m.Value) - if err != nil { + if param.paramSpace.Has(ctx, param.GetStoreKey()) == false { return false } + param.paramSpace.Get(ctx, param.GetStoreKey(), ¶m.Value) return true } - var SwitchPeriodParameter SwitchPeriodParam var _ iparam.SignalParameter = (*SwitchPeriodParam)(nil) type SwitchPeriodParam struct { - Value int64 - psetter params.Setter - pgetter params.Getter + Value int64 + paramSpace params.Subspace } func (param *SwitchPeriodParam) InitGenesis(genesisState interface{}) { param.Value = genesisState.(int64) } -func (param *SwitchPeriodParam) SetReadWriter(setter params.Setter) { - param.psetter = setter - param.pgetter = setter.Getter +func (param *SwitchPeriodParam) SetReadWriter(paramSpace params.Subspace) { + param.paramSpace = paramSpace } -func (param *SwitchPeriodParam) GetStoreKey() string { - return "Sig/upgrade/switchperiod" +func (param *SwitchPeriodParam) GetStoreKey() []byte { + return []byte("upgradeSwitchPeriod") } func (param *SwitchPeriodParam) SaveValue(ctx sdk.Context) { - param.psetter.Set(ctx, param.GetStoreKey(), param.Value) + param.paramSpace.Set(ctx, param.GetStoreKey(), param.Value) } func (param *SwitchPeriodParam) LoadValue(ctx sdk.Context) bool { - err := param.pgetter.Get(ctx, param.GetStoreKey(), ¶m.Value) - if err != nil { + if param.paramSpace.Has(ctx, param.GetStoreKey()) == false { return false } + param.paramSpace.Get(ctx, param.GetStoreKey(), ¶m.Value) return true } diff --git a/modules/upgrade/params/upgrade_params_test.go b/modules/upgrade/params/upgrade_params_test.go index 809e55cac..3f11995c4 100644 --- a/modules/upgrade/params/upgrade_params_test.go +++ b/modules/upgrade/params/upgrade_params_test.go @@ -3,7 +3,7 @@ package upgradeparams import ( "testing" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/store" @@ -13,10 +13,12 @@ import ( "github.com/tendermint/tendermint/libs/log" ) -func defaultContext(key sdk.StoreKey) sdk.Context { +func defaultContext(key sdk.StoreKey, tkeyParams *sdk.TransientStoreKey) sdk.Context { db := dbm.NewMemDB() cms := store.NewCommitMultiStore(db) cms.MountStoreWithDB(key, sdk.StoreTypeIAVL, db) + cms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) + cms.LoadLatestVersion() ctx := sdk.NewContext(cms, abci.Header{}, false, log.NewNopLogger()) return ctx @@ -24,32 +26,58 @@ func defaultContext(key sdk.StoreKey) sdk.Context { func TestCurrentUpgradeProposalIdParameter(t *testing.T) { skey := sdk.NewKVStoreKey("params") - ctx := defaultContext(skey) - paramKeeper := params.NewKeeper(wire.NewCodec(), skey) + tkeyParams := sdk.NewTransientStoreKey("transient_params") + + ctx := defaultContext(skey, tkeyParams) + cdc := codec.New() + + paramKeeper := params.NewKeeper( + cdc, + skey, tkeyParams, + ) + + subspace := paramKeeper.Subspace("Sig").WithTypeTable(params.NewTypeTable( + CurrentUpgradeProposalIdParameter.GetStoreKey(), uint64((0)), + ProposalAcceptHeightParameter.GetStoreKey(), int64(0), + SwitchPeriodParameter.GetStoreKey(), int64(0), + )) - CurrentUpgradeProposalIdParameter.SetReadWriter(paramKeeper.Setter()) + CurrentUpgradeProposalIdParameter.SetReadWriter(subspace) find := CurrentUpgradeProposalIdParameter.LoadValue(ctx) require.Equal(t, find, false) CurrentUpgradeProposalIdParameter.InitGenesis(nil) - require.Equal(t, int64(-1), CurrentUpgradeProposalIdParameter.Value) + require.Equal(t, uint64(0), CurrentUpgradeProposalIdParameter.Value) CurrentUpgradeProposalIdParameter.LoadValue(ctx) - require.Equal(t, int64(-1), CurrentUpgradeProposalIdParameter.Value) + require.Equal(t, uint64(0), CurrentUpgradeProposalIdParameter.Value) CurrentUpgradeProposalIdParameter.Value = 3 CurrentUpgradeProposalIdParameter.SaveValue(ctx) CurrentUpgradeProposalIdParameter.LoadValue(ctx) - require.Equal(t, int64(3), CurrentUpgradeProposalIdParameter.Value) + require.Equal(t, uint64(3), CurrentUpgradeProposalIdParameter.Value) } func TestProposalAcceptHeightParameter(t *testing.T) { skey := sdk.NewKVStoreKey("params") - ctx := defaultContext(skey) - paramKeeper := params.NewKeeper(wire.NewCodec(), skey) + tkeyParams := sdk.NewTransientStoreKey("transient_params") + + ctx := defaultContext(skey, tkeyParams) + cdc := codec.New() + + paramKeeper := params.NewKeeper( + cdc, + skey, tkeyParams, + ) + + subspace := paramKeeper.Subspace("Sig").WithTypeTable(params.NewTypeTable( + CurrentUpgradeProposalIdParameter.GetStoreKey(), uint64((0)), + ProposalAcceptHeightParameter.GetStoreKey(), int64(0), + SwitchPeriodParameter.GetStoreKey(), int64(0), + )) - ProposalAcceptHeightParameter.SetReadWriter(paramKeeper.Setter()) + ProposalAcceptHeightParameter.SetReadWriter(subspace) find := ProposalAcceptHeightParameter.LoadValue(ctx) require.Equal(t, find, false) @@ -68,10 +96,23 @@ func TestProposalAcceptHeightParameter(t *testing.T) { func TestSwitchPeriodParameter(t *testing.T) { skey := sdk.NewKVStoreKey("params") - ctx := defaultContext(skey) - paramKeeper := params.NewKeeper(wire.NewCodec(), skey) + tkeyParams := sdk.NewTransientStoreKey("transient_params") - SwitchPeriodParameter.SetReadWriter(paramKeeper.Setter()) + ctx := defaultContext(skey, tkeyParams) + cdc := codec.New() + + paramKeeper := params.NewKeeper( + cdc, + skey, tkeyParams, + ) + + subspace := paramKeeper.Subspace("Sig").WithTypeTable(params.NewTypeTable( + CurrentUpgradeProposalIdParameter.GetStoreKey(), uint64((0)), + ProposalAcceptHeightParameter.GetStoreKey(), int64(0), + SwitchPeriodParameter.GetStoreKey(), int64(0), + )) + + SwitchPeriodParameter.SetReadWriter(subspace) find := SwitchPeriodParameter.LoadValue(ctx) require.Equal(t, find, false) @@ -90,23 +131,36 @@ func TestSwitchPeriodParameter(t *testing.T) { func TestUpgradeParameterSetAndGet(t *testing.T) { skey := sdk.NewKVStoreKey("params") - ctx := defaultContext(skey) - paramKeeper := params.NewKeeper(wire.NewCodec(), skey) + tkeyParams := sdk.NewTransientStoreKey("transient_params") + + ctx := defaultContext(skey, tkeyParams) + cdc := codec.New() + + paramKeeper := params.NewKeeper( + cdc, + skey, tkeyParams, + ) + + subspace := paramKeeper.Subspace("Sig").WithTypeTable(params.NewTypeTable( + CurrentUpgradeProposalIdParameter.GetStoreKey(), uint64((0)), + ProposalAcceptHeightParameter.GetStoreKey(), int64(0), + SwitchPeriodParameter.GetStoreKey(), int64(0), + )) - CurrentUpgradeProposalIdParameter.SetReadWriter(paramKeeper.Setter()) + CurrentUpgradeProposalIdParameter.SetReadWriter(subspace) find := CurrentUpgradeProposalIdParameter.LoadValue(ctx) require.Equal(t, find, false) - ProposalAcceptHeightParameter.SetReadWriter(paramKeeper.Setter()) + ProposalAcceptHeightParameter.SetReadWriter(subspace) find = ProposalAcceptHeightParameter.LoadValue(ctx) require.Equal(t, find, false) - SwitchPeriodParameter.SetReadWriter(paramKeeper.Setter()) + SwitchPeriodParameter.SetReadWriter(subspace) find = SwitchPeriodParameter.LoadValue(ctx) require.Equal(t, find, false) SetCurrentUpgradeProposalId(ctx,5) - require.Equal(t,int64(5),GetCurrentUpgradeProposalId(ctx)) + require.Equal(t,uint64(5),GetCurrentUpgradeProposalId(ctx)) SetProposalAcceptHeight(ctx,100) require.Equal(t, int64(100),GetProposalAcceptHeight(ctx) ) diff --git a/modules/upgrade/params/util.go b/modules/upgrade/params/util.go index 069376c07..bc3d2ada3 100644 --- a/modules/upgrade/params/util.go +++ b/modules/upgrade/params/util.go @@ -5,7 +5,7 @@ import ( ) -func GetCurrentUpgradeProposalId(ctx sdk.Context) int64 { +func GetCurrentUpgradeProposalId(ctx sdk.Context) uint64 { CurrentUpgradeProposalIdParameter.LoadValue(ctx) return CurrentUpgradeProposalIdParameter.Value } @@ -20,7 +20,7 @@ func GetSwitchPeriod(ctx sdk.Context) int64 { return SwitchPeriodParameter.Value } -func SetCurrentUpgradeProposalId(ctx sdk.Context, i int64) { +func SetCurrentUpgradeProposalId(ctx sdk.Context, i uint64) { CurrentUpgradeProposalIdParameter.Value = i CurrentUpgradeProposalIdParameter.SaveValue(ctx) } diff --git a/modules/upgrade/tally.go b/modules/upgrade/tally.go index cbd333dd2..f87304732 100644 --- a/modules/upgrade/tally.go +++ b/modules/upgrade/tally.go @@ -5,19 +5,21 @@ import ( "github.com/irisnet/irishub/modules/upgrade/params" ) -var Threshold = sdk.NewRat(95, 100) +var Threshold = sdk.NewDecWithPrec(95, 2) func tally(ctx sdk.Context, k Keeper) (passes bool) { proposalID := upgradeparams.GetCurrentUpgradeProposalId(ctx) - if proposalID != -1 { + if proposalID != 0 { - totalVotingPower := sdk.ZeroRat() - switchVotingPower := sdk.ZeroRat() + totalVotingPower := sdk.ZeroDec() + switchVotingPower := sdk.ZeroDec() for _, validator := range k.sk.GetAllValidators(ctx) { totalVotingPower = totalVotingPower.Add(validator.GetPower()) - if _, ok := k.GetSwitch(ctx, proposalID, validator.Owner); ok { + + valAcc := sdk.AccAddress(validator.OperatorAddr) + if _, ok := k.GetSwitch(ctx, proposalID, valAcc); ok { switchVotingPower = switchVotingPower.Add(validator.GetPower()) } } @@ -25,7 +27,6 @@ func tally(ctx sdk.Context, k Keeper) (passes bool) { if switchVotingPower.Quo(totalVotingPower).GT(Threshold) { return true } - } return false } diff --git a/modules/upgrade/test_common.go b/modules/upgrade/test_common.go index 82f5a0efc..d123641f4 100644 --- a/modules/upgrade/test_common.go +++ b/modules/upgrade/test_common.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" "os" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" dbm "github.com/tendermint/tendermint/libs/db" abci "github.com/tendermint/tendermint/abci/types" @@ -43,14 +43,14 @@ func newPubKey(pk string) (res crypto.PubKey) { return pkEd } -func createTestCodec() *wire.Codec { - cdc := wire.NewCodec() - sdk.RegisterWire(cdc) - RegisterWire(cdc) - auth.RegisterWire(cdc) - bank.RegisterWire(cdc) - stake.RegisterWire(cdc) - wire.RegisterCrypto(cdc) +func createTestCodec() *codec.Codec { + cdc := codec.New() + sdk.RegisterCodec(cdc) + RegisterCodec(cdc) + auth.RegisterCodec(cdc) + bank.RegisterCodec(cdc) + stake.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) return cdc } @@ -60,6 +60,8 @@ func createTestInput(t *testing.T) (sdk.Context, Keeper, params.Keeper) { keyUpdate := sdk.NewKVStoreKey("update") keyParams := sdk.NewKVStoreKey("params") keyIparams := sdk.NewKVStoreKey("iparams") + tkeyStake := sdk.NewTransientStoreKey("transient_stake") + tkeyParams := sdk.NewTransientStoreKey("transient_params") db := dbm.NewMemDB() ms := store.NewCommitMultiStore(db) @@ -68,17 +70,27 @@ func createTestInput(t *testing.T) (sdk.Context, Keeper, params.Keeper) { ms.MountStoreWithDB(keyUpdate, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keyIparams, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(tkeyStake, sdk.StoreTypeTransient, db) + ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) err := ms.LoadLatestVersion() require.Nil(t, err) ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewTMLogger(os.Stdout)) cdc := createTestCodec() - accountMapper := auth.NewAccountMapper(cdc, keyAcc, auth.ProtoBaseAccount) - ck := bank.NewKeeper(accountMapper) - sk := stake.NewKeeper(cdc, keyStake, ck, stake.DefaultCodespace) + AccountKeeper := auth.NewAccountKeeper(cdc, keyAcc, auth.ProtoBaseAccount) + ck := bank.NewBaseKeeper(AccountKeeper) + paramsKeeper := params.NewKeeper( + cdc, + keyParams, tkeyParams, + ) + sk := stake.NewKeeper( + cdc, + keyStake, tkeyStake, + ck, paramsKeeper.Subspace(stake.DefaultParamspace), + stake.DefaultCodespace, + ) keeper := NewKeeper(cdc, keyUpdate, sk) - paramKeeper := params.NewKeeper(wire.NewCodec(), keyParams) - return ctx, keeper, paramKeeper -} \ No newline at end of file + return ctx, keeper, paramsKeeper +} diff --git a/modules/upgrade/types.go b/modules/upgrade/types.go index ac46a2086..954c5fc8b 100644 --- a/modules/upgrade/types.go +++ b/modules/upgrade/types.go @@ -33,12 +33,12 @@ func (mlist ModuleLifeTimeList) BuildModuleLifeTime(start int64, handler string, type Version struct { Id int64 - ProposalID int64 + ProposalID uint64 Start int64 ModuleList ModuleLifeTimeList } -func NewVersion(id int64, proposalID int64, start int64, moduleList ModuleLifeTimeList) Version { +func NewVersion(id int64, proposalID uint64, start int64, moduleList ModuleLifeTimeList) Version { return Version{ Id: id, ProposalID: proposalID, @@ -48,7 +48,7 @@ func NewVersion(id int64, proposalID int64, start int64, moduleList ModuleLifeTi } func (v Version) getMsgType(msg sdk.Msg) (string, sdk.Error) { - msgType := msg.Type() + msgType := msg.Route() for _, module := range v.ModuleList { if msgType == module.Handler { diff --git a/modules/upgrade/wire.go b/modules/upgrade/wire.go index b51803dcd..beb7ade69 100644 --- a/modules/upgrade/wire.go +++ b/modules/upgrade/wire.go @@ -1,18 +1,18 @@ package upgrade import ( - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" ) -// Register concrete types on wire codec -func RegisterWire(cdc *wire.Codec) { +// Register concrete types on codec codec +func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(MsgSwitch{}, "iris-hub/upgrade/MsgSwitch", nil) cdc.RegisterConcrete(&ModuleLifeTime{}, "iris-hub/upgrade/ModuleLifeTime", nil) cdc.RegisterConcrete(&Version{}, "iris-hub/upgrade/Version", nil) } -var msgCdc = wire.NewCodec() +var msgCdc = codec.New() func init() { - RegisterWire(msgCdc) + RegisterCodec(msgCdc) } diff --git a/simulation/bank/invariants.go b/simulation/bank/invariants.go index d29bd7601..5910a6647 100644 --- a/simulation/bank/invariants.go +++ b/simulation/bank/invariants.go @@ -1,40 +1,39 @@ package simulation import ( + "errors" "fmt" - "testing" - "github.com/stretchr/testify/require" - - "github.com/irisnet/irishub/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/irisnet/irishub/simulation/mock" "github.com/irisnet/irishub/simulation/mock/simulation" abci "github.com/tendermint/tendermint/abci/types" + + "github.com/irisnet/irishub/baseapp" ) // NonnegativeBalanceInvariant checks that all accounts in the application have non-negative balances -func NonnegativeBalanceInvariant(mapper auth.AccountMapper) simulation.Invariant { - return func(t *testing.T, app *baseapp.BaseApp, log string) { +func NonnegativeBalanceInvariant(mapper auth.AccountKeeper) simulation.Invariant { + return func(app *baseapp.BaseApp) error { ctx := app.NewContext(false, abci.Header{}) accts := mock.GetAllAccounts(mapper, ctx) for _, acc := range accts { coins := acc.GetCoins() - require.True(t, coins.IsNotNegative(), - fmt.Sprintf("%s has a negative denomination of %s\n%s", + if !coins.IsNotNegative() { + return fmt.Errorf("%s has a negative denomination of %s", acc.GetAddress().String(), - coins.String(), - log), - ) + coins.String()) + } } + return nil } } // TotalCoinsInvariant checks that the sum of the coins across all accounts // is what is expected -func TotalCoinsInvariant(mapper auth.AccountMapper, totalSupplyFn func() sdk.Coins) simulation.Invariant { - return func(t *testing.T, app *baseapp.BaseApp, log string) { +func TotalCoinsInvariant(mapper auth.AccountKeeper, totalSupplyFn func() sdk.Coins) simulation.Invariant { + return func(app *baseapp.BaseApp) error { ctx := app.NewContext(false, abci.Header{}) totalCoins := sdk.Coins{} @@ -45,6 +44,9 @@ func TotalCoinsInvariant(mapper auth.AccountMapper, totalSupplyFn func() sdk.Coi } mapper.IterateAccounts(ctx, chkAccount) - require.Equal(t, true, totalSupplyFn().IsGTE(totalCoins), log) + if !totalSupplyFn().IsEqual(totalCoins) { + return errors.New("total calculated coins doesn't equal expected coins") + } + return nil } } diff --git a/simulation/bank/msgs.go b/simulation/bank/msgs.go index bc5e5919d..59d0fd39d 100644 --- a/simulation/bank/msgs.go +++ b/simulation/bank/msgs.go @@ -5,69 +5,95 @@ import ( "fmt" "math/big" "math/rand" - "testing" - "github.com/stretchr/testify/require" - - "github.com/irisnet/irishub/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/irisnet/irishub/simulation/mock" "github.com/irisnet/irishub/simulation/mock/simulation" "github.com/tendermint/tendermint/crypto" + + "github.com/irisnet/irishub/baseapp" ) -// TestAndRunSingleInputMsgSend tests and runs a single msg send, with one input and one output, where both +// SingleInputSendTx tests and runs a single msg send w/ auth, with one input and one output, where both // accounts already exist. -func TestAndRunSingleInputMsgSend(mapper auth.AccountMapper) simulation.TestAndRunTx { - return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, err sdk.Error) { - fromKey := simulation.RandomKey(r, keys) - fromAddr := sdk.AccAddress(fromKey.PubKey().Address()) - toKey := simulation.RandomKey(r, keys) - // Disallow sending money to yourself - for { - if !fromKey.Equals(toKey) { - break - } - toKey = simulation.RandomKey(r, keys) +func SingleInputSendTx(mapper auth.AccountKeeper) simulation.Operation { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) (action string, fOps []simulation.FutureOperation, err error) { + fromAcc, action, msg, abort := createSingleInputSendMsg(r, ctx, accs, mapper) + if abort { + return action, nil, nil } - toAddr := sdk.AccAddress(toKey.PubKey().Address()) - initFromCoins := mapper.GetAccount(ctx, fromAddr).GetCoins() - - if len(initFromCoins) == 0 { - return "skipping, no coins at all", nil + err = sendAndVerifyMsgSend(app, mapper, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}, nil) + if err != nil { + return "", nil, err } + event("bank/sendAndVerifyTxSend/ok") - denomIndex := r.Intn(len(initFromCoins)) - // avoid the rest amt less than fee - amt, goErr := randPositiveInt(r, initFromCoins[denomIndex].Amount.Div(sdk.NewInt(2))) - if goErr != nil { - return "skipping bank send due to account having no coins of denomination " + initFromCoins[denomIndex].Denom, nil - } + return action, nil, nil + } +} - action = fmt.Sprintf("%s is sending %s %s to %s", - fromAddr.String(), - amt.String(), - initFromCoins[denomIndex].Denom, - toAddr.String(), - ) - log = fmt.Sprintf("%s\n%s", log, action) - - coins := sdk.Coins{{initFromCoins[denomIndex].Denom, amt}} - var msg = bank.MsgSend{ - Inputs: []bank.Input{bank.NewInput(fromAddr, coins)}, - Outputs: []bank.Output{bank.NewOutput(toAddr, coins)}, +// SingleInputSendMsg tests and runs a single msg send, with one input and one output, where both +// accounts already exist. +func SingleInputSendMsg(mapper auth.AccountKeeper, bk bank.Keeper) simulation.Operation { + handler := bank.NewHandler(bk) + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) (action string, fOps []simulation.FutureOperation, err error) { + fromAcc, action, msg, abort := createSingleInputSendMsg(r, ctx, accs, mapper) + if abort { + return action, nil, nil + } + err = sendAndVerifyMsgSend(app, mapper, msg, ctx, []crypto.PrivKey{fromAcc.PrivKey}, handler) + if err != nil { + return "", nil, err } - sendAndVerifyMsgSend(t, app, mapper, msg, ctx, log, []crypto.PrivKey{fromKey}) event("bank/sendAndVerifyMsgSend/ok") - return action, nil + return action, nil, nil } } +func createSingleInputSendMsg(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, mapper auth.AccountKeeper) (fromAcc simulation.Account, action string, msg bank.MsgSend, abort bool) { + fromAcc = simulation.RandomAcc(r, accs) + toAcc := simulation.RandomAcc(r, accs) + // Disallow sending money to yourself + for { + if !fromAcc.PubKey.Equals(toAcc.PubKey) { + break + } + toAcc = simulation.RandomAcc(r, accs) + } + toAddr := toAcc.Address + initFromCoins := mapper.GetAccount(ctx, fromAcc.Address).GetCoins() + + if len(initFromCoins) == 0 { + return fromAcc, "skipping, no coins at all", msg, true + } + + denomIndex := r.Intn(len(initFromCoins)) + amt, goErr := randPositiveInt(r, initFromCoins[denomIndex].Amount) + if goErr != nil { + return fromAcc, "skipping bank send due to account having no coins of denomination " + initFromCoins[denomIndex].Denom, msg, true + } + + action = fmt.Sprintf("%s is sending %s %s to %s", + fromAcc.Address.String(), + amt.String(), + initFromCoins[denomIndex].Denom, + toAddr.String(), + ) + + coins := sdk.Coins{{initFromCoins[denomIndex].Denom, amt}} + msg = bank.MsgSend{ + Inputs: []bank.Input{bank.NewInput(fromAcc.Address, coins)}, + Outputs: []bank.Output{bank.NewOutput(toAddr, coins)}, + } + return +} + // Sends and verifies the transition of a msg send. This fails if there are repeated inputs or outputs -func sendAndVerifyMsgSend(t *testing.T, app *baseapp.BaseApp, mapper auth.AccountMapper, msg bank.MsgSend, ctx sdk.Context, log string, privkeys []crypto.PrivKey) { +// pass in handler as nil to handle txs, otherwise handle msgs +func sendAndVerifyMsgSend(app *baseapp.BaseApp, mapper auth.AccountKeeper, msg bank.MsgSend, ctx sdk.Context, privkeys []crypto.PrivKey, handler sdk.Handler) error { initialInputAddrCoins := make([]sdk.Coins, len(msg.Inputs)) initialOutputAddrCoins := make([]sdk.Coins, len(msg.Outputs)) AccountNumbers := make([]int64, len(msg.Inputs)) @@ -83,45 +109,37 @@ func sendAndVerifyMsgSend(t *testing.T, app *baseapp.BaseApp, mapper auth.Accoun acc := mapper.GetAccount(ctx, msg.Outputs[i].Address) initialOutputAddrCoins[i] = acc.GetCoins() } - tx := mock.GenTx([]sdk.Msg{msg}, - AccountNumbers, - SequenceNumbers, - privkeys...) - res := app.Deliver(tx) - if !res.IsOK() { - // TODO: Do this in a more 'canonical' way - fmt.Println(res) - fmt.Println(log) - t.FailNow() - } - - kvs := res.Tags.ToKVPairs() - - feeCoin := []sdk.Coin{{Denom: "iris-atto", Amount: sdk.NewInt(0)}} - for _, v := range kvs { - if string(v.Key) == "completeConsumedTxFee-iris-atto" { - amount := sdk.NewInt(0).BigInt() - amount.UnmarshalJSON(v.Value) - feeCoin[0].Amount = sdk.NewIntFromBigInt(amount) + if handler != nil { + res := handler(ctx, msg) + if !res.IsOK() { + // TODO: Do this in a more 'canonical' way + return fmt.Errorf("handling msg failed %v", res) + } + } else { + tx := mock.GenTx([]sdk.Msg{msg}, + AccountNumbers, + SequenceNumbers, + privkeys...) + res := app.Deliver(tx) + if !res.IsOK() { + // TODO: Do this in a more 'canonical' way + return fmt.Errorf("Deliver failed %v", res) } } for i := 0; i < len(msg.Inputs); i++ { terminalInputCoins := mapper.GetAccount(ctx, msg.Inputs[i].Address).GetCoins() - require.Equal(t, - initialInputAddrCoins[i].Minus(msg.Inputs[i].Coins).Minus(feeCoin), - terminalInputCoins, - fmt.Sprintf("Input #%d had an incorrect amount of coins\n%s", i, log), - ) + if !initialInputAddrCoins[i].Minus(msg.Inputs[i].Coins).IsEqual(terminalInputCoins) { + return fmt.Errorf("input #%d had an incorrect amount of coins", i) + } } for i := 0; i < len(msg.Outputs); i++ { terminalOutputCoins := mapper.GetAccount(ctx, msg.Outputs[i].Address).GetCoins() - require.Equal(t, - initialOutputAddrCoins[i].Plus(msg.Outputs[i].Coins), - terminalOutputCoins, - fmt.Sprintf("Output #%d had an incorrect amount of coins\n%s", i, log), - ) + if !terminalOutputCoins.IsEqual(initialOutputAddrCoins[i].Plus(msg.Outputs[i].Coins)) { + return fmt.Errorf("output #%d had an incorrect amount of coins", i) + } } + return nil } func randPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { diff --git a/simulation/bank/sim_test.go b/simulation/bank/sim_test.go index 57ae98381..a01a92dfc 100644 --- a/simulation/bank/sim_test.go +++ b/simulation/bank/sim_test.go @@ -5,8 +5,6 @@ import ( "math/rand" "testing" - "github.com/tendermint/tendermint/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/irisnet/irishub/simulation/mock" @@ -16,32 +14,33 @@ import ( func TestBankWithRandomMessages(t *testing.T) { mapp := mock.NewApp() - bank.RegisterWire(mapp.Cdc) - mapper := mapp.AccountMapper - coinKeeper := bank.NewKeeper(mapper) - mapp.Router().AddRoute("bank", []*sdk.KVStoreKey{mapp.KeyAccount}, bank.NewHandler(coinKeeper)) + bank.RegisterCodec(mapp.Cdc) + mapper := mapp.AccountKeeper + bankKeeper := mapp.BankKeeper + + mapp.Router().AddRoute("bank", []*sdk.KVStoreKey{mapp.KeyAccount}, bank.NewHandler(bankKeeper)) - err := mapp.CompleteSetup([]*sdk.KVStoreKey{}) + err := mapp.CompleteSetup() if err != nil { panic(err) } - appStateFn := func(r *rand.Rand, keys []crypto.PrivKey, accs []sdk.AccAddress) json.RawMessage { - mock.RandomSetGenesis(r, mapp, accs, []string{"iris-atto"}) + appStateFn := func(r *rand.Rand, accs []simulation.Account) json.RawMessage { + simulation.RandomSetGenesis(r, mapp, accs, []string{"iris-atto"}) return json.RawMessage("{}") } simulation.Simulate( t, mapp.BaseApp, appStateFn, - []simulation.TestAndRunTx{ - TestAndRunSingleInputMsgSend(mapper), + []simulation.WeightedOperation{ + {1, SingleInputSendMsg(mapper, bankKeeper)}, }, []simulation.RandSetup{}, []simulation.Invariant{ NonnegativeBalanceInvariant(mapper), TotalCoinsInvariant(mapper, func() sdk.Coins { return mapp.TotalCoinsSupply }), }, - 30, 30, + 30, 60, false, ) } diff --git a/simulation/gov/invariants.go b/simulation/gov/invariants.go index 6752720e9..7a288b21f 100644 --- a/simulation/gov/invariants.go +++ b/simulation/gov/invariants.go @@ -1,19 +1,15 @@ package simulation import ( - "testing" - - "github.com/stretchr/testify/require" - "github.com/irisnet/irishub/baseapp" "github.com/irisnet/irishub/simulation/mock/simulation" ) // AllInvariants tests all governance invariants func AllInvariants() simulation.Invariant { - return func(t *testing.T, app *baseapp.BaseApp, log string) { + return func(app *baseapp.BaseApp) error { // TODO Add some invariants! // Checking proposal queues, no passed-but-unexecuted proposals, etc. - require.Nil(t, nil) + return nil } } diff --git a/simulation/gov/msgs.go b/simulation/gov/msgs.go index 096477a2b..2a4a94c7c 100644 --- a/simulation/gov/msgs.go +++ b/simulation/gov/msgs.go @@ -2,101 +2,200 @@ package simulation import ( "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/irisnet/irishub/modules/gov" + "math" "math/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/tendermint/tendermint/crypto" + "time" "github.com/irisnet/irishub/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/irisnet/irishub/modules/gov" "github.com/irisnet/irishub/simulation/mock/simulation" - "github.com/cosmos/cosmos-sdk/x/stake" ) const ( denom = "steak" ) -// SimulateMsgSubmitProposal -func SimulateMsgSubmitProposal(k gov.Keeper, sk stake.Keeper) simulation.TestAndRunTx { - return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, err sdk.Error) { - key := simulation.RandomKey(r, keys) - addr := sdk.AccAddress(key.PubKey().Address()) - deposit := randomDeposit(r) - msg := gov.NewMsgSubmitProposal( - simulation.RandStringOfLength(r, 5), - simulation.RandStringOfLength(r, 5), - gov.ProposalTypeText, - addr, - deposit, - gov.Param{}, - ) - require.Nil(t, msg.ValidateBasic(), "expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - ctx, write := ctx.CacheContext() - result := gov.NewHandler(k)(ctx, msg) - if result.IsOK() { - // Update pool to keep invariants - pool := sk.GetPool(ctx) - pool.LooseTokens = pool.LooseTokens.Sub(sdk.NewRatFromInt(deposit.AmountOf(denom))) - sk.SetPool(ctx, pool) - write() +// SimulateSubmittingVotingAndSlashingForProposal simulates creating a msg Submit Proposal +// voting on the proposal, and subsequently slashing the proposal. It is implemented using +// future operations. +// TODO: Vote more intelligently, so we can actually do some checks regarding votes passing or failing +// TODO: Actually check that validator slashings happened +func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, sk stake.Keeper) simulation.Operation { + handler := gov.NewHandler(k) + // The states are: + // column 1: All validators vote + // column 2: 90% vote + // column 3: 75% vote + // column 4: 40% vote + // column 5: 15% vote + // column 6: noone votes + // All columns sum to 100 for simplicity, values chosen by @valardragon semi-arbitrarily, + // feel free to change. + numVotesTransitionMatrix, _ := simulation.CreateTransitionMatrix([][]int{ + {20, 10, 0, 0, 0, 0}, + {55, 50, 20, 10, 0, 0}, + {25, 25, 30, 25, 30, 15}, + {0, 15, 30, 25, 30, 30}, + {0, 0, 20, 30, 30, 30}, + {0, 0, 0, 10, 10, 25}, + }) + statePercentageArray := []float64{1, .9, .75, .4, .15, 0} + curNumVotesState := 1 + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) (action string, fOps []simulation.FutureOperation, err error) { + // 1) submit proposal now + sender := simulation.RandomAcc(r, accs) + msg, err := simulationCreateMsgSubmitProposal(r, sender) + if err != nil { + return "", nil, err } - event(fmt.Sprintf("gov/MsgSubmitProposal/%v", result.IsOK())) - action = fmt.Sprintf("TestMsgSubmitProposal: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) - return action, nil + action, ok := simulateHandleMsgSubmitProposal(msg, sk, handler, ctx, event) + // don't schedule votes if proposal failed + if !ok { + return action, nil, nil + } + proposalID := k.GetLastProposalID(ctx) + // 2) Schedule operations for votes + // 2.1) first pick a number of people to vote. + curNumVotesState = numVotesTransitionMatrix.NextState(r, curNumVotesState) + numVotes := int(math.Ceil(float64(len(accs)) * statePercentageArray[curNumVotesState])) + // 2.2) select who votes and when + whoVotes := r.Perm(len(accs)) + // didntVote := whoVotes[numVotes:] + whoVotes = whoVotes[:numVotes] + // TODO: can't find GetVotingProcedure method, use customized votingPeriod + //votingPeriod := k.GetVotingProcedure(ctx).VotingPeriod + votingPeriod := time.Duration(60) * time.Second + fops := make([]simulation.FutureOperation, numVotes+1) + for i := 0; i < numVotes; i++ { + whenVote := ctx.BlockHeader().Time.Add(time.Duration(r.Int63n(int64(votingPeriod.Seconds()))) * time.Second) + fops[i] = simulation.FutureOperation{BlockTime: whenVote, Op: operationSimulateMsgVote(k, sk, accs[whoVotes[i]], int64(proposalID))} + } + // 3) Make an operation to ensure slashes were done correctly. (Really should be a future invariant) + // TODO: Find a way to check if a validator was slashed other than just checking their balance a block + // before and after. + + return action, fops, nil } } +// SimulateMsgSubmitProposal simulates a msg Submit Proposal +// Note: Currently doesn't ensure that the proposal txt is in JSON form +func SimulateMsgSubmitProposal(k gov.Keeper, sk stake.Keeper) simulation.Operation { + handler := gov.NewHandler(k) + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) (action string, fOps []simulation.FutureOperation, err error) { + sender := simulation.RandomAcc(r, accs) + msg, err := simulationCreateMsgSubmitProposal(r, sender) + if err != nil { + return "", nil, err + } + action, _ = simulateHandleMsgSubmitProposal(msg, sk, handler, ctx, event) + return action, nil, nil + } +} + +func simulateHandleMsgSubmitProposal(msg gov.MsgSubmitProposal, sk stake.Keeper, handler sdk.Handler, ctx sdk.Context, event func(string)) (action string, ok bool) { + ctx, write := ctx.CacheContext() + result := handler(ctx, msg) + ok = result.IsOK() + if ok { + // Update pool to keep invariants + pool := sk.GetPool(ctx) + pool.LooseTokens = pool.LooseTokens.Sub(sdk.NewDecFromInt(msg.InitialDeposit.AmountOf(denom))) + sk.SetPool(ctx, pool) + write() + } + event(fmt.Sprintf("gov/MsgSubmitProposal/%v", ok)) + action = fmt.Sprintf("TestMsgSubmitProposal: ok %v, msg %s", ok, msg.GetSignBytes()) + return +} + +func simulationCreateMsgSubmitProposal(r *rand.Rand, sender simulation.Account) (msg gov.MsgSubmitProposal, err error) { + deposit := randomDeposit(r) + param := gov.Param{ + Key: "test", + Value: "value", + } + msg = gov.NewMsgSubmitProposal( + simulation.RandStringOfLength(r, 5), + simulation.RandStringOfLength(r, 5), + gov.ProposalTypeText, + sender.Address, + deposit, + param, + ) + if msg.ValidateBasic() != nil { + err = fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + } + return +} + // SimulateMsgDeposit -func SimulateMsgDeposit(k gov.Keeper, sk stake.Keeper) simulation.TestAndRunTx { - return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, err sdk.Error) { - key := simulation.RandomKey(r, keys) - addr := sdk.AccAddress(key.PubKey().Address()) +func SimulateMsgDeposit(k gov.Keeper, sk stake.Keeper) simulation.Operation { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) (action string, fOp []simulation.FutureOperation, err error) { + acc := simulation.RandomAcc(r, accs) proposalID, ok := randomProposalID(r, k, ctx) if !ok { - return "no-operation", nil + return "no-operation", nil, nil } deposit := randomDeposit(r) - msg := gov.NewMsgDeposit(addr, proposalID, deposit) - require.Nil(t, msg.ValidateBasic(), "expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + msg := gov.NewMsgDeposit(acc.Address, uint64(proposalID), deposit) + if msg.ValidateBasic() != nil { + return "", nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + } ctx, write := ctx.CacheContext() result := gov.NewHandler(k)(ctx, msg) if result.IsOK() { // Update pool to keep invariants pool := sk.GetPool(ctx) - pool.LooseTokens = pool.LooseTokens.Sub(sdk.NewRatFromInt(deposit.AmountOf(denom))) + pool.LooseTokens = pool.LooseTokens.Sub(sdk.NewDecFromInt(deposit.AmountOf(denom))) sk.SetPool(ctx, pool) write() } event(fmt.Sprintf("gov/MsgDeposit/%v", result.IsOK())) action = fmt.Sprintf("TestMsgDeposit: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) - return action, nil + return action, nil, nil } } // SimulateMsgVote -func SimulateMsgVote(k gov.Keeper, sk stake.Keeper) simulation.TestAndRunTx { - return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, err sdk.Error) { - key := simulation.RandomKey(r, keys) - addr := sdk.AccAddress(key.PubKey().Address()) - proposalID, ok := randomProposalID(r, k, ctx) - if !ok { - return "no-operation", nil +// nolint: unparam +func SimulateMsgVote(k gov.Keeper, sk stake.Keeper) simulation.Operation { + return operationSimulateMsgVote(k, sk, simulation.Account{}, -1) +} + +// nolint: unparam +func operationSimulateMsgVote(k gov.Keeper, sk stake.Keeper, acc simulation.Account, proposalID int64) simulation.Operation { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) (action string, fOp []simulation.FutureOperation, err error) { + if acc.Equals(simulation.Account{}) { + acc = simulation.RandomAcc(r, accs) + } + + var ok bool + + if proposalID < 0 { + proposalID, ok = randomProposalID(r, k, ctx) + if !ok { + return "no-operation", nil, nil + } } option := randomVotingOption(r) - msg := gov.NewMsgVote(addr, proposalID, option) - require.Nil(t, msg.ValidateBasic(), "expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + + msg := gov.NewMsgVote(acc.Address, uint64(proposalID), option) + if msg.ValidateBasic() != nil { + return "", nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + } + ctx, write := ctx.CacheContext() result := gov.NewHandler(k)(ctx, msg) if result.IsOK() { write() } + event(fmt.Sprintf("gov/MsgVote/%v", result.IsOK())) action = fmt.Sprintf("TestMsgVote: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) - return action, nil + return action, nil, nil } } diff --git a/simulation/gov/sim_test.go b/simulation/gov/sim_test.go index ab0824c61..1dc645a5a 100644 --- a/simulation/gov/sim_test.go +++ b/simulation/gov/sim_test.go @@ -6,57 +6,86 @@ import ( "testing" abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/stake" "github.com/irisnet/irishub/modules/gov" "github.com/irisnet/irishub/simulation/mock" "github.com/irisnet/irishub/simulation/mock/simulation" - "github.com/cosmos/cosmos-sdk/x/stake" ) // TestGovWithRandomMessages func TestGovWithRandomMessages(t *testing.T) { mapp := mock.NewApp() - bank.RegisterWire(mapp.Cdc) - gov.RegisterWire(mapp.Cdc) - mapper := mapp.AccountMapper - coinKeeper := bank.NewKeeper(mapper) - stakeKey := sdk.NewKVStoreKey("stake") - stakeKeeper := stake.NewKeeper(mapp.Cdc, stakeKey, coinKeeper, stake.DefaultCodespace) - paramKey := sdk.NewKVStoreKey("params") + bank.RegisterCodec(mapp.Cdc) + gov.RegisterCodec(mapp.Cdc) + + bankKeeper := mapp.BankKeeper + stakeKey := mapp.KeyStake + stakeTKey := mapp.TkeyStake + paramKey := mapp.KeyParams govKey := sdk.NewKVStoreKey("gov") - govKeeper := gov.NewKeeper(mapp.Cdc, govKey, coinKeeper, stakeKeeper, gov.DefaultCodespace) - mapp.Router().AddRoute("gov", []*sdk.KVStoreKey{mapp.KeyGov, mapp.KeyAccount, mapp.KeyStake, mapp.KeyParams}, gov.NewHandler(govKeeper)) + + paramKeeper := mapp.ParamsKeeper + stakeKeeper := stake.NewKeeper( + mapp.Cdc, stakeKey, + stakeTKey, bankKeeper, + paramKeeper.Subspace(stake.DefaultParamspace), + stake.DefaultCodespace, + ) + govKeeper := gov.NewKeeper( + mapp.Cdc, + govKey, + bankKeeper, stakeKeeper, + mapp.RegisterCodespace(gov.DefaultCodespace), + ) + + mapp.Router().AddRoute("gov", []*sdk.KVStoreKey{govKey, mapp.KeyAccount, stakeKey, paramKey}, gov.NewHandler(govKeeper)) mapp.SetEndBlocker(func(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { gov.EndBlocker(ctx, govKeeper) return abci.ResponseEndBlock{} }) - err := mapp.CompleteSetup([]*sdk.KVStoreKey{stakeKey, paramKey, govKey}) + err := mapp.CompleteSetup(govKey) if err != nil { panic(err) } - appStateFn := func(r *rand.Rand, keys []crypto.PrivKey, accs []sdk.AccAddress) json.RawMessage { - mock.RandomSetGenesis(r, mapp, accs, []string{"iris"}) + appStateFn := func(r *rand.Rand, accs []simulation.Account) json.RawMessage { + simulation.RandomSetGenesis(r, mapp, accs, []string{"stake"}) return json.RawMessage("{}") } - setup := func(r *rand.Rand, privKeys []crypto.PrivKey) { + setup := func(r *rand.Rand, accs []simulation.Account) { ctx := mapp.NewContext(false, abci.Header{}) stake.InitGenesis(ctx, stakeKeeper, stake.DefaultGenesisState()) + gov.InitGenesis(ctx, govKeeper, gov.DefaultGenesisState()) } + // Test with unscheduled votes + simulation.Simulate( + t, mapp.BaseApp, appStateFn, + []simulation.WeightedOperation{ + {2, SimulateMsgSubmitProposal(govKeeper, stakeKeeper)}, + {3, SimulateMsgDeposit(govKeeper, stakeKeeper)}, + {20, SimulateMsgVote(govKeeper, stakeKeeper)}, + }, []simulation.RandSetup{ + setup, + }, []simulation.Invariant{ + //AllInvariants(), + }, 10, 100, + false, + ) + + // Test with scheduled votes simulation.Simulate( t, mapp.BaseApp, appStateFn, - []simulation.TestAndRunTx{ - SimulateMsgSubmitProposal(govKeeper, stakeKeeper), - SimulateMsgDeposit(govKeeper, stakeKeeper), - SimulateMsgVote(govKeeper, stakeKeeper), + []simulation.WeightedOperation{ + {10, SimulateSubmittingVotingAndSlashingForProposal(govKeeper, stakeKeeper)}, + {5, SimulateMsgDeposit(govKeeper, stakeKeeper)}, }, []simulation.RandSetup{ setup, }, []simulation.Invariant{ diff --git a/simulation/mock/app.go b/simulation/mock/app.go index 21d46cc2a..4ed054bd8 100644 --- a/simulation/mock/app.go +++ b/simulation/mock/app.go @@ -4,42 +4,69 @@ import ( "math/rand" "os" - bam "github.com/irisnet/irishub/baseapp" + "fmt" + "github.com/cosmos/cosmos-sdk/codec" 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/params" + bam "github.com/irisnet/irishub/baseapp" + "github.com/irisnet/irishub/iparam" + "github.com/irisnet/irishub/modules/gov/params" + "github.com/irisnet/irishub/modules/service/params" + "github.com/irisnet/irishub/types" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/crypto/secp256k1" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" - "github.com/irisnet/irishub/types" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/irisnet/irishub/modules/iparam" - "github.com/irisnet/irishub/modules/gov/params" ) -const chainID = "" +const ( + chainID = "" + Denom = "iris" + MiniDenom = "iris-atto" + DefaultStakeDenom = "steak" +) + +const ( + // Bech32PrefixAccAddr defines the Bech32 prefix of an account's address + bech32PrefixAccAddr = "faa" + // Bech32PrefixAccPub defines the Bech32 prefix of an account's public key + bech32PrefixAccPub = "fap" + // Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address + bech32PrefixValAddr = "fva" + // Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key + bech32PrefixValPub = "fvp" + // Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address + bech32PrefixConsAddr = "fca" + // Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key + bech32PrefixConsPub = "fcp" +) + +var ( + IrisCt = types.NewDefaultCoinType(Denom) +) // App extends an ABCI application, but with most of its parameters exported. // They are exported for convenience in creating helper functions, as object // capabilities aren't needed for testing. type App struct { *bam.BaseApp - Cdc *wire.Codec // Cdc is public since the codec is passed into the module anyways + Cdc *codec.Codec // Cdc is public since the codec is passed into the module anyways KeyMain *sdk.KVStoreKey KeyAccount *sdk.KVStoreKey - KeyIBC *sdk.KVStoreKey - KeyStake *sdk.KVStoreKey - KeySlashing *sdk.KVStoreKey - KeyGov *sdk.KVStoreKey KeyFeeCollection *sdk.KVStoreKey + KeyStake *sdk.KVStoreKey + TkeyStake *sdk.TransientStoreKey KeyParams *sdk.KVStoreKey + TkeyParams *sdk.TransientStoreKey KeyUpgrade *sdk.KVStoreKey // TODO: Abstract this out from not needing to be auth specifically - AccountMapper auth.AccountMapper + AccountKeeper auth.AccountKeeper + BankKeeper bank.Keeper FeeCollectionKeeper auth.FeeCollectionKeeper ParamsKeeper params.Keeper @@ -57,54 +84,72 @@ func NewApp() *App { db := dbm.NewMemDB() // Create the cdc with some standard codecs - cdc := wire.NewCodec() - sdk.RegisterWire(cdc) - wire.RegisterCrypto(cdc) - auth.RegisterWire(cdc) + cdc := codec.New() + auth.RegisterCodec(cdc) + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) + + config := sdk.GetConfig() + config.SetBech32PrefixForAccount(bech32PrefixAccAddr, bech32PrefixAccPub) + config.SetBech32PrefixForValidator(bech32PrefixValAddr, bech32PrefixValPub) + config.SetBech32PrefixForConsensusNode(bech32PrefixConsAddr, bech32PrefixConsPub) + config.Seal() + + bApp := bam.NewBaseApp("mock", logger, db, auth.DefaultTxDecoder(cdc), bam.SetPruning("nothing")) // Create your application object app := &App{ - BaseApp: bam.NewBaseApp("mock", cdc, logger, db, auth.DefaultTxDecoder(cdc), bam.SetPruning("nothing")), + 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"), + KeyStake: sdk.NewKVStoreKey("stake"), + TkeyStake: sdk.NewTransientStoreKey("transient_stake"), KeyParams: sdk.NewKVStoreKey("params"), + TkeyParams: sdk.NewTransientStoreKey("transient_params"), KeyUpgrade: sdk.NewKVStoreKey("upgrade"), TotalCoinsSupply: sdk.Coins{}, } - // Define the accountMapper - app.AccountMapper = auth.NewAccountMapper( + // Define the AccountKeeper + app.AccountKeeper = auth.NewAccountKeeper( app.Cdc, app.KeyAccount, auth.ProtoBaseAccount, ) - paramsKeeper := params.NewKeeper(app.Cdc, app.KeyParams) - app.ParamsKeeper = paramsKeeper - app.FeeManager = bam.NewFeeManager(app.ParamsKeeper.Setter()) + app.BankKeeper = bank.NewBaseKeeper(app.AccountKeeper) + app.FeeCollectionKeeper = auth.NewFeeCollectionKeeper(app.Cdc, app.KeyFeeCollection) + + app.ParamsKeeper = params.NewKeeper( + app.Cdc, + app.KeyParams, app.TkeyParams, + ) - // Initialize the app. The chainers and blockers can be overwritten before - // calling complete setup. app.SetInitChainer(app.InitChainer) - app.FeeCollectionKeeper = auth.NewFeeCollectionKeeper(app.Cdc, app.KeyFeeCollection) - app.SetAnteHandler(auth.NewAnteHandler(app.AccountMapper, app.FeeCollectionKeeper)) - app.SetFeeRefundHandler(bam.NewFeeRefundHandler(app.AccountMapper, app.FeeCollectionKeeper, app.FeeManager)) + app.SetAnteHandler(auth.NewAnteHandler(app.AccountKeeper, app.FeeCollectionKeeper)) + app.SetFeeRefundHandler(bam.NewFeeRefundHandler(app.AccountKeeper, app.FeeCollectionKeeper, app.FeeManager)) app.SetFeePreprocessHandler(bam.NewFeePreprocessHandler(app.FeeManager)) // Not sealing for custom extension - // init iparam - iparam.SetParamReadWriter(paramsKeeper.Setter(), + iparam.SetParamReadWriter(app.ParamsKeeper.Subspace(iparam.GovParamspace).WithTypeTable( + params.NewTypeTable( + govparams.DepositProcedureParameter.GetStoreKey(), govparams.DepositProcedure{}, + govparams.VotingProcedureParameter.GetStoreKey(), govparams.VotingProcedure{}, + govparams.TallyingProcedureParameter.GetStoreKey(), govparams.TallyingProcedure{}, + serviceparams.MaxRequestTimeoutParameter.GetStoreKey(), int64(0), + serviceparams.MinProviderDepositParameter.GetStoreKey(), sdk.Coins{}, + )), &govparams.DepositProcedureParameter, &govparams.VotingProcedureParameter, - &govparams.TallyingProcedureParameter) - iparam.RegisterGovParamMapping(&govparams.DepositProcedureParameter, + &govparams.TallyingProcedureParameter, + &serviceparams.MaxRequestTimeoutParameter, + &serviceparams.MinProviderDepositParameter) + + iparam.RegisterGovParamMapping( + &govparams.DepositProcedureParameter, &govparams.VotingProcedureParameter, &govparams.TallyingProcedureParameter) @@ -113,13 +158,26 @@ func NewApp() *App { // CompleteSetup completes the application setup after the routes have been // registered. -func (app *App) CompleteSetup(newKeys []*sdk.KVStoreKey) error { +func (app *App) CompleteSetup(newKeys ...sdk.StoreKey) error { newKeys = append(newKeys, app.KeyMain) newKeys = append(newKeys, app.KeyAccount) newKeys = append(newKeys, app.KeyParams) + newKeys = append(newKeys, app.KeyStake) newKeys = append(newKeys, app.KeyFeeCollection) + newKeys = append(newKeys, app.TkeyParams) + newKeys = append(newKeys, app.TkeyStake) + + for _, key := range newKeys { + switch key.(type) { + case *sdk.KVStoreKey: + app.MountStore(key, sdk.StoreTypeIAVL) + case *sdk.TransientStoreKey: + app.MountStore(key, sdk.StoreTypeTransient) + default: + return fmt.Errorf("unsupported StoreKey: %+v", key) + } + } - app.MountStoresIAVL(newKeys...) err := app.LoadLatestVersion(app.KeyMain) return err @@ -129,17 +187,11 @@ func (app *App) CompleteSetup(newKeys []*sdk.KVStoreKey) error { func (app *App) InitChainer(ctx sdk.Context, _ abci.RequestInitChain) abci.ResponseInitChain { // Load the genesis accounts for _, genacc := range app.GenesisAccounts { - acc := app.AccountMapper.NewAccountWithAddress(ctx, genacc.GetAddress()) + acc := app.AccountKeeper.NewAccountWithAddress(ctx, genacc.GetAddress()) acc.SetCoins(genacc.GetCoins()) - app.AccountMapper.SetAccount(ctx, acc) + app.AccountKeeper.SetAccount(ctx, acc) } - feeTokenGensisConfig := bam.FeeGenesisStateConfig{ - FeeTokenNative: types.NewDefaultCoinType("iris").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) - return abci.ResponseInitChain{} } @@ -255,21 +307,21 @@ func GeneratePrivKeyAddressPairsFromRand(rand *rand.Rand, n int) (keys []crypto. // provided addresses and coin denominations. func RandomSetGenesis(r *rand.Rand, app *App, addrs []sdk.AccAddress, denoms []string) { accts := make([]auth.Account, len(addrs), len(addrs)) - randCoinIntervals := []BigInterval{ - {sdk.NewIntWithDecimal(1, 0), sdk.NewIntWithDecimal(1, 1)}, - {sdk.NewIntWithDecimal(1, 2), sdk.NewIntWithDecimal(1, 3)}, - {sdk.NewIntWithDecimal(1, 40), sdk.NewIntWithDecimal(1, 50)}, - } + //randCoinIntervals := []BigInterval{ + // {sdk.NewIntWithDecimal(1, 0), sdk.NewIntWithDecimal(1, 1)}, + // {sdk.NewIntWithDecimal(1, 2), sdk.NewIntWithDecimal(1, 3)}, + // {sdk.NewIntWithDecimal(1, 40), sdk.NewIntWithDecimal(1, 50)}, + //} for i := 0; i < len(accts); i++ { coins := make([]sdk.Coin, len(denoms), len(denoms)) - amountStr := "100000000000000000000" - amount, _ := sdk.NewIntFromString(amountStr) + amount := sdk.NewIntWithDecimal(1, 2) // generate a random coin for each denomination for j := 0; j < len(denoms); j++ { coins[j] = sdk.Coin{Denom: denoms[j], - Amount: RandFromBigInterval(r, randCoinIntervals).Add(amount), + //Amount: RandFromBigInterval(r, randCoinIntervals).Add(amount), + Amount: amount, } } @@ -279,11 +331,12 @@ func RandomSetGenesis(r *rand.Rand, app *App, addrs []sdk.AccAddress, denoms []s (&baseAcc).SetCoins(coins) accts[i] = &baseAcc } + app.GenesisAccounts = accts } -// GetAllAccounts returns all accounts in the accountMapper. -func GetAllAccounts(mapper auth.AccountMapper, ctx sdk.Context) []auth.Account { +// GetAllAccounts returns all accounts in the AccountKeeper. +func GetAllAccounts(mapper auth.AccountKeeper, ctx sdk.Context) []auth.Account { accounts := []auth.Account{} appendAccount := func(acc auth.Account) (stop bool) { accounts = append(accounts, acc) diff --git a/simulation/mock/simulation/constants.go b/simulation/mock/simulation/constants.go deleted file mode 100644 index 6afba79a4..000000000 --- a/simulation/mock/simulation/constants.go +++ /dev/null @@ -1,36 +0,0 @@ -package simulation - -const ( - // Fraction of double-signing evidence from a past height - pastEvidenceFraction float64 = 0.5 - - // Minimum time per block - minTimePerBlock int64 = 86400 / 2 - - // Maximum time per block - maxTimePerBlock int64 = 86400 - - // Number of keys - numKeys int = 250 - - // Chance that double-signing evidence is found on a given block - evidenceFraction float64 = 0.01 - - // TODO Remove in favor of binary search for invariant violation - onOperation bool = false -) - -// kv -const ( - -) - -var ( - // Currently there are 3 different liveness types, fully online, spotty connection, offline. - initialLivenessWeightings = []int{40, 5, 5} - livenessTransitionMatrix, _ = CreateTransitionMatrix([][]int{ - {90, 20, 1}, - {10, 50, 5}, - {0, 10, 1000}, - }) -) diff --git a/simulation/mock/simulation/params.go b/simulation/mock/simulation/params.go new file mode 100644 index 000000000..5d7e2f264 --- /dev/null +++ b/simulation/mock/simulation/params.go @@ -0,0 +1,64 @@ +package simulation + +import "math/rand" + +const ( + // Minimum time per block + minTimePerBlock int64 = 10000 / 2 + + // Maximum time per block + maxTimePerBlock int64 = 10000 + + // TODO Remove in favor of binary search for invariant violation + onOperation bool = false +) + +var ( + // Currently there are 3 different liveness types, fully online, spotty connection, offline. + defaultLivenessTransitionMatrix, _ = CreateTransitionMatrix([][]int{ + {90, 20, 1}, + {10, 50, 5}, + {0, 10, 1000}, + }) + + // 3 states: rand in range [0, 4*provided blocksize], rand in range [0, 2 * provided blocksize], 0 + defaultBlockSizeTransitionMatrix, _ = CreateTransitionMatrix([][]int{ + {85, 5, 0}, + {15, 92, 1}, + {0, 3, 99}, + }) +) + +// Simulation parameters +type Params struct { + PastEvidenceFraction float64 + NumKeys int + EvidenceFraction float64 + InitialLivenessWeightings []int + LivenessTransitionMatrix TransitionMatrix + BlockSizeTransitionMatrix TransitionMatrix +} + +// Return default simulation parameters +func DefaultParams() Params { + return Params{ + PastEvidenceFraction: 0.5, + NumKeys: 250, + EvidenceFraction: 0.5, + InitialLivenessWeightings: []int{40, 5, 5}, + LivenessTransitionMatrix: defaultLivenessTransitionMatrix, + BlockSizeTransitionMatrix: defaultBlockSizeTransitionMatrix, + } +} + +// Return random simulation parameters +func RandomParams(r *rand.Rand) Params { + return Params{ + PastEvidenceFraction: r.Float64(), + NumKeys: r.Intn(250), + EvidenceFraction: r.Float64(), + InitialLivenessWeightings: []int{r.Intn(80), r.Intn(10), r.Intn(10)}, + LivenessTransitionMatrix: defaultLivenessTransitionMatrix, + BlockSizeTransitionMatrix: defaultBlockSizeTransitionMatrix, + } +} diff --git a/simulation/mock/simulation/random_simulate_blocks.go b/simulation/mock/simulation/random_simulate_blocks.go index 2220e5a12..d84f8681c 100644 --- a/simulation/mock/simulation/random_simulate_blocks.go +++ b/simulation/mock/simulation/random_simulate_blocks.go @@ -4,128 +4,356 @@ import ( "encoding/json" "fmt" "math/rand" + "os" + "os/signal" + "runtime/debug" "sort" + "strings" + "syscall" "testing" "time" + sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto" + cmn "github.com/tendermint/tendermint/libs/common" tmtypes "github.com/tendermint/tendermint/types" "github.com/irisnet/irishub/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/irisnet/irishub/simulation/mock" - "github.com/stretchr/testify/require" ) // Simulate tests application by sending random messages. -func Simulate( - t *testing.T, app *baseapp.BaseApp, appStateFn func(r *rand.Rand, keys []crypto.PrivKey, accs []sdk.AccAddress) json.RawMessage, ops []TestAndRunTx, setups []RandSetup, - invariants []Invariant, numBlocks int, blockSize int, commit bool, -) { +func Simulate(t *testing.T, app *baseapp.BaseApp, + appStateFn func(r *rand.Rand, accs []Account) json.RawMessage, + ops []WeightedOperation, setups []RandSetup, + invariants []Invariant, numBlocks int, blockSize int, commit bool) error { + time := time.Now().UnixNano() - SimulateFromSeed(t, app, appStateFn, time, ops, setups, invariants, numBlocks, blockSize, commit) + return SimulateFromSeed(t, app, appStateFn, time, ops, setups, invariants, numBlocks, blockSize, commit) +} + +func initChain(r *rand.Rand, params Params, accounts []Account, setups []RandSetup, app *baseapp.BaseApp, + appStateFn func(r *rand.Rand, accounts []Account) json.RawMessage) (validators map[string]mockValidator) { + res := app.InitChain(abci.RequestInitChain{AppStateBytes: appStateFn(r, accounts)}) + validators = make(map[string]mockValidator) + for _, validator := range res.Validators { + str := fmt.Sprintf("%v", validator.PubKey) + validators[str] = mockValidator{ + val: validator, + livenessState: GetMemberOfInitialState(r, params.InitialLivenessWeightings), + } + } + + for i := 0; i < len(setups); i++ { + setups[i](r, accounts) + } + + return +} + +func randTimestamp(r *rand.Rand) time.Time { + // json.Marshal breaks for timestamps greater with year greater than 9999 + unixTime := r.Int63n(253373529600) + return time.Unix(unixTime, 0) } // SimulateFromSeed tests an application by running the provided // operations, testing the provided invariants, but using the provided seed. -func SimulateFromSeed( - t *testing.T, app *baseapp.BaseApp, appStateFn func(r *rand.Rand, keys []crypto.PrivKey, accs []sdk.AccAddress) json.RawMessage, seed int64, ops []TestAndRunTx, setups []RandSetup, - invariants []Invariant, numBlocks int, blockSize int, commit bool, -) { - log := fmt.Sprintf("Starting SimulateFromSeed with randomness created with seed %d", int(seed)) - fmt.Printf("%s\n", log) +func SimulateFromSeed(tb testing.TB, app *baseapp.BaseApp, + appStateFn func(r *rand.Rand, accs []Account) json.RawMessage, + seed int64, ops []WeightedOperation, setups []RandSetup, invariants []Invariant, + numBlocks int, blockSize int, commit bool) (simError error) { + + // in case we have to end early, don't os.Exit so that we can run cleanup code. + stopEarly := false + testingMode, t, b := getTestingMode(tb) + fmt.Printf("Starting SimulateFromSeed with randomness created with seed %d\n", int(seed)) r := rand.New(rand.NewSource(seed)) - keys, accs := mock.GeneratePrivKeyAddressPairsFromRand(r, numKeys) + params := RandomParams(r) // := DefaultParams() + fmt.Printf("Randomized simulation params: %+v\n", params) + timestamp := randTimestamp(r) + fmt.Printf("Starting the simulation from time %v, unixtime %v\n", timestamp.UTC().Format(time.UnixDate), timestamp.Unix()) + timeDiff := maxTimePerBlock - minTimePerBlock + + accs := RandomAccounts(r, params.NumKeys) // Setup event stats events := make(map[string]uint) event := func(what string) { - log += "\nevent - " + what events[what]++ } - timestamp := time.Unix(0, 0) - timeDiff := maxTimePerBlock - minTimePerBlock - - res := app.InitChain(abci.RequestInitChain{AppStateBytes: appStateFn(r, keys, accs)}) - validators := make(map[string]mockValidator) - for _, validator := range res.Validators { - validators[string(validator.Address)] = mockValidator{validator, GetMemberOfInitialState(r, initialLivenessWeightings)} - } - - for i := 0; i < len(setups); i++ { - setups[i](r, keys) - } + validators := initChain(r, params, accs, setups, app, appStateFn) + // Second variable to keep pending validator set (delayed one block since TM 0.24) + // Initially this is the same as the initial validator set + nextValidators := validators - header := abci.Header{Height: 0, Time: timestamp} + header := abci.Header{Height: 1, Time: timestamp, ProposerAddress: randomProposer(r, validators)} opCount := 0 - request := abci.RequestBeginBlock{Header: header} + // Setup code to catch SIGTERM's + c := make(chan os.Signal) + signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) + go func() { + receivedSignal := <-c + fmt.Printf("\nExiting early due to %s, on block %d, operation %d\n", receivedSignal, header.Height, opCount) + simError = fmt.Errorf("Exited due to %s", receivedSignal) + stopEarly = true + }() var pastTimes []time.Time + var pastVoteInfos [][]abci.VoteInfo - for i := 0; i < numBlocks; i++ { + request := RandomRequestBeginBlock(r, params, validators, pastTimes, pastVoteInfos, event, header) + // These are operations which have been queued by previous operations + operationQueue := make(map[int][]Operation) + timeOperationQueue := []FutureOperation{} + var blockLogBuilders []*strings.Builder + if testingMode { + blockLogBuilders = make([]*strings.Builder, numBlocks) + } + displayLogs := logPrinter(testingMode, blockLogBuilders) + blockSimulator := createBlockSimulator(testingMode, tb, t, params, event, invariants, ops, operationQueue, timeOperationQueue, numBlocks, blockSize, displayLogs) + if !testingMode { + b.ResetTimer() + } else { + // Recover logs in case of panic + defer func() { + if r := recover(); r != nil { + fmt.Println("Panic with err\n", r) + stackTrace := string(debug.Stack()) + fmt.Println(stackTrace) + displayLogs() + simError = fmt.Errorf("Simulation halted due to panic on block %d", header.Height) + } + }() + } + + for i := 0; i < numBlocks && !stopEarly; i++ { // Log the header time for future lookup pastTimes = append(pastTimes, header.Time) + pastVoteInfos = append(pastVoteInfos, request.LastCommitInfo.Votes) + + // Construct log writer + logWriter := addLogMessage(testingMode, blockLogBuilders, i) // Run the BeginBlock handler + logWriter("BeginBlock") app.BeginBlock(request) - log += "\nBeginBlock" - - // Make sure invariants hold at beginning of block - AssertAllInvariants(t, app, invariants, log) + if testingMode { + // Make sure invariants hold at beginning of block + assertAllInvariants(t, app, invariants, "BeginBlock", displayLogs) + } ctx := app.NewContext(false, header) - var thisBlockSize int - load := r.Float64() - switch { - case load < 0.33: - thisBlockSize = 0 - case load < 0.66: - thisBlockSize = r.Intn(blockSize * 2) - default: - thisBlockSize = r.Intn(blockSize * 4) + // Run queued operations. Ignores blocksize if blocksize is too small + logWriter("Queued operations") + numQueuedOpsRan := runQueuedOperations(operationQueue, int(header.Height), tb, r, app, ctx, accs, logWriter, displayLogs, event) + numQueuedTimeOpsRan := runQueuedTimeOperations(timeOperationQueue, header.Time, tb, r, app, ctx, accs, logWriter, displayLogs, event) + if testingMode && onOperation { + // Make sure invariants hold at end of queued operations + assertAllInvariants(t, app, invariants, "QueuedOperations", displayLogs) } - for j := 0; j < thisBlockSize; j++ { - logUpdate, err := ops[r.Intn(len(ops))](t, r, app, ctx, keys, log, event) - log += "\n" + logUpdate - require.Nil(t, err, log) - if onOperation { - AssertAllInvariants(t, app, invariants, log) - } - if opCount%200 == 0 { - fmt.Printf("\rSimulating... block %d/%d, operation %d.", header.Height, numBlocks, opCount) - } - opCount++ + logWriter("Standard operations") + operations := blockSimulator(r, app, ctx, accs, header, logWriter) + opCount += operations + numQueuedOpsRan + numQueuedTimeOpsRan + if testingMode { + // Make sure invariants hold at end of block + assertAllInvariants(t, app, invariants, "StandardOperations", displayLogs) } res := app.EndBlock(abci.RequestEndBlock{}) header.Height++ header.Time = header.Time.Add(time.Duration(minTimePerBlock) * time.Second).Add(time.Duration(int64(r.Intn(int(timeDiff)))) * time.Second) + header.ProposerAddress = randomProposer(r, validators) + logWriter("EndBlock") - log += "\nEndBlock" - - // Make sure invariants hold at end of block - AssertAllInvariants(t, app, invariants, log) - + if testingMode { + // Make sure invariants hold at end of block + assertAllInvariants(t, app, invariants, "EndBlock", displayLogs) + } if commit { app.Commit() } + if header.ProposerAddress == nil { + fmt.Printf("\nSimulation stopped early as all validators have been unbonded, there is nobody left propose a block!\n") + stopEarly = true + break + } + // Generate a random RequestBeginBlock with the current validator set for the next block - request = RandomRequestBeginBlock(t, r, validators, livenessTransitionMatrix, evidenceFraction, pastTimes, event, header, log) + request = RandomRequestBeginBlock(r, params, validators, pastTimes, pastVoteInfos, event, header) - // Update the validator set - validators = updateValidators(t, r, validators, res.ValidatorUpdates, event) + // Update the validator set, which will be reflected in the application on the next block + validators = nextValidators + nextValidators = updateValidators(tb, r, params, validators, res.ValidatorUpdates, event) } - - fmt.Printf("\nSimulation complete. Final height (blocks): %d, final time (seconds): %v\n", header.Height, header.Time) + if stopEarly { + DisplayEvents(events) + return + } + fmt.Printf("\nSimulation complete. Final height (blocks): %d, final time (seconds), : %v, operations ran %d\n", header.Height, header.Time, opCount) DisplayEvents(events) + return nil +} + +type blockSimFn func( + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + accounts []Account, header abci.Header, logWriter func(string), +) (opCount int) + +// Returns a function to simulate blocks. Written like this to avoid constant parameters being passed everytime, to minimize +// memory overhead +func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, params Params, + event func(string), invariants []Invariant, + ops []WeightedOperation, operationQueue map[int][]Operation, timeOperationQueue []FutureOperation, + totalNumBlocks int, avgBlockSize int, displayLogs func()) blockSimFn { + + var ( + lastBlocksizeState = 0 // state for [4 * uniform distribution] + totalOpWeight = 0 + blocksize int + ) + + for i := 0; i < len(ops); i++ { + totalOpWeight += ops[i].Weight + } + selectOp := func(r *rand.Rand) Operation { + x := r.Intn(totalOpWeight) + for i := 0; i < len(ops); i++ { + if x <= ops[i].Weight { + return ops[i].Op + } + x -= ops[i].Weight + } + // shouldn't happen + return ops[0].Op + } + + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + accounts []Account, header abci.Header, logWriter func(string)) (opCount int) { + fmt.Printf("\rSimulating... block %d/%d, operation %d/%d. ", header.Height, totalNumBlocks, opCount, blocksize) + lastBlocksizeState, blocksize = getBlockSize(r, params, lastBlocksizeState, avgBlockSize) + for j := 0; j < blocksize; j++ { + logUpdate, futureOps, err := selectOp(r)(r, app, ctx, accounts, event) + logWriter(logUpdate) + if err != nil { + displayLogs() + tb.Fatalf("error on operation %d within block %d, %v", header.Height, opCount, err) + } + + queueOperations(operationQueue, timeOperationQueue, futureOps) + if testingMode { + if onOperation { + assertAllInvariants(t, app, invariants, fmt.Sprintf("operation: %v", logUpdate), displayLogs) + } + if opCount%50 == 0 { + fmt.Printf("\rSimulating... block %d/%d, operation %d/%d. ", header.Height, totalNumBlocks, opCount, blocksize) + } + } + opCount++ + } + return opCount + } +} + +func getTestingMode(tb testing.TB) (testingMode bool, t *testing.T, b *testing.B) { + testingMode = false + if _t, ok := tb.(*testing.T); ok { + t = _t + testingMode = true + } else { + b = tb.(*testing.B) + } + return +} + +// getBlockSize returns a block size as determined from the transition matrix. +// It targets making average block size the provided parameter. The three +// states it moves between are: +// "over stuffed" blocks with average size of 2 * avgblocksize, +// normal sized blocks, hitting avgBlocksize on average, +// and empty blocks, with no txs / only txs scheduled from the past. +func getBlockSize(r *rand.Rand, params Params, lastBlockSizeState, avgBlockSize int) (state, blocksize int) { + // TODO: Make default blocksize transition matrix actually make the average + // blocksize equal to avgBlockSize. + state = params.BlockSizeTransitionMatrix.NextState(r, lastBlockSizeState) + if state == 0 { + blocksize = r.Intn(avgBlockSize * 4) + } else if state == 1 { + blocksize = r.Intn(avgBlockSize * 2) + } else { + blocksize = 0 + } + return +} + +// adds all future operations into the operation queue. +func queueOperations(queuedOperations map[int][]Operation, queuedTimeOperations []FutureOperation, futureOperations []FutureOperation) { + if futureOperations == nil { + return + } + for _, futureOp := range futureOperations { + if futureOp.BlockHeight != 0 { + if val, ok := queuedOperations[futureOp.BlockHeight]; ok { + queuedOperations[futureOp.BlockHeight] = append(val, futureOp.Op) + } else { + queuedOperations[futureOp.BlockHeight] = []Operation{futureOp.Op} + } + } else { + // TODO: Replace with proper sorted data structure, so don't have the copy entire slice + index := sort.Search(len(queuedTimeOperations), func(i int) bool { return queuedTimeOperations[i].BlockTime.After(futureOp.BlockTime) }) + queuedTimeOperations = append(queuedTimeOperations, FutureOperation{}) + copy(queuedTimeOperations[index+1:], queuedTimeOperations[index:]) + queuedTimeOperations[index] = futureOp + } + } +} + +// nolint: errcheck +func runQueuedOperations(queueOperations map[int][]Operation, height int, tb testing.TB, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + accounts []Account, logWriter func(string), displayLogs func(), event func(string)) (numOpsRan int) { + if queuedOps, ok := queueOperations[height]; ok { + numOps := len(queuedOps) + for i := 0; i < numOps; i++ { + // For now, queued operations cannot queue more operations. + // If a need arises for us to support queued messages to queue more messages, this can + // be changed. + logUpdate, _, err := queuedOps[i](r, app, ctx, accounts, event) + logWriter(logUpdate) + if err != nil { + displayLogs() + tb.FailNow() + } + } + delete(queueOperations, height) + return numOps + } + return 0 +} + +func runQueuedTimeOperations(queueOperations []FutureOperation, currentTime time.Time, tb testing.TB, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + accounts []Account, logWriter func(string), displayLogs func(), event func(string)) (numOpsRan int) { + + numOpsRan = 0 + for len(queueOperations) > 0 && currentTime.After(queueOperations[0].BlockTime) { + // For now, queued operations cannot queue more operations. + // If a need arises for us to support queued messages to queue more messages, this can + // be changed. + logUpdate, _, err := queueOperations[0].Op(r, app, ctx, accounts, event) + logWriter(logUpdate) + if err != nil { + displayLogs() + tb.FailNow() + } + queueOperations = queueOperations[1:] + numOpsRan++ + } + return numOpsRan } func getKeys(validators map[string]mockValidator) []string { @@ -139,18 +367,34 @@ func getKeys(validators map[string]mockValidator) []string { return keys } +// randomProposer picks a random proposer from the current validator set +func randomProposer(r *rand.Rand, validators map[string]mockValidator) cmn.HexBytes { + keys := getKeys(validators) + if len(keys) == 0 { + return nil + } + key := keys[r.Intn(len(keys))] + proposer := validators[key].val + pk, err := tmtypes.PB2TM.PubKey(proposer.PubKey) + if err != nil { + panic(err) + } + return pk.Address() +} + // RandomRequestBeginBlock generates a list of signing validators according to the provided list of validators, signing fraction, and evidence fraction -func RandomRequestBeginBlock(t *testing.T, r *rand.Rand, validators map[string]mockValidator, livenessTransitions TransitionMatrix, evidenceFraction float64, - pastTimes []time.Time, event func(string), header abci.Header, log string) abci.RequestBeginBlock { +// nolint: unparam +func RandomRequestBeginBlock(r *rand.Rand, params Params, validators map[string]mockValidator, + pastTimes []time.Time, pastVoteInfos [][]abci.VoteInfo, event func(string), header abci.Header) abci.RequestBeginBlock { if len(validators) == 0 { + fmt.Printf("validator is nil\n") return abci.RequestBeginBlock{Header: header} } - signingValidators := make([]abci.SigningValidator, len(validators)) + voteInfos := make([]abci.VoteInfo, len(validators)) i := 0 - for _, key := range getKeys(validators) { mVal := validators[key] - mVal.livenessState = livenessTransitions.NextState(r, mVal.livenessState) + mVal.livenessState = params.LivenessTransitionMatrix.NextState(r, mVal.livenessState) signed := true if mVal.livenessState == 1 { @@ -167,69 +411,82 @@ func RandomRequestBeginBlock(t *testing.T, r *rand.Rand, validators map[string]m } else { event("beginblock/signing/missed") } - signingValidators[i] = abci.SigningValidator{ - Validator: mVal.val, + pubkey, err := tmtypes.PB2TM.PubKey(mVal.val.PubKey) + if err != nil { + panic(err) + } + voteInfos[i] = abci.VoteInfo{ + Validator: abci.Validator{ + Address: pubkey.Address(), + Power: mVal.val.Power, + }, SignedLastBlock: signed, } i++ } + // TODO: Determine capacity before allocation evidence := make([]abci.Evidence, 0) - for r.Float64() < evidenceFraction { - height := header.Height - time := header.Time - if r.Float64() < pastEvidenceFraction { - height = int64(r.Intn(int(header.Height))) - time = pastTimes[height] - } - validator := signingValidators[r.Intn(len(signingValidators))].Validator - var currentTotalVotingPower int64 - for _, mVal := range validators { - currentTotalVotingPower += mVal.val.Power - } - evidence = append(evidence, abci.Evidence{ - Type: tmtypes.ABCIEvidenceTypeDuplicateVote, - Validator: validator, - Height: height, - Time: time, - TotalVotingPower: currentTotalVotingPower, - }) - event("beginblock/evidence") + // Anything but the first block + if len(pastTimes) > 0 { + for r.Float64() < params.EvidenceFraction { + height := header.Height + time := header.Time + vals := voteInfos + if r.Float64() < params.PastEvidenceFraction { + height = int64(r.Intn(int(header.Height) - 1)) + time = pastTimes[height] + vals = pastVoteInfos[height] + } + validator := vals[r.Intn(len(vals))].Validator + var totalVotingPower int64 + for _, val := range vals { + totalVotingPower += val.Validator.Power + } + evidence = append(evidence, abci.Evidence{ + Type: tmtypes.ABCIEvidenceTypeDuplicateVote, + Validator: validator, + Height: height, + Time: time, + TotalVotingPower: totalVotingPower, + }) + event("beginblock/evidence") + } } return abci.RequestBeginBlock{ Header: header, LastCommitInfo: abci.LastCommitInfo{ - Validators: signingValidators, + Votes: voteInfos, }, ByzantineValidators: evidence, } } -// AssertAllInvariants asserts a list of provided invariants against application state -func AssertAllInvariants(t *testing.T, app *baseapp.BaseApp, tests []Invariant, log string) { - for i := 0; i < len(tests); i++ { - tests[i](t, app, log) - } -} - // updateValidators mimicks Tendermint's update logic -func updateValidators(t *testing.T, r *rand.Rand, current map[string]mockValidator, updates []abci.Validator, event func(string)) map[string]mockValidator { +// nolint: unparam +func updateValidators(tb testing.TB, r *rand.Rand, params Params, current map[string]mockValidator, updates []abci.ValidatorUpdate, event func(string)) map[string]mockValidator { + for _, update := range updates { + str := fmt.Sprintf("%v", update.PubKey) switch { case update.Power == 0: - require.NotNil(t, current[string(update.PubKey.Data)], "tried to delete a nonexistent validator") + if _, ok := current[str]; !ok { + tb.Fatalf("tried to delete a nonexistent validator") + } + event("endblock/validatorupdates/kicked") - delete(current, string(update.PubKey.Data)) + delete(current, str) default: // Does validator already exist? - if mVal, ok := current[string(update.PubKey.Data)]; ok { + if mVal, ok := current[str]; ok { mVal.val = update event("endblock/validatorupdates/updated") } else { // Set this new validator - current[string(update.PubKey.Data)] = mockValidator{update, GetMemberOfInitialState(r, initialLivenessWeightings)} + current[str] = mockValidator{update, GetMemberOfInitialState(r, params.InitialLivenessWeightings)} event("endblock/validatorupdates/added") } } } + return current } diff --git a/simulation/mock/simulation/types.go b/simulation/mock/simulation/types.go index e59a4209b..09317cb2d 100644 --- a/simulation/mock/simulation/types.go +++ b/simulation/mock/simulation/types.go @@ -2,44 +2,86 @@ package simulation import ( "math/rand" - "testing" + "time" - "github.com/irisnet/irishub/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/irisnet/irishub/baseapp" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" ) type ( - // TestAndRunTx produces a fuzzed transaction, and ensures the state - // transition was as expected. It returns a descriptive message "action" - // about what this fuzzed tx actually did, for ease of debugging. - TestAndRunTx func( - t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - privKeys []crypto.PrivKey, log string, event func(string), - ) (action string, err sdk.Error) + // Operation runs a state machine transition, + // and ensures the transition happened as expected. + // The operation could be running and testing a fuzzed transaction, + // or doing the same for a message. + // + // For ease of debugging, + // an operation returns a descriptive message "action", + // which details what this fuzzed state machine transition actually did. + // + // Operations can optionally provide a list of "FutureOperations" to run later + // These will be ran at the beginning of the corresponding block. + Operation func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + accounts []Account, event func(string), + ) (action string, futureOperations []FutureOperation, err error) // RandSetup performs the random setup the mock module needs. - RandSetup func(r *rand.Rand, privKeys []crypto.PrivKey) + RandSetup func(r *rand.Rand, accounts []Account) // An Invariant is a function which tests a particular invariant. - // If the invariant has been broken, the function should halt the - // test and output the log. - Invariant func(t *testing.T, app *baseapp.BaseApp, log string) + // If the invariant has been broken, it should return an error + // containing a descriptive message about what happened. + // The simulator will then halt and print the logs. + Invariant func(app *baseapp.BaseApp) error + + // Account contains a privkey, pubkey, address tuple + // eventually more useful data can be placed in here. + // (e.g. number of coins) + Account struct { + PrivKey crypto.PrivKey + PubKey crypto.PubKey + Address sdk.AccAddress + } mockValidator struct { - val abci.Validator + val abci.ValidatorUpdate livenessState int } + + // FutureOperation is an operation which will be ran at the + // beginning of the provided BlockHeight. + // If both a BlockHeight and BlockTime are specified, it will use the BlockHeight. + // In the (likely) event that multiple operations are queued at the same + // block height, they will execute in a FIFO pattern. + FutureOperation struct { + BlockHeight int + BlockTime time.Time + Op Operation + } + + // WeightedOperation is an operation with associated weight. + // This is used to bias the selection operation within the simulator. + WeightedOperation struct { + Weight int + Op Operation + } ) +// TODO remove? not being called anywhere // PeriodicInvariant returns an Invariant function closure that asserts // a given invariant if the mock application's last block modulo the given // period is congruent to the given offset. func PeriodicInvariant(invariant Invariant, period int, offset int) Invariant { - return func(t *testing.T, app *baseapp.BaseApp, log string) { + return func(app *baseapp.BaseApp) error { if int(app.LastBlockHeight())%period == offset { - invariant(t, app, log) + return invariant(app) } + return nil } } + +// nolint +func (acc Account) Equals(acc2 Account) bool { + return acc.Address.Equals(acc2.Address) +} diff --git a/simulation/mock/simulation/util.go b/simulation/mock/simulation/util.go index 1d64ba30d..b718cf6de 100644 --- a/simulation/mock/simulation/util.go +++ b/simulation/mock/simulation/util.go @@ -3,15 +3,21 @@ package simulation import ( "fmt" "math/rand" + "os" "sort" + "strings" + "testing" + "time" - "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/crypto/ed25519" + "github.com/tendermint/tendermint/crypto/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" -) -// shamelessly copied from https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang#31832326 -// TODO we should probably move this to tendermint/libs/common/random.go + "github.com/irisnet/irishub/baseapp" + "github.com/irisnet/irishub/simulation/mock" + "math/big" +) const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const ( @@ -51,14 +57,118 @@ func DisplayEvents(events map[string]uint) { } } -// Pick a random key from an array -func RandomKey(r *rand.Rand, keys []crypto.PrivKey) crypto.PrivKey { - return keys[r.Intn( - len(keys), +// RandomAcc pick a random account from an array +func RandomAcc(r *rand.Rand, accs []Account) Account { + return accs[r.Intn( + len(accs), )] } // Generate a random amount func RandomAmount(r *rand.Rand, max sdk.Int) sdk.Int { - return sdk.NewInt(int64(r.Intn(int(max.Int64())))) + //return sdk.NewInt(int64(r.Intn(int(max.Int64())))) + if max.IsInt64() { + return sdk.NewInt(int64(r.Intn(int(max.Int64())))) + } else { + return sdk.NewInt(int64(r.Intn(int(int64(9223372036854775807))))) + } +} + +// RandomDecAmount generates a random decimal amount +func RandomDecAmount(r *rand.Rand, max sdk.Dec) sdk.Dec { + randInt := big.NewInt(0).Rand(r, max.Int) + return sdk.NewDecFromBigIntWithPrec(randInt, sdk.Precision) +} + +// RandomAccounts generates n random accounts +func RandomAccounts(r *rand.Rand, n int) []Account { + accs := make([]Account, n) + for i := 0; i < n; i++ { + // don't need that much entropy for simulation + privkeySeed := make([]byte, 15) + r.Read(privkeySeed) + useSecp := r.Int63()%2 == 0 + if useSecp { + accs[i].PrivKey = secp256k1.GenPrivKeySecp256k1(privkeySeed) + } else { + accs[i].PrivKey = ed25519.GenPrivKeyFromSecret(privkeySeed) + } + accs[i].PubKey = accs[i].PrivKey.PubKey() + accs[i].Address = sdk.AccAddress(accs[i].PubKey.Address()) + } + return accs +} + +// Builds a function to add logs for this particular block +func addLogMessage(testingmode bool, blockLogBuilders []*strings.Builder, height int) func(string) { + if testingmode { + blockLogBuilders[height] = &strings.Builder{} + return func(x string) { + (*blockLogBuilders[height]).WriteString(x) + (*blockLogBuilders[height]).WriteString("\n") + } + } + return func(x string) {} +} + +// assertAllInvariants asserts a list of provided invariants against application state +func assertAllInvariants(t *testing.T, app *baseapp.BaseApp, + invariants []Invariant, where string, displayLogs func()) { + + for i := 0; i < len(invariants); i++ { + err := invariants[i](app) + if err != nil { + fmt.Printf("Invariants broken after %s\n", where) + fmt.Println(err.Error()) + displayLogs() + t.Fatal() + } + } +} + +// RandomSetGenesis wraps mock.RandomSetGenesis, but using simulation accounts +func RandomSetGenesis(r *rand.Rand, app *mock.App, accs []Account, denoms []string) { + addrs := make([]sdk.AccAddress, len(accs)) + for i := 0; i < len(accs); i++ { + addrs[i] = accs[i].Address + } + mock.RandomSetGenesis(r, app, addrs, denoms) +} + +// Creates a function to print out the logs +func logPrinter(testingmode bool, logs []*strings.Builder) func() { + if testingmode { + return func() { + numLoggers := 0 + for i := 0; i < len(logs); i++ { + // We're passed the last created block + if logs[i] == nil { + numLoggers = i + break + } + } + var f *os.File + if numLoggers > 10 { + fileName := fmt.Sprintf("simulation_log_%s.txt", time.Now().Format("2006-01-02 15:04:05")) + fmt.Printf("Too many logs to display, instead writing to %s\n", fileName) + f, _ = os.Create(fileName) + } + for i := 0; i < numLoggers; i++ { + if f != nil { + _, err := f.WriteString(fmt.Sprintf("Begin block %d\n", i+1)) + if err != nil { + panic("Failed to write logs to file") + } + _, err = f.WriteString((*logs[i]).String()) + if err != nil { + panic("Failed to write logs to file") + } + } else { + fmt.Printf("Begin block %d\n", i+1) + fmt.Println((*logs[i]).String()) + } + } + } + } + return func() {} } diff --git a/simulation/mock/test_utils.go b/simulation/mock/test_utils.go index 083638c88..481f722d1 100644 --- a/simulation/mock/test_utils.go +++ b/simulation/mock/test_utils.go @@ -5,11 +5,12 @@ import ( "math/rand" "testing" - "github.com/irisnet/irishub/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" + + "github.com/irisnet/irishub/baseapp" ) // BigInterval is a representation of the interval [lo, hi), where @@ -41,7 +42,7 @@ func RandFromBigInterval(r *rand.Rand, intervals []BigInterval) sdk.Int { // CheckBalance checks the balance of an account. func CheckBalance(t *testing.T, app *App, addr sdk.AccAddress, exp sdk.Coins) { ctxCheck := app.BaseApp.NewContext(true, abci.Header{}) - res := app.AccountMapper.GetAccount(ctxCheck, addr) + res := app.AccountKeeper.GetAccount(ctxCheck, addr) require.Equal(t, exp, res.GetCoins()) } @@ -71,13 +72,13 @@ func CheckGenTx( // returned. func SignCheckDeliver( t *testing.T, app *baseapp.BaseApp, msgs []sdk.Msg, accNums []int64, - seq []int64, expPass bool, priv ...crypto.PrivKey, + seq []int64, expSimPass, expPass bool, priv ...crypto.PrivKey, ) sdk.Result { tx := GenTx(msgs, accNums, seq, priv...) // Must simulate now as CheckTx doesn't run Msgs anymore res := app.Simulate(tx) - if expPass { + if expSimPass { require.Equal(t, sdk.ABCICodeOK, res.Code, res.Log) } else { require.NotEqual(t, sdk.ABCICodeOK, res.Code, res.Log) diff --git a/simulation/slashing/invariants.go b/simulation/slashing/invariants.go index 1f874a214..105690095 100644 --- a/simulation/slashing/invariants.go +++ b/simulation/slashing/invariants.go @@ -1,18 +1,14 @@ package simulation import ( - "testing" - - "github.com/stretchr/testify/require" - "github.com/irisnet/irishub/baseapp" "github.com/irisnet/irishub/simulation/mock/simulation" ) +// TODO Any invariants to check here? // AllInvariants tests all slashing invariants func AllInvariants() simulation.Invariant { - return func(t *testing.T, app *baseapp.BaseApp, log string) { - // TODO Any invariants to check here? - require.Nil(t, nil) + return func(_ *baseapp.BaseApp) error { + return nil } } diff --git a/simulation/slashing/msgs.go b/simulation/slashing/msgs.go index 453c670a0..1f31ddc47 100644 --- a/simulation/slashing/msgs.go +++ b/simulation/slashing/msgs.go @@ -3,32 +3,28 @@ package simulation import ( "fmt" "math/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/tendermint/tendermint/crypto" - "github.com/irisnet/irishub/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/irisnet/irishub/simulation/mock/simulation" "github.com/cosmos/cosmos-sdk/x/slashing" ) -// SimulateMsgUnrevoke -func SimulateMsgUnrevoke(k slashing.Keeper) simulation.TestAndRunTx { - return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, err sdk.Error) { - key := simulation.RandomKey(r, keys) - address := sdk.AccAddress(key.PubKey().Address()) - msg := slashing.NewMsgUnrevoke(address) - require.Nil(t, msg.ValidateBasic(), "expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) +// SimulateMsgUnjail +func SimulateMsgUnjail(k slashing.Keeper) simulation.Operation { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) (action string, fOp []simulation.FutureOperation, err error) { + acc := simulation.RandomAcc(r, accs) + address := sdk.ValAddress(acc.Address) + msg := slashing.NewMsgUnjail(address) + if msg.ValidateBasic() != nil { + return "", nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + } ctx, write := ctx.CacheContext() result := slashing.NewHandler(k)(ctx, msg) if result.IsOK() { write() } - event(fmt.Sprintf("slashing/MsgUnrevoke/%v", result.IsOK())) - action = fmt.Sprintf("TestMsgUnrevoke: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) - return action, nil + event(fmt.Sprintf("slashing/MsgUnjail/%v", result.IsOK())) + action = fmt.Sprintf("TestMsgUnjail: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) + return action, nil, nil } } diff --git a/simulation/stake/invariants.go b/simulation/stake/invariants.go index a0fc071b5..3a14e165a 100644 --- a/simulation/stake/invariants.go +++ b/simulation/stake/invariants.go @@ -1,43 +1,58 @@ package simulation import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/irisnet/irishub/baseapp" + "bytes" + "fmt" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/irisnet/irishub/simulation/mock/simulation" + "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/stake/keeper" + "github.com/irisnet/irishub/baseapp" + "github.com/irisnet/irishub/simulation/mock" + "github.com/irisnet/irishub/simulation/mock/simulation" abci "github.com/tendermint/tendermint/abci/types" ) // AllInvariants runs all invariants of the stake module. // Currently: total supply, positive power -func AllInvariants(ck bank.Keeper, k stake.Keeper, am auth.AccountMapper) simulation.Invariant { - return func(t *testing.T, app *baseapp.BaseApp, log string) { - SupplyInvariants(ck, k, am)(t, app, log) - PositivePowerInvariant(k)(t, app, log) - ValidatorSetInvariant(k)(t, app, log) +func AllInvariants(ck bank.Keeper, k stake.Keeper, + f auth.FeeCollectionKeeper, d distribution.Keeper, + am auth.AccountKeeper) simulation.Invariant { + + return func(app *baseapp.BaseApp) error { + //err := SupplyInvariants(ck, k, f, d, am)(app, header) + //if err != nil { + // return err + //} + //err = PositivePowerInvariant(k)(app, header) + //if err != nil { + // return err + //} + //err = ValidatorSetInvariant(k)(app, header) + //return err + //return nil + return nil } } // SupplyInvariants checks that the total supply reflects all held loose tokens, bonded tokens, and unbonding delegations -func SupplyInvariants(ck bank.Keeper, k stake.Keeper, am auth.AccountMapper) simulation.Invariant { - return func(t *testing.T, app *baseapp.BaseApp, log string) { +// nolint: unparam +func SupplyInvariants(ck bank.Keeper, k stake.Keeper, + f auth.FeeCollectionKeeper, d distribution.Keeper, am auth.AccountKeeper) simulation.Invariant { + return func(app *baseapp.BaseApp) error { ctx := app.NewContext(false, abci.Header{}) - //pool := k.GetPool(ctx) + pool := k.GetPool(ctx) - loose := sdk.ZeroInt() - bonded := sdk.ZeroRat() + loose := sdk.ZeroDec() + bonded := sdk.ZeroDec() am.IterateAccounts(ctx, func(acc auth.Account) bool { - loose = loose.Add(acc.GetCoins().AmountOf("steak")) + loose = loose.Add(sdk.NewDecFromInt(acc.GetCoins().AmountOf(mock.MiniDenom))) return false }) k.IterateUnbondingDelegations(ctx, func(_ int64, ubd stake.UnbondingDelegation) bool { - loose = loose.Add(ubd.Balance.Amount) + loose = loose.Add(sdk.NewDecFromInt(ubd.Balance.Amount)) return false }) k.IterateValidators(ctx, func(_ int64, validator sdk.Validator) bool { @@ -45,40 +60,80 @@ func SupplyInvariants(ck bank.Keeper, k stake.Keeper, am auth.AccountMapper) sim case sdk.Bonded: bonded = bonded.Add(validator.GetPower()) case sdk.Unbonding: + loose = loose.Add(validator.GetTokens()) case sdk.Unbonded: - loose = loose.Add(validator.GetTokens().RoundInt()) + loose = loose.Add(validator.GetTokens()) } return false }) - // Loose tokens should equal coin supply plus unbonding delegations plus tokens on unbonded validators - // XXX TODO https://github.com/cosmos/cosmos-sdk/issues/2063#issuecomment-413720872 - // require.True(t, pool.LooseTokens.RoundInt64() == loose.Int64(), "expected loose tokens to equal total steak held by accounts - pool.LooseTokens: %v, sum of account tokens: %v\nlog: %s", - // pool.LooseTokens.RoundInt64(), loose.Int64(), log) + feePool := d.GetFeePool(ctx) + + // add outstanding fees + loose = loose.Add(sdk.NewDecFromInt(f.GetCollectedFees(ctx).AmountOf(mock.MiniDenom))) + + // add community pool + loose = loose.Add(feePool.CommunityPool.AmountOf(mock.MiniDenom)) + + // add validator distribution pool + loose = loose.Add(feePool.ValPool.AmountOf(mock.MiniDenom)) + + // add validator distribution commission and yet-to-be-withdrawn-by-delegators + d.IterateValidatorDistInfos(ctx, + func(_ int64, distInfo distribution.ValidatorDistInfo) (stop bool) { + loose = loose.Add(distInfo.DelPool.AmountOf(mock.MiniDenom)) + loose = loose.Add(distInfo.ValCommission.AmountOf(mock.MiniDenom)) + return false + }, + ) + + // Loose tokens should equal coin supply plus unbonding delegations + // plus tokens on unbonded validators + if !pool.LooseTokens.Equal(loose) { + return fmt.Errorf("loose token invariance:\n\tpool.LooseTokens: %v"+ + "\n\tsum of account tokens: %v", pool.LooseTokens, loose) + } // Bonded tokens should equal sum of tokens with bonded validators - // XXX TODO https://github.com/cosmos/cosmos-sdk/issues/2063#issuecomment-413720872 - // require.True(t, pool.BondedTokens.RoundInt64() == bonded.RoundInt64(), "expected bonded tokens to equal total steak held by bonded validators - pool.BondedTokens: %v, sum of bonded validator tokens: %v\nlog: %s", - // pool.BondedTokens.RoundInt64(), bonded.RoundInt64(), log) + if !pool.BondedTokens.Equal(bonded) { + return fmt.Errorf("bonded token invariance:\n\tpool.BondedTokens: %v"+ + "\n\tsum of account tokens: %v", pool.BondedTokens, bonded) + } - // TODO Inflation check on total supply + return nil } } // PositivePowerInvariant checks that all stored validators have > 0 power func PositivePowerInvariant(k stake.Keeper) simulation.Invariant { - return func(t *testing.T, app *baseapp.BaseApp, log string) { + return func(app *baseapp.BaseApp) error { ctx := app.NewContext(false, abci.Header{}) - k.IterateValidatorsBonded(ctx, func(_ int64, validator sdk.Validator) bool { - require.True(t, validator.GetPower().GT(sdk.ZeroRat()), "validator with non-positive power stored") - return false - }) + + iterator := k.ValidatorsPowerStoreIterator(ctx) + pool := k.GetPool(ctx) + + for ; iterator.Valid(); iterator.Next() { + validator, found := k.GetValidator(ctx, iterator.Value()) + if !found { + panic(fmt.Sprintf("validator record not found for address: %X\n", iterator.Value())) + } + + powerKey := keeper.GetValidatorsByPowerIndexKey(validator, pool) + + if !bytes.Equal(iterator.Key(), powerKey) { + return fmt.Errorf("power store invariance:\n\tvalidator.Power: %v"+ + "\n\tkey should be: %v\n\tkey in store: %v", validator.GetPower(), powerKey, iterator.Key()) + } + } + iterator.Close() + return nil } } // ValidatorSetInvariant checks equivalence of Tendermint validator set and SDK validator set func ValidatorSetInvariant(k stake.Keeper) simulation.Invariant { - return func(t *testing.T, app *baseapp.BaseApp, log string) { + return func(app *baseapp.BaseApp) error { // TODO + return nil } } diff --git a/simulation/stake/msgs.go b/simulation/stake/msgs.go index 54de771c2..c4d4c0aa8 100644 --- a/simulation/stake/msgs.go +++ b/simulation/stake/msgs.go @@ -2,255 +2,252 @@ package simulation import ( "fmt" - "math/rand" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/irisnet/irishub/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/stake/keeper" + "github.com/irisnet/irishub/baseapp" "github.com/irisnet/irishub/simulation/mock" "github.com/irisnet/irishub/simulation/mock/simulation" - "github.com/cosmos/cosmos-sdk/x/stake" abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto" + "math/rand" ) // SimulateMsgCreateValidator -func SimulateMsgCreateValidator(m auth.AccountMapper, k stake.Keeper) simulation.TestAndRunTx { - return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, err sdk.Error) { +func SimulateMsgCreateValidator(m auth.AccountKeeper, k stake.Keeper) simulation.Operation { + handler := stake.NewHandler(k) + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + accs []simulation.Account, event func(string)) ( + action string, fOp []simulation.FutureOperation, err error) { + denom := k.GetParams(ctx).BondDenom description := stake.Description{ Moniker: simulation.RandStringOfLength(r, 10), } - key := simulation.RandomKey(r, keys) - pubkey := key.PubKey() - address := sdk.AccAddress(pubkey.Address()) - amount := m.GetAccount(ctx, address).GetCoins().AmountOf(denom) + + maxCommission := sdk.NewInt(10) + commission := stake.NewCommissionMsg( + sdk.NewDecWithPrec(simulation.RandomAmount(r, maxCommission).Int64(), 1), + sdk.NewDecWithPrec(simulation.RandomAmount(r, maxCommission).Int64(), 1), + sdk.NewDecWithPrec(simulation.RandomAmount(r, maxCommission).Int64(), 1), + ) + + acc := simulation.RandomAcc(r, accs) + address := sdk.ValAddress(acc.Address) + + amount := m.GetAccount(ctx, acc.Address).GetCoins().AmountOf(denom) + if amount.GT(sdk.ZeroInt()) { amount = simulation.RandomAmount(r, amount) } + if amount.Equal(sdk.ZeroInt()) { - return "no-operation", nil + return "no-operation", nil, nil } + msg := stake.MsgCreateValidator{ Description: description, + Commission: commission, ValidatorAddr: address, - DelegatorAddr: address, - PubKey: pubkey, + DelegatorAddr: acc.Address, + PubKey: acc.PubKey, Delegation: sdk.NewCoin(denom, amount), } - require.Nil(t, msg.ValidateBasic(), "expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + + if msg.ValidateBasic() != nil { + return "", nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + } + ctx, write := ctx.CacheContext() - result := stake.NewHandler(k)(ctx, msg) + result := handler(ctx, msg) if result.IsOK() { write() } + event(fmt.Sprintf("stake/MsgCreateValidator/%v", result.IsOK())) + // require.True(t, result.IsOK(), "expected OK result but instead got %v", result) action = fmt.Sprintf("TestMsgCreateValidator: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) - return action, nil + return action, nil, nil } } // SimulateMsgEditValidator -func SimulateMsgEditValidator(k stake.Keeper) simulation.TestAndRunTx { - return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, err sdk.Error) { +func SimulateMsgEditValidator(k stake.Keeper) simulation.Operation { + handler := stake.NewHandler(k) + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + accs []simulation.Account, event func(string)) ( + action string, fOp []simulation.FutureOperation, err error) { + description := stake.Description{ Moniker: simulation.RandStringOfLength(r, 10), Identity: simulation.RandStringOfLength(r, 10), Website: simulation.RandStringOfLength(r, 10), Details: simulation.RandStringOfLength(r, 10), } - key := simulation.RandomKey(r, keys) - pubkey := key.PubKey() - address := sdk.AccAddress(pubkey.Address()) + + maxCommission := sdk.NewInt(10) + newCommissionRate := sdk.NewDecWithPrec(simulation.RandomAmount(r, maxCommission).Int64(), 1) + + val := keeper.RandomValidator(r, k, ctx) + address := val.GetOperator() msg := stake.MsgEditValidator{ - Description: description, - ValidatorAddr: address, + Description: description, + ValidatorAddr: address, + CommissionRate: &newCommissionRate, + } + + if msg.ValidateBasic() != nil { + return "", nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) } - require.Nil(t, msg.ValidateBasic(), "expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + ctx, write := ctx.CacheContext() - result := stake.NewHandler(k)(ctx, msg) + result := handler(ctx, msg) if result.IsOK() { write() } event(fmt.Sprintf("stake/MsgEditValidator/%v", result.IsOK())) action = fmt.Sprintf("TestMsgEditValidator: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) - return action, nil + return action, nil, nil } } // SimulateMsgDelegate -func SimulateMsgDelegate(m auth.AccountMapper, k stake.Keeper) simulation.TestAndRunTx { - return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, err sdk.Error) { +func SimulateMsgDelegate(m auth.AccountKeeper, k stake.Keeper) simulation.Operation { + handler := stake.NewHandler(k) + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + accs []simulation.Account, event func(string)) ( + action string, fOp []simulation.FutureOperation, err error) { + denom := k.GetParams(ctx).BondDenom - validatorKey := simulation.RandomKey(r, keys) - validatorAddress := sdk.AccAddress(validatorKey.PubKey().Address()) - delegatorKey := simulation.RandomKey(r, keys) - delegatorAddress := sdk.AccAddress(delegatorKey.PubKey().Address()) + val := keeper.RandomValidator(r, k, ctx) + validatorAddress := val.GetOperator() + delegatorAcc := simulation.RandomAcc(r, accs) + delegatorAddress := delegatorAcc.Address amount := m.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) - if amount.GT(sdk.ZeroInt()) { - amount = simulation.RandomAmount(r, amount) - } + if amount.Equal(sdk.ZeroInt()) { - return "no-operation", nil + return "no-operation", nil, nil } msg := stake.MsgDelegate{ DelegatorAddr: delegatorAddress, ValidatorAddr: validatorAddress, Delegation: sdk.NewCoin(denom, amount), } - require.Nil(t, msg.ValidateBasic(), "expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + if msg.ValidateBasic() != nil { + return "", nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) + } ctx, write := ctx.CacheContext() - result := stake.NewHandler(k)(ctx, msg) + result := handler(ctx, msg) if result.IsOK() { write() } event(fmt.Sprintf("stake/MsgDelegate/%v", result.IsOK())) action = fmt.Sprintf("TestMsgDelegate: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) - return action, nil + return action, nil, nil } } // SimulateMsgBeginUnbonding -func SimulateMsgBeginUnbonding(m auth.AccountMapper, k stake.Keeper) simulation.TestAndRunTx { - return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, err sdk.Error) { - denom := k.GetParams(ctx).BondDenom - validatorKey := simulation.RandomKey(r, keys) - validatorAddress := sdk.AccAddress(validatorKey.PubKey().Address()) - delegatorKey := simulation.RandomKey(r, keys) - delegatorAddress := sdk.AccAddress(delegatorKey.PubKey().Address()) - amount := m.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) - if amount.GT(sdk.ZeroInt()) { - amount = simulation.RandomAmount(r, amount) +func SimulateMsgBeginUnbonding(m auth.AccountKeeper, k stake.Keeper) simulation.Operation { + handler := stake.NewHandler(k) + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + accs []simulation.Account, event func(string)) ( + action string, fOp []simulation.FutureOperation, err error) { + + delegatorAcc := simulation.RandomAcc(r, accs) + delegatorAddress := delegatorAcc.Address + delegations := k.GetAllDelegatorDelegations(ctx, delegatorAddress) + if len(delegations) == 0 { + return "no-operation", nil, nil } - if amount.Equal(sdk.ZeroInt()) { - return "no-operation", nil + delegation := delegations[r.Intn(len(delegations))] + + numShares := simulation.RandomDecAmount(r, delegation.Shares) + if numShares.Equal(sdk.ZeroDec()) { + return "no-operation", nil, nil } msg := stake.MsgBeginUnbonding{ DelegatorAddr: delegatorAddress, - ValidatorAddr: validatorAddress, - SharesAmount: sdk.NewRatFromInt(amount), + ValidatorAddr: delegation.ValidatorAddr, + SharesAmount: numShares, + } + if msg.ValidateBasic() != nil { + return "", nil, fmt.Errorf("expected msg to pass ValidateBasic: %s, got error %v", + msg.GetSignBytes(), msg.ValidateBasic()) } - require.Nil(t, msg.ValidateBasic(), "expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) ctx, write := ctx.CacheContext() - result := stake.NewHandler(k)(ctx, msg) + result := handler(ctx, msg) if result.IsOK() { write() } event(fmt.Sprintf("stake/MsgBeginUnbonding/%v", result.IsOK())) action = fmt.Sprintf("TestMsgBeginUnbonding: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) - return action, nil - } -} - -// SimulateMsgCompleteUnbonding -func SimulateMsgCompleteUnbonding(k stake.Keeper) simulation.TestAndRunTx { - return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, err sdk.Error) { - validatorKey := simulation.RandomKey(r, keys) - validatorAddress := sdk.AccAddress(validatorKey.PubKey().Address()) - delegatorKey := simulation.RandomKey(r, keys) - delegatorAddress := sdk.AccAddress(delegatorKey.PubKey().Address()) - msg := stake.MsgCompleteUnbonding{ - DelegatorAddr: delegatorAddress, - ValidatorAddr: validatorAddress, - } - require.Nil(t, msg.ValidateBasic(), "expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - ctx, write := ctx.CacheContext() - result := stake.NewHandler(k)(ctx, msg) - if result.IsOK() { - write() - } - event(fmt.Sprintf("stake/MsgCompleteUnbonding/%v", result.IsOK())) - action = fmt.Sprintf("TestMsgCompleteUnbonding: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) - return action, nil + return action, nil, nil } } // SimulateMsgBeginRedelegate -func SimulateMsgBeginRedelegate(m auth.AccountMapper, k stake.Keeper) simulation.TestAndRunTx { - return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, err sdk.Error) { +func SimulateMsgBeginRedelegate(m auth.AccountKeeper, k stake.Keeper) simulation.Operation { + handler := stake.NewHandler(k) + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + accs []simulation.Account, event func(string)) ( + action string, fOp []simulation.FutureOperation, err error) { + denom := k.GetParams(ctx).BondDenom - sourceValidatorKey := simulation.RandomKey(r, keys) - sourceValidatorAddress := sdk.AccAddress(sourceValidatorKey.PubKey().Address()) - destValidatorKey := simulation.RandomKey(r, keys) - destValidatorAddress := sdk.AccAddress(destValidatorKey.PubKey().Address()) - delegatorKey := simulation.RandomKey(r, keys) - delegatorAddress := sdk.AccAddress(delegatorKey.PubKey().Address()) + srcVal := keeper.RandomValidator(r, k, ctx) + srcValidatorAddress := srcVal.GetOperator() + destVal := keeper.RandomValidator(r, k, ctx) + destValidatorAddress := destVal.GetOperator() + delegatorAcc := simulation.RandomAcc(r, accs) + delegatorAddress := delegatorAcc.Address // TODO amount := m.GetAccount(ctx, delegatorAddress).GetCoins().AmountOf(denom) if amount.GT(sdk.ZeroInt()) { amount = simulation.RandomAmount(r, amount) } if amount.Equal(sdk.ZeroInt()) { - return "no-operation", nil + return "no-operation", nil, nil } msg := stake.MsgBeginRedelegate{ DelegatorAddr: delegatorAddress, - ValidatorSrcAddr: sourceValidatorAddress, + ValidatorSrcAddr: srcValidatorAddress, ValidatorDstAddr: destValidatorAddress, - SharesAmount: sdk.NewRatFromInt(amount), + SharesAmount: sdk.NewDecFromInt(amount), + } + if msg.ValidateBasic() != nil { + return "", nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) } - require.Nil(t, msg.ValidateBasic(), "expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) ctx, write := ctx.CacheContext() - result := stake.NewHandler(k)(ctx, msg) + result := handler(ctx, msg) if result.IsOK() { write() } event(fmt.Sprintf("stake/MsgBeginRedelegate/%v", result.IsOK())) action = fmt.Sprintf("TestMsgBeginRedelegate: %s", msg.GetSignBytes()) - return action, nil - } -} - -// SimulateMsgCompleteRedelegate -func SimulateMsgCompleteRedelegate(k stake.Keeper) simulation.TestAndRunTx { - return func(t *testing.T, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, keys []crypto.PrivKey, log string, event func(string)) (action string, err sdk.Error) { - validatorSrcKey := simulation.RandomKey(r, keys) - validatorSrcAddress := sdk.AccAddress(validatorSrcKey.PubKey().Address()) - validatorDstKey := simulation.RandomKey(r, keys) - validatorDstAddress := sdk.AccAddress(validatorDstKey.PubKey().Address()) - delegatorKey := simulation.RandomKey(r, keys) - delegatorAddress := sdk.AccAddress(delegatorKey.PubKey().Address()) - msg := stake.MsgCompleteRedelegate{ - DelegatorAddr: delegatorAddress, - ValidatorSrcAddr: validatorSrcAddress, - ValidatorDstAddr: validatorDstAddress, - } - require.Nil(t, msg.ValidateBasic(), "expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - ctx, write := ctx.CacheContext() - result := stake.NewHandler(k)(ctx, msg) - if result.IsOK() { - write() - } - event(fmt.Sprintf("stake/MsgCompleteRedelegate/%v", result.IsOK())) - action = fmt.Sprintf("TestMsgCompleteRedelegate: ok %v, msg %s", result.IsOK(), msg.GetSignBytes()) - return action, nil + return action, nil, nil } } // Setup +// nolint: errcheck func Setup(mapp *mock.App, k stake.Keeper) simulation.RandSetup { - return func(r *rand.Rand, privKeys []crypto.PrivKey) { + return func(r *rand.Rand, accs []simulation.Account) { ctx := mapp.NewContext(false, abci.Header{}) gen := stake.DefaultGenesisState() - gen.Params.InflationMax = sdk.NewRat(0) - gen.Params.InflationMin = sdk.NewRat(0) stake.InitGenesis(ctx, k, gen) params := k.GetParams(ctx) denom := params.BondDenom loose := sdk.ZeroInt() - mapp.AccountMapper.IterateAccounts(ctx, func(acc auth.Account) bool { + mapp.AccountKeeper.IterateAccounts(ctx, func(acc auth.Account) bool { balance := simulation.RandomAmount(r, sdk.NewInt(1000000)) acc.SetCoins(acc.GetCoins().Plus(sdk.Coins{sdk.NewCoin(denom, balance)})) - mapp.AccountMapper.SetAccount(ctx, acc) + mapp.AccountKeeper.SetAccount(ctx, acc) loose = loose.Add(balance) return false }) pool := k.GetPool(ctx) - pool.LooseTokens = pool.LooseTokens.Add(sdk.NewRat(loose.Int64(), 1)) + pool.LooseTokens = pool.LooseTokens.Add(sdk.NewDec(loose.Int64())) k.SetPool(ctx, pool) } } diff --git a/simulation/stake/sim_test.go b/simulation/stake/sim_test.go index 6381c8dc8..662695bbb 100644 --- a/simulation/stake/sim_test.go +++ b/simulation/stake/sim_test.go @@ -5,26 +5,39 @@ import ( "math/rand" "testing" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/stake" "github.com/irisnet/irishub/simulation/mock" "github.com/irisnet/irishub/simulation/mock/simulation" - "github.com/cosmos/cosmos-sdk/x/stake" + abci "github.com/tendermint/tendermint/abci/types" ) // TestStakeWithRandomMessages func TestStakeWithRandomMessages(t *testing.T) { mapp := mock.NewApp() - bank.RegisterWire(mapp.Cdc) - mapper := mapp.AccountMapper - coinKeeper := bank.NewKeeper(mapper) - stakeKey := sdk.NewKVStoreKey("stake") - stakeKeeper := stake.NewKeeper(mapp.Cdc, stakeKey, coinKeeper, stake.DefaultCodespace) - mapp.Router().AddRoute("stake", []*sdk.KVStoreKey{mapp.KeyStake, mapp.KeyAccount}, stake.NewHandler(stakeKeeper)) + bank.RegisterCodec(mapp.Cdc) + stake.RegisterCodec(mapp.Cdc) + + mapper := mapp.AccountKeeper + bankKeeper := mapp.BankKeeper + + feeKey := mapp.KeyFeeCollection + stakeKey := mapp.KeyStake + stakeTKey := mapp.TkeyStake + paramsKey := mapp.KeyParams + paramsTKey := mapp.TkeyParams + distrKey := sdk.NewKVStoreKey("distr") + + feeCollectionKeeper := auth.NewFeeCollectionKeeper(mapp.Cdc, feeKey) + paramstore := params.NewKeeper(mapp.Cdc, paramsKey, paramsTKey) + stakeKeeper := stake.NewKeeper(mapp.Cdc, stakeKey, stakeTKey, bankKeeper, paramstore.Subspace(stake.DefaultParamspace), stake.DefaultCodespace) + distrKeeper := distribution.NewKeeper(mapp.Cdc, distrKey, paramstore.Subspace(distribution.DefaultParamspace), bankKeeper, stakeKeeper, feeCollectionKeeper, distribution.DefaultCodespace) + mapp.Router().AddRoute("stake", []*sdk.KVStoreKey{stakeKey, mapp.KeyAccount, distrKey}, stake.NewHandler(stakeKeeper)) mapp.SetEndBlocker(func(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { validatorUpdates := stake.EndBlocker(ctx, stakeKeeper) return abci.ResponseEndBlock{ @@ -32,31 +45,61 @@ func TestStakeWithRandomMessages(t *testing.T) { } }) - err := mapp.CompleteSetup([]*sdk.KVStoreKey{stakeKey}) + err := mapp.CompleteSetup(distrKey) if err != nil { panic(err) } - appStateFn := func(r *rand.Rand, keys []crypto.PrivKey, accs []sdk.AccAddress) json.RawMessage { - mock.RandomSetGenesis(r, mapp, accs, []string{"iris"}) + appStateFn := func(r *rand.Rand, accs []simulation.Account) json.RawMessage { + simulation.RandomSetGenesis(r, mapp, accs, []string{mock.DefaultStakeDenom}) return json.RawMessage("{}") } + GenesisSetUp := func(r *rand.Rand, accs []simulation.Account) { + ctx := mapp.NewContext(false, abci.Header{}) + distribution.InitGenesis(ctx, distrKeeper, distribution.DefaultGenesisState()) + + // init stake genesis + var ( + validators []stake.Validator + delegations []stake.Delegation + ) + stakeGenesis := stake.DefaultGenesisState() + + // XXX Try different numbers of initially bonded validators + numInitiallyBonded := int64(4) + valAddrs := make([]sdk.ValAddress, numInitiallyBonded) + decAmt := sdk.NewDecFromInt(sdk.NewIntWithDecimal(1, 2)) + for i := 0; i < int(numInitiallyBonded); i++ { + valAddr := sdk.ValAddress(accs[i].Address) + valAddrs[i] = valAddr + + validator := stake.NewValidator(valAddr, accs[i].PubKey, stake.Description{}) + validator.Tokens = decAmt + validator.DelegatorShares = decAmt + delegation := stake.Delegation{accs[i].Address, valAddr, decAmt, 0} + validators = append(validators, validator) + delegations = append(delegations, delegation) + } + stakeGenesis.Pool.LooseTokens = sdk.NewDecFromInt(sdk.NewIntWithDecimal(1, 10)) + stakeGenesis.Validators = validators + stakeGenesis.Bonds = delegations + + stake.InitGenesis(ctx, stakeKeeper, stakeGenesis) + } + simulation.Simulate( t, mapp.BaseApp, appStateFn, - []simulation.TestAndRunTx{ - SimulateMsgCreateValidator(mapper, stakeKeeper), - SimulateMsgEditValidator(stakeKeeper), - SimulateMsgDelegate(mapper, stakeKeeper), - SimulateMsgBeginUnbonding(mapper, stakeKeeper), - SimulateMsgCompleteUnbonding(stakeKeeper), - SimulateMsgBeginRedelegate(mapper, stakeKeeper), - SimulateMsgCompleteRedelegate(stakeKeeper), + []simulation.WeightedOperation{ + {10, SimulateMsgCreateValidator(mapper, stakeKeeper)}, + {5, SimulateMsgEditValidator(stakeKeeper)}, + {15, SimulateMsgDelegate(mapper, stakeKeeper)}, + {10, SimulateMsgBeginUnbonding(mapper, stakeKeeper)}, + {10, SimulateMsgBeginRedelegate(mapper, stakeKeeper)}, }, []simulation.RandSetup{ - Setup(mapp, stakeKeeper), - }, []simulation.Invariant{ - AllInvariants(coinKeeper, stakeKeeper, mapp.AccountMapper), - }, 10, 100, + //Setup(mapp, stakeKeeper), + GenesisSetUp, + }, []simulation.Invariant{}, 10, 100, false, ) } diff --git a/tools/prometheus/consensus/metrics.go b/tools/prometheus/consensus/metrics.go index fadefdada..81adc805b 100644 --- a/tools/prometheus/consensus/metrics.go +++ b/tools/prometheus/consensus/metrics.go @@ -6,10 +6,11 @@ import ( cctx "context" "encoding/hex" "fmt" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/stake" "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/prometheus" + "github.com/irisnet/irishub/client/context" stdprometheus "github.com/prometheus/client_golang/prometheus" "github.com/spf13/viper" "github.com/tendermint/tendermint/consensus" @@ -17,7 +18,6 @@ import ( "log" "strings" "time" - "github.com/irisnet/irishub/client/context" ) // TODO @@ -117,7 +117,7 @@ type Metrics struct { // PrometheusMetrics returns Metrics build using Prometheus client library. func PrometheusMetrics() *Metrics { - tmMetrics := *consensus.PrometheusMetrics() + tmMetrics := *consensus.PrometheusMetrics("") irisMetrics := NewIrisMetrics() return &Metrics{ TmMetrics: tmMetrics, @@ -179,7 +179,7 @@ func (cs *Metrics) Start(ctx context.CLIContext) { }() } -func (cs *Metrics) RecordMetrics(ctx context.CLIContext, cdc *wire.Codec, block *types.Block) { +func (cs *Metrics) RecordMetrics(ctx context.CLIContext, cdc *codec.Codec, block *types.Block) { var client = ctx.Client cs.TmMetrics.Height.Set(float64(block.Height)) @@ -238,7 +238,7 @@ func (cs *Metrics) RecordMetrics(ctx context.CLIContext, cdc *wire.Codec, block lastBlockHight := block.Height - 1 lastBlock, _ := client.Block(&lastBlockHight) interval := block.Time.Sub(lastBlock.BlockMeta.Header.Time).Seconds() - cs.TmMetrics.BlockIntervalSeconds.Observe(interval) + cs.TmMetrics.BlockIntervalSeconds.Set(interval) } cs.TmMetrics.NumTxs.Set(float64(block.NumTxs)) @@ -267,7 +267,7 @@ func (cs *Metrics) RecordMetrics(ctx context.CLIContext, cdc *wire.Codec, block cs.IrisMetrics.UpTime.Set(float64(cs.IrisMetrics.SignedCount) / float64(cs.IrisMetrics.blockInfo.Len())) cs.IrisMetrics.MissedPrecommits.Set(float64(cs.IrisMetrics.MissedCount)) } - bz, _ := cdc.MarshalBinaryBare(block) + bz, _ := cdc.MarshalBinaryLengthPrefixed(block) cs.TmMetrics.BlockSizeBytes.Set(float64(len(bz))) } diff --git a/tools/prometheus/governance/metrics.go b/tools/prometheus/governance/metrics.go index bc39f1c5c..acd70e8d8 100644 --- a/tools/prometheus/governance/metrics.go +++ b/tools/prometheus/governance/metrics.go @@ -1,17 +1,17 @@ package governance import ( + "fmt" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/prometheus" + "github.com/irisnet/irishub/client/context" + "github.com/irisnet/irishub/modules/gov" stdprometheus "github.com/prometheus/client_golang/prometheus" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/spf13/viper" "log" "time" - "github.com/cosmos/cosmos-sdk/wire" - "github.com/cosmos/cosmos-sdk/x/gov" - "fmt" - "github.com/spf13/viper" - "github.com/irisnet/irishub/client/context" ) // TODO @@ -82,7 +82,7 @@ func (gov *Metrics) Start(ctx context.CLIContext) { }() } -func (gov *Metrics) RecordMetrics(ctx context.CLIContext, cdc *wire.Codec) { +func (gov *Metrics) RecordMetrics(ctx context.CLIContext, cdc *codec.Codec) { count := 0 needToVote := 0 if activeProposals, err := getAllActiveProposalsID(cdc, ctx); err != nil { @@ -90,8 +90,7 @@ func (gov *Metrics) RecordMetrics(ctx context.CLIContext, cdc *wire.Codec) { } else { count = len(activeProposals) for _, proposalId := range activeProposals { - if _, err := getVote(proposalId, gov.govMetrics.Address, cdc, ctx); - err != nil { + if _, err := getVote(int64(proposalId), gov.govMetrics.Address, cdc, ctx); err != nil { needToVote++ } } @@ -103,43 +102,43 @@ func (gov *Metrics) RecordMetrics(ctx context.CLIContext, cdc *wire.Codec) { //-------------------------help functions-------------------------------------- -func getAllInactiveProposalsID(cdc *wire.Codec, ctx context.CLIContext) (proposals gov.ProposalQueue, err error) { - if res, err := ctx.QueryStore(gov.KeyInactiveProposalQueue, storeName); err != nil { +func getAllInactiveProposalsID(cdc *codec.Codec, ctx context.CLIContext) (proposals gov.ProposalQueue, err error) { + if res, err := ctx.QueryStore(gov.PrefixInactiveProposalQueue, storeName); err != nil { return gov.ProposalQueue{}, err } else { - err = cdc.UnmarshalBinary(res, &proposals) + err = cdc.UnmarshalBinaryLengthPrefixed(res, &proposals) return proposals, err } } -func getAllActiveProposalsID(cdc *wire.Codec, ctx context.CLIContext) (proposals gov.ProposalQueue, err error) { - if res, err := ctx.QueryStore(gov.KeyActiveProposalQueue, storeName); len(res) == 0 || err != nil { +func getAllActiveProposalsID(cdc *codec.Codec, ctx context.CLIContext) (proposals gov.ProposalQueue, err error) { + if res, err := ctx.QueryStore(gov.PrefixActiveProposalQueue, storeName); len(res) == 0 || err != nil { return gov.ProposalQueue{}, err } else { - err = cdc.UnmarshalBinary(res, &proposals) + err = cdc.UnmarshalBinaryLengthPrefixed(res, &proposals) return proposals, err } } -func getProposal(ID int64, cdc *wire.Codec, ctx context.CLIContext) (*gov.Proposal, error) { - if res, err := ctx.QueryStore(gov.KeyProposal(ID), storeName); err != nil { +func getProposal(ID int64, cdc *codec.Codec, ctx context.CLIContext) (*gov.Proposal, error) { + if res, err := ctx.QueryStore(gov.KeyProposal(uint64(ID)), storeName); err != nil { return nil, err } else { var proposal *gov.Proposal - err = cdc.UnmarshalBinary(res, proposal) + err = cdc.UnmarshalBinaryLengthPrefixed(res, proposal) return proposal, err } } -func getVote(proposalID int64, voterAddr sdk.AccAddress, cdc *wire.Codec, ctx context.CLIContext) (vote gov.Vote, err error) { - if res, err := ctx.QueryStore(gov.KeyVote(proposalID, voterAddr), storeName); err != nil { +func getVote(proposalID int64, voterAddr sdk.AccAddress, cdc *codec.Codec, ctx context.CLIContext) (vote gov.Vote, err error) { + if res, err := ctx.QueryStore(gov.KeyVote(uint64(proposalID), voterAddr), storeName); err != nil { return gov.Vote{}, err } else { if len(res) == 0 { return gov.Vote{}, fmt.Errorf("cannot find the vote that %s vote for proposal %d", voterAddr.String(), proposalID) } - err = cdc.UnmarshalBinary(res, &vote) + err = cdc.UnmarshalBinaryLengthPrefixed(res, &vote) return vote, err } } diff --git a/tools/prometheus/mempool/metrics.go b/tools/prometheus/mempool/metrics.go index d230630e6..01541afe5 100644 --- a/tools/prometheus/mempool/metrics.go +++ b/tools/prometheus/mempool/metrics.go @@ -15,7 +15,7 @@ type Metrics struct { // PrometheusMetrics returns Metrics build using Prometheus client library. func PrometheusMetrics() *Metrics { - tmMetrics := *mempool.PrometheusMetrics() + tmMetrics := *mempool.PrometheusMetrics("") return &Metrics{ tmMetrics, } diff --git a/tools/prometheus/p2p/metrics.go b/tools/prometheus/p2p/metrics.go index b3abbb896..c70a6ef5e 100644 --- a/tools/prometheus/p2p/metrics.go +++ b/tools/prometheus/p2p/metrics.go @@ -3,6 +3,7 @@ package p2p import ( "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/prometheus" + "github.com/irisnet/irishub/client/context" "github.com/pelletier/go-toml" stdprometheus "github.com/prometheus/client_golang/prometheus" "github.com/spf13/viper" @@ -11,11 +12,9 @@ import ( "path/filepath" "strings" "time" - "github.com/irisnet/irishub/client/context" ) type Metrics struct { - // Number of peers. Peers metrics.Gauge // Number of connected persistent peers. @@ -55,7 +54,7 @@ func (m *Metrics) Start(ctx context.CLIContext) { if result, err := ctx.NetInfo(); err == nil { connected := 0 for _, peer := range result.Peers { - if _, exist := m.persistent_peers[string(peer.ID)]; exist { + if _, exist := m.persistent_peers[string(peer.NodeInfo.ID())]; exist { connected += 1 } } diff --git a/tools/prometheus/provider.go b/tools/prometheus/provider.go index db741c760..7aaece81b 100644 --- a/tools/prometheus/provider.go +++ b/tools/prometheus/provider.go @@ -1,14 +1,18 @@ package prometheus import ( + "github.com/irisnet/irishub/client/context" cs "github.com/irisnet/irishub/tools/prometheus/consensus" + gov "github.com/irisnet/irishub/tools/prometheus/governance" mempl "github.com/irisnet/irishub/tools/prometheus/mempool" "github.com/irisnet/irishub/tools/prometheus/p2p" sys "github.com/irisnet/irishub/tools/prometheus/system" - gov "github.com/irisnet/irishub/tools/prometheus/governance" - "github.com/irisnet/irishub/client/context" ) +type MetricsProvider interface { + Start(ctx context.CLIContext) +} + type Monitor struct { providers []MetricsProvider ctx context.CLIContext @@ -38,7 +42,3 @@ func (m *Monitor) Start() { provider.Start(m.ctx) } } - -type MetricsProvider interface { - Start(ctx context.CLIContext) -} diff --git a/tools/prometheus/server.go b/tools/prometheus/server.go index b4129769d..9ed27f175 100644 --- a/tools/prometheus/server.go +++ b/tools/prometheus/server.go @@ -2,7 +2,7 @@ package prometheus import ( "fmt" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/irisnet/irishub/client/context" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/spf13/cobra" @@ -13,7 +13,7 @@ import ( "github.com/irisnet/irishub/app" ) -func MonitorCommand(cdc *wire.Codec) *cobra.Command { +func MonitorCommand(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "irismon", Short: "iris monitor tool", diff --git a/tools/protoidl/parse.go b/tools/protoidl/parse.go index 3bedc04af..084a1abbb 100644 --- a/tools/protoidl/parse.go +++ b/tools/protoidl/parse.go @@ -6,6 +6,8 @@ import ( "fmt" ) +const maxElements = 200 + // validate proto idl text func ValidateProto(content string) (bool, error) { reader := strings.NewReader(content) @@ -26,12 +28,36 @@ func GetMethods(content string) (methods []Method, err error) { return methods, err } + if len(definition.Elements) > maxElements { + err = fmt.Errorf("too many elements in idl content, limit to %d", maxElements) + return methods, err + } + // iterate definition get all method var rs []*proto.RPC + rm := make(map[string]*proto.RPC) + var ms []*proto.Message + mm := make(map[string]*proto.Message) proto.Walk(definition, proto.WithRPC(func(r *proto.RPC) { + if _, ok := rm[r.Name]; ok { + err = fmt.Errorf("contains duplicate methods %s", r.Name) + } + rm[r.Name] = r rs = append(rs, r) - })) + }), + proto.WithMessage(func(m *proto.Message) { + if _, ok := mm[m.Name]; ok { + err = fmt.Errorf("contains duplicate messages %s", m.Name) + } + mm[m.Name] = m + ms = append(ms, m) + }), + ) + + if err != nil { + return methods, err + } // get method attribute from comment, each line comment only define one attribute for _, r := range rs { diff --git a/types/coin_type.go b/types/coin_type.go index 339cbfcc9..d37d13e34 100644 --- a/types/coin_type.go +++ b/types/coin_type.go @@ -119,18 +119,19 @@ func (ct CoinType) Convert(orgCoinStr string, denom string) (destCoinStr string, } // target Coin = original amount * (10^(target decimal) / 10^(original decimal)) if orgUnit, err := ct.GetUnit(orgDenom); err == nil { - rat := sdk.NewRatFromInt(destUint.GetPrecision(), orgUnit.GetPrecision()) - amount, err := sdk.NewRatFromDecimal(orgAmt, ct.MinUnit.Decimal) //Convert the original amount to the target accuracy + rat := NewRatFromInt(destUint.GetPrecision(), orgUnit.GetPrecision()) + amount, err := NewRatFromDecimal(orgAmt, ct.MinUnit.Decimal) //Convert the original amount to the target accuracy if err != nil { return destCoinStr, err } - amt := NewRat(amount.Mul(rat)).DecimalString(ct.MinUnit.Decimal) + amt := amount.Mul(rat).DecimalString(ct.MinUnit.Decimal) destCoinStr = fmt.Sprintf("%s%s", amt, destUint.Denom) return destCoinStr, nil } return destCoinStr, errors.New("not exist unit " + orgDenom) } + func (ct CoinType) ConvertToMinCoin(coinStr string) (coin sdk.Coin, err error) { minUint := ct.GetMinUnit() @@ -176,6 +177,7 @@ func NewDefaultCoinType(name string) CoinType { } } +//TODO currently only iris token is supported func CoinTypeKey(coinName string) string { return fmt.Sprintf("%s/%s/%s", "global", "coin_types", coinName) } @@ -212,14 +214,17 @@ func GetCoin(coinStr string) (denom, amount string, err error) { } func parseCoin(coinStr string) (coin sdk.Coin, err error) { - if denom, amount, err := GetCoin(coinStr); err == nil { - if amt, ok := sdk.NewIntFromString(amount); ok { - denom = strings.ToLower(denom) - coin := sdk.NewCoin(denom, amt) - return coin, err - } + denom, amount, err := GetCoin(coinStr); + if err != nil { + return sdk.Coin{}, err } - return + + amt, ok := sdk.NewIntFromString(amount) + if !ok { + return sdk.Coin{}, fmt.Errorf("invalid coin amount: %s", amount) + } + denom = strings.ToLower(denom) + return sdk.NewCoin(denom, amt), nil } func GetCoinName(coinStr string) (coinName string, err error) { diff --git a/types/coin_type_test.go b/types/coin_type_test.go index 39b1b9d73..efb728b71 100644 --- a/types/coin_type_test.go +++ b/types/coin_type_test.go @@ -8,24 +8,29 @@ import ( func TestConvert(t *testing.T) { irisToken := NewDefaultCoinType("iris") - result, err := irisToken.Convert("1500000000000000001iris-atto", "iris") + result, err := irisToken.Convert("1500000000000000001iris-atto", "iris-nano") require.Nil(t, err) + require.Equal(t,"1500000000.000000001iris-nano",result) t.Log(result) result, err = irisToken.Convert("15iris", "iris-atto") require.Nil(t, err) + require.Equal(t,"15000000000000000000iris-atto",result) t.Log(result) result, err = irisToken.Convert("1.5iris", "iris-nano") require.Nil(t, err) + require.Equal(t,"1500000000iris-nano",result) t.Log(result) result, err = irisToken.Convert("1500000000000000001iris-atto", "iris-nano") require.Nil(t, err) + require.Equal(t,"1500000000.000000001iris-nano",result) t.Log(result) result, err = irisToken.Convert("1500000001.123iris-nano", "iris") require.Nil(t, err) + require.Equal(t,"1.500000001123iris",result) t.Log(result) } diff --git a/types/rational.go b/types/rational.go index 1dc943748..296afc5e7 100644 --- a/types/rational.go +++ b/types/rational.go @@ -2,7 +2,10 @@ package types import ( "fmt" + "math/big" + "strconv" "strings" + "testing" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -16,17 +19,146 @@ import ( // we will panic unmarshalling into the // nil embedded big.Rat type Rat struct { - sdk.Rat + *big.Rat `json:"rat"` } -func NewRat(rat sdk.Rat) Rat{ - return Rat{ - rat, +// nolint - common values +func ZeroRat() Rat { return Rat{big.NewRat(0, 1)} } +func OneRat() Rat { return Rat{big.NewRat(1, 1)} } + +// New - create a new Rat from integers +func NewRat(Numerator int64, Denominator ...int64) Rat { + switch len(Denominator) { + case 0: + return Rat{big.NewRat(Numerator, 1)} + case 1: + return Rat{big.NewRat(Numerator, Denominator[0])} + default: + panic("improper use of New, can only have one denominator") + } +} + +func getNumeratorDenominator(str []string, prec int) (numerator string, denom int64, err sdk.Error) { + switch len(str) { + case 1: + if len(str[0]) == 0 { + return "", 0, sdk.ErrUnknownRequest("not a decimal string") + } + numerator = str[0] + return numerator, 1, nil + case 2: + if len(str[0]) == 0 || len(str[1]) == 0 { + return "", 0, sdk.ErrUnknownRequest("not a decimal string") + } + if len(str[1]) > prec { + return "", 0, sdk.ErrUnknownRequest("string has too many decimals") + } + numerator = str[0] + str[1] + len := int64(len(str[1])) + denom = new(big.Int).Exp(big.NewInt(10), big.NewInt(len), nil).Int64() + return numerator, denom, nil + default: + return "", 0, sdk.ErrUnknownRequest("not a decimal string") + } +} + +// create a rational from decimal string or integer string +// precision is the number of values after the decimal point which should be read +func NewRatFromDecimal(decimalStr string, prec int) (f Rat, err sdk.Error) { + // first extract any negative symbol + if len(decimalStr) == 0 { + return f, sdk.ErrUnknownRequest("decimal string is empty") + } + + neg := false + if string(decimalStr[0]) == "-" { + neg = true + decimalStr = decimalStr[1:] + } + + str := strings.Split(decimalStr, ".") + + numStr, denom, err := getNumeratorDenominator(str, prec) + if err != nil { + return f, err + } + + num, errConv := strconv.Atoi(numStr) + if errConv != nil && strings.HasSuffix(errConv.Error(), "value out of range") { + // resort to big int, don't make this default option for efficiency + numBig, success := new(big.Int).SetString(numStr, 10) + if success != true { + return f, sdk.ErrUnknownRequest("not a decimal string") + } + + if neg { + numBig.Neg(numBig) + } + + return NewRatFromBigInt(numBig, big.NewInt(denom)), nil + } else if errConv != nil { + return f, sdk.ErrUnknownRequest("not a decimal string") + } + + if neg { + num *= -1 + } + + return NewRat(int64(num), denom), nil +} + +// NewRatFromBigInt constructs Rat from big.Int +func NewRatFromBigInt(num *big.Int, denom ...*big.Int) Rat { + switch len(denom) { + case 0: + return Rat{new(big.Rat).SetInt(num)} + case 1: + return Rat{new(big.Rat).SetFrac(num, denom[0])} + default: + panic("improper use of NewRatFromBigInt, can only have one denominator") + } +} + +// NewRatFromInt constructs Rat from Int +func NewRatFromInt(num sdk.Int, denom ...sdk.Int) Rat { + switch len(denom) { + case 0: + return Rat{new(big.Rat).SetInt(num.BigInt())} + case 1: + return Rat{new(big.Rat).SetFrac(num.BigInt(), denom[0].BigInt())} + default: + panic("improper use of NewRatFromBigInt, can only have one denominator") } } +//nolint +func (r Rat) Num() sdk.Int { return sdk.NewIntFromBigInt(r.Rat.Num()) } // Num - return the numerator +func (r Rat) Denom() sdk.Int { return sdk.NewIntFromBigInt(r.Rat.Denom()) } // Denom - return the denominator +func (r Rat) IsZero() bool { return r.Num().IsZero() } // IsZero - Is the Rat equal to zero +func (r Rat) Equal(r2 Rat) bool { return (r.Rat).Cmp(r2.Rat) == 0 } +func (r Rat) GT(r2 Rat) bool { return (r.Rat).Cmp(r2.Rat) == 1 } // greater than +func (r Rat) GTE(r2 Rat) bool { return !r.LT(r2) } // greater than or equal +func (r Rat) LT(r2 Rat) bool { return (r.Rat).Cmp(r2.Rat) == -1 } // less than +func (r Rat) LTE(r2 Rat) bool { return !r.GT(r2) } // less than or equal +func (r Rat) Mul(r2 Rat) Rat { return Rat{new(big.Rat).Mul(r.Rat, r2.Rat)} } // Mul - multiplication +func (r Rat) Quo(r2 Rat) Rat { return Rat{new(big.Rat).Quo(r.Rat, r2.Rat)} } // Quo - quotient +func (r Rat) Add(r2 Rat) Rat { return Rat{new(big.Rat).Add(r.Rat, r2.Rat)} } // Add - addition +func (r Rat) Sub(r2 Rat) Rat { return Rat{new(big.Rat).Sub(r.Rat, r2.Rat)} } // Sub - subtraction +func (r Rat) String() string { return r.Rat.String() } +func (r Rat) FloatString() string { return r.Rat.FloatString(10) } // a human-friendly string format. The last digit is rounded to nearest, with halves rounded away from zero. + +var ( + zero = big.NewInt(0) + one = big.NewInt(1) + two = big.NewInt(2) + five = big.NewInt(5) + nFive = big.NewInt(-5) + ten = big.NewInt(10) +) + +//DecimalString func (r Rat) DecimalString(prec int) string { - floatStr := r.Rat.Rat.FloatString(prec) + floatStr := r.Rat.FloatString(prec) str := strings.Split(floatStr,".") if len(str) == 1 { return str[0] @@ -38,4 +170,111 @@ func (r Rat) DecimalString(prec int) string { return str[0] } return fmt.Sprintf("%s.%s",str[0],dot) -} \ No newline at end of file +} + +// evaluate the rational using bankers rounding +func (r Rat) EvaluateBig() *big.Int { + + num := r.Rat.Num() + denom := r.Rat.Denom() + + d, rem := new(big.Int), new(big.Int) + d.QuoRem(num, denom, rem) + if rem.Cmp(zero) == 0 { // is the remainder zero + return d + } + + // evaluate the remainder using bankers rounding + tenNum := new(big.Int).Mul(num, ten) + tenD := new(big.Int).Mul(d, ten) + remainderDigit := new(big.Int).Sub(new(big.Int).Quo(tenNum, denom), tenD) // get the first remainder digit + isFinalDigit := (new(big.Int).Rem(tenNum, denom).Cmp(zero) == 0) // is this the final digit in the remainder? + + switch { + case isFinalDigit && (remainderDigit.Cmp(five) == 0 || remainderDigit.Cmp(nFive) == 0): + dRem2 := new(big.Int).Rem(d, two) + return new(big.Int).Add(d, dRem2) // always rounds to the even number + case remainderDigit.Cmp(five) != -1: //remainderDigit >= 5: + d.Add(d, one) + case remainderDigit.Cmp(nFive) != 1: //remainderDigit <= -5: + d.Sub(d, one) + } + return d +} + +// RoundInt64 rounds the rational using bankers rounding +func (r Rat) RoundInt64() int64 { + return r.EvaluateBig().Int64() +} + +// RoundInt round the rational using bankers rounding +func (r Rat) RoundInt() sdk.Int { + return sdk.NewIntFromBigInt(r.EvaluateBig()) +} + +// round Rat with the provided precisionFactor +func (r Rat) Round(precisionFactor int64) Rat { + rTen := Rat{new(big.Rat).Mul(r.Rat, big.NewRat(precisionFactor, 1))} + return Rat{big.NewRat(rTen.RoundInt64(), precisionFactor)} +} + +// TODO panic if negative or if totalDigits < len(initStr)??? +// evaluate as an integer and return left padded string +func (r Rat) ToLeftPadded(totalDigits int8) string { + intStr := r.EvaluateBig().String() + fcode := `%0` + strconv.Itoa(int(totalDigits)) + `s` + return fmt.Sprintf(fcode, intStr) +} + +//___________________________________________________________________________________ + +//Wraps r.MarshalText(). +func (r Rat) MarshalAmino() (string, error) { + if r.Rat == nil { + r.Rat = new(big.Rat) + } + bz, err := r.Rat.MarshalText() + return string(bz), err +} + +// Requires a valid JSON string - strings quotes and calls UnmarshalText +func (r *Rat) UnmarshalAmino(text string) (err error) { + tempRat := big.NewRat(0, 1) + err = tempRat.UnmarshalText([]byte(text)) + if err != nil { + return err + } + r.Rat = tempRat + return nil +} + +//___________________________________________________________________________________ +// helpers + +// test if two rat arrays are equal +func RatsEqual(r1s, r2s []Rat) bool { + if len(r1s) != len(r2s) { + return false + } + + for i, r1 := range r1s { + if !r1.Equal(r2s[i]) { + return false + } + } + return true +} + +// intended to be used with require/assert: require.True(RatEq(...)) +func RatEq(t *testing.T, exp, got Rat) (*testing.T, bool, string, Rat, Rat) { + return t, exp.Equal(got), "expected:\t%v\ngot:\t\t%v", exp, got +} + +// minimum rational between two +func MinRat(r1, r2 Rat) Rat { + if r1.LT(r2) { + return r1 + } + return r2 +} + diff --git a/types/rational_test.go b/types/rational_test.go new file mode 100644 index 000000000..ef3623d51 --- /dev/null +++ b/types/rational_test.go @@ -0,0 +1,403 @@ +package types + +import ( + "math/big" + "math/rand" + "testing" + + codec "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" +) + +func TestNew(t *testing.T) { + require.Equal(t, NewRat(1), NewRat(1, 1)) + require.Equal(t, NewRat(100), NewRat(100, 1)) + require.Equal(t, NewRat(-1), NewRat(-1, 1)) + require.Equal(t, NewRat(-100), NewRat(-100, 1)) + require.Equal(t, NewRat(0), NewRat(0, 1)) + + // do not allow for more than 2 variables + require.Panics(t, func() { NewRat(1, 1, 1) }) +} + +func TestNewFromDecimal(t *testing.T) { + largeBigInt, success := new(big.Int).SetString("3109736052979742687701388262607869", 10) + require.True(t, success) + tests := []struct { + decimalStr string + expErr bool + exp Rat + }{ + {"", true, Rat{}}, + {"0", false, NewRat(0)}, + {"1", false, NewRat(1)}, + {"1.1", false, NewRat(11, 10)}, + {"0.75", false, NewRat(3, 4)}, + {"0.8", false, NewRat(4, 5)}, + {"0.11111", true, NewRat(1111, 10000)}, + {"628240629832763.5738930323617075341", true, NewRat(3141203149163817869, 5000)}, + {"621947210595948537540277652521.5738930323617075341", + true, NewRatFromBigInt(largeBigInt, big.NewInt(5000))}, + {"628240629832763.5738", false, NewRat(3141203149163817869, 5000)}, + {"621947210595948537540277652521.5738", + false, NewRatFromBigInt(largeBigInt, big.NewInt(5000))}, + {".", true, Rat{}}, + {".0", true, Rat{}}, + {"1.", true, Rat{}}, + {"foobar", true, Rat{}}, + {"0.foobar", true, Rat{}}, + {"0.foobar.", true, Rat{}}, + } + + for tcIndex, tc := range tests { + res, err := NewRatFromDecimal(tc.decimalStr, 4) + if tc.expErr { + require.NotNil(t, err, tc.decimalStr, "error expected, tc #%d", tcIndex) + } else { + require.Nil(t, err, tc.decimalStr, "unexpected error, tc #%d", tcIndex) + require.True(t, res.Equal(tc.exp), tc.decimalStr, "equality was incorrect, tc #%d", tcIndex) + } + + // negative tc + res, err = NewRatFromDecimal("-"+tc.decimalStr, 4) + if tc.expErr { + require.NotNil(t, err, tc.decimalStr, "error expected (negative case), tc #%d", tcIndex) + } else { + require.Nil(t, err, tc.decimalStr, "unexpected error (negative case), tc #%d", tcIndex) + require.True(t, res.Equal(tc.exp.Mul(NewRat(-1))), tc.decimalStr, "equality was incorrect (negative case), tc #%d", tcIndex) + } + } +} + +func TestEqualities(t *testing.T) { + tests := []struct { + r1, r2 Rat + gt, lt, eq bool + }{ + {NewRat(0), NewRat(0), false, false, true}, + {NewRat(0, 100), NewRat(0, 10000), false, false, true}, + {NewRat(100), NewRat(100), false, false, true}, + {NewRat(-100), NewRat(-100), false, false, true}, + {NewRat(-100, -1), NewRat(100), false, false, true}, + {NewRat(-1, 1), NewRat(1, -1), false, false, true}, + {NewRat(1, -1), NewRat(-1, 1), false, false, true}, + {NewRat(3, 7), NewRat(3, 7), false, false, true}, + + {NewRat(0), NewRat(3, 7), false, true, false}, + {NewRat(0), NewRat(100), false, true, false}, + {NewRat(-1), NewRat(3, 7), false, true, false}, + {NewRat(-1), NewRat(100), false, true, false}, + {NewRat(1, 7), NewRat(100), false, true, false}, + {NewRat(1, 7), NewRat(3, 7), false, true, false}, + {NewRat(-3, 7), NewRat(-1, 7), false, true, false}, + + {NewRat(3, 7), NewRat(0), true, false, false}, + {NewRat(100), NewRat(0), true, false, false}, + {NewRat(3, 7), NewRat(-1), true, false, false}, + {NewRat(100), NewRat(-1), true, false, false}, + {NewRat(100), NewRat(1, 7), true, false, false}, + {NewRat(3, 7), NewRat(1, 7), true, false, false}, + {NewRat(-1, 7), NewRat(-3, 7), true, false, false}, + } + + for tcIndex, tc := range tests { + require.Equal(t, tc.gt, tc.r1.GT(tc.r2), "GT result is incorrect, tc #%d", tcIndex) + require.Equal(t, tc.lt, tc.r1.LT(tc.r2), "LT result is incorrect, tc #%d", tcIndex) + require.Equal(t, tc.eq, tc.r1.Equal(tc.r2), "equality result is incorrect, tc #%d", tcIndex) + } + +} + +func TestArithmetic(t *testing.T) { + tests := []struct { + r1, r2 Rat + resMul, resDiv, resAdd, resSub Rat + }{ + // r1 r2 MUL DIV ADD SUB + {NewRat(0), NewRat(0), NewRat(0), NewRat(0), NewRat(0), NewRat(0)}, + {NewRat(1), NewRat(0), NewRat(0), NewRat(0), NewRat(1), NewRat(1)}, + {NewRat(0), NewRat(1), NewRat(0), NewRat(0), NewRat(1), NewRat(-1)}, + {NewRat(0), NewRat(-1), NewRat(0), NewRat(0), NewRat(-1), NewRat(1)}, + {NewRat(-1), NewRat(0), NewRat(0), NewRat(0), NewRat(-1), NewRat(-1)}, + + {NewRat(1), NewRat(1), NewRat(1), NewRat(1), NewRat(2), NewRat(0)}, + {NewRat(-1), NewRat(-1), NewRat(1), NewRat(1), NewRat(-2), NewRat(0)}, + {NewRat(1), NewRat(-1), NewRat(-1), NewRat(-1), NewRat(0), NewRat(2)}, + {NewRat(-1), NewRat(1), NewRat(-1), NewRat(-1), NewRat(0), NewRat(-2)}, + + {NewRat(3), NewRat(7), NewRat(21), NewRat(3, 7), NewRat(10), NewRat(-4)}, + {NewRat(2), NewRat(4), NewRat(8), NewRat(1, 2), NewRat(6), NewRat(-2)}, + {NewRat(100), NewRat(100), NewRat(10000), NewRat(1), NewRat(200), NewRat(0)}, + + {NewRat(3, 2), NewRat(3, 2), NewRat(9, 4), NewRat(1), NewRat(3), NewRat(0)}, + {NewRat(3, 7), NewRat(7, 3), NewRat(1), NewRat(9, 49), NewRat(58, 21), NewRat(-40, 21)}, + {NewRat(1, 21), NewRat(11, 5), NewRat(11, 105), NewRat(5, 231), NewRat(236, 105), NewRat(-226, 105)}, + {NewRat(-21), NewRat(3, 7), NewRat(-9), NewRat(-49), NewRat(-144, 7), NewRat(-150, 7)}, + {NewRat(100), NewRat(1, 7), NewRat(100, 7), NewRat(700), NewRat(701, 7), NewRat(699, 7)}, + } + + for tcIndex, tc := range tests { + require.True(t, tc.resMul.Equal(tc.r1.Mul(tc.r2)), "r1 %v, r2 %v. tc #%d", tc.r1.Rat, tc.r2.Rat, tcIndex) + require.True(t, tc.resAdd.Equal(tc.r1.Add(tc.r2)), "r1 %v, r2 %v. tc #%d", tc.r1.Rat, tc.r2.Rat, tcIndex) + require.True(t, tc.resSub.Equal(tc.r1.Sub(tc.r2)), "r1 %v, r2 %v. tc #%d", tc.r1.Rat, tc.r2.Rat, tcIndex) + + if tc.r2.Num().IsZero() { // panic for divide by zero + require.Panics(t, func() { tc.r1.Quo(tc.r2) }) + } else { + require.True(t, tc.resDiv.Equal(tc.r1.Quo(tc.r2)), "r1 %v, r2 %v. tc #%d", tc.r1.Rat, tc.r2.Rat, tcIndex) + } + } +} + +func TestEvaluate(t *testing.T) { + tests := []struct { + r1 Rat + res int64 + }{ + {NewRat(0), 0}, + {NewRat(1), 1}, + {NewRat(1, 4), 0}, + {NewRat(1, 2), 0}, + {NewRat(3, 4), 1}, + {NewRat(5, 6), 1}, + {NewRat(3, 2), 2}, + {NewRat(5, 2), 2}, + {NewRat(6, 11), 1}, // 0.545-> 1 even though 5 is first decimal and 1 not even + {NewRat(17, 11), 2}, // 1.545 + {NewRat(5, 11), 0}, + {NewRat(16, 11), 1}, + {NewRat(113, 12), 9}, + } + + for tcIndex, tc := range tests { + require.Equal(t, tc.res, tc.r1.RoundInt64(), "%v. tc #%d", tc.r1, tcIndex) + require.Equal(t, tc.res*-1, tc.r1.Mul(NewRat(-1)).RoundInt64(), "%v. tc #%d", tc.r1.Mul(NewRat(-1)), tcIndex) + } +} + +func TestRound(t *testing.T) { + many3 := "333333333333333333333333333333333333333333333" + many7 := "777777777777777777777777777777777777777777777" + big3, worked := new(big.Int).SetString(many3, 10) + require.True(t, worked) + big7, worked := new(big.Int).SetString(many7, 10) + require.True(t, worked) + + tests := []struct { + r, res Rat + precFactor int64 + }{ + {NewRat(333, 777), NewRat(429, 1000), 1000}, + {Rat{new(big.Rat).SetFrac(big3, big7)}, NewRat(429, 1000), 1000}, + {Rat{new(big.Rat).SetFrac(big3, big7)}, Rat{big.NewRat(4285714286, 10000000000)}, 10000000000}, + {NewRat(1, 2), NewRat(1, 2), 1000}, + } + + for tcIndex, tc := range tests { + require.Equal(t, tc.res, tc.r.Round(tc.precFactor), "%v", tc.r, "incorrect rounding, tc #%d", tcIndex) + negR1, negRes := tc.r.Mul(NewRat(-1)), tc.res.Mul(NewRat(-1)) + require.Equal(t, negRes, negR1.Round(tc.precFactor), "%v", negR1, "incorrect rounding (negative case), tc #%d", tcIndex) + } +} + +func TestToLeftPadded(t *testing.T) { + tests := []struct { + rat Rat + digits int8 + res string + }{ + {NewRat(100, 3), 8, "00000033"}, + {NewRat(1, 3), 8, "00000000"}, + {NewRat(100, 2), 8, "00000050"}, + {NewRat(1000, 3), 8, "00000333"}, + {NewRat(1000, 3), 12, "000000000333"}, + } + for tcIndex, tc := range tests { + require.Equal(t, tc.res, tc.rat.ToLeftPadded(tc.digits), "incorrect left padding, tc #%d", tcIndex) + } +} + +var cdc = codec.New() //var jsonCdc JSONCodec // TODO codec.Codec + +func TestZeroSerializationJSON(t *testing.T) { + r := NewRat(0, 1) + err := cdc.UnmarshalJSON([]byte(`"0/1"`), &r) + require.Nil(t, err) + err = cdc.UnmarshalJSON([]byte(`"0/0"`), &r) + require.NotNil(t, err) + err = cdc.UnmarshalJSON([]byte(`"1/0"`), &r) + require.NotNil(t, err) + err = cdc.UnmarshalJSON([]byte(`"{}"`), &r) + require.NotNil(t, err) +} + +func TestSerializationText(t *testing.T) { + r := NewRat(1, 3) + + bz, err := r.MarshalText() + require.NoError(t, err) + + var r2 = Rat{new(big.Rat)} + err = r2.UnmarshalText(bz) + require.NoError(t, err) + require.True(t, r.Equal(r2), "original: %v, unmarshalled: %v", r, r2) +} + +func TestSerializationGoWireJSON(t *testing.T) { + r := NewRat(1, 3) + bz, err := cdc.MarshalJSON(r) + require.NoError(t, err) + + var r2 Rat + err = cdc.UnmarshalJSON(bz, &r2) + require.NoError(t, err) + require.True(t, r.Equal(r2), "original: %v, unmarshalled: %v", r, r2) +} + +func TestSerializationGoWireBinary(t *testing.T) { + r := NewRat(1, 3) + bz, err := cdc.MarshalBinaryLengthPrefixed(r) + require.NoError(t, err) + + var r2 Rat + err = cdc.UnMarshalBinaryLengthPrefixed(bz, &r2) + require.NoError(t, err) + require.True(t, r.Equal(r2), "original: %v, unmarshalled: %v", r, r2) +} + +type testEmbedStruct struct { + Field1 string `json:"f1"` + Field2 int `json:"f2"` + Field3 Rat `json:"f3"` +} + +func TestEmbeddedStructSerializationGoWire(t *testing.T) { + obj := testEmbedStruct{"foo", 10, NewRat(1, 3)} + bz, err := cdc.MarshalJSON(obj) + require.Nil(t, err) + + var obj2 testEmbedStruct + err = cdc.UnmarshalJSON(bz, &obj2) + require.Nil(t, err) + + require.Equal(t, obj.Field1, obj2.Field1) + require.Equal(t, obj.Field2, obj2.Field2) + require.True(t, obj.Field3.Equal(obj2.Field3), "original: %v, unmarshalled: %v", obj, obj2) +} + +func TestRatsEqual(t *testing.T) { + tests := []struct { + r1s, r2s []Rat + eq bool + }{ + {[]Rat{NewRat(0)}, []Rat{NewRat(0)}, true}, + {[]Rat{NewRat(0)}, []Rat{NewRat(1)}, false}, + {[]Rat{NewRat(0)}, []Rat{}, false}, + {[]Rat{NewRat(0), NewRat(1)}, []Rat{NewRat(0), NewRat(1)}, true}, + {[]Rat{NewRat(1), NewRat(0)}, []Rat{NewRat(1), NewRat(0)}, true}, + {[]Rat{NewRat(1), NewRat(0)}, []Rat{NewRat(0), NewRat(1)}, false}, + {[]Rat{NewRat(1), NewRat(0)}, []Rat{NewRat(1)}, false}, + {[]Rat{NewRat(1), NewRat(2)}, []Rat{NewRat(2), NewRat(4)}, false}, + {[]Rat{NewRat(3), NewRat(18)}, []Rat{NewRat(1), NewRat(6)}, false}, + } + + for tcIndex, tc := range tests { + require.Equal(t, tc.eq, RatsEqual(tc.r1s, tc.r2s), "equality of rational arrays is incorrect, tc #%d", tcIndex) + require.Equal(t, tc.eq, RatsEqual(tc.r2s, tc.r1s), "equality of rational arrays is incorrect (converse), tc #%d", tcIndex) + } + +} + +func TestStringOverflow(t *testing.T) { + // two random 64 bit primes + rat1 := NewRat(5164315003622678713, 4389711697696177267) + rat2 := NewRat(-3179849666053572961, 8459429845579852627) + rat3 := rat1.Add(rat2) + require.Equal(t, + "29728537197630860939575850336935951464/37134458148982045574552091851127630409", + rat3.String(), + ) +} + +// Tests below uses randomness +// Since we are using *big.Rat as underlying value +// and (U/)Int is immutable value(see TestImmutability(U/)Int) +// it is safe to use randomness in the tests +func TestArithRat(t *testing.T) { + for i := 0; i < 20; i++ { + n1 := sdk.NewInt(int64(rand.Int31())) + d1 := sdk.NewInt(int64(rand.Int31())) + rat1 := NewRatFromInt(n1, d1) + + n2 := sdk.NewInt(int64(rand.Int31())) + d2 := sdk.NewInt(int64(rand.Int31())) + rat2 := NewRatFromInt(n2, d2) + + n1d2 := n1.Mul(d2) + n2d1 := n2.Mul(d1) + + cases := []struct { + nres sdk.Int + dres sdk.Int + rres Rat + }{ + {n1d2.Add(n2d1), d1.Mul(d2), rat1.Add(rat2)}, + {n1d2.Sub(n2d1), d1.Mul(d2), rat1.Sub(rat2)}, + {n1.Mul(n2), d1.Mul(d2), rat1.Mul(rat2)}, + {n1d2, n2d1, rat1.Quo(rat2)}, + } + + for _, tc := range cases { + require.Equal(t, NewRatFromInt(tc.nres, tc.dres), tc.rres) + } + } +} + +func TestCompRat(t *testing.T) { + for i := 0; i < 20; i++ { + n1 := sdk.NewInt(int64(rand.Int31())) + d1 := sdk.NewInt(int64(rand.Int31())) + rat1 := NewRatFromInt(n1, d1) + + n2 := sdk.NewInt(int64(rand.Int31())) + d2 := sdk.NewInt(int64(rand.Int31())) + rat2 := NewRatFromInt(n2, d2) + + n1d2 := n1.Mul(d2) + n2d1 := n2.Mul(d1) + + cases := []struct { + ires bool + rres bool + }{ + {n1d2.Equal(n2d1), rat1.Equal(rat2)}, + {n1d2.GT(n2d1), rat1.GT(rat2)}, + {n1d2.LT(n2d1), rat1.LT(rat2)}, + {n1d2.GT(n2d1) || n1d2.Equal(n2d1), rat1.GTE(rat2)}, + {n1d2.LT(n2d1) || n1d2.Equal(n2d1), rat1.LTE(rat2)}, + } + + for _, tc := range cases { + require.Equal(t, tc.ires, tc.rres) + } + } +} + +func TestImmutabilityRat(t *testing.T) { + for i := 0; i < 20; i++ { + n := int64(rand.Int31()) + r := NewRat(n) + z := ZeroRat() + o := OneRat() + + r.Add(z) + r.Sub(z) + r.Mul(o) + r.Quo(o) + + require.Equal(t, n, r.RoundInt64()) + require.True(t, NewRat(n).Equal(r)) + } + +} diff --git a/version/version.go b/version/version.go index f938d7b65..47f64586c 100644 --- a/version/version.go +++ b/version/version.go @@ -2,12 +2,12 @@ package version import ( "fmt" - "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/codec" "github.com/spf13/cobra" ) // Version - Iris Version -const Version = "0.6.0" +const Version = "0.7.0-Alpha" // GitCommit set by build flags var GitCommit = "" @@ -22,7 +22,7 @@ func GetVersion() string { } // ServeVersionCommand -func ServeVersionCommand(cdc *wire.Codec) *cobra.Command { +func ServeVersionCommand(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "version", Short: "Show executable binary version",