From 9b10c379f0d3fb75276fd989a67ba4752a562b96 Mon Sep 17 00:00:00 2001 From: Daniel Wedul Date: Thu, 19 May 2022 13:50:15 -0600 Subject: [PATCH] Merge v0.45.4 into PIO 0.45.x (#127) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * check error returned from NewNode (#11624) * docs: Add v0.45.x to docs versions (backport #11613) (#11623) * docs: Update mentions of Starport to Ignite CLI (backport #11612) (#11617) * feat: add (re)delegation getters (backport #11596) (#11615) * feat: add (re)delegation getters (#11596) ### Description This PR adds general helper functions to the `x/staking` module that are used in the Evmos `x/vesting` module and originated from Agoric's custom staking module implementation https://github.com/agoric-labs/cosmos-sdk/blob/4085-true-vesting/x/staking/keeper/delegation.go. - `GetDelegatorUnbonding` - `GetDelegatorBonded` - `IterateDelegatorUnbondingDelegations` - `IterateDelegatorDelegations` - `IterateDelegatorRedelegations` (cherry picked from commit b8270fc9ba2ed95eb691a2395ec28b62d75b82fb) # Conflicts: # CHANGELOG.md # x/staking/keeper/delegation.go * fix RemoveDelegation method conflict * fix CHANGELOG conflict * add new PR in CHANGELOG Co-authored-by: Daniel Burckhardt * feat: add vesting util functions (backport #11652) (#11667) * feat: add vesting util functions (#11652) * feat: add vesting util functions * changelog * revert string deletion * fix build * Update x/auth/vesting/types/period.go Co-authored-by: Aleksandr Bezobchuk Co-authored-by: Aleksandr Bezobchuk Co-authored-by: Marko (cherry picked from commit c6769522789b62908fbe6b918da9aff53fb2f6d7) # Conflicts: # CHANGELOG.md # x/auth/vesting/types/period.go * changelog * Update x/auth/vesting/types/period.go Co-authored-by: Federico Kunze Küllmer <31522760+fedekunze@users.noreply.github.com> Co-authored-by: Federico Kunze Küllmer * chore: v0.45.x bump min go version to 1.17 (#11686) * fix: Add validation on create gentx (backport #11693) (#11698) * fix: Added description of how to run the unsafe-reset-all command in simapp README (#11718) (#11719) * Fix simapp README * Revised review content Co-authored-by: Julien Robert (cherry picked from commit d5e0b86a0736a9346dded9721f4ebbd69fdbd3ca) Co-authored-by: Takahiko Tominaga <57429437+takapi327@users.noreply.github.com> * chore: remove unneeded swagger docs from 0.45 #11745 * fix: data race issues with api.Server (backport #11724) (#11748) * updates (#11750) * updates (#11752) * chore: release notes++ * Add dynamic build tag so this can build on M1 macs. * Change README line endings to dos since that's what they were originally. Co-authored-by: Jorge Hernandez <3452489+jhernandezb@users.noreply.github.com> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com> Co-authored-by: Daniel Burckhardt Co-authored-by: Federico Kunze Küllmer <31522760+fedekunze@users.noreply.github.com> Co-authored-by: Federico Kunze Küllmer Co-authored-by: Aleksandr Bezobchuk Co-authored-by: Takahiko Tominaga <57429437+takapi327@users.noreply.github.com> Co-authored-by: Marko Co-authored-by: Aleksandr Bezobchuk --- .github/workflows/proto-docker.yml | 53 - CHANGELOG.md | 22 +- Makefile | 57 +- README.md | 37 +- RELEASE_NOTES.md | 65 - client/docs/swagger_legacy.yaml | 2127 --------------------------- contrib/images/Makefile | 15 +- contrib/images/simd-dlv/Dockerfile | 22 + contrib/images/simd-dlv/README.md | 37 + contrib/images/simd-dlv/wrapper.sh | 25 + contrib/images/simd-env/Dockerfile | 1 + docker-compose.yml | 54 +- docs/.vuepress/config.js | 12 +- docs/README.md | 6 +- docs/versions | 3 +- server/api/server.go | 17 +- server/start.go | 4 +- simapp/README.md | 2 +- types/coin.go | 8 +- x/auth/vesting/types/period.go | 42 +- x/genutil/client/cli/gentx.go | 4 + x/genutil/client/testutil/suite.go | 175 +-- x/genutil/gentx_test.go | 4 +- x/staking/keeper/delegation.go | 171 ++- x/staking/keeper/delegation_test.go | 11 +- 25 files changed, 508 insertions(+), 2466 deletions(-) delete mode 100644 .github/workflows/proto-docker.yml delete mode 100644 RELEASE_NOTES.md create mode 100644 contrib/images/simd-dlv/Dockerfile create mode 100644 contrib/images/simd-dlv/README.md create mode 100755 contrib/images/simd-dlv/wrapper.sh diff --git a/.github/workflows/proto-docker.yml b/.github/workflows/proto-docker.yml deleted file mode 100644 index e59eeda18bca..000000000000 --- a/.github/workflows/proto-docker.yml +++ /dev/null @@ -1,53 +0,0 @@ -name: Build & Push SDK Proto Builder -on: - pull_request: - push: - branches: - - master - paths: - - "contrib/devtools/dockerfile" - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@master - - name: Prepare - id: prep - run: | - DOCKER_IMAGE=tendermintdev/sdk-proto-gen - VERSION=noop - if [[ $GITHUB_REF == refs/tags/* ]]; then - VERSION=${GITHUB_REF#refs/tags/} - elif [[ $GITHUB_REF == refs/heads/* ]]; then - VERSION=$(echo ${GITHUB_REF#refs/heads/} | sed -r 's#/+#-#g') - if [ "${{ github.event.repository.default_branch }}" = "$VERSION" ]; then - VERSION=latest - fi - fi - TAGS="${DOCKER_IMAGE}:${VERSION}" - echo ::set-output name=tags::${TAGS} - - - name: Set up QEMU - uses: docker/setup-qemu-action@master - with: - platforms: all - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 - - - name: Login to DockerHub - if: ${{ github.event_name != 'pull_request' }} - uses: docker/login-action@v1 - with: - username: ${{ secrets.DOCKERHUBTM_USERNAME }} - password: ${{ secrets.DOCKERHUBTM_TOKEN }} - - - name: Publish to Docker Hub - uses: docker/build-push-action@v2 - with: - context: ./contrib/devtools - file: ./contrib/devtools/dockerfile - platforms: linux/amd64,linux/arm64 - push: ${{ github.event_name != 'pull_request' }} - tags: ${{ steps.prep.outputs.tags }} diff --git a/CHANGELOG.md b/CHANGELOG.md index dd9a0285fc90..b5e2ea6ceb1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,6 +61,19 @@ Ref: https://keepachangelog.com/en/1.0.0/ # Cosmos SDK Releases +## [v0.45.4](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.45.4) - 2022-04-25 + +### Bug Fixes + +* [\#11624](https://github.com/cosmos/cosmos-sdk/pull/11624) Handle the error returned from `NewNode` in the `server` package. +* [\#11724](https://github.com/cosmos/cosmos-sdk/pull/11724) Fix data race issues with `api.Server`. + +### Improvements + +* [\#11693](https://github.com/cosmos/cosmos-sdk/pull/11693) Add validation for gentx cmd. +* [\#11686](https://github.com/cosmos/cosmos-sdk/pull/11686) Update the min required Golang version to `1.17`. +* (x/auth/vesting) [\#11652](https://github.com/cosmos/cosmos-sdk/pull/11652) Add util functions for `Period(s)` + ## [v0.45.3](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.45.3) - 2022-04-12 ### Improvements @@ -84,16 +97,17 @@ Ref: https://keepachangelog.com/en/1.0.0/ * [\#11124](https://github.com/cosmos/cosmos-sdk/pull/11124) Add `GetAllVersions` to application store * (x/auth) [\#10880](https://github.com/cosmos/cosmos-sdk/pull/10880) Added a new query to the tx query service that returns a block with transactions fully decoded. * [#11314](https://github.com/cosmos/cosmos-sdk/pull/11314) Add state rollback command. +* (x/staking) [\#11596](https://github.com/cosmos/cosmos-sdk/pull/11596) Add (re)delegation getters ### Bug Fixes * [\#11354](https://github.com/cosmos/cosmos-sdk/pull/11355) Added missing pagination flag for `bank q total` query. -* [\#11197](https://github.com/cosmos/cosmos-sdk/pull/11197) Signing with multisig now works with multisig address which is not in the keyring. +* [\#11197](https://github.com/cosmos/cosmos-sdk/pull/11197) Signing with multisig now works with multisig address which is not in the keyring. * (client) [\#11283](https://github.com/cosmos/cosmos-sdk/issues/11283) Support multiple keys for tx simulation and setting automatic gas for txs. * (store) [\#11177](https://github.com/cosmos/cosmos-sdk/pull/11177) Update the prune `everything` strategy to store the last two heights. * (store) [\#11117](https://github.com/cosmos/cosmos-sdk/pull/11117) Fix data race in store trace component * (x/authz) [\#11252](https://github.com/cosmos/cosmos-sdk/pull/11252) Allow insufficient funds error for authz simulation -* (crypto) [\#11298](https://github.com/cosmos/cosmos-sdk/pull/11298) Fix cgo secp signature verification and update libscep256k1 library. +* (crypto) [\#11298](https://github.com/cosmos/cosmos-sdk/pull/11298) Fix cgo secp signature verification and update libscep256k1 library. ### Improvements @@ -148,7 +162,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Bug Fixes -* (std/codec) [/#10595](https://github.com/cosmos/cosmos-sdk/pull/10595) Add evidence to std/codec to be able to decode evidence in client interactions. +* (std/codec) [/#10595](https://github.com/cosmos/cosmos-sdk/pull/10595) Add evidence to std/codec to be able to decode evidence in client interactions. * (types) [\#9627](https://github.com/cosmos/cosmos-sdk/pull/9627) Fix nil pointer panic on `NewBigIntFromInt`. * [#10725](https://github.com/cosmos/cosmos-sdk/pull/10725) populate `ctx.ConsensusParams` for begin/end blockers. * [\#9829](https://github.com/cosmos/cosmos-sdk/pull/9829) Fixed Coin denom sorting not being checked during `Balance.Validate` check. Refactored the Validation logic to use `Coins.Validate` for `Balance.Coins` @@ -158,7 +172,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Improvements -* (baseapp) [\#10631](https://github.com/cosmos/cosmos-sdk/pull/10631) Emit ante events even for the failed txs. +* (baseapp) [\#10631](https://github.com/cosmos/cosmos-sdk/pull/10631) Emit ante events even for the failed txs. ### Features diff --git a/Makefile b/Makefile index 8359f574e7f4..e31d297a3ba4 100644 --- a/Makefile +++ b/Makefile @@ -18,7 +18,7 @@ export GO111MODULE = on # process build tags -build_tags = netgo +build_tags = netgo dynamic ifeq ($(LEDGER_ENABLED),true) ifeq ($(OS),Windows_NT) GCCEXE = $(shell where gcc.exe 2> NUL) @@ -109,7 +109,7 @@ BUILD_TARGETS := build install build: BUILD_ARGS=-o $(BUILDDIR)/ build-linux: - GOOS=linux GOARCH=amd64 LEDGER_ENABLED=false $(MAKE) build + GOOS=linux GOARCH=$(if $(findstring aarch64,$(shell uname -m)) || $(findstring arm64,$(shell uname -m)),arm64,amd64) LEDGER_ENABLED=false $(MAKE) build $(BUILD_TARGETS): go.sum $(BUILDDIR)/ go $@ -mod=readonly $(BUILD_FLAGS) $(BUILD_ARGS) ./... @@ -117,33 +117,10 @@ $(BUILD_TARGETS): go.sum $(BUILDDIR)/ $(BUILDDIR)/: mkdir -p $(BUILDDIR)/ -build-simd-all: go.sum - $(DOCKER) rm latest-build || true - $(DOCKER) run --volume=$(CURDIR):/sources:ro \ - --env TARGET_PLATFORMS='linux/amd64 darwin/amd64 linux/arm64 windows/amd64' \ - --env APP=simd \ - --env VERSION=$(VERSION) \ - --env COMMIT=$(COMMIT) \ - --env LEDGER_ENABLED=$(LEDGER_ENABLED) \ - --name latest-build cosmossdk/rbuilder:latest - $(DOCKER) cp -a latest-build:/home/builder/artifacts/ $(CURDIR)/ - -build-simd-linux: go.sum $(BUILDDIR)/ - $(DOCKER) rm latest-build || true - $(DOCKER) run --volume=$(CURDIR):/sources:ro \ - --env TARGET_PLATFORMS='linux/amd64' \ - --env APP=simd \ - --env VERSION=$(VERSION) \ - --env COMMIT=$(COMMIT) \ - --env LEDGER_ENABLED=false \ - --name latest-build cosmossdk/rbuilder:latest - $(DOCKER) cp -a latest-build:/home/builder/artifacts/ $(CURDIR)/ - cp artifacts/simd-*-linux-amd64 $(BUILDDIR)/simd - cosmovisor: $(MAKE) -C cosmovisor cosmovisor -.PHONY: build build-linux build-simd-all build-simd-linux cosmovisor +.PHONY: build build-linux cosmovisor mockgen_cmd=go run github.com/golang/mock/mockgen @@ -484,26 +461,40 @@ proto-update-deps: ### Localnet ### ############################################################################### -# Run a 4-node testnet locally -localnet-start: build-linux localnet-stop - $(if $(shell $(DOCKER) inspect -f '{{ .Id }}' cosmossdk/simd-env 2>/dev/null),$(info found image cosmossdk/simd-env),$(MAKE) -C contrib/images simd-env) - $(DOCKER) run --rm -v $(CURDIR)/localnet:/data cosmossdk/simd-env \ - testnet init-files --v 4 -o /data --starting-ip-address 192.168.10.2 --keyring-backend=test +localnet-build-env: + $(MAKE) -C contrib/images simd-env + +localnet-build-dlv: + $(MAKE) -C contrib/images simd-dlv + +localnet-build-nodes: + $(DOCKER) run --rm -v $(CURDIR)/.testnets:/data cosmossdk/simd \ + testnet init-files --v 4 -o /data --starting-ip-address 192.168.10.2 --keyring-backend=test docker-compose up -d localnet-stop: docker-compose down -.PHONY: localnet-start localnet-stop +# localnet-start will run a 4-node testnet locally. The nodes are +# based off the docker images in: ./contrib/images/simd-env +localnet-start: localnet-stop localnet-build-env localnet-build-nodes + +# localnet-debug will run a 4-node testnet locally in debug mode +# you can read more about the debug mode here: ./contrib/images/simd-dlv/README.md +localnet-debug: localnet-stop localnet-build-dlv localnet-build-nodes + +.PHONY: localnet-start localnet-stop localnet-debug localnet-build-env \ +localnet-build-dlv localnet-build-nodes ############################################################################### ### rosetta ### ############################################################################### -# builds rosetta test data dir + rosetta-data: -docker container rm data_dir_build docker build -t rosetta-ci:latest -f contrib/rosetta/node/Dockerfile . docker run --name data_dir_build -t rosetta-ci:latest sh /rosetta/data.sh docker cp data_dir_build:/tmp/data.tar.gz "$(CURDIR)/contrib/rosetta/node/data.tar.gz" docker container rm data_dir_build + .PHONY: rosetta-data diff --git a/README.md b/README.md index f1574acf2f97..d3d39ebc2f5e 100644 --- a/README.md +++ b/README.md @@ -40,34 +40,45 @@ parent: Lint Satus -The Cosmos-SDK is a framework for building blockchain applications in Golang. -It is being used to build [`Gaia`](https://github.com/cosmos/gaia), the first implementation of the Cosmos Hub. +The Cosmos SDK is a framework for building blockchain applications. [Tendermint Core (BFT Consensus)](https://github.com/tendermint/tendermint) and the Cosmos SDK are written in the Golang programming language. Cosmos SDK is used to build [Gaia](https://github.com/cosmos/gaia), the first implementation of the Cosmos Hub. -**WARNING**: The SDK has mostly stabilized, but we are still making some +**WARNING**: The Cosmos SDK has mostly stabilized, but we are still making some breaking changes. **Note**: Requires [Go 1.17+](https://golang.org/dl/) ## Quick Start -To learn how the SDK works from a high-level perspective, go to the [SDK Intro](./docs/intro/overview.md). +To learn how the Cosmos SDK works from a high-level perspective, see the Cosmos SDK [High-Level Intro](./docs/intro/overview.md). -If you want to get started quickly and learn how to build on top of the SDK, please follow the [SDK Application Tutorial](https://tutorials.cosmos.network/nameservice/tutorial/00-intro.html). You can also fork the tutorial's repository to get started building your own Cosmos SDK application. +If you want to get started quickly and learn how to build on top of Cosmos SDK, visit [Cosmos SDK Tutorials](https://tutorials.cosmos.network). You can also fork the tutorial's repository to get started building your own Cosmos SDK application. -For more, please go to the [Cosmos SDK Docs](./docs/). +For more information, see the [Cosmos SDK Documentation](./docs/). -## Cosmos Hub Mainnet +## Contributing -The Cosmos Hub application, `gaia`, has moved to its [own repository](https://github.com/cosmos/gaia). Go there to join the Cosmos Hub mainnet and more. +See [CONTRIBUTING.md](./CONTRIBUTING.md) for details how to contribute and participate in our [dev calls](./CONTRIBUTING.md#teams-dev-calls). +If you want to follow the updates or learn more about the latest design then join our [Discord](https://discord.com/invite/cosmosnetwork). -## Interblockchain Communication (IBC) +## Tools and Frameworks -The IBC module for the SDK has moved to its [own repository](https://github.com/cosmos/ibc-go). Go there to build and integrate with the IBC module. +The Cosmos ecosystem is vast. We will only make a few notable mentions here. -## Starport ++ [Tools](https://v1.cosmos.network/tools): notable frameworks and modules. ++ [CosmJS](https://github.com/cosmos/cosmjs): the Swiss Army knife to power JavaScript based client solutions. -If you are starting a new app or a new module you can use [Starport](https://github.com/tendermint/starport) to help you get started and speed up development. If you have any questions or find a bug, feel free to open an issue in the repo. +### Cosmos Hub Mainnet + +The Cosmos Hub application, `gaia`, has moved to its own [cosmos/gaia repository](https://github.com/cosmos/gaia). Go there to join the Cosmos Hub mainnet and more. + +### Inter-Blockchain Communication (IBC) + +The IBC module for the Cosmos SDK has moved to its own [cosmos/ibc-go repository](https://github.com/cosmos/ibc-go). Go there to build and integrate with the IBC module. + +### Ignite CLI + +Ignite CLI is the all-in-one platform to build, launch, and maintain any crypto application on a sovereign and secured blockchain. If you are building a new app or a new module, use [Ignite CLI](https://github.com/ignite-hq/cli) to get started and speed up development. ## Disambiguation -This Cosmos-SDK project is not related to the [React-Cosmos](https://github.com/react-cosmos/react-cosmos) project (yet). Many thanks to Evan Coury and Ovidiu (@skidding) for this Github organization name. As per our agreement, this disambiguation notice will stay here. +This Cosmos SDK project is not related to the [React-Cosmos](https://github.com/react-cosmos/react-cosmos) project (yet). Many thanks to Evan Coury and Ovidiu (@skidding) for this Github organization name. As per our agreement, this disambiguation notice will stay here. diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md deleted file mode 100644 index 89b862b68f5d..000000000000 --- a/RELEASE_NOTES.md +++ /dev/null @@ -1,65 +0,0 @@ -# Cosmos SDK v0.44.5 Release Notes - -This release adds the updates from cosmos-sdk upstream v0.44.4 and v0.44.5 to the msg fee and rosetta fixes added into the Provenanced fork at v0.45 - -# Cosmos SDK v0.45.0 Release Notes - -- We now charge gas in two new places: on `.Seek()` even if there are no entries, and for the key length (on top of the value length). -- When block gas limit is exceeded, we consume the maximum gas possible (to charge for the performed computation). We also fixed the bug when the last transaction in a block exceeds the block gas limit, it returns an error result, but the tx is actually committed successfully. - -Finally, a small improvement in gov, we increased the maximum proposal description size from 5k characters to 10k characters. - -### API-Breaking Changes - -- The `BankKeeper` interface has a new `HasSupply` method to ensure that input denom actually exists on chain. -- The `CommitMultiStore` interface contains a new `SetIAVLCacheSize` method for a configurable IAVL cache size. -- `AuthKeeper` interface in `x/auth` now includes a function `HasAccount`. -- Moved `TestMnemonic` from `testutil` package to `testdata`. - - -Finally, when using the `SetOrder*` functions in simapp, e.g. `SetOrderBeginBlocker`, we now require that all modules be present in the function arguments, or else the node panics at startup. We also added a new `SetOrderMigration` function to set the order of running module migrations. - -### Improvements - -- Speedup improvements (e.g. speedup iterator creation after delete heavy workloads, lower allocations for `Coins.String()`, reduce RAM/CPU usage inside store/cachekv's `Store.Write`) are included in this release. -- Upgrade Rosetta to v0.7.0 . -- Support in-place migration ordering. -- Copied and updated `server.GenerateCoinKey` and `server.GenerateServerCoinKey` functions to the `testutil` package. These functions in `server` package are marked deprecated and will be removed in the next release. In the `testutil.GenerateServerCoinKey` version we added support for custom mnemonics in in-process testing network. - -See our [CHANGELOG](./CHANGELOG.md) for the exhaustive list of all changes, or a full [commit diff](https://github.com/cosmos/cosmos-sdk/compare/v0.44.5...v0.45.0). - -# Cosmos SDK v0.45.2 Release Notes - -This release introduces bug fixes and improvements on the Cosmos SDK v0.45 series: - -Highlights: - -- Add hooks to allow modules to add things to state-sync. Please see [PR #10961](https://github.com/cosmos/cosmos-sdk/pull/10961) for more information. -- Register [`EIP191`](https://eips.ethereum.org/EIPS/eip-191) as an available `SignMode` for chains to use. Please note that in v0.45.2, the Cosmos SDK does **not** support EIP-191 out of the box. But if your chain wants to integrate EIP-191, it's possible to do so by passing a `TxConfig` with your own sign mode handler which implements EIP-191, using the new provided `authtx.NewTxConfigWithHandler` function. -- Add a new `rollback` CLI command to perform a state rollback by one block. Read more in [PR #11179](https://github.com/cosmos/cosmos-sdk/pull/11179). -- Some new queries were added: - - x/authz: `GrantsByGrantee` to query grants by grantee, - - x/bank: `SpendableBalances` to query an account's total (paginated) spendable balances, - - TxService: `GetBlockWithTxs` to fetch a block along with all its transactions, decoded. -- Some bug fixes, such as: - - Update the prune `everything` strategy to store the last two heights. - - Fix data race in store trace component. - - Fix cgo secp signature verification and update libscep256k1 library. - -See the [Cosmos SDK v0.45.2 Changelog](https://github.com/cosmos/cosmos-sdk/blob/v0.45.2/CHANGELOG.md) for the exhaustive list of all changes and check other fixes in the 0.45.x release series. - -**Full Commit History**: https://github.com/cosmos/cosmos-sdk/compare/v0.45.1...v0.45.2 - -# Cosmos SDK v0.45.3 Release Notes - -This release introduces a Tendermint dependency update to v0.34.19 which -itself includes two bug fixes related to consensus. See the full changelog from -v0.34.17-v0.34.19 [here](https://github.com/tendermint/tendermint/blob/v0.34.19/CHANGELOG.md#v0.34.19). - -In addition, it includes a change to `ScheduleUpgrade` to allow upgrades without -requiring a governance proposal process. - -See the [Cosmos SDK v0.45.3 Changelog](https://github.com/cosmos/cosmos-sdk/blob/v0.45.3/CHANGELOG.md) -for the exhaustive list of all changes. - -**Full Commit History**: https://github.com/cosmos/cosmos-sdk/compare/v0.45.2...v0.45.3 diff --git a/client/docs/swagger_legacy.yaml b/client/docs/swagger_legacy.yaml index dfd2f8a90c79..cd718851741e 100644 --- a/client/docs/swagger_legacy.yaml +++ b/client/docs/swagger_legacy.yaml @@ -9,25 +9,6 @@ tags: description: Search, encode, or broadcast transactions. - name: Tendermint RPC description: Tendermint APIs, such as query blocks, transactions and validatorset - - name: Auth - description: Authenticate accounts - - name: Bank - description: Create and broadcast transactions - - name: Staking - description: Stake module APIs - - name: Governance - description: Governance module APIs - - name: Slashing - description: Slashing module APIs - - name: Distribution - description: Fee distribution module APIs - - name: Supply - description: Supply module APIs - - name: version - - name: Mint - description: Minting module APIs - - name: Misc - description: Query app version schemes: - https host: api.cosmos.network @@ -217,1767 +198,6 @@ paths: description: Invalid height 500: description: Server internal error - /txs/{hash}: - get: - deprecated: true - summary: Get a Tx by hash - tags: - - Transactions - description: Retrieve a transaction using its hash. - produces: - - application/json - parameters: - - in: path - name: hash - description: Tx hash - required: true - type: string - x-example: BCBE20E8D46758B96AE5883B792858296AC06E51435490FBDCAE25A72B3CC76B - responses: - 200: - description: Tx with the provided hash - schema: - $ref: "#/definitions/TxQuery" - 500: - description: Internal Server Error - /txs: - get: - deprecated: true - tags: - - Transactions - summary: Search transactions - description: Search transactions by events. - produces: - - application/json - parameters: - - in: query - name: message.action - type: string - description: "transaction events such as 'message.action=send' which results in the following endpoint: 'GET /txs?message.action=send'. note that each module documents its own events. look for xx_events.md in the corresponding cosmos-sdk/docs/spec directory" - x-example: "send" - - in: query - name: message.sender - type: string - description: "transaction tags with sender: 'GET /txs?message.action=send&message.sender=cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv'" - x-example: "cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv" - - in: query - name: page - description: Page number - type: integer - x-example: 1 - - in: query - name: limit - description: Maximum number of items per page - type: integer - x-example: 1 - - in: query - name: tx.minheight - type: integer - description: "transactions on blocks with height greater or equal this value" - x-example: 25 - - in: query - name: tx.maxheight - type: integer - description: "transactions on blocks with height less than or equal this value" - x-example: 800000 - responses: - 200: - description: All txs matching the provided events - schema: - $ref: "#/definitions/PaginatedQueryTxs" - 400: - description: Invalid search events - 500: - description: Internal Server Error - post: - tags: - - Transactions - summary: Broadcast a signed tx - description: Broadcast a signed tx to a full node - consumes: - - application/json - produces: - - application/json - parameters: - - in: body - name: txBroadcast - description: The tx must be a signed StdTx. The supported broadcast modes include `"block"`(return after tx commit), `"sync"`(return afer CheckTx) and `"async"`(return right away). - required: true - schema: - type: object - properties: - tx: - $ref: "#/definitions/StdTx" - mode: - type: string - example: block - responses: - 200: - description: Tx broadcasting result - schema: - $ref: "#/definitions/BroadcastTxCommitResult" - 500: - description: Internal Server Error - /txs/encode: - post: - deprecated: true - tags: - - Transactions - summary: Encode a transaction to the Amino wire format - description: Encode a transaction (signed or not) from JSON to base64-encoded Amino serialized bytes - consumes: - - application/json - produces: - - application/json - parameters: - - in: body - name: tx - description: The tx to encode - required: true - schema: - type: object - properties: - tx: - $ref: "#/definitions/StdTx" - responses: - 200: - description: The tx was successfully decoded and re-encoded - schema: - type: object - properties: - tx: - type: string - example: The base64-encoded Amino-serialized bytes for the tx - 400: - description: The tx was malformated - 500: - description: Server internal error - /txs/decode: - post: - deprecated: true - tags: - - Transactions - summary: Decode a transaction from the Amino wire format - description: Decode a transaction (signed or not) from base64-encoded Amino serialized bytes to JSON - consumes: - - application/json - produces: - - application/json - parameters: - - in: body - name: tx - description: The tx to decode - required: true - schema: - type: object - properties: - tx: - type: string - example: SvBiXe4KPqijYZoKFFHEzJ8c2HPAfv2EFUcIhx0yPagwEhTy0vPA+GGhCEslKXa4Af0uB+mfShoMCgVzdGFrZRIDMTAwEgQQwJoM - responses: - 200: - description: The tx was successfully decoded - schema: - $ref: "#/definitions/StdTx" - 400: - description: The tx was malformated - 500: - description: Server internal error - /bank/balances/{address}: - get: - deprecated: true - summary: Get the account balances - tags: - - Bank - produces: - - application/json - parameters: - - in: path - name: address - description: Account address in bech32 format - required: true - type: string - x-example: cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv - responses: - 200: - description: Account balances - schema: - type: array - items: - $ref: "#/definitions/Coin" - 500: - description: Server internal error - /bank/accounts/{address}/transfers: - post: - deprecated: true - summary: Send coins from one account to another - tags: - - Bank - consumes: - - application/json - produces: - - application/json - parameters: - - in: path - name: address - description: Account address in bech32 format - required: true - type: string - x-example: cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv - - in: body - name: account - description: The sender and tx information - required: true - schema: - type: object - properties: - base_req: - $ref: "#/definitions/BaseReq" - amount: - type: array - items: - $ref: "#/definitions/Coin" - responses: - 202: - description: Tx was succesfully generated - schema: - $ref: "#/definitions/StdTx" - 400: - description: Invalid request - 500: - description: Server internal error - /bank/total: - get: - deprecated: true - summary: Total supply of coins in the chain - tags: - - Bank - produces: - - application/json - responses: - 200: - description: OK - schema: - $ref: "#/definitions/Supply" - 500: - description: Internal Server Error - /bank/total/{denomination}: - parameters: - - in: path - name: denomination - description: Coin denomination - required: true - type: string - x-example: uatom - get: - deprecated: true - summary: Total supply of a single coin denomination - tags: - - Bank - produces: - - application/json - responses: - 200: - description: OK - schema: - type: string - 400: - description: Invalid coin denomination - 500: - description: Internal Server Error - /auth/accounts/{address}: - get: - deprecated: true - summary: Get the account information on blockchain - tags: - - Auth - produces: - - application/json - parameters: - - in: path - name: address - description: Account address - required: true - type: string - x-example: cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv - responses: - 200: - description: Account information on the blockchain - schema: - type: object - properties: - type: - type: string - value: - type: object - properties: - account_number: - type: string - address: - type: string - coins: - type: array - items: - $ref: "#/definitions/Coin" - public_key: - $ref: "#/definitions/PublicKey" - sequence: - type: string - 500: - description: Server internel error - /staking/delegators/{delegatorAddr}/delegations: - parameters: - - in: path - name: delegatorAddr - description: Bech32 AccAddress of Delegator - required: true - type: string - x-example: cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv - get: - deprecated: true - summary: Get all delegations from a delegator - tags: - - Staking - produces: - - application/json - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/Delegation" - 400: - description: Invalid delegator address - 500: - description: Internal Server Error - post: - summary: Submit delegation - parameters: - - in: body - name: delegation - description: Delegate an amount of liquid coins to a validator - schema: - type: object - properties: - base_req: - $ref: "#/definitions/BaseReq" - delegator_address: - $ref: "#/definitions/Address" - validator_address: - $ref: "#/definitions/ValidatorAddress" - amount: - $ref: "#/definitions/Coin" - tags: - - Staking - consumes: - - application/json - produces: - - application/json - responses: - 200: - description: OK - schema: - $ref: "#/definitions/StdTx" - 400: - description: Invalid delegator address or delegation request body - 401: - description: Key password is wrong - 500: - description: Internal Server Error - /staking/delegators/{delegatorAddr}/delegations/{validatorAddr}: - parameters: - - in: path - name: delegatorAddr - description: Bech32 AccAddress of Delegator - required: true - type: string - x-example: cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv - - in: path - name: validatorAddr - description: Bech32 OperatorAddress of validator - required: true - type: string - x-example: cosmosvaloper16xyempempp92x9hyzz9wrgf94r6j9h5f2w4n2l - get: - deprecated: true - summary: Query the current delegation between a delegator and a validator - tags: - - Staking - produces: - - application/json - responses: - 200: - description: OK - schema: - $ref: "#/definitions/Delegation" - 400: - description: Invalid delegator address or validator address - 500: - description: Internal Server Error - /staking/delegators/{delegatorAddr}/unbonding_delegations: - parameters: - - in: path - name: delegatorAddr - description: Bech32 AccAddress of Delegator - required: true - type: string - x-example: cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv - get: - deprecated: true - summary: Get all unbonding delegations from a delegator - tags: - - Staking - produces: - - application/json - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/UnbondingDelegation" - 400: - description: Invalid delegator address - 500: - description: Internal Server Error - post: - summary: Submit an unbonding delegation - parameters: - - in: body - name: delegation - description: Unbond an amount of bonded shares from a validator - schema: - type: object - properties: - base_req: - $ref: "#/definitions/BaseReq" - delegator_address: - $ref: "#/definitions/Address" - validator_address: - $ref: "#/definitions/ValidatorAddress" - amount: - $ref: "#/definitions/Coin" - tags: - - Staking - consumes: - - application/json - produces: - - application/json - responses: - 200: - description: OK - schema: - $ref: "#/definitions/StdTx" - 400: - description: Invalid delegator address or unbonding delegation request body - 401: - description: Key password is wrong - 500: - description: Internal Server Error - /staking/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr}: - parameters: - - in: path - name: delegatorAddr - description: Bech32 AccAddress of Delegator - required: true - type: string - x-example: cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv - - in: path - name: validatorAddr - description: Bech32 OperatorAddress of validator - required: true - type: string - x-example: cosmosvaloper16xyempempp92x9hyzz9wrgf94r6j9h5f2w4n2l - get: - deprecated: true - summary: Query all unbonding delegations between a delegator and a validator - tags: - - Staking - produces: - - application/json - responses: - 200: - description: OK - schema: - $ref: "#/definitions/UnbondingDelegationPair" - 400: - description: Invalid delegator address or validator address - 500: - description: Internal Server Error - /staking/redelegations: - parameters: - - in: query - name: delegator - description: Bech32 AccAddress of Delegator - required: false - type: string - - in: query - name: validator_from - description: Bech32 ValAddress of SrcValidator - required: false - type: string - - in: query - name: validator_to - description: Bech32 ValAddress of DstValidator - required: false - type: string - get: - deprecated: true - summary: Get all redelegations (filter by query params) - tags: - - Staking - produces: - - application/json - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/Redelegation" - 500: - description: Internal Server Error - /staking/delegators/{delegatorAddr}/redelegations: - parameters: - - in: path - name: delegatorAddr - description: Bech32 AccAddress of Delegator - required: true - type: string - x-example: cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv - post: - deprecated: true - summary: Submit a redelegation - parameters: - - in: body - name: delegation - description: The sender and tx information - schema: - type: object - properties: - base_req: - $ref: "#/definitions/BaseReq" - delegator_address: - $ref: "#/definitions/Address" - validator_src_addressess: - $ref: "#/definitions/ValidatorAddress" - validator_dst_address: - $ref: "#/definitions/ValidatorAddress" - shares: - type: string - example: "100" - tags: - - Staking - consumes: - - application/json - produces: - - application/json - responses: - 200: - description: Tx was succesfully generated - schema: - $ref: "#/definitions/StdTx" - 400: - description: Invalid delegator address or redelegation request body - 500: - description: Internal Server Error - /staking/delegators/{delegatorAddr}/validators: - parameters: - - in: path - name: delegatorAddr - description: Bech32 AccAddress of Delegator - required: true - type: string - x-example: cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv - get: - deprecated: true - summary: Query all validators that a delegator is bonded to - tags: - - Staking - produces: - - application/json - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/Validator" - 400: - description: Invalid delegator address - 500: - description: Internal Server Error - /staking/delegators/{delegatorAddr}/validators/{validatorAddr}: - parameters: - - in: path - name: delegatorAddr - description: Bech32 AccAddress of Delegator - required: true - type: string - x-example: cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv - - in: path - name: validatorAddr - description: Bech32 ValAddress of Delegator - required: true - type: string - x-example: cosmosvaloper16xyempempp92x9hyzz9wrgf94r6j9h5f2w4n2l - get: - deprecated: true - summary: Query a validator that a delegator is bonded to - tags: - - Staking - produces: - - application/json - responses: - 200: - description: OK - schema: - $ref: "#/definitions/Validator" - 400: - description: Invalid delegator address or validator address - 500: - description: Internal Server Error - /staking/validators: - get: - deprecated: true - summary: Get all validator candidates. By default it returns only the bonded validators. - parameters: - - in: query - name: status - type: string - description: The validator bond status. Must be either 'bonded', 'unbonded', or 'unbonding'. - x-example: bonded - - in: query - name: page - description: The page number. - type: integer - x-example: 1 - - in: query - name: limit - description: The maximum number of items per page. - type: integer - x-example: 1 - tags: - - Staking - produces: - - application/json - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/Validator" - 500: - description: Internal Server Error - /staking/validators/{validatorAddr}: - parameters: - - in: path - name: validatorAddr - description: Bech32 OperatorAddress of validator - required: true - type: string - x-example: cosmosvaloper16xyempempp92x9hyzz9wrgf94r6j9h5f2w4n2l - get: - deprecated: true - summary: Query the information from a single validator - tags: - - Staking - produces: - - application/json - responses: - 200: - description: OK - schema: - $ref: "#/definitions/Validator" - 400: - description: Invalid validator address - 500: - description: Internal Server Error - /staking/validators/{validatorAddr}/delegations: - parameters: - - in: path - name: validatorAddr - description: Bech32 OperatorAddress of validator - required: true - type: string - x-example: cosmosvaloper16xyempempp92x9hyzz9wrgf94r6j9h5f2w4n2l - get: - deprecated: true - summary: Get all delegations from a validator - tags: - - Staking - produces: - - application/json - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/Delegation" - 400: - description: Invalid validator address - 500: - description: Internal Server Error - /staking/validators/{validatorAddr}/unbonding_delegations: - parameters: - - in: path - name: validatorAddr - description: Bech32 OperatorAddress of validator - required: true - type: string - x-example: cosmosvaloper16xyempempp92x9hyzz9wrgf94r6j9h5f2w4n2l - get: - deprecated: true - summary: Get all unbonding delegations from a validator - tags: - - Staking - produces: - - application/json - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/UnbondingDelegation" - 400: - description: Invalid validator address - 500: - description: Internal Server Error - /staking/pool: - get: - deprecated: true - summary: Get the current state of the staking pool - tags: - - Staking - produces: - - application/json - responses: - 200: - description: OK - schema: - type: object - properties: - loose_tokens: - type: string - bonded_tokens: - type: string - inflation_last_time: - type: string - inflation: - type: string - date_last_commission_reset: - type: string - prev_bonded_shares: - type: string - 500: - description: Internal Server Error - /staking/parameters: - get: - deprecated: true - summary: Get the current staking parameter values - tags: - - Staking - produces: - - application/json - responses: - 200: - description: OK - schema: - type: object - properties: - inflation_rate_change: - type: string - inflation_max: - type: string - inflation_min: - type: string - goal_bonded: - type: string - unbonding_time: - type: string - max_validators: - type: integer - bond_denom: - type: string - 500: - description: Internal Server Error - # TODO: We need to either fix this route when the validator is not found or add a slashed validator in the contract tests - # /slashing/validators/{validatorPubKey}/signing_info: - # get: - # summary: Get sign info of given validator - # description: Get sign info of given validator - # produces: - # - application/json - # tags: - # - Slashing - # parameters: - # - type: string - # description: Bech32 validator public key - # name: validatorPubKey - # required: true - # in: path - # x-example: cosmosvalconspub1zcjduepq0vu2zgkgk49efa0nqwzndanq5m4c7pa3u4apz4g2r9gspqg6g9cs3k9cuf - # responses: - # 200: - # description: OK - # schema: - # $ref: "#/definitions/SigningInfo" - # 400: - # description: Invalid validator public key - # 500: - # description: Internal Server Error - /slashing/signing_infos: - get: - deprecated: true - summary: Get sign info of given all validators - description: Get sign info of all validators - produces: - - application/json - tags: - - Slashing - parameters: - - in: query - name: page - description: Page number - type: integer - required: true - x-example: 1 - - in: query - name: limit - description: Maximum number of items per page - type: integer - required: true - x-example: 5 - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/SigningInfo" - 400: - description: Invalid validator public key for one of the validators - 500: - description: Internal Server Error - /slashing/validators/{validatorAddr}/unjail: - post: - deprecated: true - summary: Unjail a jailed validator - description: Send transaction to unjail a jailed validator - consumes: - - application/json - produces: - - application/json - tags: - - Slashing - parameters: - - type: string - description: Bech32 validator address - name: validatorAddr - required: true - in: path - x-example: cosmosvaloper16xyempempp92x9hyzz9wrgf94r6j9h5f2w4n2l - - description: "" - name: UnjailBody - in: body - required: true - schema: - type: object - properties: - base_req: - $ref: "#/definitions/StdTx" - responses: - 200: - description: Tx was succesfully generated - schema: - $ref: "#/definitions/StdTx" - 400: - description: Invalid validator address or base_req - 500: - description: Internal Server Error - /slashing/parameters: - get: - deprecated: true - summary: Get the current slashing parameters - tags: - - Slashing - produces: - - application/json - responses: - 200: - description: OK - schema: - type: object - properties: - max_evidence_age: - type: string - signed_blocks_window: - type: string - min_signed_per_window: - type: string - double_sign_unbond_duration: - type: string - downtime_unbond_duration: - type: string - slash_fraction_double_sign: - type: string - slash_fraction_downtime: - type: string - 500: - description: Internal Server Error - /gov/proposals: - post: - deprecated: true - summary: Submit a proposal - description: Send transaction to submit a proposal - consumes: - - application/json - produces: - - application/json - tags: - - Governance - parameters: - - description: valid value of `"proposal_type"` can be `"text"`, `"parameter_change"`, `"software_upgrade"` - name: post_proposal_body - in: body - required: true - schema: - type: object - properties: - base_req: - $ref: "#/definitions/BaseReq" - title: - type: string - description: - type: string - proposal_type: - type: string - example: "text" - proposer: - $ref: "#/definitions/Address" - initial_deposit: - type: array - items: - $ref: "#/definitions/Coin" - responses: - 200: - description: Tx was succesfully generated - schema: - $ref: "#/definitions/StdTx" - 400: - description: Invalid proposal body - 500: - description: Internal Server Error - get: - deprecated: true - summary: Query proposals - description: Query proposals information with parameters - produces: - - application/json - tags: - - Governance - parameters: - - in: query - name: voter - description: voter address - required: false - type: string - - in: query - name: depositor - description: depositor address - required: false - type: string - - in: query - name: status - description: proposal status, valid values can be `"deposit_period"`, `"voting_period"`, `"passed"`, `"rejected"` - required: false - type: string - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/TextProposal" - 400: - description: Invalid query parameters - 500: - description: Internal Server Error - /gov/proposals/param_change: - post: - deprecated: true - summary: Generate a parameter change proposal transaction - description: Generate a parameter change proposal transaction - consumes: - - application/json - produces: - - application/json - tags: - - Governance - parameters: - - description: The parameter change proposal body that contains all parameter changes - name: post_proposal_body - in: body - required: true - schema: - type: object - properties: - base_req: - $ref: "#/definitions/BaseReq" - title: - type: string - x-example: "Param Change" - description: - type: string - x-example: "Update max validators" - proposer: - $ref: "#/definitions/Address" - deposit: - type: array - items: - $ref: "#/definitions/Coin" - changes: - type: array - items: - $ref: "#/definitions/ParamChange" - responses: - 200: - description: The transaction was succesfully generated - schema: - $ref: "#/definitions/StdTx" - 400: - description: Invalid proposal body - 500: - description: Internal Server Error - /gov/proposals/{proposalId}: - get: - deprecated: true - summary: Query a proposal - description: Query a proposal by id - produces: - - application/json - tags: - - Governance - parameters: - - type: string - name: proposalId - required: true - in: path - x-example: "2" - responses: - 200: - description: OK - schema: - $ref: "#/definitions/TextProposal" - 400: - description: Invalid proposal id - 500: - description: Internal Server Error - /gov/proposals/{proposalId}/proposer: - get: - deprecated: true - summary: Query proposer - description: Query for the proposer for a proposal - produces: - - application/json - tags: - - Governance - parameters: - - type: string - name: proposalId - required: true - in: path - x-example: "2" - responses: - 200: - description: OK - schema: - $ref: "#/definitions/Proposer" - 400: - description: Invalid proposal ID - 500: - description: Internal Server Error - /gov/proposals/{proposalId}/deposits: - get: - deprecated: true - summary: Query deposits - description: Query deposits by proposalId - produces: - - application/json - tags: - - Governance - parameters: - - type: string - name: proposalId - required: true - in: path - x-example: "2" - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/Deposit" - 400: - description: Invalid proposal id - 500: - description: Internal Server Error - post: - deprecated: true - summary: Deposit tokens to a proposal - description: Send transaction to deposit tokens to a proposal - consumes: - - application/json - produces: - - application/json - tags: - - Governance - parameters: - - type: string - description: proposal id - name: proposalId - required: true - in: path - x-example: "2" - - description: "" - name: post_deposit_body - in: body - required: true - schema: - type: object - properties: - base_req: - $ref: "#/definitions/BaseReq" - depositor: - $ref: "#/definitions/Address" - amount: - type: array - items: - $ref: "#/definitions/Coin" - responses: - 200: - description: OK - schema: - $ref: "#/definitions/StdTx" - 400: - description: Invalid proposal id or deposit body - 401: - description: Key password is wrong - 500: - description: Internal Server Error - /gov/proposals/{proposalId}/deposits/{depositor}: - get: - deprecated: true - summary: Query deposit - description: Query deposit by proposalId and depositor address - produces: - - application/json - tags: - - Governance - parameters: - - type: string - description: proposal id - name: proposalId - required: true - in: path - x-example: "2" - - type: string - description: Bech32 depositor address - name: depositor - required: true - in: path - x-example: cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv - responses: - 200: - description: OK - schema: - $ref: "#/definitions/Deposit" - 400: - description: Invalid proposal id or depositor address - 404: - description: Found no deposit - 500: - description: Internal Server Error - /gov/proposals/{proposalId}/votes: - get: - deprecated: true - summary: Query voters - description: Query voters information by proposalId - produces: - - application/json - tags: - - Governance - parameters: - - type: string - description: proposal id - name: proposalId - required: true - in: path - x-example: "2" - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/Vote" - 400: - description: Invalid proposal id - 500: - description: Internal Server Error - post: - deprecated: true - summary: Vote a proposal - description: Send transaction to vote a proposal - consumes: - - application/json - produces: - - application/json - tags: - - Governance - parameters: - - type: string - description: proposal id - name: proposalId - required: true - in: path - x-example: "2" - - description: valid value of `"option"` field can be `"yes"`, `"no"`, `"no_with_veto"` and `"abstain"` - name: post_vote_body - in: body - required: true - schema: - type: object - properties: - base_req: - $ref: "#/definitions/BaseReq" - voter: - $ref: "#/definitions/Address" - option: - type: string - example: "yes" - responses: - 200: - description: OK - schema: - $ref: "#/definitions/StdTx" - 400: - description: Invalid proposal id or vote body - 401: - description: Key password is wrong - 500: - description: Internal Server Error - /gov/proposals/{proposalId}/votes/{voter}: - get: - deprecated: true - summary: Query vote - description: Query vote information by proposal Id and voter address - produces: - - application/json - tags: - - Governance - parameters: - - type: string - description: proposal id - name: proposalId - required: true - in: path - x-example: "2" - - type: string - description: Bech32 voter address - name: voter - required: true - in: path - x-example: cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv - responses: - 200: - description: OK - schema: - $ref: "#/definitions/Vote" - 400: - description: Invalid proposal id or voter address - 404: - description: Found no vote - 500: - description: Internal Server Error - /gov/proposals/{proposalId}/tally: - get: - deprecated: true - summary: Get a proposal's tally result at the current time - description: Gets a proposal's tally result at the current time. If the proposal is pending deposits (i.e status 'DepositPeriod') it returns an empty tally result. - produces: - - application/json - tags: - - Governance - parameters: - - type: string - description: proposal id - name: proposalId - required: true - in: path - x-example: "2" - responses: - 200: - description: OK - schema: - $ref: "#/definitions/TallyResult" - 400: - description: Invalid proposal id - 500: - description: Internal Server Error - /gov/parameters/deposit: - get: - deprecated: true - summary: Query governance deposit parameters - description: Query governance deposit parameters. The max_deposit_period units are in nanoseconds. - produces: - - application/json - tags: - - Governance - responses: - 200: - description: OK - schema: - type: object - properties: - min_deposit: - type: array - items: - $ref: "#/definitions/Coin" - max_deposit_period: - type: string - example: "86400000000000" - 400: - description: is not a valid query request path - 404: - description: Found no deposit parameters - 500: - description: Internal Server Error - /gov/parameters/tallying: - get: - deprecated: true - summary: Query governance tally parameters - description: Query governance tally parameters - produces: - - application/json - tags: - - Governance - responses: - 200: - description: OK - schema: - properties: - threshold: - type: string - example: "0.5000000000" - veto: - type: string - example: "0.3340000000" - governance_penalty: - type: string - example: "0.0100000000" - 400: - description: is not a valid query request path - 404: - description: Found no tally parameters - 500: - description: Internal Server Error - /gov/parameters/voting: - get: - deprecated: true - summary: Query governance voting parameters - description: Query governance voting parameters. The voting_period units are in nanoseconds. - produces: - - application/json - tags: - - Governance - responses: - 200: - description: OK - schema: - properties: - voting_period: - type: string - example: "86400000000000" - 400: - description: is not a valid query request path - 404: - description: Found no voting parameters - 500: - description: Internal Server Error - /distribution/delegators/{delegatorAddr}/rewards: - parameters: - - in: path - name: delegatorAddr - description: Bech32 AccAddress of Delegator - required: true - type: string - x-example: cosmos167w96tdvmazakdwkw2u57227eduula2cy572lf - get: - deprecated: true - summary: Get the total rewards balance from all delegations - description: Get the sum of all the rewards earned by delegations by a single delegator - produces: - - application/json - tags: - - Distribution - responses: - 200: - description: OK - schema: - $ref: "#/definitions/DelegatorTotalRewards" - 400: - description: Invalid delegator address - 500: - description: Internal Server Error - post: - deprecated: true - summary: Withdraw all the delegator's delegation rewards - description: Withdraw all the delegator's delegation rewards - tags: - - Distribution - consumes: - - application/json - produces: - - application/json - parameters: - - in: body - name: Withdraw request body - schema: - properties: - base_req: - $ref: "#/definitions/BaseReq" - responses: - 200: - description: OK - schema: - $ref: "#/definitions/StdTx" - 400: - description: Invalid delegator address - 401: - description: Key password is wrong - 500: - description: Internal Server Error - /distribution/delegators/{delegatorAddr}/rewards/{validatorAddr}: - parameters: - - in: path - name: delegatorAddr - description: Bech32 AccAddress of Delegator - required: true - type: string - x-example: cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv - - in: path - name: validatorAddr - description: Bech32 OperatorAddress of validator - required: true - type: string - x-example: cosmosvaloper16xyempempp92x9hyzz9wrgf94r6j9h5f2w4n2l - get: - deprecated: true - summary: Query a delegation reward - description: Query a single delegation reward by a delegator - tags: - - Distribution - produces: - - application/json - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/Coin" - 400: - description: Invalid delegator address - 500: - description: Internal Server Error - post: - deprecated: true - summary: Withdraw a delegation reward - description: Withdraw a delegator's delegation reward from a single validator - tags: - - Distribution - consumes: - - application/json - produces: - - application/json - parameters: - - in: body - name: Withdraw request body - schema: - properties: - base_req: - $ref: "#/definitions/BaseReq" - responses: - 200: - description: OK - schema: - $ref: "#/definitions/StdTx" - 400: - description: Invalid delegator address or delegation body - 401: - description: Key password is wrong - 500: - description: Internal Server Error - /distribution/delegators/{delegatorAddr}/withdraw_address: - parameters: - - in: path - name: delegatorAddr - description: Bech32 AccAddress of Delegator - required: true - type: string - x-example: cosmos167w96tdvmazakdwkw2u57227eduula2cy572lf - get: - deprecated: true - summary: Get the rewards withdrawal address - description: Get the delegations' rewards withdrawal address. This is the address in which the user will receive the reward funds - tags: - - Distribution - produces: - - application/json - responses: - 200: - description: OK - schema: - $ref: "#/definitions/Address" - 400: - description: Invalid delegator address - 500: - description: Internal Server Error - post: - deprecated: true - summary: Replace the rewards withdrawal address - description: Replace the delegations' rewards withdrawal address for a new one. - tags: - - Distribution - consumes: - - application/json - produces: - - application/json - parameters: - - in: body - name: Withdraw request body - schema: - properties: - base_req: - $ref: "#/definitions/BaseReq" - withdraw_address: - $ref: "#/definitions/Address" - responses: - 200: - description: OK - schema: - $ref: "#/definitions/StdTx" - 400: - description: Invalid delegator or withdraw address - 401: - description: Key password is wrong - 500: - description: Internal Server Error - /distribution/validators/{validatorAddr}: - parameters: - - in: path - name: validatorAddr - description: Bech32 OperatorAddress of validator - required: true - type: string - x-example: cosmosvaloper16xyempempp92x9hyzz9wrgf94r6j9h5f2w4n2l - get: - deprecated: true - summary: Validator distribution information - description: Query the distribution information of a single validator - tags: - - Distribution - produces: - - application/json - responses: - 200: - description: OK - schema: - $ref: "#/definitions/ValidatorDistInfo" - 400: - description: Invalid validator address - 500: - description: Internal Server Error - /distribution/validators/{validatorAddr}/outstanding_rewards: - parameters: - - in: path - name: validatorAddr - description: Bech32 OperatorAddress of validator - required: true - type: string - x-example: cosmosvaloper16xyempempp92x9hyzz9wrgf94r6j9h5f2w4n2l - get: - deprecated: true - summary: Fee distribution outstanding rewards of a single validator - tags: - - Distribution - produces: - - application/json - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/Coin" - 500: - description: Internal Server Error - /distribution/validators/{validatorAddr}/rewards: - parameters: - - in: path - name: validatorAddr - description: Bech32 OperatorAddress of validator - required: true - type: string - x-example: cosmosvaloper16xyempempp92x9hyzz9wrgf94r6j9h5f2w4n2l - get: - deprecated: true - summary: Commission and self-delegation rewards of a single validator - description: Query the commission and self-delegation rewards of validator. - tags: - - Distribution - produces: - - application/json - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/Coin" - 400: - description: Invalid validator address - 500: - description: Internal Server Error - post: - deprecated: true - summary: Withdraw the validator's rewards - description: Withdraw the validator's self-delegation and commissions rewards - tags: - - Distribution - consumes: - - application/json - produces: - - application/json - parameters: - - in: body - name: Withdraw request body - schema: - properties: - base_req: - $ref: "#/definitions/BaseReq" - responses: - 200: - description: OK - schema: - $ref: "#/definitions/StdTx" - 400: - description: Invalid validator address - 401: - description: Key password is wrong - 500: - description: Internal Server Error - /distribution/community_pool: - get: - deprecated: true - summary: Community pool parameters - tags: - - Distribution - produces: - - application/json - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/Coin" - 500: - description: Internal Server Error - /distribution/parameters: - get: - deprecated: true - summary: Fee distribution parameters - tags: - - Distribution - produces: - - application/json - responses: - 200: - description: OK - schema: - properties: - base_proposer_reward: - type: string - bonus_proposer_reward: - type: string - community_tax: - type: string - 500: - description: Internal Server Error - /minting/parameters: - get: - deprecated: true - summary: Minting module parameters - tags: - - Mint - produces: - - application/json - responses: - 200: - description: OK - schema: - properties: - mint_denom: - type: string - inflation_rate_change: - type: string - inflation_max: - type: string - inflation_min: - type: string - goal_bonded: - type: string - blocks_per_year: - type: string - 500: - description: Internal Server Error - /minting/inflation: - get: - deprecated: true - summary: Current minting inflation value - tags: - - Mint - produces: - - application/json - responses: - 200: - description: OK - schema: - type: string - 500: - description: Internal Server Error - /minting/annual-provisions: - get: - deprecated: true - summary: Current minting annual provisions value - tags: - - Mint - produces: - - application/json - responses: - 200: - description: OK - schema: - type: string - 500: - description: Internal Server Error definitions: CheckTxResult: type: object @@ -2037,17 +257,6 @@ definitions: 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: @@ -2077,93 +286,6 @@ definitions: Hash: type: string example: EE5F3404034C524501629B56E0DDC38FAD651F04 - TxQuery: - type: object - properties: - hash: - type: string - example: "D085138D913993919295FF4B0A9107F1F2CDE0D37A87CE0644E217CBF3B49656" - height: - type: number - example: 368 - tx: - $ref: "#/definitions/StdTx" - result: - type: object - properties: - log: - type: string - gas_wanted: - type: string - example: "200000" - gas_used: - type: string - example: "26354" - tags: - type: array - items: - $ref: "#/definitions/KVPair" - PaginatedQueryTxs: - type: object - properties: - total_count: - type: number - example: 1 - count: - type: number - example: 1 - page_number: - type: number - example: 1 - page_total: - type: number - example: 1 - limit: - type: number - example: 30 - txs: - type: array - items: - $ref: "#/definitions/TxQuery" - StdTx: - type: object - properties: - msg: - type: array - items: - $ref: "#/definitions/Msg" - fee: - type: object - properties: - gas: - type: string - amount: - type: array - items: - $ref: "#/definitions/Coin" - memo: - type: string - signature: - type: object - properties: - signature: - type: string - example: MEUCIQD02fsDPra8MtbRsyB1w7bqTM55Wu138zQbFcWx4+CFyAIge5WNPfKIuvzBZ69MyqHsqD8S1IwiEp+iUb6VSdtlpgY= - pub_key: - type: object - properties: - type: - type: string - example: "tendermint/PubKeySecp256k1" - value: - type: string - example: "Avz04VhtKJh8ACCVzlI8aTosGy0ikFXKIVHQ3jKMrosH" - account_number: - type: string - example: "0" - sequence: - type: string - example: "0" BlockID: type: object properties: @@ -2281,26 +403,6 @@ definitions: $ref: "#/definitions/BlockID" block: $ref: "#/definitions/Block" - DelegationDelegatorReward: - type: object - properties: - validator_address: - $ref: "#/definitions/ValidatorAddress" - reward: - type: array - items: - $ref: "#/definitions/Coin" - DelegatorTotalRewards: - type: object - properties: - rewards: - type: array - items: - $ref: "#/definitions/DelegationDelegatorReward" - total: - type: array - items: - $ref: "#/definitions/Coin" BaseReq: type: object properties: @@ -2348,214 +450,6 @@ definitions: proposer_priority: type: string example: "1000" - TextProposal: - type: object - properties: - proposal_id: - type: integer - title: - type: string - description: - type: string - proposal_type: - type: string - proposal_status: - type: string - final_tally_result: - $ref: "#/definitions/TallyResult" - submit_time: - type: string - total_deposit: - type: array - items: - $ref: "#/definitions/Coin" - voting_start_time: - type: string - Proposer: - type: object - properties: - proposal_id: - type: string - proposer: - type: string - Deposit: - type: object - properties: - amount: - type: array - items: - $ref: "#/definitions/Coin" - proposal_id: - type: string - depositor: - $ref: "#/definitions/Address" - TallyResult: - type: object - properties: - yes: - type: string - example: "0.0000000000" - abstain: - type: string - example: "0.0000000000" - no: - type: string - example: "0.0000000000" - no_with_veto: - type: string - example: "0.0000000000" - Vote: - type: object - properties: - voter: - type: string - proposal_id: - type: string - option: - type: string - Validator: - type: object - properties: - operator_address: - $ref: "#/definitions/ValidatorAddress" - consensus_pubkey: - type: string - example: cosmosvalconspub1zcjduepq0vu2zgkgk49efa0nqwzndanq5m4c7pa3u4apz4g2r9gspqg6g9cs3k9cuf - jailed: - type: boolean - status: - type: integer - tokens: - type: string - delegator_shares: - type: string - description: - type: object - properties: - moniker: - type: string - identity: - type: string - website: - type: string - security_contact: - type: string - details: - type: string - bond_height: - type: string - example: "0" - bond_intra_tx_counter: - type: integer - example: 0 - unbonding_height: - type: string - example: "0" - unbonding_time: - type: string - example: "1970-01-01T00:00:00Z" - commission: - type: object - properties: - rate: - type: string - example: "0" - max_rate: - type: string - example: "0" - max_change_rate: - type: string - example: "0" - update_time: - type: string - example: "1970-01-01T00:00:00Z" - Delegation: - type: object - properties: - delegator_address: - type: string - validator_address: - type: string - shares: - type: string - balance: - $ref: "#/definitions/Coin" - UnbondingDelegationPair: - type: object - properties: - delegator_address: - type: string - validator_address: - type: string - entries: - type: array - items: - $ref: "#/definitions/UnbondingEntries" - UnbondingEntries: - type: object - properties: - initial_balance: - type: string - balance: - type: string - creation_height: - type: string - min_time: - type: string - UnbondingDelegation: - type: object - properties: - delegator_address: - type: string - validator_address: - type: string - initial_balance: - type: string - balance: - type: string - creation_height: - type: integer - min_time: - type: integer - Redelegation: - type: object - properties: - delegator_address: - type: string - validator_src_address: - type: string - validator_dst_address: - type: string - entries: - type: array - items: - $ref: "#/definitions/Redelegation" - RedelegationEntry: - type: object - properties: - creation_height: - type: integer - completion_time: - type: integer - initial_balance: - type: string - balance: - type: string - shares_dst: - type: string - ValidatorDistInfo: - type: object - properties: - operator_address: - $ref: "#/definitions/ValidatorAddress" - self_bond_rewards: - type: array - items: - $ref: "#/definitions/Coin" - val_commission: - type: array - items: - $ref: "#/definitions/Coin" PublicKey: type: object properties: @@ -2574,24 +468,3 @@ definitions: type: string missed_blocks_counter: type: string - ParamChange: - type: object - properties: - subspace: - type: string - example: "staking" - key: - type: string - example: "MaxValidators" - subkey: - type: string - example: "" - value: - type: object - Supply: - type: object - properties: - total: - type: array - items: - $ref: "#/definitions/Coin" diff --git a/contrib/images/Makefile b/contrib/images/Makefile index 03d3f8be42e5..0c9364155113 100644 --- a/contrib/images/Makefile +++ b/contrib/images/Makefile @@ -1,7 +1,14 @@ all: simd-env -simd-env: - docker build --tag cosmossdk/simd-env -f simd-env/Dockerfile \ - $(shell git rev-parse --show-toplevel) +simd-env: simd-rmi + docker build --tag cosmossdk/simd -f simd-env/Dockerfile \ + $(shell git rev-parse --show-toplevel) -.PHONY: all simd-env +simd-dlv: simd-rmi + docker build --tag cosmossdk/simd -f simd-dlv/Dockerfile \ + $(shell git rev-parse --show-toplevel) + +simd-rmi: + docker rmi cosmossdk/simd 2>/dev/null; true + +.PHONY: all simd-env simd-dlv simd-rmi \ No newline at end of file diff --git a/contrib/images/simd-dlv/Dockerfile b/contrib/images/simd-dlv/Dockerfile new file mode 100644 index 000000000000..9d15d621d761 --- /dev/null +++ b/contrib/images/simd-dlv/Dockerfile @@ -0,0 +1,22 @@ +FROM golang:1.17-alpine AS build +RUN apk add build-base git linux-headers libc-dev +RUN go install github.com/go-delve/delve/cmd/dlv@latest +WORKDIR /work +COPY go.mod go.sum /work/ +RUN go mod download +COPY ./ /work +RUN LEDGER_ENABLED=false make COSMOS_BUILD_OPTIONS="debug,nostrip" clean build + +FROM alpine:3.14 AS run +RUN apk add bash curl jq +COPY contrib/images/simd-dlv/wrapper.sh /usr/bin/wrapper.sh + +VOLUME /simd +COPY --from=build /work/build/simd /simd/ +COPY --from=build /go/bin/dlv /usr/local/bin +WORKDIR /simd + +EXPOSE 26656 26657 2345 +ENTRYPOINT ["/usr/bin/wrapper.sh"] +CMD ["start", "--log_format", "plain"] +STOPSIGNAL SIGTERM diff --git a/contrib/images/simd-dlv/README.md b/contrib/images/simd-dlv/README.md new file mode 100644 index 000000000000..dcca3cde5c8b --- /dev/null +++ b/contrib/images/simd-dlv/README.md @@ -0,0 +1,37 @@ +# Remote Debugging with go-delve + +[Delve](https://github.com/go-delve/delve) is a debugger for the Go programming language. The goal of the project is to provide a simple, full featured debugging tool for Go. Delve should be easy to invoke and easy to use. Chances are if you're using a debugger, things aren't going your way. With that in mind, Delve should stay out of your way as much as possible. + +## Use-case + +Cosmos-SDK provides you with a local network to bootstrap a chain in your machine, but how does one debug a node or module? + +If we start a single node, we won't be able to debug transactions as the machine will be in bootstrapping phase trying to find peers to connect too, thats why we need to start a local network. + +But the current `localnet-start` does not provide us with debugging tools so that's why there is a different image for debugging a local network, that is to avoid any issues in the future were debugging won't be needed. + +Both `simd-env` and `simd-dlv` work and run the same, except that `simd-dlv` uses `go-delve` to run the binaries. + +## How to use + +The command to start a local network in debug mode is: + +```shell +# make localnet-debug +``` + +The command to stop the local network and destroy its containers is: + +```shell +# make localnet-stop +``` + +__note: this works the same for both `localnet-start` and `localnet-debug`__ + +Now, by default only `simdnode0` is run in debug mode, but you can run any of the other nodes in debug mode by changing the `DEBUG` environment variable to `1` in `docker-compose.yml`. + +## How to connect + +Delve will open a port on `2345` for `simdnode0` and it will increment for each of the other nodes that have `DEBUG` set to `1`. + +You can connect to the debugging server either through [GoLand IDE](https://www.jetbrains.com/help/go/attach-to-running-go-processes-with-debugger.html) or you can use [delve cli](https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_connect.md) command. diff --git a/contrib/images/simd-dlv/wrapper.sh b/contrib/images/simd-dlv/wrapper.sh new file mode 100755 index 000000000000..a1187ea7ec78 --- /dev/null +++ b/contrib/images/simd-dlv/wrapper.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env sh +set -euo pipefail +set -x + +DEBUG=${DEBUG:-0} +BINARY=/simd/${BINARY:-simd} +ID=${ID:-0} +LOG=${LOG:-simd.log} + +if ! [ -f "${BINARY}" ]; then + echo "The binary $(basename "${BINARY}") cannot be found. Please add the binary to the shared folder. Please use the BINARY environment variable if the name of the binary is not 'simd'" + exit 1 +fi + +export SIMDHOME="/data/node${ID}/simd" + +if [ "$DEBUG" -eq 1 ]; then + dlv --listen=:2345 --continue --headless=true --api-version=2 --accept-multiclient exec "${BINARY}" -- --home "${SIMDHOME}" "$@" +elif [ "$DEBUG" -eq 1 ] && [ -d "$(dirname "${SIMDHOME}"/"${LOG}")" ]; then + dlv --listen=:2345 --continue --headless=true --api-version=2 --accept-multiclient exec "${BINARY}" -- --home "${SIMDHOME}" "$@" | tee "${SIMDHOME}/${LOG}" +elif [ -d "$(dirname "${SIMDHOME}"/"${LOG}")" ]; then + "${BINARY}" --home "${SIMDHOME}" "$@" | tee "${SIMDHOME}/${LOG}" +else + "${BINARY}" --home "${SIMDHOME}" "$@" +fi \ No newline at end of file diff --git a/contrib/images/simd-env/Dockerfile b/contrib/images/simd-env/Dockerfile index dd5d2761c267..7c5fcf7644b4 100644 --- a/contrib/images/simd-env/Dockerfile +++ b/contrib/images/simd-env/Dockerfile @@ -2,6 +2,7 @@ FROM golang:1.17-alpine AS build RUN apk add build-base git linux-headers WORKDIR /work COPY go.mod go.sum /work/ + RUN go mod download COPY ./ /work RUN LEDGER_ENABLED=false make clean build diff --git a/docker-compose.yml b/docker-compose.yml index a5ef517e547a..13851c894e9f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -3,64 +3,88 @@ version: "3" services: simdnode0: container_name: simdnode0 - image: "cosmossdk/simd-env" + image: "cosmossdk/simd" + environment: + - DEBUG=1 + - ID=0 + - LOG=${LOG:-simd.log} + cap_add: + - SYS_PTRACE + security_opt: + - seccomp:unconfined ports: - "26656-26657:26656-26657" - "1317:1317" - "9090:9090" - environment: - - ID=0 - - LOG=${LOG:-simd.log} + - "2345:2345" volumes: - - ./localnet:/data:Z + - ./.testnets:/data:Z networks: localnet: ipv4_address: 192.168.10.2 simdnode1: container_name: simdnode1 - image: "cosmossdk/simd-env" + image: "cosmossdk/simd" + environment: + - DEBUG=0 + - ID=1 + - LOG=${LOG:-simd.log} + cap_add: + - SYS_PTRACE + security_opt: + - seccomp:unconfined ports: - "26666-26667:26656-26657" - "1318:1317" - "9091:9090" - environment: - - ID=1 - - LOG=${LOG:-simd.log} + - "2346:2345" volumes: - - ./localnet:/data:Z + - ./.testnets:/data:Z networks: localnet: ipv4_address: 192.168.10.3 simdnode2: container_name: simdnode2 - image: "cosmossdk/simd-env" + image: "cosmossdk/simd" environment: + - DEBUG=0 - ID=2 - LOG=${LOG:-simd.log} + cap_add: + - SYS_PTRACE + security_opt: + - seccomp:unconfined ports: - "26676-26677:26656-26657" - "1319:1317" - "9092:9090" + - "2347:2345" volumes: - - ./localnet:/data:Z + - ./.testnets:/data:Z networks: localnet: ipv4_address: 192.168.10.4 simdnode3: container_name: simdnode3 - image: "cosmossdk/simd-env" + image: "cosmossdk/simd" environment: + - DEBUG=0 - ID=3 - LOG=${LOG:-simd.log} + cap_add: + - SYS_PTRACE + security_opt: + - seccomp:unconfined ports: - "26686-26687:26656-26657" - "1320:1317" - "9093:9090" + - "2348:2345" volumes: - - ./localnet:/data:Z + - ./.testnets:/data:Z networks: localnet: ipv4_address: 192.168.10.5 @@ -71,4 +95,4 @@ networks: ipam: driver: default config: - - subnet: 192.168.10.0/16 + - subnet: 192.168.10.0/25 diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 9db03d5bf8d3..dc8edd435a2f 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -38,18 +38,14 @@ module.exports = { index: "cosmos-sdk" }, versions: [ - { - "label": "v0.39", - "key": "v0.39" - }, - { - "label": "v0.42", - "key": "v0.42" - }, { "label": "v0.44", "key": "v0.44" }, + { + "label": "v0.45", + "key": "v0.45" + }, { "label": "master", "key": "master" diff --git a/docs/README.md b/docs/README.md index d3caf5497404..657a46f7b5a1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -47,9 +47,9 @@ aside: false ## Get Started -- **[SDK Intro](./intro/overview.md)**: High-level overview of the Cosmos SDK. -- **[Starport](https://github.com/tendermint/starport/blob/develop/docs/README.md)**: A developer-friendly interface to the Cosmos SDK to scaffold a standard Cosmos SDK blockchain app. -- **[SDK Application Tutorial](https://github.com/cosmos/sdk-application-tutorial)**: A tutorial that showcases how to build a Cosmos SDK-based blockchain from scratch and explains the basic principles of the SDK in the process. +* **[Cosmos SDK Intro](./intro/overview.md)**: High-level overview of the Cosmos SDK. +* **[Ignite CLI](https://docs.ignite.com)**: A developer-friendly interface to the Cosmos SDK to scaffold, launch, and maintain any crypto application on a sovereign and secured blockchain. +* **[SDK Tutorials](https://tutorials.cosmos.network/)**: Tutorials that showcase how to build Cosmos SDK-based blockchains from scratch and explain the basic Cosmos SDK principles in the process. ## Reference diff --git a/docs/versions b/docs/versions index aec06db250e3..a1007ab1de14 100644 --- a/docs/versions +++ b/docs/versions @@ -1,4 +1,3 @@ master master -launchpad/backports v0.39 -release/v0.42.x v0.42 release/v0.44.x v0.44 +release/v0.45.x v0.45 diff --git a/server/api/server.go b/server/api/server.go index c2987f860d1a..68d0450c3485 100644 --- a/server/api/server.go +++ b/server/api/server.go @@ -5,6 +5,7 @@ import ( "net" "net/http" "strings" + "sync" "time" "github.com/gogo/gateway" @@ -30,8 +31,13 @@ type Server struct { GRPCGatewayRouter *runtime.ServeMux ClientCtx client.Context - logger log.Logger - metrics *telemetry.Metrics + logger log.Logger + metrics *telemetry.Metrics + // Start() is blocking and generally called from a separate goroutine. + // Close() can be called asynchronously and access shared memory + // via the listener. Therefore, we sync access to Start and Close with + // this mutex to avoid data races. + mtx sync.Mutex listener net.Listener } @@ -83,9 +89,11 @@ func New(clientCtx client.Context, logger log.Logger) *Server { // and are delegated to the Tendermint JSON RPC server. The process is // non-blocking, so an external signal handler must be used. func (s *Server) Start(cfg config.Config) error { + s.mtx.Lock() if cfg.Telemetry.Enabled { m, err := telemetry.New(cfg.Telemetry) if err != nil { + s.mtx.Unlock() return err } @@ -101,6 +109,7 @@ func (s *Server) Start(cfg config.Config) error { listener, err := tmrpcserver.Listen(cfg.API.Address, tmCfg) if err != nil { + s.mtx.Unlock() return err } @@ -111,15 +120,19 @@ func (s *Server) Start(cfg config.Config) error { if cfg.API.EnableUnsafeCORS { allowAllCORS := handlers.CORS(handlers.AllowedHeaders([]string{"Content-Type"})) + s.mtx.Unlock() return tmrpcserver.Serve(s.listener, allowAllCORS(h), s.logger, tmCfg) } s.logger.Info("starting API server...") + s.mtx.Unlock() return tmrpcserver.Serve(s.listener, s.Router, s.logger, tmCfg) } // Close closes the API server. func (s *Server) Close() error { + s.mtx.Lock() + defer s.mtx.Unlock() return s.listener.Close() } diff --git a/server/start.go b/server/start.go index 553f5810271a..15b9651ecef9 100644 --- a/server/start.go +++ b/server/start.go @@ -279,7 +279,9 @@ func startInProcess(ctx *Context, clientCtx client.Context, appCreator types.App node.DefaultMetricsProvider(cfg.Instrumentation), ctx.Logger, ) - + if err != nil { + return err + } if err := tmNode.Start(); err != nil { return err } diff --git a/simapp/README.md b/simapp/README.md index 4d00c0c2d166..b6170f52857a 100644 --- a/simapp/README.md +++ b/simapp/README.md @@ -16,7 +16,7 @@ in this testnet. `simd` binary inside a new `build` directory. The following instructions are run from inside the `build` directory. 2. If you've run `simd` before, you may need to reset your database before starting a new - testnet. You can reset your database with the following command: `$ ./simd unsafe-reset-all`. + testnet. You can reset your database with the following command: `$ ./simd tendermint unsafe-reset-all`. 3. `$ ./simd init [moniker] --chain-id [chain-id]`. This will initialize a new working directory at the default location `~/.simapp`. You need to provide a "moniker" and a "chain id". These two names can be anything, but you will need to use the same "chain id" in the following steps. diff --git a/types/coin.go b/types/coin.go index af8ef0ae7cc3..20ae56fead2e 100644 --- a/types/coin.go +++ b/types/coin.go @@ -814,13 +814,13 @@ func ParseCoinNormalized(coinStr string) (coin Coin, err error) { return coin, nil } -// ParseCoinsNormalized will parse out a list of coins separated by commas, and normalize them by converting to smallest -// unit. If the parsing is successuful, the provided coins will be sanitized by removing zero coins and sorting the coin +// ParseCoinsNormalized will parse out a list of coins separated by commas, and normalize them by converting to the smallest +// unit. If the parsing is successful, the provided coins will be sanitized by removing zero coins and sorting the coin // set. Lastly a validation of the coin set is executed. If the check passes, ParseCoinsNormalized will return the // sanitized coins. -// Otherwise it will return an error. +// Otherwise, it will return an error. // If an empty string is provided to ParseCoinsNormalized, it returns nil Coins. -// ParseCoinsNormalized supports decimal coins as inputs, and truncate them to int after converted to smallest unit. +// ParseCoinsNormalized supports decimal coins as inputs, and truncate them to int after converted to the smallest unit. // Expected format: "{amount0}{denomination},...,{amountN}{denominationN}" func ParseCoinsNormalized(coinStr string) (Coins, error) { coins, err := ParseDecCoins(coinStr) diff --git a/x/auth/vesting/types/period.go b/x/auth/vesting/types/period.go index a3b32fcaf7b3..045c142a3ce7 100644 --- a/x/auth/vesting/types/period.go +++ b/x/auth/vesting/types/period.go @@ -3,23 +3,55 @@ package types import ( "fmt" "strings" + "time" yaml "gopkg.in/yaml.v2" + + sdk "github.com/cosmos/cosmos-sdk/types" ) // Periods stores all vesting periods passed as part of a PeriodicVestingAccount type Periods []Period -// String Period implements stringer interface +// Duration is converts the period Length from seconds to a time.Duration +func (p Period) Duration() time.Duration { + return time.Duration(p.Length) * time.Second +} + +// String implements the fmt.Stringer interface func (p Period) String() string { out, _ := yaml.Marshal(p) return string(out) } -// String Periods implements stringer interface -func (vp Periods) String() string { - periodsListString := make([]string, len(vp)) - for _, period := range vp { +// TotalLength return the total length in seconds for a period +func (p Periods) TotalLength() int64 { + var total int64 + for _, period := range p { + total += period.Length + } + return total +} + +// TotalDuration returns the total duration of the period +func (p Periods) TotalDuration() time.Duration { + len := p.TotalLength() + return time.Duration(len) * time.Second +} + +// TotalDuration returns the sum of coins for the period +func (p Periods) TotalAmount() sdk.Coins { + total := sdk.Coins{} + for _, period := range p { + total = total.Add(period.Amount...) + } + return total +} + +// String implements the fmt.Stringer interface +func (p Periods) String() string { + periodsListString := make([]string, len(p)) + for _, period := range p { periodsListString = append(periodsListString, period.String()) } diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index be347b745b05..379ff1a3fccd 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -162,6 +162,10 @@ $ %s gentx my-key-name 1000000stake --home=/path/to/home/dir --keyring-backend=o w := bytes.NewBuffer([]byte{}) clientCtx = clientCtx.WithOutput(w) + if err = msg.ValidateBasic(); err != nil { + return err + } + if err = authclient.PrintUnsignedStdTx(txBldr, clientCtx, []sdk.Msg{msg}); err != nil { return errors.Wrap(err, "failed to print unsigned std tx") } diff --git a/x/genutil/client/testutil/suite.go b/x/genutil/client/testutil/suite.go index 084a5f530f8d..5ef4d7ca2c5b 100644 --- a/x/genutil/client/testutil/suite.go +++ b/x/genutil/client/testutil/suite.go @@ -1,18 +1,16 @@ package testutil import ( - "context" "fmt" - "io/ioutil" + "io" "os" "path/filepath" "github.com/stretchr/testify/suite" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/simapp" - "github.com/cosmos/cosmos-sdk/testutil" + clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/testutil/network" sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -48,84 +46,97 @@ func (s *IntegrationTestSuite) TearDownSuite() { func (s *IntegrationTestSuite) TestGenTxCmd() { val := s.network.Validators[0] - dir := s.T().TempDir() - - cmd := cli.GenTxCmd( - simapp.ModuleBasics, - val.ClientCtx.TxConfig, banktypes.GenesisBalancesIterator{}, val.ClientCtx.HomeDir) - - _, out := testutil.ApplyMockIO(cmd) - clientCtx := val.ClientCtx.WithOutput(out) - - ctx := context.Background() - ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - + clientCtx := val.ClientCtx amount := sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(12)) - genTxFile := filepath.Join(dir, "myTx") - cmd.SetArgs([]string{ - fmt.Sprintf("--%s=%s", flags.FlagChainID, s.network.Config.ChainID), - fmt.Sprintf("--%s=%s", flags.FlagOutputDocument, genTxFile), - val.Moniker, - amount.String(), - }) - - err := cmd.ExecuteContext(ctx) - s.Require().NoError(err) - - // validate generated transaction. - open, err := os.Open(genTxFile) - s.Require().NoError(err) - - all, err := ioutil.ReadAll(open) - s.Require().NoError(err) - - tx, err := val.ClientCtx.TxConfig.TxJSONDecoder()(all) - s.Require().NoError(err) - - msgs := tx.GetMsgs() - s.Require().Len(msgs, 1) - - s.Require().Equal(sdk.MsgTypeURL(&types.MsgCreateValidator{}), sdk.MsgTypeURL(msgs[0])) - s.Require().Equal([]sdk.AccAddress{val.Address}, msgs[0].GetSigners()) - s.Require().Equal(amount, msgs[0].(*types.MsgCreateValidator).Value) - s.Require().NoError(tx.ValidateBasic()) -} - -func (s *IntegrationTestSuite) TestGenTxCmdPubkey() { - val := s.network.Validators[0] - dir := s.T().TempDir() - - cmd := cli.GenTxCmd( - simapp.ModuleBasics, - val.ClientCtx.TxConfig, - banktypes.GenesisBalancesIterator{}, - val.ClientCtx.HomeDir, - ) - - _, out := testutil.ApplyMockIO(cmd) - clientCtx := val.ClientCtx.WithOutput(out) - ctx := context.Background() - ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - - amount := sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(12)) - genTxFile := filepath.Join(dir, "myTx") - - cmd.SetArgs([]string{ - fmt.Sprintf("--%s=%s", flags.FlagChainID, s.network.Config.ChainID), - fmt.Sprintf("--%s=%s", flags.FlagOutputDocument, genTxFile), - fmt.Sprintf("--%s={\"key\":\"BOIkjkFruMpfOFC9oNPhiJGfmY2pHF/gwHdLDLnrnS0=\"}", stakingcli.FlagPubKey), - val.Moniker, - amount.String(), - }) - s.Require().Error(cmd.ExecuteContext(ctx)) - - cmd.SetArgs([]string{ - fmt.Sprintf("--%s=%s", flags.FlagChainID, s.network.Config.ChainID), - fmt.Sprintf("--%s=%s", flags.FlagOutputDocument, genTxFile), - fmt.Sprintf("--%s={\"@type\":\"/cosmos.crypto.ed25519.PubKey\",\"key\":\"BOIkjkFruMpfOFC9oNPhiJGfmY2pHF/gwHdLDLnrnS0=\"}", stakingcli.FlagPubKey), - val.Moniker, - amount.String(), - }) - s.Require().NoError(cmd.ExecuteContext(ctx)) + tests := []struct { + name string + args []string + expError bool + }{ + { + name: "invalid commission rate returns error", + args: []string{ + fmt.Sprintf("--%s=%s", flags.FlagChainID, s.network.Config.ChainID), + fmt.Sprintf("--%s=1", stakingcli.FlagCommissionRate), + val.Moniker, + amount.String(), + }, + expError: true, + }, + { + name: "valid gentx", + args: []string{ + fmt.Sprintf("--%s=%s", flags.FlagChainID, s.network.Config.ChainID), + val.Moniker, + amount.String(), + }, + expError: false, + }, + { + name: "invalid pubkey", + args: []string{ + fmt.Sprintf("--%s=%s", flags.FlagChainID, s.network.Config.ChainID), + fmt.Sprintf("--%s={\"key\":\"BOIkjkFruMpfOFC9oNPhiJGfmY2pHF/gwHdLDLnrnS0=\"}", stakingcli.FlagPubKey), + val.Moniker, + amount.String(), + }, + expError: true, + }, + { + name: "valid pubkey flag", + args: []string{ + fmt.Sprintf("--%s=%s", flags.FlagChainID, s.network.Config.ChainID), + fmt.Sprintf("--%s={\"@type\":\"/cosmos.crypto.ed25519.PubKey\",\"key\":\"BOIkjkFruMpfOFC9oNPhiJGfmY2pHF/gwHdLDLnrnS0=\"}", stakingcli.FlagPubKey), + val.Moniker, + amount.String(), + }, + expError: false, + }, + } + + for _, tc := range tests { + tc := tc + + dir := s.T().TempDir() + genTxFile := filepath.Join(dir, "myTx") + tc.args = append(tc.args, fmt.Sprintf("--%s=%s", flags.FlagOutputDocument, genTxFile)) + + s.Run(tc.name, func() { + cmd := cli.GenTxCmd( + simapp.ModuleBasics, + val.ClientCtx.TxConfig, + banktypes.GenesisBalancesIterator{}, + val.ClientCtx.HomeDir) + + out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) + + if tc.expError { + s.Require().Error(err) + + _, err = os.Open(genTxFile) + s.Require().Error(err) + } else { + s.Require().NoError(err, "test: %s\noutput: %s", tc.name, out.String()) + + // validate generated transaction. + open, err := os.Open(genTxFile) + s.Require().NoError(err) + + all, err := io.ReadAll(open) + s.Require().NoError(err) + + tx, err := val.ClientCtx.TxConfig.TxJSONDecoder()(all) + s.Require().NoError(err) + + msgs := tx.GetMsgs() + s.Require().Len(msgs, 1) + + s.Require().Equal(sdk.MsgTypeURL(&types.MsgCreateValidator{}), sdk.MsgTypeURL(msgs[0])) + s.Require().True(val.Address.Equals(msgs[0].GetSigners()[0])) + s.Require().Equal(amount, msgs[0].(*types.MsgCreateValidator).Value) + s.Require().NoError(tx.ValidateBasic()) + } + }) + } } diff --git a/x/genutil/gentx_test.go b/x/genutil/gentx_test.go index 8de5bc4afe41..35390d823e9b 100644 --- a/x/genutil/gentx_test.go +++ b/x/genutil/gentx_test.go @@ -64,7 +64,7 @@ func (suite *GenTxTestSuite) setAccountBalance(addr sdk.AccAddress, amount int64 acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr) suite.app.AccountKeeper.SetAccount(suite.ctx, acc) - err := simapp.FundAccount(suite.app.BankKeeper, suite.ctx, addr, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 25)}) + err := simapp.FundAccount(suite.app.BankKeeper, suite.ctx, addr, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, amount)}) suite.Require().NoError(err) bankGenesisState := suite.app.BankKeeper.ExportGenesis(suite.ctx) @@ -230,7 +230,7 @@ func (suite *GenTxTestSuite) TestDeliverGenTxs() { "success", func() { _ = suite.setAccountBalance(addr1, 50) - _ = suite.setAccountBalance(addr2, 0) + _ = suite.setAccountBalance(addr2, 1) msg := banktypes.NewMsgSend(addr1, addr2, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 1)}) tx, err := helpers.GenTx( diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index 6ed92e37aab9..438e160d1454 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/types" ) -// return a specific delegation +// GetDelegation returns a specific delegation. func (k Keeper) GetDelegation(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) (delegation types.Delegation, found bool) { store := ctx.KVStore(k.storeKey) @@ -26,7 +26,7 @@ func (k Keeper) GetDelegation(ctx sdk.Context, return delegation, true } -// IterateAllDelegations iterate through all of the delegations +// IterateAllDelegations iterates through all of the delegations. func (k Keeper) IterateAllDelegations(ctx sdk.Context, cb func(delegation types.Delegation) (stop bool)) { store := ctx.KVStore(k.storeKey) @@ -41,7 +41,7 @@ func (k Keeper) IterateAllDelegations(ctx sdk.Context, cb func(delegation types. } } -// GetAllDelegations returns all delegations used during genesis dump +// GetAllDelegations returns all delegations used during genesis dump. func (k Keeper) GetAllDelegations(ctx sdk.Context) (delegations []types.Delegation) { k.IterateAllDelegations(ctx, func(delegation types.Delegation) bool { delegations = append(delegations, delegation) @@ -51,7 +51,8 @@ func (k Keeper) GetAllDelegations(ctx sdk.Context) (delegations []types.Delegati return delegations } -// return all delegations to a specific validator. Useful for querier. +// GetValidatorDelegations returns all delegations to a specific validator. +// Useful for querier. func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) (delegations []types.Delegation) { //nolint:interfacer store := ctx.KVStore(k.storeKey) @@ -68,7 +69,8 @@ func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) return delegations } -// return a given amount of all the delegations from a delegator +// GetDelegatorDelegations returns a given amount of all the delegations from a +// delegator. func (k Keeper) GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress, maxRetrieve uint16) (delegations []types.Delegation) { delegations = make([]types.Delegation, maxRetrieve) @@ -88,7 +90,7 @@ func (k Keeper) GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddres return delegations[:i] // trim if the array length < maxRetrieve } -// set a delegation +// SetDelegation sets a delegation. func (k Keeper) SetDelegation(ctx sdk.Context, delegation types.Delegation) { delegatorAddress, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) if err != nil { @@ -100,7 +102,7 @@ func (k Keeper) SetDelegation(ctx sdk.Context, delegation types.Delegation) { store.Set(types.GetDelegationKey(delegatorAddress, delegation.GetValidatorAddr()), b) } -// remove a delegation +// RemoveDelegation removes a delegation. func (k Keeper) RemoveDelegation(ctx sdk.Context, delegation types.Delegation) { delegatorAddress, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) if err != nil { @@ -112,7 +114,7 @@ func (k Keeper) RemoveDelegation(ctx sdk.Context, delegation types.Delegation) { store.Delete(types.GetDelegationKey(delegatorAddress, delegation.GetValidatorAddr())) } -// return a given amount of all the delegator unbonding-delegations +// GetUnbondingDelegations returns a given amount of all the delegator unbonding-delegations. func (k Keeper) GetUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddress, maxRetrieve uint16) (unbondingDelegations []types.UnbondingDelegation) { unbondingDelegations = make([]types.UnbondingDelegation, maxRetrieve) @@ -133,7 +135,7 @@ func (k Keeper) GetUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddres return unbondingDelegations[:i] // trim if the array length < maxRetrieve } -// return a unbonding delegation +// GetUnbondingDelegation returns a unbonding delegation. func (k Keeper) GetUnbondingDelegation( ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, ) (ubd types.UnbondingDelegation, found bool) { @@ -150,7 +152,8 @@ func (k Keeper) GetUnbondingDelegation( return ubd, true } -// return all unbonding delegations from a particular validator +// GetUnbondingDelegationsFromValidator returns all unbonding delegations from a +// particular validator. func (k Keeper) GetUnbondingDelegationsFromValidator(ctx sdk.Context, valAddr sdk.ValAddress) (ubds []types.UnbondingDelegation) { store := ctx.KVStore(k.storeKey) @@ -167,7 +170,7 @@ func (k Keeper) GetUnbondingDelegationsFromValidator(ctx sdk.Context, valAddr sd return ubds } -// iterate through all of the unbonding delegations +// IterateUnbondingDelegations iterates through all of the unbonding delegations. func (k Keeper) IterateUnbondingDelegations(ctx sdk.Context, fn func(index int64, ubd types.UnbondingDelegation) (stop bool)) { store := ctx.KVStore(k.storeKey) @@ -183,7 +186,85 @@ func (k Keeper) IterateUnbondingDelegations(ctx sdk.Context, fn func(index int64 } } -// HasMaxUnbondingDelegationEntries - check if unbonding delegation has maximum number of entries +// GetDelegatorUnbonding returns the total amount a delegator has unbonding. +func (k Keeper) GetDelegatorUnbonding(ctx sdk.Context, delegator sdk.AccAddress) sdk.Int { + unbonding := sdk.ZeroInt() + k.IterateDelegatorUnbondingDelegations(ctx, delegator, func(ubd types.UnbondingDelegation) bool { + for _, entry := range ubd.Entries { + unbonding = unbonding.Add(entry.Balance) + } + return false + }) + return unbonding +} + +// IterateDelegatorUnbondingDelegations iterates through a delegator's unbonding delegations. +func (k Keeper) IterateDelegatorUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddress, cb func(ubd types.UnbondingDelegation) (stop bool)) { + store := ctx.KVStore(k.storeKey) + + iterator := sdk.KVStorePrefixIterator(store, types.GetUBDsKey(delegator)) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + ubd := types.MustUnmarshalUBD(k.cdc, iterator.Value()) + if cb(ubd) { + break + } + } +} + +// GetDelegatorBonded returs the total amount a delegator has bonded. +func (k Keeper) GetDelegatorBonded(ctx sdk.Context, delegator sdk.AccAddress) sdk.Int { + bonded := sdk.ZeroDec() + + k.IterateDelegatorDelegations(ctx, delegator, func(delegation types.Delegation) bool { + validatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) + if err != nil { + panic(err) // shouldn't happen + } + validator, found := k.GetValidator(ctx, validatorAddr) + if found { + shares := delegation.Shares + tokens := validator.TokensFromSharesTruncated(shares) + bonded = bonded.Add(tokens) + } + return false + }) + return bonded.RoundInt() +} + +// IterateDelegatorDelegations iterates through one delegator's delegations. +func (k Keeper) IterateDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress, cb func(delegation types.Delegation) (stop bool)) { + store := ctx.KVStore(k.storeKey) + delegatorPrefixKey := types.GetDelegationsKey(delegator) + iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value()) + if cb(delegation) { + break + } + } +} + +// IterateDelegatorRedelegations iterates through one delegator's redelegations. +func (k Keeper) IterateDelegatorRedelegations(ctx sdk.Context, delegator sdk.AccAddress, cb func(red types.Redelegation) (stop bool)) { + store := ctx.KVStore(k.storeKey) + delegatorPrefixKey := types.GetREDsKey(delegator) + + iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + red := types.MustUnmarshalRED(k.cdc, iterator.Value()) + if cb(red) { + break + } + } +} + +// HasMaxUnbondingDelegationEntries - check if unbonding delegation has maximum number of entries. func (k Keeper) HasMaxUnbondingDelegationEntries(ctx sdk.Context, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) bool { ubd, found := k.GetUnbondingDelegation(ctx, delegatorAddr, validatorAddr) @@ -194,7 +275,7 @@ func (k Keeper) HasMaxUnbondingDelegationEntries(ctx sdk.Context, return len(ubd.Entries) >= int(k.MaxEntries(ctx)) } -// set the unbonding delegation and associated index +// SetUnbondingDelegation sets the unbonding delegation and associated index. func (k Keeper) SetUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDelegation) { delegatorAddress, err := sdk.AccAddressFromBech32(ubd.DelegatorAddress) if err != nil { @@ -211,7 +292,7 @@ func (k Keeper) SetUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDeleg store.Set(types.GetUBDByValIndexKey(delegatorAddress, addr), []byte{}) // index, store empty bytes } -// remove the unbonding delegation object and associated index +// RemoveUnbondingDelegation removes the unbonding delegation object and associated index. func (k Keeper) RemoveUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDelegation) { delegatorAddress, err := sdk.AccAddressFromBech32(ubd.DelegatorAddress) if err != nil { @@ -229,7 +310,7 @@ func (k Keeper) RemoveUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDe } // SetUnbondingDelegationEntry adds an entry to the unbonding delegation at -// the given addresses. It creates the unbonding delegation if it does not exist +// the given addresses. It creates the unbonding delegation if it does not exist. func (k Keeper) SetUnbondingDelegationEntry( ctx sdk.Context, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, creationHeight int64, minTime time.Time, balance sdk.Int, @@ -248,8 +329,9 @@ func (k Keeper) SetUnbondingDelegationEntry( // unbonding delegation queue timeslice operations -// gets a specific unbonding queue timeslice. A timeslice is a slice of DVPairs -// corresponding to unbonding delegations that expire at a certain time. +// GetUBDQueueTimeSlice gets a specific unbonding queue timeslice. A timeslice +// is a slice of DVPairs corresponding to unbonding delegations that expire at a +// certain time. func (k Keeper) GetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvPairs []types.DVPair) { store := ctx.KVStore(k.storeKey) @@ -264,14 +346,15 @@ func (k Keeper) GetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvPa return pairs.Pairs } -// Sets a specific unbonding queue timeslice. +// SetUBDQueueTimeSlice sets a specific unbonding queue timeslice. func (k Keeper) SetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time, keys []types.DVPair) { store := ctx.KVStore(k.storeKey) bz := k.cdc.MustMarshal(&types.DVPairs{Pairs: keys}) store.Set(types.GetUnbondingDelegationTimeKey(timestamp), bz) } -// Insert an unbonding delegation to the appropriate timeslice in the unbonding queue +// InsertUBDQueue inserts an unbonding delegation to the appropriate timeslice +// in the unbonding queue. func (k Keeper) InsertUBDQueue(ctx sdk.Context, ubd types.UnbondingDelegation, completionTime time.Time) { dvPair := types.DVPair{DelegatorAddress: ubd.DelegatorAddress, ValidatorAddress: ubd.ValidatorAddress} @@ -285,15 +368,15 @@ func (k Keeper) InsertUBDQueue(ctx sdk.Context, ubd types.UnbondingDelegation, } } -// Returns all the unbonding queue timeslices from time 0 until endTime +// UBDQueueIterator returns all the unbonding queue timeslices from time 0 until endTime. func (k Keeper) UBDQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator { store := ctx.KVStore(k.storeKey) return store.Iterator(types.UnbondingQueueKey, sdk.InclusiveEndBytes(types.GetUnbondingDelegationTimeKey(endTime))) } -// Returns a concatenated list of all the timeslices inclusively previous to -// currTime, and deletes the timeslices from the queue +// DequeueAllMatureUBDQueue returns a concatenated list of all the timeslices inclusively previous to +// currTime, and deletes the timeslices from the queue. func (k Keeper) DequeueAllMatureUBDQueue(ctx sdk.Context, currTime time.Time) (matureUnbonds []types.DVPair) { store := ctx.KVStore(k.storeKey) @@ -314,7 +397,7 @@ func (k Keeper) DequeueAllMatureUBDQueue(ctx sdk.Context, currTime time.Time) (m return matureUnbonds } -// return a given amount of all the delegator redelegations +// GetRedelegations returns a given amount of all the delegator redelegations. func (k Keeper) GetRedelegations(ctx sdk.Context, delegator sdk.AccAddress, maxRetrieve uint16) (redelegations []types.Redelegation) { redelegations = make([]types.Redelegation, maxRetrieve) @@ -335,7 +418,7 @@ func (k Keeper) GetRedelegations(ctx sdk.Context, delegator sdk.AccAddress, return redelegations[:i] // trim if the array length < maxRetrieve } -// return a redelegation +// GetRedelegation returns a redelegation. func (k Keeper) GetRedelegation(ctx sdk.Context, delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) (red types.Redelegation, found bool) { store := ctx.KVStore(k.storeKey) @@ -351,7 +434,8 @@ func (k Keeper) GetRedelegation(ctx sdk.Context, return red, true } -// return all redelegations from a particular validator +// GetRedelegationsFromSrcValidator returns all redelegations from a particular +// validator. func (k Keeper) GetRedelegationsFromSrcValidator(ctx sdk.Context, valAddr sdk.ValAddress) (reds []types.Redelegation) { store := ctx.KVStore(k.storeKey) @@ -368,7 +452,7 @@ func (k Keeper) GetRedelegationsFromSrcValidator(ctx sdk.Context, valAddr sdk.Va return reds } -// check if validator is receiving a redelegation +// HasReceivingRedelegation checks if validator is receiving a redelegation. func (k Keeper) HasReceivingRedelegation(ctx sdk.Context, delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) bool { store := ctx.KVStore(k.storeKey) @@ -380,7 +464,7 @@ func (k Keeper) HasReceivingRedelegation(ctx sdk.Context, return iterator.Valid() } -// HasMaxRedelegationEntries - redelegation has maximum number of entries +// HasMaxRedelegationEntries checks if redelegation has maximum number of entries. func (k Keeper) HasMaxRedelegationEntries(ctx sdk.Context, delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress) bool { @@ -392,7 +476,7 @@ func (k Keeper) HasMaxRedelegationEntries(ctx sdk.Context, return len(red.Entries) >= int(k.MaxEntries(ctx)) } -// set a redelegation and associated index +// SetRedelegation set a redelegation and associated index. func (k Keeper) SetRedelegation(ctx sdk.Context, red types.Redelegation) { delegatorAddress, err := sdk.AccAddressFromBech32(red.DelegatorAddress) if err != nil { @@ -415,8 +499,8 @@ func (k Keeper) SetRedelegation(ctx sdk.Context, red types.Redelegation) { store.Set(types.GetREDByValDstIndexKey(delegatorAddress, valSrcAddr, valDestAddr), []byte{}) } -// SetUnbondingDelegationEntry adds an entry to the unbonding delegation at -// the given addresses. It creates the unbonding delegation if it does not exist +// SetRedelegationEntry adds an entry to the unbonding delegation at the given +// addresses. It creates the unbonding delegation if it does not exist. func (k Keeper) SetRedelegationEntry(ctx sdk.Context, delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress, creationHeight int64, @@ -435,7 +519,7 @@ func (k Keeper) SetRedelegationEntry(ctx sdk.Context, return red } -// iterate through all redelegations +// IterateRedelegations iterates through all redelegations. func (k Keeper) IterateRedelegations(ctx sdk.Context, fn func(index int64, red types.Redelegation) (stop bool)) { store := ctx.KVStore(k.storeKey) @@ -451,7 +535,7 @@ func (k Keeper) IterateRedelegations(ctx sdk.Context, fn func(index int64, red t } } -// remove a redelegation object and associated index +// RemoveRedelegation removes a redelegation object and associated index. func (k Keeper) RemoveRedelegation(ctx sdk.Context, red types.Redelegation) { delegatorAddress, err := sdk.AccAddressFromBech32(red.DelegatorAddress) if err != nil { @@ -474,8 +558,9 @@ func (k Keeper) RemoveRedelegation(ctx sdk.Context, red types.Redelegation) { // redelegation queue timeslice operations -// Gets a specific redelegation queue timeslice. A timeslice is a slice of DVVTriplets corresponding to redelegations -// that expire at a certain time. +// GetRedelegationQueueTimeSlice gets a specific redelegation queue timeslice. A +// timeslice is a slice of DVVTriplets corresponding to redelegations that +// expire at a certain time. func (k Keeper) GetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvvTriplets []types.DVVTriplet) { store := ctx.KVStore(k.storeKey) @@ -490,14 +575,15 @@ func (k Keeper) GetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Ti return triplets.Triplets } -// Sets a specific redelegation queue timeslice. +// SetRedelegationQueueTimeSlice sets a specific redelegation queue timeslice. func (k Keeper) SetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Time, keys []types.DVVTriplet) { store := ctx.KVStore(k.storeKey) bz := k.cdc.MustMarshal(&types.DVVTriplets{Triplets: keys}) store.Set(types.GetRedelegationTimeKey(timestamp), bz) } -// Insert an redelegation delegation to the appropriate timeslice in the redelegation queue +// InsertRedelegationQueue insert an redelegation delegation to the appropriate +// timeslice in the redelegation queue. func (k Keeper) InsertRedelegationQueue(ctx sdk.Context, red types.Redelegation, completionTime time.Time) { timeSlice := k.GetRedelegationQueueTimeSlice(ctx, completionTime) @@ -514,14 +600,16 @@ func (k Keeper) InsertRedelegationQueue(ctx sdk.Context, red types.Redelegation, } } -// Returns all the redelegation queue timeslices from time 0 until endTime +// RedelegationQueueIterator returns all the redelegation queue timeslices from +// time 0 until endTime. func (k Keeper) RedelegationQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator { store := ctx.KVStore(k.storeKey) return store.Iterator(types.RedelegationQueueKey, sdk.InclusiveEndBytes(types.GetRedelegationTimeKey(endTime))) } -// Returns a concatenated list of all the timeslices inclusively previous to -// currTime, and deletes the timeslices from the queue +// DequeueAllMatureRedelegationQueue returns a concatenated list of all the +// timeslices inclusively previous to currTime, and deletes the timeslices from +// the queue. func (k Keeper) DequeueAllMatureRedelegationQueue(ctx sdk.Context, currTime time.Time) (matureRedelegations []types.DVVTriplet) { store := ctx.KVStore(k.storeKey) @@ -626,7 +714,7 @@ func (k Keeper) Delegate( return newShares, nil } -// Unbond a particular delegation and perform associated store operations. +// Unbond unbonds a particular delegation and perform associated store operations. func (k Keeper) Unbond( ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, shares sdk.Dec, ) (amount sdk.Int, err error) { @@ -800,7 +888,8 @@ func (k Keeper) CompleteUnbonding(ctx sdk.Context, delAddr sdk.AccAddress, valAd return balances, nil } -// begin unbonding / redelegation; create a redelegation record +// BeginRedelegation begins unbonding / redelegation and creates a redelegation +// record. func (k Keeper) BeginRedelegation( ctx sdk.Context, delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress, sharesAmount sdk.Dec, ) (completionTime time.Time, err error) { diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index cac61af1fbe2..f44a88a2ca4a 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -107,6 +107,11 @@ func TestDelegation(t *testing.T) { require.Len(t, resDels, 2) } + // test total bonded for single delegator + expBonded := bond1to1.Shares.Add(bond2to1.Shares).Add(bond1to3.Shares) + resDelBond := app.StakingKeeper.GetDelegatorBonded(ctx, addrDels[0]) + require.Equal(t, expBonded, sdk.NewDecFromInt(resDelBond)) + // delete a record app.StakingKeeper.RemoveDelegation(ctx, bond2to3) _, found = app.StakingKeeper.GetDelegation(ctx, addrDels[1], valAddrs[2]) @@ -152,7 +157,8 @@ func TestUnbondingDelegation(t *testing.T) { require.Equal(t, ubd, resUnbond) // modify a records, save, and retrieve - ubd.Entries[0].Balance = sdk.NewInt(21) + expUnbond := sdk.NewInt(21) + ubd.Entries[0].Balance = expUnbond app.StakingKeeper.SetUnbondingDelegation(ctx, ubd) resUnbonds := app.StakingKeeper.GetUnbondingDelegations(ctx, delAddrs[0], 5) @@ -165,6 +171,9 @@ func TestUnbondingDelegation(t *testing.T) { require.True(t, found) require.Equal(t, ubd, resUnbond) + resDelUnbond := app.StakingKeeper.GetDelegatorUnbonding(ctx, delAddrs[0]) + require.Equal(t, expUnbond, resDelUnbond) + // delete a record app.StakingKeeper.RemoveUnbondingDelegation(ctx, ubd) _, found = app.StakingKeeper.GetUnbondingDelegation(ctx, delAddrs[0], valAddrs[0])