From b85371ae512da9b0f035587ea977d728ff5fdfdc Mon Sep 17 00:00:00 2001 From: Alexander Bezobchuk Date: Sun, 21 Apr 2019 20:03:09 -0400 Subject: [PATCH 01/13] Merge PR #4163: Fix v0.33.x export script to port gov data correctly --- contrib/export/v0.33.x-to-v0.34.0.py | 35 +++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/contrib/export/v0.33.x-to-v0.34.0.py b/contrib/export/v0.33.x-to-v0.34.0.py index bb7d6520c..fd49e9b69 100755 --- a/contrib/export/v0.33.x-to-v0.34.0.py +++ b/contrib/export/v0.33.x-to-v0.34.0.py @@ -15,7 +15,10 @@ def process_raw_genesis(genesis, parsed_args): }, } - # default tm value + # migrate governance state as the internal structure of proposals has changed + migrate_gov_data(genesis['app_state']['gov']) + + # default Tendermint block time (ms) genesis['consensus_params']['block']['time_iota_ms'] = '1000' # proposal #1 updates @@ -36,6 +39,36 @@ def process_raw_genesis(genesis, parsed_args): return genesis +def migrate_gov_data(gov_data): + for p in gov_data['proposals']: + # get Amino type and value + t = p['type'] + v = p['value'] + + del p['type'] + del p['value'] + + assert t == 'gov/TextProposal', 'invalid proposal type: {t}' + assert p == {}, 'expected proposal to be empty after deleting contents' + + p['proposal_content'] = { + 'type': t, + 'value': { + 'title': v['title'], + 'description': v['description'] + } + } + + p['proposal_id'] = v['proposal_id'] + p['proposal_status'] = v['proposal_status'] + p['final_tally_result'] = v['final_tally_result'] + p['submit_time'] = v['submit_time'] + p['deposit_end_time'] = v['deposit_end_time'] + p['total_deposit'] = v['total_deposit'] + p['voting_start_time'] = v['voting_start_time'] + p['voting_end_time'] = v['voting_end_time'] + + if __name__ == '__main__': parser = lib.init_default_argument_parser( prog_desc='Convert genesis.json from v0.33.x to v0.34.0', From 8e9210664fd2ab8d4b93d9b32929f05617f88149 Mon Sep 17 00:00:00 2001 From: gamarin Date: Tue, 23 Apr 2019 15:35:40 +0200 Subject: [PATCH 02/13] docs update --- README.md | 2 +- docs/.vuepress/config.js | 2 +- docs/README.md | 6 +- docs/cosmos-hub/delegator-guide-cli.md | 30 ++++++-- docs/cosmos-hub/deploy-testnet.md | 2 +- docs/cosmos-hub/gaiacli.md | 36 +++++++--- docs/cosmos-hub/upgrade-node.md | 99 ++++++++++++++++++++++++++ docs/intro/README.md | 99 +++++++++++++++++++++++++- docs/intro/sdk-app-architecture.md | 96 ------------------------- docs/intro/sdk-design.md | 20 +++--- 10 files changed, 262 insertions(+), 130 deletions(-) create mode 100644 docs/cosmos-hub/upgrade-node.md delete mode 100644 docs/intro/sdk-app-architecture.md diff --git a/README.md b/README.md index f216f2cd6..fc9f6b7cc 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ breaking changes. ## Cosmos Hub Mainnet -To run a full-node for the mainnet of the Cosmos Hub, first [install `gaia`](./docs/gaia/installation.md), then follow [the guide](./docs/gaia/join-mainnet.md). +To run a full-node for the mainnet of the Cosmos Hub, first [install `gaia`](./docs/cosmos-hub/installation.md), then follow [the guide](./docs/cosmos-hub/join-mainnet.md). For status updates and genesis file, see the [launch repo](https://github.com/cosmos/launch). diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 52dfd3a2b..6ab800888 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -29,7 +29,7 @@ module.exports = { collapsable: true, children: [ "/intro/", - "/intro/sdk-app-architecture", + "/intro/sdk-design", "/intro/ocap" ] }, diff --git a/docs/README.md b/docs/README.md index 7b1632437..9c5e8c964 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,9 +13,9 @@ ## Cosmos Hub -- [Join the mainnet](./gaia/join-mainnet.md) of the Cosmos Hub. -- [Join the latest public testnet](./gaia/join-testnet.md) of the Cosmos Hub. -- [Start your own `gaia` testnet](./gaia/deploy-testnet.md). +- [Join the mainnet](./cosmos-hub/join-mainnet.md) of the Cosmos Hub. +- [Join the latest public testnet](./cosmos-hub/join-testnet.md) of the Cosmos Hub. +- [Start your own `gaia` testnet](./cosmos-hub/deploy-testnet.md). ## Creating a new SDK project diff --git a/docs/cosmos-hub/delegator-guide-cli.md b/docs/cosmos-hub/delegator-guide-cli.md index aab15da88..02dad2e34 100644 --- a/docs/cosmos-hub/delegator-guide-cli.md +++ b/docs/cosmos-hub/delegator-guide-cli.md @@ -55,7 +55,7 @@ Please exercise extreme caution! [**Download the binaries**] Not available yet. -[**Install from source**](https://cosmos.network/docs/gaia/installation.html) +[**Install from source**](https://cosmos.network/docs/cosmos-hub/installation.html) ::: tip `gaiacli` is used from a terminal. To open the terminal, follow these steps: @@ -237,7 +237,7 @@ In order to query the state and send transactions, you need a way to access the This is the most secure option, but comes with relatively high resource requirements. In order to run your own full-node, you need good bandwidth and at least 1TB of disk space. -You will find the tutorial on how to install `gaiad` [here](https://cosmos.network/docs/gaia/installation.html), and the guide to run a full-node [here](https://cosmos.network/docs/gaia/join-mainnet.html). +You will find the tutorial on how to install `gaiad` [here](https://cosmos.network/docs/cosmos-hub/installation.html), and the guide to run a full-node [here](https://cosmos.network/docs/cosmos-hub/join-mainnet.html). ### Connecting to a Remote Full-Node @@ -286,7 +286,7 @@ gaiacli config trust-node false Finally, let us set the `chain-id` of the blockchain we want to interact with: ```bash -gaiacli config chain-id cosmoshub-1 +gaiacli config chain-id cosmoshub-2 ``` ## Querying the State @@ -358,6 +358,24 @@ The transaction `fees` are the product of `gas` and `gasPrice`. As a user, you h For mainnet, the recommended `gas-prices` is `0.025uatom`. ::: +### Sending Tokens + +::: tip +**Before you can bond atoms and withdraw rewards, you need to [set up `gaiacli`](#setting-up-gaiacli) and [create an account](#creating-an-account)** +::: + +::: warning +**Note: These commands need to be run on an online computer. It is more secure to perform them commands using a ledger device. For the offline procedure, click [here](#signing-transactions-from-an-offline-computer).** +::: + +```bash +// Send a certain amount of tokens to an address +// Ex value for parameters (do not actually use these values in your tx!!): =cosmos16m93fezfiezhvnjajzrfyszml8qm92a0w67ntjhd3d0 =1000000uatom +// Ex value for flags: =0.025uatom + +gaiacli tx send --from --gas auto --gas-adjustment 1.5 --gas-prices +``` + ### Bonding Atoms and Withdrawing Rewards ::: tip @@ -480,10 +498,10 @@ gaiacli tx staking delegate --from --chain-id cosmoshub-1 +gaiacli query account --chain-id cosmoshub-2 ``` Then, copy `unsignedTx.json` and transfer it (e.g. via USB) to the offline computer. If it is not done already, [create an account on the offline computer](#using-a-computer). For additional security, you can double check the parameters of your transaction before signing it using the following command: @@ -495,7 +513,7 @@ cat unsignedTx.json Now, sign the transaction using the following command. You will need the `chain-id`, `sequence` and `account-number` obtained earlier: ```bash -gaiacli tx sign unsignedTx.json --from --offline --chain-id cosmoshub-1 --sequence --account-number > signedTx.json +gaiacli tx sign unsignedTx.json --from --offline --chain-id cosmoshub-2 --sequence --account-number > signedTx.json ``` Copy `signedTx.json` and transfer it back to the online computer. Finally, use the following command to broadcast the transaction: diff --git a/docs/cosmos-hub/deploy-testnet.md b/docs/cosmos-hub/deploy-testnet.md index 0757d6581..1e2af63cb 100644 --- a/docs/cosmos-hub/deploy-testnet.md +++ b/docs/cosmos-hub/deploy-testnet.md @@ -1,4 +1,4 @@ -# Deploy Your Own Testnet +# Deploy Your Own Gaia Testnet This document describes 3 ways to setup a network of `gaiad` nodes, each serving a different usecase: diff --git a/docs/cosmos-hub/gaiacli.md b/docs/cosmos-hub/gaiacli.md index 509745551..de2f3b689 100644 --- a/docs/cosmos-hub/gaiacli.md +++ b/docs/cosmos-hub/gaiacli.md @@ -2,27 +2,41 @@ ## Gaia CLI -::: tip Note -If you receive this error message: +`gaiacli` is the tool that enables you to interact with the node that runs on the Cosmos Hub network, whether you run it yourself or not. Let us set it up properly. In order to install it, follow the [installation procedure](./installation.md). + +### Setting up gaiacli + +The main command used to set up `gaiacli` is the following: ```bash -Must specify these options: --chain-id when --trust-node is false +gaiacli config ``` -you must choose whether you wish to verify lite client proofs. If you trust the node which you are querying, you can simply pass `--trust-node=true` - otherwise you'll need to specify `--chain-id`. -::: +It allows you to set a default value for each given flag. -`gaiacli` is the command line interface to manage accounts and transactions on Cosmos testnets. -Its configuration file resides in `$HOME/.gaiacli/config/config.toml` and can be edited either -by hand or via the `gaiacli config` command: +First, set up the address of the full-node you want to connect to: ```bash -gaiacli config chain-id gaia-9004 +gaiacli config node : to a version . + +## Software Upgrade + +First, stop your instance of `gaiad`. Next, upgrade the software: + +```bash +cd $GOPATH/src/github.com/cosmos/cosmos-sdk +git fetch --all && git checkout +make tools install +``` + +::: tip +*NOTE*: If you have issues at this step, please check that you have the latest stable version of GO installed. +::: + +See the [testnet repo](https://github.com/cosmos/testnets) for details on which version is needed for which public testnet, and the [SDK release page](https://github.com/cosmos/cosmos-sdk/releases) for details on each release. + +Your full node has been cleanly upgraded! + +## Fetch new genesis + +:::warning +If the version you are upgrading to is breaking from the previous one, you will have to restart your chain. If it is not breaking, you can skip to [Restart](#restart) +::: + +The first step is to remove your current genesis: + +```bash +rm $HOME/.gaiad/config/addrbook.json $HOME/.gaiad/config/genesis.json +``` + +The procedure varies depending on the network you want to connect to. + +### Mainnet + +Follow the [official upgrade guide](https://gist.github.com/alexanderbez/5e87886221eb304b9e85ad4b167c99c8). + +### Public Testnet + +If you are joining a new public testnet, fetch the genesis from the appropriate testnet in the [testnet repo](https://github.com/cosmos/testnets). Save the new genesis as `new_genesis.json`. Then replace the old `genesis.json` with `new_genesis.json` + +```bash +cd $HOME/.gaiad/config +cp -f genesis.json new-_enesis.json +mv new_genesis.json genesis.json +``` + +### Local Testnet + +If you are running your own local testnet, you can either start with a brand new genesis using `gaiad init`, or export the state from you previous network as a new genesis. To do so, use the following command + +```bash +cd $HOME/.gaiad/config +gaiad export --for-zero-height --height= > new_genesis.json +``` + +Then, replace the old `genesis.json` with `new_genesis.json`. + +```bash +cp -f genesis.json new-_enesis.json +mv new_genesis.json genesis.json +``` + +## Reset Data + +:::warning +If the version you are upgrading to is not breaking from the previous one, you should not reset the data. If it is not breaking, you can skip to [Restart](#restart) +::: + +::: warning +If you are running a **validator node** on the mainnet, always be careful when doing `gaiad unsafe-reset-all`. You should never use this command if you are not switching `chain-id`. +::: + +::: danger Warning +Make sure that every node has a unique `priv_validator.json`. Do not copy the `priv_validator.json` from an old node to multiple new nodes. Running two nodes with the same `priv_validator.json` will cause you to double sign. +::: + +First, remove the outdated files and reset the data. **If you are running a validator node, make sure you understand what you are doing before resetting**. + +```bash +gaiad unsafe-reset-all +``` + +Your node is now in a pristine state while keeping the original `priv_validator.json` and `config.toml`. If you had any sentry nodes or full nodes setup before, your node will still try to connect to them, but may fail if they haven't also been upgraded. + +## Restart + +To restart your node, just type: + +```bash +gaiad start +``` diff --git a/docs/intro/README.md b/docs/intro/README.md index 204e2f1f2..f7b51e67f 100644 --- a/docs/intro/README.md +++ b/docs/intro/README.md @@ -1,6 +1,6 @@ # SDK Intro -The [Cosmos-SDK](https://github.com/cosmos/cosmos-sdk) is a framework for building multi-asset Proof-of-Stake (PoS) blockchains, like the Cosmos Hub, as well as Proof-Of-Authority (PoA) blockchains. +The [Cosmos-SDK](https://github.com/cosmos/cosmos-sdk) is a framework for building multi-asset public Proof-of-Stake (PoS) blockchains, like the Cosmos Hub, as well as permissionned Proof-Of-Authority (PoA) blockchains. The goal of the Cosmos SDK is to allow developers to easily create custom blockchains from scratch that can natively interoperate with other blockchains. We envision the SDK as the npm-like framework to build secure blockchain applications on top of [Tendermint](https://github.com/tendermint/tendermint). @@ -10,4 +10,99 @@ It is based on two major principles: - **Capabilities:** The SDK is inspired by capabilities-based security, and informed by years of wrestling with blockchain state-machines. Most developers will need to access other 3rd party modules when building their own modules. Given that the Cosmos-SDK is an open framework, some of the modules may be malicious, which means there is a need for security principles to reason about inter-module interactions. These principles are based on object-capabilities. In practice, this means that instead of having each module keep an access control list for other modules, each module implements special objects called keepers that can be passed to other modules to grant a pre-defined set of capabilities. For example, if an instance of module A's keepers is passed to module B, the latter will be able to call a restricted set of module A's functions. The capabilities of each keeper are defined by the module's developer, and it's the developer's job to understand and audit the safety of foreign code from 3rd party modules based on the capabilities they are passing into each third party module. For a deeper look at capabilities, jump to [this section](./ocap.md). -### Next, learn more about the [SDK Application Architecture](./sdk-app-architecture.md) +## SDK Application Architecture + +### State machine + +At its core, a blockchain is a [replicated deterministic state machine](https://en.wikipedia.org/wiki/State_machine_replication). + +A state machine is a computer science concept whereby a machine can have multiple states, but only one at any given time. There is a `state`, which describes the current state of the system, and `transactions`, that trigger state transitions. + +Given a state S and a transaction T, the state machine will return a new state S'. + +``` ++--------+ +--------+ +| | | | +| S +---------------->+ S' | +| | apply(T) | | ++--------+ +--------+ +``` + +In practice, the transactions are bundled in blocks to make the process more efficient. Given a state S and a block of transactions B, the state machine will return a new state S'. + +``` ++--------+ +--------+ +| | | | +| S +----------------------------> | S' | +| | For each T in B: apply(T) | | ++--------+ +--------+ +``` + +In a blockchain context, the state machine is deterministic. This means that if you start at a given state and replay the same sequence of transactions, you will always end up with the same final state. + +The Cosmos SDK gives you maximum flexibility to define the state of your application, transaction types and state transition functions. The process of building the state-machine with the SDK will be described more in depth in the following sections. But first, let us see how it is replicated using **Tendermint**. + +### Tendermint + +As a developer, you just have to define the state machine using the Cosmos-SDK, and [*Tendermint*](https://tendermint.com/docs/introduction/what-is-tendermint.html) will handle replication over the network for you. + + +``` + ^ +-------------------------------+ ^ + | | | | Built with Cosmos SDK + | | State-machine = Application | | + | | | v + | +-------------------------------+ + | | | ^ +Blockchain node | | Consensus | | + | | | | + | +-------------------------------+ | Tendermint Core + | | | | + | | Networking | | + | | | | + v +-------------------------------+ v +``` + + +Tendermint is an application-agnostic engine that is responsible for handling the *networking* and *consensus* layers of your blockchain. In practice, this means that Tendermint is responsible for propagating and ordering transaction bytes. Tendermint Core relies on an eponymous Byzantine-Fault-Tolerant (BFT) algorithm to reach consensus on the order of transactions. For more on Tendermint, click [here](https://tendermint.com/docs/introduction/what-is-tendermint.html). + +Tendermint consensus algorithm works with a set of special nodes called *Validators*. Validators are responsible for adding blocks of transactions to the blockchain. At any given block, there is a validator set V. A validator in V is chosen by the algorithm to be the proposer of the next block. This block is considered valid if more than two thirds of V signed a *[prevote](https://tendermint.com/docs/spec/consensus/consensus.html#prevote-step-height-h-round-r)* and a *[precommit](https://tendermint.com/docs/spec/consensus/consensus.html#precommit-step-height-h-round-r)* on it, and if all the transactions that it contains are valid. The validator set can be changed by rules written in the state-machine. For a deeper look at the algorithm, click [here](https://tendermint.com/docs/introduction/what-is-tendermint.html#consensus-overview). + + +The main part of a Cosmos SDK application is a blockchain daemon that is run by each node in the network locally. If less than one third of the *validator set* is byzantine (i.e. malicious), then each node should obtain the same result when querying the state at the same time. + +## ABCI + +Tendermint passes transactions from the network to the application through an interface called the [ABCI](https://github.com/tendermint/tendermint/tree/master/abci), which the application must implement. + +``` ++---------------------+ +| | +| Application | +| | ++--------+---+--------+ + ^ | + | | ABCI + | v ++--------+---+--------+ +| | +| | +| Tendermint | +| | +| | ++---------------------+ +``` + +Note that **Tendermint only handles transaction bytes**. It has no knowledge of what these bytes mean. All Tendermint does is order these transaction bytes deterministically. Tendermint passes the bytes to the application via the ABCI, and expects a return code to inform it if the messages contained in the transactions were successfully processed or not. + +Here are the most important messages of the ABCI: + +- `CheckTx`: When a transaction is received by Tendermint Core, it is passed to the application to check if a few basic requirements are met. `CheckTx` is used to protect the mempool of full-nodes against spam. A special handler called the "Ante Handler" is used to execute a series of validation steps such as checking for sufficient fees and validating the signatures. If the check is valid, the transaction is added to the [mempool](https://tendermint.com/docs/spec/reactors/mempool/functionality.html#mempool-functionality) and relayed to peer nodes. Note that transactions are not processed (i.e. no modification of the state occurs) with `CheckTx` since they have not been included in a block yet. +- `DeliverTx`: When a [valid block](https://tendermint.com/docs/spec/blockchain/blockchain.html#validation) is received by Tendermint Core, each transaction in the given block is passed to the application via `DeliverTx` to be processed. It is during this stage that the state transitions occur. The "Ante Handler" executes again along with the actual handlers for each message in the transaction. + - `BeginBlock`/`EndBlock`: These messages are executed at the beginning and the end of each block, whether the block contains transaction or not. It is useful to trigger automatic execution of logic. Proceed with caution though, as computationally expensive loops could slow down your blockchain, or even freeze it if the loop is infinite. + +For a more detailed view of the ABCI methods and types, click [here](https://tendermint.com/docs/spec/abci/abci.html#overview). + +Any application built on Tendermint needs to implement the ABCI interface in order to communicate with the underlying local Tendermint engine. Fortunately, you do not have to implement the ABCI interface. The Cosmos SDK provides a boilerplate implementation of it in the form of [baseapp](./sdk-design.md#baseapp). + +### Next, let us go into the [high-level design principles of the SDK](./sdk-design.md) \ No newline at end of file diff --git a/docs/intro/sdk-app-architecture.md b/docs/intro/sdk-app-architecture.md deleted file mode 100644 index f1c67c416..000000000 --- a/docs/intro/sdk-app-architecture.md +++ /dev/null @@ -1,96 +0,0 @@ -# SDK Application Architecture - -## State machine - -At its core, a blockchain application is a [replicated deterministic state machine](https://en.wikipedia.org/wiki/State_machine_replication). - -A state machine is a computer science concept whereby a machine can have multiple states, but only one at any given time. There is a state, which describes the current state of the system, and transactions, that trigger state transitions. - -Given a state S and a transaction T, the state machine will return a new state S'. - -``` -+--------+ +--------+ -| | | | -| S +---------------->+ S' | -| | apply(T) | | -+--------+ +--------+ -``` - -In practice, the transactions are bundled in blocks to make the process more efficient. Given a state S and a block of transactions B, the state machine will return a new state S'. - -``` -+--------+ +--------+ -| | | | -| S +----------------------------> | S' | -| | For each T in B: apply(T) | | -+--------+ +--------+ -``` - -In a blockchain context, the state machine is deterministic. This means that if you start at a given state and replay the same sequence of transactions, you will always end up with the same final state. - -The Cosmos SDK gives you maximum flexibility to define the state of your application, transaction types and state-transition functions. The process of building the state-machine with the SDK will be described more in depth in the following sections. But first, let us see how it is replicated using **Tendermint**. - -## Tendermint - -As a developer, you just have to define the state machine using the Cosmos-SDK, and [*Tendermint*](https://tendermint.com/docs/introduction/what-is-tendermint.html) will handle replication over the network for you. - - -``` - ^ +-------------------------------+ ^ - | | | | Built with Cosmos SDK - | | State-machine = Application | | - | | | v - | +-------------------------------+ - | | | ^ -Blockchain node | | Consensus | | - | | | | - | +-------------------------------+ | Tendermint Core - | | | | - | | Networking | | - | | | | - v +-------------------------------+ v -``` - - -Tendermint is an application-agnostic engine that is responsible for handling the *networking* and *consensus* layers of your blockchain. In practice, this means that Tendermint is responsible for propagating and ordering transaction bytes. Tendermint Core relies on an eponymous Byzantine-Fault-Tolerant (BFT) algorithm to reach consensus on the order of transactions. For more on Tendermint, click [here](https://tendermint.com/docs/introduction/what-is-tendermint.html). - -Tendermint consensus algorithm works with a set of special nodes called *Validators*. Validators are responsible for adding blocks of transactions to the blockchain. At any given block, there is a validator set V. A validator in V is chosen by the algorithm to be the proposer of the next block. This block is considered valid if more than two thirds of V signed a *[prevote](https://tendermint.com/docs/spec/consensus/consensus.html#prevote-step-height-h-round-r)* and a *[precommit](https://tendermint.com/docs/spec/consensus/consensus.html#precommit-step-height-h-round-r)* on it, and if all the transactions that it contains are valid. The validator set can be changed by rules written in the state-machine. For a deeper look at the algorithm, click [here](https://tendermint.com/docs/introduction/what-is-tendermint.html#consensus-overview). - - -The main part of a Cosmos SDK application is a blockchain daemon that is run by each node in the network locally. If less than one third of the *validator set* is byzantine (i.e. malicious), then each node should obtain the same result when querying the state at the same time. - -## ABCI - -Tendermint passes transactions from the network to the application through an interface called the [ABCI](https://github.com/tendermint/tendermint/tree/master/abci), which the application must implement. - -``` -+---------------------+ -| | -| Application | -| | -+--------+---+--------+ - ^ | - | | ABCI - | v -+--------+---+--------+ -| | -| | -| Tendermint | -| | -| | -+---------------------+ -``` - -Note that Tendermint only handles transaction bytes. It has no knowledge of what these bytes really mean. All Tendermint does is to order them deterministically. It is the job of the application to give meaning to these bytes. Tendermint passes the bytes to the application via the ABCI, and expects a return code to inform it if the message was successful or not. - -Here are the most important messages of the ABCI: - -- `CheckTx`: When a transaction is received by Tendermint Core, it is passed to the application to check its validity. A special handler called the "Ante Handler" is used to execute a series of validation steps such as checking for sufficient fees and validating the signatures. If the transaction is valid, the transaction is added to the [mempool](https://tendermint.com/docs/spec/reactors/mempool/functionality.html#mempool-functionality) and relayed to peer nodes. Note that transactions are not processed (i.e. no modification of the state occurs) with `CheckTx` since they have not been included in a block yet. -- `DeliverTx`: When a [valid block](https://tendermint.com/docs/spec/blockchain/blockchain.html#validation) is received by Tendermint Core, each transaction in the given block is passed to the application via `DeliverTx` to be processed. It is during this stage where the state transitions occur. The "Ante Handler" executes again along with the actual handlers for each message in the transaction. - - `BeginBlock`/`EndBlock`: These messages are executed at the beginning and the end of each block, whether the block contains transaction or not. It is useful to trigger automatic execution of logic. Proceed with caution though, as computationally expensive loops could slow down your blockchain, or even freeze it if the loop is infinite. - -For a more detailed view of the ABCI methods and types, click [here](https://tendermint.com/docs/spec/abci/abci.html#overview). - -Any application built on Tendermint needs to implement the ABCI interface in order to communicate with the underlying local Tendermint engine. Fortunately, you do not have to implement the ABCI interface. The Cosmos SDK provides a boilerplate implementation of it in the form of [baseapp](./sdk-design.md#baseapp). - -### Next, let us go into the [high-level design principles of the SDK](./sdk-design.md) diff --git a/docs/intro/sdk-design.md b/docs/intro/sdk-design.md index dc52cc932..9549cad4d 100644 --- a/docs/intro/sdk-design.md +++ b/docs/intro/sdk-design.md @@ -2,13 +2,12 @@ The Cosmos SDK is a framework that facilitates the development of secure state-machines on top of Tendermint. At its core, the SDK is a boilerplate implementation of the ABCI in Golang. It comes with a `multistore` to persist data and a `router` to handle transactions. -Here is a simplified view of how transactions are handled by an application built on top of the Cosmos SDK when transferred from Tendermint via `DeliverTx` -(the `CheckTx` process is the same without enforcing state changes): +Here is a simplified view of how transactions are handled by an application built on top of the Cosmos SDK when transferred from Tendermint via `DeliverTx`: -1. Decode transactions received from the Tendermint consensus engine (remember that Tendermint only deals with `[]bytes`). -2. Extract messages from transactions and do basic sanity checks. +1. Decode `transactions` received from the Tendermint consensus engine (remember that Tendermint only deals with `[]bytes`). +2. Extract `messages` from `transactions` and do basic sanity checks. 3. Route each message to the appropriate module so that it can be processed. -4. Commit the state changes. +4. Commit state changes. The application also enables you to generate transactions, encode them and pass them to the underlying Tendermint engine to broadcast them. @@ -16,7 +15,7 @@ The application also enables you to generate transactions, encode them and pass `baseApp` is the boilerplate implementation of the ABCI of the Cosmos SDK. It comes with a `router` to route transactions to their respective module. The main `app.go` file of your application will define your custom `app` type that will embed `baseapp`. This way, your custom `app` type will automatically inherit all the ABCI methods of `baseapp`. See an example of this in the [SDK application tutorial](https://github.com/cosmos/sdk-application-tutorial/blob/master/app.go#L27). -The goal of `baseapp` to provide a secure interface between the store and the extensible state machine while defining as little about that state machine as possible (staying true to the ABCI). +The goal of `baseapp` is to provide a secure interface between the store and the extensible state machine while defining as little about the state machine as possible (staying true to the ABCI). For more on `baseapp`, please click [here](../concepts/baseapp.md). @@ -30,11 +29,14 @@ The multistore abstraction is used to divide the state in distinct compartments, The power of the Cosmos SDK lies in its modularity. SDK applications are built by aggregating a collection of interoperable modules. Each module defines a subset of the state and contains its own message/transaction processor, while the SDK is responsible for routing each message to its respective module. +Here is a simplified view of how a transaction is processed by the application of each full-node when it is received in a valid block: + ``` + | - | Transaction relayed from Tendermint - | via DeliverTx + | Transaction relayed from the full-node's Tendermint engine + | to the node's application via DeliverTx + | | | +---------------------v--------------------------+ @@ -74,7 +76,7 @@ The power of the Cosmos SDK lies in its modularity. SDK applications are built b v ``` -Each module can be seen as a little state-machine. Developers need to define the subset of the state handled by the module, as well as custom message types that modify the state (*Note:* Messages are extracted from transactions in `baseapp`'s methods). In general, each module declares its own `KVStore` in the multistore to persist the subset of the state it defines. Most developers will need to access other 3rd party modules when building their own modules. Given that the Cosmos-SDK is an open framework, some of the modules may be malicious, which means there is a need for security principles to reason about inter-module interactions. These principles are based on [object-capabilities](./ocap.md). In practice, this means that instead of having each module keep an access control list for other modules, each module implements special objects called keepers that can be passed to other modules to grant a pre-defined set of capabilities. +Each module can be seen as a little state-machine. Developers need to define the subset of the state handled by the module, as well as custom message types that modify the state (*Note:* `messages` are extracted from `transactions` using `baseapp`). In general, each module declares its own `KVStore` in the multistore to persist the subset of the state it defines. Most developers will need to access other 3rd party modules when building their own modules. Given that the Cosmos-SDK is an open framework, some of the modules may be malicious, which means there is a need for security principles to reason about inter-module interactions. These principles are based on [object-capabilities](./ocap.md). In practice, this means that instead of having each module keep an access control list for other modules, each module implements special objects called `keepers` that can be passed to other modules to grant a pre-defined set of capabilities. SDK modules are defined in the `x/` folder of the SDK. Some core modules include: From 4742e406ae0687f1c25d65a8732ca53b09e57829 Mon Sep 17 00:00:00 2001 From: gamarin Date: Tue, 23 Apr 2019 16:14:56 +0200 Subject: [PATCH 03/13] few nits --- docs/cosmos-hub/validators/validator-setup.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cosmos-hub/validators/validator-setup.md b/docs/cosmos-hub/validators/validator-setup.md index 4c524b52f..0087e8f8e 100644 --- a/docs/cosmos-hub/validators/validator-setup.md +++ b/docs/cosmos-hub/validators/validator-setup.md @@ -159,7 +159,7 @@ Your validator is active if the following command returns anything: gaiacli query tendermint-validator-set | grep "$(gaiad tendermint show-validator)" ``` -You should also be able to see your validator on the [Explorer](https://explorecosmos.network/validators). You are looking for the `bech32` encoded `address` in the `~/.gaiad/config/priv_validator.json` file. +You should now see your validator in one of the Cosmos Hub explorers. You are looking for the `bech32` encoded `address` in the `~/.gaiad/config/priv_validator.json` file. ::: warning Note To be in the validator set, you need to have more total voting power than the 100th validator. From 0a51d56e902f6629f92470c1d303b6cb293b596b Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Tue, 23 Apr 2019 19:17:13 +0200 Subject: [PATCH 04/13] Apply suggestions from code review Co-Authored-By: gamarin2 --- docs/cosmos-hub/delegator-guide-cli.md | 2 +- docs/cosmos-hub/upgrade-node.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/cosmos-hub/delegator-guide-cli.md b/docs/cosmos-hub/delegator-guide-cli.md index 02dad2e34..7db80595e 100644 --- a/docs/cosmos-hub/delegator-guide-cli.md +++ b/docs/cosmos-hub/delegator-guide-cli.md @@ -365,7 +365,7 @@ For mainnet, the recommended `gas-prices` is `0.025uatom`. ::: ::: warning -**Note: These commands need to be run on an online computer. It is more secure to perform them commands using a ledger device. For the offline procedure, click [here](#signing-transactions-from-an-offline-computer).** +**Note: These commands need to be run on an online computer. It is more secure to perform them commands using a Ledger Nano S device. For the offline procedure, click [here](#signing-transactions-from-an-offline-computer).** ::: ```bash diff --git a/docs/cosmos-hub/upgrade-node.md b/docs/cosmos-hub/upgrade-node.md index 85f508d0e..cab9aec72 100644 --- a/docs/cosmos-hub/upgrade-node.md +++ b/docs/cosmos-hub/upgrade-node.md @@ -4,7 +4,7 @@ The detailed procedure to upgrade a mainnet node from `cosmoshub-1` to `cosmoshub-2` can be found [here](https://gist.github.com/alexanderbez/5e87886221eb304b9e85ad4b167c99c8). ::: -This document describes the upgrade procedure of a `gaiad` full-node from a version to a version . +This document describes the upgrade procedure of a `gaiad` full-node to a new version. ## Software Upgrade @@ -27,7 +27,7 @@ Your full node has been cleanly upgraded! ## Fetch new genesis :::warning -If the version you are upgrading to is breaking from the previous one, you will have to restart your chain. If it is not breaking, you can skip to [Restart](#restart) +If the new version you are upgrading to has breaking changes, you will have to restart your chain. If it is not breaking, you can skip to [Restart](#restart) ::: The first step is to remove your current genesis: @@ -78,8 +78,8 @@ If the version you are upgrading to is not breaking from the previ If you are running a **validator node** on the mainnet, always be careful when doing `gaiad unsafe-reset-all`. You should never use this command if you are not switching `chain-id`. ::: -::: danger Warning -Make sure that every node has a unique `priv_validator.json`. Do not copy the `priv_validator.json` from an old node to multiple new nodes. Running two nodes with the same `priv_validator.json` will cause you to double sign. +::: danger IMPORTANT +Make sure that every node has a unique `priv_validator.json`. Do not copy the `priv_validator.json` from an old node to multiple new nodes. Running two nodes with the same `priv_validator.json` will cause you to get slashed due to double sign ! ::: First, remove the outdated files and reset the data. **If you are running a validator node, make sure you understand what you are doing before resetting**. From 5d10a6f05bbdf91175283d4f0cd97155d44404a5 Mon Sep 17 00:00:00 2001 From: gamarin Date: Tue, 23 Apr 2019 19:17:36 +0200 Subject: [PATCH 05/13] code review --- docs/cosmos-hub/gaiacli.md | 6 +++--- docs/cosmos-hub/upgrade-node.md | 10 ---------- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/docs/cosmos-hub/gaiacli.md b/docs/cosmos-hub/gaiacli.md index de2f3b689..48756c6c0 100644 --- a/docs/cosmos-hub/gaiacli.md +++ b/docs/cosmos-hub/gaiacli.md @@ -27,15 +27,15 @@ If you run your own full-node, just use `tcp://localhost:26657` as the address. Then, let us set the default value of the `--trust-node` flag: ```bash -gaiacli config trust-node false +gaiacli config trust-node true -// Set to true if you run a light-client node, false otherwise +// Set to true if you trust the full-node you are connecting to, false otherwise ``` Finally, let us set the `chain-id` of the blockchain we want to interact with: ```bash -gaiacli config chain-id cosmoshub-1 +gaiacli config chain-id cosmoshub-2 ``` ### Keys diff --git a/docs/cosmos-hub/upgrade-node.md b/docs/cosmos-hub/upgrade-node.md index 85f508d0e..b1fb8e8a6 100644 --- a/docs/cosmos-hub/upgrade-node.md +++ b/docs/cosmos-hub/upgrade-node.md @@ -1,9 +1,5 @@ # Upgrade Your Node -::: warning -The detailed procedure to upgrade a mainnet node from `cosmoshub-1` to `cosmoshub-2` can be found [here](https://gist.github.com/alexanderbez/5e87886221eb304b9e85ad4b167c99c8). -::: - This document describes the upgrade procedure of a `gaiad` full-node from a version to a version . ## Software Upgrade @@ -30,12 +26,6 @@ Your full node has been cleanly upgraded! If the version you are upgrading to is breaking from the previous one, you will have to restart your chain. If it is not breaking, you can skip to [Restart](#restart) ::: -The first step is to remove your current genesis: - -```bash -rm $HOME/.gaiad/config/addrbook.json $HOME/.gaiad/config/genesis.json -``` - The procedure varies depending on the network you want to connect to. ### Mainnet From dcdd5973502169b2453df241d2e56a4c5b631159 Mon Sep 17 00:00:00 2001 From: gamarin Date: Tue, 23 Apr 2019 19:57:30 +0200 Subject: [PATCH 06/13] udate upgrade node doc --- docs/cosmos-hub/upgrade-node.md | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/docs/cosmos-hub/upgrade-node.md b/docs/cosmos-hub/upgrade-node.md index a55a61534..b152417ee 100644 --- a/docs/cosmos-hub/upgrade-node.md +++ b/docs/cosmos-hub/upgrade-node.md @@ -1,14 +1,6 @@ # Upgrade Your Node -<<<<<<< HEAD -This document describes the upgrade procedure of a `gaiad` full-node from a version to a version . -======= -::: warning -The detailed procedure to upgrade a mainnet node from `cosmoshub-1` to `cosmoshub-2` can be found [here](https://gist.github.com/alexanderbez/5e87886221eb304b9e85ad4b167c99c8). -::: - -This document describes the upgrade procedure of a `gaiad` full-node to a new version. ->>>>>>> 0a51d56e902f6629f92470c1d303b6cb293b596b +This document describes the upgrade procedure of a `gaiad` full-node to a new version. ## Software Upgrade @@ -28,21 +20,19 @@ See the [testnet repo](https://github.com/cosmos/testnets) for details on which Your full node has been cleanly upgraded! -## Fetch new genesis +## Ugrade Genesis File :::warning If the new version you are upgrading to has breaking changes, you will have to restart your chain. If it is not breaking, you can skip to [Restart](#restart) ::: -The procedure varies depending on the network you want to connect to. +To upgrade the genesis file, you can either fetch it from a trusted source or export it locally. -### Mainnet +### Fetching from a Trusted Source -Follow the [official upgrade guide](https://gist.github.com/alexanderbez/5e87886221eb304b9e85ad4b167c99c8). +If you are joining the mainnet, fetch the genesis from the [mainnet repo](https://github.com/cosmos/launc). If you are joining a public testnet, fetch the genesis from the appropriate testnet in the [testnet repo](https://github.com/cosmos/testnets). Otherwise, fetch it from your trusted source. -### Public Testnet - -If you are joining a new public testnet, fetch the genesis from the appropriate testnet in the [testnet repo](https://github.com/cosmos/testnets). Save the new genesis as `new_genesis.json`. Then replace the old `genesis.json` with `new_genesis.json` +Save the new genesis as `new_genesis.json`. Then replace the old `genesis.json` with `new_genesis.json` ```bash cd $HOME/.gaiad/config @@ -50,15 +40,19 @@ cp -f genesis.json new-_enesis.json mv new_genesis.json genesis.json ``` -### Local Testnet +Then, go to the [reset data](#reset-data) section. -If you are running your own local testnet, you can either start with a brand new genesis using `gaiad init`, or export the state from you previous network as a new genesis. To do so, use the following command +### Exporting State to a New Genesis Locally + +If you were running a node in the previous version of the network and want to build your new genesis locally from a state of this previous network, use the following command: ```bash cd $HOME/.gaiad/config gaiad export --for-zero-height --height= > new_genesis.json ``` +The command above take a state at a certain height `` and turns it into a new genesis file that can be used to start a new network. + Then, replace the old `genesis.json` with `new_genesis.json`. ```bash @@ -66,6 +60,8 @@ cp -f genesis.json new-_enesis.json mv new_genesis.json genesis.json ``` +At this point, you might want to run a script to update the exported genesis into a genesis that is compatible with your new version. For example, the attributes of a the `Account` type changed, a script should query encoded account from the account store, unmarshall them, update their type, re-marhsall and re-store them. You can find an example of such script [here](https://github.com/cosmos/cosmos-sdk/blob/develop/contrib/export/v0.33.x-to-v0.34.0.py). + ## Reset Data :::warning From 92dd6ffefd46e73f424f07aca26efbf0a1bc0526 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Wed, 24 Apr 2019 09:05:19 -0400 Subject: [PATCH 07/13] Remove TOC --- CHANGELOG.md | 26 -------------------------- 1 file changed, 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ff1081e7c..795a050e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,31 +1,5 @@ # Changelog -* [0.34.0](#0340) - * [Breaking Changes](#breaking-changes) - * [Gaia](#gaia) - * [Gaia CLI](#gaia-cli) - * [SDK](#sdk) - * [Tendermint](#tendermint) - * [New features](#new-features) - * [SDK](#sdk-1) - * [Gaia](#gaia-1) - * [Gaia CLI](#gaia-cli-1) - * [Gaia REST API](#gaia-rest-api) - * [Improvements](#improvements) - * [Gaia](#gaia-2) - * [Gaia CLI](#gaia-cli-2) - * [SDK](#sdk-2) - * [Bug Fixes](#bug-fixes) - * [Gaia](#gaia-3) - * [Gaia CLI](#gaia-cli-3) - * [SDK](#sdk-3) -* [0.33.2](#0332) - * [Improvements](#improvements-1) - * [Tendermint](#tendermint-1) -* [0.33.1](#0331) - * [Bug Fixes](#bug-fixes-1) - * [Gaia](#gaia-4) - ## 0.34.0 ### Breaking Changes From 18b973e1a057b2ec20fd96e961a135e7f83ee177 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Wed, 24 Apr 2019 09:40:55 -0400 Subject: [PATCH 08/13] Add missing changelog entry for v0.34.1 --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 795a050e5..44d40eefd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 0.34.1 + +### Bug Fixes + +#### Gaia + +* [#4163](https://github.com/cosmos/cosmos-sdk/pull/4163) Fix v0.33.x export script to port gov data correctly. + ## 0.34.0 ### Breaking Changes From c0e6b38394e2bfdb5aa261629f5ea29ad8de45d4 Mon Sep 17 00:00:00 2001 From: Alexander Bezobchuk Date: Wed, 24 Apr 2019 11:51:49 -0400 Subject: [PATCH 09/13] Merge PR #4182: Cherry pick #4083 into v0.34.2 --- CHANGELOG.md | 9 +++++++++ client/config.go | 2 +- client/lcd/test_helpers.go | 2 +- client/rpc/codec.go | 2 +- cmd/gaia/app/app.go | 8 +++++--- cmd/gaia/app/app_test.go | 4 ++-- cmd/gaia/app/invariants.go | 3 ++- cmd/gaia/app/sim_test.go | 14 +++++++------- cmd/gaia/cmd/gaiacli/main.go | 2 +- cmd/gaia/cmd/gaiad/main.go | 15 ++++++++------- cmd/gaia/cmd/gaiareplay/main.go | 2 +- crypto/amino.go | 4 ++-- crypto/keys/hd/fundraiser_test.go | 2 +- crypto/keys/hd/hdpath_test.go | 2 +- x/auth/client/txbuilder/txbuilder.go | 4 ++++ x/mint/client/module_client.go | 1 + 16 files changed, 47 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 44d40eefd..465be449a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 0.34.2 + +### Improvements + +#### SDK + +* [\#4053](https://github.com/cosmos/cosmos-sdk/issues/4053) Add `--inv-check-period` +flag to gaiad to set period at which invariants checks will run. + ## 0.34.1 ### Bug Fixes diff --git a/client/config.go b/client/config.go index d785093a3..04ec8f80d 100644 --- a/client/config.go +++ b/client/config.go @@ -9,7 +9,7 @@ import ( "github.com/tendermint/tendermint/libs/cli" - "github.com/pelletier/go-toml" + toml "github.com/pelletier/go-toml" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/client/lcd/test_helpers.go b/client/lcd/test_helpers.go index 856efaf95..9cd87362c 100644 --- a/client/lcd/test_helpers.go +++ b/client/lcd/test_helpers.go @@ -221,7 +221,7 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.AccAddress privVal.Reset() db := dbm.NewMemDB() - app := gapp.NewGaiaApp(logger, db, nil, true, false) + app := gapp.NewGaiaApp(logger, db, nil, true, 0) cdc = gapp.MakeCodec() genesisFile := config.GenesisFile() diff --git a/client/rpc/codec.go b/client/rpc/codec.go index 1a64ee4ae..841366fef 100644 --- a/client/rpc/codec.go +++ b/client/rpc/codec.go @@ -1,7 +1,7 @@ package rpc import ( - "github.com/tendermint/go-amino" + amino "github.com/tendermint/go-amino" ctypes "github.com/tendermint/tendermint/rpc/core/types" ) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 262115649..d257627b2 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -42,7 +42,7 @@ type GaiaApp struct { *bam.BaseApp cdc *codec.Codec - assertInvariantsBlockly bool + invCheckPeriod uint // keys to access the substores keyMain *sdk.KVStoreKey @@ -72,7 +72,8 @@ type GaiaApp struct { } // NewGaiaApp returns a reference to an initialized GaiaApp. -func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest, assertInvariantsBlockly bool, +func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, + invCheckPeriod uint, baseAppOptions ...func(*bam.BaseApp)) *GaiaApp { cdc := MakeCodec() @@ -83,6 +84,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest, var app = &GaiaApp{ BaseApp: bApp, cdc: cdc, + invCheckPeriod: invCheckPeriod, keyMain: sdk.NewKVStoreKey(bam.MainStoreKey), keyAccount: sdk.NewKVStoreKey(auth.StoreKey), keyStaking: sdk.NewKVStoreKey(staking.StoreKey), @@ -244,7 +246,7 @@ func (app *GaiaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.R validatorUpdates, endBlockerTags := staking.EndBlocker(ctx, app.stakingKeeper) tags = append(tags, endBlockerTags...) - if app.assertInvariantsBlockly { + if app.invCheckPeriod != 0 && ctx.BlockHeight()%int64(app.invCheckPeriod) == 0 { app.assertRuntimeInvariants() } diff --git a/cmd/gaia/app/app_test.go b/cmd/gaia/app/app_test.go index ec38f06a6..95fa02119 100644 --- a/cmd/gaia/app/app_test.go +++ b/cmd/gaia/app/app_test.go @@ -55,11 +55,11 @@ func setGenesis(gapp *GaiaApp, accs ...*auth.BaseAccount) error { func TestGaiadExport(t *testing.T) { db := db.NewMemDB() - gapp := NewGaiaApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, false) + gapp := NewGaiaApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0) setGenesis(gapp) // Making a new app object with the db, so that initchain hasn't been called - newGapp := NewGaiaApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, false) + newGapp := NewGaiaApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0) _, _, err := newGapp.ExportAppStateAndValidators(false, []string{}) require.NoError(t, err, "ExportAppStateAndValidators should not have an error") } diff --git a/cmd/gaia/app/invariants.go b/cmd/gaia/app/invariants.go index 841732ca1..899d6bdba 100644 --- a/cmd/gaia/app/invariants.go +++ b/cmd/gaia/app/invariants.go @@ -26,5 +26,6 @@ func (app *GaiaApp) assertRuntimeInvariantsOnContext(ctx sdk.Context) { } end := time.Now() diff := end.Sub(start) - app.BaseApp.Logger().With("module", "invariants").Info("Asserted all invariants", "duration", diff) + app.BaseApp.Logger().With("module", "invariants").Info( + "Asserted all invariants", "duration", diff, "height", app.LastBlockHeight()) } diff --git a/cmd/gaia/app/sim_test.go b/cmd/gaia/app/sim_test.go index 247cc262a..80a268ee2 100644 --- a/cmd/gaia/app/sim_test.go +++ b/cmd/gaia/app/sim_test.go @@ -319,7 +319,7 @@ func BenchmarkFullGaiaSimulation(b *testing.B) { db.Close() os.RemoveAll(dir) }() - app := NewGaiaApp(logger, db, nil, true, false) + app := NewGaiaApp(logger, db, nil, true, 0) // Run randomized simulation // TODO parameterize numbers, save for a later PR @@ -354,7 +354,7 @@ func TestFullGaiaSimulation(t *testing.T) { db.Close() os.RemoveAll(dir) }() - app := NewGaiaApp(logger, db, nil, true, false, fauxMerkleModeOpt) + app := NewGaiaApp(logger, db, nil, true, 0, fauxMerkleModeOpt) require.Equal(t, "GaiaApp", app.Name()) // Run randomized simulation @@ -388,7 +388,7 @@ func TestGaiaImportExport(t *testing.T) { db.Close() os.RemoveAll(dir) }() - app := NewGaiaApp(logger, db, nil, true, false, fauxMerkleModeOpt) + app := NewGaiaApp(logger, db, nil, true, 0, fauxMerkleModeOpt) require.Equal(t, "GaiaApp", app.Name()) // Run randomized simulation @@ -415,7 +415,7 @@ func TestGaiaImportExport(t *testing.T) { newDB.Close() os.RemoveAll(newDir) }() - newApp := NewGaiaApp(log.NewNopLogger(), newDB, nil, true, false, fauxMerkleModeOpt) + newApp := NewGaiaApp(log.NewNopLogger(), newDB, nil, true, 0, fauxMerkleModeOpt) require.Equal(t, "GaiaApp", newApp.Name()) var genesisState GenesisState err = app.cdc.UnmarshalJSON(appState, &genesisState) @@ -478,7 +478,7 @@ func TestGaiaSimulationAfterImport(t *testing.T) { db.Close() os.RemoveAll(dir) }() - app := NewGaiaApp(logger, db, nil, true, false, fauxMerkleModeOpt) + app := NewGaiaApp(logger, db, nil, true, 0, fauxMerkleModeOpt) require.Equal(t, "GaiaApp", app.Name()) // Run randomized simulation @@ -514,7 +514,7 @@ func TestGaiaSimulationAfterImport(t *testing.T) { newDB.Close() os.RemoveAll(newDir) }() - newApp := NewGaiaApp(log.NewNopLogger(), newDB, nil, true, false, fauxMerkleModeOpt) + newApp := NewGaiaApp(log.NewNopLogger(), newDB, nil, true, 0, fauxMerkleModeOpt) require.Equal(t, "GaiaApp", newApp.Name()) newApp.InitChain(abci.RequestInitChain{ AppStateBytes: appState, @@ -542,7 +542,7 @@ func TestAppStateDeterminism(t *testing.T) { for j := 0; j < numTimesToRunPerSeed; j++ { logger := log.NewNopLogger() db := dbm.NewMemDB() - app := NewGaiaApp(logger, db, nil, true, false) + app := NewGaiaApp(logger, db, nil, true, 0) // Run randomized simulation simulation.SimulateFromSeed( diff --git a/cmd/gaia/cmd/gaiacli/main.go b/cmd/gaia/cmd/gaiacli/main.go index b440db8f9..4fd6d1c3a 100644 --- a/cmd/gaia/cmd/gaiacli/main.go +++ b/cmd/gaia/cmd/gaiacli/main.go @@ -12,7 +12,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/tendermint/go-amino" + amino "github.com/tendermint/go-amino" "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/client" diff --git a/cmd/gaia/cmd/gaiad/main.go b/cmd/gaia/cmd/gaiad/main.go index b515f5236..58e6cf576 100644 --- a/cmd/gaia/cmd/gaiad/main.go +++ b/cmd/gaia/cmd/gaiad/main.go @@ -23,9 +23,9 @@ import ( ) // gaiad custom flags -const flagAssertInvariantsBlockly = "assert-invariants-blockly" +const flagInvCheckPeriod = "inv-check-period" -var assertInvariantsBlockly bool +var invCheckPeriod uint func main() { cdc := app.MakeCodec() @@ -43,6 +43,7 @@ func main() { Short: "Gaia Daemon (server)", PersistentPreRunE: server.PersistentPreRunEFn(ctx), } + rootCmd.AddCommand(gaiaInit.InitCmd(ctx, cdc)) rootCmd.AddCommand(gaiaInit.CollectGenTxsCmd(ctx, cdc)) rootCmd.AddCommand(gaiaInit.TestnetFilesCmd(ctx, cdc)) @@ -55,8 +56,8 @@ func main() { // prepare and add flags executor := cli.PrepareBaseCmd(rootCmd, "GA", app.DefaultNodeHome) - rootCmd.PersistentFlags().BoolVar(&assertInvariantsBlockly, flagAssertInvariantsBlockly, - false, "Assert registered invariants on a blockly basis") + rootCmd.PersistentFlags().UintVar(&invCheckPeriod, flagInvCheckPeriod, + 1, "Assert registered invariants every N blocks") err := executor.Execute() if err != nil { // handle with #870 @@ -66,7 +67,7 @@ func main() { func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) abci.Application { return app.NewGaiaApp( - logger, db, traceStore, true, assertInvariantsBlockly, + logger, db, traceStore, true, invCheckPeriod, baseapp.SetPruning(store.NewPruningOptionsFromString(viper.GetString("pruning"))), baseapp.SetMinGasPrices(viper.GetString(server.FlagMinGasPrices)), ) @@ -77,13 +78,13 @@ func exportAppStateAndTMValidators( ) (json.RawMessage, []tmtypes.GenesisValidator, error) { if height != -1 { - gApp := app.NewGaiaApp(logger, db, traceStore, false, false) + gApp := app.NewGaiaApp(logger, db, traceStore, false, uint(1)) err := gApp.LoadHeight(height) if err != nil { return nil, nil, err } return gApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) } - gApp := app.NewGaiaApp(logger, db, traceStore, true, false) + gApp := app.NewGaiaApp(logger, db, traceStore, true, uint(1)) return gApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) } diff --git a/cmd/gaia/cmd/gaiareplay/main.go b/cmd/gaia/cmd/gaiareplay/main.go index fd2c518a4..d41a65c7e 100644 --- a/cmd/gaia/cmd/gaiareplay/main.go +++ b/cmd/gaia/cmd/gaiareplay/main.go @@ -107,7 +107,7 @@ func run(rootDir string) { // Application fmt.Println("Creating application") myapp := app.NewGaiaApp( - ctx.Logger, appDB, traceStoreWriter, true, true, + ctx.Logger, appDB, traceStoreWriter, true, uint(1), baseapp.SetPruning(store.PruneEverything), // nothing ) diff --git a/crypto/amino.go b/crypto/amino.go index 3a12c9681..553a4723f 100644 --- a/crypto/amino.go +++ b/crypto/amino.go @@ -1,8 +1,8 @@ package crypto import ( - "github.com/tendermint/go-amino" - "github.com/tendermint/tendermint/crypto/encoding/amino" + amino "github.com/tendermint/go-amino" + cryptoAmino "github.com/tendermint/tendermint/crypto/encoding/amino" ) var cdc = amino.NewCodec() diff --git a/crypto/keys/hd/fundraiser_test.go b/crypto/keys/hd/fundraiser_test.go index 5e3cf06f3..6fa4ca725 100644 --- a/crypto/keys/hd/fundraiser_test.go +++ b/crypto/keys/hd/fundraiser_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/cosmos/go-bip39" + bip39 "github.com/cosmos/go-bip39" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/secp256k1" diff --git a/crypto/keys/hd/hdpath_test.go b/crypto/keys/hd/hdpath_test.go index 275b714ce..509cdb6c2 100644 --- a/crypto/keys/hd/hdpath_test.go +++ b/crypto/keys/hd/hdpath_test.go @@ -5,7 +5,7 @@ import ( "fmt" "testing" - "github.com/cosmos/go-bip39" + bip39 "github.com/cosmos/go-bip39" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/x/auth/client/txbuilder/txbuilder.go b/x/auth/client/txbuilder/txbuilder.go index 480d8fd41..034ef86f8 100644 --- a/x/auth/client/txbuilder/txbuilder.go +++ b/x/auth/client/txbuilder/txbuilder.go @@ -248,6 +248,10 @@ func (bldr TxBuilder) BuildTxForSim(msgs []sdk.Msg) ([]byte, error) { // SignStdTx appends a signature to a StdTx and returns a copy of it. If append // is false, it replaces the signatures already attached with the new signature. func (bldr TxBuilder) SignStdTx(name, passphrase string, stdTx auth.StdTx, appendSig bool) (signedStdTx auth.StdTx, err error) { + if bldr.chainID == "" { + return auth.StdTx{}, fmt.Errorf("chain ID required but not specified") + } + stdSignature, err := MakeSignature(bldr.keybase, name, passphrase, StdSignMsg{ ChainID: bldr.chainID, AccountNumber: bldr.accountNumber, diff --git a/x/mint/client/module_client.go b/x/mint/client/module_client.go index 96f6c00fd..857bb7992 100644 --- a/x/mint/client/module_client.go +++ b/x/mint/client/module_client.go @@ -4,6 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/mint/client/cli" + "github.com/spf13/cobra" "github.com/tendermint/go-amino" ) From 66a913c205da9e2f9639d7922184ac6d2a2014ec Mon Sep 17 00:00:00 2001 From: Alexander Bezobchuk Date: Wed, 24 Apr 2019 11:56:28 -0400 Subject: [PATCH 10/13] Merge PR #4181: Cherry pick 4135 v0.34.2 --- CHANGELOG.md | 8 ++++++++ client/context/context.go | 4 +++- client/flags.go | 2 +- docs/cosmos-hub/gaiacli.md | 4 ++++ types/result.go | 4 ++++ 5 files changed, 20 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 465be449a..ededd10f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ #### SDK +* [\#4135](https://github.com/cosmos/cosmos-sdk/pull/4135) Add further clarification +to generate only usage. + +### Bug Fixes + +#### SDK + +* [\#4135](https://github.com/cosmos/cosmos-sdk/pull/4135) Fix `NewResponseFormatBroadcastTxCommit` * [\#4053](https://github.com/cosmos/cosmos-sdk/issues/4053) Add `--inv-check-period` flag to gaiad to set period at which invariants checks will run. diff --git a/client/context/context.go b/client/context/context.go index e9d7e6782..ea87533ff 100644 --- a/client/context/context.go +++ b/client/context/context.go @@ -7,6 +7,8 @@ import ( "os" "path/filepath" + "github.com/pkg/errors" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/codec" @@ -292,7 +294,7 @@ func GetFromFields(from string, genOnly bool) (sdk.AccAddress, string, error) { if genOnly { addr, err := sdk.AccAddressFromBech32(from) if err != nil { - return nil, "", err + return nil, "", errors.Wrap(err, "must provide a valid Bech32 address for generate-only") } return addr, "", nil diff --git a/client/flags.go b/client/flags.go index 77aec7e24..26ff68e82 100644 --- a/client/flags.go +++ b/client/flags.go @@ -93,7 +93,7 @@ func PostCommands(cmds ...*cobra.Command) []*cobra.Command { c.Flags().Bool(FlagPrintResponse, true, "return tx response (only works with async = false)") c.Flags().Bool(FlagTrustNode, true, "Trust connected full node (don't verify proofs for responses)") c.Flags().Bool(FlagDryRun, false, "ignore the --gas flag and perform a simulation of a transaction, but don't broadcast it") - c.Flags().Bool(FlagGenerateOnly, false, "build an unsigned transaction and write it to STDOUT") + c.Flags().Bool(FlagGenerateOnly, false, "Build an unsigned transaction and write it to STDOUT (when enabled, the local Keybase is not accessible)") c.Flags().BoolP(FlagSkipConfirmation, "y", false, "Skip tx broadcasting prompt confirmation") // --gas can accept integers and "simulate" diff --git a/docs/cosmos-hub/gaiacli.md b/docs/cosmos-hub/gaiacli.md index 509745551..4aa133ec8 100644 --- a/docs/cosmos-hub/gaiacli.md +++ b/docs/cosmos-hub/gaiacli.md @@ -242,6 +242,10 @@ gaiacli tx sign \ unsignedSendTx.json > signedSendTx.json ``` +::: tip Note +The `--generate-only` flag prevents `gaiacli` from accessing the local keybase. +::: + You can validate the transaction's signatures by typing the following: ```bash diff --git a/types/result.go b/types/result.go index e83ed56e1..7f0590241 100644 --- a/types/result.go +++ b/types/result.go @@ -107,6 +107,10 @@ func NewResponseResultTx(res *ctypes.ResultTx, tx Tx, timestamp string) TxRespon // NewResponseFormatBroadcastTxCommit returns a TxResponse given a // ResultBroadcastTxCommit from tendermint. func NewResponseFormatBroadcastTxCommit(res *ctypes.ResultBroadcastTxCommit) TxResponse { + if res == nil { + return TxResponse{} + } + if !res.CheckTx.IsOK() { return newTxResponseCheckTx(res) } From 94bc55ef4fb26859a2a71043575ee5cf5d5d4c95 Mon Sep 17 00:00:00 2001 From: Alexander Bezobchuk Date: Wed, 24 Apr 2019 12:03:55 -0400 Subject: [PATCH 11/13] Merge PR #4183: Cherry pick 4181 into v0.34.2 * Support pagination and status query params for /staking/validators * Rename BondStatusToString to String * Cherry pick 4181 * Remove pending log --- CHANGELOG.md | 2 ++ client/lcd/swagger-ui/swagger.yaml | 18 +++++++++- client/tx/query.go | 1 - types/staking.go | 16 +++++---- x/staking/alias.go | 10 +++--- x/staking/client/rest/query.go | 28 +++++++++++++-- x/staking/keeper/validator_test.go | 5 ++- x/staking/querier/querier.go | 57 ++++++++++++++++++++++++++---- x/staking/querier/querier_test.go | 40 ++++++++++++++------- x/staking/types/validator.go | 2 +- 10 files changed, 142 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ededd10f6..097d6b3c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ to generate only usage. * [\#4135](https://github.com/cosmos/cosmos-sdk/pull/4135) Fix `NewResponseFormatBroadcastTxCommit` * [\#4053](https://github.com/cosmos/cosmos-sdk/issues/4053) Add `--inv-check-period` flag to gaiad to set period at which invariants checks will run. +* [\#4099](https://github.com/cosmos/cosmos-sdk/issues/4099) Update the /staking/validators endpoint to support +status and pagination query flags. ## 0.34.1 diff --git a/client/lcd/swagger-ui/swagger.yaml b/client/lcd/swagger-ui/swagger.yaml index cb479a63f..11deeab65 100644 --- a/client/lcd/swagger-ui/swagger.yaml +++ b/client/lcd/swagger-ui/swagger.yaml @@ -763,7 +763,23 @@ paths: description: Internal Server Error /staking/validators: get: - summary: Get all validator candidates + 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 gage number. + type: integer + x-example: 1 + - in: query + name: limit + description: The maximum number of items per page. + type: integer + x-example: 1 tags: - ICS21 produces: diff --git a/client/tx/query.go b/client/tx/query.go index 8bb8e10cd..3cf290044 100644 --- a/client/tx/query.go +++ b/client/tx/query.go @@ -162,7 +162,6 @@ func QueryTxsByTagsRequestHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) } tags, page, limit, err = rest.ParseHTTPArgs(r) - if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return diff --git a/types/staking.go b/types/staking.go index 79832ac00..54f28f972 100644 --- a/types/staking.go +++ b/types/staking.go @@ -25,19 +25,23 @@ const ( // Constant as this should not change without a hard fork. // TODO: Link to some Tendermint docs, this is very unobvious. ValidatorUpdateDelay int64 = 1 + + BondStatusUnbonded = "Unbonded" + BondStatusUnbonding = "Unbonding" + BondStatusBonded = "Bonded" ) -//BondStatusToString for pretty prints of Bond Status -func BondStatusToString(b BondStatus) string { +// String implements the Stringer interface for BondStatus. +func (b BondStatus) String() string { switch b { case 0x00: - return "Unbonded" + return BondStatusUnbonded case 0x01: - return "Unbonding" + return BondStatusUnbonding case 0x02: - return "Bonded" + return BondStatusBonded default: - panic("improper use of BondStatusToString") + panic("invalid bond status") } } diff --git a/x/staking/alias.go b/x/staking/alias.go index cee0c7b4c..d1e48ef79 100644 --- a/x/staking/alias.go +++ b/x/staking/alias.go @@ -36,6 +36,7 @@ type ( QueryValidatorParams = querier.QueryValidatorParams QueryBondsParams = querier.QueryBondsParams QueryRedelegationParams = querier.QueryRedelegationParams + QueryValidatorsParams = querier.QueryValidatorsParams ) var ( @@ -97,10 +98,11 @@ var ( NewMsgUndelegate = types.NewMsgUndelegate NewMsgBeginRedelegate = types.NewMsgBeginRedelegate - NewQuerier = querier.NewQuerier - NewQueryDelegatorParams = querier.NewQueryDelegatorParams - NewQueryValidatorParams = querier.NewQueryValidatorParams - NewQueryBondsParams = querier.NewQueryBondsParams + NewQuerier = querier.NewQuerier + NewQueryDelegatorParams = querier.NewQueryDelegatorParams + NewQueryValidatorParams = querier.NewQueryValidatorParams + NewQueryBondsParams = querier.NewQueryBondsParams + NewQueryValidatorsParams = querier.NewQueryValidatorsParams ) const ( diff --git a/x/staking/client/rest/query.go b/x/staking/client/rest/query.go index 63fcc6d24..a9439bd80 100644 --- a/x/staking/client/rest/query.go +++ b/x/staking/client/rest/query.go @@ -1,6 +1,7 @@ package rest import ( + "fmt" "net/http" "strings" @@ -15,7 +16,6 @@ import ( ) func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { - // Get all delegations from a delegator r.HandleFunc( "/staking/delegators/{delegatorAddr}/delegations", @@ -249,7 +249,31 @@ func delegatorValidatorHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) ht // HTTP request handler to query list of validators func validatorsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - res, err := cliCtx.QueryWithData("custom/staking/validators", nil) + _, page, limit, err := rest.ParseHTTPArgs(r) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + // override default limit if it wasn't provided + if l := r.FormValue("limit"); l == "" { + limit = 0 + } + + status := r.FormValue("status") + if status == "" { + status = sdk.BondStatusBonded + } + + params := staking.NewQueryValidatorsParams(page, limit, status) + bz, err := cdc.MarshalJSON(params) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + route := fmt.Sprintf("custom/%s/%s", staking.QuerierRoute, staking.QueryValidators) + res, err := cliCtx.QueryWithData(route, bz) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return diff --git a/x/staking/keeper/validator_test.go b/x/staking/keeper/validator_test.go index d2aa5b270..d359d637c 100644 --- a/x/staking/keeper/validator_test.go +++ b/x/staking/keeper/validator_test.go @@ -162,9 +162,8 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { assert.Equal( t, status, val.GetStatus(), - fmt.Sprintf("expected validator at index %v to have status: %s", - valIdx, - sdk.BondStatusToString(status))) + fmt.Sprintf("expected validator at index %v to have status: %s", valIdx, status), + ) } } diff --git a/x/staking/querier/querier.go b/x/staking/querier/querier.go index 4230dc6a4..8694a35b9 100644 --- a/x/staking/querier/querier.go +++ b/x/staking/querier/querier.go @@ -2,6 +2,7 @@ package querier import ( "fmt" + "strings" abci "github.com/tendermint/tendermint/abci/types" @@ -35,7 +36,7 @@ func NewQuerier(k keep.Keeper, cdc *codec.Codec) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) (res []byte, err sdk.Error) { switch path[0] { case QueryValidators: - return queryValidators(ctx, cdc, k) + return queryValidators(ctx, cdc, req, k) case QueryValidator: return queryValidator(ctx, cdc, req, k) case QueryValidatorDelegations: @@ -128,14 +129,47 @@ func NewQueryRedelegationParams(delegatorAddr sdk.AccAddress, srcValidatorAddr s } } -func queryValidators(ctx sdk.Context, cdc *codec.Codec, k keep.Keeper) (res []byte, err sdk.Error) { - stakingParams := k.GetParams(ctx) - validators := k.GetValidators(ctx, stakingParams.MaxValidators) +func queryValidators(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) ([]byte, sdk.Error) { + var params QueryValidatorsParams - res, errRes := codec.MarshalJSONIndent(cdc, validators) + err := cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { - return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) + return nil, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } + + stakingParams := k.GetParams(ctx) + if params.Limit == 0 { + params.Limit = int(stakingParams.MaxValidators) + } + + validators := k.GetAllValidators(ctx) + filteredVals := make([]types.Validator, 0, len(validators)) + + for _, val := range validators { + if strings.ToLower(val.GetStatus().String()) == strings.ToLower(params.Status) { + filteredVals = append(filteredVals, val) + } + } + + // get pagination bounds + start := (params.Page - 1) * params.Limit + end := params.Limit + start + if end >= len(filteredVals) { + end = len(filteredVals) + } + + if start >= len(filteredVals) { + // page is out of bounds + filteredVals = []types.Validator{} + } else { + filteredVals = filteredVals[start:end] + } + + res, err := codec.MarshalJSONIndent(cdc, filteredVals) + if err != nil { + return nil, sdk.ErrInternal(sdk.AppendMsgToErr("failed to JSON marshal result: %s", err.Error())) + } + return res, nil } @@ -354,3 +388,14 @@ func queryParameters(ctx sdk.Context, cdc *codec.Codec, k keep.Keeper) (res []by } return res, nil } + +// QueryValidatorsParams defines the params for the following queries: +// - 'custom/staking/validators' +type QueryValidatorsParams struct { + Page, Limit int + Status string +} + +func NewQueryValidatorsParams(page, limit int, status string) QueryValidatorsParams { + return QueryValidatorsParams{page, limit, status} +} diff --git a/x/staking/querier/querier_test.go b/x/staking/querier/querier_test.go index f4fe9592b..f83c95070 100644 --- a/x/staking/querier/querier_test.go +++ b/x/staking/querier/querier_test.go @@ -1,6 +1,7 @@ package querier import ( + "fmt" "testing" "github.com/stretchr/testify/require" @@ -44,9 +45,6 @@ func TestNewQuerier(t *testing.T) { require.NotNil(t, err) require.Nil(t, bz) - _, err = querier(ctx, []string{"validators"}, query) - require.Nil(t, err) - _, err = querier(ctx, []string{"pool"}, query) require.Nil(t, err) @@ -121,28 +119,44 @@ func TestQueryValidators(t *testing.T) { params := keeper.GetParams(ctx) // Create Validators - amts := []sdk.Int{sdk.NewInt(9), sdk.NewInt(8)} - var validators [2]types.Validator + amts := []sdk.Int{sdk.NewInt(9), sdk.NewInt(8), sdk.NewInt(7)} + status := []sdk.BondStatus{sdk.Bonded, sdk.Unbonded, sdk.Unbonding} + var validators [3]types.Validator for i, amt := range amts { validators[i] = types.NewValidator(sdk.ValAddress(keep.Addrs[i]), keep.PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) + validators[i], pool = validators[i].UpdateStatus(pool, status[i]) } + keeper.SetPool(ctx, pool) keeper.SetValidator(ctx, validators[0]) keeper.SetValidator(ctx, validators[1]) + keeper.SetValidator(ctx, validators[2]) // Query Validators queriedValidators := keeper.GetValidators(ctx, params.MaxValidators) - res, err := queryValidators(ctx, cdc, keeper) - require.Nil(t, err) + for i, s := range status { + queryValsParams := NewQueryValidatorsParams(1, int(params.MaxValidators), s.String()) + bz, errRes := cdc.MarshalJSON(queryValsParams) + require.Nil(t, errRes) - var validatorsResp []types.Validator - errRes := cdc.UnmarshalJSON(res, &validatorsResp) - require.Nil(t, errRes) + req := abci.RequestQuery{ + Path: fmt.Sprintf("/custom/%s/%s", types.QuerierRoute, QueryValidators), + Data: bz, + } - require.Equal(t, len(queriedValidators), len(validatorsResp)) - require.ElementsMatch(t, queriedValidators, validatorsResp) + res, err := queryValidators(ctx, cdc, req, keeper) + require.Nil(t, err) + + var validatorsResp []types.Validator + errRes = cdc.UnmarshalJSON(res, &validatorsResp) + require.Nil(t, errRes) + + require.Equal(t, 1, len(validatorsResp)) + require.ElementsMatch(t, validators[i].OperatorAddress, validatorsResp[0].OperatorAddress) + + } // Query each validator queryParams := NewQueryValidatorParams(addrVal1) @@ -153,7 +167,7 @@ func TestQueryValidators(t *testing.T) { Path: "/custom/staking/validator", Data: bz, } - res, err = queryValidator(ctx, cdc, query, keeper) + res, err := queryValidator(ctx, cdc, query, keeper) require.Nil(t, err) var validator types.Validator diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index c048de744..962345aac 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -117,7 +117,7 @@ func (v Validator) String() string { Unbonding Completion Time: %v Minimum Self Delegation: %v Commission: %s`, v.OperatorAddress, bechConsPubKey, - v.Jailed, sdk.BondStatusToString(v.Status), v.Tokens, + v.Jailed, v.Status, v.Tokens, v.DelegatorShares, v.Description, v.UnbondingHeight, v.UnbondingCompletionTime, v.MinSelfDelegation, v.Commission) } From d39bb63ffede2bdfff022cb6a1f0747ebb3efdf2 Mon Sep 17 00:00:00 2001 From: Jack Zampolin Date: Thu, 25 Apr 2019 16:41:46 -0400 Subject: [PATCH 12/13] Fix CODEOWNERS --- .github/CODEOWNERS | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 11f9e598b..3f2a5ac8a 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,9 +1,4 @@ # CODEOWNERS: https://help.github.com/articles/about-codeowners/ # Primary repo maintainers -* @ebuchman @rigelrozanski @cwgoes - -# Precious documentation -/docs/README.md @zramsay -/docs/DOCS_README.md @zramsay -/docs/.vuepress/ @zramsay +* @alessio @alexanderbez @cwgoes @jackzampolin From 1cc1148807b6ef320f5ddd0b3ec5fac9e5bf639d Mon Sep 17 00:00:00 2001 From: frog power 4000 Date: Thu, 25 Apr 2019 21:49:43 -0400 Subject: [PATCH 13/13] Update docs/cosmos-hub/upgrade-node.md Co-Authored-By: alexanderbez --- docs/cosmos-hub/upgrade-node.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cosmos-hub/upgrade-node.md b/docs/cosmos-hub/upgrade-node.md index b152417ee..a54752e74 100644 --- a/docs/cosmos-hub/upgrade-node.md +++ b/docs/cosmos-hub/upgrade-node.md @@ -60,7 +60,7 @@ cp -f genesis.json new-_enesis.json mv new_genesis.json genesis.json ``` -At this point, you might want to run a script to update the exported genesis into a genesis that is compatible with your new version. For example, the attributes of a the `Account` type changed, a script should query encoded account from the account store, unmarshall them, update their type, re-marhsall and re-store them. You can find an example of such script [here](https://github.com/cosmos/cosmos-sdk/blob/develop/contrib/export/v0.33.x-to-v0.34.0.py). +At this point, you might want to run a script to update the exported genesis into a genesis that is compatible with your new version. For example, the attributes of a the `Account` type changed, a script should query encoded account from the account store, unmarshall them, update their type, re-marshal and re-store them. You can find an example of such script [here](https://github.com/cosmos/cosmos-sdk/blob/develop/contrib/export/v0.33.x-to-v0.34.0.py). ## Reset Data