Merge remote-tracking branch 'origin/develop' into rigel/fee-distribution

This commit is contained in:
rigelrozanski 2018-10-04 18:33:12 -04:00
commit 45f0dd0e3b
149 changed files with 83721 additions and 3280 deletions

View File

@ -3,7 +3,7 @@ version: 2
defaults: &defaults
working_directory: /go/src/github.com/cosmos/cosmos-sdk
docker:
- image: circleci/golang:1.10.3
- image: circleci/golang:1.11.1
environment:
GOBIN: /tmp/workspace/bin
@ -206,6 +206,12 @@ jobs:
- run:
name: run localnet and exit on failure
command: |
pushd /tmp
wget https://dl.google.com/go/go1.11.linux-amd64.tar.gz
sudo tar -xvf go1.11.linux-amd64.tar.gz
sudo rm -rf /usr/local/go
sudo mv go /usr/local
popd
set -x
make get_tools
make get_vendor_deps

1
.gitignore vendored
View File

@ -17,6 +17,7 @@ docs/_build
examples/basecoin/app/data
baseapp/data/*
client/lcd/keys/*
client/lcd/statik/statik.go
mytestnet
# Testing

87
Gopkg.lock generated
View File

@ -34,11 +34,11 @@
[[projects]]
branch = "master"
digest = "1:2c00f064ba355903866cbfbf3f7f4c0fe64af6638cc7d1b8bdcf3181bc67f1d8"
digest = "1:c0decf632843204d2b8781de7b26e7038584e2dcccc7e2f401e88ae85b1df2b7"
name = "github.com/btcsuite/btcd"
packages = ["btcec"]
pruneopts = "UT"
revision = "d81d8877b8f327112e94e814937143a71d1692a7"
revision = "2a560b2036bee5e3679ec2133eb6520b2f195213"
[[projects]]
digest = "1:386de157f7d19259a7f9c81f26ce011223ce0f090353c1152ffdf730d7d10ac2"
@ -95,12 +95,12 @@
version = "v0.3.0"
[[projects]]
digest = "1:c4a2528ccbcabf90f9f3c464a5fc9e302d592861bbfd0b7135a7de8a943d0406"
digest = "1:586ea76dbd0374d6fb649a91d70d652b7fe0ccffb8910a77468e7702e7901f3d"
name = "github.com/go-stack/stack"
packages = ["."]
pruneopts = "UT"
revision = "259ab82a6cad3992b4e21ff5cac294ccb06474bc"
version = "v1.7.0"
revision = "2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a"
version = "v1.8.0"
[[projects]]
digest = "1:35621fe20f140f05a0c4ef662c26c0ab4ee50bca78aa30fe87d33120bd28165e"
@ -164,13 +164,13 @@
version = "v1.2.0"
[[projects]]
branch = "master"
digest = "1:12247a2e99a060cc692f6680e5272c8adf0b8f572e6bce0d7095e624c958a240"
digest = "1:c0d19ab64b32ce9fe5cf4ddceba78d5bc9807f0016db6b1183599da3dcc24d10"
name = "github.com/hashicorp/hcl"
packages = [
".",
"hcl/ast",
"hcl/parser",
"hcl/printer",
"hcl/scanner",
"hcl/strconv",
"hcl/token",
@ -179,7 +179,8 @@
"json/token",
]
pruneopts = "UT"
revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168"
revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241"
version = "v1.0.0"
[[projects]]
digest = "1:870d441fe217b8e689d7949fef6e43efbc787e50f200cb1e70dbca9204a1d6be"
@ -214,12 +215,12 @@
version = "v1.8.0"
[[projects]]
digest = "1:d4d17353dbd05cb52a2a52b7fe1771883b682806f68db442b436294926bbfafb"
digest = "1:0981502f9816113c9c8c4ac301583841855c8cf4da8c72f696b3ebedf6d0e4e5"
name = "github.com/mattn/go-isatty"
packages = ["."]
pruneopts = "UT"
revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39"
version = "v0.0.3"
revision = "6ca4dbf54d38eea1a992b3c722a76a5d1c4cb25c"
version = "v0.0.4"
[[projects]]
digest = "1:ff5ebae34cfbf047d505ee150de27e60570e8c394b3b8fdbb720ff6ac71985fc"
@ -238,12 +239,12 @@
version = "v1.0.0"
[[projects]]
digest = "1:645110e089152bd0f4a011a2648fbb0e4df5977be73ca605781157ac297f50c4"
digest = "1:e32dfc6abff6a3633ef4d9a1022fd707c8ef26f1e1e8f855dc58dc415ce7c8f3"
name = "github.com/mitchellh/mapstructure"
packages = ["."]
pruneopts = "UT"
revision = "fa473d140ef3c6adf42d6b391fe76707f1f243c8"
version = "v1.0.0"
revision = "fe40af7a9c397fa3ddba203c38a5042c5d0475ad"
version = "v1.1.1"
[[projects]]
digest = "1:95741de3af260a92cc5c7f3f3061e85273f5a81b5db20d4bd68da74bd521675e"
@ -301,7 +302,7 @@
[[projects]]
branch = "master"
digest = "1:8c49953a1414305f2ff5465147ee576dd705487c35b15918fcd4efdc0cb7a290"
digest = "1:ef1dd9945e58ee9b635273d28c0ef3fa3742a7dedc038ebe207fd63e6ce000ef"
name = "github.com/prometheus/procfs"
packages = [
".",
@ -310,7 +311,15 @@
"xfs",
]
pruneopts = "UT"
revision = "05ee40e3a273f7245e8777337fc7b46e533a9a92"
revision = "418d78d0b9a7b7de3a6bbc8a23def624cc977bb2"
[[projects]]
digest = "1:ea0700160aca4ef099f4e06686a665a87691f4248dddd40796925eda2e46bd64"
name = "github.com/rakyll/statik"
packages = ["fs"]
pruneopts = "UT"
revision = "aa8a7b1baecd0f31a436bf7956fcdcc609a83035"
version = "v0.1.4"
[[projects]]
digest = "1:c4556a44e350b50a490544d9b06e9fba9c286c21d6c0e47f54f3a9214597298c"
@ -320,15 +329,15 @@
revision = "e2704e165165ec55d062f5919b4b29494e9fa790"
[[projects]]
digest = "1:bd1ae00087d17c5a748660b8e89e1043e1e5479d0fea743352cda2f8dd8c4f84"
digest = "1:6a4a11ba764a56d2758899ec6f3848d24698d48442ebce85ee7a3f63284526cd"
name = "github.com/spf13/afero"
packages = [
".",
"mem",
]
pruneopts = "UT"
revision = "787d034dfe70e44075ccc060d346146ef53270ad"
version = "v1.1.1"
revision = "d40851caa0d747393da1ffb28f7f9d8b4eeffebd"
version = "v1.1.2"
[[projects]]
digest = "1:516e71bed754268937f57d4ecb190e01958452336fa73dbac880894164e91c1f"
@ -347,12 +356,12 @@
version = "v0.0.1"
[[projects]]
branch = "master"
digest = "1:8a020f916b23ff574845789daee6818daf8d25a4852419aae3f0b12378ba432a"
digest = "1:68ea4e23713989dc20b1bded5d9da2c5f9be14ff9885beef481848edd18c26cb"
name = "github.com/spf13/jwalterweatherman"
packages = ["."]
pruneopts = "UT"
revision = "14d3d4c518341bea657dd8a226f5121c0ff8c9f2"
revision = "4a4406e478ca629068e7768fc33f3f044173c0a6"
version = "v1.0.0"
[[projects]]
digest = "1:dab83a1bbc7ad3d7a6ba1a1cc1760f25ac38cdf7d96a5cdd55cd915a4f5ceaf9"
@ -402,6 +411,13 @@
pruneopts = "UT"
revision = "ae2bd5eed72d46b28834ec3f60db3a3ebedd8dbd"
[[projects]]
digest = "1:605b6546f3f43745695298ec2d342d3e952b6d91cdf9f349bea9315f677d759f"
name = "github.com/tendermint/btcd"
packages = ["btcec"]
pruneopts = "UT"
revision = "e5840949ff4fff0c56f9b6a541e22b63581ea9df"
[[projects]]
branch = "master"
digest = "1:087aaa7920e5d0bf79586feb57ce01c35c830396ab4392798112e8aae8c47722"
@ -415,12 +431,12 @@
revision = "d8387025d2b9d158cf4efb07e7ebf814bcce2057"
[[projects]]
digest = "1:e0a2a4be1e20c305badc2b0a7a9ab7fef6da500763bec23ab81df3b5f9eec9ee"
digest = "1:2c971a45c89ca2ccc735af50919cdee05fbdc54d4bf50625073693300e31ead8"
name = "github.com/tendermint/go-amino"
packages = ["."]
pruneopts = "UT"
revision = "a8328986c1608950fa5d3d1c0472cccc4f8fc02c"
version = "v0.12.0-rc0"
revision = "faa6e731944e2b7b6a46ad202902851e8ce85bee"
version = "v0.12.0"
[[projects]]
digest = "1:53397098d6acb7613358683cc84ae59281a60c6033f0bff62fa8d3f279c6c430"
@ -431,7 +447,7 @@
version = "v0.11.0"
[[projects]]
digest = "1:4f15e95fe3888cc75dd34f407d6394cbc7fd3ff24920851b92b295f6a8b556e6"
digest = "1:f4fcc1a4dbe079b200556ca26c1ff1dacf23712125b9c265d8f02c0dbc318f39"
name = "github.com/tendermint/tendermint"
packages = [
"abci/client",
@ -449,6 +465,8 @@
"crypto/ed25519",
"crypto/encoding/amino",
"crypto/merkle",
"crypto/multisig",
"crypto/multisig/bitarray",
"crypto/secp256k1",
"crypto/tmhash",
"crypto/xsalsa20symmetric",
@ -468,7 +486,6 @@
"lite",
"lite/client",
"lite/errors",
"lite/files",
"lite/proxy",
"mempool",
"node",
@ -491,11 +508,12 @@
"state/txindex/kv",
"state/txindex/null",
"types",
"types/time",
"version",
]
pruneopts = "UT"
revision = "81df19e68ab1519399fccf0cab81cb75bf9d782e"
version = "v0.23.1-rc0"
revision = "d419fffe18531317c28c29a292ad7d253f6cafdf"
version = "v0.24.0"
[[projects]]
digest = "1:7886f86064faff6f8d08a3eb0e8c773648ff5a2e27730831e2bfbf07467f6666"
@ -526,7 +544,7 @@
"salsa20/salsa",
]
pruneopts = "UT"
revision = "614d502a4dac94afa3a6ce146bd1736da82514c6"
revision = "e3636079e1a4c1f337f212cc5cd2aca108f6c900"
[[projects]]
digest = "1:d36f55a999540d29b6ea3c2ea29d71c76b1d9853fdcd3e5c5cb4836f2ba118f1"
@ -546,14 +564,14 @@
[[projects]]
branch = "master"
digest = "1:ead82e3e398388679f3ad77633a087ac31a47a6be59ae20841e1d1b3a3fbbd22"
digest = "1:8bc8ecef1d63576cfab4d08b44a1f255dd67e5b019b7a44837d62380f266a91c"
name = "golang.org/x/sys"
packages = [
"cpu",
"unix",
]
pruneopts = "UT"
revision = "4ea2f632f6e912459fe60b26b1749377f0d889d5"
revision = "e4b3c5e9061176387e7cea65e4dc5853801f3fb7"
[[projects]]
digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18"
@ -580,11 +598,11 @@
[[projects]]
branch = "master"
digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c"
digest = "1:1e6b0176e8c5dd8ff551af65c76f8b73a99bcf4d812cedff1b91711b7df4804c"
name = "google.golang.org/genproto"
packages = ["googleapis/rpc/status"]
pruneopts = "UT"
revision = "c66870c02cf823ceb633bcd05be3c7cda29976f4"
revision = "c7e5094acea1ca1b899e2259d80a6b0f882f81f8"
[[projects]]
digest = "1:2dab32a43451e320e49608ff4542fdfc653c95dcc35d0065ec9c6c3dd540ed74"
@ -641,6 +659,7 @@
"github.com/mitchellh/go-homedir",
"github.com/pelletier/go-toml",
"github.com/pkg/errors",
"github.com/rakyll/statik/fs",
"github.com/spf13/cobra",
"github.com/spf13/pflag",
"github.com/spf13/viper",

View File

@ -49,7 +49,7 @@
[[override]]
name = "github.com/tendermint/go-amino"
version = "=v0.12.0-rc0"
version = "=v0.12.0"
[[override]]
name = "github.com/tendermint/iavl"
@ -57,7 +57,7 @@
[[override]]
name = "github.com/tendermint/tendermint"
version = "=v0.23.1-rc0"
version = "=0.24.0"
[[constraint]]
name = "github.com/bartekn/go-bip39"
@ -67,6 +67,10 @@
name = "github.com/zondax/ledger-goclient"
version = "=v0.1.0"
[[constraint]]
name = "github.com/rakyll/statik"
version = "=v0.1.4"
[prune]
go-tests = true
unused-packages = true

View File

@ -32,7 +32,7 @@ TMP_BUILD_TAGS := $(BUILD_TAGS)
BUILD_TAGS = $(filter-out ledger, $(TMP_BUILD_TAGS))
endif
build: check-ledger
build: check-ledger update_gaia_lite_docs
ifeq ($(OS),Windows_NT)
go build $(BUILD_FLAGS) -o build/gaiad.exe ./cmd/gaia/cmd/gaiad
go build $(BUILD_FLAGS) -o build/gaiacli.exe ./cmd/gaia/cmd/gaiacli
@ -44,6 +44,9 @@ endif
build-linux:
LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build
update_gaia_lite_docs:
@statik -src=client/lcd/swagger-ui -dest=client/lcd -f
build_cosmos-sdk-cli:
ifeq ($(OS),Windows_NT)
go build $(BUILD_FLAGS) -o build/cosmos-sdk-cli.exe ./cmd/cosmos-sdk-cli
@ -64,7 +67,7 @@ else
go build $(BUILD_FLAGS) -o build/democli ./examples/democoin/cmd/democli
endif
install: check-ledger
install: check-ledger update_gaia_lite_docs
go install $(BUILD_FLAGS) ./cmd/gaia/cmd/gaiad
go install $(BUILD_FLAGS) ./cmd/gaia/cmd/gaiacli
@ -179,14 +182,14 @@ test_cover:
test_lint:
gometalinter.v2 --config=tools/gometalinter.json ./...
!(gometalinter.v2 --disable-all --enable='errcheck' --vendor ./... | grep -v "client/")
!(gometalinter.v2 --exclude /usr/lib/go/src/ --exclude client/lcd/statik/statik.go --disable-all --enable='errcheck' --vendor ./... | grep -v "client/")
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" | xargs gofmt -d -s
dep status >> /dev/null
!(grep -n branch Gopkg.toml)
format:
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" | xargs gofmt -w -s
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" | xargs misspell -w
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs gofmt -w -s
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs misspell -w
benchmark:
@go test -bench=. $(PACKAGES_NOSIMULATION)

View File

@ -37,11 +37,16 @@ BREAKING CHANGES
* `cosmosaccaddr` / `cosmosaccpub` => `cosmos` / `cosmospub`
* `cosmosvaladdr` / `cosmosvalpub` => `cosmosvaloper` / `cosmosvaloperpub`
* [x/stake] [#1013] TendermintUpdates now uses transient store
* [x/stake] \#2435 Remove empty bytes from the ValidatorPowerRank store key
* [x/gov] [#2195] Governance uses BFT Time
* [x/gov] \#2256 Removed slashing for governance non-voting validators
* [simulation] \#2162 Added back correct supply invariants
* SDK
* [core] \#2219 Update to Tendermint 0.24.0
* Validator set updates delayed by one block
* BFT timestamp that can safely be used by applications
* Fixed maximum block size enforcement
* [core] [\#1807](https://github.com/cosmos/cosmos-sdk/issues/1807) Switch from use of rational to decimal
* [types] [\#1901](https://github.com/cosmos/cosmos-sdk/issues/1901) Validator interface's GetOwner() renamed to GetOperator()
* [x/slashing] [#2122](https://github.com/cosmos/cosmos-sdk/pull/2122) - Implement slashing period
@ -60,6 +65,7 @@ BREAKING CHANGES
* [x/auth] \#2377 auth.StdSignMsg -> txbuilder.StdSignMsg
* [x/staking] \#2244 staking now holds a consensus-address-index instead of a consensus-pubkey-index
* [x/staking] \#2236 more distribution hooks for distribution
* [x/stake] \#2394 Split up UpdateValidator into distinct state transitions applied only in EndBlock
* Tendermint
@ -71,6 +77,7 @@ FEATURES
* [gaia-lite] [\#966](https://github.com/cosmos/cosmos-sdk/issues/966) Add support for `generate_only=true` query argument to generate offline unsigned transactions
* [gaia-lite] [\#1953](https://github.com/cosmos/cosmos-sdk/issues/1953) Add /sign endpoint to sign transactions generated with `generate_only=true`.
* [gaia-lite] [\#1954](https://github.com/cosmos/cosmos-sdk/issues/1954) Add /broadcast endpoint to broadcast transactions signed by the /sign endpoint.
* [gaia-lite] [\#2113](https://github.com/cosmos/cosmos-sdk/issues/2113) Rename `/accounts/{address}/send` to `/bank/accounts/{address}/transfers`
* Gaia CLI (`gaiacli`)
* [cli] Cmds to query staking pool and params
@ -104,6 +111,7 @@ FEATURES
* [x/auth] \#2376 Remove FeePayer() from StdTx
* [x/stake] [\#1672](https://github.com/cosmos/cosmos-sdk/issues/1672) Implement
basis for the validator commission model.
* [x/auth] Support account removal in the account mapper.
* Tendermint
@ -124,6 +132,7 @@ IMPROVEMENTS
* [x/auth] Signature verification's gas cost now accounts for pubkey type. [#2046](https://github.com/tendermint/tendermint/pull/2046)
* [x/stake] [x/slashing] Ensure delegation invariants to jailed validators [#1883](https://github.com/cosmos/cosmos-sdk/issues/1883).
* [x/stake] Improve speed of GetValidator, which was shown to be a performance bottleneck. [#2046](https://github.com/tendermint/tendermint/pull/2200)
* [x/stake] \#2435 Improve memory efficiency of getting the various store keys
* [genesis] \#2229 Ensure that there are no duplicate accounts or validators in the genesis state.
* Add SDK validation to `config.toml` (namely disabling `create_empty_blocks`) \#1571
* \#1941(https://github.com/cosmos/cosmos-sdk/issues/1941) Version is now inferred via `git describe --tags`.
@ -138,6 +147,7 @@ IMPROVEMENTS
* [simulation] Make logs not just pure strings, speeding it up by a large factor at greater block heights \#2282
* [simulation] Add a concept of weighting the operations \#2303
* [simulation] Logs get written to file if large, and also get printed on panics \#2285
* [simulation] Bank simulations now makes testing auth configurable \#2425
* [gaiad] \#1992 Add optional flag to `gaiad testnet` to make config directory of daemon (default `gaiad`) and cli (default `gaiacli`) configurable
* [x/stake] Add stake `Queriers` for Gaia-lite endpoints. This increases the staking endpoints performance by reusing the staking `keeper` logic for queries. [#2249](https://github.com/cosmos/cosmos-sdk/pull/2149)
* [store] [\#2017](https://github.com/cosmos/cosmos-sdk/issues/2017) Refactor
@ -168,5 +178,7 @@ BUG FIXES
* [\#2158](https://github.com/cosmos/cosmos-sdk/issues/2158) Fix non-deterministic ordering of validator iteration when slashing in `gov EndBlocker`
* [simulation] \#1924 Make simulation stop on SIGTERM
* [\#2388](https://github.com/cosmos/cosmos-sdk/issues/2388) Remove dependency on deprecated tendermint/tmlibs repository.
* [\#2416](https://github.com/cosmos/cosmos-sdk/issues/2416) Refactored
`InitializeTestLCD` to properly include proposing validator in genesis state.
* Tendermint

View File

@ -22,7 +22,7 @@ breaking changes.
## Gaia Testnet
To join the latest testnet, follow
[the guide](https://cosmos.network/docs/getting-started/full-node.html#setting-up-a-new-node).
[the guide](./docs/getting-started/join-testnet.md).
For status updates and genesis files, see the
[testnets repo](https://github.com/cosmos/testnets).
@ -30,15 +30,14 @@ For status updates and genesis files, see the
## Install
See the
[install instructions](https://cosmos.network/docs/getting-started/installation.html).
[install instructions](./docs/getting-started/installation.md).
## Quick Start
See the [Cosmos Docs](https://cosmos.network/docs/)
- [Getting started with the SDK](https://cosmos.network/docs/sdk/core/intro.html)
- [Getting started with the SDK](./docs/sdk/core/intro.md)
- [SDK Examples](/examples)
- [Join the testnet](https://cosmos.network/docs/getting-started/full-node.html#run-a-full-node)
## Disambiguation

View File

@ -64,9 +64,9 @@ 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
@ -435,7 +435,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
}
@ -509,12 +509,12 @@ func validateBasicTxMsgs(msgs []sdk.Msg) sdk.Error {
}
// retrieve the context for the ante handler and store the tx bytes; store
// the signing validators if the tx runs within the deliverTx() state.
// 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
ctx = getState(app, mode).ctx.WithTxBytes(txBytes)
if mode == runTxModeDeliver {
ctx = ctx.WithSigningValidators(app.signedValidators)
ctx = ctx.WithVoteInfos(app.voteInfos)
}
return
}

View File

@ -1,15 +1,15 @@
package client
import (
"github.com/spf13/cobra"
"github.com/mitchellh/go-homedir"
"bufio"
"path"
"os"
"io/ioutil"
"github.com/pelletier/go-toml"
"fmt"
"github.com/cosmos/cosmos-sdk/types"
"github.com/mitchellh/go-homedir"
"github.com/pelletier/go-toml"
"github.com/spf13/cobra"
"io/ioutil"
"os"
"path"
)
type cliConfig struct {
@ -34,7 +34,7 @@ func ConfigCmd() *cobra.Command {
return cfg
}
func runConfigCmd(cmd *cobra.Command, args [] string) error {
func runConfigCmd(cmd *cobra.Command, args []string) error {
home, err := homedir.Dir()
if err != nil {
return err

View File

@ -69,6 +69,22 @@ func (ctx CLIContext) BroadcastTxAndAwaitCommit(tx []byte) (*ctypes.ResultBroadc
return res, err
}
// BroadcastTxSync broadcasts transaction bytes to a Tendermint node
// synchronously.
func (ctx CLIContext) BroadcastTxSync(tx []byte) (*ctypes.ResultBroadcastTx, error) {
node, err := ctx.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 (ctx CLIContext) BroadcastTxAsync(tx []byte) (*ctypes.ResultBroadcastTx, error) {
@ -91,7 +107,7 @@ func (ctx CLIContext) broadcastTxAsync(txBytes []byte) (*ctypes.ResultBroadcastT
return res, err
}
if ctx.Logger != nil {
if ctx.Output != nil {
if ctx.JSON {
type toJSON struct {
TxHash string
@ -103,10 +119,10 @@ func (ctx CLIContext) broadcastTxAsync(txBytes []byte) (*ctypes.ResultBroadcastT
return res, err
}
ctx.Logger.Write(bz)
io.WriteString(ctx.Logger, "\n")
ctx.Output.Write(bz)
io.WriteString(ctx.Output, "\n")
} else {
io.WriteString(ctx.Logger, fmt.Sprintf("async tx sent (tx hash: %s)\n", res.Hash))
io.WriteString(ctx.Output, fmt.Sprintf("async tx sent (tx hash: %s)\n", res.Hash))
}
}
@ -128,21 +144,21 @@ func (ctx CLIContext) broadcastTxCommit(txBytes []byte) (*ctypes.ResultBroadcast
Response abci.ResponseDeliverTx
}
if ctx.Logger != nil {
if ctx.Output != nil {
resJSON := toJSON{res.Height, res.Hash.String(), res.DeliverTx}
bz, err := ctx.Codec.MarshalJSON(resJSON)
if err != nil {
return res, err
}
ctx.Logger.Write(bz)
io.WriteString(ctx.Logger, "\n")
ctx.Output.Write(bz)
io.WriteString(ctx.Output, "\n")
}
return res, nil
}
if ctx.Logger != nil {
if ctx.Output != nil {
resStr := fmt.Sprintf("Committed at block %d (tx hash: %s)\n", res.Height, res.Hash.String())
if ctx.PrintResponse {
@ -151,7 +167,7 @@ func (ctx CLIContext) broadcastTxCommit(txBytes []byte) (*ctypes.ResultBroadcast
)
}
io.WriteString(ctx.Logger, resStr)
io.WriteString(ctx.Output, resStr)
}
return res, nil

View File

@ -4,6 +4,8 @@ import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
@ -11,25 +13,29 @@ import (
"github.com/spf13/viper"
"github.com/cosmos/cosmos-sdk/client/keys"
cskeys "github.com/cosmos/cosmos-sdk/crypto/keys"
"github.com/cosmos/cosmos-sdk/types"
"github.com/tendermint/tendermint/libs/cli"
"github.com/tendermint/tendermint/libs/log"
tmlite "github.com/tendermint/tendermint/lite"
tmliteProxy "github.com/tendermint/tendermint/lite/proxy"
rpcclient "github.com/tendermint/tendermint/rpc/client"
"os"
"github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/client/keys"
cskeys "github.com/cosmos/cosmos-sdk/crypto/keys"
)
const ctxAccStoreName = "acc"
var (
verifier tmlite.Verifier
)
// CLIContext implements a typical CLI context created in SDK modules for
// transaction handling and queries.
type CLIContext struct {
Codec *codec.Codec
AccDecoder auth.AccountDecoder
Client rpcclient.Client
Logger io.Writer
Output io.Writer
Height int64
NodeURI string
From string
@ -39,11 +45,12 @@ type CLIContext struct {
Async bool
JSON bool
PrintResponse bool
Certifier tmlite.Certifier
Verifier tmlite.Verifier
DryRun bool
GenerateOnly bool
fromAddress types.AccAddress
fromName string
Indent bool
}
// NewCLIContext returns a new initialized CLIContext with parameters from the
@ -59,8 +66,14 @@ func NewCLIContext() CLIContext {
from := viper.GetString(client.FlagFrom)
fromAddress, fromName := fromFields(from)
// We need to use a single verifier for all contexts
if verifier == nil {
verifier = createVerifier()
}
return CLIContext{
Client: rpc,
Output: os.Stdout,
NodeURI: nodeURI,
AccountStore: ctxAccStoreName,
From: viper.GetString(client.FlagFrom),
@ -70,15 +83,16 @@ func NewCLIContext() CLIContext {
Async: viper.GetBool(client.FlagAsync),
JSON: viper.GetBool(client.FlagJson),
PrintResponse: viper.GetBool(client.FlagPrintResponse),
Certifier: createCertifier(),
Verifier: verifier,
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
@ -107,15 +121,16 @@ func createCertifier() tmlite.Certifier {
fmt.Printf("Must specify these options: %s when --trust-node is false\n", errMsg.String())
os.Exit(1)
}
node := rpcclient.NewHTTP(nodeURI, "/websocket")
verifier, err := tmliteProxy.NewVerifier(chainID, filepath.Join(home, ".gaialite"), node, log.NewNopLogger())
certifier, err := tmliteProxy.GetCertifier(chainID, home, nodeURI)
if err != nil {
fmt.Printf("Create certifier failed: %s\n", err.Error())
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 certifier
return verifier
}
func fromFields(from string) (fromAddr types.AccAddress, fromName string) {
@ -162,9 +177,9 @@ func (ctx CLIContext) WithAccountDecoder(decoder auth.AccountDecoder) CLIContext
return ctx
}
// WithLogger returns a copy of the context with an updated logger.
func (ctx CLIContext) WithLogger(w io.Writer) CLIContext {
ctx.Logger = w
// WithOutput returns a copy of the context with an updated output writer (e.g. stdout).
func (ctx CLIContext) WithOutput(w io.Writer) CLIContext {
ctx.Output = w
return ctx
}
@ -206,8 +221,8 @@ func (ctx CLIContext) WithUseLedger(useLedger bool) CLIContext {
return ctx
}
// WithCertifier - return a copy of the context with an updated Certifier
func (ctx CLIContext) WithCertifier(certifier tmlite.Certifier) CLIContext {
ctx.Certifier = certifier
// WithVerifier - return a copy of the context with an updated Verifier
func (ctx CLIContext) WithVerifier(verifier tmlite.Verifier) CLIContext {
ctx.Verifier = verifier
return ctx
}

View File

@ -14,10 +14,10 @@ import (
"github.com/cosmos/cosmos-sdk/store"
abci "github.com/tendermint/tendermint/abci/types"
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"
rpcclient "github.com/tendermint/tendermint/rpc/client"
tmtypes "github.com/tendermint/tendermint/types"
)
// GetNode returns an RPC client. If the context's client is not defined, an
@ -184,14 +184,14 @@ func (ctx CLIContext) query(path string, key cmn.HexBytes) (res []byte, err erro
return resp.Value, nil
}
// Certify verifies the consensus proof at given height.
func (ctx CLIContext) Certify(height int64) (lite.Commit, error) {
check, err := tmliteProxy.GetCertifiedCommit(height, ctx.Client, ctx.Certifier)
// Verify verifies the consensus proof at given height.
func (ctx CLIContext) Verify(height int64) (tmtypes.SignedHeader, error) {
check, err := tmliteProxy.GetCertifiedCommit(height, ctx.Client, ctx.Verifier)
switch {
case tmliteErr.IsCommitNotFoundErr(err):
return lite.Commit{}, ErrVerifyCommit(height)
case tmliteErr.IsErrCommitNotFound(err):
return tmtypes.SignedHeader{}, ErrVerifyCommit(height)
case err != nil:
return lite.Commit{}, err
return tmtypes.SignedHeader{}, err
}
return check, nil
@ -199,12 +199,12 @@ func (ctx CLIContext) Certify(height int64) (lite.Commit, error) {
// verifyProof perform response proof verification.
func (ctx CLIContext) verifyProof(_ string, resp abci.ResponseQuery) error {
if ctx.Certifier == nil {
if ctx.Verifier == nil {
return fmt.Errorf("missing valid certifier to verify data from distrusted node")
}
// the AppHash for height H is in header H+1
commit, err := ctx.Certify(resp.Height + 1)
commit, err := ctx.Verify(resp.Height + 1)
if err != nil {
return err
}

View File

@ -17,24 +17,25 @@ const (
DefaultGasLimit = 200000
GasFlagSimulate = "simulate"
FlagUseLedger = "ledger"
FlagChainID = "chain-id"
FlagNode = "node"
FlagHeight = "height"
FlagGas = "gas"
FlagGasAdjustment = "gas-adjustment"
FlagTrustNode = "trust-node"
FlagFrom = "from"
FlagName = "name"
FlagAccountNumber = "account-number"
FlagSequence = "sequence"
FlagMemo = "memo"
FlagFee = "fee"
FlagAsync = "async"
FlagJson = "json"
FlagPrintResponse = "print-response"
FlagDryRun = "dry-run"
FlagGenerateOnly = "generate-only"
FlagUseLedger = "ledger"
FlagChainID = "chain-id"
FlagNode = "node"
FlagHeight = "height"
FlagGas = "gas"
FlagGasAdjustment = "gas-adjustment"
FlagTrustNode = "trust-node"
FlagFrom = "from"
FlagName = "name"
FlagAccountNumber = "account-number"
FlagSequence = "sequence"
FlagMemo = "memo"
FlagFee = "fee"
FlagAsync = "async"
FlagJson = "json"
FlagPrintResponse = "print-response"
FlagDryRun = "dry-run"
FlagGenerateOnly = "generate-only"
FlagIndentResponse = "indent"
)
// LineBreak can be included in a command list to provide a blank line
@ -47,6 +48,7 @@ var (
// 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, false, "Trust connected full node (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")
@ -63,6 +65,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 or address 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")

View File

@ -43,7 +43,7 @@ func generateSelfSignedCert(host string) (certBytes []byte, priv *ecdsa.PrivateK
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
IsCA: true,
IsCA: true,
}
hosts := strings.Split(host, ",")
for _, h := range hosts {

View File

@ -42,7 +42,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()
// get seed
@ -125,7 +125,7 @@ func TestVersion(t *testing.T) {
t.SkipNow()
}
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{})
cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{})
defer cleanup()
// node info
@ -148,7 +148,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
@ -170,7 +170,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
@ -200,7 +200,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
@ -235,7 +235,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")
@ -303,7 +303,7 @@ func TestCoinSend(t *testing.T) {
func DisabledTestIBCTransfer(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()
acc := getAccount(t, port, addr)
@ -332,7 +332,7 @@ func DisabledTestIBCTransfer(t *testing.T) {
func TestCoinSendGenerateSignAndBroadcast(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()
acc := getAccount(t, port, addr)
@ -372,8 +372,9 @@ func TestCoinSendGenerateSignAndBroadcast(t *testing.T) {
// broadcast tx
broadcastPayload := struct {
Tx auth.StdTx `json:"tx"`
}{Tx: signedMsg}
Tx auth.StdTx `json:"tx"`
Return string `json:"return"`
}{Tx: signedMsg, Return: "block"}
json, err = cdc.MarshalJSON(broadcastPayload)
require.Nil(t, err)
res, body = Request(t, port, "POST", "/tx/broadcast", json)
@ -391,7 +392,7 @@ func TestCoinSendGenerateSignAndBroadcast(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
@ -450,7 +451,7 @@ func TestTxs(t *testing.T) {
func TestPoolParamsQuery(t *testing.T) {
_, password := "test", "1234567890"
addr, _ := CreateAddr(t, "test", password, GetKeyBase(t))
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
defer cleanup()
defaultParams := stake.DefaultParams()
@ -484,9 +485,11 @@ func TestPoolParamsQuery(t *testing.T) {
}
func TestValidatorsQuery(t *testing.T) {
cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{})
cleanup, valPubKeys, operAddrs, port := InitializeTestLCD(t, 1, []sdk.AccAddress{})
defer cleanup()
require.Equal(t, 1, len(pks))
require.Equal(t, 1, len(valPubKeys))
require.Equal(t, 1, len(operAddrs))
validators := getValidators(t, port)
require.Equal(t, len(validators), 1)
@ -494,35 +497,35 @@ func TestValidatorsQuery(t *testing.T) {
// make sure all the validators were found (order unknown because sorted by operator addr)
foundVal := false
if validators[0].ConsPubKey == pks[0] {
if validators[0].ConsPubKey == valPubKeys[0] {
foundVal = true
}
require.True(t, foundVal, "pk %v, operator %v", pks[0], validators[0].OperatorAddr)
require.True(t, foundVal, "pk %v, operator %v", operAddrs[0], validators[0].OperatorAddr)
}
func TestValidatorQuery(t *testing.T) {
cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{})
cleanup, valPubKeys, operAddrs, port := InitializeTestLCD(t, 1, []sdk.AccAddress{})
defer cleanup()
require.Equal(t, 1, len(pks))
require.Equal(t, 1, len(valPubKeys))
require.Equal(t, 1, len(operAddrs))
validator1Operator := sdk.ValAddress(pks[0].Address())
validator := getValidator(t, port, validator1Operator)
assert.Equal(t, validator.OperatorAddr, validator1Operator, "The returned validator does not hold the correct data")
validator := getValidator(t, port, operAddrs[0])
assert.Equal(t, validator.OperatorAddr, operAddrs[0], "The returned validator does not hold the correct data")
}
func TestBonding(t *testing.T) {
name, password, denom := "test", "1234567890", "steak"
addr, seed := CreateAddr(t, name, password, GetKeyBase(t))
cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
cleanup, _, operAddrs, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
defer cleanup()
amt := sdk.NewDec(60)
validator1Operator := sdk.ValAddress(pks[0].Address())
validator := getValidator(t, port, validator1Operator)
validator := getValidator(t, port, operAddrs[0])
// create bond TX
resultTx := doDelegate(t, port, seed, name, password, addr, validator1Operator, 60)
resultTx := doDelegate(t, port, seed, name, password, addr, operAddrs[0], 60)
tests.WaitForHeight(resultTx.Height+1, port)
require.Equal(t, uint32(0), resultTx.CheckTx.Code)
@ -534,7 +537,7 @@ func TestBonding(t *testing.T) {
require.Equal(t, int64(40), coins.AmountOf(denom).Int64())
// query validator
bond := getDelegation(t, port, addr, validator1Operator)
bond := getDelegation(t, port, addr, operAddrs[0])
require.Equal(t, amt, bond.Shares)
summary := getDelegationSummary(t, port, addr)
@ -545,17 +548,17 @@ func TestBonding(t *testing.T) {
bondedValidators := getDelegatorValidators(t, port, addr)
require.Len(t, bondedValidators, 1)
require.Equal(t, validator1Operator, bondedValidators[0].OperatorAddr)
require.Equal(t, operAddrs[0], bondedValidators[0].OperatorAddr)
require.Equal(t, validator.DelegatorShares.Add(amt).String(), bondedValidators[0].DelegatorShares.String())
bondedValidator := getDelegatorValidator(t, port, addr, validator1Operator)
require.Equal(t, validator1Operator, bondedValidator.OperatorAddr)
bondedValidator := getDelegatorValidator(t, port, addr, operAddrs[0])
require.Equal(t, operAddrs[0], bondedValidator.OperatorAddr)
//////////////////////
// testing unbonding
// create unbond TX
resultTx = doBeginUnbonding(t, port, seed, name, password, addr, validator1Operator, 60)
resultTx = doBeginUnbonding(t, port, seed, name, password, addr, operAddrs[0], 60)
tests.WaitForHeight(resultTx.Height+1, port)
require.Equal(t, uint32(0), resultTx.CheckTx.Code)
@ -566,7 +569,7 @@ func TestBonding(t *testing.T) {
coins = acc.GetCoins()
require.Equal(t, int64(40), coins.AmountOf("steak").Int64())
unbonding := getUndelegation(t, port, addr, validator1Operator)
unbonding := getUndelegation(t, port, addr, operAddrs[0])
require.Equal(t, "60", unbonding.Balance.Amount.String())
summary = getDelegationSummary(t, port, addr)
@ -599,7 +602,7 @@ func TestBonding(t *testing.T) {
func TestSubmitProposal(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()
// create SubmitProposal TX
@ -621,7 +624,7 @@ func TestSubmitProposal(t *testing.T) {
func TestDeposit(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()
// create SubmitProposal TX
@ -655,7 +658,7 @@ func TestDeposit(t *testing.T) {
func TestVote(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()
// create SubmitProposal TX
@ -693,12 +696,12 @@ func TestVote(t *testing.T) {
func TestUnjail(t *testing.T) {
_, password := "test", "1234567890"
addr, _ := CreateAddr(t, "test", password, GetKeyBase(t))
cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
cleanup, valPubKeys, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr})
defer cleanup()
// XXX: any less than this and it fails
tests.WaitForHeight(3, port)
pkString, _ := sdk.Bech32ifyConsPub(pks[0])
pkString, _ := sdk.Bech32ifyConsPub(valPubKeys[0])
signingInfo := getSigningInfo(t, port, pkString)
tests.WaitForHeight(4, port)
require.Equal(t, true, signingInfo.IndexOffset > 0)
@ -711,7 +714,7 @@ func TestProposalsQuery(t *testing.T) {
name2, password2 := "test2", "1234567890"
addr, seed := CreateAddr(t, "test", password1, GetKeyBase(t))
addr2, seed2 := CreateAddr(t, "test2", password2, GetKeyBase(t))
cleanup, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr, addr2})
cleanup, _, _, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr, addr2})
defer cleanup()
// Addr1 proposes (and deposits) proposals #1 and #2
@ -849,7 +852,7 @@ func doSendWithGas(t *testing.T, port, seed, name, password string, addr sdk.Acc
}
}`, coinbz, gasStr, gasAdjustmentStr, name, password, chainID, accnum, sequence))
res, body = Request(t, port, "POST", fmt.Sprintf("/accounts/%s/send%v", receiveAddr, queryStr), jsonStr)
res, body = Request(t, port, "POST", fmt.Sprintf("/bank/accounts/%s/transfers%v", receiveAddr, queryStr), jsonStr)
return
}

View File

@ -18,6 +18,7 @@ import (
slashing "github.com/cosmos/cosmos-sdk/x/slashing/client/rest"
stake "github.com/cosmos/cosmos-sdk/x/stake/client/rest"
"github.com/gorilla/mux"
"github.com/rakyll/statik/fs"
"github.com/spf13/cobra"
"github.com/spf13/viper"
cmn "github.com/tendermint/tendermint/libs/common"
@ -46,6 +47,7 @@ func ServeCommand(cdc *codec.Codec) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) (err error) {
listenAddr := viper.GetString(flagListenAddr)
handler := createHandler(cdc)
registerSwaggerUI(handler)
logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)).With("module", "rest-server")
maxOpen := viper.GetInt(flagMaxOpenConnections)
sslHosts := viper.GetString(flagSSLHosts)
@ -121,6 +123,7 @@ func ServeCommand(cdc *codec.Codec) *cobra.Command {
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, "Trust connected full node (don't verify proofs for responses)")
cmd.Flags().Bool(client.FlagIndentResponse, false, "Add indent to JSON response")
viper.BindPFlag(client.FlagTrustNode, cmd.Flags().Lookup(client.FlagTrustNode))
viper.BindPFlag(client.FlagChainID, cmd.Flags().Lookup(client.FlagChainID))
viper.BindPFlag(client.FlagNode, cmd.Flags().Lookup(client.FlagNode))
@ -128,7 +131,7 @@ func ServeCommand(cdc *codec.Codec) *cobra.Command {
return cmd
}
func createHandler(cdc *codec.Codec) http.Handler {
func createHandler(cdc *codec.Codec) *mux.Router {
r := mux.NewRouter()
kb, err := keys.GetKeyBase() //XXX
@ -136,7 +139,7 @@ func createHandler(cdc *codec.Codec) http.Handler {
panic(err)
}
cliCtx := context.NewCLIContext().WithCodec(cdc).WithLogger(os.Stdout)
cliCtx := context.NewCLIContext().WithCodec(cdc)
// TODO: make more functional? aka r = keys.RegisterRoutes(r)
r.HandleFunc("/version", CLIVersionRequestHandler).Methods("GET")
@ -154,6 +157,15 @@ func createHandler(cdc *codec.Codec) http.Handler {
return r
}
func registerSwaggerUI(r *mux.Router) {
statikFS, err := fs.New()
if err != nil {
panic(err)
}
staticServer := http.FileServer(statikFS)
r.PathPrefix("/swagger-ui/").Handler(http.StripPrefix("/swagger-ui/", staticServer))
}
func validateCertKeyFiles(certFile, keyFile string) error {
if keyFile == "" {
return errors.New("a key file is required")

View File

@ -0,0 +1,3 @@
package statik
//This just for fixing the error in importing empty github.com/cosmos/cosmos-sdk/client/lcd/statik

Binary file not shown.

After

Width:  |  Height:  |  Size: 445 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -0,0 +1,60 @@
<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="stylesheet" type="text/css" href="swagger-ui.css" >
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16" />
<style>
html
{
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after
{
box-sizing: inherit;
}
body
{
margin:0;
background: #fafafa;
}
</style>
</head>
<body>
<div id="swagger-ui"></div>
<script src="swagger-ui-bundle.js"> </script>
<script src="swagger-ui-standalone-preset.js"> </script>
<script>
window.onload = function() {
// Build a system
const ui = SwaggerUIBundle({
url: "./swagger.yaml",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
}
</script>
</body>
</html>

View File

@ -0,0 +1,67 @@
<!doctype html>
<html lang="en-US">
<body onload="run()">
</body>
</html>
<script>
'use strict';
function run () {
var oauth2 = window.opener.swaggerUIRedirectOauth2;
var sentState = oauth2.state;
var redirectUrl = oauth2.redirectUrl;
var isValid, qp, arr;
if (/code|token|error/.test(window.location.hash)) {
qp = window.location.hash.substring(1);
} else {
qp = location.search.substring(1);
}
arr = qp.split("&")
arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';})
qp = qp ? JSON.parse('{' + arr.join() + '}',
function (key, value) {
return key === "" ? value : decodeURIComponent(value)
}
) : {}
isValid = qp.state === sentState
if ((
oauth2.auth.schema.get("flow") === "accessCode"||
oauth2.auth.schema.get("flow") === "authorizationCode"
) && !oauth2.auth.code) {
if (!isValid) {
oauth2.errCb({
authId: oauth2.auth.name,
source: "auth",
level: "warning",
message: "Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server"
});
}
if (qp.code) {
delete oauth2.state;
oauth2.auth.code = qp.code;
oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
} else {
let oauthErrorMsg
if (qp.error) {
oauthErrorMsg = "["+qp.error+"]: " +
(qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
(qp.error_uri ? "More info: "+qp.error_uri : "");
}
oauth2.errCb({
authId: oauth2.auth.name,
source: "auth",
level: "error",
message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server"
});
}
} else {
oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl});
}
window.close();
}
</script>

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
{"version":3,"sources":[],"names":[],"mappings":"","file":"swagger-ui.css","sourceRoot":""}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,704 @@
---
swagger: '2.0'
info:
version: 1.1.0
title: Gaia-Lite (former LCD) to interface with Cosmos BaseServer via REST
description: Specification for Gaia-lite provided by `gaiacli rest-server`
tags:
- name: ICS0
description: Tendermint APIs, such as query blocks, transactions and validatorset
- name: ICS20
description: Create and sign a send tx
- name: version
description: Information about the app version
schemes:
- https
securityDefinitions:
kms:
type: basic
paths:
/version:
get:
summary: Version of Gaia-lite
tags:
- version
description: Get the version of gaia-lite running locally to compare against expected
responses:
200:
description: Plaintext version i.e. "v0.5.0"
/node_version:
get:
summary: Version of the connected node
tags:
- ICS0
description: Get the version of the SDK running on the connected node to compare against expected
responses:
200:
description: Plaintext version i.e. "v0.5.0"
/node_info:
get:
description: 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: gaia-2
channels:
type: string
listen_addr:
type: string
example: 192.168.56.1:26656
version:
description: Tendermint version
type: string
example: 0.15.0
other:
description: more information on versions
type: array
items:
type: string
/syncing:
get:
summary: Syncing state of node
tags:
- ICS0
description: Get if the node is currently syning with other nodes
responses:
200:
description: '"true" or "false"'
/blocks/latest:
get:
summary: Get the latest block
tags:
- ICS0
produces:
- application/json
responses:
200:
description: The latest block
schema:
$ref: "#/definitions/QueryBlock"
/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/QueryBlock"
404:
description: Block at height is not available
/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/Validator"
/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/Validator"
404:
description: Block at height not available
/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"
404:
description: Tx not available for provided hash
/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=`'cosmos1g9ahr6xhht5rmqven628nklxluzyv8z9jqjcmc'`"
required: true
- in: query
name: page
description: Pagination page
type: integer
- in: query
name: size
description: Pagination size
type: integer
responses:
200:
description: All Tx matching the provided tags
schema:
type: array
items:
$ref: "#/definitions/TxQuery"
404:
description: Pagination is out of bounds
post:
tags:
- ICS0
summary: broadcast Tx
description: broadcast tx with tendermint rpc
consumes:
- application/json
produces:
- application/json
parameters:
- in: body
name: txBroadcast
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:
$ref: "#/definitions/TendertmintTx"
responses:
200:
description: Broadcast tx result
schema:
$ref: "#/definitions/BroadcastTxCommitResult"
/tx/sign:
post:
tags:
- ICS20
summary: Sign a Tx
description: Sign a Tx providing locally stored account and according password
consumes:
- application/json
produces:
- application/json
parameters:
- in: body
name: sendToken
description: sign tx
required: true
schema:
$ref: "#/definitions/TxSign"
responses:
200:
description: The signed Tx
schema:
$ref: "#/definitions/StdTx"
401:
description: Account name and/or password where wrong
/tx/broadcast:
post:
tags:
- ICS20
summary: Send a signed Tx
description: Send a signed Tx to a Gaiad full node
consumes:
- application/json
produces:
- application/json
parameters:
- in: body
name: txBroadcast
description: broadcast tx
required: true
schema:
$ref: "#/definitions/TxBroadcast"
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
/bank/balances/{address}:
get:
summary: Get the account balances
tags:
- ICS20
produces:
- application/json
parameters:
- in: path
name: address
description: Account address in bech32 format
required: true
type: string
responses:
200:
description: Account balances
schema:
type: array
items:
$ref: "#/definitions/Coin"
204:
description: There is no data for the requested account. This is not a 404 as the account might exist, just does not hold data.
/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: 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_req:
$ref: "#/definitions/BaseReq"
amount:
type: array
items:
$ref: "#/definitions/Coin"
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
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
Fee:
type: object
properties:
gas:
type: string
amount:
type: array
items:
$ref: "#/definitions/Coin"
Msg:
type: string
Address:
type: string
description: bech32 encoded addres
example: cosmoszgnkwr7eyyv643dllwfpdwensmgdtz89yu73zq
ValidatorAddress:
type: string
description: bech32 encoded addres
example: cosmosvaloper:zgnkwr7eyyv643dllwfpdwensmgdtz89yu73zq
PubKey:
type: object
properties:
type:
type: string
example: "tendermint/PubKeySecp256k1"
value:
type: string
example: "Avz04VhtKJh8ACCVzlI8aTosGy0ikFXKIVHQ3jKMrosH"
ValidatorPubKey:
type: string
description: bech32 encoded public key
example: cosmosvalconspub:zgnkwr7eyyv643dllwfpdwensmgdtz89yu73zq
Coin:
type: object
properties:
denom:
type: string
example: steak
amount:
type: string
example: "50"
Hash:
type: string
example: EE5F3404034C524501629B56E0DDC38FAD651F04
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"
TxQuery:
type: object
properties:
hash:
type: string
height:
type: number
tx:
$ref: "#/definitions/StdTx"
result:
$ref: "#/definitions/Result"
TendertmintTx:
type: object
properties:
tx:
type: string
return:
type: string
example: block
TxBroadcast:
type: object
properties:
tx:
$ref: "#/definitions/StdTx"
TxSign:
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
StdTx:
type: object
properties:
msg:
type: array
items:
$ref: "#/definitions/Msg"
fee:
$ref: "#/definitions/Fee"
memo:
type: string
signature:
type: object
properties:
signature:
type: string
example: MEUCIQD02fsDPra8MtbRsyB1w7bqTM55Wu138zQbFcWx4+CFyAIge5WNPfKIuvzBZ69MyqHsqD8S1IwiEp+iUb6VSdtlpgY=
pub_key:
$ref: "#/definitions/PubKey"
account_number:
type: string
example: "0"
sequence:
type: string
example: "0"
Account:
type: object
properties:
name:
type: string
example: Main Account
address:
$ref: "#/definitions/Address"
pub_key:
$ref: "#/definitions/PubKey"
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: gaia-2
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"
consensus_hash:
$ref: "#/definitions/Hash"
app_hash:
$ref: "#/definitions/Hash"
last_results_hash:
$ref: "#/definitions/Hash"
evidence_hash:
$ref: "#/definitions/Hash"
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=='
BlockMeta:
type: object
properties:
header:
$ref: "#/definitions/BlockHeader"
block_id:
$ref: "#/definitions/BlockID"
QueryBlock:
type: object
properties:
block_meta:
$ref: "#/definitions/BlockMeta"
block:
$ref: "#/definitions/Block"
BaseReq:
type: object
properties:
name:
type: string
password:
type: string
chain_id:
type: string
account_number:
type: string
example: "0"
sequence:
type: string
example: "0"
gas:
type: string
example: "200000"
gas_adjustment:
type: string
example: "1.2"
Validator:
type: object
properties:
address:
$ref: '#/definitions/ValidatorAddress'
pub_key:
$ref: "#/definitions/ValidatorPubKey"
power:
type: number
example: 1000
accum:
type: number
example: 1000

View File

@ -33,6 +33,7 @@ import (
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"
@ -114,7 +115,14 @@ func CreateAddr(t *testing.T, name, password string, kb crkeys.Keybase) (sdk.Acc
// 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
@ -135,40 +143,34 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress
genDoc, err := tmtypes.GenesisDocFromFile(genesisFile)
require.NoError(t, err)
if nValidators < 1 {
panic("InitializeTestLCD must use at least one validator")
// append initial (proposing) validator
genDoc.Validators[0] = tmtypes.GenesisValidator{
PubKey: privVal.GetPubKey(),
Power: 999999, // create enough power to enable 2/3 voting power
Name: "validator-1",
}
//// add the priv validator (actual node) to genesis validators
//genDoc.Validators = append(genDoc.Validators,
//tmtypes.GenesisValidator{
//PubKey: privVal.PubKey,
//Power: 1,
//Name: "val",
//},
//)
// then add some randoms
// append any additional (non-proposing) validators
for i := 1; i < nValidators; i++ {
genDoc.Validators = append(genDoc.Validators,
tmtypes.GenesisValidator{
PubKey: ed25519.GenPrivKey().PubKey(),
Power: 1,
Name: "val",
Name: fmt.Sprintf("validator-%d", i+1),
},
)
}
var validatorsPKs []crypto.PubKey
// NOTE: It's bad practice to reuse public key address for the operator
// address but doing in the test for simplicity.
var appGenTxs []json.RawMessage
for _, gdValidator := range genDoc.Validators {
pk := gdValidator.PubKey
validatorsPKs = append(validatorsPKs, pk)
appGenTx, _, _, err := gapp.GaiaAppGenTxNF(cdc, pk, sdk.AccAddress(pk.Address()), "test_val1")
for _, gdValidator := range genDoc.Validators {
operAddr := ed25519.GenPrivKey().PubKey().Address()
pk := gdValidator.PubKey
valConsPubKeys = append(valConsPubKeys, pk)
valOperAddrs = append(valOperAddrs, sdk.ValAddress(operAddr))
appGenTx, _, _, err := gapp.GaiaAppGenTxNF(cdc, pk, sdk.AccAddress(operAddr), gdValidator.Name)
require.NoError(t, err)
appGenTxs = append(appGenTxs, appGenTx)
@ -196,7 +198,8 @@ 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)
viper.Set(client.FlagTrustNode, false)
// 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)
@ -211,14 +214,14 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress
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
@ -232,9 +235,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,

View File

@ -8,6 +8,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/utils"
"github.com/gorilla/mux"
"github.com/spf13/cobra"
"github.com/spf13/viper"
@ -46,7 +47,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
}
@ -62,13 +63,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.MarshalJSON(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
@ -133,7 +131,7 @@ func BlockRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
w.Write([]byte(err.Error()))
return
}
w.Write(output)
utils.PostProcessResponse(w, cdc, output, cliCtx.Indent)
}
}
@ -152,6 +150,6 @@ func LatestBlockRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
w.Write([]byte(err.Error()))
return
}
w.Write(output)
utils.PostProcessResponse(w, cdc, output, cliCtx.Indent)
}
}

View File

@ -9,8 +9,9 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
"github.com/cosmos/cosmos-sdk/client/utils"
"github.com/spf13/viper"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
)
func statusCommand() *cobra.Command {
@ -22,6 +23,7 @@ func statusCommand() *cobra.Command {
cmd.Flags().StringP(client.FlagNode, "n", "tcp://localhost:26657", "Node to connect to")
viper.BindPFlag(client.FlagNode, cmd.Flags().Lookup(client.FlagNode))
cmd.Flags().Bool(client.FlagIndentResponse, false, "Add indent to JSON response")
return cmd
}
@ -38,13 +40,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
}
@ -66,14 +75,7 @@ func NodeInfoRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
}
nodeInfo := status.NodeInfo
output, err := cdc.MarshalJSON(nodeInfo)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
return
}
w.Write(output)
utils.PostProcessResponse(w, cdc, nodeInfo, cliCtx.Indent)
}
}

View File

@ -12,8 +12,9 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context"
sdk "github.com/cosmos/cosmos-sdk/types"
tmtypes "github.com/tendermint/tendermint/types"
"github.com/spf13/viper"
tmtypes "github.com/tendermint/tendermint/types"
"github.com/cosmos/cosmos-sdk/client/utils"
)
// TODO these next two functions feel kinda hacky based on their placement
@ -76,12 +77,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")
}
}
@ -98,12 +99,11 @@ func getValidators(cliCtx context.CLIContext, height *int64) ([]byte, error) {
}
}
output, err := cdc.MarshalJSON(outputValidatorsRes)
if err != nil {
return nil, err
if cliCtx.Indent {
return cdc.MarshalJSONIndent(outputValidatorsRes, "", " ")
}
return cdc.MarshalJSON(outputValidatorsRes)
return output, nil
}
// CMD
@ -158,8 +158,7 @@ func ValidatorSetRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
w.Write([]byte(err.Error()))
return
}
w.Write(output)
utils.PostProcessResponse(w, cdc, output, cliCtx.Indent)
}
}
@ -179,7 +178,6 @@ func LatestValidatorSetRequestHandlerFn(cliCtx context.CLIContext) http.HandlerF
w.Write([]byte(err.Error()))
return
}
w.Write(output)
utils.PostProcessResponse(w, cdc, output, cliCtx.Indent)
}
}

View File

@ -1,37 +1,60 @@
package tx
import (
"encoding/json"
"net/http"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/utils"
"github.com/cosmos/cosmos-sdk/codec"
"io/ioutil"
)
// Tx Broadcast Body
type BroadcastTxBody struct {
TxBytes string `json:"tx"`
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"`
}
// BroadcastTx REST Handler
func BroadcastTxRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
// 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 BroadcastTxBody
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&m)
var m BroadcastBody
body, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(400)
w.Write([]byte(err.Error()))
utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
res, err := cliCtx.BroadcastTxAndAwaitCommit([]byte(m.TxBytes))
err = cdc.UnmarshalJSON(body, &m)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
w.Write([]byte(string(res.Height)))
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)
}
}

View File

@ -3,8 +3,8 @@ package tx
import (
"encoding/hex"
"fmt"
"net/http"
"github.com/tendermint/tendermint/libs/common"
"net/http"
"github.com/gorilla/mux"
"github.com/spf13/cobra"
@ -13,6 +13,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/utils"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
@ -78,12 +79,15 @@ func queryTx(cdc *codec.Codec, cliCtx context.CLIContext, hashHexStr string) ([]
return nil, err
}
return codec.MarshalJSONIndent(cdc, 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
}
@ -142,7 +146,6 @@ func QueryTxRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.H
w.Write([]byte(err.Error()))
return
}
w.Write(output)
utils.PostProcessResponse(w, cdc, output, cliCtx.Indent)
}
}

View File

@ -20,6 +20,5 @@ func AddCommands(cmd *cobra.Command, cdc *codec.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/sign", SignTxRequstHandler).Methods("POST")
// r.HandleFunc("/txs/broadcast", BroadcastTxRequestHandler).Methods("POST")
r.HandleFunc("/txs", BroadcastTxRequest(cliCtx, cdc)).Methods("POST")
}

View File

@ -15,6 +15,7 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/cosmos/cosmos-sdk/client/utils"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
)
@ -51,7 +52,13 @@ $ gaiacli tendermint txs --tag test1,test2 --any
return err
}
output, err := cdc.MarshalJSON(txs)
var output []byte
if cliCtx.Indent {
output, err = cdc.MarshalJSONIndent(txs, "", " ")
} else {
output, err = cdc.MarshalJSON(txs)
}
if err != nil {
return err
}
@ -174,13 +181,6 @@ func SearchTxRequestHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.
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)
}
}

View File

@ -1,5 +1,6 @@
package utils
import "C"
import (
"fmt"
"io/ioutil"
@ -8,11 +9,11 @@ import (
"strconv"
"strings"
client "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
auth "github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/auth"
authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder"
)
@ -240,11 +241,27 @@ func CompleteAndBroadcastTxREST(w http.ResponseWriter, r *http.Request, cliCtx c
return
}
output, err := codec.MarshalJSONIndent(cdc, res)
if err != nil {
WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
PostProcessResponse(w, cdc, res, cliCtx.Indent)
}
// 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)
}

View File

@ -31,7 +31,7 @@ func setGenesis(gapp *GaiaApp, accs ...*auth.BaseAccount) error {
}
// Initialize the chain
vals := []abci.Validator{}
vals := []abci.ValidatorUpdate{}
gapp.InitChain(abci.RequestInitChain{Validators: vals, AppStateBytes: stateBytes})
gapp.Commit()

View File

@ -31,5 +31,5 @@ func ExampleTxSendSize() {
fmt.Println(len(cdc.MustMarshalBinaryBare([]sdk.Msg{msg1})))
fmt.Println(len(cdc.MustMarshalBinaryBare(tx)))
// output: 80
// 173
// 167
}

View File

@ -90,7 +90,7 @@ func appStateFn(r *rand.Rand, accs []simulation.Account) json.RawMessage {
func testAndRunTxs(app *GaiaApp) []simulation.WeightedOperation {
return []simulation.WeightedOperation{
{100, banksim.SimulateSingleInputMsgSend(app.accountMapper)},
{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)},

View File

@ -7,8 +7,8 @@ import (
"fmt"
"io/ioutil"
"os"
"testing"
"path"
"testing"
"github.com/stretchr/testify/require"

View File

@ -1,7 +1,11 @@
package main
import (
"os"
"path"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/tendermint/tendermint/libs/cli"
@ -10,7 +14,9 @@ import (
"github.com/cosmos/cosmos-sdk/client/lcd"
"github.com/cosmos/cosmos-sdk/client/rpc"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/cmd/gaia/app"
"github.com/cosmos/cosmos-sdk/version"
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli"
distrcmd "github.com/cosmos/cosmos-sdk/x/distribution/client/cli"
@ -18,11 +24,7 @@ import (
slashingcmd "github.com/cosmos/cosmos-sdk/x/slashing/client/cli"
stakecmd "github.com/cosmos/cosmos-sdk/x/stake/client/cli"
"os"
"path"
"github.com/cosmos/cosmos-sdk/cmd/gaia/app"
"github.com/spf13/viper"
_ "github.com/cosmos/cosmos-sdk/client/lcd/statik"
)
const (

View File

@ -55,6 +55,7 @@ func ExamplePrintRegisteredTypes() {
//| PrivKeyLedgerSecp256k1 | tendermint/PrivKeyLedgerSecp256k1 | 0x10CAB393 | variable | |
//| PubKeyEd25519 | tendermint/PubKeyEd25519 | 0x1624DE64 | 0x20 | |
//| PubKeySecp256k1 | tendermint/PubKeySecp256k1 | 0xEB5AE987 | 0x21 | |
//| PubKeyMultisigThreshold | tendermint/PubKeyMultisigThreshold | 0x22C1F7E2 | variable | |
//| PrivKeyEd25519 | tendermint/PrivKeyEd25519 | 0xA3288910 | 0x40 | |
//| PrivKeySecp256k1 | tendermint/PrivKeySecp256k1 | 0xE1B0F79B | 0x20 | |
}

View File

@ -9,12 +9,12 @@ import (
"github.com/cosmos/cosmos-sdk/crypto"
"github.com/cosmos/cosmos-sdk/crypto/keys/bip39"
"github.com/cosmos/cosmos-sdk/crypto/keys/hd"
"github.com/cosmos/cosmos-sdk/types"
"github.com/pkg/errors"
tmcrypto "github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/encoding/amino"
"github.com/tendermint/tendermint/crypto/secp256k1"
dbm "github.com/tendermint/tendermint/libs/db"
"github.com/cosmos/cosmos-sdk/types"
)
var _ Keybase = dbKeybase{}

View File

@ -10,8 +10,8 @@ import (
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519"
dbm "github.com/tendermint/tendermint/libs/db"
"github.com/cosmos/cosmos-sdk/types"
dbm "github.com/tendermint/tendermint/libs/db"
)
func init() {
@ -403,4 +403,4 @@ func ExampleNew() {
func accAddr(info Info) types.AccAddress {
return (types.AccAddress)(info.GetPubKey().Address())
}
}

View File

@ -15,7 +15,8 @@ module.exports = {
collapsable: false,
children: [
"/introduction/cosmos-hub",
"/introduction/tendermint",
"/introduction/tendermint-cosmos",
"/introduction/tendermint"
]
},
{
@ -54,6 +55,18 @@ module.exports = {
// "/specs/icts",
// ]
// },
{
title: "SDK by Examples - Simple Governance",
collapsable: false,
children: [
["/sdk/sdk-by-examples/simple-governance/intro", "Intro"],
"/sdk/sdk-by-examples/simple-governance/setup-and-design",
"/sdk/sdk-by-examples/simple-governance/app-init",
"/sdk/sdk-by-examples/simple-governance/simple-gov-module",
"/sdk/sdk-by-examples/simple-governance/bridging-it-all",
"/sdk/sdk-by-examples/simple-governance/running-the-application"
]
},
{
title: "Lotion JS",
collapsable: false,
@ -71,6 +84,13 @@ module.exports = {
"/validators/validator-faq"
]
},
{
title: "Clients",
collapsable: false,
children: [
["/clients/service-providers", "Service Providers"]
]
},
{
title: "Resources",
collapsable: false,

View File

@ -10,6 +10,11 @@ built from the files in this (`/docs`) directory for
and [develop](https://github.com/cosmos/cosmos-sdk/tree/develop/docs),
respectively.
Besides, gaia-lite API docs are also provided by gaia-lite. The default API docs page is:
```
https://localhost:1317/swagger-ui/
```
## How It Works
There is a Jenkins job listening for changes in the `/docs` directory, on both
@ -93,3 +98,18 @@ then navigate to localhost:8080 in your browser.
Because the build processes are identical (as is the information contained herein), this file should be kept in sync as
much as possible with its [counterpart in the Tendermint Core repo](https://github.com/tendermint/tendermint/blob/develop/docs/DOCS_README.md).
## Update and Build the RPC docs
1. Execute the following command at the root directory to install the swagger-ui generate tool.
```
make get_tools
```
2. Edit API docs
1. Directly Edit API docs manually: `client/lcd/swagger-ui/swagger.yaml`.
2. Edit API docs within [SwaggerHub](https://app.swaggerhub.com). Please refer to this [document](https://app.swaggerhub.com/help/index) for how to use the about website to edit API docs.
3. Download `swagger.yaml` and replace the old `swagger.yaml` under fold `client/lcd/swagger-ui`.
4. Compile gaiacli
```
make install
```

View File

@ -1,75 +1,44 @@
# High priority
## Fees
- Collection
- Simple flat fee set in-config by validators & full nodes - ref [#1921](https://github.com/cosmos/cosmos-sdk/issues/1921)
- @sunnya97 working on implementation
- _*BLOCKER:*_ Blocked on [tendermint/tendermint#2275](https://github.com/tendermint/tendermint/issues/2275) @ValarDragon
- Distribution
- "Piggy bank" fee distribution - ref [#1944](https://github.com/cosmos/cosmos-sdk/pull/1944) (spec)
- @rigelrozanski working on implementation
- EST TIMELINE:
- Work on fees should be completed in the `v0.25.0` release
# Post-0.25/GoS Pre-Release
## Staking/Slashing/Stability
- Unbonding state for validators (WIP) [#2163](https://github.com/cosmos/cosmos-sdk/pull/2163) @rigelrozanski
- Needs :eyes: from @chris
- Should be in `v0.25.0` release
- Slashing period PR - ref [#2122](https://github.com/cosmos/cosmos-sdk/pull/2122)
- Needs :eyes: from @cwgoes and @jaekwon
- Should be in `v0.25.0` release
- Other slashing issues blocking for launch - [#1256](https://github.com/cosmos/cosmos-sdk/issues/1256)
- Update staking/slashing for NextValSet change
- @cwgoes to start next
- Miscellaneous minor staking issues
- [List here](https://github.com/cosmos/cosmos-sdk/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+label%3Astaking+label%3Aprelaunch)
- Need to figure out scope of work here to estimate time
- @rigelrozanski to start next
## Vesting
- Single `VestingAccount` allowing delegation/voting but no withdrawals
- Ref [#1875](https://github.com/cosmos/cosmos-sdk/pull/1875) (spec)
- @AdityaSripal working on this.
- Should be in `v0.25.0` release
- Consider "tombstone" / "prison" - double-sign and you can never validate again - https://github.com/cosmos/cosmos-sdk/issues/2363
## Multisig
- Already implemented on TM side, need simple CLI interface
- @alessio working on the SDK side of things here
- Need to schedule some time with @alessio, @ebuchman and @ValarDragon this week to finalize feature set/implementation plan
- Need to test changes in https://github.com/cosmos/cosmos-sdk/pull/2165
- Spam prevention - https://github.com/cosmos/cosmos-sdk/issues/2019
## ABCI Changes
- Need to update for new ABCI changes - error string, tags are list of lists, proposer in header (Tendermint 0.24?)
- @cwgoes has done some work here. Should be on `develop` in tendermint w/in next week.
- Include in tendermint `v0.24.0` release?
- Need to update for new ABCI changes when/if they land - error string, tags are list of lists
- Need to verify correct proposer reward semantics
- CheckEvidence/DeliverEvidence, CheckTx/DeliverTx ordering semantics
## Gas
- Simple transaction benchmarking work by @jlandrews to inform additional work here
- Integrate @alessio's simulation work into CLI and LCD
- Sanity Checks
- Charge for transaction size
- Decide what "one gas" corresponds to (standard hardware benchmarks?)
- More benchmarking
- Consider charging based on maximum depth of IAVL tree iteration
- Test out gas estimation in CLI and LCD and ensure the UX works
## LCD
- Bianje working on implementation ([#2147](https://github.com/cosmos/cosmos-sdk/pull/2147))
- ICS 0,ICS 1, ICS 20 and ICS 21 implemented in this PR :point_up:
- @fedekunze, @jackzampolin and @alexanderbez to review
- Bianje working on implementation of ICS standards
- Additional PR incoming for ICS 22 and ICS 23
- Include [#382](https://github.com/cosmos/cosmos-sdk/issues/382)
- Decide what ought to be ICS-standardized and what ought not to
# Lower priority
## Governance v2
- Simple software upgrade proposals
- Implementation described in [#1079](https://github.com/cosmos/cosmos-sdk/issues/1079)
- Agree upon a block height to switch to new version
- Another Governance proposal from @jaekwon [#2116](https://github.com/cosmos/cosmos-sdk/pull/2116)
- Circuit breaker
- Circuit breaker - https://github.com/cosmos/cosmos-sdk/issues/926
- Parameter change proposals (roughly the same implementation as circuit breaker)
## Documentation

View File

@ -8,6 +8,12 @@ The first blockchain in the Cosmos Network is the Cosmos Hub, whose native token
Cosmos can interoperate with multiple other applications and cryptocurrencies. By creating a new zone, you can plug any blockchain system into the Cosmos hub and pass tokens back and forth between those zones, without the need for an intermediary.
## Quick Start
- [Getting started with the SDK](./sdk/core/intro.md)
- [SDK Examples](../examples)
- [Join the testnet](./getting-started/join-testnet.md#run-a-full-node)
## Edit the Documentation
See [this file](./DOCS_README.md) for details of the build process and

View File

@ -1,936 +0,0 @@
swagger: '2.0'
info:
version: '1.1.0'
title: Gaia-Lite (former LCD) to interface with Cosmos BaseServer via REST
description: Specification for Gaia-lite provided by `gaiacli rest-server`
tags:
- name: keys
description: Key management to add or view local private keys
- name: send
description: Create and sign a send tx
- name: stake
description: Stake module API for staking and validation
- name: account
description: Query account balance
- name: query
description: Information about blocks and txs
- name: validator set
description: Check the state of the validator set
- name: node
description: Information of the connected node
- name: version
description: Information about the app version
securityDefinitions:
kms:
type: basic
paths:
/version:
get:
summary: Version of Gaia-lite
tags:
- version
description: Get the version of gaia-lite running locally to compare against expected
responses:
200:
description: Plaintext version i.e. "v0.5.0"
/node_version:
get:
summary: Version of the connected node
tags:
- node
description: Get the version of the SDK running on the connected node to compare against expected
responses:
200:
description: Plaintext version i.e. "v0.5.0"
/node_info:
get:
description: Information about the connected node
summary: The properties of the connected node
tags:
- node
produces:
- application/json
responses:
200:
description: Node status
schema:
type: object
properties:
pub_key:
$ref: '#/definitions/PubKey'
moniker:
type: string
example: 159.89.198.221
network:
type: string
example: gaia-2
remote_addr:
type: string
listen_addr:
type: string
example: 192.168.56.1:26656
version:
description: Tendermint version
type: string
example: 0.15.0
other:
description: more information on versions
type: array
items:
type: string
/syncing:
get:
summary: Syncing state of node
tags:
- node
description: Get if the node is currently syning with other nodes
responses:
200:
description: '"true" or "false"'
/keys:
get:
summary: List of accounts stored locally
tags:
- keys
produces:
- application/json
responses:
200:
description: Array of accounts
schema:
type: array
items:
$ref: '#/definitions/Account'
post:
summary: Create a new account locally
tags:
- keys
consumes:
- 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 address of the account created
/keys/seed:
get:
summary: Create a new seed to create a new account with
tags:
- keys
produces:
- application/json
responses:
200:
description: 16 word Seed
schema:
type: string
/keys/{name}:
parameters:
- in: path
name: name
description: Account name
required: true
type: string
get:
summary: Get a certain locally stored account
tags:
- keys
produces:
- application/json
responses:
200:
description: Locally stored account
schema:
$ref: "#/definitions/Account"
404:
description: Account is not available
put:
summary: Update the password for this account in the KMS
tags:
- keys
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: Password is wrong
404:
description: Account is not available
delete:
summary: Remove an account
tags:
- keys
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: Password is wrong
404:
description: Account is not available
# /accounts/send:
# post:
# summary: Send coins (build -> sign -> send)
# security:
# - sign: []
# requestBody:
# content:
# application/json:
# schema:
# type: object
# properties:
# fees:
# $ref: "#/definitions/Coins"
# outputs:
# type: array
# items:
# type: object
# properties:
# pub_key:
# $ref: "#/definitions/PubKey"
# amount:
# type: array
# items:
# $ref: "#/definitions/Coins"
# responses:
# 202:
# description: Tx was send and will probably be added to the next block
# 400:
# description: The Tx was malformated
/accounts/{address}:
parameters:
- in: path
name: address
description: Account address in bech32 format
required: true
type: string
get:
summary: Get the account balances
tags:
- account
produces:
- application/json
responses:
200:
description: Account balances
schema:
$ref: "#/definitions/Balance"
204:
description: There is no data for the requested account. This is not a 404 as the account might exist, just does not hold data.
/accounts/{address}/send:
parameters:
- in: path
name: address
description: Account address in bech32 format
required: true
type: string
post:
summary: Send coins (build -> sign -> send)
tags:
- send
security:
- kms: []
consumes:
- application/json
parameters:
- in: body
name: account
description: The password of the account to remove from the KMS
schema:
type: object
properties:
name:
type: string
password:
type: string
amount:
type: array
items:
$ref: "#/definitions/Coins"
chain_id:
type: string
squence:
type: number
responses:
202:
description: Tx was send and will probably be added to the next block
400:
description: The Tx was malformated
/blocks/latest:
get:
summary: Get the latest block
tags:
- query
produces:
- application/json
responses:
200:
description: The latest block
schema:
$ref: "#/definitions/Block"
/blocks/{height}:
parameters:
- in: path
name: height
description: Block height
required: true
type: number
get:
summary: Get a block at a certain height
tags:
- query
produces:
- application/json
responses:
200:
description: The block at a specific height
schema:
$ref: "#/definitions/Block"
404:
description: Block at height is not available
/validatorsets/latest:
get:
summary: Get the latest validator set
tags:
- validator set
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/Validator"
/validatorsets/{height}:
parameters:
- in: path
name: height
description: Block height
required: true
type: number
get:
summary: Get a validator set a certain height
tags:
- validator set
produces:
- application/json
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/Validator"
404:
description: Block at height not available
# /txs:
# parameters:
# - in: query
# name: tag
# schema:
# type: string
# example: "coin.sender=EE5F3404034C524501629B56E0DDC38FAD651F04"
# required: true
# - in: query
# name: page
# description: Pagination page
# schema:
# type: number
# default: 0
# - in: query
# name: size
# description: Pagination size
# schema:
# type: number
# default: 50
# get:
# summary: Query Tx
# responses:
# 200:
# description: All Tx matching the provided tags
# content:
# application/json:
# schema:
# type: array
# items:
# $ref: "#/definitions/Tx"
# 404:
# description: Pagination is out of bounds
# /txs/sign:
# post:
# summary: Sign a Tx
# description: Sign a Tx providing locally stored account and according password
# security:
# - sign: []
# requestBody:
# content:
# application/json:
# schema:
# $ref: "#/definitions/TxBuild"
# responses:
# 200:
# description: The signed Tx
# content:
# application/json:
# schema:
# $ref: "#/definitions/TxSigned"
# 401:
# description: Account name and/or password where wrong
# /txs/broadcast:
# post:
# summary: Send signed Tx
# requestBody:
# content:
# application/json:
# schema:
# $ref: "#/definitions/TxSigned"
# responses:
# 202:
# description: Tx was send and will probably be added to the next block
# 400:
# description: The Tx was malformated
/txs/{hash}:
parameters:
- in: path
name: hash
description: Tx hash
required: true
type: string
get:
summary: Get a Tx by hash
tags:
- query
produces:
- application/json
responses:
200:
description: Tx with the provided hash
schema:
$ref: "#/definitions/Tx"
404:
description: Tx not available for provided hash
# ================== Staking Module # ==================
# TODO create D
/stake/delegators/{delegatorAddr}:
parameters:
- in: path
name: delegatorAddr
description: AccAddress of Delegator
required: true
type: string
get:
summary: Get all delegations (delegation, undelegation) from a delegator
tags:
- stake
produces:
- application/json
responses:
200:
description: OK
404:
description: Not Found
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:
- stake
produces:
- application/json
responses:
200:
description: OK
404:
description: Not Found
/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:
- stake
produces:
- application/json
responses:
200:
description: OK
404:
description: Not Found
/stake/delegators/{delegatorAddr}/txs:
parameters:
- in: path
name: delegatorAddr
description: AccAddress of Delegator
required: true
type: string
get:
summary: Get all staking txs (i.e msgs) from a delegator
tags:
- stake
produces:
- application/json
responses:
200:
description: OK
schema:
$ref: "#/definitions/Tx"
404:
description: Not Found
500:
description: Internal Server Error
/stake/delegators/{delegatorAddr}/delegations:
parameters:
- in: path
name: delegatorAddr
description: Bech32 AccAddress of Delegator
required: true
type: string
post:
summary: Submit delegation
parameters:
- in: body
name: delegation
description: The password of the account to remove from the KMS
schema:
type: object
properties:
name:
type: string
password:
type: string
account_number:
type: number
delegations:
type: array
items:
type: string
begin_unbondings:
type: array
items:
type: string
complete_unbondings:
type: array
items:
type: string
begin_redelegates:
type: array
items:
type: string
complete_redelegates:
type: array
items:
type: string
chain_id:
type: string
gas:
type: number
sequence:
type: number
tags:
- stake
produces:
- application/json
responses:
200:
description: OK
schema:
$ref: "#/definitions/Tx"
404:
description: Not Found
500:
description: Internal Server Error
/stake/delegators/{delegatorAddr}/delegations/{validatorAddr}:
parameters:
- in: path
name: delegatorAddr
description: Bech32 AccAddress of Delegator
required: true
type: string
- in: path
name: validatorAddr
description: Bech32 ValAddress of Delegator
required: true
type: string
get:
summary: Query the current delegation status between a delegator and a validator
tags:
- stake
produces:
- application/json
responses:
200:
description: OK
404:
description: Not Found
/stake/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}:
parameters:
- in: path
name: delegatorAddr
description: Bech32 AccAddress of Delegator
required: true
type: string
- in: path
name: validatorAddr
description: Bech32 ValAddress of Delegator
required: true
type: string
get:
summary: Query all unbonding delegations between a delegator and a validator
tags:
- stake
produces:
- application/json
responses:
200:
description: OK
404:
description: Not Found
500:
description: Internal Server Error
/stake/validators:
get:
summary: Get all validator candidates
tags:
- stake
produces:
- application/json
responses:
200:
description: OK
500:
description: Internal Server Error
/stake/validators/{validatorAddr}:
parameters:
- in: path
name: validatorAddr
description: Bech32 ValAddress of Delegator
required: true
type: string
get:
summary: Query the information from a single validator
tags:
- stake
produces:
- application/json
responses:
200:
description: OK
404:
description: Not Found
500:
description: Internal Server Error
# TODO Add staking definitions
definitions:
Address:
type: string
description: bech32 encoded addres
example: cosmos:zgnkwr7eyyv643dllwfpdwensmgdtz89yu73zq
ValidatorAddress:
type: string
description: bech32 encoded addres
example: cosmosvaloper:zgnkwr7eyyv643dllwfpdwensmgdtz89yu73zq
PubKey:
type: string
description: bech32 encoded public key
example: cosmospub:zgnkwr7eyyv643dllwfpdwensmgdtz89yu73zq
ValidatorPubKey:
type: string
description: bech32 encoded public key
example: cosmosvalconspub:zgnkwr7eyyv643dllwfpdwensmgdtz89yu73zq
Coins:
type: object
properties:
denom:
type: string
example: steak
amount:
type: number
example: 50
Hash:
type: string
example: EE5F3404034C524501629B56E0DDC38FAD651F04
Tx:
type: object
properties:
type:
type: string
enum:
- stake/delegate
data:
type: object
TxChain:
type: object
properties:
type:
type: string
default: chain/tx
data:
type: object
properties:
chain_id:
type: string
example: gaia-2
expires_at:
type: number
example: 0
tx:
type: object
properties:
type:
type: string
default: nonce
data:
type: object
properties:
sequence:
type: number
example: 0
signers:
type: array
items:
type: object
properties:
chain:
type: string
example: ''
app:
type: string
default: sigs
addr:
$ref: "#/definitions/Address"
tx:
$ref: "#/definitions/Tx"
TxBuild:
type: object
properties:
type:
type: string
default: sigs/one
data:
type: object
properties:
tx:
$ref: "#/definitions/Tx"
signature:
type: object
properties:
Sig:
type: string
default: ''
Pubkey:
type: string
default: ''
TxSigned:
type: object
properties:
type:
type: string
default: sigs/one
data:
type: object
properties:
tx:
$ref: "#/definitions/Tx"
signature:
type: object
properties:
Sig:
type: string
example: 81B11E717789600CC192B26F452A983DF13B985EE75ABD9DD9E68D7BA007A958
Pubkey:
$ref: "#/definitions/PubKey"
Account:
type: object
properties:
name:
type: string
example: Main Account
address:
$ref: "#/definitions/Address"
pub_key:
$ref: "#/definitions/PubKey"
Balance:
type: object
properties:
height:
type: number
example: 123456
coins:
type: array
items:
$ref: "#/definitions/Coins"
credit:
type: array
items:
type: object
BlockID:
type: object
properties:
hash:
$ref: "#/definitions/Hash"
parts:
type: object
properties:
total:
type: number
example: 0
hash:
$ref: "#/definitions/Hash"
Block:
type: object
properties:
header:
type: object
properties:
chain_id:
type: string
example: gaia-2
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"
consensus_hash:
$ref: "#/definitions/Hash"
app_hash:
$ref: "#/definitions/Hash"
last_results_hash:
$ref: "#/definitions/Hash"
evidence_hash:
$ref: "#/definitions/Hash"
txs:
type: array
items:
$ref: "#/definitions/Tx"
evidence:
type: array
items:
type: object
last_commit:
type: object
properties:
blockID:
$ref: "#/definitions/BlockID"
precommits:
type: array
items:
type: object
Validator:
type: object
properties:
address:
$ref: '#/definitions/ValidatorAddress'
pub_key:
$ref: "#/definitions/ValidatorPubKey"
power:
type: number
example: 1000
accum:
type: number
example: 1000
# Added by API Auto Mocking Plugin
host: virtserver.swaggerhub.com
basePath: /faboweb1/Cosmos-LCD-2/1.0.0
schemes:
- https

View File

@ -1,6 +1,6 @@
# Install the SDK
This guide will explain how to install the [Cosmos SDK](/sdk/overview.md) onto your system. With the SDK installed on a server, you can participate in the latest testnet as either a [Full Node](full-node.md) or a [Validator](/validators/validator-setup.md).
This guide will explain how to install the [Cosmos SDK](/sdk/overview.md) onto your system. With the SDK installed on a server, you can participate in the latest testnet as either a [Full Node](./join-testnet.md#run-a-full-node) or a [Validator](/validators/validator-setup.md).
## Install Go

View File

@ -9,7 +9,7 @@ From the [networks/local directory](https://github.com/cosmos/cosmos-sdk/tree/de
### Requirements
- [Install gaia](https://cosmos.network/docs/getting-started/installation.html)
- [Install gaia](./installation.md)
- [Install docker](https://docs.docker.com/engine/installation/)
- [Install docker-compose](https://docs.docker.com/compose/install/)

View File

@ -1,4 +1,4 @@
## Tendermint and Cosmos
# Tendermint and Cosmos
Blockchains can be divided into three conceptual layers:

View File

@ -10,7 +10,7 @@ The ability to tolerate machines failing in arbitrary ways, including becoming m
## Application Blockchain Interface
Tendermint consists of two chief technical components: a blockchain consensus engine and a generic application interface. The consensus engine, called Tendermint Core, ensures that the same transactions are recorded on every machine in the same order. The application interface, called the Application Blockchain Interface (ABCI), enables the transactions to be processed in any programming language. Unlike other blockchain and consensus solutions developers can use Tendermint for BFT state machine replication in any programming language or development environment. Visit the [Tendermint docs](https://tendermint.readthedocs.io/projects/tools/en/master/introduction.html#abci-overview) for a deep dive into the ABCI.
Tendermint consists of two chief technical components: a blockchain consensus engine and a generic application interface. The consensus engine, called Tendermint Core, ensures that the same transactions are recorded on every machine in the same order. The application interface, called the Application Blockchain Interface (ABCI), enables the transactions to be processed in any programming language. Unlike other blockchain and consensus solutions developers can use Tendermint for BFT state machine replication in any programming language or development environment. Visit the [Tendermint docs](https://tendermint.com/docs/introduction/introduction.html#abci-overview) for a deep dive into the ABCI.
## Understanding the roles of the different layers

View File

@ -20,6 +20,7 @@ LCD will be used in the Cosmos Hub, the first Hub in the Cosmos network.
2. [**Get Started**](getting_started.md)
3. [**API**](api.md)
4. [**Specifications**](specification.md)
4. [**Update API docs To Swagger-UI**](update_API_docs.md)
## Overview

View File

@ -169,7 +169,7 @@ gaiacli tx broadcast --node=<node> signedSendTx.json
#### Set up a Validator
Please refer to the [Validator Setup](https://cosmos.network/docs/validators/validator-setup.html) section for a more complete guide on how to set up a validator-candidate.
Please refer to the [Validator Setup](../validators/validator-setup.md) section for a more complete guide on how to set up a validator-candidate.
#### Delegate to a Validator

View File

@ -1,23 +0,0 @@
## Application CLI
**File: [`cmd/simplegovcli/maing.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/cmd/simplegovcli/main.go)**
To interact with our application, let us add the commands from the `simple_governance` module to our `simpleGov` application, as well as the pre-built SDK commands:
```go
// cmd/simplegovcli/main.go
...
rootCmd.AddCommand(
client.GetCommands(
simplegovcmd.GetCmdQueryProposal("proposals", cdc),
simplegovcmd.GetCmdQueryProposals("proposals", cdc),
simplegovcmd.GetCmdQueryProposalVotes("proposals", cdc),
simplegovcmd.GetCmdQueryProposalVote("proposals", cdc),
)...)
rootCmd.AddCommand(
client.PostCommands(
simplegovcmd.PostCmdPropose(cdc),
simplegovcmd.PostCmdVote(cdc),
)...)
...
```

View File

@ -1,21 +0,0 @@
## Application codec
**File: [`app/app.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/app/app.go)**
Finally, we need to define the `MakeCodec()` function and register the concrete types and interface from the various modules.
```go
func MakeCodec() *codec.Codec {
var cdc = codec.New()
codec.RegisterCrypto(cdc) // Register crypto.
sdk.RegisterCodec(cdc) // Register Msgs
bank.RegisterCodec(cdc)
simplestake.RegisterCodec(cdc)
simpleGov.RegisterCodec(cdc)
// Register AppAccount
cdc.RegisterInterface((*auth.Account)(nil), nil)
cdc.RegisterConcrete(&types.AppAccount{}, "simpleGov/Account", nil)
return cdc
}
```

View File

@ -1,9 +0,0 @@
## App commands
We will need to add the newly created commands to our application. To do so, go to the `cmd` folder inside your root directory:
```bash
// At root level of directory
cd cmd
```
`simplegovd` is the folder that stores the command for running the server daemon, whereas `simplegovcli` defines the commands of your application.

View File

@ -1,61 +0,0 @@
## Application constructor
**File: [`app/app.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/app/app.go)**
Now, we need to define the constructor for our application.
```go
func NewSimpleGovApp(logger log.Logger, db dbm.DB) *SimpleGovApp
```
In this function, we will:
- Create the codec
```go
var cdc = MakeCodec()
```
- Instantiate our application. This includes creating the keys to access each of the substores.
```go
// Create your application object.
var app = &SimpleGovApp{
BaseApp: bam.NewBaseApp(appName, cdc, logger, db),
cdc: cdc,
capKeyMainStore: sdk.NewKVStoreKey("main"),
capKeyAccountStore: sdk.NewKVStoreKey("acc"),
capKeyStakingStore: sdk.NewKVStoreKey("stake"),
capKeySimpleGovStore: sdk.NewKVStoreKey("simpleGov"),
}
```
- Instantiate the keepers. Note that keepers generally need access to other module's keepers. In this case, make sure you only pass an instance of the keeper for the functionality that is needed. If a keeper only needs to read in another module's store, a read-only keeper should be passed to it.
```go
app.bankKeeper = bank.NewBaseKeeper(app.accountMapper)
app.stakeKeeper = simplestake.NewKeeper(app.capKeyStakingStore, app.bankKeeper,app.RegisterCodespace(simplestake.DefaultCodespace))
app.simpleGovKeeper = simpleGov.NewKeeper(app.capKeySimpleGovStore, app.bankKeeper, app.stakeKeeper, app.RegisterCodespace(simpleGov.DefaultCodespace))
```
- Declare the handlers.
```go
app.Router().
AddRoute("bank", bank.NewHandler(app.bankKeeper)).
AddRoute("simplestake", simplestake.NewHandler(app.stakeKeeper)).
AddRoute("simpleGov", simpleGov.NewHandler(app.simpleGovKeeper))
```
- Initialize the application.
```go
// Initialize BaseApp.
app.MountStoresIAVL(app.capKeyMainStore, app.capKeyAccountStore, app.capKeySimpleGovStore, app.capKeyStakingStore)
app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper))
err := app.LoadLatestVersion(app.capKeyMainStore)
if err != nil {
cmn.Exit(err.Error())
}
return app
```

View File

@ -1,4 +1,4 @@
## Application initialization
# Application Initialization
In the root of your fork of the SDK, create an `app` and `cmd` folder. In this folder, we will create the main file for our application, `app.go` and the repository to handle REST and CLI commands for our app.

View File

@ -1,22 +0,0 @@
## Makefile
The [Makefile](https://en.wikipedia.org/wiki/Makefile) compiles the Go program by defining a set of rules with targets and recipes. We'll need to add our application commands to it:
```
// Makefile
build_examples:
ifeq ($(OS),Windows_NT)
...
go build $(BUILD_FLAGS) -o build/simplegovd.exe ./examples/simpleGov/cmd/simplegovd
go build $(BUILD_FLAGS) -o build/simplegovcli.exe ./examples/simpleGov/cmd/simplegovcli
else
...
go build $(BUILD_FLAGS) -o build/simplegovd ./examples/simpleGov/cmd/simplegovd
go build $(BUILD_FLAGS) -o build/simplegovcli ./examples/simpleGov/cmd/simplegovcli
endif
...
install_examples:
...
go install $(BUILD_FLAGS) ./examples/simpleGov/cmd/simplegovd
go install $(BUILD_FLAGS) ./examples/simpleGov/cmd/simplegovcli
```

View File

@ -1,57 +0,0 @@
##### Rest server
**File: [`cmd/simplegovd/main.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/cmd/simplegovd/main.go)**
The `simplegovd` command will run the daemon server as a background process. First, let us create some `utils` functions:
```go
// cmd/simplegovd/main.go
// SimpleGovAppInit initial parameters
var SimpleGovAppInit = server.AppInit{
AppGenState: SimpleGovAppGenState,
AppGenTx: server.SimpleAppGenTx,
}
// SimpleGovAppGenState sets up the app_state and appends the simpleGov app state
func SimpleGovAppGenState(cdc *codec.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) {
appState, err = server.SimpleAppGenState(cdc, appGenTxs)
if err != nil {
return
}
return
}
func newApp(logger log.Logger, db dbm.DB) abci.Application {
return app.NewSimpleGovApp(logger, db)
}
func exportAppState(logger log.Logger, db dbm.DB) (json.RawMessage, error) {
dapp := app.NewSimpleGovApp(logger, db)
return dapp.ExportAppStateJSON()
}
```
Now, let us define the command for the daemon server within the `main()` function:
```go
// cmd/simplegovd/main.go
func main() {
cdc := app.MakeCodec()
ctx := server.NewDefaultContext()
rootCmd := &cobra.Command{
Use: "simplegovd",
Short: "Simple Governance Daemon (server)",
PersistentPreRunE: server.PersistentPreRunEFn(ctx),
}
server.AddCommands(ctx, cdc, rootCmd, SimpleGovAppInit,
server.ConstructAppCreator(newApp, "simplegov"),
server.ConstructAppExporter(exportAppState, "simplegov"))
// prepare and add flags
rootDir := os.ExpandEnv("$HOME/.simplegovd")
executor := cli.PrepareBaseCmd(rootCmd, "BC", rootDir)
executor.Execute()
}
```

View File

@ -1,55 +0,0 @@
## Application structure
Now, that we have built all the pieces we need, it is time to integrate them into the application. Let us exit the `/x` director go back at the root of the SDK directory.
```bash
// At root level of directory
cd app
```
We are ready to create our simple governance application!
*Note: You can check the full file (with comments!) [here](link)*
The `app.go` file is the main file that defines your application. In it, you will declare all the modules you need, their keepers, handlers, stores, etc. Let us take a look at each section of this file to see how the application is constructed.
Secondly, we need to define the name of our application.
```go
const (
appName = "SimpleGovApp"
)
```
Then, let us define the structure of our application.
```go
// Extended ABCI application
type SimpleGovApp struct {
*bam.BaseApp
cdc *codec.Codec
// keys to access the substores
capKeyMainStore *sdk.KVStoreKey
capKeyAccountStore *sdk.KVStoreKey
capKeyStakingStore *sdk.KVStoreKey
capKeySimpleGovStore *sdk.KVStoreKey
// keepers
feeCollectionKeeper auth.FeeCollectionKeeper
bankKeeper bank.Keeper
stakeKeeper simplestake.Keeper
simpleGovKeeper simpleGov.Keeper
// Manage getting and setting accounts
accountMapper auth.AccountMapper
}
```
- Each application builds on top of the `BaseApp` template, hence the pointer.
- `cdc` is the codec used in our application.
- Then come the keys to the stores we need in our application. For our simple governance app, we need 3 stores + the main store.
- Then come the keepers and mappers.
Let us do a quick reminder so that it is clear why we need these stores and keepers. Our application is primarily based on the `simple_governance` module. However, we have established in section [Keepers for our app](module-keeper.md) that our module needs access to two other modules: the `bank` module and the `stake` module. We also need the `auth` module for basic account functionalities. Finally, we need access to the main multistore to declare the stores of each of the module we use.

View File

@ -0,0 +1,256 @@
# From Module To Application
## Application structure
Now, that we have built all the pieces we need, it is time to integrate them into the application. Let us exit the `/x` director go back at the root of the SDK directory.
```bash
// At root level of directory
cd app
```
We are ready to create our simple governance application!
*Note: You can check the full file (with comments!) [here](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/app/app.go)*
The `app.go` file is the main file that defines your application. In it, you will declare all the modules you need, their keepers, handlers, stores, etc. Let us take a look at each section of this file to see how the application is constructed.
Secondly, we need to define the name of our application.
```go
const (
appName = "SimpleGovApp"
)
```
Then, let us define the structure of our application.
```go
// Extended ABCI application
type SimpleGovApp struct {
*bam.BaseApp
cdc *codec.Codec
// keys to access the substores
capKeyMainStore *sdk.KVStoreKey
capKeyAccountStore *sdk.KVStoreKey
capKeyStakingStore *sdk.KVStoreKey
capKeySimpleGovStore *sdk.KVStoreKey
// keepers
feeCollectionKeeper auth.FeeCollectionKeeper
bankKeeper bank.Keeper
stakeKeeper simplestake.Keeper
simpleGovKeeper simpleGov.Keeper
// Manage getting and setting accounts
accountMapper auth.AccountMapper
}
```
- Each application builds on top of the `BaseApp` template, hence the pointer.
- `cdc` is the codec used in our application.
- Then come the keys to the stores we need in our application. For our simple governance app, we need 3 stores + the main store.
- Then come the keepers and mappers.
Let us do a quick reminder so that it is clear why we need these stores and keepers. Our application is primarily based on the `simple_governance` module. However, we have established in section [Keepers for our app](module-keeper.md) that our module needs access to two other modules: the `bank` module and the `stake` module. We also need the `auth` module for basic account functionalities. Finally, we need access to the main multistore to declare the stores of each of the module we use.
## CLI and Rest server
We will need to add the newly created commands to our application. To do so, go to the `cmd` folder inside your root directory:
```bash
// At root level of directory
cd cmd
```
`simplegovd` is the folder that stores the command for running the server daemon, whereas `simplegovcli` defines the commands of your application.
### Application CLI
**File: [`cmd/simplegovcli/maing.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/cmd/simplegovcli/main.go)**
To interact with our application, let us add the commands from the `simple_governance` module to our `simpleGov` application, as well as the pre-built SDK commands:
```go
// cmd/simplegovcli/main.go
...
rootCmd.AddCommand(
client.GetCommands(
simplegovcmd.GetCmdQueryProposal("proposals", cdc),
simplegovcmd.GetCmdQueryProposals("proposals", cdc),
simplegovcmd.GetCmdQueryProposalVotes("proposals", cdc),
simplegovcmd.GetCmdQueryProposalVote("proposals", cdc),
)...)
rootCmd.AddCommand(
client.PostCommands(
simplegovcmd.PostCmdPropose(cdc),
simplegovcmd.PostCmdVote(cdc),
)...)
...
```
### Rest server
**File: [`cmd/simplegovd/main.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/cmd/simplegovd/main.go)**
The `simplegovd` command will run the daemon server as a background process. First, let us create some `utils` functions:
```go
// cmd/simplegovd/main.go
// SimpleGovAppInit initial parameters
var SimpleGovAppInit = server.AppInit{
AppGenState: SimpleGovAppGenState,
AppGenTx: server.SimpleAppGenTx,
}
// SimpleGovAppGenState sets up the app_state and appends the simpleGov app state
func SimpleGovAppGenState(cdc *codec.Codec, appGenTxs []json.RawMessage) (appState json.RawMessage, err error) {
appState, err = server.SimpleAppGenState(cdc, appGenTxs)
if err != nil {
return
}
return
}
func newApp(logger log.Logger, db dbm.DB) abci.Application {
return app.NewSimpleGovApp(logger, db)
}
func exportAppState(logger log.Logger, db dbm.DB) (json.RawMessage, error) {
dapp := app.NewSimpleGovApp(logger, db)
return dapp.ExportAppStateJSON()
}
```
Now, let us define the command for the daemon server within the `main()` function:
```go
// cmd/simplegovd/main.go
func main() {
cdc := app.MakeCodec()
ctx := server.NewDefaultContext()
rootCmd := &cobra.Command{
Use: "simplegovd",
Short: "Simple Governance Daemon (server)",
PersistentPreRunE: server.PersistentPreRunEFn(ctx),
}
server.AddCommands(ctx, cdc, rootCmd, SimpleGovAppInit,
server.ConstructAppCreator(newApp, "simplegov"),
server.ConstructAppExporter(exportAppState, "simplegov"))
// prepare and add flags
rootDir := os.ExpandEnv("$HOME/.simplegovd")
executor := cli.PrepareBaseCmd(rootCmd, "BC", rootDir)
executor.Execute()
}
```
## Makefile
The [Makefile](https://en.wikipedia.org/wiki/Makefile) compiles the Go program by defining a set of rules with targets and recipes. We'll need to add our application commands to it:
```
// Makefile
build_examples:
ifeq ($(OS),Windows_NT)
...
go build $(BUILD_FLAGS) -o build/simplegovd.exe ./examples/simpleGov/cmd/simplegovd
go build $(BUILD_FLAGS) -o build/simplegovcli.exe ./examples/simpleGov/cmd/simplegovcli
else
...
go build $(BUILD_FLAGS) -o build/simplegovd ./examples/simpleGov/cmd/simplegovd
go build $(BUILD_FLAGS) -o build/simplegovcli ./examples/simpleGov/cmd/simplegovcli
endif
...
install_examples:
...
go install $(BUILD_FLAGS) ./examples/simpleGov/cmd/simplegovd
go install $(BUILD_FLAGS) ./examples/simpleGov/cmd/simplegovcli
```
## Application constructor
**File: [`app/app.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/app/app.go)**
Now, we need to define the constructor for our application.
```go
func NewSimpleGovApp(logger log.Logger, db dbm.DB) *SimpleGovApp
```
In this function, we will:
- Create the codec
```go
var cdc = MakeCodec()
```
- Instantiate our application. This includes creating the keys to access each of the substores.
```go
// Create your application object.
var app = &SimpleGovApp{
BaseApp: bam.NewBaseApp(appName, cdc, logger, db),
cdc: cdc,
capKeyMainStore: sdk.NewKVStoreKey("main"),
capKeyAccountStore: sdk.NewKVStoreKey("acc"),
capKeyStakingStore: sdk.NewKVStoreKey("stake"),
capKeySimpleGovStore: sdk.NewKVStoreKey("simpleGov"),
}
```
- Instantiate the keepers. Note that keepers generally need access to other module's keepers. In this case, make sure you only pass an instance of the keeper for the functionality that is needed. If a keeper only needs to read in another module's store, a read-only keeper should be passed to it.
```go
app.bankKeeper = bank.NewBaseKeeper(app.accountMapper)
app.stakeKeeper = simplestake.NewKeeper(app.capKeyStakingStore, app.bankKeeper,app.RegisterCodespace(simplestake.DefaultCodespace))
app.simpleGovKeeper = simpleGov.NewKeeper(app.capKeySimpleGovStore, app.bankKeeper, app.stakeKeeper, app.RegisterCodespace(simpleGov.DefaultCodespace))
```
- Declare the handlers.
```go
app.Router().
AddRoute("bank", bank.NewHandler(app.bankKeeper)).
AddRoute("simplestake", simplestake.NewHandler(app.stakeKeeper)).
AddRoute("simpleGov", simpleGov.NewHandler(app.simpleGovKeeper))
```
- Initialize the application.
```go
// Initialize BaseApp.
app.MountStoresIAVL(app.capKeyMainStore, app.capKeyAccountStore, app.capKeySimpleGovStore, app.capKeyStakingStore)
app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper))
err := app.LoadLatestVersion(app.capKeyMainStore)
if err != nil {
cmn.Exit(err.Error())
}
return app
```
## Application codec
**File: [`app/app.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/app/app.go)**
Finally, we need to define the `MakeCodec()` function and register the concrete types and interface from the various modules.
```go
func MakeCodec() *codec.Codec {
var cdc = codec.New()
codec.RegisterCrypto(cdc) // Register crypto.
sdk.RegisterCodec(cdc) // Register Msgs
bank.RegisterCodec(cdc)
simplestake.RegisterCodec(cdc)
simpleGov.RegisterCodec(cdc)
// Register AppAccount
cdc.RegisterInterface((*auth.Account)(nil), nil)
cdc.RegisterConcrete(&types.AppAccount{}, "simpleGov/Account", nil)
return cdc
}
```

View File

@ -1,19 +0,0 @@
## Cast a vote to an existing proposal
Let's cast a vote on the created proposal:
```bash
simplegovcli vote --proposal-id=1 --option="No"
```
Get the value of the option from your casted vote :
```bash
simplegovcli proposal-vote 1 <your_address>
```
You can also check all the casted votes of a proposal:
```bash
simplegovcli proposals-votes 1
```

View File

@ -6,45 +6,43 @@ Before getting in the bulk of the code, we will start by some introductory conte
## Table of contents:
### Introduction - Prerequsite reading
### Introduction - Prerequisite reading
- [Intro to Tendermint and Cosmos](../../../introduction/tendermint-cosmos.md)
- [Tendermint Core and ABCI](../../../introduction/tendermint.md)
- [Intro to Cosmos-SDK](../../overview.md)
- [Starting your own project](start.md)
- [Intro to Tendermint and Cosmos](/introduction/tendermint-cosmos.md)
- [Tendermint Core and ABCI](/introduction/tendermint.md)
- [Intro to Cosmos-SDK](/sdk/overview.md)
### Setup and design phase
- [Setup](setup.md)
- [Application design](app-design.md)
### [Setup and design](setup-and-design.md)
- [Starting your own project](setup-and-design.md#get-started)
- [Setup](setup-and-design.md#setup)
- [Application design](setup-and-design.md#application-design)
### Implementation of the application
**Important note: All the code for this application can be found [here](https://github.com/cosmos/cosmos-sdk/tree/fedekunze/module_tutorial/examples/simpleGov). Snippets will be provided throughout the tutorial, but please refer to the provided link for the full implementation details**
- [Application initialization](app-init.md)
- Simple Governance module
+ [Module initialization](module-init.md)
+ [Types](module-types.md)
+ [Keeper](module-keeper.md)
+ [Handler](module-handler.md)
+ [Wire](module-codec.md)
+ [Errors](module-errors.md)
+ Command-Line Interface and Rest API
* [Command-Line Interface](module-cli.md)
* [Rest API](module-rest.md)
- Bridging it all together
+ [Application structure](app-structure.md)
+ [Application CLI and Rest Server](app-commands.md)
* [Application CLI](app-cli.md)
* [Rest Server](app-rest.md)
+ [Makefile](app-makefile.md)
+ [Application constructor](app-constructor.md)
+ [Application codec](app-codec.md)
- Running the application
+ [Installation](run-install.md)
+ [Submit a proposal](submit-proposal.md)
+ [Cast a vote](cast-vote.md)
- [Simple Governance module](simple-gov-module.md)
+ [Module initialization](simple-gov-module.md#module-initialization)
+ [Types](simple-gov-module.md#types)
+ [Keeper](simple-gov-module.md#keeper)
+ [Handler](simple-gov-module.md#handler)
+ [Wire](simple-gov-module.md#codec)
+ [Errors](simple-gov-module.md#errors)
+ [Command-Line Interface](simple-gov-module.md#command-line-interface)
+ [Rest API](simple-gov-module.md#rest-api)
- [Bridging it all together](bridging-it-all.md)
+ [Application structure](bridging-it-all.md#application-structure)
+ [Application CLI and Rest Server](bridging-it-all.md#cli-and-rest-server)
+ [Makefile](bridging-it-all.md#makefile)
+ [Application constructor](bridging-it-all.md#application-constructor)
+ [Application codec](bridging-it-all.md#application-codec)
- [Running the application](running-the-application.md)
+ [Installation](running-the-application.md#installation)
+ [Submit a proposal](running-the-application.md#submit-a-proposal)
+ [Cast a vote](running-the-application.md#cast-a-vote)
## Useful links

View File

@ -1,33 +0,0 @@
## Command-Line Interface (CLI)
**File: [`x/simple_governance/client/cli/simple_governance.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/x/simple_governance/client/cli/simple_governance.go)**
Go in the `cli` folder and create a `simple_governance.go` file. This is where we will define the commands for our module.
The CLI builds on top of [Cobra](https://github.com/spf13/cobra). Here is the schema to build a command on top of Cobra:
```go
// Declare flags
const(
Flag = "flag"
...
)
// Main command function. One function for each command.
func Command(codec *codec.Codec) *cobra.Command {
// Create the command to return
command := &cobra.Command{
Use: "actual command",
Short: "Short description",
Run: func(cmd *cobra.Command, args []string) error {
// Actual function to run when command is used
},
}
// Add flags to the command
command.Flags().<Type>(FlagNameConstant, <example_value>, "<Description>")
return command
}
```

View File

@ -1,13 +0,0 @@
## Codec
**File: [`x/simple_governance/codec.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/x/simple_governance/codec.go)**
The `codec.go` file allows developers to register the concrete message types of their module into the codec. In our case, we have two messages to declare:
```go
func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterConcrete(SubmitProposalMsg{}, "simple_governance/SubmitProposalMsg", nil)
cdc.RegisterConcrete(VoteMsg{}, "simple_governance/VoteMsg", nil)
}
```
Don't forget to call this function in `app.go` (see [Application - Bridging it all together](app-structure.md)) for more).

View File

@ -1,7 +0,0 @@
## Errors
**File: [`x/simple_governance/errors.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/x/simple_governance/errors.go)**
The `error.go` file allows us to define custom error messages for our module. Declaring errors should be relatively similar in all modules. You can look in the `error.go` file directly for a concrete example. The code is self-explanatory.
Note that the errors of our module inherit from the `sdk.Error` interface and therefore possess the method `Result()`. This method is useful when there is an error in the `handler` and an error has to be returned in place of an actual result.

View File

@ -1,73 +0,0 @@
## Handler
**File: [`x/simple_governance/handler.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/x/simple_governance/handler.go)**
### Constructor and core handlers
Handlers implement the core logic of the state-machine. When a transaction is routed from the app to the module, it is run by the `handler` function.
In practice, one `handler` will be implemented for each message of the module. In our case, we have two message types. We will therefore need two `handler` functions. We will also need a constructor function to route the message to the correct `handler`:
```go
func NewHandler(k Keeper) sdk.Handler {
return func(ctx sdk.Context, msg sdk.Msg) sdk.Result {
switch msg := msg.(type) {
case SubmitProposalMsg:
return handleSubmitProposalMsg(ctx, k, msg)
case VoteMsg:
return handleVoteMsg(ctx, k, msg)
default:
errMsg := "Unrecognized gov Msg type: " + msg.Name()
return sdk.ErrUnknownRequest(errMsg).Result()
}
}
}
```
The messages are routed to the appropriate `handler` depending on their type. For our simple governance module, we only have two `handlers`, that correspond to our two message types. They have similar signatures:
```go
func handleSubmitProposalMsg(ctx sdk.Context, k Keeper, msg SubmitProposalMsg) sdk.Result
```
Let us take a look at the parameters of this function:
- The context `ctx` to access the stores.
- The keeper `k` allows the handler to read and write from the different stores, including the module's store (`SimpleGovernance` in our case) and all the stores from other modules that the keeper `k` has been granted an access to (`stake` and `bank` in our case).
- The message `msg` that holds all the information provided by the sender of the transaction.
The function returns a `Result` that is returned to the application. It contains several useful information such as the amount of `Gas` for this transaction and wether the message was succesfully processed or not. At this point, we exit the boundaries of our simple governance module and go back to root application level. The `Result` will differ from application to application. You can check the `sdk.Result` type directly [here](https://github.com/cosmos/cosmos-sdk/blob/develop/types/result.go) for more info.
### BeginBlocker and EndBlocker
In contrast to most smart-contracts platform, it is possible to perform automatic (i.e. not triggered by a transaction sent by an end-user) execution of logic in Cosmos-SDK applications.
This automatic execution of code takes place in the `BeginBlock` and `EndBlock` functions that are called at the beginning and at the end of every block. They are powerful tools, but it is important for application developers to be careful with them. For example, it is crutial that developers control the amount of computing that happens in these functions, as expensive computation could delay the block time, and never-ending loop freeze the chain altogether.
`BeginBlock` and `EndBlock` are composable functions, meaning that each module can implement its own `BeginBlock` and `EndBlock` logic. When needed, `BeginBlock` and `EndBlock` logic is implemented in the module's `handler`. Here is the standard way to proceed for `EndBlock` (`BeginBlock` follows the exact same pattern):
```go
func NewEndBlocker(k Keeper) sdk.EndBlocker {
return func(ctx sdk.Context, req abci.RequestEndBlock) (res abci.ResponseEndBlock) {
err := checkProposal(ctx, k)
if err != nil {
panic(err)
}
return
}
}
```
Do not forget that each module need to declare its `BeginBlock` and `EndBlock` constructors at application level. See the [Application - Bridging it all together](app-structure.md).
For the purpose of our simple governance application, we will use `EndBlock` to automatically tally the results of the vote. Here are the different steps that will be performed:
1. Get the oldest proposal from the `ProposalProcessingQueue`
2. Check if the `CurrentBlock` is the block at which the voting period for this proposal ends. If Yes, go to 3.. If no, exit.
3. Check if proposal is accepted or rejected. Update the proposal status.
4. Pop the proposal from the `ProposalProcessingQueue` and go back to 1.
Let us perform a quick safety analysis on this process.
- The loop will not run forever because the number of proposals in `ProposalProcessingQueue` is finite
- The computation should not be too expensive because tallying of individual proposals is not expensive and the number of proposals is expected be relatively low. That is because proposals require a `Deposit` to be accepted. `MinDeposit` should be high enough so that we don't have too many `Proposals` in the queue.
- In the eventuality that the application becomes so successful that the `ProposalProcessingQueue` ends up containing so many proposals that the blockchain starts slowing down, the module should be modified to mitigate the situation. One clever way of doing it is to cap the number of iteration per individual `EndBlock` at `MaxIteration`. This way, tallying will be spread over many blocks if the number of proposals is too important and block time should remain stable. This would require to modify the current check `if (CurrentBlock == Proposal.SubmitBlock + VotingPeriod)` to `if (CurrentBlock > Proposal.SubmitBlock + VotingPeriod) AND (Proposal.Status == ProposalStatusActive)`.

View File

@ -1,31 +0,0 @@
## Module initialization
First, let us go into the module's folder and create a folder for our module.
```bash
cd x/
mkdir simple_governance
cd simple_governance
mkdir -p client/cli client/rest
touch client/cli/simple_governance.go client/rest/simple_governance.go errors.go handler.go handler_test.go keeper_keys.go keeper_test.go keeper.go test_common.go test_types.go types.go codec.go
```
Let us start by adding the files we will need. Your module's folder should look something like that:
```
x
└─── simple_governance
├─── client
│ ├─── cli
│ │ └─── simple_governance.go
│ └─── rest
│ └─── simple_governance.go
├─── errors.go
├─── handler.go
├─── keeper_keys.go
├─── keeper.go
├─── types.go
└─── codec.go
```
Let us go into the detail of each of these files.

View File

@ -1,96 +0,0 @@
## Keeper
**File: [`x/simple_governance/keeper.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/x/simple_governance/keeper.go)**
### Short intro to keepers
`Keepers` are a module abstraction that handle reading/writing to the module store. This is a practical implementation of the **Object Capability Model** for Cosmos.
As module developers, we have to define keepers to interact with our module's store(s) not only from within our module, but also from other modules. When another module wants to access one of our module's store(s), a keeper for this store has to be passed to it at the application level. In practice, it will look like that:
```go
// in app.go
// instanciate keepers
keeperA = moduleA.newKeeper(app.moduleAStoreKey)
keeperB = moduleB.newKeeper(app.moduleBStoreKey)
// pass instance of keeperA to handler of module B
app.Router().
AddRoute("moduleA", moduleA.NewHandler(keeperA)).
AddRoute("moduleB", moduleB.NewHandler(keeperB, keeperA)) // Here module B can access one of module A's store via the keeperA instance
```
`KeeperA` grants a set of capabilities to the handler of module B. When developing a module, it is good practice to think about the sensitivity of the different capabilities that can be granted through keepers. For example, some module may need to read and write to module A's main store, while others only need to read it. If a module has multiple stores, then some keepers could grant access to all of them, while others would only grant access to specific sub-stores. It is the job of the module developer to make sure it is easy for application developers to instanciate a keeper with the right capabilities. Of course, the handler of a module will most likely get an unrestricted instance of that module's keeper.
### Store for our app
Before we delve into the keeper itself, let us see what objects we need to store in our governance sub-store, and how to index them.
- `Proposals` will be indexed by `'proposals'|<proposalID>`.
- `Votes` (`Yes`, `No`, `Abstain`) will be indexed by `'proposals'|<proposalID>|'votes'|<voterAddress>`.
Notice the quote mark on `'proposals'` and `'votes'`. They indicate that these are constant keywords. So, for example, the option casted by voter with address `0x01` on proposal `0101` will be stored at index `'proposals'|0101|'votes'|0x01`.
These keywords are used to faciliate range queries. Range queries (TODO: Link to formal spec) allow developer to query a subspace of the store, and return an iterator. They are made possible by the nice properties of the [IAVL+ tree](https://github.com/tendermint/iavl) that is used in the background. In practice, this means that it is possible to store and query a Key-Value pair in O(1), while still being able to iterate over a given subspace of Key-Value pairs. For example, we can query all the addresses that voted on a given proposal, along with their votes, by calling `rangeQuery(SimpleGovStore, <proposalID|'addresses'>)`.
### Keepers for our app
In our case, we only have one store to access, the `SimpleGov` store. We will need to set and get values inside this store via our keeper. However, these two actions do not have the same impact in terms of security. While there should no problem in granting read access to our store to other modules, write access is way more sensitive. So ideally application developers should be able to create either a governance mapper that can only get values from the store, or one that can both get and set values. To this end, we will introduce two keepers: `Keeper` and `KeeperRead`. When application developers create their application, they will be able to decide which of our module's keeper to use.
Now, let us try to think about which keeper from **external** modules our module's keepers need access to.
Each proposal requires a deposit. This means our module needs to be able to both read and write to the module that handles tokens, which is the `bank` module. We also need to be able to determine the voting power of each voter based on their stake. To this end, we need read access to the store of the `staking` module. However, we don't need write access to this store. We should therefore indicate that in our module, and the application developer should be careful to only pass a read-only keeper of the `staking` module to our module's handler.
With all that in mind, we can define the structure of our `Keeper`:
```go
type Keeper struct {
SimpleGov sdk.StoreKey // Key to our module's store
cdc *codec.Codec // Codec to encore/decode structs
ck bank.Keeper // Needed to handle deposits. This module onlyl requires read/writes to Atom balance
sm stake.Keeper // Needed to compute voting power. This module only needs read access to the staking store.
codespace sdk.CodespaceType // Reserves space for error codes
}
```
And the structure of our `KeeperRead`:
```go
type KeeperRead struct {
Keeper
}
```
`KeeperRead` will inherit all methods from `Keeper`, except those that we override. These will be the methods that perform writes to the store.
### Functions and Methods
The first function we have to create is the constructor.
```go
func NewKeeper(SimpleGov sdk.StoreKey, ck bank.Keeper, sm stake.Keeper, codespace sdk.CodespaceType) Keeper
```
This function is called from the main [`app.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/app/app.go) file to instanciate a new `Keeper`. A similar function exits for `KeeperRead`.
```go
func NewKeeperRead(SimpleGov sdk.StoreKey, ck bank.Keeper, sm stake.Keeper, codespace sdk.CodespaceType) KeeperRead
```
Depending on the needs of the application and its modules, either `Keeper`, `KeeperRead`, or both, will be instanciated at application level.
*Note: Both the `Keeper` type name and `NewKeeper()` function's name are standard names used in every module. It is no requirement to follow this standard, but doing so can facilitate the life of application developers*
Now, let us describe the methods we need for our module's `Keeper`. For the full implementation, please refer to `keeper.go`.
- `GetProposal`: Get a `Proposal` given a `proposalID`. Proposals need to be decoded from `byte` before they can be read.
- `SetProposal`: Set a `Proposal` at index `'proposals'|<proposalID>`. Proposals need to be encoded to `byte` before they can be stored.
- `NewProposalID`: A function to generate a new unique `proposalID`.
- `GetVote`: Get a vote `Option` given a `proposalID` and a `voterAddress`.
- `SetVote`: Set a vote `Option` given a `proposalID` and a `voterAddress`.
- Proposal Queue methods: These methods implement a standard proposal queue to store `Proposals` on a First-In First-Out basis. It is used to tally the votes at the end of the voting period.
The last thing that needs to be done is to override certain methods for the `KeeperRead` type. `KeeperRead` should not have write access to the stores. Therefore, we will override the methods `SetProposal()`, `SetVote()` and `NewProposalID()`, as well as `setProposalQueue()` from the Proposal Queue's methods. For `KeeperRead`, these methods will just throw an error.
*Note: If you look at the code, you'll notice that the context `ctx` is a parameter of many of the methods. The context `ctx` provides useful information on the current state such as the current block height and allows the keeper `k` to access the `KVStore`. You can check all the methods of `ctx` [here](https://github.com/cosmos/cosmos-sdk/blob/develop/types/context.go#L144-L168)*.

View File

@ -1,32 +0,0 @@
## Rest API
**File: [`x/simple_governance/client/rest/simple_governance.goo`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/x/simple_governance/client/rest/simple_governance.go)**
The Rest Server, also called [Light-Client Daemon (LCD)](https://github.com/cosmos/cosmos-sdk/tree/master/client/lcd), provides support for **HTTP queries**.
________________________________________________________
USER INTERFACE <=======> REST SERVER <=======> FULL-NODE
________________________________________________________
It allows end-users that do not want to run full-nodes themselves to interract with the chain. The LCD can be configured to perform **Light-Client verification** via the flag `--trust-node`, which can be set to `true` or `false`.
- If *light-client verification* is enabled, the Rest Server acts as a light-client and needs to be run on the end-user's machine. It allows them to interract with the chain in a trustless way without having to store the whole chain locally.
- If *light-client verification* is disabled, the Rest Server acts as a simple relayer for HTTP calls. In this setting, the Rest server needs not be run on the end-user's machine. Instead, it will probably be run by the same entity that operates the full-node the server connects to. This mode is useful if end-users trust the full-node operator and do not want to store anything locally.
Now, let us define endpoints that will be available for users to query through HTTP requests. These endpoints will be defined in a `simple_governance.go` file stored in the `rest` folder.
| Method | URL | Description |
|--------|---------------------------------|-------------------------------------------------------------|
| GET | /proposals | Range query to get all submitted proposals |
| POST | /proposals | Submit a new proposal |
| GET | /proposals/{id} | Returns a proposal given its ID |
| GET | /proposals/{id}/votes | Range query to get all the votes casted on a given proposal |
| POST | /proposals/{id}/votes | Cast a vote on a given proposal |
| GET | /proposals/{id}/votes/{address} | Returns the vote of a given address on a given proposal |
It is the job of module developers to provide sensible endpoints so that front-end developers and service providers can properly interact with it.
Additionaly, here is a [link](https://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9) for REST APIs best practices.

View File

@ -1,23 +0,0 @@
## Types
**File: [`x/simple_governance/types.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/x/simple_governance/types.go)**
In this file, we define the custom types for our module. This includes the types from the [State](app-design.md#State) section and the custom message types defined in the [Messages](app-design#Messages) section.
For each new type that is not a message, it is possible to add methods that make sense in the context of the application. In our case, we will implement an `updateTally` function to easily update the tally of a given proposal as vote messages come in.
Messages are a bit different. They implement the `Message` interface defined in the SDK's `types` folder. Here are the methods you need to implement when you define a custom message type:
- `Type()`: This function returns the name of our module's route. When messages are processed by the application, they are routed using the string returned by the `Type()` method.
- `GetSignBytes()`: Returns the byte representation of the message. It is used to sign the message.
- `GetSigners()`: Returns address(es) of the signer(s).
- `ValidateBasic()`: This function is used to discard obviously invalid messages. It is called at the beginning of `runTx()` in the baseapp file. If `ValidateBasic()` does not return `nil`, the app stops running the transaction.
- `Get()`: A basic getter, returns some property of the message.
- `String()`: Returns a human-readable version of the message
For our simple governance messages, this means:
- `Type()` will return `"simpleGov"`
- For `SubmitProposalMsg`, we need to make sure that the attributes are not empty and that the deposit is both valid and positive. Note that this is only basic validation, we will therefore not check in this method that the sender has sufficient funds to pay for the deposit
- For `VoteMsg`, we check that the address and option are valid and that the proposalID is not negative.
- As for other methods, less customization is required. You can check the code to see a standard way of implementing these.

View File

@ -1,18 +0,0 @@
## Installation
Once you have finallized your application, install it using `go get`. The following commands will install the pre-built modules and examples of the SDK as well as your `simpleGov` application:
```bash
go get github.com/<your_username>/cosmos-sdk
cd $GOPATH/src/github.com/<your_username>/cosmos-sdk
make get_vendor_deps
make install
make install_examples
```
Check that the app is correctly installed by typing:
```bash
simplegovcli -h
simplegovd -h
```

View File

@ -0,0 +1,77 @@
# Running The Application
## Installation
Once you have finallized your application, install it using `go get`. The following commands will install the pre-built modules and examples of the SDK as well as your `simpleGov` application:
```bash
go get github.com/<your_username>/cosmos-sdk
cd $GOPATH/src/github.com/<your_username>/cosmos-sdk
make get_vendor_deps
make install
make install_examples
```
Check that the app is correctly installed by typing:
```bash
simplegovcli -h
simplegovd -h
```
## Submit a proposal
Uuse the CLI to create a new proposal:
```bash
simplegovcli propose --title="Voting Period update" --description="Should we change the proposal voting period to 3 weeks?" --deposit=300Atoms
```
Or, via a json file:
```bash
simplegovcli propose --proposal="path/to/proposal.json"
```
Where proposal.json contains:
```json
{
"title": "Voting Period Update",
"description": "Should we change the proposal voting period to 3 weeks?",
"type": "Text",
"deposit": "300Atoms"
}
```
Get the details of your newly created proposal:
```bash
simplegovcli proposal 1
```
You can also check all the existing open proposals:
```bash
simplegovcli proposals --active=true
```
## Cast a vote
Let's cast a vote on the created proposal:
```bash
simplegovcli vote --proposal-id=1 --option="No"
```
Get the value of the option from your casted vote :
```bash
simplegovcli proposal-vote 1 <your_address>
```
You can also check all the casted votes of a proposal:
```bash
simplegovcli proposals-votes 1
```

View File

@ -1,3 +1,47 @@
# Setup And Design
## Get started
To get started, you just have to follow these simple steps:
1. Clone the [Cosmos-SDK](https://github.com/cosmos/cosmos-sdk/tree/develop)repo
2. Code the modules needed by your application that do not already exist.
3. Create your app directory. In the app main file, import the module you need and instantiate the different stores.
4. Launch your blockchain.
## Setup
### Prerequisites
- Have [go](https://golang.org/dl/) and [git](https://git-scm.com/downloads) installed
- Don't forget to set your `PATH` and `GOPATH`
### Setup work environment
Go to the [Cosmos-SDK repo](https://githum.com/cosmos/cosmos-sdk) and fork it. Then open a terminal and:
```bash
cd $GOPATH/src/github.com/your_username
git clone github.com/your_username/cosmos-sdk
cd cosmos-sdk
```
Now we'll add the origin Cosmos-SDK as upstream in case some cool feature or module gets merged:
```bash
git remote add upstream github.com/cosmos/cosmos-sdk
git fetch upstream
git rebase upstream/master
```
We will also create a branch dedicated to our module:
```bash
git checkout -b my_new_application
```
We are all set!
## Application design
### Application description

View File

@ -1,32 +0,0 @@
## Setup
### Prerequisites
- Have [go](https://golang.org/dl/) and [git](https://git-scm.com/downloads) installed
- Don't forget to set your `PATH` and `GOPATH`
### Setup work environment
Go to the [Cosmos-SDK repo](https://githum.com/cosmos/cosmos-sdk) and fork it. Then open a terminal and:
```bash
cd $GOPATH/src/github.com/your_username
git clone github.com/your_username/cosmos-sdk
cd cosmos-sdk
```
Now we'll add the origin Cosmos-SDK as upstream in case some cool feature or module gets merged:
```bash
git remote add upstream github.com/cosmos/cosmos-sdk
git fetch upstream
git rebase upstream/master
```
We will also create a branch dedicated to our module:
```bash
git checkout -b my_new_application
```
We are all set!

View File

@ -0,0 +1,316 @@
# Simple Governance Module
## Module initialization
First, let us go into the module's folder and create a folder for our module.
```bash
cd x/
mkdir simple_governance
cd simple_governance
mkdir -p client/cli client/rest
touch client/cli/simple_governance.go client/rest/simple_governance.go errors.go handler.go handler_test.go keeper_keys.go keeper_test.go keeper.go test_common.go test_types.go types.go codec.go
```
Let us start by adding the files we will need. Your module's folder should look something like that:
```
x
└─── simple_governance
├─── client
│ ├─── cli
│ │ └─── simple_governance.go
│ └─── rest
│ └─── simple_governance.go
├─── errors.go
├─── handler.go
├─── keeper_keys.go
├─── keeper.go
├─── types.go
└─── codec.go
```
Let us go into the detail of each of these files.
## Types
**File: [`x/simple_governance/types.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/x/simple_governance/types.go)**
In this file, we define the custom types for our module. This includes the types from the [State](app-design.md#State) section and the custom message types defined in the [Messages](app-design#Messages) section.
For each new type that is not a message, it is possible to add methods that make sense in the context of the application. In our case, we will implement an `updateTally` function to easily update the tally of a given proposal as vote messages come in.
Messages are a bit different. They implement the `Message` interface defined in the SDK's `types` folder. Here are the methods you need to implement when you define a custom message type:
- `Type()`: This function returns the name of our module's route. When messages are processed by the application, they are routed using the string returned by the `Type()` method.
- `GetSignBytes()`: Returns the byte representation of the message. It is used to sign the message.
- `GetSigners()`: Returns address(es) of the signer(s).
- `ValidateBasic()`: This function is used to discard obviously invalid messages. It is called at the beginning of `runTx()` in the baseapp file. If `ValidateBasic()` does not return `nil`, the app stops running the transaction.
- `Get()`: A basic getter, returns some property of the message.
- `String()`: Returns a human-readable version of the message
For our simple governance messages, this means:
- `Type()` will return `"simpleGov"`
- For `SubmitProposalMsg`, we need to make sure that the attributes are not empty and that the deposit is both valid and positive. Note that this is only basic validation, we will therefore not check in this method that the sender has sufficient funds to pay for the deposit
- For `VoteMsg`, we check that the address and option are valid and that the proposalID is not negative.
- As for other methods, less customization is required. You can check the code to see a standard way of implementing these.
## Keeper
**File: [`x/simple_governance/keeper.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/x/simple_governance/keeper.go)**
### Short intro to keepers
`Keepers` are a module abstraction that handle reading/writing to the module store. This is a practical implementation of the **Object Capability Model** for Cosmos.
As module developers, we have to define keepers to interact with our module's store(s) not only from within our module, but also from other modules. When another module wants to access one of our module's store(s), a keeper for this store has to be passed to it at the application level. In practice, it will look like that:
```go
// in app.go
// instanciate keepers
keeperA = moduleA.newKeeper(app.moduleAStoreKey)
keeperB = moduleB.newKeeper(app.moduleBStoreKey)
// pass instance of keeperA to handler of module B
app.Router().
AddRoute("moduleA", moduleA.NewHandler(keeperA)).
AddRoute("moduleB", moduleB.NewHandler(keeperB, keeperA)) // Here module B can access one of module A's store via the keeperA instance
```
`KeeperA` grants a set of capabilities to the handler of module B. When developing a module, it is good practice to think about the sensitivity of the different capabilities that can be granted through keepers. For example, some module may need to read and write to module A's main store, while others only need to read it. If a module has multiple stores, then some keepers could grant access to all of them, while others would only grant access to specific sub-stores. It is the job of the module developer to make sure it is easy for application developers to instanciate a keeper with the right capabilities. Of course, the handler of a module will most likely get an unrestricted instance of that module's keeper.
### Store for our app
Before we delve into the keeper itself, let us see what objects we need to store in our governance sub-store, and how to index them.
- `Proposals` will be indexed by `'proposals'|<proposalID>`.
- `Votes` (`Yes`, `No`, `Abstain`) will be indexed by `'proposals'|<proposalID>|'votes'|<voterAddress>`.
Notice the quote mark on `'proposals'` and `'votes'`. They indicate that these are constant keywords. So, for example, the option casted by voter with address `0x01` on proposal `0101` will be stored at index `'proposals'|0101|'votes'|0x01`.
These keywords are used to faciliate range queries. Range queries (TODO: Link to formal spec) allow developer to query a subspace of the store, and return an iterator. They are made possible by the nice properties of the [IAVL+ tree](https://github.com/tendermint/iavl) that is used in the background. In practice, this means that it is possible to store and query a Key-Value pair in O(1), while still being able to iterate over a given subspace of Key-Value pairs. For example, we can query all the addresses that voted on a given proposal, along with their votes, by calling `rangeQuery(SimpleGovStore, <proposalID|'addresses'>)`.
### Keepers for our app
In our case, we only have one store to access, the `SimpleGov` store. We will need to set and get values inside this store via our keeper. However, these two actions do not have the same impact in terms of security. While there should no problem in granting read access to our store to other modules, write access is way more sensitive. So ideally application developers should be able to create either a governance mapper that can only get values from the store, or one that can both get and set values. To this end, we will introduce two keepers: `Keeper` and `KeeperRead`. When application developers create their application, they will be able to decide which of our module's keeper to use.
Now, let us try to think about which keeper from **external** modules our module's keepers need access to.
Each proposal requires a deposit. This means our module needs to be able to both read and write to the module that handles tokens, which is the `bank` module. We also need to be able to determine the voting power of each voter based on their stake. To this end, we need read access to the store of the `staking` module. However, we don't need write access to this store. We should therefore indicate that in our module, and the application developer should be careful to only pass a read-only keeper of the `staking` module to our module's handler.
With all that in mind, we can define the structure of our `Keeper`:
```go
type Keeper struct {
SimpleGov sdk.StoreKey // Key to our module's store
cdc *codec.Codec // Codec to encore/decode structs
ck bank.Keeper // Needed to handle deposits. This module onlyl requires read/writes to Atom balance
sm stake.Keeper // Needed to compute voting power. This module only needs read access to the staking store.
codespace sdk.CodespaceType // Reserves space for error codes
}
```
And the structure of our `KeeperRead`:
```go
type KeeperRead struct {
Keeper
}
```
`KeeperRead` will inherit all methods from `Keeper`, except those that we override. These will be the methods that perform writes to the store.
### Functions and Methods
The first function we have to create is the constructor.
```go
func NewKeeper(SimpleGov sdk.StoreKey, ck bank.Keeper, sm stake.Keeper, codespace sdk.CodespaceType) Keeper
```
This function is called from the main [`app.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/app/app.go) file to instanciate a new `Keeper`. A similar function exits for `KeeperRead`.
```go
func NewKeeperRead(SimpleGov sdk.StoreKey, ck bank.Keeper, sm stake.Keeper, codespace sdk.CodespaceType) KeeperRead
```
Depending on the needs of the application and its modules, either `Keeper`, `KeeperRead`, or both, will be instanciated at application level.
*Note: Both the `Keeper` type name and `NewKeeper()` function's name are standard names used in every module. It is no requirement to follow this standard, but doing so can facilitate the life of application developers*
Now, let us describe the methods we need for our module's `Keeper`. For the full implementation, please refer to `keeper.go`.
- `GetProposal`: Get a `Proposal` given a `proposalID`. Proposals need to be decoded from `byte` before they can be read.
- `SetProposal`: Set a `Proposal` at index `'proposals'|<proposalID>`. Proposals need to be encoded to `byte` before they can be stored.
- `NewProposalID`: A function to generate a new unique `proposalID`.
- `GetVote`: Get a vote `Option` given a `proposalID` and a `voterAddress`.
- `SetVote`: Set a vote `Option` given a `proposalID` and a `voterAddress`.
- Proposal Queue methods: These methods implement a standard proposal queue to store `Proposals` on a First-In First-Out basis. It is used to tally the votes at the end of the voting period.
The last thing that needs to be done is to override certain methods for the `KeeperRead` type. `KeeperRead` should not have write access to the stores. Therefore, we will override the methods `SetProposal()`, `SetVote()` and `NewProposalID()`, as well as `setProposalQueue()` from the Proposal Queue's methods. For `KeeperRead`, these methods will just throw an error.
*Note: If you look at the code, you'll notice that the context `ctx` is a parameter of many of the methods. The context `ctx` provides useful information on the current state such as the current block height and allows the keeper `k` to access the `KVStore`. You can check all the methods of `ctx` [here](https://github.com/cosmos/cosmos-sdk/blob/develop/types/context.go#L144-L168)*.
## Handler
**File: [`x/simple_governance/handler.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/x/simple_governance/handler.go)**
### Constructor and core handlers
Handlers implement the core logic of the state-machine. When a transaction is routed from the app to the module, it is run by the `handler` function.
In practice, one `handler` will be implemented for each message of the module. In our case, we have two message types. We will therefore need two `handler` functions. We will also need a constructor function to route the message to the correct `handler`:
```go
func NewHandler(k Keeper) sdk.Handler {
return func(ctx sdk.Context, msg sdk.Msg) sdk.Result {
switch msg := msg.(type) {
case SubmitProposalMsg:
return handleSubmitProposalMsg(ctx, k, msg)
case VoteMsg:
return handleVoteMsg(ctx, k, msg)
default:
errMsg := "Unrecognized gov Msg type: " + reflect.TypeOf(msg).Name()
return sdk.ErrUnknownRequest(errMsg).Result()
}
}
}
```
The messages are routed to the appropriate `handler` depending on their type. For our simple governance module, we only have two `handlers`, that correspond to our two message types. They have similar signatures:
```go
func handleSubmitProposalMsg(ctx sdk.Context, k Keeper, msg SubmitProposalMsg) sdk.Result
```
Let us take a look at the parameters of this function:
- The context `ctx` to access the stores.
- The keeper `k` allows the handler to read and write from the different stores, including the module's store (`SimpleGovernance` in our case) and all the stores from other modules that the keeper `k` has been granted an access to (`stake` and `bank` in our case).
- The message `msg` that holds all the information provided by the sender of the transaction.
The function returns a `Result` that is returned to the application. It contains several useful information such as the amount of `Gas` for this transaction and wether the message was succesfully processed or not. At this point, we exit the boundaries of our simple governance module and go back to root application level. The `Result` will differ from application to application. You can check the `sdk.Result` type directly [here](https://github.com/cosmos/cosmos-sdk/blob/develop/types/result.go) for more info.
### BeginBlocker and EndBlocker
In contrast to most smart-contracts platform, it is possible to perform automatic (i.e. not triggered by a transaction sent by an end-user) execution of logic in Cosmos-SDK applications.
This automatic execution of code takes place in the `BeginBlock` and `EndBlock` functions that are called at the beginning and at the end of every block. They are powerful tools, but it is important for application developers to be careful with them. For example, it is crutial that developers control the amount of computing that happens in these functions, as expensive computation could delay the block time, and never-ending loop freeze the chain altogether.
`BeginBlock` and `EndBlock` are composable functions, meaning that each module can implement its own `BeginBlock` and `EndBlock` logic. When needed, `BeginBlock` and `EndBlock` logic is implemented in the module's `handler`. Here is the standard way to proceed for `EndBlock` (`BeginBlock` follows the exact same pattern):
```go
func NewEndBlocker(k Keeper) sdk.EndBlocker {
return func(ctx sdk.Context, req abci.RequestEndBlock) (res abci.ResponseEndBlock) {
err := checkProposal(ctx, k)
if err != nil {
panic(err)
}
return
}
}
```
Do not forget that each module need to declare its `BeginBlock` and `EndBlock` constructors at application level. See the [Application - Bridging it all together](app-structure.md).
For the purpose of our simple governance application, we will use `EndBlock` to automatically tally the results of the vote. Here are the different steps that will be performed:
1. Get the oldest proposal from the `ProposalProcessingQueue`
2. Check if the `CurrentBlock` is the block at which the voting period for this proposal ends. If Yes, go to 3.. If no, exit.
3. Check if proposal is accepted or rejected. Update the proposal status.
4. Pop the proposal from the `ProposalProcessingQueue` and go back to 1.
Let us perform a quick safety analysis on this process.
- The loop will not run forever because the number of proposals in `ProposalProcessingQueue` is finite
- The computation should not be too expensive because tallying of individual proposals is not expensive and the number of proposals is expected be relatively low. That is because proposals require a `Deposit` to be accepted. `MinDeposit` should be high enough so that we don't have too many `Proposals` in the queue.
- In the eventuality that the application becomes so successful that the `ProposalProcessingQueue` ends up containing so many proposals that the blockchain starts slowing down, the module should be modified to mitigate the situation. One clever way of doing it is to cap the number of iteration per individual `EndBlock` at `MaxIteration`. This way, tallying will be spread over many blocks if the number of proposals is too important and block time should remain stable. This would require to modify the current check `if (CurrentBlock == Proposal.SubmitBlock + VotingPeriod)` to `if (CurrentBlock > Proposal.SubmitBlock + VotingPeriod) AND (Proposal.Status == ProposalStatusActive)`.
## Codec
**File: [`x/simple_governance/codec.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/x/simple_governance/codec.go)**
The `codec.go` file allows developers to register the concrete message types of their module into the codec. In our case, we have two messages to declare:
```go
func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterConcrete(SubmitProposalMsg{}, "simple_governance/SubmitProposalMsg", nil)
cdc.RegisterConcrete(VoteMsg{}, "simple_governance/VoteMsg", nil)
}
```
Don't forget to call this function in `app.go` (see [Application - Bridging it all together](app-structure.md)) for more).
## Errors
**File: [`x/simple_governance/errors.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/x/simple_governance/errors.go)**
The `error.go` file allows us to define custom error messages for our module. Declaring errors should be relatively similar in all modules. You can look in the `error.go` file directly for a concrete example. The code is self-explanatory.
Note that the errors of our module inherit from the `sdk.Error` interface and therefore possess the method `Result()`. This method is useful when there is an error in the `handler` and an error has to be returned in place of an actual result.
## Command-Line Interface
**File: [`x/simple_governance/client/cli/simple_governance.go`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/x/simple_governance/client/cli/simple_governance.go)**
Go in the `cli` folder and create a `simple_governance.go` file. This is where we will define the commands for our module.
The CLI builds on top of [Cobra](https://github.com/spf13/cobra). Here is the schema to build a command on top of Cobra:
```go
// Declare flags
const(
Flag = "flag"
...
)
// Main command function. One function for each command.
func Command(codec *codec.Codec) *cobra.Command {
// Create the command to return
command := &cobra.Command{
Use: "actual command",
Short: "Short description",
Run: func(cmd *cobra.Command, args []string) error {
// Actual function to run when command is used
},
}
// Add flags to the command
command.Flags().<Type>(FlagNameConstant, <example_value>, "<Description>")
return command
}
```
## Rest API
**File: [`x/simple_governance/client/rest/simple_governance.goo`](https://github.com/cosmos/cosmos-sdk/blob/fedekunze/module_tutorial/examples/simpleGov/x/simple_governance/client/rest/simple_governance.go)**
The Rest Server, also called [Light-Client Daemon (LCD)](https://github.com/cosmos/cosmos-sdk/tree/master/client/lcd), provides support for **HTTP queries**.
________________________________________________________
USER INTERFACE <=======> REST SERVER <=======> FULL-NODE
________________________________________________________
It allows end-users that do not want to run full-nodes themselves to interract with the chain. The LCD can be configured to perform **Light-Client verification** via the flag `--trust-node`, which can be set to `true` or `false`.
- If *light-client verification* is enabled, the Rest Server acts as a light-client and needs to be run on the end-user's machine. It allows them to interract with the chain in a trustless way without having to store the whole chain locally.
- If *light-client verification* is disabled, the Rest Server acts as a simple relayer for HTTP calls. In this setting, the Rest server needs not be run on the end-user's machine. Instead, it will probably be run by the same entity that operates the full-node the server connects to. This mode is useful if end-users trust the full-node operator and do not want to store anything locally.
Now, let us define endpoints that will be available for users to query through HTTP requests. These endpoints will be defined in a `simple_governance.go` file stored in the `rest` folder.
| Method | URL | Description |
|--------|---------------------------------|-------------------------------------------------------------|
| GET | /proposals | Range query to get all submitted proposals |
| POST | /proposals | Submit a new proposal |
| GET | /proposals/{id} | Returns a proposal given its ID |
| GET | /proposals/{id}/votes | Range query to get all the votes casted on a given proposal |
| POST | /proposals/{id}/votes | Cast a vote on a given proposal |
| GET | /proposals/{id}/votes/{address} | Returns the vote of a given address on a given proposal |
It is the job of module developers to provide sensible endpoints so that front-end developers and service providers can properly interact with it.
Additionaly, here is a [link](https://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9) for REST APIs best practices.

View File

@ -1,10 +0,0 @@
## Starting your own project
To get started, you just have to follow these simple steps:
1. Clone the [Cosmos-SDK](https://github.com/cosmos/cosmos-sdk/tree/develop)repo
2. Code the modules needed by your application that do not already exist.
3. Create your app directory. In the app main file, import the module you need and instantiate the different stores.
4. Launch your blockchain.
Easy as pie! With the introduction over, let us delve into practice and learn how to code a SDK application with an example.

View File

@ -1,36 +0,0 @@
## Submit a proposal
Uuse the CLI to create a new proposal:
```bash
simplegovcli propose --title="Voting Period update" --description="Should we change the proposal voting period to 3 weeks?" --deposit=300Atoms
```
Or, via a json file:
```bash
simplegovcli propose --proposal="path/to/proposal.json"
```
Where proposal.json contains:
```json
{
"title": "Voting Period Update",
"description": "Should we change the proposal voting period to 3 weeks?",
"type": "Text",
"deposit": "300Atoms"
}
```
Get the details of your newly created proposal:
```bash
simplegovcli proposal 1
```
You can also check all the existing open proposals:
```bash
simplegovcli proposals --active=true
```

View File

@ -216,12 +216,12 @@ We have to solve this simple equation to find the reward R for each validator:
* For the proposer validator:
* The pool obtains `R + R * 5%`: 105 Atoms
* Commission: `105 * 80% * 1%` = 0.84 Atoms
* Validator's reward: `100 * 20% + Commission` = 21.84 Atoms
* Validator's reward: `105 * 20% + Commission` = 21.84 Atoms
* Delegators' rewards: `105 * 80% - Commission` = 83.16 Atoms (each delegator will be able to claim its portion of these rewards in proportion to their stake)
* For each non-proposer validator:
* The pool obtains R: 100 Atoms
* Commission: `100 * 80% * 1%` = 0.8 Atoms
* Validator's reward: `105 * 20% + Commission` = 20.8 Atoms
* Validator's reward: `100 * 20% + Commission` = 20.8 Atoms
* Delegators' rewards: `100 * 80% - Commission` = 79.2 Atoms (each delegator will be able to claim its portion of these rewards in proportion to their stake)
### What are the slashing conditions?

View File

@ -29,7 +29,7 @@ func setGenesis(baseApp *BasecoinApp, accounts ...*types.AppAccount) (types.Gene
// initialize and commit the chain
baseApp.InitChain(abci.RequestInitChain{
Validators: []abci.Validator{}, AppStateBytes: stateBytes,
Validators: []abci.ValidatorUpdate{}, AppStateBytes: stateBytes,
})
baseApp.Commit()
@ -72,7 +72,7 @@ func TestGenesis(t *testing.T) {
// initialize the chain with the expected genesis state
baseApp.InitChain(abci.RequestInitChain{
Validators: []abci.Validator{}, AppStateBytes: stateBytes,
Validators: []abci.ValidatorUpdate{}, AppStateBytes: stateBytes,
})
ctx = baseApp.BaseApp.NewContext(true, abci.Header{})

View File

@ -6,6 +6,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/client/lcd"
_ "github.com/cosmos/cosmos-sdk/client/lcd/statik"
"github.com/cosmos/cosmos-sdk/client/rpc"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/examples/basecoin/app"

View File

@ -33,7 +33,7 @@ func setGenesis(bapp *DemocoinApp, trend string, accs ...auth.BaseAccount) error
}
// Initialize the chain
vals := []abci.Validator{}
vals := []abci.ValidatorUpdate{}
bapp.InitChain(abci.RequestInitChain{Validators: vals, AppStateBytes: stateBytes})
bapp.Commit()

View File

@ -1,8 +1,6 @@
package cli
import (
"os"
"github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/client/context"
@ -24,7 +22,6 @@ func QuizTxCmd(cdc *codec.Codec) *cobra.Command {
txBldr := authtxb.NewTxBuilderFromCLI().WithCodec(cdc)
cliCtx := context.NewCLIContext().
WithCodec(cdc).
WithLogger(os.Stdout).
WithAccountDecoder(authcmd.GetAccountDecoder(cdc))
from, err := cliCtx.GetFromAddress()
@ -49,7 +46,6 @@ func SetTrendTxCmd(cdc *codec.Codec) *cobra.Command {
txBldr := authtxb.NewTxBuilderFromCLI().WithCodec(cdc)
cliCtx := context.NewCLIContext().
WithCodec(cdc).
WithLogger(os.Stdout).
WithAccountDecoder(authcmd.GetAccountDecoder(cdc))
from, err := cliCtx.GetFromAddress()

View File

@ -1,7 +1,6 @@
package cli
import (
"os"
"strconv"
"github.com/cosmos/cosmos-sdk/client/context"
@ -25,7 +24,6 @@ func MineCmd(cdc *codec.Codec) *cobra.Command {
txBldr := authtxb.NewTxBuilderFromCLI().WithCodec(cdc)
cliCtx := context.NewCLIContext().
WithCodec(cdc).
WithLogger(os.Stdout).
WithAccountDecoder(authcmd.GetAccountDecoder(cdc))
from, err := cliCtx.GetFromAddress()

View File

@ -3,7 +3,6 @@ package cli
import (
"encoding/hex"
"fmt"
"os"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/utils"
@ -33,7 +32,6 @@ func BondTxCmd(cdc *codec.Codec) *cobra.Command {
txBldr := authtxb.NewTxBuilderFromCLI().WithCodec(cdc)
cliCtx := context.NewCLIContext().
WithCodec(cdc).
WithLogger(os.Stdout).
WithAccountDecoder(authcmd.GetAccountDecoder(cdc))
from, err := cliCtx.GetFromAddress()
@ -86,8 +84,7 @@ func UnbondTxCmd(cdc *codec.Codec) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
txBldr := authtxb.NewTxBuilderFromCLI().WithCodec(cdc)
cliCtx := context.NewCLIContext().
WithCodec(cdc).
WithLogger(os.Stdout)
WithCodec(cdc)
from, err := cliCtx.GetFromAddress()
if err != nil {

View File

@ -10,6 +10,7 @@ import (
tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands"
cmn "github.com/tendermint/tendermint/libs/common"
"github.com/tendermint/tendermint/node"
"github.com/tendermint/tendermint/p2p"
pvm "github.com/tendermint/tendermint/privval"
"github.com/tendermint/tendermint/proxy"
)
@ -97,10 +98,16 @@ func startInProcess(ctx *Context, appCreator AppCreator) (*node.Node, error) {
return nil, err
}
nodeKey, err := p2p.LoadOrGenNodeKey(cfg.NodeKeyFile())
if err != nil {
return nil, err
}
// create & start tendermint node
tmNode, err := node.NewNode(
cfg,
pvm.LoadOrGenFilePV(cfg.PrivValidatorFile()),
nodeKey,
proxy.NewLocalClientCreator(app),
node.DefaultGenesisDocProviderFunc(cfg),
node.DefaultDBProvider,

View File

@ -1,6 +1,7 @@
package store
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
@ -13,8 +14,8 @@ func newCacheKVStore() CacheKVStore {
return NewCacheKVStore(mem)
}
func keyFmt(i int) []byte { return bz(cmn.Fmt("key%0.8d", i)) }
func valFmt(i int) []byte { return bz(cmn.Fmt("value%0.8d", i)) }
func keyFmt(i int) []byte { return bz(fmt.Sprintf("key%0.8d", i)) }
func valFmt(i int) []byte { return bz(fmt.Sprintf("value%0.8d", i)) }
func TestCacheKVStore(t *testing.T) {
mem := dbStoreAdapter{dbm.NewMemDB()}

View File

@ -14,7 +14,7 @@ func First(st KVStore, start, end []byte) (kv cmn.KVPair, ok bool) {
}
defer iter.Close()
return cmn.KVPair{iter.Key(), iter.Value()}, true
return cmn.KVPair{Key: iter.Key(), Value: iter.Value()}, true
}
// Gets the last item. `end` is exclusive.
@ -22,7 +22,7 @@ func Last(st KVStore, start, end []byte) (kv cmn.KVPair, ok bool) {
iter := st.ReverseIterator(end, start)
if !iter.Valid() {
if v := st.Get(start); v != nil {
return cmn.KVPair{cp(start), cp(v)}, true
return cmn.KVPair{Key: cp(start), Value: cp(v)}, true
}
return kv, false
}
@ -36,5 +36,5 @@ func Last(st KVStore, start, end []byte) (kv cmn.KVPair, ok bool) {
}
}
return cmn.KVPair{iter.Key(), iter.Value()}, true
return cmn.KVPair{Key: iter.Key(), Value: iter.Value()}, true
}

View File

@ -240,7 +240,7 @@ func (st *iavlStore) Query(req abci.RequestQuery) (res abci.ResponseQuery) {
var KVs []KVPair
iterator := sdk.KVStorePrefixIterator(st, subspace)
for ; iterator.Valid(); iterator.Next() {
KVs = append(KVs, KVPair{iterator.Key(), iterator.Value()})
KVs = append(KVs, KVPair{Key: iterator.Key(), Value: iterator.Value()})
}
iterator.Close()
res.Value = cdc.MustMarshalBinary(KVs)
@ -310,7 +310,7 @@ func (iter *iavlIterator) iterateRoutine() {
select {
case <-iter.quitCh:
return true // done with iteration.
case iter.iterCh <- cmn.KVPair{key, value}:
case iter.iterCh <- cmn.KVPair{Key: key, Value: value}:
return false // yay.
}
},

View File

@ -387,12 +387,12 @@ func TestIAVLStoreQuery(t *testing.T) {
ksub := []byte("key")
KVs0 := []KVPair{}
KVs1 := []KVPair{
{k1, v1},
{k2, v2},
{Key: k1, Value: v1},
{Key: k2, Value: v2},
}
KVs2 := []KVPair{
{k1, v3},
{k2, v2},
{Key: k1, Value: v3},
{Key: k2, Value: v2},
}
valExpSubEmpty := cdc.MustMarshalBinary(KVs0)
valExpSub1 := cdc.MustMarshalBinary(KVs1)

View File

@ -12,6 +12,7 @@ INEFFASSIGN = github.com/gordonklaus/ineffassign
MISSPELL = github.com/client9/misspell/cmd/misspell
ERRCHECK = github.com/kisielk/errcheck
UNPARAM = mvdan.cc/unparam
STATIK = github.com/rakyll/statik
DEP_CHECK := $(shell command -v dep 2> /dev/null)
GOLINT_CHECK := $(shell command -v golint 2> /dev/null)
@ -21,6 +22,7 @@ INEFFASSIGN_CHECK := $(shell command -v ineffassign 2> /dev/null)
MISSPELL_CHECK := $(shell command -v misspell 2> /dev/null)
ERRCHECK_CHECK := $(shell command -v errcheck 2> /dev/null)
UNPARAM_CHECK := $(shell command -v unparam 2> /dev/null)
STATIK_CHECK := $(shell command -v statik 2> /dev/null)
check_tools:
ifndef DEP_CHECK
@ -66,6 +68,12 @@ ifndef UNPARAM_CHECK
else
@echo "Found unparam in path."
endif
ifndef STATIK_CHECK
@echo "No statik in path. Install with 'make get_tools'."
else
@echo "Found statik in path."
endif
get_tools:
ifdef DEP_CHECK
@ -74,6 +82,13 @@ else
@echo "Installing dep"
go get -v $(DEP)
endif
ifdef STATIK_CHECK
@echo "Statik is already installed. Run 'make update_tools' to update."
else
@echo "Installing statik"
go version
go get -v $(STATIK)
endif
get_dev_tools:
$(MAKE) get_tools
@ -119,6 +134,12 @@ else
@echo "Installing unparam"
go get -v $(UNPARAM)
endif
ifdef STATIK_CHECK
@echo "statik is already installed. Run 'make update_tools' to update."
else
@echo "Installing statik"
go get -v $(STATIK)
endif
update_tools:
@echo "Updating dep"
@ -140,6 +161,8 @@ update_dev_tools:
go get -u -v $(ERRCHECK)
@echo "Updating unparam"
go get -u -v $(UNPARAM)
@echo "Updating statik"
go get -u -v $(STATIK)
# To avoid unintended conflicts with file names, always add to .PHONY
# unless there is a reason not to.

View File

@ -5,5 +5,6 @@
"Enable": ["golint", "vet", "ineffassign", "unparam", "unconvert", "misspell"],
"Deadline": "500s",
"Vendor": true,
"Cyclo": 11
}
"Cyclo": 11,
"Exclude": ["/usr/lib/go/src/", "client/lcd/statik/statik.go"]
}

View File

@ -10,7 +10,7 @@ import (
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/cosmos/cosmos-sdk/types"
)
)
var invalidStrs = []string{
"",

View File

@ -443,7 +443,7 @@ func BenchmarkCoinsAdditionIntersect(b *testing.B) {
}
}
benchmarkSizes := [][]int{[]int{1, 1}, []int{5, 5}, []int{5, 20}, []int{1, 1000}, []int{2, 1000}}
benchmarkSizes := [][]int{{1, 1}, {5, 5}, {5, 20}, {1, 1000}, {2, 1000}}
for i := 0; i < len(benchmarkSizes); i++ {
sizeA := benchmarkSizes[i][0]
sizeB := benchmarkSizes[i][1]
@ -469,7 +469,7 @@ func BenchmarkCoinsAdditionNoIntersect(b *testing.B) {
}
}
benchmarkSizes := [][]int{[]int{1, 1}, []int{5, 5}, []int{5, 20}, []int{1, 1000}, []int{2, 1000}, []int{1000, 2}}
benchmarkSizes := [][]int{{1, 1}, {5, 5}, {5, 20}, {1, 1000}, {2, 1000}, {1000, 2}}
for i := 0; i < len(benchmarkSizes); i++ {
sizeA := benchmarkSizes[i][0]
sizeB := benchmarkSizes[i][1]

Some files were not shown because too many files have changed in this diff Show More