From 0d28eda1464a00ddecf356215c2677411516d54e Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Fri, 29 Jun 2018 13:02:45 -0700 Subject: [PATCH 1/9] Merge PR #1463: docs: Fix dependencies, from monorepo merge Closes #1456 --- docs/core/app1.md | 60 ++++++++++++++++----------------- docs/core/app4.md | 10 +++--- docs/core/examples/app2.go | 2 +- docs/spec/slashing/end_block.md | 10 +++--- examples/README.md | 39 +++++++++++---------- 5 files changed, 60 insertions(+), 61 deletions(-) diff --git a/docs/core/app1.md b/docs/core/app1.md index ac07e4755d..91e75966a7 100644 --- a/docs/core/app1.md +++ b/docs/core/app1.md @@ -1,7 +1,7 @@ # The Basics Here we introduce the basic components of an SDK by building `App1`, a simple bank. -Users have an account address and an account, and they can send coins around. +Users have an account address and an account, and they can send coins around. It has no authentication, and just uses JSON for serialization. The complete code can be found in [app1.go](examples/app1.go). @@ -22,11 +22,11 @@ type Msg interface { // ValidateBasic does a simple validation check that // doesn't require access to any other information. ValidateBasic() error - + // Get the canonical byte representation of the Msg. // This is what is signed. GetSignBytes() []byte - + // Signers returns the addrs of signers that must sign. // CONTRACT: All signatures must be present to be valid. // CONTRACT: Returns addrs in some deterministic order. @@ -38,7 +38,7 @@ type Msg interface { The `Msg` interface allows messages to define basic validity checks, as well as what needs to be signed and who needs to sign it. -For instance, take the simple token sending message type from app1.go: +For instance, take the simple token sending message type from app1.go: ```go // MsgSend to send coins from Input to Output @@ -134,7 +134,7 @@ type KVStore interface { Note it is unforgiving - it panics on nil keys! -The primary implementation of the KVStore is currently the IAVL store. In the future, we plan to support other Merkle KVStores, +The primary implementation of the KVStore is currently the IAVL store. In the future, we plan to support other Merkle KVStores, like Ethereum's radix trie. As we'll soon see, apps have many distinct KVStores, each with a different name and for a different concern. @@ -157,7 +157,7 @@ Only handlers which were given explict access to a store's key will be able to a ### Context -The SDK uses a `Context` to propogate common information across functions. +The SDK uses a `Context` to propogate common information across functions. Most importantly, the `Context` restricts access to KVStores based on object-capability keys. Only handlers which have been given explicit access to a key will be able to access the corresponding store. @@ -177,10 +177,10 @@ func newFooHandler(key sdk.StoreKey) sdk.Handler { [context.Context](https://golang.org/pkg/context/), which has become ubiquitous in networking middleware and routing applications as a means to easily propogate request context through handler functions. -Many methods on SDK objects receive a context as the first argument. +Many methods on SDK objects receive a context as the first argument. -The Context also contains the -[block header](https://github.com/tendermint/tendermint/blob/master/docs/spec/blockchain/blockchain.md#header), +The Context also contains the +[block header](https://github.com/tendermint/tendermint/blob/master/docs/spec/blockchain/blockchain.md#header), which includes the latest timestamp from the blockchain and other information about the latest block. See the [Context API @@ -189,7 +189,7 @@ docs](https://godoc.org/github.com/cosmos/cosmos-sdk/types#Context) for more det ### Result Handler takes a Context and Msg and returns a Result. -Result is motivated by the corresponding [ABCI result](https://github.com/tendermint/abci/blob/master/types/types.proto#L165). +Result is motivated by the corresponding [ABCI result](https://github.com/tendermint/tendermint/abci/blob/master/types/types.proto#L165). It contains return values, error information, logs, and meta data about the transaction: ```go @@ -268,7 +268,7 @@ type appAccount struct { } ``` -Coins is a useful type provided by the SDK for multi-asset accounts. +Coins is a useful type provided by the SDK for multi-asset accounts. We could just use an integer here for a single coin type, but it's worth [getting to know Coins](https://godoc.org/github.com/cosmos/cosmos-sdk/types#Coins). @@ -349,7 +349,7 @@ func handleTo(store sdk.KVStore, to sdk.Address, amt sdk.Coins) sdk.Result { ``` The handler is straight forward. We first load the KVStore from the context using the granted capability key. -Then we make two state transitions: one for the sender, one for the receiver. +Then we make two state transitions: one for the sender, one for the receiver. Each one involves JSON unmarshalling the account bytes from the store, mutating the `Coins`, and JSON marshalling back into the store. @@ -359,7 +359,7 @@ And that's that! The final piece before putting it all together is the `Tx`. While `Msg` contains the content for particular functionality in the application, the actual input -provided by the user is a serialized `Tx`. Applications may have many implementations of the `Msg` interface, +provided by the user is a serialized `Tx`. Applications may have many implementations of the `Msg` interface, but they should have only a single implementation of `Tx`: @@ -371,7 +371,7 @@ type Tx interface { } ``` -The `Tx` just wraps a `[]Msg`, and may include additional authentication data, like signatures and account nonces. +The `Tx` just wraps a `[]Msg`, and may include additional authentication data, like signatures and account nonces. Applications must specify how their `Tx` is decoded, as this is the ultimate input into the application. We'll talk more about `Tx` types later, specifically when we introduce the `StdTx`. @@ -409,11 +409,11 @@ func txDecoder(txBytes []byte) (sdk.Tx, sdk.Error) { Finally, we stitch it all together using the `BaseApp`. The BaseApp is an abstraction over the [Tendermint -ABCI](https://github.com/tendermint/abci) that +ABCI](https://github.com/tendermint/tendermint/abci) that simplifies application development by handling common low-level concerns. It serves as the mediator between the two key components of an SDK app: the store and the message handlers. The BaseApp implements the -[`abci.Application`](https://godoc.org/github.com/tendermint/abci/types#Application) interface. +[`abci.Application`](https://godoc.org/github.com/tendermint/tendermint/abci/types#Application) interface. See the [BaseApp API documentation](https://godoc.org/github.com/cosmos/cosmos-sdk/baseapp) for more details. @@ -422,22 +422,22 @@ Here is the complete setup for App1: ```go func NewApp1(logger log.Logger, db dbm.DB) *bapp.BaseApp { cdc := wire.NewCodec() - + // Create the base application object. app := bapp.NewBaseApp(app1Name, cdc, logger, db) - + // Create a capability key for accessing the account store. keyAccount := sdk.NewKVStoreKey("acc") - + // Determine how transactions are decoded. app.SetTxDecoder(txDecoder) - + // Register message routes. // Note the handler receives the keyAccount and thus // gets access to the account store. app.Router(). AddRoute("bank", NewApp1Handler(keyAccount)) - + // Mount stores and load the latest state. app.MountStoresIAVL(keyAccount) err := app.LoadLatestVersion(keyAccount) @@ -450,8 +450,8 @@ func NewApp1(logger log.Logger, db dbm.DB) *bapp.BaseApp { Every app will have such a function that defines the setup of the app. It will typically be contained in an `app.go` file. -We'll talk about how to connect this app object with the CLI, a REST API, -the logger, and the filesystem later in the tutorial. For now, note that this is where we +We'll talk about how to connect this app object with the CLI, a REST API, +the logger, and the filesystem later in the tutorial. For now, note that this is where we register handlers for messages and grant them access to stores. Here, we have only a single Msg type, `bank`, a single store for accounts, and a single handler. @@ -465,30 +465,30 @@ Since we only have one store, we only mount one. ## Execution We're now done the core logic of the app! From here, we can write tests in Go -that initialize the store with accounts and execute transactions by calling +that initialize the store with accounts and execute transactions by calling the `app.DeliverTx` method. In a real setup, the app would run as an ABCI application on top of the Tendermint consensus engine. It would be initialized by a Genesis file, and it -would be driven by blocks of transactions committed by the underlying Tendermint +would be driven by blocks of transactions committed by the underlying Tendermint consensus. We'll talk more about ABCI and how this all works a bit later, but -feel free to check the -[specification](https://github.com/tendermint/abci/blob/master/specification.md). +feel free to check the +[specification](https://github.com/tendermint/tendermint/abci/blob/master/specification.md). We'll also see how to connect our app to a complete suite of components -for running and using a live blockchain application. +for running and using a live blockchain application. For now, we note the follow sequence of events occurs when a transaction is received (through `app.DeliverTx`): - serialized transaction is received by `app.DeliverTx` - transaction is deserialized using `TxDecoder` -- for each message in the transaction, run `msg.ValidateBasic()` +- for each message in the transaction, run `msg.ValidateBasic()` - for each message in the transaction, load the appropriate handler and execute it with the message ## Conclusion -We now have a complete implementation of a simple app! +We now have a complete implementation of a simple app! In the next section, we'll add another Msg type and another store. Once we have multiple message types we'll need a better way of decoding transactions, since we'll need to decode diff --git a/docs/core/app4.md b/docs/core/app4.md index d5d70bc3f4..d7226b4666 100644 --- a/docs/core/app4.md +++ b/docs/core/app4.md @@ -5,7 +5,7 @@ delineated boundary between the Cosmos-SDK and Tendermint. It separates the logical state transition machine of your application from its secure replication across many physical machines. -By providing a clear, language agnostic boundary between applications and consensus, +By providing a clear, language agnostic boundary between applications and consensus, ABCI provides tremendous developer flexibility and [support in many languages](https://tendermint.com/ecosystem). That said, it is still quite a low-level protocol, and requires frameworks to be built to abstract over that low-level componentry. @@ -14,9 +14,9 @@ The Cosmos-SDK is one such framework. While we've already seen `DeliverTx`, the workhorse of any ABCI application, here we will introduce the other ABCI requests sent by Tendermint, and how we can use them to build more advanced applications. For a more complete -depiction of the ABCI and how its used, see +depiction of the ABCI and how its used, see [the -specification](https://github.com/tendermint/abci/blob/master/specification.md) +specification](https://github.com/tendermint/tendermint/abci/blob/master/specification.md) ## InitChain @@ -26,8 +26,8 @@ which is called once by Tendermint the very first time the application boots up. The InitChain request contains a variety of Tendermint information, like the consensus parameters and an initial validator set, but it also contains an opaque blob of -application specific bytes - typically JSON encoded. -Apps can decide what to do with all of this information by calling the +application specific bytes - typically JSON encoded. +Apps can decide what to do with all of this information by calling the `app.SetInitChainer` method. For instance, let's introduce a `GenesisAccount` struct that can be JSON encoded diff --git a/docs/core/examples/app2.go b/docs/core/examples/app2.go index ff9baa7bcd..d7490765e5 100644 --- a/docs/core/examples/app2.go +++ b/docs/core/examples/app2.go @@ -5,7 +5,7 @@ import ( "encoding/json" "fmt" - "github.com/tendermint/go-crypto" + "github.com/tendermint/tendermint/crypto" cmn "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/tmlibs/log" diff --git a/docs/spec/slashing/end_block.md b/docs/spec/slashing/end_block.md index 5958d0a215..6ac24138ba 100644 --- a/docs/spec/slashing/end_block.md +++ b/docs/spec/slashing/end_block.md @@ -1,4 +1,4 @@ -# End-Block +# End-Block ## Slashing @@ -6,16 +6,16 @@ Tendermint blocks can include [Evidence](https://github.com/tendermint/tendermint/blob/develop/docs/spec/blockchain/blockchain.md#evidence), which indicates that a validator committed malicious behaviour. The relevant information is forwarded to the application as [ABCI -Evidence](https://github.com/tendermint/abci/blob/develop/types/types.proto#L259), so the validator an be accordingly punished. +Evidence](https://github.com/tendermint/tendermint/abci/blob/develop/types/types.proto#L259), so the validator an be accordingly punished. -For some `evidence` to be valid, it must satisfy: +For some `evidence` to be valid, it must satisfy: `evidence.Timestamp >= block.Timestamp - MAX_EVIDENCE_AGE` where `evidence.Timestamp` is the timestamp in the block at height `evidence.Height` and `block.Timestamp` is the current block timestamp. -If valid evidence is included in a block, the validator's stake is reduced by `SLASH_PROPORTION` of +If valid evidence is included in a block, the validator's stake is reduced by `SLASH_PROPORTION` of what their stake was when the equivocation occurred (rather than when the evidence was discovered): ``` @@ -89,7 +89,7 @@ for val in block.Validators: // else previous == val not in block.AbsentValidators, no change // validator must be active for at least SIGNED_BLOCKS_WINDOW - // before they can be automatically unbonded for failing to be + // before they can be automatically unbonded for failing to be // included in 50% of the recent LastCommits minHeight = signInfo.StartHeight + SIGNED_BLOCKS_WINDOW minSigned = SIGNED_BLOCKS_WINDOW / 2 diff --git a/examples/README.md b/examples/README.md index 55db606c4c..3f45e025cf 100644 --- a/examples/README.md +++ b/examples/README.md @@ -6,7 +6,7 @@ what is happening under the hood. ## Setup and Install -You will need to have go installed on your computer. Please refer to the [cosmos testnet tutorial](https://cosmos.network/validators/tutorial), which will always have the most updated instructions on how to get setup with go and the cosmos repository. +You will need to have go installed on your computer. Please refer to the [cosmos testnet tutorial](https://cosmos.network/validators/tutorial), which will always have the most updated instructions on how to get setup with go and the cosmos repository. Once you have go installed, run the command: @@ -27,7 +27,7 @@ make get_tools // run make update_tools if you already had it installed make get_vendor_deps make install_examples ``` -Then run `make install_examples`, which creates binaries for `basecli` and `basecoind`. You can look at the Makefile if you want to see the details on what these make commands are doing. +Then run `make install_examples`, which creates binaries for `basecli` and `basecoind`. You can look at the Makefile if you want to see the details on what these make commands are doing. ## Using basecli and basecoind @@ -40,7 +40,7 @@ basecoind version They should read something like `0.17.1-5d18d5f`, but the versions will be constantly updating so don't worry if your version is higher that 0.17.1. That's a good thing. -Note that you can always check help in the terminal by running `basecli -h` or `basecoind -h`. It is good to check these out if you are stuck, because updates to the code base might slightly change the commands, and you might find the correct command in there. +Note that you can always check help in the terminal by running `basecli -h` or `basecoind -h`. It is good to check these out if you are stuck, because updates to the code base might slightly change the commands, and you might find the correct command in there. Let's start by initializing the basecoind daemon. Run the command @@ -60,7 +60,7 @@ And you should see something like this: } ``` -This creates the `~/.basecoind folder`, which has config.toml, genesis.json, node_key.json, priv_validator.json. Take some time to review what is contained in these files if you want to understand what is going on at a deeper level. +This creates the `~/.basecoind folder`, which has config.toml, genesis.json, node_key.json, priv_validator.json. Take some time to review what is contained in these files if you want to understand what is going on at a deeper level. ## Generating keys @@ -79,7 +79,7 @@ Repeat the passphrase: Enter your recovery seed phrase: ``` -You just created your first locally stored key, under the name alice, and this account is linked to the private key that is running the basecoind validator node. Once you do this, the ~/.basecli folder is created, which will hold the alice key and any other keys you make. Now that you have the key for alice, you can start up the blockchain by running +You just created your first locally stored key, under the name alice, and this account is linked to the private key that is running the basecoind validator node. Once you do this, the ~/.basecli folder is created, which will hold the alice key and any other keys you make. Now that you have the key for alice, you can start up the blockchain by running ``` basecoind start @@ -100,7 +100,7 @@ You can see your keys with the command: basecli keys list ``` -You should now see alice, bob and charlie's account all show up. +You should now see alice, bob and charlie's account all show up. ``` NAME: ADDRESS: PUBKEY: @@ -123,11 +123,11 @@ Where `90B0B9BE0914ECEE0B6DB74E67B07A00056B9BBD` is alice's address we got from The following command will send coins from alice, to bob: ``` -basecli send --name=alice --amount=10000mycoin --to=29D721F054537C91F618A0FDBF770DA51EF8C48D +basecli send --name=alice --amount=10000mycoin --to=29D721F054537C91F618A0FDBF770DA51EF8C48D --sequence=0 --chain-id=test-chain-AE4XQo ``` -Flag Descriptions: +Flag Descriptions: - `name` is the name you gave your key - `mycoin` is the name of the token for this basecoin demo, initialized in the genesis.json file - `sequence` is a tally of how many transactions have been made by this account. Since this is the first tx on this account, it is 0 @@ -142,7 +142,7 @@ basecli account 29D721F054537C91F618A0FDBF770DA51EF8C48D Now lets send some from bob to charlie. Make sure you send less than bob has, otherwise the transaction will fail: ``` -basecli send --name=bob --amount=5000mycoin --to=2E8E13EEB8E3F0411ACCBC9BE0384732C24FBD5E +basecli send --name=bob --amount=5000mycoin --to=2E8E13EEB8E3F0411ACCBC9BE0384732C24FBD5E --sequence=0 --chain-id=test-chain-AE4XQo ``` @@ -151,7 +151,7 @@ Note how we use the ``--name`` flag to select a different account to send from. Lets now try to send from bob back to alice: ``` -basecli send --name=bob --amount=3000mycoin --to=90B0B9BE0914ECEE0B6DB74E67B07A00056B9BBD +basecli send --name=bob --amount=3000mycoin --to=90B0B9BE0914ECEE0B6DB74E67B07A00056B9BBD --sequence=1 --chain-id=test-chain-AE4XQo ``` @@ -171,8 +171,8 @@ That is the basic implementation of basecoin! **WARNING:** Running these commands will wipe out any existing information in both the ``~/.basecli`` and ``~/.basecoind`` directories, including private keys. This should be no problem considering that basecoin -is just an example, but it is always good to pay extra attention when -you are removing private keys, in any scenario involving a blockchain. +is just an example, but it is always good to pay extra attention when +you are removing private keys, in any scenario involving a blockchain. To remove all the files created and refresh your environment (e.g., if starting this tutorial again or trying something new), the following @@ -212,7 +212,7 @@ The Basecoin state consists entirely of a set of accounts. Each account contains an address, a public key, a balance in many different coin denominations, and a strictly increasing sequence number for replay protection. This type of account was directly inspired by accounts in Ethereum, and is -unlike Bitcoin's use of Unspent Transaction Outputs (UTXOs). +unlike Bitcoin's use of Unspent Transaction Outputs (UTXOs). ``` type BaseAccount struct { @@ -225,7 +225,7 @@ type BaseAccount struct { You can also add more fields to accounts, and basecoin actually does so. Basecoin adds a Name field in order to show how easily the base account structure can be -modified to suit any applications needs. It takes the `auth.BaseAccount` we see above, +modified to suit any applications needs. It takes the `auth.BaseAccount` we see above, and extends it with `Name`. ``` @@ -256,7 +256,7 @@ Accounts are serialized and stored in a Merkle tree under the key Typically, the address of the account is the 20-byte ``RIPEMD160`` hash of the public key, but other formats are acceptable as well, as defined in the `Tendermint crypto -library `__. The Merkle tree +library `__. The Merkle tree used in Basecoin is a balanced, binary search tree, which we call an `IAVL tree `__. @@ -293,15 +293,15 @@ Note the `SendTx` includes a field for `Gas` and `Fee`. The transaction, while the `Fee` refers to the total amount paid in fees. This is slightly different from Ethereum's concept of `Gas` and `GasPrice`, where `Fee = Gas x GasPrice`. In Basecoin, the `Gas` -and `Fee` are independent, and the `GasPrice` is implicit. +and `Fee` are independent, and the `GasPrice` is implicit. In Basecoin, the `Fee` is meant to be used by the validators to inform the ordering of transactions, like in Bitcoin. And the `Gas` is meant to be used by the application plugin to control its execution. There is currently no means to pass `Fee` information to the Tendermint -validators, but it will come soon... so this version of Basecoin does -not actually fully implement fees and gas, but it still allows us -to send transactions between accounts. +validators, but it will come soon... so this version of Basecoin does +not actually fully implement fees and gas, but it still allows us +to send transactions between accounts. Note also that the `PubKey` only needs to be sent for `Sequence == 0`. After that, it is stored under the account in the @@ -318,4 +318,3 @@ serve as a basic unit of decentralized exchange. When using multiple inputs and outputs, you must make sure that the sum of coins of the inputs equals the sum of coins of the outputs (no creating money), and that all accounts that provide inputs have signed the transaction. - From 47e4682d9f73b74a59ebf15f0ebbf7d8009379d8 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Fri, 29 Jun 2018 13:30:12 -0700 Subject: [PATCH 2/9] Merge PR #1415: x/stake: Limit the size of rationals from user input * x/stake: Limit the size of rationals from user input This commit sets the maximum number of decimal points that can be passed in from messages. This is enforced on the validate basic of MsgBeginUnbonding and MsgBeginRedelegation. The cli has been updated to truncate the user input to the specified precision. This also updates types/rational to return big ints for Num() and Den(). Closes #887 * Switch NewFromDecimal to error instead of truncating --- CHANGELOG.md | 1 + types/int.go | 4 ++++ types/rational.go | 29 ++++++++++++++++++++++------- types/rational_test.go | 25 ++++++++++++++++--------- x/stake/client/cli/tx.go | 5 +++-- x/stake/client/rest/tx.go | 5 +++-- x/stake/types/errors.go | 6 ++++++ x/stake/types/msg.go | 17 ++++++++++++++++- 8 files changed, 71 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b48c46a16..d62e3eed1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -67,6 +67,7 @@ FIXES * \#1367 - set ChainID in InitChain * \#1353 - CLI: Show pool shares fractions in human-readable format * \#1258 - printing big.rat's can no longer overflow int64 +* \#887 - limit the size of rationals that can be passed in from user input IMPROVEMENTS * bank module uses go-wire codec instead of 'encoding/json' diff --git a/types/int.go b/types/int.go index 760fc607b5..d04c6a80cd 100644 --- a/types/int.go +++ b/types/int.go @@ -227,6 +227,10 @@ func (i Int) Neg() (res Int) { return Int{neg(i.i)} } +func (i Int) String() string { + return i.i.String() +} + // MarshalAmino defines custom encoding scheme func (i Int) MarshalAmino() (string, error) { if i.i == nil { // Necessary since default Uint initialization has i.i as nil diff --git a/types/rational.go b/types/rational.go index a192aa316f..f24831f89e 100644 --- a/types/rational.go +++ b/types/rational.go @@ -38,8 +38,8 @@ func NewRat(Numerator int64, Denominator ...int64) Rat { } // create a rational from decimal string or integer string -func NewRatFromDecimal(decimalStr string) (f Rat, err Error) { - +// precision is the number of values after the decimal point which should be read +func NewRatFromDecimal(decimalStr string, prec int) (f Rat, err Error) { // first extract any negative symbol neg := false if string(decimalStr[0]) == "-" { @@ -61,6 +61,9 @@ func NewRatFromDecimal(decimalStr string) (f Rat, err Error) { if len(str[0]) == 0 || len(str[1]) == 0 { return f, ErrUnknownRequest("not a decimal string") } + if len(str[1]) > prec { + return f, ErrUnknownRequest("string has too many decimals") + } numStr = str[0] + str[1] len := int64(len(str[1])) denom = new(big.Int).Exp(big.NewInt(10), big.NewInt(len), nil).Int64() @@ -69,8 +72,20 @@ func NewRatFromDecimal(decimalStr string) (f Rat, err Error) { } num, errConv := strconv.Atoi(numStr) - if errConv != nil { - return f, ErrUnknownRequest(errConv.Error()) + if errConv != nil && strings.HasSuffix(errConv.Error(), "value out of range") { + // resort to big int, don't make this default option for efficiency + numBig, success := new(big.Int).SetString(numStr, 10) + if success != true { + return f, ErrUnknownRequest("not a decimal string") + } + + if neg { + numBig.Neg(numBig) + } + + return NewRatFromBigInt(numBig, big.NewInt(denom)), nil + } else if errConv != nil { + return f, ErrUnknownRequest("not a decimal string") } if neg { @@ -105,9 +120,9 @@ func NewRatFromInt(num Int, denom ...Int) Rat { } //nolint -func (r Rat) Num() int64 { return r.Rat.Num().Int64() } // Num - return the numerator -func (r Rat) Denom() int64 { return r.Rat.Denom().Int64() } // Denom - return the denominator -func (r Rat) IsZero() bool { return r.Num() == 0 } // IsZero - Is the Rat equal to zero +func (r Rat) Num() Int { return Int{r.Rat.Num()} } // Num - return the numerator +func (r Rat) Denom() Int { return Int{r.Rat.Denom()} } // Denom - return the denominator +func (r Rat) IsZero() bool { return r.Num().IsZero() } // IsZero - Is the Rat equal to zero func (r Rat) Equal(r2 Rat) bool { return (r.Rat).Cmp(r2.Rat) == 0 } func (r Rat) GT(r2 Rat) bool { return (r.Rat).Cmp(r2.Rat) == 1 } // greater than func (r Rat) GTE(r2 Rat) bool { return !r.LT(r2) } // greater than or equal diff --git a/types/rational_test.go b/types/rational_test.go index 43c9ddd575..a137ca498e 100644 --- a/types/rational_test.go +++ b/types/rational_test.go @@ -21,6 +21,8 @@ func TestNew(t *testing.T) { } func TestNewFromDecimal(t *testing.T) { + largeBigInt, success := new(big.Int).SetString("3109736052979742687701388262607869", 10) + require.True(t, success) tests := []struct { decimalStr string expErr bool @@ -31,7 +33,13 @@ func TestNewFromDecimal(t *testing.T) { {"1.1", false, NewRat(11, 10)}, {"0.75", false, NewRat(3, 4)}, {"0.8", false, NewRat(4, 5)}, - {"0.11111", false, NewRat(11111, 100000)}, + {"0.11111", true, NewRat(1111, 10000)}, + {"628240629832763.5738930323617075341", true, NewRat(3141203149163817869, 5000)}, + {"621947210595948537540277652521.5738930323617075341", + true, NewRatFromBigInt(largeBigInt, big.NewInt(5000))}, + {"628240629832763.5738", false, NewRat(3141203149163817869, 5000)}, + {"621947210595948537540277652521.5738", + false, NewRatFromBigInt(largeBigInt, big.NewInt(5000))}, {".", true, Rat{}}, {".0", true, Rat{}}, {"1.", true, Rat{}}, @@ -41,22 +49,21 @@ func TestNewFromDecimal(t *testing.T) { } for _, tc := range tests { - - res, err := NewRatFromDecimal(tc.decimalStr) + res, err := NewRatFromDecimal(tc.decimalStr, 4) if tc.expErr { assert.NotNil(t, err, tc.decimalStr) } else { - assert.Nil(t, err) - assert.True(t, res.Equal(tc.exp)) + require.Nil(t, err, tc.decimalStr) + require.True(t, res.Equal(tc.exp), tc.decimalStr) } // negative tc - res, err = NewRatFromDecimal("-" + tc.decimalStr) + res, err = NewRatFromDecimal("-"+tc.decimalStr, 4) if tc.expErr { assert.NotNil(t, err, tc.decimalStr) } else { - assert.Nil(t, err) - assert.True(t, res.Equal(tc.exp.Mul(NewRat(-1)))) + assert.Nil(t, err, tc.decimalStr) + assert.True(t, res.Equal(tc.exp.Mul(NewRat(-1))), tc.decimalStr) } } } @@ -133,7 +140,7 @@ func TestArithmetic(t *testing.T) { assert.True(t, tc.resAdd.Equal(tc.r1.Add(tc.r2)), "r1 %v, r2 %v", tc.r1.Rat, tc.r2.Rat) assert.True(t, tc.resSub.Equal(tc.r1.Sub(tc.r2)), "r1 %v, r2 %v", tc.r1.Rat, tc.r2.Rat) - if tc.r2.Num() == 0 { // panic for divide by zero + if tc.r2.Num().IsZero() { // panic for divide by zero assert.Panics(t, func() { tc.r1.Quo(tc.r2) }) } else { assert.True(t, tc.resDiv.Equal(tc.r1.Quo(tc.r2)), "r1 %v, r2 %v", tc.r1.Rat, tc.r2.Rat) diff --git a/x/stake/client/cli/tx.go b/x/stake/client/cli/tx.go index b7941e2bb8..b0fa2e524a 100644 --- a/x/stake/client/cli/tx.go +++ b/x/stake/client/cli/tx.go @@ -12,6 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/wire" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/stake/types" ) // create create validator command @@ -219,7 +220,7 @@ func getShares(storeName string, cdc *wire.Codec, sharesAmountStr, sharesPercent case sharesAmountStr == "" && sharesPercentStr == "": return sharesAmount, errors.Errorf("can either specify the amount OR the percent of the shares, not both") case sharesAmountStr != "": - sharesAmount, err = sdk.NewRatFromDecimal(sharesAmountStr) + sharesAmount, err = sdk.NewRatFromDecimal(sharesAmountStr, types.MaxBondDenominatorPrecision) if err != nil { return sharesAmount, err } @@ -228,7 +229,7 @@ func getShares(storeName string, cdc *wire.Codec, sharesAmountStr, sharesPercent } case sharesPercentStr != "": var sharesPercent sdk.Rat - sharesPercent, err = sdk.NewRatFromDecimal(sharesPercentStr) + sharesPercent, err = sdk.NewRatFromDecimal(sharesPercentStr, types.MaxBondDenominatorPrecision) if err != nil { return sharesAmount, err } diff --git a/x/stake/client/rest/tx.go b/x/stake/client/rest/tx.go index 1d85476622..51a854528d 100644 --- a/x/stake/client/rest/tx.go +++ b/x/stake/client/rest/tx.go @@ -14,6 +14,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/stake" + "github.com/cosmos/cosmos-sdk/x/stake/types" ) func registerTxRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { @@ -145,7 +146,7 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } - shares, err := sdk.NewRatFromDecimal(msg.SharesAmount) + shares, err := sdk.NewRatFromDecimal(msg.SharesAmount, types.MaxBondDenominatorPrecision) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode shares amount. Error: %s", err.Error()))) @@ -210,7 +211,7 @@ func editDelegationsRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx conte w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) return } - shares, err := sdk.NewRatFromDecimal(msg.SharesAmount) + shares, err := sdk.NewRatFromDecimal(msg.SharesAmount, types.MaxBondDenominatorPrecision) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Couldn't decode shares amount. Error: %s", err.Error()))) diff --git a/x/stake/types/errors.go b/x/stake/types/errors.go index 622bd0e1a9..2914741f45 100644 --- a/x/stake/types/errors.go +++ b/x/stake/types/errors.go @@ -79,6 +79,12 @@ func ErrNotEnoughDelegationShares(codespace sdk.CodespaceType, shares string) sd func ErrBadSharesAmount(codespace sdk.CodespaceType) sdk.Error { return sdk.NewError(codespace, CodeInvalidDelegation, "shares must be > 0") } +func ErrBadSharesPrecision(codespace sdk.CodespaceType) sdk.Error { + return sdk.NewError(codespace, CodeInvalidDelegation, + fmt.Sprintf("shares denominator must be < %s, try reducing the number of decimal points", + maximumBondingRationalDenominator.String()), + ) +} func ErrBadSharesPercent(codespace sdk.CodespaceType) sdk.Error { return sdk.NewError(codespace, CodeInvalidDelegation, "shares percent must be >0 and <=1") } diff --git a/x/stake/types/msg.go b/x/stake/types/msg.go index f8b8e67170..878c1ba17b 100644 --- a/x/stake/types/msg.go +++ b/x/stake/types/msg.go @@ -1,6 +1,8 @@ package types import ( + "math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/crypto" ) @@ -8,11 +10,18 @@ import ( // name to idetify transaction types const MsgType = "stake" -//Verify interface at compile time +// Maximum amount of decimal points in the decimal representation of rationals +// used in MsgBeginUnbonding / MsgBeginRedelegate +const MaxBondDenominatorPrecision = 8 + +// Verify interface at compile time var _, _, _ sdk.Msg = &MsgCreateValidator{}, &MsgEditValidator{}, &MsgDelegate{} var _, _ sdk.Msg = &MsgBeginUnbonding{}, &MsgCompleteUnbonding{} var _, _ sdk.Msg = &MsgBeginRedelegate{}, &MsgCompleteRedelegate{} +// Initialize Int for the denominator +var maximumBondingRationalDenominator sdk.Int = sdk.NewInt(int64(math.Pow10(MaxBondDenominatorPrecision))) + //______________________________________________________________________ // MsgCreateValidator - struct for unbonding transactions @@ -234,6 +243,9 @@ func (msg MsgBeginRedelegate) ValidateBasic() sdk.Error { if msg.SharesAmount.LTE(sdk.ZeroRat()) { return ErrBadSharesAmount(DefaultCodespace) } + if msg.SharesAmount.Denom().GT(maximumBondingRationalDenominator) { + return ErrBadSharesPrecision(DefaultCodespace) + } return nil } @@ -340,6 +352,9 @@ func (msg MsgBeginUnbonding) ValidateBasic() sdk.Error { if msg.SharesAmount.LTE(sdk.ZeroRat()) { return ErrBadSharesAmount(DefaultCodespace) } + if msg.SharesAmount.Denom().GT(maximumBondingRationalDenominator) { + return ErrBadSharesPrecision(DefaultCodespace) + } return nil } From 097dd8a164c797a9c454c47416b91297838d4d51 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Fri, 29 Jun 2018 15:22:24 -0700 Subject: [PATCH 3/9] tools: Add unparam linter (#1443) * tools: Add unparam linter unparam detects unused parameters in functions, and a parameter to a function which only ever takes on one value. The latter is an indication that more tests are required. There are many nolints in this PR, as I believe that writing tests to fix alot of these situations is out of scope for this PR / it will be changed in future commits. There are some nolints for when we have to comply to normal api's. * crypto/keys no longer used by x/gov/client/rest/rest.go --- CHANGELOG.md | 1 + Makefile | 2 +- client/lcd/root.go | 4 +-- client/lcd/test_helpers.go | 2 +- client/lcd/version.go | 3 +- cmd/gaia/app/app.go | 1 + cmd/gaia/app/genesis.go | 4 +-- cmd/gaia/cmd/gaiadebug/hack.go | 1 + examples/basecoin/app/app.go | 1 + examples/democoin/app/app.go | 1 + examples/democoin/x/simplestake/errors.go | 1 + examples/democoin/x/simplestake/handler.go | 10 +++---- server/init.go | 4 +-- server/mock/store.go | 2 +- server/mock/store_test.go | 2 +- store/iavlstore.go | 2 ++ tools/Makefile | 21 ++++++++++++-- x/auth/mock/simulate_block.go | 2 +- x/gov/client/rest/rest.go | 32 +++++++++++----------- x/gov/handler.go | 6 ++-- x/gov/keeper.go | 8 +++--- x/gov/tally.go | 2 +- x/ibc/client/cli/relay.go | 1 + x/ibc/errors.go | 1 + x/slashing/app_test.go | 2 +- x/stake/client/rest/query.go | 18 ++++++------ x/stake/keeper/test_common.go | 2 ++ x/stake/keeper/validator.go | 8 +++--- x/stake/keeper/validator_test.go | 22 +++++++-------- x/stake/types/test_common.go | 3 ++ x/stake/types/validator.go | 5 ++-- 31 files changed, 102 insertions(+), 72 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d62e3eed1e..6393dd4d53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,7 @@ FEATURES * unconvert * ineffassign * errcheck + * unparam * [tools] Add `make format` command to automate fixing misspell and gofmt errors. * [server] Default config now creates a profiler at port 6060, and increase p2p send/recv rates * [tests] Add WaitForNextNBlocksTM helper method diff --git a/Makefile b/Makefile index cc70aa6f72..96ffb47a2c 100644 --- a/Makefile +++ b/Makefile @@ -108,7 +108,7 @@ test_cover: @bash tests/test_cover.sh test_lint: - gometalinter.v2 --disable-all --enable='golint' --enable='misspell' --enable='unconvert' --enable='ineffassign' --linter='vet:go vet -composites=false:PATH:LINE:MESSAGE' --enable='vet' --deadline=500s --vendor ./... + gometalinter.v2 --disable-all --enable='golint' --enable='misspell' --enable='unparam' --enable='unconvert' --enable='ineffassign' --linter='vet:go vet -composites=false:PATH:LINE:MESSAGE' --enable='vet' --deadline=500s --vendor ./... !(gometalinter.v2 --disable-all --enable='errcheck' --vendor ./... | grep -v "client/") find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" | xargs gofmt -d -s diff --git a/client/lcd/root.go b/client/lcd/root.go index f9c30de861..d84e7d9f1c 100644 --- a/client/lcd/root.go +++ b/client/lcd/root.go @@ -76,7 +76,7 @@ func createHandler(cdc *wire.Codec) http.Handler { // TODO make more functional? aka r = keys.RegisterRoutes(r) r.HandleFunc("/version", CLIVersionRequestHandler).Methods("GET") - r.HandleFunc("/node_version", NodeVersionRequestHandler(cdc, ctx)).Methods("GET") + r.HandleFunc("/node_version", NodeVersionRequestHandler(ctx)).Methods("GET") keys.RegisterRoutes(r) rpc.RegisterRoutes(ctx, r) tx.RegisterRoutes(ctx, r, cdc) @@ -84,6 +84,6 @@ func createHandler(cdc *wire.Codec) http.Handler { bank.RegisterRoutes(ctx, r, cdc, kb) ibc.RegisterRoutes(ctx, r, cdc, kb) stake.RegisterRoutes(ctx, r, cdc, kb) - gov.RegisterRoutes(ctx, r, cdc, kb) + gov.RegisterRoutes(ctx, r, cdc) return r } diff --git a/client/lcd/test_helpers.go b/client/lcd/test_helpers.go index 0d5d7cad2f..ecf6748a57 100644 --- a/client/lcd/test_helpers.go +++ b/client/lcd/test_helpers.go @@ -132,7 +132,7 @@ func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.Address) ( for _, gdValidator := range genDoc.Validators { pk := gdValidator.PubKey validatorsPKs = append(validatorsPKs, pk) // append keys for output - appGenTx, _, _, err := gapp.GaiaAppGenTxNF(cdc, pk, pk.Address(), "test_val1", true) + appGenTx, _, _, err := gapp.GaiaAppGenTxNF(cdc, pk, pk.Address(), "test_val1") require.NoError(t, err) appGenTxs = append(appGenTxs, appGenTx) } diff --git a/client/lcd/version.go b/client/lcd/version.go index be097393e0..4e328b7a0b 100644 --- a/client/lcd/version.go +++ b/client/lcd/version.go @@ -6,7 +6,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/wire" ) // cli version REST handler endpoint @@ -16,7 +15,7 @@ func CLIVersionRequestHandler(w http.ResponseWriter, r *http.Request) { } // connected node version REST handler endpoint -func NodeVersionRequestHandler(cdc *wire.Codec, ctx context.CoreContext) http.HandlerFunc { +func NodeVersionRequestHandler(ctx context.CoreContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { version, err := ctx.Query("/app/version") if err != nil { diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index bdb2d3a2d0..399c816830 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -129,6 +129,7 @@ func (app *GaiaApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) ab } // application updates every end block +// nolint: unparam func (app *GaiaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) diff --git a/cmd/gaia/app/genesis.go b/cmd/gaia/app/genesis.go index ce4b6ccfca..805c6d4f79 100644 --- a/cmd/gaia/app/genesis.go +++ b/cmd/gaia/app/genesis.go @@ -103,12 +103,12 @@ func GaiaAppGenTx(cdc *wire.Codec, pk crypto.PubKey, genTxConfig config.GenTx) ( cliPrint = json.RawMessage(bz) - appGenTx, _, validator, err = GaiaAppGenTxNF(cdc, pk, addr, genTxConfig.Name, genTxConfig.Overwrite) + appGenTx, _, validator, err = GaiaAppGenTxNF(cdc, pk, addr, genTxConfig.Name) return } // Generate a gaia genesis transaction without flags -func GaiaAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.Address, name string, overwrite bool) ( +func GaiaAppGenTxNF(cdc *wire.Codec, pk crypto.PubKey, addr sdk.Address, name string) ( appGenTx, cliPrint json.RawMessage, validator tmtypes.GenesisValidator, err error) { var bz []byte diff --git a/cmd/gaia/cmd/gaiadebug/hack.go b/cmd/gaia/cmd/gaiadebug/hack.go index 0cb1160f5b..74b42adb38 100644 --- a/cmd/gaia/cmd/gaiadebug/hack.go +++ b/cmd/gaia/cmd/gaiadebug/hack.go @@ -210,6 +210,7 @@ func (app *GaiaApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) ab } // application updates every end block +// nolint: unparam func (app *GaiaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) diff --git a/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index de29a1316b..089d1ca23c 100644 --- a/examples/basecoin/app/app.go +++ b/examples/basecoin/app/app.go @@ -120,6 +120,7 @@ func (app *BasecoinApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock } // application updates every end block +// nolint: unparam func (app *BasecoinApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { validatorUpdates := stake.EndBlocker(ctx, app.stakeKeeper) diff --git a/examples/democoin/app/app.go b/examples/democoin/app/app.go index a87dc15e44..195af0c9ea 100644 --- a/examples/democoin/app/app.go +++ b/examples/democoin/app/app.go @@ -117,6 +117,7 @@ func MakeCodec() *wire.Codec { } // custom logic for democoin initialization +// nolint: unparam func (app *DemocoinApp) initChainerFn(coolKeeper cool.Keeper, powKeeper pow.Keeper) sdk.InitChainer { return func(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { stateJSON := req.AppStateBytes diff --git a/examples/democoin/x/simplestake/errors.go b/examples/democoin/x/simplestake/errors.go index 0effba9c0a..8125e57aab 100644 --- a/examples/democoin/x/simplestake/errors.go +++ b/examples/democoin/x/simplestake/errors.go @@ -32,6 +32,7 @@ func ErrEmptyStake(codespace sdk.CodespaceType) sdk.Error { // ----------------------------- // Helpers +// nolint: unparam func newError(codespace sdk.CodespaceType, code sdk.CodeType, msg string) sdk.Error { return sdk.NewError(codespace, code, msg) } diff --git a/examples/democoin/x/simplestake/handler.go b/examples/democoin/x/simplestake/handler.go index 6b21879e92..114f066436 100644 --- a/examples/democoin/x/simplestake/handler.go +++ b/examples/democoin/x/simplestake/handler.go @@ -7,18 +7,18 @@ import ( // NewHandler returns a handler for "simplestake" type messages. func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { - switch msg := msg.(type) { + switch msg.(type) { case MsgBond: - return handleMsgBond(ctx, k, msg) + return handleMsgBond() case MsgUnbond: - return handleMsgUnbond(ctx, k, msg) + return handleMsgUnbond() default: return sdk.ErrUnknownRequest("No match for message type.").Result() } } } -func handleMsgBond(ctx sdk.Context, k Keeper, msg MsgBond) sdk.Result { +func handleMsgBond() sdk.Result { // Removed ValidatorSet from result because it does not get used. // TODO: Implement correct bond/unbond handling return sdk.Result{ @@ -26,7 +26,7 @@ func handleMsgBond(ctx sdk.Context, k Keeper, msg MsgBond) sdk.Result { } } -func handleMsgUnbond(ctx sdk.Context, k Keeper, msg MsgUnbond) sdk.Result { +func handleMsgUnbond() sdk.Result { return sdk.Result{ Code: sdk.ABCICodeOK, } diff --git a/server/init.go b/server/init.go index 3bfe06e5fb..ed1727e35e 100644 --- a/server/init.go +++ b/server/init.go @@ -226,7 +226,7 @@ func initWithConfig(cdc *wire.Codec, appInit AppInit, config *cfg.Config, initCo var persistentPeers string if initConfig.GenTxs { - validators, appGenTxs, persistentPeers, err = processGenTxs(initConfig.GenTxsDir, cdc, appInit) + validators, appGenTxs, persistentPeers, err = processGenTxs(initConfig.GenTxsDir, cdc) if err != nil { return } @@ -263,7 +263,7 @@ func initWithConfig(cdc *wire.Codec, appInit AppInit, config *cfg.Config, initCo } // append a genesis-piece -func processGenTxs(genTxsDir string, cdc *wire.Codec, appInit AppInit) ( +func processGenTxs(genTxsDir string, cdc *wire.Codec) ( validators []tmtypes.GenesisValidator, appGenTxs []json.RawMessage, persistentPeers string, err error) { var fos []os.FileInfo diff --git a/server/mock/store.go b/server/mock/store.go index f00c4dd8d0..9dca581596 100644 --- a/server/mock/store.go +++ b/server/mock/store.go @@ -115,6 +115,6 @@ func (kv kvStore) ReverseSubspaceIterator(prefix []byte) sdk.Iterator { panic("not implemented") } -func NewCommitMultiStore(db dbm.DB) sdk.CommitMultiStore { +func NewCommitMultiStore() sdk.CommitMultiStore { return multiStore{kv: make(map[sdk.StoreKey]kvStore)} } diff --git a/server/mock/store_test.go b/server/mock/store_test.go index e920609476..bd01244667 100644 --- a/server/mock/store_test.go +++ b/server/mock/store_test.go @@ -12,7 +12,7 @@ import ( func TestStore(t *testing.T) { db := dbm.NewMemDB() - cms := NewCommitMultiStore(db) + cms := NewCommitMultiStore() key := sdk.NewKVStoreKey("test") cms.MountStoreWithDB(key, sdk.StoreTypeIAVL, db) diff --git a/store/iavlstore.go b/store/iavlstore.go index 31463e977e..5758802c6e 100644 --- a/store/iavlstore.go +++ b/store/iavlstore.go @@ -47,6 +47,8 @@ type iavlStore struct { } // CONTRACT: tree should be fully loaded. +// TODO: use more numHistory's, so the below nolint can be removed +// nolint: unparam func newIAVLStore(tree *iavl.VersionedTree, numHistory int64) *iavlStore { st := &iavlStore{ tree: tree, diff --git a/tools/Makefile b/tools/Makefile index 516de1a426..195e67aa52 100644 --- a/tools/Makefile +++ b/tools/Makefile @@ -11,6 +11,7 @@ UNCONVERT = github.com/mdempsky/unconvert INEFFASSIGN = github.com/gordonklaus/ineffassign MISSPELL = github.com/client9/misspell/cmd/misspell ERRCHECK = github.com/kisielk/errcheck +UNPARAM = mvdan.cc/unparam DEP_CHECK := $(shell command -v dep 2> /dev/null) GOLINT_CHECK := $(shell command -v golint 2> /dev/null) @@ -19,6 +20,7 @@ UNCONVERT_CHECK := $(shell command -v unconvert 2> /dev/null) INEFFASSIGN_CHECK := $(shell command -v ineffassign 2> /dev/null) MISSPELL_CHECK := $(shell command -v misspell 2> /dev/null) ERRCHECK_CHECK := $(shell command -v errcheck 2> /dev/null) +UNPARAM_CHECK := $(shell command -v unparam 2> /dev/null) check_tools: ifndef DEP_CHECK @@ -51,11 +53,16 @@ ifndef MISSPELL_CHECK else @echo "Found misspell in path." endif -ifndef MISSPELL_CHECK +ifndef ERRCHECK_CHECK @echo "No errcheck in path. Install with 'make get_tools'." else @echo "Found errcheck in path." endif +ifndef UNPARAM_CHECK + @echo "No unparam in path. Install with 'make get_tools'." +else + @echo "Found unparam in path." +endif get_tools: ifdef DEP_CHECK @@ -95,11 +102,17 @@ else go get -v $(MISSPELL) endif ifdef ERRCHECK_CHECK - @echo "misspell is already installed. Run 'make update_tools' to update." + @echo "errcheck is already installed. Run 'make update_tools' to update." else - @echo "Installing misspell" + @echo "Installing errcheck" go get -v $(ERRCHECK) endif +ifdef UNPARAM_CHECK + @echo "unparam is already installed. Run 'make update_tools' to update." +else + @echo "Installing unparam" + go get -v $(UNPARAM) +endif update_tools: @echo "Updating dep" @@ -116,6 +129,8 @@ update_tools: go get -u -v $(MISSPELL) @echo "Updating errcheck" go get -u -v $(ERRCHECK) + @echo "Updating unparam" + go get -u -v $(UNPARAM) # To avoid unintended conflicts with file names, always add to .PHONY # unless there is a reason not to. diff --git a/x/auth/mock/simulate_block.go b/x/auth/mock/simulate_block.go index 00ffc30df1..a047fbf4b6 100644 --- a/x/auth/mock/simulate_block.go +++ b/x/auth/mock/simulate_block.go @@ -76,7 +76,7 @@ func incrementAllSequenceNumbers(initSeqNums []int64) { } // check a transaction result -func SignCheck(t *testing.T, app *baseapp.BaseApp, msgs []sdk.Msg, accnums []int64, seq []int64, priv ...crypto.PrivKeyEd25519) sdk.Result { +func SignCheck(app *baseapp.BaseApp, msgs []sdk.Msg, accnums []int64, seq []int64, priv ...crypto.PrivKeyEd25519) sdk.Result { tx := GenTx(msgs, accnums, seq, priv...) res := app.Check(tx) return res diff --git a/x/gov/client/rest/rest.go b/x/gov/client/rest/rest.go index a47823ab32..3e185dc914 100644 --- a/x/gov/client/rest/rest.go +++ b/x/gov/client/rest/rest.go @@ -6,7 +6,6 @@ import ( "strconv" "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/gov" @@ -20,19 +19,20 @@ const ( RestProposalID = "proposalID" RestDepositer = "depositer" RestVoter = "voter" + storeName = "gov" ) // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { - r.HandleFunc("/gov/proposals", postProposalHandlerFn(cdc, kb, ctx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), depositHandlerFn(cdc, kb, ctx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), voteHandlerFn(cdc, kb, ctx)).Methods("POST") +func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec) { + r.HandleFunc("/gov/proposals", postProposalHandlerFn(cdc, ctx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), depositHandlerFn(cdc, ctx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), voteHandlerFn(cdc, ctx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}", RestProposalID), queryProposalHandlerFn("gov", cdc, kb, ctx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits/{%s}", RestProposalID, RestDepositer), queryDepositHandlerFn("gov", cdc, kb, ctx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes/{%s}", RestProposalID, RestVoter), queryVoteHandlerFn("gov", cdc, kb, ctx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}", RestProposalID), queryProposalHandlerFn(cdc)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits/{%s}", RestProposalID, RestDepositer), queryDepositHandlerFn(cdc)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes/{%s}", RestProposalID, RestVoter), queryVoteHandlerFn(cdc)).Methods("GET") - r.HandleFunc("/gov/proposals", queryProposalsWithParameterFn("gov", cdc, kb, ctx)).Methods("GET") + r.HandleFunc("/gov/proposals", queryProposalsWithParameterFn(cdc)).Methods("GET") } type postProposalReq struct { @@ -56,7 +56,7 @@ type voteReq struct { Option string `json:"option"` // option from OptionSet chosen by the voter } -func postProposalHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { +func postProposalHandlerFn(cdc *wire.Codec, ctx context.CoreContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req postProposalReq err := buildReq(w, r, cdc, &req) @@ -93,7 +93,7 @@ func postProposalHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreCon } } -func depositHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { +func depositHandlerFn(cdc *wire.Codec, ctx context.CoreContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -141,7 +141,7 @@ func depositHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) } } -func voteHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { +func voteHandlerFn(cdc *wire.Codec, ctx context.CoreContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -195,7 +195,7 @@ func voteHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) ht } } -func queryProposalHandlerFn(storeName string, cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { +func queryProposalHandlerFn(cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -236,7 +236,7 @@ func queryProposalHandlerFn(storeName string, cdc *wire.Codec, kb keys.Keybase, } } -func queryDepositHandlerFn(storeName string, cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { +func queryDepositHandlerFn(cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -302,7 +302,7 @@ func queryDepositHandlerFn(storeName string, cdc *wire.Codec, kb keys.Keybase, c } } -func queryVoteHandlerFn(storeName string, cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { +func queryVoteHandlerFn(cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) strProposalID := vars[RestProposalID] @@ -369,7 +369,7 @@ func queryVoteHandlerFn(storeName string, cdc *wire.Codec, kb keys.Keybase, ctx } } -func queryProposalsWithParameterFn(storeName string, cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { +func queryProposalsWithParameterFn(cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { bechVoterAddr := r.URL.Query().Get(RestVoter) bechDepositerAddr := r.URL.Query().Get(RestDepositer) diff --git a/x/gov/handler.go b/x/gov/handler.go index 1d9545948a..dc218953ae 100644 --- a/x/gov/handler.go +++ b/x/gov/handler.go @@ -114,7 +114,7 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (tags sdk.Tags, nonVotingVals [] for shouldPopActiveProposalQueue(ctx, keeper) { activeProposal := keeper.ActiveProposalQueuePop(ctx) - if ctx.BlockHeight() >= activeProposal.GetVotingStartBlock()+keeper.GetVotingProcedure(ctx).VotingPeriod { + if ctx.BlockHeight() >= activeProposal.GetVotingStartBlock()+keeper.GetVotingProcedure().VotingPeriod { passes, nonVotingVals = tally(ctx, keeper, activeProposal) proposalIDBytes := keeper.cdc.MustMarshalBinaryBare(activeProposal.GetProposalID()) if passes { @@ -136,7 +136,7 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (tags sdk.Tags, nonVotingVals [] return tags, nonVotingVals } func shouldPopInactiveProposalQueue(ctx sdk.Context, keeper Keeper) bool { - depositProcedure := keeper.GetDepositProcedure(ctx) + depositProcedure := keeper.GetDepositProcedure() peekProposal := keeper.InactiveProposalQueuePeek(ctx) if peekProposal == nil { @@ -150,7 +150,7 @@ func shouldPopInactiveProposalQueue(ctx sdk.Context, keeper Keeper) bool { } func shouldPopActiveProposalQueue(ctx sdk.Context, keeper Keeper) bool { - votingProcedure := keeper.GetVotingProcedure(ctx) + votingProcedure := keeper.GetVotingProcedure() peekProposal := keeper.ActiveProposalQueuePeek(ctx) if peekProposal == nil { diff --git a/x/gov/keeper.go b/x/gov/keeper.go index 7d0eb04067..c22cd3dfe7 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -129,7 +129,7 @@ func (keeper Keeper) activateVotingPeriod(ctx sdk.Context, proposal Proposal) { // Procedures // Gets procedure from store. TODO: move to global param store and allow for updating of this -func (keeper Keeper) GetDepositProcedure(ctx sdk.Context) DepositProcedure { +func (keeper Keeper) GetDepositProcedure() DepositProcedure { return DepositProcedure{ MinDeposit: sdk.Coins{sdk.NewCoin("steak", 10)}, MaxDepositPeriod: 200, @@ -137,14 +137,14 @@ func (keeper Keeper) GetDepositProcedure(ctx sdk.Context) DepositProcedure { } // Gets procedure from store. TODO: move to global param store and allow for updating of this -func (keeper Keeper) GetVotingProcedure(ctx sdk.Context) VotingProcedure { +func (keeper Keeper) GetVotingProcedure() VotingProcedure { return VotingProcedure{ VotingPeriod: 200, } } // Gets procedure from store. TODO: move to global param store and allow for updating of this -func (keeper Keeper) GetTallyingProcedure(ctx sdk.Context) TallyingProcedure { +func (keeper Keeper) GetTallyingProcedure() TallyingProcedure { return TallyingProcedure{ Threshold: sdk.NewRat(1, 2), Veto: sdk.NewRat(1, 3), @@ -256,7 +256,7 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID int64, depositerAddr // Check if deposit tipped proposal into voting period // Active voting period if so activatedVotingPeriod := false - if proposal.GetStatus() == StatusDepositPeriod && proposal.GetTotalDeposit().IsGTE(keeper.GetDepositProcedure(ctx).MinDeposit) { + if proposal.GetStatus() == StatusDepositPeriod && proposal.GetTotalDeposit().IsGTE(keeper.GetDepositProcedure().MinDeposit) { keeper.activateVotingPeriod(ctx, proposal) activatedVotingPeriod = true } diff --git a/x/gov/tally.go b/x/gov/tally.go index 2e70ac24cc..c5e0ec763b 100644 --- a/x/gov/tally.go +++ b/x/gov/tally.go @@ -81,7 +81,7 @@ func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, nonV totalVotingPower = totalVotingPower.Add(votingPower) } - tallyingProcedure := keeper.GetTallyingProcedure(ctx) + tallyingProcedure := keeper.GetTallyingProcedure() // If no one votes, proposal fails if totalVotingPower.Sub(results[OptionAbstain]).Equal(sdk.ZeroRat()) { diff --git a/x/ibc/client/cli/relay.go b/x/ibc/client/cli/relay.go index 07ee4ae999..2dc3129c6e 100644 --- a/x/ibc/client/cli/relay.go +++ b/x/ibc/client/cli/relay.go @@ -71,6 +71,7 @@ func IBCRelayCmd(cdc *wire.Codec) *cobra.Command { return cmd } +// nolint: unparam func (c relayCommander) runIBCRelay(cmd *cobra.Command, args []string) { fromChainID := viper.GetString(FlagFromChainID) fromChainNode := viper.GetString(FlagFromChainNode) diff --git a/x/ibc/errors.go b/x/ibc/errors.go index f7beb0e1db..7a3194baf1 100644 --- a/x/ibc/errors.go +++ b/x/ibc/errors.go @@ -36,6 +36,7 @@ func ErrIdenticalChains(codespace sdk.CodespaceType) sdk.Error { // ------------------------- // Helpers +// nolint: unparam func newError(codespace sdk.CodespaceType, code sdk.CodeType, msg string) sdk.Error { msg = msgOrDefaultMsg(msg, code) return sdk.NewError(codespace, code, msg) diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index 52dd947493..2120e75b68 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -108,6 +108,6 @@ func TestSlashingMsgs(t *testing.T) { checkValidatorSigningInfo(t, mapp, keeper, addr1, false) // unrevoke should fail with unknown validator - res := mock.SignCheck(t, mapp.BaseApp, []sdk.Msg{unrevokeMsg}, []int64{0}, []int64{1}, priv1) + res := mock.SignCheck(mapp.BaseApp, []sdk.Msg{unrevokeMsg}, []int64{0}, []int64{1}, priv1) require.Equal(t, sdk.ToABCICode(DefaultCodespace, CodeInvalidValidator), res.Code) } diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index fd213382b4..afa9e3bf0c 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -12,31 +12,33 @@ import ( "github.com/cosmos/cosmos-sdk/x/stake" ) +const storeName = "stake" + func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec) { r.HandleFunc( "/stake/{delegator}/delegation/{validator}", - delegationHandlerFn(ctx, "stake", cdc), + delegationHandlerFn(ctx, cdc), ).Methods("GET") r.HandleFunc( "/stake/{delegator}/ubd/{validator}", - ubdHandlerFn(ctx, "stake", cdc), + ubdHandlerFn(ctx, cdc), ).Methods("GET") r.HandleFunc( "/stake/{delegator}/red/{validator_src}/{validator_dst}", - redHandlerFn(ctx, "stake", cdc), + redHandlerFn(ctx, cdc), ).Methods("GET") r.HandleFunc( "/stake/validators", - validatorsHandlerFn(ctx, "stake", cdc), + validatorsHandlerFn(ctx, cdc), ).Methods("GET") } // http request handler to query a delegation -func delegationHandlerFn(ctx context.CoreContext, storeName string, cdc *wire.Codec) http.HandlerFunc { +func delegationHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // read parameters @@ -93,7 +95,7 @@ func delegationHandlerFn(ctx context.CoreContext, storeName string, cdc *wire.Co } // http request handler to query an unbonding-delegation -func ubdHandlerFn(ctx context.CoreContext, storeName string, cdc *wire.Codec) http.HandlerFunc { +func ubdHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // read parameters @@ -150,7 +152,7 @@ func ubdHandlerFn(ctx context.CoreContext, storeName string, cdc *wire.Codec) ht } // http request handler to query an redelegation -func redHandlerFn(ctx context.CoreContext, storeName string, cdc *wire.Codec) http.HandlerFunc { +func redHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // read parameters @@ -271,7 +273,7 @@ func bech32StakeValidatorOutput(validator stake.Validator) (StakeValidatorOutput // TODO bech32 // http request handler to query list of validators -func validatorsHandlerFn(ctx context.CoreContext, storeName string, cdc *wire.Codec) http.HandlerFunc { +func validatorsHandlerFn(ctx context.CoreContext, cdc *wire.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { kvs, err := ctx.QuerySubspace(cdc, stake.ValidatorsKey, storeName) if err != nil { diff --git a/x/stake/keeper/test_common.go b/x/stake/keeper/test_common.go index 5a51a0e29f..17b21c6346 100644 --- a/x/stake/keeper/test_common.go +++ b/x/stake/keeper/test_common.go @@ -162,6 +162,7 @@ func TestAddr(addr string, bech string) sdk.Address { return res } +// nolint: unparam func createTestAddrs(numAddrs int) []sdk.Address { var addresses []sdk.Address var buffer bytes.Buffer @@ -180,6 +181,7 @@ func createTestAddrs(numAddrs int) []sdk.Address { return addresses } +// nolint: unparam func createTestPubKeys(numPubKeys int) []crypto.PubKey { var publicKeys []crypto.PubKey var buffer bytes.Buffer diff --git a/x/stake/keeper/validator.go b/x/stake/keeper/validator.go index 75797c868c..0d556f7dc4 100644 --- a/x/stake/keeper/validator.go +++ b/x/stake/keeper/validator.go @@ -247,7 +247,7 @@ func (k Keeper) UpdateValidator(ctx sdk.Context, validator types.Validator) type // efficiency case: // if already bonded and power increasing only need to update tendermint if powerIncreasing && !validator.Revoked && oldValidator.Status() == sdk.Bonded { - bz := k.cdc.MustMarshalBinary(validator.ABCIValidator(k.cdc)) + bz := k.cdc.MustMarshalBinary(validator.ABCIValidator()) store.Set(GetTendermintUpdatesKey(ownerAddr), bz) return validator } @@ -445,7 +445,7 @@ func (k Keeper) unbondValidator(ctx sdk.Context, validator types.Validator) type store.Set(GetValidatorKey(validator.Owner), bzVal) // add to accumulated changes for tendermint - bzABCI := k.cdc.MustMarshalBinary(validator.ABCIValidatorZero(k.cdc)) + bzABCI := k.cdc.MustMarshalBinary(validator.ABCIValidatorZero()) store.Set(GetTendermintUpdatesKey(validator.Owner), bzABCI) // also remove from the Bonded types.Validators Store @@ -474,7 +474,7 @@ func (k Keeper) bondValidator(ctx sdk.Context, validator types.Validator) types. store.Set(GetValidatorsBondedIndexKey(validator.Owner), validator.Owner) // add to accumulated changes for tendermint - bzABCI := k.cdc.MustMarshalBinary(validator.ABCIValidator(k.cdc)) + bzABCI := k.cdc.MustMarshalBinary(validator.ABCIValidator()) store.Set(GetTendermintUpdatesKey(validator.Owner), bzABCI) return validator @@ -503,7 +503,7 @@ func (k Keeper) RemoveValidator(ctx sdk.Context, address sdk.Address) { } store.Delete(GetValidatorsBondedIndexKey(validator.Owner)) - bz := k.cdc.MustMarshalBinary(validator.ABCIValidatorZero(k.cdc)) + bz := k.cdc.MustMarshalBinary(validator.ABCIValidatorZero()) store.Set(GetTendermintUpdatesKey(address), bz) } diff --git a/x/stake/keeper/validator_test.go b/x/stake/keeper/validator_test.go index 3bbcee94c0..098c17e75f 100644 --- a/x/stake/keeper/validator_test.go +++ b/x/stake/keeper/validator_test.go @@ -46,7 +46,7 @@ func TestSetValidator(t *testing.T) { updates := keeper.GetTendermintUpdates(ctx) require.Equal(t, 1, len(updates)) - assert.Equal(t, validator.ABCIValidator(keeper.cdc), updates[0]) + assert.Equal(t, validator.ABCIValidator(), updates[0]) } @@ -494,8 +494,8 @@ func TestGetTendermintUpdatesAllNone(t *testing.T) { updates := keeper.GetTendermintUpdates(ctx) require.Equal(t, 2, len(updates)) - assert.Equal(t, validators[0].ABCIValidator(keeper.cdc), updates[0]) - assert.Equal(t, validators[1].ABCIValidator(keeper.cdc), updates[1]) + assert.Equal(t, validators[0].ABCIValidator(), updates[0]) + assert.Equal(t, validators[1].ABCIValidator(), updates[1]) // test from something to nothing // tendermintUpdate set: {} -> {c1, c2, c3, c4} @@ -560,7 +560,7 @@ func TestGetTendermintUpdatesSingleValueChange(t *testing.T) { updates := keeper.GetTendermintUpdates(ctx) require.Equal(t, 1, len(updates)) - assert.Equal(t, validators[0].ABCIValidator(keeper.cdc), updates[0]) + assert.Equal(t, validators[0].ABCIValidator(), updates[0]) } func TestGetTendermintUpdatesMultipleValueChange(t *testing.T) { @@ -590,8 +590,8 @@ func TestGetTendermintUpdatesMultipleValueChange(t *testing.T) { updates := keeper.GetTendermintUpdates(ctx) require.Equal(t, 2, len(updates)) - require.Equal(t, validators[0].ABCIValidator(keeper.cdc), updates[0]) - require.Equal(t, validators[1].ABCIValidator(keeper.cdc), updates[1]) + require.Equal(t, validators[0].ABCIValidator(), updates[0]) + require.Equal(t, validators[1].ABCIValidator(), updates[1]) } func TestGetTendermintUpdatesInserted(t *testing.T) { @@ -615,7 +615,7 @@ func TestGetTendermintUpdatesInserted(t *testing.T) { validators[2] = keeper.UpdateValidator(ctx, validators[2]) updates := keeper.GetTendermintUpdates(ctx) require.Equal(t, 1, len(updates)) - require.Equal(t, validators[2].ABCIValidator(keeper.cdc), updates[0]) + require.Equal(t, validators[2].ABCIValidator(), updates[0]) // test validtor added at the beginning // tendermintUpdate set: {} -> {c0} @@ -623,7 +623,7 @@ func TestGetTendermintUpdatesInserted(t *testing.T) { validators[3] = keeper.UpdateValidator(ctx, validators[3]) updates = keeper.GetTendermintUpdates(ctx) require.Equal(t, 1, len(updates)) - require.Equal(t, validators[3].ABCIValidator(keeper.cdc), updates[0]) + require.Equal(t, validators[3].ABCIValidator(), updates[0]) // test validtor added at the end // tendermintUpdate set: {} -> {c0} @@ -631,7 +631,7 @@ func TestGetTendermintUpdatesInserted(t *testing.T) { validators[4] = keeper.UpdateValidator(ctx, validators[4]) updates = keeper.GetTendermintUpdates(ctx) require.Equal(t, 1, len(updates)) - require.Equal(t, validators[4].ABCIValidator(keeper.cdc), updates[0]) + require.Equal(t, validators[4].ABCIValidator(), updates[0]) } func TestGetTendermintUpdatesNotValidatorCliff(t *testing.T) { @@ -671,6 +671,6 @@ func TestGetTendermintUpdatesNotValidatorCliff(t *testing.T) { updates = keeper.GetTendermintUpdates(ctx) require.Equal(t, 2, len(updates), "%v", updates) - require.Equal(t, validators[0].ABCIValidatorZero(keeper.cdc), updates[0]) - require.Equal(t, validators[2].ABCIValidator(keeper.cdc), updates[1]) + require.Equal(t, validators[0].ABCIValidatorZero(), updates[0]) + require.Equal(t, validators[2].ABCIValidator(), updates[1]) } diff --git a/x/stake/types/test_common.go b/x/stake/types/test_common.go index 1ecb10d6b9..5edb5568d8 100644 --- a/x/stake/types/test_common.go +++ b/x/stake/types/test_common.go @@ -31,6 +31,7 @@ var ( type Operation func(r *rand.Rand, pool Pool, c Validator) (Pool, Validator, int64, string) // operation: bond or unbond a validator depending on current status +// nolint: unparam func OpBondOrUnbond(r *rand.Rand, pool Pool, val Validator) (Pool, Validator, int64, string) { var msg string var newStatus sdk.BondStatus @@ -89,6 +90,7 @@ func RandomOperation(r *rand.Rand) Operation { } // ensure invariants that should always be true are true +// nolint: unparam func AssertInvariants(t *testing.T, msg string, pOrig Pool, cOrig []Validator, pMod Pool, vMods []Validator, tokens int64) { @@ -161,6 +163,7 @@ func AssertInvariants(t *testing.T, msg string, // TODO refactor this random setup // generate a random validator +// nolint: unparam func randomValidator(r *rand.Rand, i int) Validator { poolSharesAmt := sdk.NewRat(int64(r.Int31n(10000))) diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index fcc7bf3925..652fd9e6e8 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -9,7 +9,6 @@ import ( tmtypes "github.com/tendermint/tendermint/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/wire" ) // Validator defines the total amount of bond shares and their exchange rate to @@ -135,7 +134,7 @@ func (d Description) EnsureLength() (Description, sdk.Error) { } // abci validator from stake validator type -func (v Validator) ABCIValidator(cdc *wire.Codec) abci.Validator { +func (v Validator) ABCIValidator() abci.Validator { return abci.Validator{ PubKey: tmtypes.TM2PB.PubKey(v.PubKey), Power: v.PoolShares.Bonded().Evaluate(), @@ -144,7 +143,7 @@ func (v Validator) ABCIValidator(cdc *wire.Codec) abci.Validator { // abci validator from stake validator type // with zero power used for validator updates -func (v Validator) ABCIValidatorZero(cdc *wire.Codec) abci.Validator { +func (v Validator) ABCIValidatorZero() abci.Validator { return abci.Validator{ PubKey: tmtypes.TM2PB.PubKey(v.PubKey), Power: 0, From fc3dd56281a392dd921467990a500aff9cb1ce96 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Fri, 29 Jun 2018 15:47:09 -0700 Subject: [PATCH 4/9] Merge PR #1477: gaiacli: Make recovery allow new keys * gaiacli: Make recovery allow new keys * Move create key to a temporary method, restore create fundraiser key --- client/keys/add.go | 2 +- crypto/keys/keybase.go | 17 ++++++++++++++++- crypto/keys/types.go | 2 ++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/client/keys/add.go b/client/keys/add.go index f0055366ac..a39a374c82 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -104,7 +104,7 @@ func runAddCmd(cmd *cobra.Command, args []string) error { if err != nil { return err } - info, err := kb.CreateFundraiserKey(name, seed, pass) + info, err := kb.CreateKey(name, seed, pass) if err != nil { return err } diff --git a/crypto/keys/keybase.go b/crypto/keys/keybase.go index ad086b13c6..396bb57821 100644 --- a/crypto/keys/keybase.go +++ b/crypto/keys/keybase.go @@ -89,13 +89,28 @@ func (kb dbKeybase) CreateMnemonic(name string, language Language, passwd string return } +// TEMPORARY METHOD UNTIL WE FIGURE OUT USER FACING HD DERIVATION API +func (kb dbKeybase) CreateKey(name, mnemonic, passwd string) (info Info, err error) { + words := strings.Split(mnemonic, " ") + if len(words) != 12 && len(words) != 24 { + err = fmt.Errorf("recovering only works with 12 word (fundraiser) or 24 word mnemonics, got: %v words", len(words)) + return + } + seed, err := bip39.MnemonicToSeedWithErrChecking(mnemonic) + if err != nil { + return + } + info, err = kb.persistDerivedKey(seed, passwd, name, hd.FullFundraiserPath) + return +} + // CreateFundraiserKey converts a mnemonic to a private key and persists it, // encrypted with the given password. // TODO(ismail) func (kb dbKeybase) CreateFundraiserKey(name, mnemonic, passwd string) (info Info, err error) { words := strings.Split(mnemonic, " ") if len(words) != 12 { - err = fmt.Errorf("recovering only works with 12 word (fundraiser) mnemonics, got: %v words", len(words)) + err = fmt.Errorf("recovering only works with 12 word (fundraiser), got: %v words", len(words)) return } seed, err := bip39.MnemonicToSeedWithErrChecking(mnemonic) diff --git a/crypto/keys/types.go b/crypto/keys/types.go index e143ed63d0..0e77725c31 100644 --- a/crypto/keys/types.go +++ b/crypto/keys/types.go @@ -21,6 +21,8 @@ type Keybase interface { // CreateMnemonic creates a new mnemonic, and derives a hierarchical deterministic // key from that. CreateMnemonic(name string, language Language, passwd string, algo SigningAlgo) (info Info, seed string, err error) + // CreateKey takes a mnemonic and derives, a password. This method is temporary + CreateKey(name, mnemonic, passwd string) (info Info, err error) // CreateFundraiserKey takes a mnemonic and derives, a password CreateFundraiserKey(name, mnemonic, passwd string) (info Info, err error) // Derive derives a key from the passed mnemonic using a BIP44 path. From 955a0c9af70d5f8a8a799f17f73f754625cf858a Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Fri, 29 Jun 2018 18:10:15 -0700 Subject: [PATCH 5/9] Switch asserts to require (#1483) * meta: Switch the majority of asserts to require Switch most assert statements to require, to ease debugging. Closes #1418 * Fix imports --- baseapp/baseapp_test.go | 132 ++++++------- client/lcd/lcd_test.go | 136 ++++++------- cmd/gaia/app/genesis_test.go | 4 +- cmd/gaia/cli_test/cli_test.go | 43 +++-- crypto/encode_test.go | 31 ++- crypto/keys/bip39/wordcodec_test.go | 6 +- crypto/keys/hd/fundraiser_test.go | 14 +- crypto/keys/keybase_test.go | 98 +++++----- crypto/ledger_test.go | 7 +- examples/basecoin/app/app_test.go | 5 +- examples/democoin/app/app_test.go | 5 +- .../democoin/x/assoc/validator_set_test.go | 34 ++-- examples/democoin/x/cool/app_test.go | 3 +- examples/democoin/x/cool/keeper_test.go | 12 +- examples/democoin/x/oracle/oracle_test.go | 59 +++--- examples/democoin/x/pow/app_test.go | 3 +- examples/democoin/x/pow/handler_test.go | 16 +- examples/democoin/x/pow/keeper_test.go | 16 +- examples/democoin/x/pow/types_test.go | 20 +- .../democoin/x/simplestake/keeper_test.go | 19 +- examples/democoin/x/simplestake/msgs_test.go | 6 +- server/mock/app_test.go | 5 +- server/mock/store_test.go | 14 +- server/util_test.go | 3 +- store/cachekvstore_test.go | 51 +++-- store/iavlstore_test.go | 124 ++++++------ store/prefixstore_test.go | 7 +- store/rootmultistore_test.go | 62 +++--- types/coin_test.go | 47 ++--- types/context_test.go | 15 +- types/errors_test.go | 10 +- types/int_test.go | 104 +++++----- types/lib/linear_test.go | 42 ++--- types/rational_test.go | 73 ++++--- types/store_test.go | 6 +- x/auth/account_test.go | 44 ++--- x/auth/ante_test.go | 23 ++- x/auth/context_test.go | 12 +- x/auth/feekeeper_test.go | 16 +- x/auth/mapper_test.go | 18 +- x/auth/mock/auth_app_test.go | 7 +- x/auth/mock/simulate_block.go | 3 +- x/auth/stdtx_test.go | 8 +- x/bank/app_test.go | 5 +- x/bank/keeper_test.go | 93 ++++----- x/bank/msgs_test.go | 28 +-- x/fee_distribution/keeper_test.go | 6 +- x/gov/endblocker_test.go | 114 +++++------ x/gov/keeper_test.go | 178 +++++++++--------- x/gov/msgs_test.go | 14 +- x/gov/tally_test.go | 100 +++++----- x/ibc/app_test.go | 3 +- x/ibc/ibc_test.go | 30 +-- x/ibc/types_test.go | 18 +- x/slashing/app_test.go | 5 +- x/slashing/msg_test.go | 4 +- x/stake/app_test.go | 6 +- x/stake/handler_test.go | 55 +++--- x/stake/keeper/delegation_test.go | 79 ++++---- x/stake/keeper/inflation_test.go | 39 ++-- x/stake/keeper/keeper_test.go | 10 +- x/stake/keeper/validator_test.go | 72 +++---- x/stake/types/msg_test.go | 17 +- x/stake/types/pool_test.go | 41 ++-- x/stake/types/validator_test.go | 72 +++---- 65 files changed, 1156 insertions(+), 1196 deletions(-) diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 9d567c6bff..0d0b226265 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -37,26 +37,26 @@ func newBaseApp(name string) *BaseApp { func TestMountStores(t *testing.T) { name := t.Name() app := newBaseApp(name) - assert.Equal(t, name, app.Name()) + require.Equal(t, name, app.Name()) // make some cap keys capKey1 := sdk.NewKVStoreKey("key1") capKey2 := sdk.NewKVStoreKey("key2") // no stores are mounted - assert.Panics(t, func() { app.LoadLatestVersion(capKey1) }) + require.Panics(t, func() { app.LoadLatestVersion(capKey1) }) app.MountStoresIAVL(capKey1, capKey2) // stores are mounted err := app.LoadLatestVersion(capKey1) - assert.Nil(t, err) + require.Nil(t, err) // check both stores store1 := app.cms.GetCommitKVStore(capKey1) - assert.NotNil(t, store1) + require.NotNil(t, store1) store2 := app.cms.GetCommitKVStore(capKey2) - assert.NotNil(t, store2) + require.NotNil(t, store2) } // Test that we can make commits and then reload old versions. @@ -71,14 +71,14 @@ func TestLoadVersion(t *testing.T) { capKey := sdk.NewKVStoreKey("main") app.MountStoresIAVL(capKey) err := app.LoadLatestVersion(capKey) // needed to make stores non-nil - assert.Nil(t, err) + require.Nil(t, err) emptyCommitID := sdk.CommitID{} lastHeight := app.LastBlockHeight() lastID := app.LastCommitID() - assert.Equal(t, int64(0), lastHeight) - assert.Equal(t, emptyCommitID, lastID) + require.Equal(t, int64(0), lastHeight) + require.Equal(t, emptyCommitID, lastID) // execute some blocks header := abci.Header{Height: 1} @@ -94,7 +94,7 @@ func TestLoadVersion(t *testing.T) { app = NewBaseApp(name, nil, logger, db) app.MountStoresIAVL(capKey) err = app.LoadLatestVersion(capKey) - assert.Nil(t, err) + require.Nil(t, err) testLoadVersionHelper(t, app, int64(2), commitID2) // reload with LoadVersion, see if you can commit the same block and get @@ -102,7 +102,7 @@ func TestLoadVersion(t *testing.T) { app = NewBaseApp(name, nil, logger, db) app.MountStoresIAVL(capKey) err = app.LoadVersion(1, capKey) - assert.Nil(t, err) + require.Nil(t, err) testLoadVersionHelper(t, app, int64(1), commitID1) app.BeginBlock(abci.RequestBeginBlock{Header: header}) app.Commit() @@ -112,8 +112,8 @@ func TestLoadVersion(t *testing.T) { func testLoadVersionHelper(t *testing.T, app *BaseApp, expectedHeight int64, expectedID sdk.CommitID) { lastHeight := app.LastBlockHeight() lastID := app.LastCommitID() - assert.Equal(t, expectedHeight, lastHeight) - assert.Equal(t, expectedID, lastID) + require.Equal(t, expectedHeight, lastHeight) + require.Equal(t, expectedID, lastID) } // Test that the app hash is static @@ -125,7 +125,7 @@ func testLoadVersionHelper(t *testing.T, app *BaseApp, expectedHeight int64, exp capKey := sdk.NewKVStoreKey("main") app.MountStoresIAVL(capKey) err := app.LoadLatestVersion(capKey) // needed to make stores non-nil - assert.Nil(t, err) + require.Nil(t, err) // execute some blocks header := abci.Header{Height: 1} @@ -138,7 +138,7 @@ func testLoadVersionHelper(t *testing.T, app *BaseApp, expectedHeight int64, exp res = app.Commit() commitID2 := sdk.CommitID{2, res.Data} - assert.Equal(t, commitID1.Hash, commitID2.Hash) + require.Equal(t, commitID1.Hash, commitID2.Hash) } */ @@ -160,7 +160,7 @@ func TestInfo(t *testing.T) { assert.Equal(t, "", res.Version) assert.Equal(t, t.Name(), res.GetData()) assert.Equal(t, int64(0), res.LastBlockHeight) - assert.Equal(t, []uint8(nil), res.LastBlockAppHash) + require.Equal(t, []uint8(nil), res.LastBlockAppHash) // ----- test a proper response ------- // TODO @@ -179,7 +179,7 @@ func TestInitChainer(t *testing.T) { capKey2 := sdk.NewKVStoreKey("key2") app.MountStoresIAVL(capKey, capKey2) err := app.LoadLatestVersion(capKey) // needed to make stores non-nil - assert.Nil(t, err) + require.Nil(t, err) key, value := []byte("hello"), []byte("goodbye") @@ -198,7 +198,7 @@ func TestInitChainer(t *testing.T) { // initChainer is nil - nothing happens app.InitChain(abci.RequestInitChain{}) res := app.Query(query) - assert.Equal(t, 0, len(res.Value)) + require.Equal(t, 0, len(res.Value)) // set initChainer and try again - should see the value app.SetInitChainer(initChainer) @@ -206,31 +206,31 @@ func TestInitChainer(t *testing.T) { // assert that chainID is set correctly in InitChain chainID := app.deliverState.ctx.ChainID() - assert.Equal(t, "test-chain-id", chainID, "ChainID in deliverState not set correctly in InitChain") + require.Equal(t, "test-chain-id", chainID, "ChainID in deliverState not set correctly in InitChain") chainID = app.checkState.ctx.ChainID() - assert.Equal(t, "test-chain-id", chainID, "ChainID in checkState not set correctly in InitChain") + require.Equal(t, "test-chain-id", chainID, "ChainID in checkState not set correctly in InitChain") app.Commit() res = app.Query(query) - assert.Equal(t, value, res.Value) + require.Equal(t, value, res.Value) // reload app app = NewBaseApp(name, nil, logger, db) app.MountStoresIAVL(capKey, capKey2) err = app.LoadLatestVersion(capKey) // needed to make stores non-nil - assert.Nil(t, err) + require.Nil(t, err) app.SetInitChainer(initChainer) // ensure we can still query after reloading res = app.Query(query) - assert.Equal(t, value, res.Value) + require.Equal(t, value, res.Value) // commit and ensure we can still query app.BeginBlock(abci.RequestBeginBlock{}) app.Commit() res = app.Query(query) - assert.Equal(t, value, res.Value) + require.Equal(t, value, res.Value) } func getStateCheckingHandler(t *testing.T, capKey *sdk.KVStoreKey, txPerHeight int, checkHeader bool) func(ctx sdk.Context, msg sdk.Msg) sdk.Result { @@ -243,7 +243,7 @@ func getStateCheckingHandler(t *testing.T, capKey *sdk.KVStoreKey, txPerHeight i // check previous value in store counterBytes := []byte{byte(counter - 1)} prevBytes := store.Get(counterBytes) - assert.Equal(t, counterBytes, prevBytes) + require.Equal(t, counterBytes, prevBytes) } // set the current counter in the store @@ -255,7 +255,7 @@ func getStateCheckingHandler(t *testing.T, capKey *sdk.KVStoreKey, txPerHeight i if checkHeader { thisHeader := ctx.BlockHeader() height := int64((counter / txPerHeight) + 1) - assert.Equal(t, height, thisHeader.Height) + require.Equal(t, height, thisHeader.Height) } counter++ @@ -293,7 +293,7 @@ func TestCheckTx(t *testing.T) { capKey := sdk.NewKVStoreKey("main") app.MountStoresIAVL(capKey) err := app.LoadLatestVersion(capKey) // needed to make stores non-nil - assert.Nil(t, err) + require.Nil(t, err) app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { return }) txPerHeight := 3 @@ -317,7 +317,7 @@ func TestCheckTx(t *testing.T) { checkStateStore := app.checkState.ctx.KVStore(capKey) for i := 0; i < txPerHeight; i++ { storedValue := checkStateStore.Get([]byte{byte(i)}) - assert.Nil(t, storedValue) + require.Nil(t, storedValue) } } @@ -330,7 +330,7 @@ func TestDeliverTx(t *testing.T) { capKey := sdk.NewKVStoreKey("main") app.MountStoresIAVL(capKey) err := app.LoadLatestVersion(capKey) // needed to make stores non-nil - assert.Nil(t, err) + require.Nil(t, err) txPerHeight := 2 app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { return }) @@ -359,7 +359,7 @@ func TestSimulateTx(t *testing.T) { capKey := sdk.NewKVStoreKey("main") app.MountStoresIAVL(capKey) err := app.LoadLatestVersion(capKey) // needed to make stores non-nil - assert.Nil(t, err) + require.Nil(t, err) counter := 0 app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { return }) @@ -372,7 +372,7 @@ func TestSimulateTx(t *testing.T) { // check we can see the current header thisHeader := ctx.BlockHeader() height := int64(counter) - assert.Equal(t, height, thisHeader.Height) + require.Equal(t, height, thisHeader.Height) counter++ return sdk.Result{} }) @@ -421,18 +421,18 @@ func TestRunInvalidTransaction(t *testing.T) { capKey := sdk.NewKVStoreKey("main") app.MountStoresIAVL(capKey) err := app.LoadLatestVersion(capKey) // needed to make stores non-nil - assert.Nil(t, err) + require.Nil(t, err) app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { return }) app.Router().AddRoute(msgType2, func(ctx sdk.Context, msg sdk.Msg) (res sdk.Result) { return }) app.BeginBlock(abci.RequestBeginBlock{}) // Transaction where validate fails invalidTx := testTx{-1} err1 := app.Deliver(invalidTx) - assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeTxDecode), err1.Code) + require.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeTxDecode), err1.Code) // Transaction with no known route unknownRouteTx := testUpdatePowerTx{} err2 := app.Deliver(unknownRouteTx) - assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeUnknownRequest), err2.Code) + require.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeUnknownRequest), err2.Code) } // Test that transactions exceeding gas limits fail @@ -445,7 +445,7 @@ func TestTxGasLimits(t *testing.T) { capKey := sdk.NewKVStoreKey("main") app.MountStoresIAVL(capKey) err := app.LoadLatestVersion(capKey) // needed to make stores non-nil - assert.Nil(t, err) + require.Nil(t, err) app.SetAnteHandler(func(ctx sdk.Context, tx sdk.Tx) (newCtx sdk.Context, res sdk.Result, abort bool) { newCtx = ctx.WithGasMeter(sdk.NewGasMeter(0)) @@ -461,7 +461,7 @@ func TestTxGasLimits(t *testing.T) { app.BeginBlock(abci.RequestBeginBlock{Header: header}) res := app.Deliver(tx) - assert.Equal(t, res.Code, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeOutOfGas), "Expected transaction to run out of gas") + require.Equal(t, res.Code, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeOutOfGas), "Expected transaction to run out of gas") app.EndBlock(abci.RequestEndBlock{}) app.Commit() } @@ -474,7 +474,7 @@ func TestQuery(t *testing.T) { capKey := sdk.NewKVStoreKey("main") app.MountStoresIAVL(capKey) err := app.LoadLatestVersion(capKey) // needed to make stores non-nil - assert.Nil(t, err) + require.Nil(t, err) key, value := []byte("hello"), []byte("goodbye") @@ -492,25 +492,25 @@ func TestQuery(t *testing.T) { // query is empty before we do anything res := app.Query(query) - assert.Equal(t, 0, len(res.Value)) + require.Equal(t, 0, len(res.Value)) tx := testUpdatePowerTx{} // doesn't matter // query is still empty after a CheckTx app.Check(tx) res = app.Query(query) - assert.Equal(t, 0, len(res.Value)) + require.Equal(t, 0, len(res.Value)) // query is still empty after a DeliverTx before we commit app.BeginBlock(abci.RequestBeginBlock{}) app.Deliver(tx) res = app.Query(query) - assert.Equal(t, 0, len(res.Value)) + require.Equal(t, 0, len(res.Value)) // query returns correct value after Commit app.Commit() res = app.Query(query) - assert.Equal(t, value, res.Value) + require.Equal(t, value, res.Value) } // Test p2p filter queries @@ -521,7 +521,7 @@ func TestP2PQuery(t *testing.T) { capKey := sdk.NewKVStoreKey("main") app.MountStoresIAVL(capKey) err := app.LoadLatestVersion(capKey) // needed to make stores non-nil - assert.Nil(t, err) + require.Nil(t, err) app.SetAddrPeerFilter(func(addrport string) abci.ResponseQuery { require.Equal(t, "1.1.1.1:8000", addrport) @@ -585,8 +585,8 @@ func TestValidatorChange(t *testing.T) { // Load latest state, which should be empty. err := app.LoadLatestVersion(capKey) - assert.Nil(t, err) - assert.Equal(t, app.LastBlockHeight(), int64(0)) + require.Nil(t, err) + require.Equal(t, app.LastBlockHeight(), int64(0)) // Create the validators var numVals = 3 @@ -611,7 +611,7 @@ func TestValidatorChange(t *testing.T) { } txBytes := toJSON(tx) res := app.DeliverTx(txBytes) - assert.True(t, res.IsOK(), "%#v\nABCI log: %s", res, res.Log) + require.True(t, res.IsOK(), "%#v\nABCI log: %s", res, res.Log) } // Simulate the end of a block. @@ -624,18 +624,18 @@ func TestValidatorChange(t *testing.T) { pubkey, err := tmtypes.PB2TM.PubKey(val.PubKey) // Sanity - assert.Nil(t, err) + require.Nil(t, err) // Find matching update and splice it out. for j := 0; j < len(valUpdates); j++ { valUpdate := valUpdates[j] updatePubkey, err := tmtypes.PB2TM.PubKey(valUpdate.PubKey) - assert.Nil(t, err) + require.Nil(t, err) // Matched. if updatePubkey.Equals(pubkey) { - assert.Equal(t, valUpdate.Power, val.Power+1) + require.Equal(t, valUpdate.Power, val.Power+1) if j < len(valUpdates)-1 { // Splice it out. valUpdates = append(valUpdates[:j], valUpdates[j+1:]...) @@ -646,7 +646,7 @@ func TestValidatorChange(t *testing.T) { // Not matched. } } - assert.Equal(t, len(valUpdates), 0, "Some validator updates were unexpected") + require.Equal(t, len(valUpdates), 0, "Some validator updates were unexpected") } //---------------------------------------- @@ -808,15 +808,15 @@ func TestMultipleBurn(t *testing.T) { addr := priv.PubKey().Address() app.accountKeeper.AddCoins(app.deliverState.ctx, addr, sdk.Coins{{"foocoin", sdk.NewInt(100)}}) - assert.Equal(t, sdk.Coins{{"foocoin", sdk.NewInt(100)}}, app.accountKeeper.GetCoins(app.deliverState.ctx, addr), "Balance did not update") + require.Equal(t, sdk.Coins{{"foocoin", sdk.NewInt(100)}}, app.accountKeeper.GetCoins(app.deliverState.ctx, addr), "Balance did not update") msg := testBurnMsg{addr, sdk.Coins{{"foocoin", sdk.NewInt(50)}}} tx := GenTx(t.Name(), []sdk.Msg{msg, msg}, []int64{0}, []int64{0}, priv) res := app.Deliver(tx) - assert.Equal(t, true, res.IsOK(), res.Log) - assert.Equal(t, sdk.Coins(nil), app.accountKeeper.GetCoins(app.deliverState.ctx, addr), "Double burn did not work") + require.Equal(t, true, res.IsOK(), res.Log) + require.Equal(t, sdk.Coins(nil), app.accountKeeper.GetCoins(app.deliverState.ctx, addr), "Double burn did not work") } // tests multiples msgs of same type from different addresses in single tx @@ -861,8 +861,8 @@ func TestBurnMultipleOwners(t *testing.T) { app.accountKeeper.AddCoins(app.deliverState.ctx, addr1, sdk.Coins{{"foocoin", sdk.NewInt(100)}}) app.accountKeeper.AddCoins(app.deliverState.ctx, addr2, sdk.Coins{{"foocoin", sdk.NewInt(100)}}) - assert.Equal(t, sdk.Coins{{"foocoin", sdk.NewInt(100)}}, app.accountKeeper.GetCoins(app.deliverState.ctx, addr1), "Balance1 did not update") - assert.Equal(t, sdk.Coins{{"foocoin", sdk.NewInt(100)}}, app.accountKeeper.GetCoins(app.deliverState.ctx, addr2), "Balance2 did not update") + require.Equal(t, sdk.Coins{{"foocoin", sdk.NewInt(100)}}, app.accountKeeper.GetCoins(app.deliverState.ctx, addr1), "Balance1 did not update") + require.Equal(t, sdk.Coins{{"foocoin", sdk.NewInt(100)}}, app.accountKeeper.GetCoins(app.deliverState.ctx, addr2), "Balance2 did not update") msg1 := testBurnMsg{addr1, sdk.Coins{{"foocoin", sdk.NewInt(100)}}} msg2 := testBurnMsg{addr2, sdk.Coins{{"foocoin", sdk.NewInt(100)}}} @@ -871,19 +871,19 @@ func TestBurnMultipleOwners(t *testing.T) { tx := GenTx(t.Name(), []sdk.Msg{msg1, msg2}, []int64{0, 0}, []int64{0, 0}, priv1, priv1) res := app.Deliver(tx) - assert.Equal(t, sdk.ABCICodeType(0x10003), res.Code, "Wrong signatures passed") + require.Equal(t, sdk.ABCICodeType(0x10003), res.Code, "Wrong signatures passed") - assert.Equal(t, sdk.Coins{{"foocoin", sdk.NewInt(100)}}, app.accountKeeper.GetCoins(app.deliverState.ctx, addr1), "Balance1 changed after invalid sig") - assert.Equal(t, sdk.Coins{{"foocoin", sdk.NewInt(100)}}, app.accountKeeper.GetCoins(app.deliverState.ctx, addr2), "Balance2 changed after invalid sig") + require.Equal(t, sdk.Coins{{"foocoin", sdk.NewInt(100)}}, app.accountKeeper.GetCoins(app.deliverState.ctx, addr1), "Balance1 changed after invalid sig") + require.Equal(t, sdk.Coins{{"foocoin", sdk.NewInt(100)}}, app.accountKeeper.GetCoins(app.deliverState.ctx, addr2), "Balance2 changed after invalid sig") // test valid tx tx = GenTx(t.Name(), []sdk.Msg{msg1, msg2}, []int64{0, 1}, []int64{1, 0}, priv1, priv2) res = app.Deliver(tx) - assert.Equal(t, true, res.IsOK(), res.Log) + require.Equal(t, true, res.IsOK(), res.Log) - assert.Equal(t, sdk.Coins(nil), app.accountKeeper.GetCoins(app.deliverState.ctx, addr1), "Balance1 did not change after valid tx") - assert.Equal(t, sdk.Coins(nil), app.accountKeeper.GetCoins(app.deliverState.ctx, addr2), "Balance2 did not change after valid tx") + require.Equal(t, sdk.Coins(nil), app.accountKeeper.GetCoins(app.deliverState.ctx, addr1), "Balance1 did not change after valid tx") + require.Equal(t, sdk.Coins(nil), app.accountKeeper.GetCoins(app.deliverState.ctx, addr2), "Balance2 did not change after valid tx") } // tests different msg types in single tx with different addresses @@ -929,7 +929,7 @@ func TestSendBurn(t *testing.T) { acc := app.accountMapper.NewAccountWithAddress(app.deliverState.ctx, addr2) app.accountMapper.SetAccount(app.deliverState.ctx, acc) - assert.Equal(t, sdk.Coins{{"foocoin", sdk.NewInt(100)}}, app.accountKeeper.GetCoins(app.deliverState.ctx, addr1), "Balance1 did not update") + require.Equal(t, sdk.Coins{{"foocoin", sdk.NewInt(100)}}, app.accountKeeper.GetCoins(app.deliverState.ctx, addr1), "Balance1 did not update") sendMsg := testSendMsg{addr1, addr2, sdk.Coins{{"foocoin", sdk.NewInt(50)}}} @@ -940,10 +940,10 @@ func TestSendBurn(t *testing.T) { tx := GenTx(t.Name(), []sdk.Msg{sendMsg, msg2, msg1}, []int64{0, 1}, []int64{0, 0}, priv1, priv2) res := app.Deliver(tx) - assert.Equal(t, true, res.IsOK(), res.Log) + require.Equal(t, true, res.IsOK(), res.Log) - assert.Equal(t, sdk.Coins(nil), app.accountKeeper.GetCoins(app.deliverState.ctx, addr1), "Balance1 did not change after valid tx") - assert.Equal(t, sdk.Coins(nil), app.accountKeeper.GetCoins(app.deliverState.ctx, addr2), "Balance2 did not change after valid tx") + require.Equal(t, sdk.Coins(nil), app.accountKeeper.GetCoins(app.deliverState.ctx, addr1), "Balance1 did not change after valid tx") + require.Equal(t, sdk.Coins(nil), app.accountKeeper.GetCoins(app.deliverState.ctx, addr2), "Balance2 did not change after valid tx") // Check that state is only updated if all msgs in tx pass. app.accountKeeper.AddCoins(app.deliverState.ctx, addr1, sdk.Coins{{"foocoin", sdk.NewInt(50)}}) @@ -960,10 +960,10 @@ func TestSendBurn(t *testing.T) { app.BeginBlock(abci.RequestBeginBlock{}) app.deliverState.ctx = app.deliverState.ctx.WithChainID(t.Name()) - assert.Equal(t, sdk.ABCICodeType(0x1000a), res.Code, "Allowed tx to pass with insufficient funds") + require.Equal(t, sdk.ABCICodeType(0x1000a), res.Code, "Allowed tx to pass with insufficient funds") - assert.Equal(t, sdk.Coins{{"foocoin", sdk.NewInt(50)}}, app.accountKeeper.GetCoins(app.deliverState.ctx, addr1), "Allowed valid msg to pass in invalid tx") - assert.Equal(t, sdk.Coins(nil), app.accountKeeper.GetCoins(app.deliverState.ctx, addr2), "Balance2 changed after invalid tx") + require.Equal(t, sdk.Coins{{"foocoin", sdk.NewInt(50)}}, app.accountKeeper.GetCoins(app.deliverState.ctx, addr1), "Allowed valid msg to pass in invalid tx") + require.Equal(t, sdk.Coins(nil), app.accountKeeper.GetCoins(app.deliverState.ctx, addr2), "Balance2 changed after invalid tx") } //---------------------------------------- diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index e3b19c999d..37d7e91916 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -46,7 +46,7 @@ func TestKeys(t *testing.T) { reg, err := regexp.Compile(`([a-z]+ ){12}`) require.Nil(t, err) match := reg.MatchString(seed) - assert.True(t, match, "Returned seed has wrong format", seed) + require.True(t, match, "Returned seed has wrong format", seed) newName := "test_newname" newPassword := "0987654321" @@ -74,10 +74,10 @@ func TestKeys(t *testing.T) { addr2Bech32 := sdk.MustBech32ifyAcc(addr2Acc) addrBech32 := sdk.MustBech32ifyAcc(addr) - assert.Equal(t, name, m[0].Name, "Did not serve keys name correctly") - assert.Equal(t, addrBech32, m[0].Address, "Did not serve keys Address correctly") - assert.Equal(t, newName, m[1].Name, "Did not serve keys name correctly") - assert.Equal(t, addr2Bech32, m[1].Address, "Did not serve keys Address correctly") + require.Equal(t, name, m[0].Name, "Did not serve keys name correctly") + require.Equal(t, addrBech32, m[0].Address, "Did not serve keys Address correctly") + require.Equal(t, newName, m[1].Name, "Did not serve keys name correctly") + require.Equal(t, addr2Bech32, m[1].Address, "Did not serve keys Address correctly") // select key keyEndpoint := fmt.Sprintf("/keys/%s", newName) @@ -87,8 +87,8 @@ func TestKeys(t *testing.T) { err = cdc.UnmarshalJSON([]byte(body), &m2) require.Nil(t, err) - assert.Equal(t, newName, m2.Name, "Did not serve keys name correctly") - assert.Equal(t, addr2Bech32, m2.Address, "Did not serve keys Address correctly") + require.Equal(t, newName, m2.Name, "Did not serve keys name correctly") + require.Equal(t, addr2Bech32, m2.Address, "Did not serve keys Address correctly") // update key jsonStr = []byte(fmt.Sprintf(`{ @@ -120,7 +120,7 @@ func TestVersion(t *testing.T) { reg, err := regexp.Compile(`\d+\.\d+\.\d+(-dev)?`) require.Nil(t, err) match := reg.MatchString(body) - assert.True(t, match, body) + require.True(t, match, body) // node info res, body = Request(t, port, "GET", "/node_version", nil) @@ -129,7 +129,7 @@ func TestVersion(t *testing.T) { reg, err = regexp.Compile(`\d+\.\d+\.\d+(-dev)?`) require.Nil(t, err) match = reg.MatchString(body) - assert.True(t, match, body) + require.True(t, match, body) } func TestNodeStatus(t *testing.T) { @@ -144,14 +144,14 @@ func TestNodeStatus(t *testing.T) { err := cdc.UnmarshalJSON([]byte(body), &nodeInfo) require.Nil(t, err, "Couldn't parse node info") - assert.NotEqual(t, p2p.NodeInfo{}, nodeInfo, "res: %v", res) + require.NotEqual(t, p2p.NodeInfo{}, nodeInfo, "res: %v", res) // syncing res, body = Request(t, port, "GET", "/syncing", nil) require.Equal(t, http.StatusOK, res.StatusCode, body) // we expect that there is no other node running so the syncing state is "false" - assert.Equal(t, "false", body) + require.Equal(t, "false", body) } func TestBlock(t *testing.T) { @@ -166,7 +166,7 @@ func TestBlock(t *testing.T) { err := cdc.UnmarshalJSON([]byte(body), &resultBlock) require.Nil(t, err, "Couldn't parse block") - assert.NotEqual(t, ctypes.ResultBlock{}, resultBlock) + require.NotEqual(t, ctypes.ResultBlock{}, resultBlock) // -- @@ -176,7 +176,7 @@ func TestBlock(t *testing.T) { err = wire.Cdc.UnmarshalJSON([]byte(body), &resultBlock) require.Nil(t, err, "Couldn't parse block") - assert.NotEqual(t, ctypes.ResultBlock{}, resultBlock) + require.NotEqual(t, ctypes.ResultBlock{}, resultBlock) // -- @@ -196,10 +196,10 @@ func TestValidators(t *testing.T) { err := cdc.UnmarshalJSON([]byte(body), &resultVals) require.Nil(t, err, "Couldn't parse validatorset") - assert.NotEqual(t, rpc.ResultValidatorsOutput{}, resultVals) + require.NotEqual(t, rpc.ResultValidatorsOutput{}, resultVals) - assert.Contains(t, resultVals.Validators[0].Address, "cosmosvaladdr") - assert.Contains(t, resultVals.Validators[0].PubKey, "cosmosvalpub") + require.Contains(t, resultVals.Validators[0].Address, "cosmosvaladdr") + require.Contains(t, resultVals.Validators[0].PubKey, "cosmosvalpub") // -- @@ -209,7 +209,7 @@ func TestValidators(t *testing.T) { err = cdc.UnmarshalJSON([]byte(body), &resultVals) require.Nil(t, err, "Couldn't parse validatorset") - assert.NotEqual(t, rpc.ResultValidatorsOutput{}, resultVals) + require.NotEqual(t, rpc.ResultValidatorsOutput{}, resultVals) // -- @@ -239,24 +239,24 @@ func TestCoinSend(t *testing.T) { tests.WaitForHeight(resultTx.Height+1, port) // check if tx was committed - assert.Equal(t, uint32(0), resultTx.CheckTx.Code) - assert.Equal(t, uint32(0), resultTx.DeliverTx.Code) + require.Equal(t, uint32(0), resultTx.CheckTx.Code) + require.Equal(t, uint32(0), resultTx.DeliverTx.Code) // query sender acc = getAccount(t, port, addr) coins := acc.GetCoins() mycoins := coins[0] - assert.Equal(t, "steak", mycoins.Denom) - assert.Equal(t, initialBalance[0].Amount.SubRaw(1), mycoins.Amount) + require.Equal(t, "steak", mycoins.Denom) + require.Equal(t, initialBalance[0].Amount.SubRaw(1), mycoins.Amount) // query receiver acc = getAccount(t, port, receiveAddr) coins = acc.GetCoins() mycoins = coins[0] - assert.Equal(t, "steak", mycoins.Denom) - assert.Equal(t, int64(1), mycoins.Amount.Int64()) + require.Equal(t, "steak", mycoins.Denom) + require.Equal(t, int64(1), mycoins.Amount.Int64()) } func TestIBCTransfer(t *testing.T) { @@ -274,16 +274,16 @@ func TestIBCTransfer(t *testing.T) { tests.WaitForHeight(resultTx.Height+1, port) // check if tx was committed - assert.Equal(t, uint32(0), resultTx.CheckTx.Code) - assert.Equal(t, uint32(0), resultTx.DeliverTx.Code) + require.Equal(t, uint32(0), resultTx.CheckTx.Code) + require.Equal(t, uint32(0), resultTx.DeliverTx.Code) // query sender acc = getAccount(t, port, addr) coins := acc.GetCoins() mycoins := coins[0] - assert.Equal(t, "steak", mycoins.Denom) - assert.Equal(t, initialBalance[0].Amount.SubRaw(1), mycoins.Amount) + require.Equal(t, "steak", mycoins.Denom) + require.Equal(t, initialBalance[0].Amount.SubRaw(1), mycoins.Amount) // TODO: query ibc egress packet state } @@ -301,7 +301,7 @@ func TestTxs(t *testing.T) { // query empty res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=sender_bech32='%s'", "cosmosaccaddr1jawd35d9aq4u76sr3fjalmcqc8hqygs9gtnmv3"), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - assert.Equal(t, "[]", body) + require.Equal(t, "[]", body) // create TX receiveAddr, resultTx := doSend(t, port, seed, name, password, addr) @@ -323,15 +323,15 @@ func TestTxs(t *testing.T) { // check if tx is queryable res, body = Request(t, port, "GET", fmt.Sprintf("/txs?tag=tx.hash='%s'", resultTx.Hash), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - assert.NotEqual(t, "[]", body) + require.NotEqual(t, "[]", body) err := cdc.UnmarshalJSON([]byte(body), &indexedTxs) require.NoError(t, err) - assert.Equal(t, 1, len(indexedTxs)) + require.Equal(t, 1, len(indexedTxs)) // XXX should this move into some other testfile for txs in general? // test if created TX hash is the correct hash - assert.Equal(t, resultTx.Hash, indexedTxs[0].Hash) + require.Equal(t, resultTx.Hash, indexedTxs[0].Hash) // query sender // also tests url decoding @@ -342,7 +342,7 @@ func TestTxs(t *testing.T) { err = cdc.UnmarshalJSON([]byte(body), &indexedTxs) require.NoError(t, err) require.Equal(t, 1, len(indexedTxs), "%v", indexedTxs) // there are 2 txs created with doSend - assert.Equal(t, resultTx.Height, indexedTxs[0].Height) + require.Equal(t, resultTx.Height, indexedTxs[0].Height) // query recipient receiveAddrBech := sdk.MustBech32ifyAcc(receiveAddr) @@ -352,7 +352,7 @@ func TestTxs(t *testing.T) { err = cdc.UnmarshalJSON([]byte(body), &indexedTxs) require.NoError(t, err) require.Equal(t, 1, len(indexedTxs)) - assert.Equal(t, resultTx.Height, indexedTxs[0].Height) + require.Equal(t, resultTx.Height, indexedTxs[0].Height) } func TestValidatorsQuery(t *testing.T) { @@ -361,7 +361,7 @@ func TestValidatorsQuery(t *testing.T) { require.Equal(t, 2, len(pks)) validators := getValidators(t, port) - assert.Equal(t, len(validators), 2) + require.Equal(t, len(validators), 2) // make sure all the validators were found (order unknown because sorted by owner addr) foundVal1, foundVal2 := false, false @@ -373,8 +373,8 @@ func TestValidatorsQuery(t *testing.T) { if validators[0].PubKey == pk2Bech || validators[1].PubKey == pk2Bech { foundVal2 = true } - assert.True(t, foundVal1, "pk1Bech %v, owner1 %v, owner2 %v", pk1Bech, validators[0].Owner, validators[1].Owner) - assert.True(t, foundVal2, "pk2Bech %v, owner1 %v, owner2 %v", pk2Bech, validators[0].Owner, validators[1].Owner) + require.True(t, foundVal1, "pk1Bech %v, owner1 %v, owner2 %v", pk1Bech, validators[0].Owner, validators[1].Owner) + require.True(t, foundVal2, "pk2Bech %v, owner1 %v, owner2 %v", pk2Bech, validators[0].Owner, validators[1].Owner) } func TestBonding(t *testing.T) { @@ -390,18 +390,18 @@ func TestBonding(t *testing.T) { tests.WaitForHeight(resultTx.Height+1, port) // check if tx was committed - assert.Equal(t, uint32(0), resultTx.CheckTx.Code) - assert.Equal(t, uint32(0), resultTx.DeliverTx.Code) + require.Equal(t, uint32(0), resultTx.CheckTx.Code) + require.Equal(t, uint32(0), resultTx.DeliverTx.Code) // query sender acc := getAccount(t, port, addr) coins := acc.GetCoins() - assert.Equal(t, int64(40), coins.AmountOf(denom).Int64()) + require.Equal(t, int64(40), coins.AmountOf(denom).Int64()) // query validator bond := getDelegation(t, port, addr, validator1Owner) - assert.Equal(t, "60/1", bond.Shares.String()) + require.Equal(t, "60/1", bond.Shares.String()) ////////////////////// // testing unbonding @@ -412,17 +412,17 @@ func TestBonding(t *testing.T) { // query validator bond = getDelegation(t, port, addr, validator1Owner) - assert.Equal(t, "30/1", bond.Shares.String()) + require.Equal(t, "30/1", bond.Shares.String()) // check if tx was committed - assert.Equal(t, uint32(0), resultTx.CheckTx.Code) - assert.Equal(t, uint32(0), resultTx.DeliverTx.Code) + require.Equal(t, uint32(0), resultTx.CheckTx.Code) + require.Equal(t, uint32(0), resultTx.DeliverTx.Code) // should the sender should have not received any coins as the unbonding has only just begun // query sender acc = getAccount(t, port, addr) coins = acc.GetCoins() - assert.Equal(t, int64(40), coins.AmountOf("steak").Int64()) + require.Equal(t, int64(40), coins.AmountOf("steak").Int64()) // TODO add redelegation, need more complex capabilities such to mock context and } @@ -438,15 +438,15 @@ func TestSubmitProposal(t *testing.T) { tests.WaitForHeight(resultTx.Height+1, port) // check if tx was committed - assert.Equal(t, uint32(0), resultTx.CheckTx.Code) - assert.Equal(t, uint32(0), resultTx.DeliverTx.Code) + require.Equal(t, uint32(0), resultTx.CheckTx.Code) + require.Equal(t, uint32(0), resultTx.DeliverTx.Code) var proposalID int64 cdc.UnmarshalBinaryBare(resultTx.DeliverTx.GetData(), &proposalID) // query proposal proposal := getProposal(t, port, proposalID) - assert.Equal(t, "Test", proposal.Title) + require.Equal(t, "Test", proposal.Title) } func TestDeposit(t *testing.T) { @@ -460,15 +460,15 @@ func TestDeposit(t *testing.T) { tests.WaitForHeight(resultTx.Height+1, port) // check if tx was committed - assert.Equal(t, uint32(0), resultTx.CheckTx.Code) - assert.Equal(t, uint32(0), resultTx.DeliverTx.Code) + require.Equal(t, uint32(0), resultTx.CheckTx.Code) + require.Equal(t, uint32(0), resultTx.DeliverTx.Code) var proposalID int64 cdc.UnmarshalBinaryBare(resultTx.DeliverTx.GetData(), &proposalID) // query proposal proposal := getProposal(t, port, proposalID) - assert.Equal(t, "Test", proposal.Title) + require.Equal(t, "Test", proposal.Title) // create SubmitProposal TX resultTx = doDeposit(t, port, seed, name, password, addr, proposalID) @@ -476,11 +476,11 @@ func TestDeposit(t *testing.T) { // query proposal proposal = getProposal(t, port, proposalID) - assert.True(t, proposal.TotalDeposit.IsEqual(sdk.Coins{sdk.NewCoin("steak", 10)})) + require.True(t, proposal.TotalDeposit.IsEqual(sdk.Coins{sdk.NewCoin("steak", 10)})) // query deposit deposit := getDeposit(t, port, proposalID, addr) - assert.True(t, deposit.Amount.IsEqual(sdk.Coins{sdk.NewCoin("steak", 10)})) + require.True(t, deposit.Amount.IsEqual(sdk.Coins{sdk.NewCoin("steak", 10)})) } func TestVote(t *testing.T) { @@ -494,15 +494,15 @@ func TestVote(t *testing.T) { tests.WaitForHeight(resultTx.Height+1, port) // check if tx was committed - assert.Equal(t, uint32(0), resultTx.CheckTx.Code) - assert.Equal(t, uint32(0), resultTx.DeliverTx.Code) + require.Equal(t, uint32(0), resultTx.CheckTx.Code) + require.Equal(t, uint32(0), resultTx.DeliverTx.Code) var proposalID int64 cdc.UnmarshalBinaryBare(resultTx.DeliverTx.GetData(), &proposalID) // query proposal proposal := getProposal(t, port, proposalID) - assert.Equal(t, "Test", proposal.Title) + require.Equal(t, "Test", proposal.Title) // create SubmitProposal TX resultTx = doDeposit(t, port, seed, name, password, addr, proposalID) @@ -510,15 +510,15 @@ func TestVote(t *testing.T) { // query proposal proposal = getProposal(t, port, proposalID) - assert.Equal(t, gov.StatusToString(gov.StatusVotingPeriod), proposal.Status) + require.Equal(t, gov.StatusToString(gov.StatusVotingPeriod), proposal.Status) // create SubmitProposal TX resultTx = doVote(t, port, seed, name, password, addr, proposalID) tests.WaitForHeight(resultTx.Height+1, port) vote := getVote(t, port, proposalID, addr) - assert.Equal(t, proposalID, vote.ProposalID) - assert.Equal(t, gov.VoteOptionToString(gov.OptionYes), vote.Option) + require.Equal(t, proposalID, vote.ProposalID) + require.Equal(t, gov.VoteOptionToString(gov.OptionYes), vote.Option) } func TestProposalsQuery(t *testing.T) { @@ -563,31 +563,31 @@ func TestProposalsQuery(t *testing.T) { // Test query all proposals proposals := getProposalsAll(t, port) - assert.Equal(t, proposalID1, (proposals[0]).ProposalID) - assert.Equal(t, proposalID2, (proposals[1]).ProposalID) - assert.Equal(t, proposalID3, (proposals[2]).ProposalID) + require.Equal(t, proposalID1, (proposals[0]).ProposalID) + require.Equal(t, proposalID2, (proposals[1]).ProposalID) + require.Equal(t, proposalID3, (proposals[2]).ProposalID) // Test query deposited by addr1 proposals = getProposalsFilterDepositer(t, port, addr) - assert.Equal(t, proposalID1, (proposals[0]).ProposalID) + require.Equal(t, proposalID1, (proposals[0]).ProposalID) // Test query deposited by addr2 proposals = getProposalsFilterDepositer(t, port, addr2) - assert.Equal(t, proposalID2, (proposals[0]).ProposalID) - assert.Equal(t, proposalID3, (proposals[1]).ProposalID) + require.Equal(t, proposalID2, (proposals[0]).ProposalID) + require.Equal(t, proposalID3, (proposals[1]).ProposalID) // Test query voted by addr1 proposals = getProposalsFilterVoter(t, port, addr) - assert.Equal(t, proposalID2, (proposals[0]).ProposalID) - assert.Equal(t, proposalID3, (proposals[1]).ProposalID) + require.Equal(t, proposalID2, (proposals[0]).ProposalID) + require.Equal(t, proposalID3, (proposals[1]).ProposalID) // Test query voted by addr2 proposals = getProposalsFilterVoter(t, port, addr2) - assert.Equal(t, proposalID3, (proposals[0]).ProposalID) + require.Equal(t, proposalID3, (proposals[0]).ProposalID) // Test query voted and deposited by addr1 proposals = getProposalsFilterVoterDepositer(t, port, addr, addr) - assert.Equal(t, proposalID2, (proposals[0]).ProposalID) + require.Equal(t, proposalID2, (proposals[0]).ProposalID) } //_____________________________________________________________________________ diff --git a/cmd/gaia/app/genesis_test.go b/cmd/gaia/app/genesis_test.go index 90677e8ff1..7f0da29901 100644 --- a/cmd/gaia/app/genesis_test.go +++ b/cmd/gaia/app/genesis_test.go @@ -5,7 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" ) @@ -14,7 +14,7 @@ func TestToAccount(t *testing.T) { addr := sdk.Address(priv.PubKey().Address()) authAcc := auth.NewBaseAccountWithAddress(addr) genAcc := NewGenesisAccount(&authAcc) - assert.Equal(t, authAcc, *genAcc.ToAccount()) + require.Equal(t, authAcc, *genAcc.ToAccount()) } func TestGaiaAppGenTx(t *testing.T) { diff --git a/cmd/gaia/cli_test/cli_test.go b/cmd/gaia/cli_test/cli_test.go index f8937c42dc..62fe0631a3 100644 --- a/cmd/gaia/cli_test/cli_test.go +++ b/cmd/gaia/cli_test/cli_test.go @@ -5,7 +5,6 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client/keys" @@ -47,33 +46,33 @@ func TestGaiaCLISend(t *testing.T) { require.NoError(t, err) fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags)) - assert.Equal(t, int64(50), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf("steak").Int64()) executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --name=foo", flags, barCech), pass) tests.WaitForNextHeightTM(port) barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags)) - assert.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak").Int64()) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags)) - assert.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak").Int64()) // test autosequencing executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --name=foo", flags, barCech), pass) tests.WaitForNextHeightTM(port) barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags)) - assert.Equal(t, int64(20), barAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, int64(20), barAcc.GetCoins().AmountOf("steak").Int64()) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags)) - assert.Equal(t, int64(30), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, int64(30), fooAcc.GetCoins().AmountOf("steak").Int64()) // test memo executeWrite(t, fmt.Sprintf("gaiacli send %v --amount=10steak --to=%v --name=foo --memo 'testmemo'", flags, barCech), pass) tests.WaitForNextHeightTM(port) barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags)) - assert.Equal(t, int64(30), barAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, int64(30), barAcc.GetCoins().AmountOf("steak").Int64()) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags)) - assert.Equal(t, int64(20), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, int64(20), fooAcc.GetCoins().AmountOf("steak").Int64()) } func TestGaiaCLICreateValidator(t *testing.T) { @@ -108,9 +107,9 @@ func TestGaiaCLICreateValidator(t *testing.T) { tests.WaitForNextHeightTM(port) barAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags)) - assert.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, int64(10), barAcc.GetCoins().AmountOf("steak").Int64()) fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags)) - assert.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, int64(40), fooAcc.GetCoins().AmountOf("steak").Int64()) // create validator cvStr := fmt.Sprintf("gaiacli stake create-validator %v", flags) @@ -127,8 +126,8 @@ func TestGaiaCLICreateValidator(t *testing.T) { require.Equal(t, int64(8), barAcc.GetCoins().AmountOf("steak").Int64(), "%v", barAcc) validator := executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %v --output=json %v", barCech, flags)) - assert.Equal(t, validator.Owner, barAddr) - assert.Equal(t, "2/1", validator.PoolShares.Amount.String()) + require.Equal(t, validator.Owner, barAddr) + require.Equal(t, "2/1", validator.PoolShares.Amount.String()) // unbond a single share unbondStr := fmt.Sprintf("gaiacli stake unbond %v", flags) @@ -145,7 +144,7 @@ func TestGaiaCLICreateValidator(t *testing.T) { barAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", barCech, flags)) require.Equal(t, int64(9), barAcc.GetCoins().AmountOf("steak").Int64(), "%v", barAcc) validator = executeGetValidator(t, fmt.Sprintf("gaiacli stake validator %v --output=json %v", barCech, flags)) - assert.Equal(t, "1/1", validator.PoolShares.Amount.String()) + require.Equal(t, "1/1", validator.PoolShares.Amount.String()) } func TestGaiaCLISubmitProposal(t *testing.T) { @@ -172,33 +171,33 @@ func TestGaiaCLISubmitProposal(t *testing.T) { require.NoError(t, err) fooAcc := executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags)) - assert.Equal(t, int64(50), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, int64(50), fooAcc.GetCoins().AmountOf("steak").Int64()) executeWrite(t, fmt.Sprintf("gaiacli gov submitproposal %v --proposer=%v --deposit=5steak --type=Text --title=Test --description=test --name=foo", flags, fooCech), pass) tests.WaitForNextHeightTM(port) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags)) - assert.Equal(t, int64(45), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, int64(45), fooAcc.GetCoins().AmountOf("steak").Int64()) proposal1 := executeGetProposal(t, fmt.Sprintf("gaiacli gov query-proposal --proposalID=1 --output=json %v", flags)) - assert.Equal(t, int64(1), proposal1.ProposalID) - assert.Equal(t, gov.StatusToString(gov.StatusDepositPeriod), proposal1.Status) + require.Equal(t, int64(1), proposal1.ProposalID) + require.Equal(t, gov.StatusToString(gov.StatusDepositPeriod), proposal1.Status) executeWrite(t, fmt.Sprintf("gaiacli gov deposit %v --depositer=%v --deposit=10steak --proposalID=1 --name=foo", flags, fooCech), pass) tests.WaitForNextHeightTM(port) fooAcc = executeGetAccount(t, fmt.Sprintf("gaiacli account %v %v", fooCech, flags)) - assert.Equal(t, int64(35), fooAcc.GetCoins().AmountOf("steak").Int64()) + require.Equal(t, int64(35), fooAcc.GetCoins().AmountOf("steak").Int64()) proposal1 = executeGetProposal(t, fmt.Sprintf("gaiacli gov query-proposal --proposalID=1 --output=json %v", flags)) - assert.Equal(t, int64(1), proposal1.ProposalID) - assert.Equal(t, gov.StatusToString(gov.StatusVotingPeriod), proposal1.Status) + require.Equal(t, int64(1), proposal1.ProposalID) + require.Equal(t, gov.StatusToString(gov.StatusVotingPeriod), proposal1.Status) executeWrite(t, fmt.Sprintf("gaiacli gov vote %v --proposalID=1 --voter=%v --option=Yes --name=foo", flags, fooCech), pass) tests.WaitForNextHeightTM(port) vote := executeGetVote(t, fmt.Sprintf("gaiacli gov query-vote --proposalID=1 --voter=%v --output=json %v", fooCech, flags)) - assert.Equal(t, int64(1), vote.ProposalID) - assert.Equal(t, gov.VoteOptionToString(gov.OptionYes), vote.Option) + require.Equal(t, int64(1), vote.ProposalID) + require.Equal(t, gov.VoteOptionToString(gov.OptionYes), vote.Option) } //___________________________________________________________________________________ diff --git a/crypto/encode_test.go b/crypto/encode_test.go index f9ab851b40..99dd727cf7 100644 --- a/crypto/encode_test.go +++ b/crypto/encode_test.go @@ -1,7 +1,6 @@ package crypto import ( - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "os" "testing" @@ -18,10 +17,10 @@ func checkAminoBinary(t *testing.T, src byter, dst interface{}, size int) { bz, err := cdc.MarshalBinaryBare(src) require.Nil(t, err, "%+v", err) // Make sure this is compatible with current (Bytes()) encoding. - assert.Equal(t, src.Bytes(), bz, "Amino binary vs Bytes() mismatch") + require.Equal(t, src.Bytes(), bz, "Amino binary vs Bytes() mismatch") // Make sure we have the expected length. if size != -1 { - assert.Equal(t, size, len(bz), "Amino binary size mismatch") + require.Equal(t, size, len(bz), "Amino binary size mismatch") } // Unmarshal. err = cdc.UnmarshalBinaryBare(bz, dst) @@ -33,10 +32,10 @@ func checkAminoJSON(t *testing.T, src interface{}, dst interface{}, isNil bool) js, err := cdc.MarshalJSON(src) require.Nil(t, err, "%+v", err) if isNil { - assert.Equal(t, string(js), `null`) + require.Equal(t, string(js), `null`) } else { - assert.Contains(t, string(js), `"type":`) - assert.Contains(t, string(js), `"value":`) + require.Contains(t, string(js), `"type":`) + require.Contains(t, string(js), `"value":`) } // Unmarshal. err = cdc.UnmarshalJSON(js, dst) @@ -79,26 +78,26 @@ func TestKeyEncodings(t *testing.T) { // Check (de/en)codings of PrivKeys. var priv2, priv3 tcrypto.PrivKey checkAminoBinary(t, tc.privKey, &priv2, tc.privSize) - assert.EqualValues(t, tc.privKey, priv2) + require.EqualValues(t, tc.privKey, priv2) checkAminoJSON(t, tc.privKey, &priv3, false) // TODO also check Prefix bytes. - assert.EqualValues(t, tc.privKey, priv3) + require.EqualValues(t, tc.privKey, priv3) // Check (de/en)codings of Signatures. var sig1, sig2, sig3 tcrypto.Signature sig1, err := tc.privKey.Sign([]byte("something")) - assert.NoError(t, err) + require.NoError(t, err) checkAminoBinary(t, sig1, &sig2, -1) // Signature size changes for Secp anyways. - assert.EqualValues(t, sig1, sig2) + require.EqualValues(t, sig1, sig2) checkAminoJSON(t, sig1, &sig3, false) // TODO also check Prefix bytes. - assert.EqualValues(t, sig1, sig3) + require.EqualValues(t, sig1, sig3) // Check (de/en)codings of PubKeys. pubKey := tc.privKey.PubKey() var pub2, pub3 tcrypto.PubKey checkAminoBinary(t, pubKey, &pub2, tc.pubSize) - assert.EqualValues(t, pubKey, pub2) + require.EqualValues(t, pubKey, pub2) checkAminoJSON(t, pubKey, &pub3, false) // TODO also check Prefix bytes. - assert.EqualValues(t, pubKey, pub3) + require.EqualValues(t, pubKey, pub3) } } @@ -107,16 +106,16 @@ func TestNilEncodings(t *testing.T) { // Check nil Signature. var a, b tcrypto.Signature checkAminoJSON(t, &a, &b, true) - assert.EqualValues(t, a, b) + require.EqualValues(t, a, b) // Check nil PubKey. var c, d tcrypto.PubKey checkAminoJSON(t, &c, &d, true) - assert.EqualValues(t, c, d) + require.EqualValues(t, c, d) // Check nil PrivKey. var e, f tcrypto.PrivKey checkAminoJSON(t, &e, &f, true) - assert.EqualValues(t, e, f) + require.EqualValues(t, e, f) } diff --git a/crypto/keys/bip39/wordcodec_test.go b/crypto/keys/bip39/wordcodec_test.go index dbc5c0d020..a821239d7b 100644 --- a/crypto/keys/bip39/wordcodec_test.go +++ b/crypto/keys/bip39/wordcodec_test.go @@ -3,13 +3,13 @@ package bip39 import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestWordCodec_NewMnemonic(t *testing.T) { _, err := NewMnemonic(FundRaiser) - assert.NoError(t, err, "unexpected error generating fundraiser mnemonic") + require.NoError(t, err, "unexpected error generating fundraiser mnemonic") _, err = NewMnemonic(FreshKey) - assert.NoError(t, err, "unexpected error generating new 24-word mnemonic") + require.NoError(t, err, "unexpected error generating new 24-word mnemonic") } diff --git a/crypto/keys/hd/fundraiser_test.go b/crypto/keys/hd/fundraiser_test.go index 3e45de7e2d..f4112d958b 100644 --- a/crypto/keys/hd/fundraiser_test.go +++ b/crypto/keys/hd/fundraiser_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/bartekn/go-bip39" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" ) @@ -56,7 +56,7 @@ func TestFundraiserCompatibility(t *testing.T) { master, ch := ComputeMastersFromSeed(seed) priv, err := DerivePrivateKeyForPath(master, ch, "44'/118'/0'/0/0") - assert.NoError(t, err) + require.NoError(t, err) pub := crypto.PrivKeySecp256k1(priv).PubKey() t.Log("\tNODEJS GOLANG\n") @@ -65,16 +65,16 @@ func TestFundraiserCompatibility(t *testing.T) { t.Logf("PRIV \t%X %X\n", privB, priv) t.Logf("PUB \t%X %X\n", pubB, pub) - assert.Equal(t, seedB, seed) - assert.Equal(t, master[:], masterB, fmt.Sprintf("Expected masters to match for %d", i)) - assert.Equal(t, priv[:], privB, "Expected priv keys to match") + require.Equal(t, seedB, seed) + require.Equal(t, master[:], masterB, fmt.Sprintf("Expected masters to match for %d", i)) + require.Equal(t, priv[:], privB, "Expected priv keys to match") var pubBFixed [33]byte copy(pubBFixed[:], pubB) - assert.Equal(t, pub, crypto.PubKeySecp256k1(pubBFixed), fmt.Sprintf("Expected pub keys to match for %d", i)) + require.Equal(t, pub, crypto.PubKeySecp256k1(pubBFixed), fmt.Sprintf("Expected pub keys to match for %d", i)) addr := pub.Address() t.Logf("ADDR \t%X %X\n", addrB, addr) - assert.Equal(t, addr, crypto.Address(addrB), fmt.Sprintf("Expected addresses to match %d", i)) + require.Equal(t, addr, crypto.Address(addrB), fmt.Sprintf("Expected addresses to match %d", i)) } } diff --git a/crypto/keys/keybase_test.go b/crypto/keys/keybase_test.go index d2f093bf2d..ac0f7fa4da 100644 --- a/crypto/keys/keybase_test.go +++ b/crypto/keys/keybase_test.go @@ -29,11 +29,11 @@ func TestKeyManagement(t *testing.T) { assert.Empty(t, l) _, _, err = cstore.CreateMnemonic(n1, English, p1, Ed25519) - assert.Error(t, err, "ed25519 keys are currently not supported by keybase") + require.Error(t, err, "ed25519 keys are currently not supported by keybase") // create some keys _, err = cstore.Get(n1) - assert.Error(t, err) + require.Error(t, err) i, _, err := cstore.CreateMnemonic(n1, English, p1, algo) require.NoError(t, err) @@ -43,18 +43,18 @@ func TestKeyManagement(t *testing.T) { // we can get these keys i2, err := cstore.Get(n2) - assert.NoError(t, err) + require.NoError(t, err) _, err = cstore.Get(n3) - assert.NotNil(t, err) + require.NotNil(t, err) // list shows them in order keyS, err := cstore.List() require.NoError(t, err) require.Equal(t, 2, len(keyS)) // note these are in alphabetical order - assert.Equal(t, n2, keyS[0].GetName()) - assert.Equal(t, n1, keyS[1].GetName()) - assert.Equal(t, i2.GetPubKey(), keyS[0].GetPubKey()) + require.Equal(t, n2, keyS[0].GetName()) + require.Equal(t, n1, keyS[1].GetName()) + require.Equal(t, i2.GetPubKey(), keyS[0].GetPubKey()) // deleting a key removes it err = cstore.Delete("bad name", "foo") @@ -63,9 +63,9 @@ func TestKeyManagement(t *testing.T) { require.NoError(t, err) keyS, err = cstore.List() require.NoError(t, err) - assert.Equal(t, 1, len(keyS)) + require.Equal(t, 1, len(keyS)) _, err = cstore.Get(n1) - assert.Error(t, err) + require.Error(t, err) // create an offline key o1 := "offline" @@ -158,19 +158,19 @@ func TestSignVerify(t *testing.T) { for i, tc := range cases { valid := tc.key.VerifyBytes(tc.data, tc.sig) - assert.Equal(t, tc.valid, valid, "%d", i) + require.Equal(t, tc.valid, valid, "%d", i) } // Now try to sign data with a secret-less key _, _, err = cstore.Sign(n3, p3, d3) - assert.NotNil(t, err) + require.NotNil(t, err) } func assertPassword(t *testing.T, cstore Keybase, name, pass, badpass string) { err := cstore.Update(name, badpass, pass) - assert.NotNil(t, err) + require.NotNil(t, err) err = cstore.Update(name, pass, pass) - assert.Nil(t, err, "%+v", err) + require.Nil(t, err, "%+v", err) } // TestExportImport tests exporting and importing @@ -183,26 +183,26 @@ func TestExportImport(t *testing.T) { ) info, _, err := cstore.CreateMnemonic("john", English, "secretcpw", Secp256k1) - assert.NoError(t, err) - assert.Equal(t, info.GetName(), "john") + require.NoError(t, err) + require.Equal(t, info.GetName(), "john") john, err := cstore.Get("john") - assert.NoError(t, err) - assert.Equal(t, info.GetName(), "john") + require.NoError(t, err) + require.Equal(t, info.GetName(), "john") johnAddr := info.GetPubKey().Address() armor, err := cstore.Export("john") - assert.NoError(t, err) + require.NoError(t, err) err = cstore.Import("john2", armor) - assert.NoError(t, err) + require.NoError(t, err) john2, err := cstore.Get("john2") - assert.NoError(t, err) + require.NoError(t, err) - assert.Equal(t, john.GetPubKey().Address(), johnAddr) - assert.Equal(t, john.GetName(), "john") - assert.Equal(t, john, john2) + require.Equal(t, john.GetPubKey().Address(), johnAddr) + require.Equal(t, john.GetName(), "john") + require.Equal(t, john, john2) } // @@ -216,35 +216,35 @@ func TestExportImportPubKey(t *testing.T) { // CreateMnemonic a private-public key pair and ensure consistency notPasswd := "n9y25ah7" info, _, err := cstore.CreateMnemonic("john", English, notPasswd, Secp256k1) - assert.Nil(t, err) - assert.NotEqual(t, info, "") - assert.Equal(t, info.GetName(), "john") + require.Nil(t, err) + require.NotEqual(t, info, "") + require.Equal(t, info.GetName(), "john") addr := info.GetPubKey().Address() john, err := cstore.Get("john") - assert.NoError(t, err) - assert.Equal(t, john.GetName(), "john") - assert.Equal(t, john.GetPubKey().Address(), addr) + require.NoError(t, err) + require.Equal(t, john.GetName(), "john") + require.Equal(t, john.GetPubKey().Address(), addr) // Export the public key only armor, err := cstore.ExportPubKey("john") - assert.NoError(t, err) + require.NoError(t, err) // Import it under a different name err = cstore.ImportPubKey("john-pubkey-only", armor) - assert.NoError(t, err) + require.NoError(t, err) // Ensure consistency john2, err := cstore.Get("john-pubkey-only") - assert.NoError(t, err) + require.NoError(t, err) // Compare the public keys - assert.True(t, john.GetPubKey().Equals(john2.GetPubKey())) + require.True(t, john.GetPubKey().Equals(john2.GetPubKey())) // Ensure the original key hasn't changed john, err = cstore.Get("john") - assert.NoError(t, err) - assert.Equal(t, john.GetPubKey().Address(), addr) - assert.Equal(t, john.GetName(), "john") + require.NoError(t, err) + require.Equal(t, john.GetPubKey().Address(), addr) + require.Equal(t, john.GetName(), "john") // Ensure keys cannot be overwritten err = cstore.ImportPubKey("john-pubkey-only", armor) - assert.NotNil(t, err) + require.NotNil(t, err) } // TestAdvancedKeyManagement verifies update, import, export functionality @@ -266,34 +266,34 @@ func TestAdvancedKeyManagement(t *testing.T) { // update password requires the existing password err = cstore.Update(n1, "jkkgkg", p2) - assert.NotNil(t, err) + require.NotNil(t, err) assertPassword(t, cstore, n1, p1, p2) // then it changes the password when correct err = cstore.Update(n1, p1, p2) - assert.NoError(t, err) + require.NoError(t, err) // p2 is now the proper one! assertPassword(t, cstore, n1, p2, p1) // exporting requires the proper name and passphrase _, err = cstore.Export(n1 + ".notreal") - assert.NotNil(t, err) + require.NotNil(t, err) _, err = cstore.Export(" " + n1) - assert.NotNil(t, err) + require.NotNil(t, err) _, err = cstore.Export(n1 + " ") - assert.NotNil(t, err) + require.NotNil(t, err) _, err = cstore.Export("") - assert.NotNil(t, err) + require.NotNil(t, err) exported, err := cstore.Export(n1) require.Nil(t, err, "%+v", err) // import succeeds err = cstore.Import(n2, exported) - assert.NoError(t, err) + require.NoError(t, err) // second import fails err = cstore.Import(n2, exported) - assert.NotNil(t, err) + require.NotNil(t, err) } // TestSeedPhrase verifies restoring from a seed phrase @@ -311,7 +311,7 @@ func TestSeedPhrase(t *testing.T) { // make sure key works with initial password info, mnemonic, err := cstore.CreateMnemonic(n1, English, p1, algo) require.Nil(t, err, "%+v", err) - assert.Equal(t, n1, info.GetName()) + require.Equal(t, n1, info.GetName()) assert.NotEmpty(t, mnemonic) // now, let us delete this key @@ -324,9 +324,9 @@ func TestSeedPhrase(t *testing.T) { params := *hd.NewFundraiserParams(0, 0) newInfo, err := cstore.Derive(n2, mnemonic, p2, params) require.NoError(t, err) - assert.Equal(t, n2, newInfo.GetName()) - assert.Equal(t, info.GetPubKey().Address(), newInfo.GetPubKey().Address()) - assert.Equal(t, info.GetPubKey(), newInfo.GetPubKey()) + require.Equal(t, n2, newInfo.GetName()) + require.Equal(t, info.GetPubKey().Address(), newInfo.GetPubKey().Address()) + require.Equal(t, info.GetPubKey(), newInfo.GetPubKey()) } func ExampleNew() { diff --git a/crypto/ledger_test.go b/crypto/ledger_test.go index 072d846473..997dfbc3bc 100644 --- a/crypto/ledger_test.go +++ b/crypto/ledger_test.go @@ -4,7 +4,6 @@ import ( "os" "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" tcrypto "github.com/tendermint/tendermint/crypto" @@ -26,7 +25,7 @@ func TestRealLedgerSecp256k1(t *testing.T) { require.Nil(t, err) valid := pub.VerifyBytes(msg, sig) - assert.True(t, valid) + require.True(t, valid) // now, let's serialize the key and make sure it still works bs := priv.Bytes() @@ -41,13 +40,13 @@ func TestRealLedgerSecp256k1(t *testing.T) { sig, err = priv2.Sign(msg) require.Nil(t, err) valid = pub.VerifyBytes(msg, sig) - assert.True(t, valid) + require.True(t, valid) // make sure pubkeys serialize properly as well bs = pub.Bytes() bpub, err := tcrypto.PubKeyFromBytes(bs) require.NoError(t, err) - assert.Equal(t, pub, bpub) + require.Equal(t, pub, bpub) } // TestRealLedgerErrorHandling calls. These tests assume diff --git a/examples/basecoin/app/app_test.go b/examples/basecoin/app/app_test.go index 539a52c731..499c0e4082 100644 --- a/examples/basecoin/app/app_test.go +++ b/examples/basecoin/app/app_test.go @@ -5,7 +5,6 @@ import ( "os" "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/examples/basecoin/types" @@ -69,7 +68,7 @@ func TestGenesis(t *testing.T) { // A checkTx context ctx := bapp.BaseApp.NewContext(true, abci.Header{}) res1 := bapp.accountMapper.GetAccount(ctx, baseAcc.Address) - assert.Equal(t, acc, res1) + require.Equal(t, acc, res1) // reload app and ensure the account is still there bapp = NewBasecoinApp(logger, db) @@ -85,5 +84,5 @@ func TestGenesis(t *testing.T) { ctx = bapp.BaseApp.NewContext(true, abci.Header{}) res1 = bapp.accountMapper.GetAccount(ctx, baseAcc.Address) - assert.Equal(t, acc, res1) + require.Equal(t, acc, res1) } diff --git a/examples/democoin/app/app_test.go b/examples/democoin/app/app_test.go index d67e4f7064..36aca760f1 100644 --- a/examples/democoin/app/app_test.go +++ b/examples/democoin/app/app_test.go @@ -4,7 +4,6 @@ import ( "os" "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/examples/democoin/types" @@ -64,12 +63,12 @@ func TestGenesis(t *testing.T) { // A checkTx context ctx := bapp.BaseApp.NewContext(true, abci.Header{}) res1 := bapp.accountMapper.GetAccount(ctx, baseAcc.Address) - assert.Equal(t, acc, res1) + require.Equal(t, acc, res1) // reload app and ensure the account is still there bapp = NewDemocoinApp(logger, db) bapp.InitChain(abci.RequestInitChain{AppStateBytes: []byte("{}")}) ctx = bapp.BaseApp.NewContext(true, abci.Header{}) res1 = bapp.accountMapper.GetAccount(ctx, baseAcc.Address) - assert.Equal(t, acc, res1) + require.Equal(t, acc, res1) } diff --git a/examples/democoin/x/assoc/validator_set_test.go b/examples/democoin/x/assoc/validator_set_test.go index 289604149b..c20aeb8571 100644 --- a/examples/democoin/x/assoc/validator_set_test.go +++ b/examples/democoin/x/assoc/validator_set_test.go @@ -4,7 +4,7 @@ import ( "bytes" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tmlibs/db" @@ -38,34 +38,34 @@ func TestValidatorSet(t *testing.T) { valset := NewValidatorSet(wire.NewCodec(), sdk.NewPrefixStoreGetter(key, []byte("assoc")), base, 1, 5) - assert.Equal(t, base.Validator(ctx, addr1), valset.Validator(ctx, addr1)) - assert.Equal(t, base.Validator(ctx, addr2), valset.Validator(ctx, addr2)) + require.Equal(t, base.Validator(ctx, addr1), valset.Validator(ctx, addr1)) + require.Equal(t, base.Validator(ctx, addr2), valset.Validator(ctx, addr2)) assoc1 := []byte("asso1") assoc2 := []byte("asso2") - assert.True(t, valset.Associate(ctx, addr1, assoc1)) - assert.True(t, valset.Associate(ctx, addr2, assoc2)) + require.True(t, valset.Associate(ctx, addr1, assoc1)) + require.True(t, valset.Associate(ctx, addr2, assoc2)) - assert.Equal(t, base.Validator(ctx, addr1), valset.Validator(ctx, assoc1)) - assert.Equal(t, base.Validator(ctx, addr2), valset.Validator(ctx, assoc2)) + require.Equal(t, base.Validator(ctx, addr1), valset.Validator(ctx, assoc1)) + require.Equal(t, base.Validator(ctx, addr2), valset.Validator(ctx, assoc2)) - assert.Equal(t, base.Validator(ctx, addr1), valset.Validator(ctx, addr1)) - assert.Equal(t, base.Validator(ctx, addr2), valset.Validator(ctx, addr2)) + require.Equal(t, base.Validator(ctx, addr1), valset.Validator(ctx, addr1)) + require.Equal(t, base.Validator(ctx, addr2), valset.Validator(ctx, addr2)) assocs := valset.Associations(ctx, addr1) - assert.Equal(t, 1, len(assocs)) - assert.True(t, bytes.Equal(assoc1, assocs[0])) + require.Equal(t, 1, len(assocs)) + require.True(t, bytes.Equal(assoc1, assocs[0])) - assert.False(t, valset.Associate(ctx, addr1, assoc2)) - assert.False(t, valset.Associate(ctx, addr2, assoc1)) + require.False(t, valset.Associate(ctx, addr1, assoc2)) + require.False(t, valset.Associate(ctx, addr2, assoc1)) valset.Dissociate(ctx, addr1, assoc1) valset.Dissociate(ctx, addr2, assoc2) - assert.Equal(t, base.Validator(ctx, addr1), valset.Validator(ctx, addr1)) - assert.Equal(t, base.Validator(ctx, addr2), valset.Validator(ctx, addr2)) + require.Equal(t, base.Validator(ctx, addr1), valset.Validator(ctx, addr1)) + require.Equal(t, base.Validator(ctx, addr2), valset.Validator(ctx, addr2)) - assert.Nil(t, valset.Validator(ctx, assoc1)) - assert.Nil(t, valset.Validator(ctx, assoc2)) + require.Nil(t, valset.Validator(ctx, assoc1)) + require.Nil(t, valset.Validator(ctx, assoc2)) } diff --git a/examples/democoin/x/cool/app_test.go b/examples/democoin/x/cool/app_test.go index efcc6c1bf2..e93f6d99c5 100644 --- a/examples/democoin/x/cool/app_test.go +++ b/examples/democoin/x/cool/app_test.go @@ -3,7 +3,6 @@ package cool import ( "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" @@ -88,7 +87,7 @@ func TestMsgQuiz(t *testing.T) { // A checkTx context (true) ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) res1 := mapp.AccountMapper.GetAccount(ctxCheck, addr1) - assert.Equal(t, acc1, res1) + require.Equal(t, acc1, res1) // Set the trend, submit a really cool quiz and check for reward mock.SignCheckDeliver(t, mapp.BaseApp, []sdk.Msg{setTrendMsg1}, []int64{0}, []int64{0}, true, priv1) diff --git a/examples/democoin/x/cool/keeper_test.go b/examples/democoin/x/cool/keeper_test.go index 3dfad91f13..ee2e529f26 100644 --- a/examples/democoin/x/cool/keeper_test.go +++ b/examples/democoin/x/cool/keeper_test.go @@ -3,7 +3,7 @@ package cool import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tmlibs/db" @@ -35,16 +35,16 @@ func TestCoolKeeper(t *testing.T) { keeper := NewKeeper(capKey, ck, DefaultCodespace) err := InitGenesis(ctx, keeper, Genesis{"icy"}) - assert.Nil(t, err) + require.Nil(t, err) genesis := WriteGenesis(ctx, keeper) - assert.Nil(t, err) - assert.Equal(t, genesis, Genesis{"icy"}) + require.Nil(t, err) + require.Equal(t, genesis, Genesis{"icy"}) res := keeper.GetTrend(ctx) - assert.Equal(t, res, "icy") + require.Equal(t, res, "icy") keeper.setTrend(ctx, "fiery") res = keeper.GetTrend(ctx) - assert.Equal(t, res, "fiery") + require.Equal(t, res, "fiery") } diff --git a/examples/democoin/x/oracle/oracle_test.go b/examples/democoin/x/oracle/oracle_test.go index 01885e0d5e..228378c34a 100644 --- a/examples/democoin/x/oracle/oracle_test.go +++ b/examples/democoin/x/oracle/oracle_test.go @@ -4,7 +4,6 @@ import ( "encoding/json" "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" @@ -124,50 +123,50 @@ func TestOracle(t *testing.T) { // Nonmock.Validator signed, transaction failed msg := Msg{seqOracle{0, 0}, []byte("randomguy")} res := h(ctx, msg) - assert.False(t, res.IsOK()) - assert.Equal(t, 0, getSequence(ctx, key)) + require.False(t, res.IsOK()) + require.Equal(t, 0, getSequence(ctx, key)) // Less than 2/3 signed, msg not processed msg.Signer = addr1 res = h(ctx, msg) - assert.True(t, res.IsOK()) - assert.Equal(t, 0, getSequence(ctx, key)) + require.True(t, res.IsOK()) + require.Equal(t, 0, getSequence(ctx, key)) // Double signed, transaction failed res = h(ctx, msg) - assert.False(t, res.IsOK()) - assert.Equal(t, 0, getSequence(ctx, key)) + require.False(t, res.IsOK()) + require.Equal(t, 0, getSequence(ctx, key)) // More than 2/3 signed, msg processed msg.Signer = addr2 res = h(ctx, msg) - assert.True(t, res.IsOK()) - assert.Equal(t, 1, getSequence(ctx, key)) + require.True(t, res.IsOK()) + require.Equal(t, 1, getSequence(ctx, key)) // Already processed, transaction failed msg.Signer = addr3 res = h(ctx, msg) - assert.False(t, res.IsOK()) - assert.Equal(t, 1, getSequence(ctx, key)) + require.False(t, res.IsOK()) + require.Equal(t, 1, getSequence(ctx, key)) // Less than 2/3 signed, msg not processed msg = Msg{seqOracle{100, 1}, addr1} res = h(ctx, msg) - assert.True(t, res.IsOK()) - assert.Equal(t, 1, getSequence(ctx, key)) + require.True(t, res.IsOK()) + require.Equal(t, 1, getSequence(ctx, key)) // More than 2/3 signed but payload is invalid msg.Signer = addr2 res = h(ctx, msg) - assert.True(t, res.IsOK()) - assert.NotEqual(t, "", res.Log) - assert.Equal(t, 1, getSequence(ctx, key)) + require.True(t, res.IsOK()) + require.NotEqual(t, "", res.Log) + require.Equal(t, 1, getSequence(ctx, key)) // Already processed, transaction failed msg.Signer = addr3 res = h(ctx, msg) - assert.False(t, res.IsOK()) - assert.Equal(t, 1, getSequence(ctx, key)) + require.False(t, res.IsOK()) + require.Equal(t, 1, getSequence(ctx, key)) // Should handle mock.Validator set change valset.AddValidator(mock.Validator{addr4, sdk.NewRat(12)}) @@ -178,28 +177,28 @@ func TestOracle(t *testing.T) { // Less than 2/3 signed, msg not processed msg = Msg{seqOracle{1, 2}, addr1} res = h(ctx, msg) - assert.True(t, res.IsOK()) - assert.Equal(t, 1, getSequence(ctx, key)) + require.True(t, res.IsOK()) + require.Equal(t, 1, getSequence(ctx, key)) // Less than 2/3 signed, msg not processed msg.Signer = addr2 res = h(ctx, msg) - assert.True(t, res.IsOK()) - assert.Equal(t, 1, getSequence(ctx, key)) + require.True(t, res.IsOK()) + require.Equal(t, 1, getSequence(ctx, key)) // More than 2/3 signed, msg processed msg.Signer = addr4 res = h(ctx, msg) - assert.True(t, res.IsOK()) - assert.Equal(t, 2, getSequence(ctx, key)) + require.True(t, res.IsOK()) + require.Equal(t, 2, getSequence(ctx, key)) // Should handle mock.Validator set change while oracle process is happening msg = Msg{seqOracle{2, 3}, addr4} // Less than 2/3 signed, msg not processed res = h(ctx, msg) - assert.True(t, res.IsOK()) - assert.Equal(t, 2, getSequence(ctx, key)) + require.True(t, res.IsOK()) + require.Equal(t, 2, getSequence(ctx, key)) // Signed mock.Validator is kicked out valset.RemoveValidator(addr4) @@ -210,12 +209,12 @@ func TestOracle(t *testing.T) { // Less than 2/3 signed, msg not processed msg.Signer = addr1 res = h(ctx, msg) - assert.True(t, res.IsOK()) - assert.Equal(t, 2, getSequence(ctx, key)) + require.True(t, res.IsOK()) + require.Equal(t, 2, getSequence(ctx, key)) // More than 2/3 signed, msg processed msg.Signer = addr2 res = h(ctx, msg) - assert.True(t, res.IsOK()) - assert.Equal(t, 3, getSequence(ctx, key)) + require.True(t, res.IsOK()) + require.Equal(t, 3, getSequence(ctx, key)) } diff --git a/examples/democoin/x/pow/app_test.go b/examples/democoin/x/pow/app_test.go index 6dab193886..d223a1f107 100644 --- a/examples/democoin/x/pow/app_test.go +++ b/examples/democoin/x/pow/app_test.go @@ -3,7 +3,6 @@ package pow import ( "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" @@ -68,7 +67,7 @@ func TestMsgMine(t *testing.T) { // A checkTx context (true) ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) res1 := mapp.AccountMapper.GetAccount(ctxCheck, addr1) - assert.Equal(t, acc1, res1) + require.Equal(t, acc1, res1) // Mine and check for reward mineMsg1 := GenerateMsgMine(addr1, 1, 2) diff --git a/examples/democoin/x/pow/handler_test.go b/examples/democoin/x/pow/handler_test.go index 5aaba48bbb..77a22057bc 100644 --- a/examples/democoin/x/pow/handler_test.go +++ b/examples/democoin/x/pow/handler_test.go @@ -3,7 +3,7 @@ package pow import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tmlibs/log" @@ -32,21 +32,21 @@ func TestPowHandler(t *testing.T) { difficulty := uint64(2) err := InitGenesis(ctx, keeper, Genesis{uint64(1), uint64(0)}) - assert.Nil(t, err) + require.Nil(t, err) nonce, proof := mine(addr, count, difficulty) msg := NewMsgMine(addr, difficulty, count, nonce, proof) result := handler(ctx, msg) - assert.Equal(t, result, sdk.Result{}) + require.Equal(t, result, sdk.Result{}) newDiff, err := keeper.GetLastDifficulty(ctx) - assert.Nil(t, err) - assert.Equal(t, newDiff, uint64(2)) + require.Nil(t, err) + require.Equal(t, newDiff, uint64(2)) newCount, err := keeper.GetLastCount(ctx) - assert.Nil(t, err) - assert.Equal(t, newCount, uint64(1)) + require.Nil(t, err) + require.Equal(t, newCount, uint64(1)) // todo assert correct coin change, awaiting https://github.com/cosmos/cosmos-sdk/pull/691 @@ -55,5 +55,5 @@ func TestPowHandler(t *testing.T) { msg = NewMsgMine(addr, difficulty, count, nonce, proof) result = handler(ctx, msg) - assert.NotEqual(t, result, sdk.Result{}) + require.NotEqual(t, result, sdk.Result{}) } diff --git a/examples/democoin/x/pow/keeper_test.go b/examples/democoin/x/pow/keeper_test.go index 53c3e83b4b..31ad2fc121 100644 --- a/examples/democoin/x/pow/keeper_test.go +++ b/examples/democoin/x/pow/keeper_test.go @@ -3,7 +3,7 @@ package pow import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tmlibs/db" @@ -39,19 +39,19 @@ func TestPowKeeperGetSet(t *testing.T) { keeper := NewKeeper(capKey, config, ck, DefaultCodespace) err := InitGenesis(ctx, keeper, Genesis{uint64(1), uint64(0)}) - assert.Nil(t, err) + require.Nil(t, err) genesis := WriteGenesis(ctx, keeper) - assert.Nil(t, err) - assert.Equal(t, genesis, Genesis{uint64(1), uint64(0)}) + require.Nil(t, err) + require.Equal(t, genesis, Genesis{uint64(1), uint64(0)}) res, err := keeper.GetLastDifficulty(ctx) - assert.Nil(t, err) - assert.Equal(t, res, uint64(1)) + require.Nil(t, err) + require.Equal(t, res, uint64(1)) keeper.SetLastDifficulty(ctx, 2) res, err = keeper.GetLastDifficulty(ctx) - assert.Nil(t, err) - assert.Equal(t, res, uint64(2)) + require.Nil(t, err) + require.Equal(t, res, uint64(2)) } diff --git a/examples/democoin/x/pow/types_test.go b/examples/democoin/x/pow/types_test.go index e69e595592..9ed5dc102c 100644 --- a/examples/democoin/x/pow/types_test.go +++ b/examples/democoin/x/pow/types_test.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -13,13 +13,13 @@ func TestNewMsgMine(t *testing.T) { addr := sdk.Address([]byte("sender")) msg := MsgMine{addr, 0, 0, 0, []byte("")} equiv := NewMsgMine(addr, 0, 0, 0, []byte("")) - assert.Equal(t, msg, equiv, "%s != %s", msg, equiv) + require.Equal(t, msg, equiv, "%s != %s", msg, equiv) } func TestMsgMineType(t *testing.T) { addr := sdk.Address([]byte("sender")) msg := MsgMine{addr, 0, 0, 0, []byte("")} - assert.Equal(t, msg.Type(), "pow") + require.Equal(t, msg.Type(), "pow") } func TestMsgMineValidation(t *testing.T) { @@ -33,21 +33,21 @@ func TestMsgMineValidation(t *testing.T) { nonce, proof := mine(addr, count, difficulty) msg := MsgMine{addr, difficulty, count, nonce, proof} err := msg.ValidateBasic() - assert.Nil(t, err, "error with difficulty %d - %+v", difficulty, err) + require.Nil(t, err, "error with difficulty %d - %+v", difficulty, err) msg.Count++ err = msg.ValidateBasic() - assert.NotNil(t, err, "count was wrong, should have thrown error with msg %s", msg) + require.NotNil(t, err, "count was wrong, should have thrown error with msg %s", msg) msg.Count-- msg.Nonce++ err = msg.ValidateBasic() - assert.NotNil(t, err, "nonce was wrong, should have thrown error with msg %s", msg) + require.NotNil(t, err, "nonce was wrong, should have thrown error with msg %s", msg) msg.Nonce-- msg.Sender = otherAddr err = msg.ValidateBasic() - assert.NotNil(t, err, "sender was wrong, should have thrown error with msg %s", msg) + require.NotNil(t, err, "sender was wrong, should have thrown error with msg %s", msg) } } @@ -55,19 +55,19 @@ func TestMsgMineString(t *testing.T) { addr := sdk.Address([]byte("sender")) msg := MsgMine{addr, 0, 0, 0, []byte("abc")} res := msg.String() - assert.Equal(t, res, "MsgMine{Sender: 73656E646572, Difficulty: 0, Count: 0, Nonce: 0, Proof: abc}") + require.Equal(t, res, "MsgMine{Sender: 73656E646572, Difficulty: 0, Count: 0, Nonce: 0, Proof: abc}") } func TestMsgMineGetSignBytes(t *testing.T) { addr := sdk.Address([]byte("sender")) msg := MsgMine{addr, 1, 1, 1, []byte("abc")} res := msg.GetSignBytes() - assert.Equal(t, string(res), `{"sender":"73656E646572","difficulty":1,"count":1,"nonce":1,"proof":"YWJj"}`) + require.Equal(t, string(res), `{"sender":"73656E646572","difficulty":1,"count":1,"nonce":1,"proof":"YWJj"}`) } func TestMsgMineGetSigners(t *testing.T) { addr := sdk.Address([]byte("sender")) msg := MsgMine{addr, 1, 1, 1, []byte("abc")} res := msg.GetSigners() - assert.Equal(t, fmt.Sprintf("%v", res), "[73656E646572]") + require.Equal(t, fmt.Sprintf("%v", res), "[73656E646572]") } diff --git a/examples/democoin/x/simplestake/keeper_test.go b/examples/democoin/x/simplestake/keeper_test.go index 9cb02afd7d..be8e335e2b 100644 --- a/examples/democoin/x/simplestake/keeper_test.go +++ b/examples/democoin/x/simplestake/keeper_test.go @@ -5,7 +5,6 @@ import ( "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" @@ -42,7 +41,7 @@ func TestKeeperGetSet(t *testing.T) { addr := sdk.Address([]byte("some-address")) bi := stakeKeeper.getBondInfo(ctx, addr) - assert.Equal(t, bi, bondInfo{}) + require.Equal(t, bi, bondInfo{}) privKey := crypto.GenPrivKeyEd25519() @@ -54,9 +53,9 @@ func TestKeeperGetSet(t *testing.T) { stakeKeeper.setBondInfo(ctx, addr, bi) savedBi := stakeKeeper.getBondInfo(ctx, addr) - assert.NotNil(t, savedBi) + require.NotNil(t, savedBi) fmt.Printf("Bond Info: %v\n", savedBi) - assert.Equal(t, int64(10), savedBi.Power) + require.Equal(t, int64(10), savedBi.Power) } func TestBonding(t *testing.T) { @@ -74,19 +73,19 @@ func TestBonding(t *testing.T) { pubKey := privKey.PubKey() _, _, err := stakeKeeper.unbondWithoutCoins(ctx, addr) - assert.Equal(t, err, ErrInvalidUnbond(DefaultCodespace)) + require.Equal(t, err, ErrInvalidUnbond(DefaultCodespace)) _, err = stakeKeeper.bondWithoutCoins(ctx, addr, pubKey, sdk.NewCoin("steak", 10)) - assert.Nil(t, err) + require.Nil(t, err) power, err := stakeKeeper.bondWithoutCoins(ctx, addr, pubKey, sdk.NewCoin("steak", 10)) require.Nil(t, err) - assert.Equal(t, int64(20), power) + require.Equal(t, int64(20), power) pk, _, err := stakeKeeper.unbondWithoutCoins(ctx, addr) - assert.Nil(t, err) - assert.Equal(t, pubKey, pk) + require.Nil(t, err) + require.Equal(t, pubKey, pk) _, _, err = stakeKeeper.unbondWithoutCoins(ctx, addr) - assert.Equal(t, err, ErrInvalidUnbond(DefaultCodespace)) + require.Equal(t, err, ErrInvalidUnbond(DefaultCodespace)) } diff --git a/examples/democoin/x/simplestake/msgs_test.go b/examples/democoin/x/simplestake/msgs_test.go index 188a4ec3a8..9baf0dd1a9 100644 --- a/examples/democoin/x/simplestake/msgs_test.go +++ b/examples/democoin/x/simplestake/msgs_test.go @@ -3,7 +3,7 @@ package simplestake import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" @@ -23,9 +23,9 @@ func TestBondMsgValidation(t *testing.T) { for i, tc := range cases { err := tc.msgBond.ValidateBasic() if tc.valid { - assert.Nil(t, err, "%d: %+v", i, err) + require.Nil(t, err, "%d: %+v", i, err) } else { - assert.NotNil(t, err, "%d", i) + require.NotNil(t, err, "%d", i) } } } diff --git a/server/mock/app_test.go b/server/mock/app_test.go index 7c0b70da25..05ec865219 100644 --- a/server/mock/app_test.go +++ b/server/mock/app_test.go @@ -3,7 +3,6 @@ package mock import ( "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" @@ -38,7 +37,7 @@ func TestInitApp(t *testing.T) { } qres := app.Query(query) require.Equal(t, uint32(0), qres.Code, qres.Log) - assert.Equal(t, []byte("bar"), qres.Value) + require.Equal(t, []byte("bar"), qres.Value) } // TextDeliverTx ensures we can write a tx @@ -74,5 +73,5 @@ func TestDeliverTx(t *testing.T) { } qres := app.Query(query) require.Equal(t, uint32(0), qres.Code, qres.Log) - assert.Equal(t, []byte(value), qres.Value) + require.Equal(t, []byte(value), qres.Value) } diff --git a/server/mock/store_test.go b/server/mock/store_test.go index bd01244667..bf6a1007b6 100644 --- a/server/mock/store_test.go +++ b/server/mock/store_test.go @@ -3,7 +3,7 @@ package mock import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" dbm "github.com/tendermint/tmlibs/db" @@ -17,17 +17,17 @@ func TestStore(t *testing.T) { key := sdk.NewKVStoreKey("test") cms.MountStoreWithDB(key, sdk.StoreTypeIAVL, db) err := cms.LoadLatestVersion() - assert.Nil(t, err) + require.Nil(t, err) store := cms.GetKVStore(key) - assert.NotNil(t, store) + require.NotNil(t, store) k := []byte("hello") v := []byte("world") - assert.False(t, store.Has(k)) + require.False(t, store.Has(k)) store.Set(k, v) - assert.True(t, store.Has(k)) - assert.Equal(t, v, store.Get(k)) + require.True(t, store.Has(k)) + require.Equal(t, v, store.Get(k)) store.Delete(k) - assert.False(t, store.Has(k)) + require.False(t, store.Has(k)) } diff --git a/server/util_test.go b/server/util_test.go index 13f8ad5dbc..8f1ab21dbc 100644 --- a/server/util_test.go +++ b/server/util_test.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/cosmos/cosmos-sdk/wire" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -37,5 +36,5 @@ func TestAppendJSON(t *testing.T) { err = cdc.UnmarshalJSON(appended["barOuter"], &resBar) require.NoError(t, err) - assert.Equal(t, bar, resBar, "appended: %v", appended) + require.Equal(t, bar, resBar, "appended: %v", appended) } diff --git a/store/cachekvstore_test.go b/store/cachekvstore_test.go index 0c88ca27d0..f9be76dae3 100644 --- a/store/cachekvstore_test.go +++ b/store/cachekvstore_test.go @@ -3,7 +3,6 @@ package store import ( "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" cmn "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" @@ -103,11 +102,11 @@ func TestCacheKVIteratorBounds(t *testing.T) { var i = 0 for ; itr.Valid(); itr.Next() { k, v := itr.Key(), itr.Value() - assert.Equal(t, keyFmt(i), k) - assert.Equal(t, valFmt(i), v) + require.Equal(t, keyFmt(i), k) + require.Equal(t, valFmt(i), v) i++ } - assert.Equal(t, nItems, i) + require.Equal(t, nItems, i) // iterate over none itr = st.Iterator(bz("money"), nil) @@ -115,29 +114,29 @@ func TestCacheKVIteratorBounds(t *testing.T) { for ; itr.Valid(); itr.Next() { i++ } - assert.Equal(t, 0, i) + require.Equal(t, 0, i) // iterate over lower itr = st.Iterator(keyFmt(0), keyFmt(3)) i = 0 for ; itr.Valid(); itr.Next() { k, v := itr.Key(), itr.Value() - assert.Equal(t, keyFmt(i), k) - assert.Equal(t, valFmt(i), v) + require.Equal(t, keyFmt(i), k) + require.Equal(t, valFmt(i), v) i++ } - assert.Equal(t, 3, i) + require.Equal(t, 3, i) // iterate over upper itr = st.Iterator(keyFmt(2), keyFmt(4)) i = 2 for ; itr.Valid(); itr.Next() { k, v := itr.Key(), itr.Value() - assert.Equal(t, keyFmt(i), k) - assert.Equal(t, valFmt(i), v) + require.Equal(t, keyFmt(i), k) + require.Equal(t, valFmt(i), v) i++ } - assert.Equal(t, 4, i) + require.Equal(t, 4, i) } func TestCacheKVMergeIteratorBasics(t *testing.T) { @@ -367,11 +366,11 @@ func assertIterateDomain(t *testing.T, st KVStore, expectedN int) { var i = 0 for ; itr.Valid(); itr.Next() { k, v := itr.Key(), itr.Value() - assert.Equal(t, keyFmt(i), k) - assert.Equal(t, valFmt(i), v) + require.Equal(t, keyFmt(i), k) + require.Equal(t, valFmt(i), v) i++ } - assert.Equal(t, expectedN, i) + require.Equal(t, expectedN, i) } func assertIterateDomainCheck(t *testing.T, st KVStore, mem dbm.DB, r []keyRange) { @@ -383,25 +382,25 @@ func assertIterateDomainCheck(t *testing.T, st KVStore, mem dbm.DB, r []keyRange i := 0 for ; krc.valid(); krc.next() { - assert.True(t, itr.Valid()) - assert.True(t, itr2.Valid()) + require.True(t, itr.Valid()) + require.True(t, itr2.Valid()) // check the key/val matches the ground truth k, v := itr.Key(), itr.Value() k2, v2 := itr2.Key(), itr2.Value() - assert.Equal(t, k, k2) - assert.Equal(t, v, v2) + require.Equal(t, k, k2) + require.Equal(t, v, v2) // check they match the counter - assert.Equal(t, k, keyFmt(krc.key())) + require.Equal(t, k, keyFmt(krc.key())) itr.Next() itr2.Next() i++ } - assert.False(t, itr.Valid()) - assert.False(t, itr2.Valid()) + require.False(t, itr.Valid()) + require.False(t, itr2.Valid()) } func assertIterateDomainCompare(t *testing.T, st KVStore, mem dbm.DB) { @@ -414,15 +413,15 @@ func assertIterateDomainCompare(t *testing.T, st KVStore, mem dbm.DB) { func checkIterators(t *testing.T, itr, itr2 Iterator) { for ; itr.Valid(); itr.Next() { - assert.True(t, itr2.Valid()) + require.True(t, itr2.Valid()) k, v := itr.Key(), itr.Value() k2, v2 := itr2.Key(), itr2.Value() - assert.Equal(t, k, k2) - assert.Equal(t, v, v2) + require.Equal(t, k, k2) + require.Equal(t, v, v2) itr2.Next() } - assert.False(t, itr.Valid()) - assert.False(t, itr2.Valid()) + require.False(t, itr.Valid()) + require.False(t, itr2.Valid()) } //-------------------------------------------------------- diff --git a/store/iavlstore_test.go b/store/iavlstore_test.go index 25e08aefd9..b23f04e5cd 100644 --- a/store/iavlstore_test.go +++ b/store/iavlstore_test.go @@ -3,7 +3,7 @@ package store import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/tendermint/iavl" abci "github.com/tendermint/tendermint/abci/types" @@ -38,7 +38,7 @@ func newTree(t *testing.T, db dbm.DB) (*iavl.VersionedTree, CommitID) { tree.Set(key, value) } hash, ver, err := tree.SaveVersion() - assert.Nil(t, err) + require.Nil(t, err) return tree, CommitID{ver, hash} } @@ -50,21 +50,21 @@ func TestIAVLStoreGetSetHasDelete(t *testing.T) { key := "hello" exists := iavlStore.Has([]byte(key)) - assert.True(t, exists) + require.True(t, exists) value := iavlStore.Get([]byte(key)) - assert.EqualValues(t, value, treeData[key]) + require.EqualValues(t, value, treeData[key]) value2 := "notgoodbye" iavlStore.Set([]byte(key), []byte(value2)) value = iavlStore.Get([]byte(key)) - assert.EqualValues(t, value, value2) + require.EqualValues(t, value, value2) iavlStore.Delete([]byte(key)) exists = iavlStore.Has([]byte(key)) - assert.False(t, exists) + require.False(t, exists) } func TestIAVLIterator(t *testing.T) { @@ -78,66 +78,66 @@ func TestIAVLIterator(t *testing.T) { for i = 0; iter.Valid(); iter.Next() { expectedKey := expected[i] key, value := iter.Key(), iter.Value() - assert.EqualValues(t, key, expectedKey) - assert.EqualValues(t, value, treeData[expectedKey]) + require.EqualValues(t, key, expectedKey) + require.EqualValues(t, value, treeData[expectedKey]) i++ } - assert.Equal(t, len(expected), i) + require.Equal(t, len(expected), i) iter = iavlStore.Iterator([]byte("golang"), []byte("rocks")) expected = []string{"hello"} for i = 0; iter.Valid(); iter.Next() { expectedKey := expected[i] key, value := iter.Key(), iter.Value() - assert.EqualValues(t, key, expectedKey) - assert.EqualValues(t, value, treeData[expectedKey]) + require.EqualValues(t, key, expectedKey) + require.EqualValues(t, value, treeData[expectedKey]) i++ } - assert.Equal(t, len(expected), i) + require.Equal(t, len(expected), i) iter = iavlStore.Iterator(nil, []byte("golang")) expected = []string{"aloha"} for i = 0; iter.Valid(); iter.Next() { expectedKey := expected[i] key, value := iter.Key(), iter.Value() - assert.EqualValues(t, key, expectedKey) - assert.EqualValues(t, value, treeData[expectedKey]) + require.EqualValues(t, key, expectedKey) + require.EqualValues(t, value, treeData[expectedKey]) i++ } - assert.Equal(t, len(expected), i) + require.Equal(t, len(expected), i) iter = iavlStore.Iterator(nil, []byte("shalom")) expected = []string{"aloha", "hello"} for i = 0; iter.Valid(); iter.Next() { expectedKey := expected[i] key, value := iter.Key(), iter.Value() - assert.EqualValues(t, key, expectedKey) - assert.EqualValues(t, value, treeData[expectedKey]) + require.EqualValues(t, key, expectedKey) + require.EqualValues(t, value, treeData[expectedKey]) i++ } - assert.Equal(t, len(expected), i) + require.Equal(t, len(expected), i) iter = iavlStore.Iterator(nil, nil) expected = []string{"aloha", "hello"} for i = 0; iter.Valid(); iter.Next() { expectedKey := expected[i] key, value := iter.Key(), iter.Value() - assert.EqualValues(t, key, expectedKey) - assert.EqualValues(t, value, treeData[expectedKey]) + require.EqualValues(t, key, expectedKey) + require.EqualValues(t, value, treeData[expectedKey]) i++ } - assert.Equal(t, len(expected), i) + require.Equal(t, len(expected), i) iter = iavlStore.Iterator([]byte("golang"), nil) expected = []string{"hello"} for i = 0; iter.Valid(); iter.Next() { expectedKey := expected[i] key, value := iter.Key(), iter.Value() - assert.EqualValues(t, key, expectedKey) - assert.EqualValues(t, value, treeData[expectedKey]) + require.EqualValues(t, key, expectedKey) + require.EqualValues(t, value, treeData[expectedKey]) i++ } - assert.Equal(t, len(expected), i) + require.Equal(t, len(expected), i) } func TestIAVLSubspaceIterator(t *testing.T) { @@ -162,11 +162,11 @@ func TestIAVLSubspaceIterator(t *testing.T) { for i = 0; iter.Valid(); iter.Next() { expectedKey := expected[i] key, value := iter.Key(), iter.Value() - assert.EqualValues(t, key, expectedKey) - assert.EqualValues(t, value, expectedKey) + require.EqualValues(t, key, expectedKey) + require.EqualValues(t, value, expectedKey) i++ } - assert.Equal(t, len(expected), i) + require.Equal(t, len(expected), i) iter = sdk.KVStorePrefixIterator(iavlStore, []byte{byte(55), byte(255), byte(255)}) expected2 := [][]byte{ @@ -177,11 +177,11 @@ func TestIAVLSubspaceIterator(t *testing.T) { for i = 0; iter.Valid(); iter.Next() { expectedKey := expected2[i] key, value := iter.Key(), iter.Value() - assert.EqualValues(t, key, expectedKey) - assert.EqualValues(t, value, []byte("test4")) + require.EqualValues(t, key, expectedKey) + require.EqualValues(t, value, []byte("test4")) i++ } - assert.Equal(t, len(expected), i) + require.Equal(t, len(expected), i) iter = sdk.KVStorePrefixIterator(iavlStore, []byte{byte(255), byte(255)}) expected2 = [][]byte{ @@ -192,11 +192,11 @@ func TestIAVLSubspaceIterator(t *testing.T) { for i = 0; iter.Valid(); iter.Next() { expectedKey := expected2[i] key, value := iter.Key(), iter.Value() - assert.EqualValues(t, key, expectedKey) - assert.EqualValues(t, value, []byte("test4")) + require.EqualValues(t, key, expectedKey) + require.EqualValues(t, value, []byte("test4")) i++ } - assert.Equal(t, len(expected), i) + require.Equal(t, len(expected), i) } func TestIAVLReverseSubspaceIterator(t *testing.T) { @@ -221,11 +221,11 @@ func TestIAVLReverseSubspaceIterator(t *testing.T) { for i = 0; iter.Valid(); iter.Next() { expectedKey := expected[i] key, value := iter.Key(), iter.Value() - assert.EqualValues(t, key, expectedKey) - assert.EqualValues(t, value, expectedKey) + require.EqualValues(t, key, expectedKey) + require.EqualValues(t, value, expectedKey) i++ } - assert.Equal(t, len(expected), i) + require.Equal(t, len(expected), i) iter = sdk.KVStoreReversePrefixIterator(iavlStore, []byte{byte(55), byte(255), byte(255)}) expected2 := [][]byte{ @@ -236,11 +236,11 @@ func TestIAVLReverseSubspaceIterator(t *testing.T) { for i = 0; iter.Valid(); iter.Next() { expectedKey := expected2[i] key, value := iter.Key(), iter.Value() - assert.EqualValues(t, key, expectedKey) - assert.EqualValues(t, value, []byte("test4")) + require.EqualValues(t, key, expectedKey) + require.EqualValues(t, value, []byte("test4")) i++ } - assert.Equal(t, len(expected), i) + require.Equal(t, len(expected), i) iter = sdk.KVStoreReversePrefixIterator(iavlStore, []byte{byte(255), byte(255)}) expected2 = [][]byte{ @@ -251,11 +251,11 @@ func TestIAVLReverseSubspaceIterator(t *testing.T) { for i = 0; iter.Valid(); iter.Next() { expectedKey := expected2[i] key, value := iter.Key(), iter.Value() - assert.EqualValues(t, key, expectedKey) - assert.EqualValues(t, value, []byte("test4")) + require.EqualValues(t, key, expectedKey) + require.EqualValues(t, value, []byte("test4")) i++ } - assert.Equal(t, len(expected), i) + require.Equal(t, len(expected), i) } func TestIAVLStoreQuery(t *testing.T) { @@ -288,8 +288,8 @@ func TestIAVLStoreQuery(t *testing.T) { // query subspace before anything set qres := iavlStore.Query(querySub) - assert.Equal(t, uint32(sdk.CodeOK), qres.Code) - assert.Equal(t, valExpSubEmpty, qres.Value) + require.Equal(t, uint32(sdk.CodeOK), qres.Code) + require.Equal(t, valExpSubEmpty, qres.Value) // set data iavlStore.Set(k1, v1) @@ -297,25 +297,25 @@ func TestIAVLStoreQuery(t *testing.T) { // set data without commit, doesn't show up qres = iavlStore.Query(query) - assert.Equal(t, uint32(sdk.CodeOK), qres.Code) - assert.Nil(t, qres.Value) + require.Equal(t, uint32(sdk.CodeOK), qres.Code) + require.Nil(t, qres.Value) // commit it, but still don't see on old version cid = iavlStore.Commit() qres = iavlStore.Query(query) - assert.Equal(t, uint32(sdk.CodeOK), qres.Code) - assert.Nil(t, qres.Value) + require.Equal(t, uint32(sdk.CodeOK), qres.Code) + require.Nil(t, qres.Value) // but yes on the new version query.Height = cid.Version qres = iavlStore.Query(query) - assert.Equal(t, uint32(sdk.CodeOK), qres.Code) - assert.Equal(t, v1, qres.Value) + require.Equal(t, uint32(sdk.CodeOK), qres.Code) + require.Equal(t, v1, qres.Value) // and for the subspace qres = iavlStore.Query(querySub) - assert.Equal(t, uint32(sdk.CodeOK), qres.Code) - assert.Equal(t, valExpSub1, qres.Value) + require.Equal(t, uint32(sdk.CodeOK), qres.Code) + require.Equal(t, valExpSub1, qres.Value) // modify iavlStore.Set(k1, v3) @@ -323,26 +323,26 @@ func TestIAVLStoreQuery(t *testing.T) { // query will return old values, as height is fixed qres = iavlStore.Query(query) - assert.Equal(t, uint32(sdk.CodeOK), qres.Code) - assert.Equal(t, v1, qres.Value) + require.Equal(t, uint32(sdk.CodeOK), qres.Code) + require.Equal(t, v1, qres.Value) // update to latest in the query and we are happy query.Height = cid.Version qres = iavlStore.Query(query) - assert.Equal(t, uint32(sdk.CodeOK), qres.Code) - assert.Equal(t, v3, qres.Value) + require.Equal(t, uint32(sdk.CodeOK), qres.Code) + require.Equal(t, v3, qres.Value) query2 := abci.RequestQuery{Path: "/key", Data: k2, Height: cid.Version} qres = iavlStore.Query(query2) - assert.Equal(t, uint32(sdk.CodeOK), qres.Code) - assert.Equal(t, v2, qres.Value) + require.Equal(t, uint32(sdk.CodeOK), qres.Code) + require.Equal(t, v2, qres.Value) // and for the subspace qres = iavlStore.Query(querySub) - assert.Equal(t, uint32(sdk.CodeOK), qres.Code) - assert.Equal(t, valExpSub2, qres.Value) + require.Equal(t, uint32(sdk.CodeOK), qres.Code) + require.Equal(t, valExpSub2, qres.Value) // default (height 0) will show latest -1 query0 := abci.RequestQuery{Path: "/store", Data: k1} qres = iavlStore.Query(query0) - assert.Equal(t, uint32(sdk.CodeOK), qres.Code) - assert.Equal(t, v1, qres.Value) + require.Equal(t, uint32(sdk.CodeOK), qres.Code) + require.Equal(t, v1, qres.Value) } diff --git a/store/prefixstore_test.go b/store/prefixstore_test.go index d41d120553..76fb7f481f 100644 --- a/store/prefixstore_test.go +++ b/store/prefixstore_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/tendermint/iavl" dbm "github.com/tendermint/tmlibs/db" @@ -96,14 +97,14 @@ func TestPrefixStoreIterate(t *testing.T) { pIter := sdk.KVStorePrefixIterator(prefixStore, nil) for bIter.Valid() && pIter.Valid() { - assert.Equal(t, bIter.Key(), append(prefix, pIter.Key()...)) - assert.Equal(t, bIter.Value(), pIter.Value()) + require.Equal(t, bIter.Key(), append(prefix, pIter.Key()...)) + require.Equal(t, bIter.Value(), pIter.Value()) bIter.Next() pIter.Next() } - assert.Equal(t, bIter.Valid(), pIter.Valid()) + require.Equal(t, bIter.Valid(), pIter.Valid()) bIter.Close() pIter.Close() } diff --git a/store/rootmultistore_test.go b/store/rootmultistore_test.go index 89d40f761c..197726f4ac 100644 --- a/store/rootmultistore_test.go +++ b/store/rootmultistore_test.go @@ -3,7 +3,7 @@ package store import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/tmlibs/merkle" @@ -20,7 +20,7 @@ func TestMultistoreCommitLoad(t *testing.T) { } store := newMultiStoreWithMounts(db) err := store.LoadLatestVersion() - assert.Nil(t, err) + require.Nil(t, err) // New store has empty last commit. commitID := CommitID{} @@ -28,11 +28,11 @@ func TestMultistoreCommitLoad(t *testing.T) { // Make sure we can get stores by name. s1 := store.getStoreByName("store1") - assert.NotNil(t, s1) + require.NotNil(t, s1) s3 := store.getStoreByName("store3") - assert.NotNil(t, s3) + require.NotNil(t, s3) s77 := store.getStoreByName("store77") - assert.Nil(t, s77) + require.Nil(t, s77) // Make a few commits and check them. nCommits := int64(3) @@ -45,7 +45,7 @@ func TestMultistoreCommitLoad(t *testing.T) { // Load the latest multistore again and check version. store = newMultiStoreWithMounts(db) err = store.LoadLatestVersion() - assert.Nil(t, err) + require.Nil(t, err) commitID = getExpectedCommitID(store, nCommits) checkStore(t, store, commitID, commitID) @@ -58,7 +58,7 @@ func TestMultistoreCommitLoad(t *testing.T) { ver := nCommits - 1 store = newMultiStoreWithMounts(db) err = store.LoadVersion(ver) - assert.Nil(t, err) + require.Nil(t, err) commitID = getExpectedCommitID(store, ver) checkStore(t, store, commitID, commitID) @@ -71,29 +71,29 @@ func TestMultistoreCommitLoad(t *testing.T) { // LatestVersion store = newMultiStoreWithMounts(db) err = store.LoadLatestVersion() - assert.Nil(t, err) + require.Nil(t, err) commitID = getExpectedCommitID(store, ver+1) checkStore(t, store, commitID, commitID) } func TestParsePath(t *testing.T) { _, _, err := parsePath("foo") - assert.Error(t, err) + require.Error(t, err) store, subpath, err := parsePath("/foo") - assert.NoError(t, err) - assert.Equal(t, store, "foo") - assert.Equal(t, subpath, "") + require.NoError(t, err) + require.Equal(t, store, "foo") + require.Equal(t, subpath, "") store, subpath, err = parsePath("/fizz/bang/baz") - assert.NoError(t, err) - assert.Equal(t, store, "fizz") - assert.Equal(t, subpath, "/bang/baz") + require.NoError(t, err) + require.Equal(t, store, "fizz") + require.Equal(t, subpath, "/bang/baz") substore, subsubpath, err := parsePath(subpath) - assert.NoError(t, err) - assert.Equal(t, substore, "bang") - assert.Equal(t, subsubpath, "/baz") + require.NoError(t, err) + require.Equal(t, substore, "bang") + require.Equal(t, subsubpath, "/baz") } @@ -101,7 +101,7 @@ func TestMultiStoreQuery(t *testing.T) { db := dbm.NewMemDB() multi := newMultiStoreWithMounts(db) err := multi.LoadLatestVersion() - assert.Nil(t, err) + require.Nil(t, err) k, v := []byte("wind"), []byte("blows") k2, v2 := []byte("water"), []byte("flows") @@ -111,7 +111,7 @@ func TestMultiStoreQuery(t *testing.T) { // Make sure we can get by name. garbage := multi.getStoreByName("bad-name") - assert.Nil(t, garbage) + require.Nil(t, garbage) // Set and commit data in one store. store1 := multi.getStoreByName("store1").(KVStore) @@ -128,35 +128,35 @@ func TestMultiStoreQuery(t *testing.T) { // Test bad path. query := abci.RequestQuery{Path: "/key", Data: k, Height: ver} qres := multi.Query(query) - assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeUnknownRequest), sdk.ABCICodeType(qres.Code)) + require.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeUnknownRequest), sdk.ABCICodeType(qres.Code)) query.Path = "h897fy32890rf63296r92" qres = multi.Query(query) - assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeUnknownRequest), sdk.ABCICodeType(qres.Code)) + require.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeUnknownRequest), sdk.ABCICodeType(qres.Code)) // Test invalid store name. query.Path = "/garbage/key" qres = multi.Query(query) - assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeUnknownRequest), sdk.ABCICodeType(qres.Code)) + require.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeUnknownRequest), sdk.ABCICodeType(qres.Code)) // Test valid query with data. query.Path = "/store1/key" qres = multi.Query(query) - assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeOK), sdk.ABCICodeType(qres.Code)) - assert.Equal(t, v, qres.Value) + require.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeOK), sdk.ABCICodeType(qres.Code)) + require.Equal(t, v, qres.Value) // Test valid but empty query. query.Path = "/store2/key" query.Prove = true qres = multi.Query(query) - assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeOK), sdk.ABCICodeType(qres.Code)) - assert.Nil(t, qres.Value) + require.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeOK), sdk.ABCICodeType(qres.Code)) + require.Nil(t, qres.Value) // Test store2 data. query.Data = k2 qres = multi.Query(query) - assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeOK), sdk.ABCICodeType(qres.Code)) - assert.Equal(t, v2, qres.Value) + require.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeOK), sdk.ABCICodeType(qres.Code)) + require.Equal(t, v2, qres.Value) } //----------------------------------------------------------------------- @@ -174,8 +174,8 @@ func newMultiStoreWithMounts(db dbm.DB) *rootMultiStore { } func checkStore(t *testing.T, store *rootMultiStore, expect, got CommitID) { - assert.Equal(t, expect, got) - assert.Equal(t, expect, store.LastCommitID()) + require.Equal(t, expect, got) + require.Equal(t, expect, store.LastCommitID()) } diff --git a/types/coin_test.go b/types/coin_test.go index 5f5c82087b..c7ccc5746c 100644 --- a/types/coin_test.go +++ b/types/coin_test.go @@ -4,11 +4,10 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIsPositiveCoin(t *testing.T) { - assert := assert.New(t) - cases := []struct { inputOne Coin expected bool @@ -20,13 +19,11 @@ func TestIsPositiveCoin(t *testing.T) { for _, tc := range cases { res := tc.inputOne.IsPositive() - assert.Equal(tc.expected, res) + require.Equal(t, tc.expected, res) } } func TestIsNotNegativeCoin(t *testing.T) { - assert := assert.New(t) - cases := []struct { inputOne Coin expected bool @@ -38,13 +35,11 @@ func TestIsNotNegativeCoin(t *testing.T) { for _, tc := range cases { res := tc.inputOne.IsNotNegative() - assert.Equal(tc.expected, res) + require.Equal(t, tc.expected, res) } } func TestSameDenomAsCoin(t *testing.T) { - assert := assert.New(t) - cases := []struct { inputOne Coin inputTwo Coin @@ -59,13 +54,11 @@ func TestSameDenomAsCoin(t *testing.T) { for _, tc := range cases { res := tc.inputOne.SameDenomAs(tc.inputTwo) - assert.Equal(tc.expected, res) + require.Equal(t, tc.expected, res) } } func TestIsGTECoin(t *testing.T) { - assert := assert.New(t) - cases := []struct { inputOne Coin inputTwo Coin @@ -79,13 +72,11 @@ func TestIsGTECoin(t *testing.T) { for _, tc := range cases { res := tc.inputOne.IsGTE(tc.inputTwo) - assert.Equal(tc.expected, res) + require.Equal(t, tc.expected, res) } } func TestIsEqualCoin(t *testing.T) { - assert := assert.New(t) - cases := []struct { inputOne Coin inputTwo Coin @@ -100,13 +91,11 @@ func TestIsEqualCoin(t *testing.T) { for _, tc := range cases { res := tc.inputOne.IsEqual(tc.inputTwo) - assert.Equal(tc.expected, res) + require.Equal(t, tc.expected, res) } } func TestPlusCoin(t *testing.T) { - assert := assert.New(t) - cases := []struct { inputOne Coin inputTwo Coin @@ -119,7 +108,7 @@ func TestPlusCoin(t *testing.T) { for _, tc := range cases { res := tc.inputOne.Plus(tc.inputTwo) - assert.Equal(tc.expected, res) + require.Equal(t, tc.expected, res) } tc := struct { @@ -128,12 +117,10 @@ func TestPlusCoin(t *testing.T) { expected int64 }{NewCoin("asdf", -1), NewCoin("asdf", 1), 0} res := tc.inputOne.Plus(tc.inputTwo) - assert.Equal(tc.expected, res.Amount.Int64()) + require.Equal(t, tc.expected, res.Amount.Int64()) } func TestMinusCoin(t *testing.T) { - assert := assert.New(t) - cases := []struct { inputOne Coin inputTwo Coin @@ -147,7 +134,7 @@ func TestMinusCoin(t *testing.T) { for _, tc := range cases { res := tc.inputOne.Minus(tc.inputTwo) - assert.Equal(tc.expected, res) + require.Equal(t, tc.expected, res) } tc := struct { @@ -156,7 +143,7 @@ func TestMinusCoin(t *testing.T) { expected int64 }{NewCoin("A", 1), NewCoin("A", 1), 0} res := tc.inputOne.Minus(tc.inputTwo) - assert.Equal(tc.expected, res.Amount.Int64()) + require.Equal(t, tc.expected, res.Amount.Int64()) } @@ -208,8 +195,6 @@ func TestCoins(t *testing.T) { } func TestPlusCoins(t *testing.T) { - assert := assert.New(t) - one := NewInt(1) zero := NewInt(0) negone := NewInt(-1) @@ -229,8 +214,8 @@ func TestPlusCoins(t *testing.T) { for _, tc := range cases { res := tc.inputOne.Plus(tc.inputTwo) - assert.True(res.IsValid()) - assert.Equal(tc.expected, res) + assert.True(t, res.IsValid()) + require.Equal(t, tc.expected, res) } } @@ -260,9 +245,9 @@ func TestParse(t *testing.T) { for _, tc := range cases { res, err := ParseCoins(tc.input) if !tc.valid { - assert.NotNil(t, err, "%s: %#v", tc.input, res) + require.NotNil(t, err, "%s: %#v", tc.input, res) } else if assert.Nil(t, err, "%s: %+v", tc.input, err) { - assert.Equal(t, tc.expected, res) + require.Equal(t, tc.expected, res) } } @@ -312,9 +297,9 @@ func TestSortCoins(t *testing.T) { } for _, tc := range cases { - assert.Equal(t, tc.before, tc.coins.IsValid()) + require.Equal(t, tc.before, tc.coins.IsValid()) tc.coins.Sort() - assert.Equal(t, tc.after, tc.coins.IsValid()) + require.Equal(t, tc.after, tc.coins.IsValid()) } } diff --git a/types/context_test.go b/types/context_test.go index e5b31a9a74..cad2076640 100644 --- a/types/context_test.go +++ b/types/context_test.go @@ -3,7 +3,6 @@ package types_test import ( "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" dbm "github.com/tendermint/tmlibs/db" @@ -72,21 +71,21 @@ func TestCacheContext(t *testing.T) { ctx := defaultContext(key) store := ctx.KVStore(key) store.Set(k1, v1) - assert.Equal(t, v1, store.Get(k1)) - assert.Nil(t, store.Get(k2)) + require.Equal(t, v1, store.Get(k1)) + require.Nil(t, store.Get(k2)) cctx, write := ctx.CacheContext() cstore := cctx.KVStore(key) - assert.Equal(t, v1, cstore.Get(k1)) - assert.Nil(t, cstore.Get(k2)) + require.Equal(t, v1, cstore.Get(k1)) + require.Nil(t, cstore.Get(k2)) cstore.Set(k2, v2) - assert.Equal(t, v2, cstore.Get(k2)) - assert.Nil(t, store.Get(k2)) + require.Equal(t, v2, cstore.Get(k2)) + require.Nil(t, store.Get(k2)) write() - assert.Equal(t, v2, store.Get(k2)) + require.Equal(t, v2, store.Get(k2)) } func TestLogContext(t *testing.T) { diff --git a/types/errors_test.go b/types/errors_test.go index 798eafefcb..959f059d00 100644 --- a/types/errors_test.go +++ b/types/errors_test.go @@ -4,7 +4,7 @@ import ( "strings" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var codeTypes = []CodeType{ @@ -32,11 +32,11 @@ var errFns = []errFn{ } func TestCodeType(t *testing.T) { - assert.True(t, ABCICodeOK.IsOK()) + require.True(t, ABCICodeOK.IsOK()) for _, c := range codeTypes { msg := CodeToDefaultMsg(c) - assert.False(t, strings.HasPrefix(msg, "Unknown code")) + require.False(t, strings.HasPrefix(msg, "Unknown code")) } } @@ -44,7 +44,7 @@ func TestErrFn(t *testing.T) { for i, errFn := range errFns { err := errFn("") codeType := codeTypes[i] - assert.Equal(t, err.Code(), codeType) - assert.Equal(t, err.Result().Code, ToABCICode(CodespaceRoot, codeType)) + require.Equal(t, err.Code(), codeType) + require.Equal(t, err.Result().Code, ToABCICode(CodespaceRoot, codeType)) } } diff --git a/types/int_test.go b/types/int_test.go index 310325133b..e81bd6d7ed 100644 --- a/types/int_test.go +++ b/types/int_test.go @@ -5,107 +5,107 @@ import ( "math/rand" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestFromInt64(t *testing.T) { for n := 0; n < 20; n++ { r := rand.Int63() - assert.Equal(t, r, NewInt(r).Int64()) + require.Equal(t, r, NewInt(r).Int64()) } } func TestInt(t *testing.T) { // Max Int = 2^255-1 = 5.789e+76 // Min Int = -(2^255-1) = -5.789e+76 - assert.NotPanics(t, func() { NewIntWithDecimal(1, 76) }) + require.NotPanics(t, func() { NewIntWithDecimal(1, 76) }) i1 := NewIntWithDecimal(1, 76) - assert.NotPanics(t, func() { NewIntWithDecimal(2, 76) }) + require.NotPanics(t, func() { NewIntWithDecimal(2, 76) }) i2 := NewIntWithDecimal(2, 76) - assert.NotPanics(t, func() { NewIntWithDecimal(3, 76) }) + require.NotPanics(t, func() { NewIntWithDecimal(3, 76) }) i3 := NewIntWithDecimal(3, 76) - assert.Panics(t, func() { NewIntWithDecimal(6, 76) }) - assert.Panics(t, func() { NewIntWithDecimal(9, 80) }) + require.Panics(t, func() { NewIntWithDecimal(6, 76) }) + require.Panics(t, func() { NewIntWithDecimal(9, 80) }) // Overflow check - assert.NotPanics(t, func() { i1.Add(i1) }) - assert.NotPanics(t, func() { i2.Add(i2) }) - assert.Panics(t, func() { i3.Add(i3) }) + require.NotPanics(t, func() { i1.Add(i1) }) + require.NotPanics(t, func() { i2.Add(i2) }) + require.Panics(t, func() { i3.Add(i3) }) - assert.NotPanics(t, func() { i1.Sub(i1.Neg()) }) - assert.NotPanics(t, func() { i2.Sub(i2.Neg()) }) - assert.Panics(t, func() { i3.Sub(i3.Neg()) }) + require.NotPanics(t, func() { i1.Sub(i1.Neg()) }) + require.NotPanics(t, func() { i2.Sub(i2.Neg()) }) + require.Panics(t, func() { i3.Sub(i3.Neg()) }) - assert.Panics(t, func() { i1.Mul(i1) }) - assert.Panics(t, func() { i2.Mul(i2) }) - assert.Panics(t, func() { i3.Mul(i3) }) + require.Panics(t, func() { i1.Mul(i1) }) + require.Panics(t, func() { i2.Mul(i2) }) + require.Panics(t, func() { i3.Mul(i3) }) - assert.Panics(t, func() { i1.Neg().Mul(i1.Neg()) }) - assert.Panics(t, func() { i2.Neg().Mul(i2.Neg()) }) - assert.Panics(t, func() { i3.Neg().Mul(i3.Neg()) }) + require.Panics(t, func() { i1.Neg().Mul(i1.Neg()) }) + require.Panics(t, func() { i2.Neg().Mul(i2.Neg()) }) + require.Panics(t, func() { i3.Neg().Mul(i3.Neg()) }) // Underflow check i3n := i3.Neg() - assert.NotPanics(t, func() { i3n.Sub(i1) }) - assert.NotPanics(t, func() { i3n.Sub(i2) }) - assert.Panics(t, func() { i3n.Sub(i3) }) + require.NotPanics(t, func() { i3n.Sub(i1) }) + require.NotPanics(t, func() { i3n.Sub(i2) }) + require.Panics(t, func() { i3n.Sub(i3) }) - assert.NotPanics(t, func() { i3n.Add(i1.Neg()) }) - assert.NotPanics(t, func() { i3n.Add(i2.Neg()) }) - assert.Panics(t, func() { i3n.Add(i3.Neg()) }) + require.NotPanics(t, func() { i3n.Add(i1.Neg()) }) + require.NotPanics(t, func() { i3n.Add(i2.Neg()) }) + require.Panics(t, func() { i3n.Add(i3.Neg()) }) - assert.Panics(t, func() { i1.Mul(i1.Neg()) }) - assert.Panics(t, func() { i2.Mul(i2.Neg()) }) - assert.Panics(t, func() { i3.Mul(i3.Neg()) }) + require.Panics(t, func() { i1.Mul(i1.Neg()) }) + require.Panics(t, func() { i2.Mul(i2.Neg()) }) + require.Panics(t, func() { i3.Mul(i3.Neg()) }) // Bound check intmax := NewIntFromBigInt(new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(1))) intmin := intmax.Neg() - assert.NotPanics(t, func() { intmax.Add(ZeroInt()) }) - assert.NotPanics(t, func() { intmin.Sub(ZeroInt()) }) - assert.Panics(t, func() { intmax.Add(OneInt()) }) - assert.Panics(t, func() { intmin.Sub(OneInt()) }) + require.NotPanics(t, func() { intmax.Add(ZeroInt()) }) + require.NotPanics(t, func() { intmin.Sub(ZeroInt()) }) + require.Panics(t, func() { intmax.Add(OneInt()) }) + require.Panics(t, func() { intmin.Sub(OneInt()) }) // Division-by-zero check - assert.Panics(t, func() { i1.Div(NewInt(0)) }) + require.Panics(t, func() { i1.Div(NewInt(0)) }) } func TestUint(t *testing.T) { // Max Uint = 1.15e+77 // Min Uint = 0 - assert.NotPanics(t, func() { NewUintWithDecimal(5, 76) }) + require.NotPanics(t, func() { NewUintWithDecimal(5, 76) }) i1 := NewUintWithDecimal(5, 76) - assert.NotPanics(t, func() { NewUintWithDecimal(10, 76) }) + require.NotPanics(t, func() { NewUintWithDecimal(10, 76) }) i2 := NewUintWithDecimal(10, 76) - assert.NotPanics(t, func() { NewUintWithDecimal(11, 76) }) + require.NotPanics(t, func() { NewUintWithDecimal(11, 76) }) i3 := NewUintWithDecimal(11, 76) - assert.Panics(t, func() { NewUintWithDecimal(12, 76) }) - assert.Panics(t, func() { NewUintWithDecimal(1, 80) }) + require.Panics(t, func() { NewUintWithDecimal(12, 76) }) + require.Panics(t, func() { NewUintWithDecimal(1, 80) }) // Overflow check - assert.NotPanics(t, func() { i1.Add(i1) }) - assert.Panics(t, func() { i2.Add(i2) }) - assert.Panics(t, func() { i3.Add(i3) }) + require.NotPanics(t, func() { i1.Add(i1) }) + require.Panics(t, func() { i2.Add(i2) }) + require.Panics(t, func() { i3.Add(i3) }) - assert.Panics(t, func() { i1.Mul(i1) }) - assert.Panics(t, func() { i2.Mul(i2) }) - assert.Panics(t, func() { i3.Mul(i3) }) + require.Panics(t, func() { i1.Mul(i1) }) + require.Panics(t, func() { i2.Mul(i2) }) + require.Panics(t, func() { i3.Mul(i3) }) // Underflow check - assert.NotPanics(t, func() { i2.Sub(i1) }) - assert.NotPanics(t, func() { i2.Sub(i2) }) - assert.Panics(t, func() { i2.Sub(i3) }) + require.NotPanics(t, func() { i2.Sub(i1) }) + require.NotPanics(t, func() { i2.Sub(i2) }) + require.Panics(t, func() { i2.Sub(i3) }) // Bound check uintmax := NewUintFromBigInt(new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(1))) uintmin := NewUint(0) - assert.NotPanics(t, func() { uintmax.Add(ZeroUint()) }) - assert.NotPanics(t, func() { uintmin.Sub(ZeroUint()) }) - assert.Panics(t, func() { uintmax.Add(OneUint()) }) - assert.Panics(t, func() { uintmin.Sub(OneUint()) }) + require.NotPanics(t, func() { uintmax.Add(ZeroUint()) }) + require.NotPanics(t, func() { uintmin.Sub(ZeroUint()) }) + require.Panics(t, func() { uintmax.Add(OneUint()) }) + require.Panics(t, func() { uintmin.Sub(OneUint()) }) // Division-by-zero check - assert.Panics(t, func() { i1.Div(uintmin) }) + require.Panics(t, func() { i1.Div(uintmin) }) } diff --git a/types/lib/linear_test.go b/types/lib/linear_test.go index 8ee3276b5a..8b5a63fd41 100644 --- a/types/lib/linear_test.go +++ b/types/lib/linear_test.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/tmlibs/log" @@ -41,30 +41,30 @@ func TestList(t *testing.T) { var res S lm.Push(val) - assert.Equal(t, uint64(1), lm.Len()) + require.Equal(t, uint64(1), lm.Len()) lm.Get(uint64(0), &res) - assert.Equal(t, val, res) + require.Equal(t, val, res) val = S{2, false} lm.Set(uint64(0), val) lm.Get(uint64(0), &res) - assert.Equal(t, val, res) + require.Equal(t, val, res) val = S{100, false} lm.Push(val) - assert.Equal(t, uint64(2), lm.Len()) + require.Equal(t, uint64(2), lm.Len()) lm.Get(uint64(1), &res) - assert.Equal(t, val, res) + require.Equal(t, val, res) lm.Delete(uint64(1)) - assert.Equal(t, uint64(2), lm.Len()) + require.Equal(t, uint64(2), lm.Len()) lm.Iterate(&res, func(index uint64) (brk bool) { var temp S lm.Get(index, &temp) - assert.Equal(t, temp, res) + require.Equal(t, temp, res) - assert.True(t, index != 1) + require.True(t, index != 1) return }) @@ -74,7 +74,7 @@ func TestList(t *testing.T) { }) lm.Get(uint64(0), &res) - assert.Equal(t, S{3, true}, res) + require.Equal(t, S{3, true}, res) } func TestQueue(t *testing.T) { @@ -89,13 +89,13 @@ func TestQueue(t *testing.T) { qm.Push(val) qm.Peek(&res) - assert.Equal(t, val, res) + require.Equal(t, val, res) qm.Pop() empty := qm.IsEmpty() - assert.True(t, empty) - assert.NotNil(t, qm.Peek(&res)) + require.True(t, empty) + require.NotNil(t, qm.Peek(&res)) qm.Push(S{1, true}) qm.Push(S{2, true}) @@ -107,10 +107,10 @@ func TestQueue(t *testing.T) { return }) - assert.False(t, qm.IsEmpty()) + require.False(t, qm.IsEmpty()) qm.Pop() - assert.True(t, qm.IsEmpty()) + require.True(t, qm.IsEmpty()) } func TestOptions(t *testing.T) { @@ -136,22 +136,22 @@ func TestOptions(t *testing.T) { // Checking keys.LengthKey err := cdc.UnmarshalBinary(store.Get(keys.LengthKey), &len) - assert.Nil(t, err) - assert.Equal(t, len, linear.Len()) + require.Nil(t, err) + require.Equal(t, len, linear.Len()) // Checking keys.ElemKey for i := 0; i < 10; i++ { linear.Get(uint64(i), &expected) bz := store.Get(append(keys.ElemKey, []byte(fmt.Sprintf("%020d", i))...)) err = cdc.UnmarshalBinary(bz, &actual) - assert.Nil(t, err) - assert.Equal(t, expected, actual) + require.Nil(t, err) + require.Equal(t, expected, actual) } linear.Pop() err = cdc.UnmarshalBinary(store.Get(keys.TopKey), &top) - assert.Nil(t, err) - assert.Equal(t, top, linear.getTop()) + require.Nil(t, err) + require.Equal(t, top, linear.getTop()) } diff --git a/types/rational_test.go b/types/rational_test.go index a137ca498e..db875c83e8 100644 --- a/types/rational_test.go +++ b/types/rational_test.go @@ -5,19 +5,18 @@ import ( "testing" wire "github.com/cosmos/cosmos-sdk/wire" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNew(t *testing.T) { - assert.Equal(t, NewRat(1), NewRat(1, 1)) - assert.Equal(t, NewRat(100), NewRat(100, 1)) - assert.Equal(t, NewRat(-1), NewRat(-1, 1)) - assert.Equal(t, NewRat(-100), NewRat(-100, 1)) - assert.Equal(t, NewRat(0), NewRat(0, 1)) + require.Equal(t, NewRat(1), NewRat(1, 1)) + require.Equal(t, NewRat(100), NewRat(100, 1)) + require.Equal(t, NewRat(-1), NewRat(-1, 1)) + require.Equal(t, NewRat(-100), NewRat(-100, 1)) + require.Equal(t, NewRat(0), NewRat(0, 1)) // do not allow for more than 2 variables - assert.Panics(t, func() { NewRat(1, 1, 1) }) + require.Panics(t, func() { NewRat(1, 1, 1) }) } func TestNewFromDecimal(t *testing.T) { @@ -51,7 +50,7 @@ func TestNewFromDecimal(t *testing.T) { for _, tc := range tests { res, err := NewRatFromDecimal(tc.decimalStr, 4) if tc.expErr { - assert.NotNil(t, err, tc.decimalStr) + require.NotNil(t, err, tc.decimalStr) } else { require.Nil(t, err, tc.decimalStr) require.True(t, res.Equal(tc.exp), tc.decimalStr) @@ -60,10 +59,10 @@ func TestNewFromDecimal(t *testing.T) { // negative tc res, err = NewRatFromDecimal("-"+tc.decimalStr, 4) if tc.expErr { - assert.NotNil(t, err, tc.decimalStr) + require.NotNil(t, err, tc.decimalStr) } else { - assert.Nil(t, err, tc.decimalStr) - assert.True(t, res.Equal(tc.exp.Mul(NewRat(-1))), tc.decimalStr) + require.Nil(t, err, tc.decimalStr) + require.True(t, res.Equal(tc.exp.Mul(NewRat(-1))), tc.decimalStr) } } } @@ -100,9 +99,9 @@ func TestEqualities(t *testing.T) { } for _, tc := range tests { - assert.Equal(t, tc.gt, tc.r1.GT(tc.r2)) - assert.Equal(t, tc.lt, tc.r1.LT(tc.r2)) - assert.Equal(t, tc.eq, tc.r1.Equal(tc.r2)) + require.Equal(t, tc.gt, tc.r1.GT(tc.r2)) + require.Equal(t, tc.lt, tc.r1.LT(tc.r2)) + require.Equal(t, tc.eq, tc.r1.Equal(tc.r2)) } } @@ -136,14 +135,14 @@ func TestArithmetic(t *testing.T) { } for _, tc := range tests { - assert.True(t, tc.resMul.Equal(tc.r1.Mul(tc.r2)), "r1 %v, r2 %v", tc.r1.Rat, tc.r2.Rat) - assert.True(t, tc.resAdd.Equal(tc.r1.Add(tc.r2)), "r1 %v, r2 %v", tc.r1.Rat, tc.r2.Rat) - assert.True(t, tc.resSub.Equal(tc.r1.Sub(tc.r2)), "r1 %v, r2 %v", tc.r1.Rat, tc.r2.Rat) + require.True(t, tc.resMul.Equal(tc.r1.Mul(tc.r2)), "r1 %v, r2 %v", tc.r1.Rat, tc.r2.Rat) + require.True(t, tc.resAdd.Equal(tc.r1.Add(tc.r2)), "r1 %v, r2 %v", tc.r1.Rat, tc.r2.Rat) + require.True(t, tc.resSub.Equal(tc.r1.Sub(tc.r2)), "r1 %v, r2 %v", tc.r1.Rat, tc.r2.Rat) if tc.r2.Num().IsZero() { // panic for divide by zero - assert.Panics(t, func() { tc.r1.Quo(tc.r2) }) + require.Panics(t, func() { tc.r1.Quo(tc.r2) }) } else { - assert.True(t, tc.resDiv.Equal(tc.r1.Quo(tc.r2)), "r1 %v, r2 %v", tc.r1.Rat, tc.r2.Rat) + require.True(t, tc.resDiv.Equal(tc.r1.Quo(tc.r2)), "r1 %v, r2 %v", tc.r1.Rat, tc.r2.Rat) } } } @@ -169,8 +168,8 @@ func TestEvaluate(t *testing.T) { } for _, tc := range tests { - assert.Equal(t, tc.res, tc.r1.Evaluate(), "%v", tc.r1) - assert.Equal(t, tc.res*-1, tc.r1.Mul(NewRat(-1)).Evaluate(), "%v", tc.r1.Mul(NewRat(-1))) + require.Equal(t, tc.res, tc.r1.Evaluate(), "%v", tc.r1) + require.Equal(t, tc.res*-1, tc.r1.Mul(NewRat(-1)).Evaluate(), "%v", tc.r1.Mul(NewRat(-1))) } } @@ -193,9 +192,9 @@ func TestRound(t *testing.T) { } for _, tc := range tests { - assert.Equal(t, tc.res, tc.r.Round(tc.precFactor), "%v", tc.r) + require.Equal(t, tc.res, tc.r.Round(tc.precFactor), "%v", tc.r) negR1, negRes := tc.r.Mul(NewRat(-1)), tc.res.Mul(NewRat(-1)) - assert.Equal(t, negRes, negR1.Round(tc.precFactor), "%v", negR1) + require.Equal(t, negRes, negR1.Round(tc.precFactor), "%v", negR1) } } @@ -212,7 +211,7 @@ func TestToLeftPadded(t *testing.T) { {NewRat(1000, 3), 12, "000000000333"}, } for _, tc := range tests { - assert.Equal(t, tc.res, tc.rat.ToLeftPadded(tc.digits)) + require.Equal(t, tc.res, tc.rat.ToLeftPadded(tc.digits)) } } @@ -221,13 +220,13 @@ var cdc = wire.NewCodec() //var jsonCdc JSONCodec // TODO wire.Codec func TestZeroSerializationJSON(t *testing.T) { r := NewRat(0, 1) err := cdc.UnmarshalJSON([]byte(`"0/1"`), &r) - assert.Nil(t, err) + require.Nil(t, err) err = cdc.UnmarshalJSON([]byte(`"0/0"`), &r) - assert.NotNil(t, err) + require.NotNil(t, err) err = cdc.UnmarshalJSON([]byte(`"1/0"`), &r) - assert.NotNil(t, err) + require.NotNil(t, err) err = cdc.UnmarshalJSON([]byte(`"{}"`), &r) - assert.NotNil(t, err) + require.NotNil(t, err) } func TestSerializationText(t *testing.T) { @@ -239,7 +238,7 @@ func TestSerializationText(t *testing.T) { var r2 = Rat{new(big.Rat)} err = r2.UnmarshalText(bz) require.NoError(t, err) - assert.True(t, r.Equal(r2), "original: %v, unmarshalled: %v", r, r2) + require.True(t, r.Equal(r2), "original: %v, unmarshalled: %v", r, r2) } func TestSerializationGoWireJSON(t *testing.T) { @@ -250,7 +249,7 @@ func TestSerializationGoWireJSON(t *testing.T) { var r2 Rat err = cdc.UnmarshalJSON(bz, &r2) require.NoError(t, err) - assert.True(t, r.Equal(r2), "original: %v, unmarshalled: %v", r, r2) + require.True(t, r.Equal(r2), "original: %v, unmarshalled: %v", r, r2) } func TestSerializationGoWireBinary(t *testing.T) { @@ -261,7 +260,7 @@ func TestSerializationGoWireBinary(t *testing.T) { var r2 Rat err = cdc.UnmarshalBinary(bz, &r2) require.NoError(t, err) - assert.True(t, r.Equal(r2), "original: %v, unmarshalled: %v", r, r2) + require.True(t, r.Equal(r2), "original: %v, unmarshalled: %v", r, r2) } type testEmbedStruct struct { @@ -279,9 +278,9 @@ func TestEmbeddedStructSerializationGoWire(t *testing.T) { err = cdc.UnmarshalJSON(bz, &obj2) require.Nil(t, err) - assert.Equal(t, obj.Field1, obj2.Field1) - assert.Equal(t, obj.Field2, obj2.Field2) - assert.True(t, obj.Field3.Equal(obj2.Field3), "original: %v, unmarshalled: %v", obj, obj2) + require.Equal(t, obj.Field1, obj2.Field1) + require.Equal(t, obj.Field2, obj2.Field2) + require.True(t, obj.Field3.Equal(obj2.Field3), "original: %v, unmarshalled: %v", obj, obj2) } func TestRatsEqual(t *testing.T) { @@ -299,8 +298,8 @@ func TestRatsEqual(t *testing.T) { } for _, tc := range tests { - assert.Equal(t, tc.eq, RatsEqual(tc.r1s, tc.r2s)) - assert.Equal(t, tc.eq, RatsEqual(tc.r2s, tc.r1s)) + require.Equal(t, tc.eq, RatsEqual(tc.r1s, tc.r2s)) + require.Equal(t, tc.eq, RatsEqual(tc.r2s, tc.r1s)) } } @@ -310,7 +309,7 @@ func TestStringOverflow(t *testing.T) { rat1 := NewRat(5164315003622678713, 4389711697696177267) rat2 := NewRat(-3179849666053572961, 8459429845579852627) rat3 := rat1.Add(rat2) - assert.Equal(t, + require.Equal(t, "29728537197630860939575850336935951464/37134458148982045574552091851127630409", rat3.String(), ) diff --git a/types/store_test.go b/types/store_test.go index 43dd1f5d3f..f376f3be1e 100644 --- a/types/store_test.go +++ b/types/store_test.go @@ -3,12 +3,10 @@ package types import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPrefixEndBytes(t *testing.T) { - assert := assert.New(t) - var testCases = []struct { prefix []byte expected []byte @@ -24,6 +22,6 @@ func TestPrefixEndBytes(t *testing.T) { for _, test := range testCases { end := PrefixEndBytes(test.prefix) - assert.Equal(test.expected, end) + require.Equal(t, test.expected, end) } } diff --git a/x/auth/account_test.go b/x/auth/account_test.go index 55cef7cda5..bc7a195097 100644 --- a/x/auth/account_test.go +++ b/x/auth/account_test.go @@ -3,7 +3,7 @@ package auth import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" @@ -24,31 +24,31 @@ func TestBaseAddressPubKey(t *testing.T) { acc := NewBaseAccountWithAddress(addr1) // check the address (set) and pubkey (not set) - assert.EqualValues(t, addr1, acc.GetAddress()) - assert.EqualValues(t, nil, acc.GetPubKey()) + require.EqualValues(t, addr1, acc.GetAddress()) + require.EqualValues(t, nil, acc.GetPubKey()) // can't override address err := acc.SetAddress(addr2) - assert.NotNil(t, err) - assert.EqualValues(t, addr1, acc.GetAddress()) + require.NotNil(t, err) + require.EqualValues(t, addr1, acc.GetAddress()) // set the pubkey err = acc.SetPubKey(pub1) - assert.Nil(t, err) - assert.Equal(t, pub1, acc.GetPubKey()) + require.Nil(t, err) + require.Equal(t, pub1, acc.GetPubKey()) // can override pubkey err = acc.SetPubKey(pub2) - assert.Nil(t, err) - assert.Equal(t, pub2, acc.GetPubKey()) + require.Nil(t, err) + require.Equal(t, pub2, acc.GetPubKey()) //------------------------------------ // can set address on empty account acc2 := BaseAccount{} err = acc2.SetAddress(addr2) - assert.Nil(t, err) - assert.EqualValues(t, addr2, acc2.GetAddress()) + require.Nil(t, err) + require.EqualValues(t, addr2, acc2.GetAddress()) } func TestBaseAccountCoins(t *testing.T) { @@ -58,8 +58,8 @@ func TestBaseAccountCoins(t *testing.T) { someCoins := sdk.Coins{sdk.NewCoin("atom", 123), sdk.NewCoin("eth", 246)} err := acc.SetCoins(someCoins) - assert.Nil(t, err) - assert.Equal(t, someCoins, acc.GetCoins()) + require.Nil(t, err) + require.Equal(t, someCoins, acc.GetCoins()) } func TestBaseAccountSequence(t *testing.T) { @@ -69,8 +69,8 @@ func TestBaseAccountSequence(t *testing.T) { seq := int64(7) err := acc.SetSequence(seq) - assert.Nil(t, err) - assert.Equal(t, seq, acc.GetSequence()) + require.Nil(t, err) + require.Equal(t, seq, acc.GetSequence()) } func TestBaseAccountMarshal(t *testing.T) { @@ -82,27 +82,27 @@ func TestBaseAccountMarshal(t *testing.T) { // set everything on the account err := acc.SetPubKey(pub) - assert.Nil(t, err) + require.Nil(t, err) err = acc.SetSequence(seq) - assert.Nil(t, err) + require.Nil(t, err) err = acc.SetCoins(someCoins) - assert.Nil(t, err) + require.Nil(t, err) // need a codec for marshaling codec := wire.NewCodec() wire.RegisterCrypto(codec) b, err := codec.MarshalBinary(acc) - assert.Nil(t, err) + require.Nil(t, err) acc2 := BaseAccount{} err = codec.UnmarshalBinary(b, &acc2) - assert.Nil(t, err) - assert.Equal(t, acc, acc2) + require.Nil(t, err) + require.Equal(t, acc, acc2) // error on bad bytes acc2 = BaseAccount{} err = codec.UnmarshalBinary(b[:len(b)/2], &acc2) - assert.NotNil(t, err) + require.NotNil(t, err) } diff --git a/x/auth/ante_test.go b/x/auth/ante_test.go index 2ddb96872e..1808afc99c 100644 --- a/x/auth/ante_test.go +++ b/x/auth/ante_test.go @@ -4,7 +4,6 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" @@ -41,9 +40,9 @@ func privAndAddr() (crypto.PrivKey, sdk.Address) { // run the tx through the anteHandler and ensure its valid func checkValidTx(t *testing.T, anteHandler sdk.AnteHandler, ctx sdk.Context, tx sdk.Tx) { _, result, abort := anteHandler(ctx, tx) - assert.False(t, abort) - assert.Equal(t, sdk.ABCICodeOK, result.Code) - assert.True(t, result.IsOK()) + require.False(t, abort) + require.Equal(t, sdk.ABCICodeOK, result.Code) + require.True(t, result.IsOK()) } // run the tx through the anteHandler and ensure it fails with the given code @@ -52,7 +51,7 @@ func checkInvalidTx(t *testing.T, anteHandler sdk.AnteHandler, ctx sdk.Context, if r := recover(); r != nil { switch r.(type) { case sdk.ErrorOutOfGas: - assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, code), sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeOutOfGas), + require.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, code), sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeOutOfGas), fmt.Sprintf("Expected ErrorOutOfGas, got %v", r)) default: panic(r) @@ -60,8 +59,8 @@ func checkInvalidTx(t *testing.T, anteHandler sdk.AnteHandler, ctx sdk.Context, } }() _, result, abort := anteHandler(ctx, tx) - assert.True(t, abort) - assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, code), result.Code, + require.True(t, abort) + require.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, code), result.Code, fmt.Sprintf("Expected %v, got %v", sdk.ToABCICode(sdk.CodespaceRoot, code), result)) } @@ -138,7 +137,7 @@ func TestAnteHandlerSigErrors(t *testing.T) { // tx.GetSigners returns addresses in correct order: addr1, addr2, addr3 expectedSigners := []sdk.Address{addr1, addr2, addr3} stdTx := tx.(StdTx) - assert.Equal(t, expectedSigners, stdTx.GetSigners()) + require.Equal(t, expectedSigners, stdTx.GetSigners()) // Check no signatures fails checkInvalidTx(t, anteHandler, ctx, tx, sdk.CodeUnauthorized) @@ -330,13 +329,13 @@ func TestAnteHandlerFees(t *testing.T) { mapper.SetAccount(ctx, acc1) checkInvalidTx(t, anteHandler, ctx, tx, sdk.CodeInsufficientFunds) - assert.True(t, feeCollector.GetCollectedFees(ctx).IsEqual(emptyCoins)) + require.True(t, feeCollector.GetCollectedFees(ctx).IsEqual(emptyCoins)) acc1.SetCoins(sdk.Coins{sdk.NewCoin("atom", 150)}) mapper.SetAccount(ctx, acc1) checkValidTx(t, anteHandler, ctx, tx) - assert.True(t, feeCollector.GetCollectedFees(ctx).IsEqual(sdk.Coins{sdk.NewCoin("atom", 150)})) + require.True(t, feeCollector.GetCollectedFees(ctx).IsEqual(sdk.Coins{sdk.NewCoin("atom", 150)})) } // Test logic around memo gas consumption. @@ -559,12 +558,12 @@ func TestAnteHandlerSetPubKey(t *testing.T) { checkInvalidTx(t, anteHandler, ctx, tx, sdk.CodeInvalidPubKey) acc2 = mapper.GetAccount(ctx, addr2) - assert.Nil(t, acc2.GetPubKey()) + require.Nil(t, acc2.GetPubKey()) // test invalid signature and public key tx = newTestTx(ctx, msgs, privs, []int64{1}, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, sdk.CodeInvalidPubKey) acc2 = mapper.GetAccount(ctx, addr2) - assert.Nil(t, acc2.GetPubKey()) + require.Nil(t, acc2.GetPubKey()) } diff --git a/x/auth/context_test.go b/x/auth/context_test.go index 53ff7b1db6..5f432be357 100644 --- a/x/auth/context_test.go +++ b/x/auth/context_test.go @@ -3,7 +3,7 @@ package auth import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tmlibs/log" @@ -24,17 +24,17 @@ func TestContextWithSigners(t *testing.T) { // new ctx has no signers signers := GetSigners(ctx) - assert.Equal(t, 0, len(signers)) + require.Equal(t, 0, len(signers)) ctx2 := WithSigners(ctx, []Account{&acc1, &acc2}) // original context is unchanged signers = GetSigners(ctx) - assert.Equal(t, 0, len(signers)) + require.Equal(t, 0, len(signers)) // new context has signers signers = GetSigners(ctx2) - assert.Equal(t, 2, len(signers)) - assert.Equal(t, acc1, *(signers[0].(*BaseAccount))) - assert.Equal(t, acc2, *(signers[1].(*BaseAccount))) + require.Equal(t, 2, len(signers)) + require.Equal(t, acc1, *(signers[0].(*BaseAccount))) + require.Equal(t, acc2, *(signers[1].(*BaseAccount))) } diff --git a/x/auth/feekeeper_test.go b/x/auth/feekeeper_test.go index a6ce8e3e5a..e935bb4c49 100644 --- a/x/auth/feekeeper_test.go +++ b/x/auth/feekeeper_test.go @@ -3,7 +3,7 @@ package auth import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tmlibs/log" @@ -28,13 +28,13 @@ func TestFeeCollectionKeeperGetSet(t *testing.T) { // no coins initially currFees := fck.GetCollectedFees(ctx) - assert.True(t, currFees.IsEqual(emptyCoins)) + require.True(t, currFees.IsEqual(emptyCoins)) // set feeCollection to oneCoin fck.setCollectedFees(ctx, oneCoin) // check that it is equal to oneCoin - assert.True(t, fck.GetCollectedFees(ctx).IsEqual(oneCoin)) + require.True(t, fck.GetCollectedFees(ctx).IsEqual(oneCoin)) } func TestFeeCollectionKeeperAdd(t *testing.T) { @@ -46,15 +46,15 @@ func TestFeeCollectionKeeperAdd(t *testing.T) { fck := NewFeeCollectionKeeper(cdc, capKey2) // no coins initially - assert.True(t, fck.GetCollectedFees(ctx).IsEqual(emptyCoins)) + require.True(t, fck.GetCollectedFees(ctx).IsEqual(emptyCoins)) // add oneCoin and check that pool is now oneCoin fck.addCollectedFees(ctx, oneCoin) - assert.True(t, fck.GetCollectedFees(ctx).IsEqual(oneCoin)) + require.True(t, fck.GetCollectedFees(ctx).IsEqual(oneCoin)) // add oneCoin again and check that pool is now twoCoins fck.addCollectedFees(ctx, oneCoin) - assert.True(t, fck.GetCollectedFees(ctx).IsEqual(twoCoins)) + require.True(t, fck.GetCollectedFees(ctx).IsEqual(twoCoins)) } func TestFeeCollectionKeeperClear(t *testing.T) { @@ -67,9 +67,9 @@ func TestFeeCollectionKeeperClear(t *testing.T) { // set coins initially fck.setCollectedFees(ctx, twoCoins) - assert.True(t, fck.GetCollectedFees(ctx).IsEqual(twoCoins)) + require.True(t, fck.GetCollectedFees(ctx).IsEqual(twoCoins)) // clear fees and see that pool is now empty fck.ClearCollectedFees(ctx) - assert.True(t, fck.GetCollectedFees(ctx).IsEqual(emptyCoins)) + require.True(t, fck.GetCollectedFees(ctx).IsEqual(emptyCoins)) } diff --git a/x/auth/mapper_test.go b/x/auth/mapper_test.go index a5f96d5e90..4b270f0225 100644 --- a/x/auth/mapper_test.go +++ b/x/auth/mapper_test.go @@ -3,7 +3,7 @@ package auth import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tmlibs/db" @@ -38,17 +38,17 @@ func TestAccountMapperGetSet(t *testing.T) { // no account before its created acc := mapper.GetAccount(ctx, addr) - assert.Nil(t, acc) + require.Nil(t, acc) // create account and check default values acc = mapper.NewAccountWithAddress(ctx, addr) - assert.NotNil(t, acc) - assert.Equal(t, addr, acc.GetAddress()) - assert.EqualValues(t, nil, acc.GetPubKey()) - assert.EqualValues(t, 0, acc.GetSequence()) + require.NotNil(t, acc) + require.Equal(t, addr, acc.GetAddress()) + require.EqualValues(t, nil, acc.GetPubKey()) + require.EqualValues(t, 0, acc.GetSequence()) // NewAccount doesn't call Set, so it's still nil - assert.Nil(t, mapper.GetAccount(ctx, addr)) + require.Nil(t, mapper.GetAccount(ctx, addr)) // set some values on the account and save it newSequence := int64(20) @@ -57,6 +57,6 @@ func TestAccountMapperGetSet(t *testing.T) { // check the new values acc = mapper.GetAccount(ctx, addr) - assert.NotNil(t, acc) - assert.Equal(t, newSequence, acc.GetSequence()) + require.NotNil(t, acc) + require.Equal(t, newSequence, acc.GetSequence()) } diff --git a/x/auth/mock/auth_app_test.go b/x/auth/mock/auth_app_test.go index 0a7a03534d..3f340bbf90 100644 --- a/x/auth/mock/auth_app_test.go +++ b/x/auth/mock/auth_app_test.go @@ -3,7 +3,6 @@ package mock import ( "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" @@ -75,7 +74,7 @@ func TestMsgPrivKeys(t *testing.T) { // A checkTx context (true) ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) res1 := mapp.AccountMapper.GetAccount(ctxCheck, addr1) - assert.Equal(t, acc1, res1.(*auth.BaseAccount)) + require.Equal(t, acc1, res1.(*auth.BaseAccount)) // Run a CheckDeliver SignCheckDeliver(t, mapp.BaseApp, []sdk.Msg{testMsg1}, []int64{0}, []int64{0}, true, priv1) @@ -84,10 +83,10 @@ func TestMsgPrivKeys(t *testing.T) { mapp.BeginBlock(abci.RequestBeginBlock{}) tx := GenTx([]sdk.Msg{testMsg1}, []int64{0}, []int64{1}, priv2) res := mapp.Deliver(tx) - assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeUnauthorized), res.Code, res.Log) + require.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeUnauthorized), res.Code, res.Log) // resigning the tx with the correct priv key should still work res = SignCheckDeliver(t, mapp.BaseApp, []sdk.Msg{testMsg1}, []int64{0}, []int64{1}, true, priv1) - assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeOK), res.Code, res.Log) + require.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeOK), res.Code, res.Log) } diff --git a/x/auth/mock/simulate_block.go b/x/auth/mock/simulate_block.go index a047fbf4b6..f85fdf1803 100644 --- a/x/auth/mock/simulate_block.go +++ b/x/auth/mock/simulate_block.go @@ -6,7 +6,6 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" @@ -29,7 +28,7 @@ func SetGenesis(app *App, accs []auth.Account) { func CheckBalance(t *testing.T, app *App, addr sdk.Address, exp sdk.Coins) { ctxCheck := app.BaseApp.NewContext(true, abci.Header{}) res := app.AccountMapper.GetAccount(ctxCheck, addr) - assert.Equal(t, exp, res.GetCoins()) + require.Equal(t, exp, res.GetCoins()) } // generate a signed transaction diff --git a/x/auth/stdtx_test.go b/x/auth/stdtx_test.go index 43712e5a5e..533596431a 100644 --- a/x/auth/stdtx_test.go +++ b/x/auth/stdtx_test.go @@ -3,7 +3,7 @@ package auth import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" @@ -24,9 +24,9 @@ func TestStdTx(t *testing.T) { sigs := []StdSignature{} tx := NewStdTx(msgs, fee, sigs, "") - assert.Equal(t, msgs, tx.GetMsgs()) - assert.Equal(t, sigs, tx.GetSignatures()) + require.Equal(t, msgs, tx.GetMsgs()) + require.Equal(t, sigs, tx.GetSignatures()) feePayer := FeePayer(tx) - assert.Equal(t, addr, feePayer) + require.Equal(t, addr, feePayer) } diff --git a/x/bank/app_test.go b/x/bank/app_test.go index 2d6efc3ca1..72ea312a9a 100644 --- a/x/bank/app_test.go +++ b/x/bank/app_test.go @@ -3,7 +3,6 @@ package bank import ( "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" @@ -112,7 +111,7 @@ func TestMsgSendWithAccounts(t *testing.T) { ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) res1 := mapp.AccountMapper.GetAccount(ctxCheck, addr1) require.NotNil(t, res1) - assert.Equal(t, acc, res1.(*auth.BaseAccount)) + require.Equal(t, acc, res1.(*auth.BaseAccount)) // Run a CheckDeliver mock.SignCheckDeliver(t, mapp.BaseApp, []sdk.Msg{sendMsg1}, []int64{0}, []int64{0}, true, priv1) @@ -130,7 +129,7 @@ func TestMsgSendWithAccounts(t *testing.T) { tx.Signatures[0].Sequence = 1 res := mapp.Deliver(tx) - assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeUnauthorized), res.Code, res.Log) + require.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, sdk.CodeUnauthorized), res.Code, res.Log) // resigning the tx with the bumped sequence should work mock.SignCheckDeliver(t, mapp.BaseApp, []sdk.Msg{sendMsg1, sendMsg2}, []int64{0}, []int64{1}, true, priv1) diff --git a/x/bank/keeper_test.go b/x/bank/keeper_test.go index 2eae4e815c..b35298be9d 100644 --- a/x/bank/keeper_test.go +++ b/x/bank/keeper_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tmlibs/db" @@ -42,57 +43,57 @@ func TestKeeper(t *testing.T) { // Test GetCoins/SetCoins accountMapper.SetAccount(ctx, acc) - assert.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{})) + require.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{})) coinKeeper.SetCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 10)}) - assert.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 10)})) + require.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 10)})) // Test HasCoins - assert.True(t, coinKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 10)})) - assert.True(t, coinKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 5)})) - assert.False(t, coinKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 15)})) - assert.False(t, coinKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("barcoin", 5)})) + require.True(t, coinKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 10)})) + require.True(t, coinKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 5)})) + require.False(t, coinKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 15)})) + require.False(t, coinKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("barcoin", 5)})) // Test AddCoins coinKeeper.AddCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 15)}) - assert.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 25)})) + require.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 25)})) coinKeeper.AddCoins(ctx, addr, sdk.Coins{sdk.NewCoin("barcoin", 15)}) - assert.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 15), sdk.NewCoin("foocoin", 25)})) + require.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 15), sdk.NewCoin("foocoin", 25)})) // Test SubtractCoins coinKeeper.SubtractCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 10)}) coinKeeper.SubtractCoins(ctx, addr, sdk.Coins{sdk.NewCoin("barcoin", 5)}) - assert.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 10), sdk.NewCoin("foocoin", 15)})) + require.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 10), sdk.NewCoin("foocoin", 15)})) coinKeeper.SubtractCoins(ctx, addr, sdk.Coins{sdk.NewCoin("barcoin", 11)}) - assert.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 10), sdk.NewCoin("foocoin", 15)})) + require.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 10), sdk.NewCoin("foocoin", 15)})) coinKeeper.SubtractCoins(ctx, addr, sdk.Coins{sdk.NewCoin("barcoin", 10)}) - assert.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 15)})) - assert.False(t, coinKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("barcoin", 1)})) + require.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 15)})) + require.False(t, coinKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("barcoin", 1)})) // Test SendCoins coinKeeper.SendCoins(ctx, addr, addr2, sdk.Coins{sdk.NewCoin("foocoin", 5)}) - assert.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 10)})) - assert.True(t, coinKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 5)})) + require.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 10)})) + require.True(t, coinKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 5)})) _, err2 := coinKeeper.SendCoins(ctx, addr, addr2, sdk.Coins{sdk.NewCoin("foocoin", 50)}) assert.Implements(t, (*sdk.Error)(nil), err2) - assert.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 10)})) - assert.True(t, coinKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 5)})) + require.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 10)})) + require.True(t, coinKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 5)})) coinKeeper.AddCoins(ctx, addr, sdk.Coins{sdk.NewCoin("barcoin", 30)}) coinKeeper.SendCoins(ctx, addr, addr2, sdk.Coins{sdk.NewCoin("barcoin", 10), sdk.NewCoin("foocoin", 5)}) - assert.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 20), sdk.NewCoin("foocoin", 5)})) - assert.True(t, coinKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 10), sdk.NewCoin("foocoin", 10)})) + require.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 20), sdk.NewCoin("foocoin", 5)})) + require.True(t, coinKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 10), sdk.NewCoin("foocoin", 10)})) // Test InputOutputCoins input1 := NewInput(addr2, sdk.Coins{sdk.NewCoin("foocoin", 2)}) output1 := NewOutput(addr, sdk.Coins{sdk.NewCoin("foocoin", 2)}) coinKeeper.InputOutputCoins(ctx, []Input{input1}, []Output{output1}) - assert.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 20), sdk.NewCoin("foocoin", 7)})) - assert.True(t, coinKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 10), sdk.NewCoin("foocoin", 8)})) + require.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 20), sdk.NewCoin("foocoin", 7)})) + require.True(t, coinKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 10), sdk.NewCoin("foocoin", 8)})) inputs := []Input{ NewInput(addr, sdk.Coins{sdk.NewCoin("foocoin", 3)}), @@ -104,9 +105,9 @@ func TestKeeper(t *testing.T) { NewOutput(addr3, sdk.Coins{sdk.NewCoin("barcoin", 2), sdk.NewCoin("foocoin", 5)}), } coinKeeper.InputOutputCoins(ctx, inputs, outputs) - assert.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 21), sdk.NewCoin("foocoin", 4)})) - assert.True(t, coinKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 7), sdk.NewCoin("foocoin", 6)})) - assert.True(t, coinKeeper.GetCoins(ctx, addr3).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 2), sdk.NewCoin("foocoin", 5)})) + require.True(t, coinKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 21), sdk.NewCoin("foocoin", 4)})) + require.True(t, coinKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 7), sdk.NewCoin("foocoin", 6)})) + require.True(t, coinKeeper.GetCoins(ctx, addr3).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 2), sdk.NewCoin("foocoin", 5)})) } @@ -128,40 +129,40 @@ func TestSendKeeper(t *testing.T) { // Test GetCoins/SetCoins accountMapper.SetAccount(ctx, acc) - assert.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{})) + require.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{})) coinKeeper.SetCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 10)}) - assert.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 10)})) + require.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 10)})) // Test HasCoins - assert.True(t, sendKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 10)})) - assert.True(t, sendKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 5)})) - assert.False(t, sendKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 15)})) - assert.False(t, sendKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("barcoin", 5)})) + require.True(t, sendKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 10)})) + require.True(t, sendKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 5)})) + require.False(t, sendKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 15)})) + require.False(t, sendKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("barcoin", 5)})) coinKeeper.SetCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 15)}) // Test SendCoins sendKeeper.SendCoins(ctx, addr, addr2, sdk.Coins{sdk.NewCoin("foocoin", 5)}) - assert.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 10)})) - assert.True(t, sendKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 5)})) + require.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 10)})) + require.True(t, sendKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 5)})) _, err2 := sendKeeper.SendCoins(ctx, addr, addr2, sdk.Coins{sdk.NewCoin("foocoin", 50)}) assert.Implements(t, (*sdk.Error)(nil), err2) - assert.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 10)})) - assert.True(t, sendKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 5)})) + require.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 10)})) + require.True(t, sendKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 5)})) coinKeeper.AddCoins(ctx, addr, sdk.Coins{sdk.NewCoin("barcoin", 30)}) sendKeeper.SendCoins(ctx, addr, addr2, sdk.Coins{sdk.NewCoin("barcoin", 10), sdk.NewCoin("foocoin", 5)}) - assert.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 20), sdk.NewCoin("foocoin", 5)})) - assert.True(t, sendKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 10), sdk.NewCoin("foocoin", 10)})) + require.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 20), sdk.NewCoin("foocoin", 5)})) + require.True(t, sendKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 10), sdk.NewCoin("foocoin", 10)})) // Test InputOutputCoins input1 := NewInput(addr2, sdk.Coins{sdk.NewCoin("foocoin", 2)}) output1 := NewOutput(addr, sdk.Coins{sdk.NewCoin("foocoin", 2)}) sendKeeper.InputOutputCoins(ctx, []Input{input1}, []Output{output1}) - assert.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 20), sdk.NewCoin("foocoin", 7)})) - assert.True(t, sendKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 10), sdk.NewCoin("foocoin", 8)})) + require.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 20), sdk.NewCoin("foocoin", 7)})) + require.True(t, sendKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 10), sdk.NewCoin("foocoin", 8)})) inputs := []Input{ NewInput(addr, sdk.Coins{sdk.NewCoin("foocoin", 3)}), @@ -173,9 +174,9 @@ func TestSendKeeper(t *testing.T) { NewOutput(addr3, sdk.Coins{sdk.NewCoin("barcoin", 2), sdk.NewCoin("foocoin", 5)}), } sendKeeper.InputOutputCoins(ctx, inputs, outputs) - assert.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 21), sdk.NewCoin("foocoin", 4)})) - assert.True(t, sendKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 7), sdk.NewCoin("foocoin", 6)})) - assert.True(t, sendKeeper.GetCoins(ctx, addr3).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 2), sdk.NewCoin("foocoin", 5)})) + require.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 21), sdk.NewCoin("foocoin", 4)})) + require.True(t, sendKeeper.GetCoins(ctx, addr2).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 7), sdk.NewCoin("foocoin", 6)})) + require.True(t, sendKeeper.GetCoins(ctx, addr3).IsEqual(sdk.Coins{sdk.NewCoin("barcoin", 2), sdk.NewCoin("foocoin", 5)})) } @@ -195,14 +196,14 @@ func TestViewKeeper(t *testing.T) { // Test GetCoins/SetCoins accountMapper.SetAccount(ctx, acc) - assert.True(t, viewKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{})) + require.True(t, viewKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{})) coinKeeper.SetCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 10)}) - assert.True(t, viewKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 10)})) + require.True(t, viewKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{sdk.NewCoin("foocoin", 10)})) // Test HasCoins - assert.True(t, viewKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 10)})) - assert.True(t, viewKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 5)})) - assert.False(t, viewKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 15)})) - assert.False(t, viewKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("barcoin", 5)})) + require.True(t, viewKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 10)})) + require.True(t, viewKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 5)})) + require.False(t, viewKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("foocoin", 15)})) + require.False(t, viewKeeper.HasCoins(ctx, addr, sdk.Coins{sdk.NewCoin("barcoin", 5)})) } diff --git a/x/bank/msgs_test.go b/x/bank/msgs_test.go index 350a51d7aa..3754858ec7 100644 --- a/x/bank/msgs_test.go +++ b/x/bank/msgs_test.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -22,7 +22,7 @@ func TestMsgSendType(t *testing.T) { } // TODO some failures for bad result - assert.Equal(t, msg.Type(), "bank") + require.Equal(t, msg.Type(), "bank") } func TestInputValidation(t *testing.T) { @@ -60,9 +60,9 @@ func TestInputValidation(t *testing.T) { for i, tc := range cases { err := tc.txIn.ValidateBasic() if tc.valid { - assert.Nil(t, err, "%d: %+v", i, err) + require.Nil(t, err, "%d: %+v", i, err) } else { - assert.NotNil(t, err, "%d", i) + require.NotNil(t, err, "%d", i) } } } @@ -102,9 +102,9 @@ func TestOutputValidation(t *testing.T) { for i, tc := range cases { err := tc.txOut.ValidateBasic() if tc.valid { - assert.Nil(t, err, "%d: %+v", i, err) + require.Nil(t, err, "%d: %+v", i, err) } else { - assert.NotNil(t, err, "%d", i) + require.NotNil(t, err, "%d", i) } } } @@ -170,9 +170,9 @@ func TestMsgSendValidation(t *testing.T) { for i, tc := range cases { err := tc.tx.ValidateBasic() if tc.valid { - assert.Nil(t, err, "%d: %+v", i, err) + require.Nil(t, err, "%d: %+v", i, err) } else { - assert.NotNil(t, err, "%d", i) + require.NotNil(t, err, "%d", i) } } } @@ -188,7 +188,7 @@ func TestMsgSendGetSignBytes(t *testing.T) { res := msg.GetSignBytes() expected := `{"inputs":[{"address":"cosmosaccaddr1d9h8qat5e4ehc5","coins":[{"denom":"atom","amount":"10"}]}],"outputs":[{"address":"cosmosaccaddr1da6hgur4wse3jx32","coins":[{"denom":"atom","amount":"10"}]}]}` - assert.Equal(t, expected, string(res)) + require.Equal(t, expected, string(res)) } func TestMsgSendGetSigners(t *testing.T) { @@ -201,7 +201,7 @@ func TestMsgSendGetSigners(t *testing.T) { } res := msg.GetSigners() // TODO: fix this ! - assert.Equal(t, fmt.Sprintf("%v", res), "[696E70757431 696E70757432 696E70757433]") + require.Equal(t, fmt.Sprintf("%v", res), "[696E70757431 696E70757432 696E70757433]") } /* @@ -220,7 +220,7 @@ func TestMsgSendSigners(t *testing.T) { } tx := NewMsgSend(inputs, nil) - assert.Equal(t, signers, tx.Signers()) + require.Equal(t, signers, tx.Signers()) } */ @@ -241,7 +241,7 @@ func TestMsgIssueType(t *testing.T) { } // TODO some failures for bad result - assert.Equal(t, msg.Type(), "bank") + require.Equal(t, msg.Type(), "bank") } func TestMsgIssueValidation(t *testing.T) { @@ -258,7 +258,7 @@ func TestMsgIssueGetSignBytes(t *testing.T) { res := msg.GetSignBytes() expected := `{"banker":"cosmosaccaddr1d9h8qat5e4ehc5","outputs":[{"address":"cosmosaccaddr1d3hkzm3dveex7mfdvfsku6cwsauqd","coins":[{"denom":"atom","amount":"10"}]}]}` - assert.Equal(t, expected, string(res)) + require.Equal(t, expected, string(res)) } func TestMsgIssueGetSigners(t *testing.T) { @@ -266,5 +266,5 @@ func TestMsgIssueGetSigners(t *testing.T) { Banker: sdk.Address([]byte("onlyone")), } res := msg.GetSigners() - assert.Equal(t, fmt.Sprintf("%v", res), "[6F6E6C796F6E65]") + require.Equal(t, fmt.Sprintf("%v", res), "[6F6E6C796F6E65]") } diff --git a/x/fee_distribution/keeper_test.go b/x/fee_distribution/keeper_test.go index 4ad8180e17..0d732f8a19 100644 --- a/x/fee_distribution/keeper_test.go +++ b/x/fee_distribution/keeper_test.go @@ -15,11 +15,11 @@ package stake //// test that an empty gotValidator set doesn't have any gotValidators //gotValidators := keeper.GetValidators(ctx) -//assert.Equal(t, 5, len(gotValidators)) +//require.Equal(t, 5, len(gotValidators)) //totPow := keeper.GetTotalPrecommitVotingPower(ctx) //exp := sdk.NewRat(11111) -//assert.True(t, exp.Equal(totPow), "exp %v, got %v", exp, totPow) +//require.True(t, exp.Equal(totPow), "exp %v, got %v", exp, totPow) //// set absent gotValidators to be the 1st and 3rd record sorted by pubKey address //ctx = ctx.WithAbsentValidators([]int32{1, 3}) @@ -27,5 +27,5 @@ package stake //// XXX verify that this order should infact exclude these two records //exp = sdk.NewRat(11100) -//assert.True(t, exp.Equal(totPow), "exp %v, got %v", exp, totPow) +//require.True(t, exp.Equal(totPow), "exp %v, got %v", exp, totPow) //} diff --git a/x/gov/endblocker_test.go b/x/gov/endblocker_test.go index 4aeac9417e..0070bb5777 100644 --- a/x/gov/endblocker_test.go +++ b/x/gov/endblocker_test.go @@ -3,7 +3,7 @@ package gov import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" @@ -15,29 +15,29 @@ func TestTickExpiredDepositPeriod(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) govHandler := NewHandler(keeper) - assert.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewCoin("steak", 5)}) res := govHandler(ctx, newProposalMsg) - assert.True(t, res.IsOK()) + require.True(t, res.IsOK()) EndBlocker(ctx, keeper) - assert.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) ctx = ctx.WithBlockHeight(10) EndBlocker(ctx, keeper) - assert.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) ctx = ctx.WithBlockHeight(250) - assert.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.True(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.True(t, shouldPopInactiveProposalQueue(ctx, keeper)) EndBlocker(ctx, keeper) - assert.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) } func TestTickMultipleExpiredDepositPeriod(t *testing.T) { @@ -46,40 +46,40 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) govHandler := NewHandler(keeper) - assert.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewCoin("steak", 5)}) res := govHandler(ctx, newProposalMsg) - assert.True(t, res.IsOK()) + require.True(t, res.IsOK()) EndBlocker(ctx, keeper) - assert.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) ctx = ctx.WithBlockHeight(10) EndBlocker(ctx, keeper) - assert.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) newProposalMsg2 := NewMsgSubmitProposal("Test2", "test2", ProposalTypeText, addrs[1], sdk.Coins{sdk.NewCoin("steak", 5)}) res = govHandler(ctx, newProposalMsg2) - assert.True(t, res.IsOK()) + require.True(t, res.IsOK()) ctx = ctx.WithBlockHeight(205) - assert.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.True(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.True(t, shouldPopInactiveProposalQueue(ctx, keeper)) EndBlocker(ctx, keeper) - assert.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) ctx = ctx.WithBlockHeight(215) - assert.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.True(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.True(t, shouldPopInactiveProposalQueue(ctx, keeper)) EndBlocker(ctx, keeper) - assert.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) } func TestTickPassedDepositPeriod(t *testing.T) { @@ -88,41 +88,41 @@ func TestTickPassedDepositPeriod(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) govHandler := NewHandler(keeper) - assert.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) - assert.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopActiveProposalQueue(ctx, keeper)) + require.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) + require.False(t, shouldPopActiveProposalQueue(ctx, keeper)) newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewCoin("steak", 5)}) res := govHandler(ctx, newProposalMsg) - assert.True(t, res.IsOK()) + require.True(t, res.IsOK()) var proposalID int64 keeper.cdc.UnmarshalBinaryBare(res.Data, &proposalID) EndBlocker(ctx, keeper) - assert.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) ctx = ctx.WithBlockHeight(10) EndBlocker(ctx, keeper) - assert.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) newDepositMsg := NewMsgDeposit(addrs[1], proposalID, sdk.Coins{sdk.NewCoin("steak", 5)}) res = govHandler(ctx, newDepositMsg) - assert.True(t, res.IsOK()) + require.True(t, res.IsOK()) - assert.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.True(t, shouldPopInactiveProposalQueue(ctx, keeper)) - assert.NotNil(t, keeper.ActiveProposalQueuePeek(ctx)) + require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.True(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.NotNil(t, keeper.ActiveProposalQueuePeek(ctx)) EndBlocker(ctx, keeper) - assert.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) - assert.NotNil(t, keeper.ActiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopActiveProposalQueue(ctx, keeper)) + require.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.NotNil(t, keeper.ActiveProposalQueuePeek(ctx)) + require.False(t, shouldPopActiveProposalQueue(ctx, keeper)) } func TestTickPassedVotingPeriod(t *testing.T) { @@ -132,37 +132,37 @@ func TestTickPassedVotingPeriod(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) govHandler := NewHandler(keeper) - assert.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) - assert.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) - assert.False(t, shouldPopActiveProposalQueue(ctx, keeper)) + require.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.False(t, shouldPopInactiveProposalQueue(ctx, keeper)) + require.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) + require.False(t, shouldPopActiveProposalQueue(ctx, keeper)) newProposalMsg := NewMsgSubmitProposal("Test", "test", ProposalTypeText, addrs[0], sdk.Coins{sdk.NewCoin("steak", 5)}) res := govHandler(ctx, newProposalMsg) - assert.True(t, res.IsOK()) + require.True(t, res.IsOK()) var proposalID int64 keeper.cdc.UnmarshalBinaryBare(res.Data, &proposalID) ctx = ctx.WithBlockHeight(10) newDepositMsg := NewMsgDeposit(addrs[1], proposalID, sdk.Coins{sdk.NewCoin("steak", 5)}) res = govHandler(ctx, newDepositMsg) - assert.True(t, res.IsOK()) + require.True(t, res.IsOK()) EndBlocker(ctx, keeper) ctx = ctx.WithBlockHeight(215) - assert.True(t, shouldPopActiveProposalQueue(ctx, keeper)) + require.True(t, shouldPopActiveProposalQueue(ctx, keeper)) depositsIterator := keeper.GetDeposits(ctx, proposalID) - assert.True(t, depositsIterator.Valid()) + require.True(t, depositsIterator.Valid()) depositsIterator.Close() - assert.Equal(t, StatusVotingPeriod, keeper.GetProposal(ctx, proposalID).GetStatus()) + require.Equal(t, StatusVotingPeriod, keeper.GetProposal(ctx, proposalID).GetStatus()) EndBlocker(ctx, keeper) - assert.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) + require.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) depositsIterator = keeper.GetDeposits(ctx, proposalID) - assert.False(t, depositsIterator.Valid()) + require.False(t, depositsIterator.Valid()) depositsIterator.Close() - assert.Equal(t, StatusRejected, keeper.GetProposal(ctx, proposalID).GetStatus()) + require.Equal(t, StatusRejected, keeper.GetProposal(ctx, proposalID).GetStatus()) } diff --git a/x/gov/keeper_test.go b/x/gov/keeper_test.go index 1033600e65..786953fd3a 100644 --- a/x/gov/keeper_test.go +++ b/x/gov/keeper_test.go @@ -3,7 +3,7 @@ package gov import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" @@ -20,7 +20,7 @@ func TestGetSetProposal(t *testing.T) { keeper.SetProposal(ctx, proposal) gotProposal := keeper.GetProposal(ctx, proposalID) - assert.True(t, ProposalEqual(proposal, gotProposal)) + require.True(t, ProposalEqual(proposal, gotProposal)) } func TestIncrementProposalNumber(t *testing.T) { @@ -35,7 +35,7 @@ func TestIncrementProposalNumber(t *testing.T) { keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposal6 := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) - assert.Equal(t, int64(6), proposal6.GetProposalID()) + require.Equal(t, int64(6), proposal6.GetProposalID()) } func TestActivateVotingPeriod(t *testing.T) { @@ -45,13 +45,13 @@ func TestActivateVotingPeriod(t *testing.T) { proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) - assert.Equal(t, int64(-1), proposal.GetVotingStartBlock()) - assert.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) + require.Equal(t, int64(-1), proposal.GetVotingStartBlock()) + require.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) keeper.activateVotingPeriod(ctx, proposal) - assert.Equal(t, proposal.GetVotingStartBlock(), ctx.BlockHeight()) - assert.Equal(t, proposal.GetProposalID(), keeper.ActiveProposalQueuePeek(ctx).GetProposalID()) + require.Equal(t, proposal.GetVotingStartBlock(), ctx.BlockHeight()) + require.Equal(t, proposal.GetProposalID(), keeper.ActiveProposalQueuePeek(ctx).GetProposalID()) } func TestDeposits(t *testing.T) { @@ -69,77 +69,77 @@ func TestDeposits(t *testing.T) { addr0Initial := keeper.ck.GetCoins(ctx, addrs[0]) addr1Initial := keeper.ck.GetCoins(ctx, addrs[1]) - // assert.True(t, addr0Initial.IsEqual(sdk.Coins{sdk.NewCoin("steak", 42)})) - assert.Equal(t, sdk.Coins{sdk.NewCoin("steak", 42)}, addr0Initial) + // require.True(t, addr0Initial.IsEqual(sdk.Coins{sdk.NewCoin("steak", 42)})) + require.Equal(t, sdk.Coins{sdk.NewCoin("steak", 42)}, addr0Initial) - assert.True(t, proposal.GetTotalDeposit().IsEqual(sdk.Coins{})) + require.True(t, proposal.GetTotalDeposit().IsEqual(sdk.Coins{})) // Check no deposits at beginning deposit, found := keeper.GetDeposit(ctx, proposalID, addrs[1]) - assert.False(t, found) - assert.Equal(t, keeper.GetProposal(ctx, proposalID).GetVotingStartBlock(), int64(-1)) - assert.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) + require.False(t, found) + require.Equal(t, keeper.GetProposal(ctx, proposalID).GetVotingStartBlock(), int64(-1)) + require.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) // Check first deposit err, votingStarted := keeper.AddDeposit(ctx, proposalID, addrs[0], fourSteak) - assert.Nil(t, err) - assert.False(t, votingStarted) + require.Nil(t, err) + require.False(t, votingStarted) deposit, found = keeper.GetDeposit(ctx, proposalID, addrs[0]) - assert.True(t, found) - assert.Equal(t, fourSteak, deposit.Amount) - assert.Equal(t, addrs[0], deposit.Depositer) - assert.Equal(t, fourSteak, keeper.GetProposal(ctx, proposalID).GetTotalDeposit()) - assert.Equal(t, addr0Initial.Minus(fourSteak), keeper.ck.GetCoins(ctx, addrs[0])) + require.True(t, found) + require.Equal(t, fourSteak, deposit.Amount) + require.Equal(t, addrs[0], deposit.Depositer) + require.Equal(t, fourSteak, keeper.GetProposal(ctx, proposalID).GetTotalDeposit()) + require.Equal(t, addr0Initial.Minus(fourSteak), keeper.ck.GetCoins(ctx, addrs[0])) // Check a second deposit from same address err, votingStarted = keeper.AddDeposit(ctx, proposalID, addrs[0], fiveSteak) - assert.Nil(t, err) - assert.False(t, votingStarted) + require.Nil(t, err) + require.False(t, votingStarted) deposit, found = keeper.GetDeposit(ctx, proposalID, addrs[0]) - assert.True(t, found) - assert.Equal(t, fourSteak.Plus(fiveSteak), deposit.Amount) - assert.Equal(t, addrs[0], deposit.Depositer) - assert.Equal(t, fourSteak.Plus(fiveSteak), keeper.GetProposal(ctx, proposalID).GetTotalDeposit()) - assert.Equal(t, addr0Initial.Minus(fourSteak).Minus(fiveSteak), keeper.ck.GetCoins(ctx, addrs[0])) + require.True(t, found) + require.Equal(t, fourSteak.Plus(fiveSteak), deposit.Amount) + require.Equal(t, addrs[0], deposit.Depositer) + require.Equal(t, fourSteak.Plus(fiveSteak), keeper.GetProposal(ctx, proposalID).GetTotalDeposit()) + require.Equal(t, addr0Initial.Minus(fourSteak).Minus(fiveSteak), keeper.ck.GetCoins(ctx, addrs[0])) // Check third deposit from a new address err, votingStarted = keeper.AddDeposit(ctx, proposalID, addrs[1], fourSteak) - assert.Nil(t, err) - assert.True(t, votingStarted) + require.Nil(t, err) + require.True(t, votingStarted) deposit, found = keeper.GetDeposit(ctx, proposalID, addrs[1]) - assert.True(t, found) - assert.Equal(t, addrs[1], deposit.Depositer) - assert.Equal(t, fourSteak, deposit.Amount) - assert.Equal(t, fourSteak.Plus(fiveSteak).Plus(fourSteak), keeper.GetProposal(ctx, proposalID).GetTotalDeposit()) - assert.Equal(t, addr1Initial.Minus(fourSteak), keeper.ck.GetCoins(ctx, addrs[1])) + require.True(t, found) + require.Equal(t, addrs[1], deposit.Depositer) + require.Equal(t, fourSteak, deposit.Amount) + require.Equal(t, fourSteak.Plus(fiveSteak).Plus(fourSteak), keeper.GetProposal(ctx, proposalID).GetTotalDeposit()) + require.Equal(t, addr1Initial.Minus(fourSteak), keeper.ck.GetCoins(ctx, addrs[1])) // Check that proposal moved to voting period - assert.Equal(t, ctx.BlockHeight(), keeper.GetProposal(ctx, proposalID).GetVotingStartBlock()) - assert.NotNil(t, keeper.ActiveProposalQueuePeek(ctx)) - assert.Equal(t, proposalID, keeper.ActiveProposalQueuePeek(ctx).GetProposalID()) + require.Equal(t, ctx.BlockHeight(), keeper.GetProposal(ctx, proposalID).GetVotingStartBlock()) + require.NotNil(t, keeper.ActiveProposalQueuePeek(ctx)) + require.Equal(t, proposalID, keeper.ActiveProposalQueuePeek(ctx).GetProposalID()) // Test deposit iterator depositsIterator := keeper.GetDeposits(ctx, proposalID) - assert.True(t, depositsIterator.Valid()) + require.True(t, depositsIterator.Valid()) keeper.cdc.MustUnmarshalBinary(depositsIterator.Value(), &deposit) - assert.Equal(t, addrs[0], deposit.Depositer) - assert.Equal(t, fourSteak.Plus(fiveSteak), deposit.Amount) + require.Equal(t, addrs[0], deposit.Depositer) + require.Equal(t, fourSteak.Plus(fiveSteak), deposit.Amount) depositsIterator.Next() keeper.cdc.MustUnmarshalBinary(depositsIterator.Value(), &deposit) - assert.Equal(t, addrs[1], deposit.Depositer) - assert.Equal(t, fourSteak, deposit.Amount) + require.Equal(t, addrs[1], deposit.Depositer) + require.Equal(t, fourSteak, deposit.Amount) depositsIterator.Next() - assert.False(t, depositsIterator.Valid()) + require.False(t, depositsIterator.Valid()) // Test Refund Deposits deposit, found = keeper.GetDeposit(ctx, proposalID, addrs[1]) - assert.True(t, found) - assert.Equal(t, fourSteak, deposit.Amount) + require.True(t, found) + require.Equal(t, fourSteak, deposit.Amount) keeper.RefundDeposits(ctx, proposalID) deposit, found = keeper.GetDeposit(ctx, proposalID, addrs[1]) - assert.False(t, found) - assert.Equal(t, addr0Initial, keeper.ck.GetCoins(ctx, addrs[0])) - assert.Equal(t, addr1Initial, keeper.ck.GetCoins(ctx, addrs[1])) + require.False(t, found) + require.Equal(t, addr0Initial, keeper.ck.GetCoins(ctx, addrs[0])) + require.Equal(t, addr1Initial, keeper.ck.GetCoins(ctx, addrs[1])) } @@ -158,44 +158,44 @@ func TestVotes(t *testing.T) { // Test first vote keeper.AddVote(ctx, proposalID, addrs[0], OptionAbstain) vote, found := keeper.GetVote(ctx, proposalID, addrs[0]) - assert.True(t, found) - assert.Equal(t, addrs[0], vote.Voter) - assert.Equal(t, proposalID, vote.ProposalID) - assert.Equal(t, OptionAbstain, vote.Option) + require.True(t, found) + require.Equal(t, addrs[0], vote.Voter) + require.Equal(t, proposalID, vote.ProposalID) + require.Equal(t, OptionAbstain, vote.Option) // Test change of vote keeper.AddVote(ctx, proposalID, addrs[0], OptionYes) vote, found = keeper.GetVote(ctx, proposalID, addrs[0]) - assert.True(t, found) - assert.Equal(t, addrs[0], vote.Voter) - assert.Equal(t, proposalID, vote.ProposalID) - assert.Equal(t, OptionYes, vote.Option) + require.True(t, found) + require.Equal(t, addrs[0], vote.Voter) + require.Equal(t, proposalID, vote.ProposalID) + require.Equal(t, OptionYes, vote.Option) // Test second vote keeper.AddVote(ctx, proposalID, addrs[1], OptionNoWithVeto) vote, found = keeper.GetVote(ctx, proposalID, addrs[1]) - assert.True(t, found) - assert.Equal(t, addrs[1], vote.Voter) - assert.Equal(t, proposalID, vote.ProposalID) - assert.Equal(t, OptionNoWithVeto, vote.Option) + require.True(t, found) + require.Equal(t, addrs[1], vote.Voter) + require.Equal(t, proposalID, vote.ProposalID) + require.Equal(t, OptionNoWithVeto, vote.Option) // Test vote iterator votesIterator := keeper.GetVotes(ctx, proposalID) - assert.True(t, votesIterator.Valid()) + require.True(t, votesIterator.Valid()) keeper.cdc.MustUnmarshalBinary(votesIterator.Value(), &vote) - assert.True(t, votesIterator.Valid()) - assert.Equal(t, addrs[0], vote.Voter) - assert.Equal(t, proposalID, vote.ProposalID) - assert.Equal(t, OptionYes, vote.Option) + require.True(t, votesIterator.Valid()) + require.Equal(t, addrs[0], vote.Voter) + require.Equal(t, proposalID, vote.ProposalID) + require.Equal(t, OptionYes, vote.Option) votesIterator.Next() - assert.True(t, votesIterator.Valid()) + require.True(t, votesIterator.Valid()) keeper.cdc.MustUnmarshalBinary(votesIterator.Value(), &vote) - assert.True(t, votesIterator.Valid()) - assert.Equal(t, addrs[1], vote.Voter) - assert.Equal(t, proposalID, vote.ProposalID) - assert.Equal(t, OptionNoWithVeto, vote.Option) + require.True(t, votesIterator.Valid()) + require.Equal(t, addrs[1], vote.Voter) + require.Equal(t, proposalID, vote.ProposalID) + require.Equal(t, OptionNoWithVeto, vote.Option) votesIterator.Next() - assert.False(t, votesIterator.Valid()) + require.False(t, votesIterator.Valid()) } func TestProposalQueues(t *testing.T) { @@ -204,8 +204,8 @@ func TestProposalQueues(t *testing.T) { ctx := mapp.BaseApp.NewContext(false, abci.Header{}) mapp.InitChainer(ctx, abci.RequestInitChain{}) - assert.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) - assert.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) + require.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) + require.Nil(t, keeper.ActiveProposalQueuePeek(ctx)) // create test proposals proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) @@ -220,14 +220,14 @@ func TestProposalQueues(t *testing.T) { keeper.InactiveProposalQueuePush(ctx, proposal4) // test peeking and popping from inactive proposal queue - assert.Equal(t, keeper.InactiveProposalQueuePeek(ctx).GetProposalID(), proposal.GetProposalID()) - assert.Equal(t, keeper.InactiveProposalQueuePop(ctx).GetProposalID(), proposal.GetProposalID()) - assert.Equal(t, keeper.InactiveProposalQueuePeek(ctx).GetProposalID(), proposal2.GetProposalID()) - assert.Equal(t, keeper.InactiveProposalQueuePop(ctx).GetProposalID(), proposal2.GetProposalID()) - assert.Equal(t, keeper.InactiveProposalQueuePeek(ctx).GetProposalID(), proposal3.GetProposalID()) - assert.Equal(t, keeper.InactiveProposalQueuePop(ctx).GetProposalID(), proposal3.GetProposalID()) - assert.Equal(t, keeper.InactiveProposalQueuePeek(ctx).GetProposalID(), proposal4.GetProposalID()) - assert.Equal(t, keeper.InactiveProposalQueuePop(ctx).GetProposalID(), proposal4.GetProposalID()) + require.Equal(t, keeper.InactiveProposalQueuePeek(ctx).GetProposalID(), proposal.GetProposalID()) + require.Equal(t, keeper.InactiveProposalQueuePop(ctx).GetProposalID(), proposal.GetProposalID()) + require.Equal(t, keeper.InactiveProposalQueuePeek(ctx).GetProposalID(), proposal2.GetProposalID()) + require.Equal(t, keeper.InactiveProposalQueuePop(ctx).GetProposalID(), proposal2.GetProposalID()) + require.Equal(t, keeper.InactiveProposalQueuePeek(ctx).GetProposalID(), proposal3.GetProposalID()) + require.Equal(t, keeper.InactiveProposalQueuePop(ctx).GetProposalID(), proposal3.GetProposalID()) + require.Equal(t, keeper.InactiveProposalQueuePeek(ctx).GetProposalID(), proposal4.GetProposalID()) + require.Equal(t, keeper.InactiveProposalQueuePop(ctx).GetProposalID(), proposal4.GetProposalID()) // test pushing to active proposal queue keeper.ActiveProposalQueuePush(ctx, proposal) @@ -236,12 +236,12 @@ func TestProposalQueues(t *testing.T) { keeper.ActiveProposalQueuePush(ctx, proposal4) // test peeking and popping from active proposal queue - assert.Equal(t, keeper.ActiveProposalQueuePeek(ctx).GetProposalID(), proposal.GetProposalID()) - assert.Equal(t, keeper.ActiveProposalQueuePop(ctx).GetProposalID(), proposal.GetProposalID()) - assert.Equal(t, keeper.ActiveProposalQueuePeek(ctx).GetProposalID(), proposal2.GetProposalID()) - assert.Equal(t, keeper.ActiveProposalQueuePop(ctx).GetProposalID(), proposal2.GetProposalID()) - assert.Equal(t, keeper.ActiveProposalQueuePeek(ctx).GetProposalID(), proposal3.GetProposalID()) - assert.Equal(t, keeper.ActiveProposalQueuePop(ctx).GetProposalID(), proposal3.GetProposalID()) - assert.Equal(t, keeper.ActiveProposalQueuePeek(ctx).GetProposalID(), proposal4.GetProposalID()) - assert.Equal(t, keeper.ActiveProposalQueuePop(ctx).GetProposalID(), proposal4.GetProposalID()) + require.Equal(t, keeper.ActiveProposalQueuePeek(ctx).GetProposalID(), proposal.GetProposalID()) + require.Equal(t, keeper.ActiveProposalQueuePop(ctx).GetProposalID(), proposal.GetProposalID()) + require.Equal(t, keeper.ActiveProposalQueuePeek(ctx).GetProposalID(), proposal2.GetProposalID()) + require.Equal(t, keeper.ActiveProposalQueuePop(ctx).GetProposalID(), proposal2.GetProposalID()) + require.Equal(t, keeper.ActiveProposalQueuePeek(ctx).GetProposalID(), proposal3.GetProposalID()) + require.Equal(t, keeper.ActiveProposalQueuePop(ctx).GetProposalID(), proposal3.GetProposalID()) + require.Equal(t, keeper.ActiveProposalQueuePeek(ctx).GetProposalID(), proposal4.GetProposalID()) + require.Equal(t, keeper.ActiveProposalQueuePop(ctx).GetProposalID(), proposal4.GetProposalID()) } diff --git a/x/gov/msgs_test.go b/x/gov/msgs_test.go index 3100f98ca0..e9be4ded3d 100644 --- a/x/gov/msgs_test.go +++ b/x/gov/msgs_test.go @@ -3,7 +3,7 @@ package gov import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/mock" @@ -42,9 +42,9 @@ func TestMsgSubmitProposal(t *testing.T) { for i, tc := range tests { msg := NewMsgSubmitProposal(tc.title, tc.description, tc.proposalType, tc.proposerAddr, tc.initialDeposit) if tc.expectPass { - assert.Nil(t, msg.ValidateBasic(), "test: %v", i) + require.Nil(t, msg.ValidateBasic(), "test: %v", i) } else { - assert.NotNil(t, msg.ValidateBasic(), "test: %v", i) + require.NotNil(t, msg.ValidateBasic(), "test: %v", i) } } } @@ -69,9 +69,9 @@ func TestMsgDeposit(t *testing.T) { for i, tc := range tests { msg := NewMsgDeposit(tc.depositerAddr, tc.proposalID, tc.depositAmount) if tc.expectPass { - assert.Nil(t, msg.ValidateBasic(), "test: %v", i) + require.Nil(t, msg.ValidateBasic(), "test: %v", i) } else { - assert.NotNil(t, msg.ValidateBasic(), "test: %v", i) + require.NotNil(t, msg.ValidateBasic(), "test: %v", i) } } } @@ -97,9 +97,9 @@ func TestMsgVote(t *testing.T) { for i, tc := range tests { msg := NewMsgVote(tc.voterAddr, tc.proposalID, tc.option) if tc.expectPass { - assert.Nil(t, msg.ValidateBasic(), "test: %v", i) + require.Nil(t, msg.ValidateBasic(), "test: %v", i) } else { - assert.NotNil(t, msg.ValidateBasic(), "test: %v", i) + require.NotNil(t, msg.ValidateBasic(), "test: %v", i) } } } diff --git a/x/gov/tally_test.go b/x/gov/tally_test.go index 171a2e2e9c..bcc3f2eb01 100644 --- a/x/gov/tally_test.go +++ b/x/gov/tally_test.go @@ -3,7 +3,7 @@ package gov import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" @@ -31,7 +31,7 @@ func TestTallyNoOneVotes(t *testing.T) { passes, _ := tally(ctx, keeper, keeper.GetProposal(ctx, proposalID)) - assert.False(t, passes) + require.False(t, passes) } func TestTallyOnlyValidatorsAllYes(t *testing.T) { @@ -43,10 +43,10 @@ func TestTallyOnlyValidatorsAllYes(t *testing.T) { dummyDescription := stake.NewDescription("T", "E", "S", "T") val1CreateMsg := stake.NewMsgCreateValidator(addrs[0], crypto.GenPrivKeyEd25519().PubKey(), sdk.NewCoin("steak", 5), dummyDescription) res := stakeHandler(ctx, val1CreateMsg) - assert.True(t, res.IsOK()) + require.True(t, res.IsOK()) val2CreateMsg := stake.NewMsgCreateValidator(addrs[1], crypto.GenPrivKeyEd25519().PubKey(), sdk.NewCoin("steak", 5), dummyDescription) res = stakeHandler(ctx, val2CreateMsg) - assert.True(t, res.IsOK()) + require.True(t, res.IsOK()) proposal := keeper.NewTextProposal(ctx, "Test", "description", ProposalTypeText) proposalID := proposal.GetProposalID() @@ -54,13 +54,13 @@ func TestTallyOnlyValidatorsAllYes(t *testing.T) { keeper.SetProposal(ctx, proposal) err := keeper.AddVote(ctx, proposalID, addrs[0], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[1], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) passes, _ := tally(ctx, keeper, keeper.GetProposal(ctx, proposalID)) - assert.True(t, passes) + require.True(t, passes) } func TestTallyOnlyValidators51No(t *testing.T) { @@ -81,13 +81,13 @@ func TestTallyOnlyValidators51No(t *testing.T) { keeper.SetProposal(ctx, proposal) err := keeper.AddVote(ctx, proposalID, addrs[0], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[1], OptionNo) - assert.Nil(t, err) + require.Nil(t, err) passes, _ := tally(ctx, keeper, keeper.GetProposal(ctx, proposalID)) - assert.False(t, passes) + require.False(t, passes) } func TestTallyOnlyValidators51Yes(t *testing.T) { @@ -110,15 +110,15 @@ func TestTallyOnlyValidators51Yes(t *testing.T) { keeper.SetProposal(ctx, proposal) err := keeper.AddVote(ctx, proposalID, addrs[0], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[1], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[2], OptionNo) - assert.Nil(t, err) + require.Nil(t, err) passes, _ := tally(ctx, keeper, keeper.GetProposal(ctx, proposalID)) - assert.True(t, passes) + require.True(t, passes) } func TestTallyOnlyValidatorsVetoed(t *testing.T) { @@ -141,15 +141,15 @@ func TestTallyOnlyValidatorsVetoed(t *testing.T) { keeper.SetProposal(ctx, proposal) err := keeper.AddVote(ctx, proposalID, addrs[0], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[1], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[2], OptionNoWithVeto) - assert.Nil(t, err) + require.Nil(t, err) passes, _ := tally(ctx, keeper, keeper.GetProposal(ctx, proposalID)) - assert.False(t, passes) + require.False(t, passes) } func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { @@ -172,15 +172,15 @@ func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { keeper.SetProposal(ctx, proposal) err := keeper.AddVote(ctx, proposalID, addrs[0], OptionAbstain) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[1], OptionNo) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[2], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) passes, _ := tally(ctx, keeper, keeper.GetProposal(ctx, proposalID)) - assert.True(t, passes) + require.True(t, passes) } func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { @@ -203,15 +203,15 @@ func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { keeper.SetProposal(ctx, proposal) err := keeper.AddVote(ctx, proposalID, addrs[0], OptionAbstain) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[1], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[2], OptionNo) - assert.Nil(t, err) + require.Nil(t, err) passes, _ := tally(ctx, keeper, keeper.GetProposal(ctx, proposalID)) - assert.False(t, passes) + require.False(t, passes) } func TestTallyOnlyValidatorsNonVoter(t *testing.T) { @@ -234,15 +234,15 @@ func TestTallyOnlyValidatorsNonVoter(t *testing.T) { keeper.SetProposal(ctx, proposal) err := keeper.AddVote(ctx, proposalID, addrs[1], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[2], OptionNo) - assert.Nil(t, err) + require.Nil(t, err) passes, nonVoting := tally(ctx, keeper, keeper.GetProposal(ctx, proposalID)) - assert.False(t, passes) - assert.Equal(t, 1, len(nonVoting)) - assert.Equal(t, addrs[0], nonVoting[0]) + require.False(t, passes) + require.Equal(t, 1, len(nonVoting)) + require.Equal(t, addrs[0], nonVoting[0]) } func TestTallyDelgatorOverride(t *testing.T) { @@ -268,17 +268,17 @@ func TestTallyDelgatorOverride(t *testing.T) { keeper.SetProposal(ctx, proposal) err := keeper.AddVote(ctx, proposalID, addrs[0], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[1], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[2], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[3], OptionNo) - assert.Nil(t, err) + require.Nil(t, err) passes, _ := tally(ctx, keeper, keeper.GetProposal(ctx, proposalID)) - assert.False(t, passes) + require.False(t, passes) } func TestTallyDelgatorInherit(t *testing.T) { @@ -304,16 +304,16 @@ func TestTallyDelgatorInherit(t *testing.T) { keeper.SetProposal(ctx, proposal) err := keeper.AddVote(ctx, proposalID, addrs[0], OptionNo) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[1], OptionNo) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[2], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) passes, nonVoting := tally(ctx, keeper, keeper.GetProposal(ctx, proposalID)) - assert.True(t, passes) - assert.Equal(t, 0, len(nonVoting)) + require.True(t, passes) + require.Equal(t, 0, len(nonVoting)) } func TestTallyDelgatorMultipleOverride(t *testing.T) { @@ -341,17 +341,17 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { keeper.SetProposal(ctx, proposal) err := keeper.AddVote(ctx, proposalID, addrs[0], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[1], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[2], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[3], OptionNo) - assert.Nil(t, err) + require.Nil(t, err) passes, _ := tally(ctx, keeper, keeper.GetProposal(ctx, proposalID)) - assert.False(t, passes) + require.False(t, passes) } func TestTallyDelgatorMultipleInherit(t *testing.T) { @@ -379,13 +379,13 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { keeper.SetProposal(ctx, proposal) err := keeper.AddVote(ctx, proposalID, addrs[0], OptionYes) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[1], OptionNo) - assert.Nil(t, err) + require.Nil(t, err) err = keeper.AddVote(ctx, proposalID, addrs[2], OptionNo) - assert.Nil(t, err) + require.Nil(t, err) passes, _ := tally(ctx, keeper, keeper.GetProposal(ctx, proposalID)) - assert.False(t, passes) + require.False(t, passes) } diff --git a/x/ibc/app_test.go b/x/ibc/app_test.go index 077bc87bb6..1540bf2ed8 100644 --- a/x/ibc/app_test.go +++ b/x/ibc/app_test.go @@ -3,7 +3,6 @@ package ibc import ( "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" @@ -51,7 +50,7 @@ func TestIBCMsgs(t *testing.T) { // A checkTx context (true) ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) res1 := mapp.AccountMapper.GetAccount(ctxCheck, addr1) - assert.Equal(t, acc, res1) + require.Equal(t, acc, res1) packet := IBCPacket{ SrcAddr: addr1, diff --git a/x/ibc/ibc_test.go b/x/ibc/ibc_test.go index f292fabfe8..33535145d8 100644 --- a/x/ibc/ibc_test.go +++ b/x/ibc/ibc_test.go @@ -3,7 +3,7 @@ package ibc import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" @@ -72,8 +72,8 @@ func TestIBC(t *testing.T) { mycoins := sdk.Coins{sdk.NewCoin("mycoin", 10)} coins, _, err := ck.AddCoins(ctx, src, mycoins) - assert.Nil(t, err) - assert.Equal(t, mycoins, coins) + require.Nil(t, err) + require.Equal(t, mycoins, coins) ibcm := NewMapper(cdc, key, DefaultCodespace) h := NewHandler(ibcm, ck) @@ -93,23 +93,23 @@ func TestIBC(t *testing.T) { var igs int64 egl = ibcm.getEgressLength(store, chainid) - assert.Equal(t, egl, int64(0)) + require.Equal(t, egl, int64(0)) msg = IBCTransferMsg{ IBCPacket: packet, } res = h(ctx, msg) - assert.True(t, res.IsOK()) + require.True(t, res.IsOK()) coins, err = getCoins(ck, ctx, src) - assert.Nil(t, err) - assert.Equal(t, zero, coins) + require.Nil(t, err) + require.Equal(t, zero, coins) egl = ibcm.getEgressLength(store, chainid) - assert.Equal(t, egl, int64(1)) + require.Equal(t, egl, int64(1)) igs = ibcm.GetIngressSequence(ctx, chainid) - assert.Equal(t, igs, int64(0)) + require.Equal(t, igs, int64(0)) msg = IBCReceiveMsg{ IBCPacket: packet, @@ -117,18 +117,18 @@ func TestIBC(t *testing.T) { Sequence: 0, } res = h(ctx, msg) - assert.True(t, res.IsOK()) + require.True(t, res.IsOK()) coins, err = getCoins(ck, ctx, dest) - assert.Nil(t, err) - assert.Equal(t, mycoins, coins) + require.Nil(t, err) + require.Equal(t, mycoins, coins) igs = ibcm.GetIngressSequence(ctx, chainid) - assert.Equal(t, igs, int64(1)) + require.Equal(t, igs, int64(1)) res = h(ctx, msg) - assert.False(t, res.IsOK()) + require.False(t, res.IsOK()) igs = ibcm.GetIngressSequence(ctx, chainid) - assert.Equal(t, igs, int64(1)) + require.Equal(t, igs, int64(1)) } diff --git a/x/ibc/types_test.go b/x/ibc/types_test.go index 5127546989..690179baa1 100644 --- a/x/ibc/types_test.go +++ b/x/ibc/types_test.go @@ -3,7 +3,7 @@ package ibc import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -23,9 +23,9 @@ func TestIBCPacketValidation(t *testing.T) { for i, tc := range cases { err := tc.packet.ValidateBasic() if tc.valid { - assert.Nil(t, err, "%d: %+v", i, err) + require.Nil(t, err, "%d: %+v", i, err) } else { - assert.NotNil(t, err, "%d", i) + require.NotNil(t, err, "%d", i) } } } @@ -37,7 +37,7 @@ func TestIBCTransferMsg(t *testing.T) { packet := constructIBCPacket(true) msg := IBCTransferMsg{packet} - assert.Equal(t, msg.Type(), "ibc") + require.Equal(t, msg.Type(), "ibc") } func TestIBCTransferMsgValidation(t *testing.T) { @@ -55,9 +55,9 @@ func TestIBCTransferMsgValidation(t *testing.T) { for i, tc := range cases { err := tc.msg.ValidateBasic() if tc.valid { - assert.Nil(t, err, "%d: %+v", i, err) + require.Nil(t, err, "%d: %+v", i, err) } else { - assert.NotNil(t, err, "%d", i) + require.NotNil(t, err, "%d", i) } } } @@ -69,7 +69,7 @@ func TestIBCReceiveMsg(t *testing.T) { packet := constructIBCPacket(true) msg := IBCReceiveMsg{packet, sdk.Address([]byte("relayer")), 0} - assert.Equal(t, msg.Type(), "ibc") + require.Equal(t, msg.Type(), "ibc") } func TestIBCReceiveMsgValidation(t *testing.T) { @@ -87,9 +87,9 @@ func TestIBCReceiveMsgValidation(t *testing.T) { for i, tc := range cases { err := tc.msg.ValidateBasic() if tc.valid { - assert.Nil(t, err, "%d: %+v", i, err) + require.Nil(t, err, "%d: %+v", i, err) } else { - assert.NotNil(t, err, "%d", i) + require.NotNil(t, err, "%d", i) } } } diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index 2120e75b68..18416174bd 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -7,7 +7,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/mock" "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/x/stake" @@ -66,7 +65,7 @@ func checkValidator(t *testing.T, mapp *mock.App, keeper stake.Keeper, addr sdk.Address, expFound bool) stake.Validator { ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) validator, found := keeper.GetValidator(ctxCheck, addr1) - assert.Equal(t, expFound, found) + require.Equal(t, expFound, found) return validator } @@ -74,7 +73,7 @@ func checkValidatorSigningInfo(t *testing.T, mapp *mock.App, keeper Keeper, addr sdk.Address, expFound bool) ValidatorSigningInfo { ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) signingInfo, found := keeper.getValidatorSigningInfo(ctxCheck, addr) - assert.Equal(t, expFound, found) + require.Equal(t, expFound, found) return signingInfo } diff --git a/x/slashing/msg_test.go b/x/slashing/msg_test.go index be7797107e..a668bc33fa 100644 --- a/x/slashing/msg_test.go +++ b/x/slashing/msg_test.go @@ -3,7 +3,7 @@ package slashing import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -12,5 +12,5 @@ func TestMsgUnrevokeGetSignBytes(t *testing.T) { addr := sdk.Address("abcd") msg := NewMsgUnrevoke(addr) bytes := msg.GetSignBytes() - assert.Equal(t, string(bytes), `{"address":"cosmosvaladdr1v93xxeqamr0mv"}`) + require.Equal(t, string(bytes), `{"address":"cosmosvaladdr1v93xxeqamr0mv"}`) } diff --git a/x/stake/app_test.go b/x/stake/app_test.go index 2b02533092..d4fc5bdf00 100644 --- a/x/stake/app_test.go +++ b/x/stake/app_test.go @@ -75,7 +75,7 @@ func checkValidator(t *testing.T, mapp *mock.App, keeper Keeper, ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) validator, found := keeper.GetValidator(ctxCheck, addr1) - assert.Equal(t, expFound, found) + require.Equal(t, expFound, found) return validator } @@ -85,11 +85,11 @@ func checkDelegation(t *testing.T, mapp *mock.App, keeper Keeper, delegatorAddr, ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) delegation, found := keeper.GetDelegation(ctxCheck, delegatorAddr, validatorAddr) if expFound { - assert.True(t, found) + require.True(t, found) assert.True(sdk.RatEq(t, expShares, delegation.Shares)) return } - assert.False(t, found) + require.False(t, found) } func TestStakeMsgs(t *testing.T) { diff --git a/x/stake/handler_test.go b/x/stake/handler_test.go index 61acc94d7f..ef47318c68 100644 --- a/x/stake/handler_test.go +++ b/x/stake/handler_test.go @@ -3,7 +3,6 @@ package stake import ( "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" @@ -52,7 +51,7 @@ func TestValidatorByPowerIndex(t *testing.T) { // create validator msgCreateValidator := newTestMsgCreateValidator(validatorAddr, keep.PKs[0], initBond) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) - assert.True(t, got.IsOK(), "expected create-validator to be ok, got %v", got) + require.True(t, got.IsOK(), "expected create-validator to be ok, got %v", got) // verify the self-delegation exists bond, found := keeper.GetDelegation(ctx, validatorAddr, validatorAddr) @@ -72,7 +71,7 @@ func TestValidatorByPowerIndex(t *testing.T) { // create a second validator keep it bonded msgCreateValidator = newTestMsgCreateValidator(validatorAddr3, keep.PKs[2], int64(1000000)) got = handleMsgCreateValidator(ctx, msgCreateValidator, keeper) - assert.True(t, got.IsOK(), "expected create-validator to be ok, got %v", got) + require.True(t, got.IsOK(), "expected create-validator to be ok, got %v", got) // slash and revoke the first validator keeper.Slash(ctx, keep.PKs[0], 0, sdk.NewRat(1, 2)) @@ -83,7 +82,7 @@ func TestValidatorByPowerIndex(t *testing.T) { require.Equal(t, int64(500000), validator.PoolShares.Amount.Evaluate()) // ensure is unbonded // the old power record should have been deleted as the power changed - assert.False(t, keep.ValidatorByPowerIndexExists(ctx, keeper, power)) + require.False(t, keep.ValidatorByPowerIndexExists(ctx, keeper, power)) // but the new power record should have been created validator, found = keeper.GetValidator(ctx, validatorAddr) @@ -100,7 +99,7 @@ func TestValidatorByPowerIndex(t *testing.T) { // now the new record power index should be the same as the original record power3 := GetValidatorsByPowerIndexKey(validator, pool) - assert.Equal(t, power2, power3) + require.Equal(t, power2, power3) // unbond self-delegation msgBeginUnbonding := NewMsgBeginUnbonding(validatorAddr, validatorAddr, sdk.NewRat(1000000)) @@ -113,7 +112,7 @@ func TestValidatorByPowerIndex(t *testing.T) { // verify that by power key nolonger exists _, found = keeper.GetValidator(ctx, validatorAddr) require.False(t, found) - assert.False(t, keep.ValidatorByPowerIndexExists(ctx, keeper, power3)) + require.False(t, keep.ValidatorByPowerIndexExists(ctx, keeper, power3)) } func TestDuplicatesMsgCreateValidator(t *testing.T) { @@ -123,21 +122,21 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) { pk := keep.PKs[0] msgCreateValidator := newTestMsgCreateValidator(validatorAddr, pk, 10) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) - assert.True(t, got.IsOK(), "%v", got) + require.True(t, got.IsOK(), "%v", got) validator, found := keeper.GetValidator(ctx, validatorAddr) require.True(t, found) - assert.Equal(t, sdk.Bonded, validator.Status()) - assert.Equal(t, validatorAddr, validator.Owner) - assert.Equal(t, pk, validator.PubKey) - assert.Equal(t, sdk.NewRat(10), validator.PoolShares.Bonded()) - assert.Equal(t, sdk.NewRat(10), validator.DelegatorShares) - assert.Equal(t, Description{}, validator.Description) + require.Equal(t, sdk.Bonded, validator.Status()) + require.Equal(t, validatorAddr, validator.Owner) + require.Equal(t, pk, validator.PubKey) + require.Equal(t, sdk.NewRat(10), validator.PoolShares.Bonded()) + require.Equal(t, sdk.NewRat(10), validator.DelegatorShares) + require.Equal(t, Description{}, validator.Description) // one validator cannot bond twice msgCreateValidator.PubKey = keep.PKs[1] got = handleMsgCreateValidator(ctx, msgCreateValidator, keeper) - assert.False(t, got.IsOK(), "%v", got) + require.False(t, got.IsOK(), "%v", got) } func TestIncrementsMsgDelegate(t *testing.T) { @@ -151,26 +150,26 @@ func TestIncrementsMsgDelegate(t *testing.T) { // first create validator msgCreateValidator := newTestMsgCreateValidator(validatorAddr, keep.PKs[0], bondAmount) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) - assert.True(t, got.IsOK(), "expected create validator msg to be ok, got %v", got) + require.True(t, got.IsOK(), "expected create validator msg to be ok, got %v", got) validator, found := keeper.GetValidator(ctx, validatorAddr) require.True(t, found) require.Equal(t, sdk.Bonded, validator.Status()) - assert.Equal(t, bondAmount, validator.DelegatorShares.Evaluate()) - assert.Equal(t, bondAmount, validator.PoolShares.Bonded().Evaluate(), "validator: %v", validator) + require.Equal(t, bondAmount, validator.DelegatorShares.Evaluate()) + require.Equal(t, bondAmount, validator.PoolShares.Bonded().Evaluate(), "validator: %v", validator) _, found = keeper.GetDelegation(ctx, delegatorAddr, validatorAddr) require.False(t, found) bond, found := keeper.GetDelegation(ctx, validatorAddr, validatorAddr) require.True(t, found) - assert.Equal(t, bondAmount, bond.Shares.Evaluate()) + require.Equal(t, bondAmount, bond.Shares.Evaluate()) pool := keeper.GetPool(ctx) exRate := validator.DelegatorShareExRate(pool) require.True(t, exRate.Equal(sdk.OneRat()), "expected exRate 1 got %v", exRate) - assert.Equal(t, bondAmount, pool.BondedShares.Evaluate()) - assert.Equal(t, bondAmount, pool.BondedTokens) + require.Equal(t, bondAmount, pool.BondedShares.Evaluate()) + require.Equal(t, bondAmount, pool.BondedTokens) // just send the same msgbond multiple times msgDelegate := newTestMsgDelegate(delegatorAddr, validatorAddr, bondAmount) @@ -223,16 +222,16 @@ func TestIncrementsMsgUnbond(t *testing.T) { msgCreateValidator := newTestMsgCreateValidator(validatorAddr, keep.PKs[0], initBond) got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) - assert.True(t, got.IsOK(), "expected create-validator to be ok, got %v", got) + require.True(t, got.IsOK(), "expected create-validator to be ok, got %v", got) msgDelegate := newTestMsgDelegate(delegatorAddr, validatorAddr, initBond) got = handleMsgDelegate(ctx, msgDelegate, keeper) - assert.True(t, got.IsOK(), "expected delegation to be ok, got %v", got) + require.True(t, got.IsOK(), "expected delegation to be ok, got %v", got) validator, found := keeper.GetValidator(ctx, validatorAddr) require.True(t, found) - assert.Equal(t, initBond*2, validator.DelegatorShares.Evaluate()) - assert.Equal(t, initBond*2, validator.PoolShares.Bonded().Evaluate()) + require.Equal(t, initBond*2, validator.DelegatorShares.Evaluate()) + require.Equal(t, initBond*2, validator.PoolShares.Bonded().Evaluate()) // just send the same msgUnbond multiple times // TODO use decimals here @@ -292,14 +291,14 @@ func TestIncrementsMsgUnbond(t *testing.T) { unbondShares = sdk.NewRat(leftBonded + 1) msgBeginUnbonding = NewMsgBeginUnbonding(delegatorAddr, validatorAddr, unbondShares) got = handleMsgBeginUnbonding(ctx, msgBeginUnbonding, keeper) - assert.False(t, got.IsOK(), + require.False(t, got.IsOK(), "got: %v\nmsgUnbond: %v\nshares: %v\nleftBonded: %v\n", got, msgBeginUnbonding, unbondShares.String(), leftBonded) // should be able to unbond just what we have unbondShares = sdk.NewRat(leftBonded) msgBeginUnbonding = NewMsgBeginUnbonding(delegatorAddr, validatorAddr, unbondShares) got = handleMsgBeginUnbonding(ctx, msgBeginUnbonding, keeper) - assert.True(t, got.IsOK(), + require.True(t, got.IsOK(), "got: %v\nmsgUnbond: %v\nshares: %v\nleftBonded: %v\n", got, msgBeginUnbonding, unbondShares, leftBonded) } @@ -420,7 +419,7 @@ func TestRevokeValidator(t *testing.T) { // test that this address cannot yet be bonded too because is revoked got = handleMsgDelegate(ctx, msgDelegate, keeper) - assert.False(t, got.IsOK(), "expected error, got %v", got) + require.False(t, got.IsOK(), "expected error, got %v", got) // test that the delegator can still withdraw their bonds msgBeginUnbondingDelegator := NewMsgBeginUnbonding(delegatorAddr, validatorAddr, sdk.NewRat(10)) @@ -432,7 +431,7 @@ func TestRevokeValidator(t *testing.T) { // verify that the pubkey can now be reused got = handleMsgCreateValidator(ctx, msgCreateValidator, keeper) - assert.True(t, got.IsOK(), "expected ok, got %v", got) + require.True(t, got.IsOK(), "expected ok, got %v", got) } func TestUnbondingPeriod(t *testing.T) { diff --git a/x/stake/keeper/delegation_test.go b/x/stake/keeper/delegation_test.go index d7c1ac9849..f20188ccdc 100644 --- a/x/stake/keeper/delegation_test.go +++ b/x/stake/keeper/delegation_test.go @@ -6,7 +6,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/stake/types" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -37,20 +36,20 @@ func TestDelegation(t *testing.T) { // check the empty keeper first _, found := keeper.GetDelegation(ctx, addrDels[0], addrVals[0]) - assert.False(t, found) + require.False(t, found) // set and retrieve a record keeper.SetDelegation(ctx, bond1to1) resBond, found := keeper.GetDelegation(ctx, addrDels[0], addrVals[0]) - assert.True(t, found) - assert.True(t, bond1to1.Equal(resBond)) + require.True(t, found) + require.True(t, bond1to1.Equal(resBond)) // modify a records, save, and retrieve bond1to1.Shares = sdk.NewRat(99) keeper.SetDelegation(ctx, bond1to1) resBond, found = keeper.GetDelegation(ctx, addrDels[0], addrVals[0]) - assert.True(t, found) - assert.True(t, bond1to1.Equal(resBond)) + require.True(t, found) + require.True(t, bond1to1.Equal(resBond)) // add some more records bond1to2 := types.Delegation{addrDels[0], addrVals[1], sdk.NewRat(9), 0} @@ -67,43 +66,43 @@ func TestDelegation(t *testing.T) { // test all bond retrieve capabilities resBonds := keeper.GetDelegations(ctx, addrDels[0], 5) require.Equal(t, 3, len(resBonds)) - assert.True(t, bond1to1.Equal(resBonds[0])) - assert.True(t, bond1to2.Equal(resBonds[1])) - assert.True(t, bond1to3.Equal(resBonds[2])) + require.True(t, bond1to1.Equal(resBonds[0])) + require.True(t, bond1to2.Equal(resBonds[1])) + require.True(t, bond1to3.Equal(resBonds[2])) resBonds = keeper.GetDelegations(ctx, addrDels[0], 3) require.Equal(t, 3, len(resBonds)) resBonds = keeper.GetDelegations(ctx, addrDels[0], 2) require.Equal(t, 2, len(resBonds)) resBonds = keeper.GetDelegations(ctx, addrDels[1], 5) require.Equal(t, 3, len(resBonds)) - assert.True(t, bond2to1.Equal(resBonds[0])) - assert.True(t, bond2to2.Equal(resBonds[1])) - assert.True(t, bond2to3.Equal(resBonds[2])) + require.True(t, bond2to1.Equal(resBonds[0])) + require.True(t, bond2to2.Equal(resBonds[1])) + require.True(t, bond2to3.Equal(resBonds[2])) allBonds := keeper.GetAllDelegations(ctx) require.Equal(t, 6, len(allBonds)) - assert.True(t, bond1to1.Equal(allBonds[0])) - assert.True(t, bond1to2.Equal(allBonds[1])) - assert.True(t, bond1to3.Equal(allBonds[2])) - assert.True(t, bond2to1.Equal(allBonds[3])) - assert.True(t, bond2to2.Equal(allBonds[4])) - assert.True(t, bond2to3.Equal(allBonds[5])) + require.True(t, bond1to1.Equal(allBonds[0])) + require.True(t, bond1to2.Equal(allBonds[1])) + require.True(t, bond1to3.Equal(allBonds[2])) + require.True(t, bond2to1.Equal(allBonds[3])) + require.True(t, bond2to2.Equal(allBonds[4])) + require.True(t, bond2to3.Equal(allBonds[5])) // delete a record keeper.RemoveDelegation(ctx, bond2to3) _, found = keeper.GetDelegation(ctx, addrDels[1], addrVals[2]) - assert.False(t, found) + require.False(t, found) resBonds = keeper.GetDelegations(ctx, addrDels[1], 5) require.Equal(t, 2, len(resBonds)) - assert.True(t, bond2to1.Equal(resBonds[0])) - assert.True(t, bond2to2.Equal(resBonds[1])) + require.True(t, bond2to1.Equal(resBonds[0])) + require.True(t, bond2to2.Equal(resBonds[1])) // delete all the records from delegator 2 keeper.RemoveDelegation(ctx, bond2to1) keeper.RemoveDelegation(ctx, bond2to2) _, found = keeper.GetDelegation(ctx, addrDels[1], addrVals[0]) - assert.False(t, found) + require.False(t, found) _, found = keeper.GetDelegation(ctx, addrDels[1], addrVals[1]) - assert.False(t, found) + require.False(t, found) resBonds = keeper.GetDelegations(ctx, addrDels[1], 5) require.Equal(t, 0, len(resBonds)) } @@ -123,20 +122,20 @@ func TestUnbondingDelegation(t *testing.T) { // set and retrieve a record keeper.SetUnbondingDelegation(ctx, ubd) resBond, found := keeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0]) - assert.True(t, found) - assert.True(t, ubd.Equal(resBond)) + require.True(t, found) + require.True(t, ubd.Equal(resBond)) // modify a records, save, and retrieve ubd.Balance = sdk.NewCoin("steak", 21) keeper.SetUnbondingDelegation(ctx, ubd) resBond, found = keeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0]) - assert.True(t, found) - assert.True(t, ubd.Equal(resBond)) + require.True(t, found) + require.True(t, ubd.Equal(resBond)) // delete a record keeper.RemoveUnbondingDelegation(ctx, ubd) _, found = keeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0]) - assert.False(t, found) + require.False(t, found) } func TestUnbondDelegation(t *testing.T) { @@ -166,7 +165,7 @@ func TestUnbondDelegation(t *testing.T) { var amount int64 amount, err = keeper.unbond(ctx, addrDels[0], addrVals[0], sdk.NewRat(6)) require.NoError(t, err) - assert.Equal(t, int64(6), amount) // shares to be added to an unbonding delegation / redelegation + require.Equal(t, int64(6), amount) // shares to be added to an unbonding delegation / redelegation delegation, found := keeper.GetDelegation(ctx, addrDels[0], addrVals[0]) require.True(t, found) @@ -174,10 +173,10 @@ func TestUnbondDelegation(t *testing.T) { require.True(t, found) pool = keeper.GetPool(ctx) - assert.Equal(t, int64(4), delegation.Shares.Evaluate()) - assert.Equal(t, int64(4), validator.PoolShares.Bonded().Evaluate()) - assert.Equal(t, int64(6), pool.LooseTokens, "%v", pool) - assert.Equal(t, int64(4), pool.BondedTokens) + require.Equal(t, int64(4), delegation.Shares.Evaluate()) + require.Equal(t, int64(4), validator.PoolShares.Bonded().Evaluate()) + require.Equal(t, int64(6), pool.LooseTokens, "%v", pool) + require.Equal(t, int64(4), pool.BondedTokens) } // tests Get/Set/Remove/Has UnbondingDelegation @@ -196,28 +195,28 @@ func TestRedelegation(t *testing.T) { // test shouldn't have and redelegations has := keeper.HasReceivingRedelegation(ctx, addrDels[0], addrVals[1]) - assert.False(t, has) + require.False(t, has) // set and retrieve a record keeper.SetRedelegation(ctx, rd) resBond, found := keeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1]) - assert.True(t, found) - assert.True(t, rd.Equal(resBond)) + require.True(t, found) + require.True(t, rd.Equal(resBond)) // check if has the redelegation has = keeper.HasReceivingRedelegation(ctx, addrDels[0], addrVals[1]) - assert.True(t, has) + require.True(t, has) // modify a records, save, and retrieve rd.SharesSrc = sdk.NewRat(21) rd.SharesDst = sdk.NewRat(21) keeper.SetRedelegation(ctx, rd) resBond, found = keeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1]) - assert.True(t, found) - assert.True(t, rd.Equal(resBond)) + require.True(t, found) + require.True(t, rd.Equal(resBond)) // delete a record keeper.RemoveRedelegation(ctx, rd) _, found = keeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1]) - assert.False(t, found) + require.False(t, found) } diff --git a/x/stake/keeper/inflation_test.go b/x/stake/keeper/inflation_test.go index d748ce0cb2..944559dfc2 100644 --- a/x/stake/keeper/inflation_test.go +++ b/x/stake/keeper/inflation_test.go @@ -5,7 +5,6 @@ import ( "strconv" "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" @@ -61,7 +60,7 @@ func TestGetInflation(t *testing.T) { inflation := keeper.NextInflation(ctx) diffInflation := inflation.Sub(tc.setInflation) - assert.True(t, diffInflation.Equal(tc.expectedChange), + require.True(t, diffInflation.Equal(tc.expectedChange), "Name: %v\nDiff: %v\nExpected: %v\n", tc.name, diffInflation, tc.expectedChange) } } @@ -155,7 +154,7 @@ func TestLargeUnbond(t *testing.T) { pool = keeper.GetPool(ctx) validator, found := keeper.GetValidator(ctx, Addrs[0]) - assert.True(t, found) + require.True(t, found) // initialBondedRatio that we can use to compare to the new values after the unbond initialBondedRatio := pool.BondedRatio() @@ -172,9 +171,9 @@ func TestLargeUnbond(t *testing.T) { unbondedShares = unbondedShares.Add(sdk.NewRat(val0UnbondedTokens, 1).Mul(pool.UnbondedShareExRate())) // unbonded shares should increase - assert.True(t, unbondedShares.GT(sdk.NewRat(300000000, 1))) + require.True(t, unbondedShares.GT(sdk.NewRat(300000000, 1))) // Ensure that new bonded ratio is less than old bonded ratio , because before they were increasing (i.e. 50% < 75) - assert.True(t, (pool.BondedRatio().LT(initialBondedRatio))) + require.True(t, (pool.BondedRatio().LT(initialBondedRatio))) // Final check that the pool equals initial values + provisions and adjustments we recorded pool = keeper.GetPool(ctx) @@ -202,7 +201,7 @@ func TestLargeBond(t *testing.T) { pool = keeper.GetPool(ctx) validator, found := keeper.GetValidator(ctx, Addrs[9]) - assert.True(t, found) + require.True(t, found) // initialBondedRatio that we can use to compare to the new values after the unbond initialBondedRatio := pool.BondedRatio() @@ -220,9 +219,9 @@ func TestLargeBond(t *testing.T) { unbondedShares = unbondedShares.Sub(unbondedSharesVal9) // unbonded shares should decrease - assert.True(t, unbondedShares.LT(sdk.NewRat(1200000000, 1))) + require.True(t, unbondedShares.LT(sdk.NewRat(1200000000, 1))) // Ensure that new bonded ratio is greater than old bonded ratio (i.e. 50% > 25%) - assert.True(t, (pool.BondedRatio().GT(initialBondedRatio))) + require.True(t, (pool.BondedRatio().GT(initialBondedRatio))) // Final check that the pool equals initial values + provisions and adjustments we recorded pool = keeper.GetPool(ctx) @@ -289,7 +288,7 @@ func TestInflationWithRandomOperations(t *testing.T) { // Final check on the global pool values for what the total tokens accumulated from each hour of provisions func checkFinalPoolValues(t *testing.T, pool types.Pool, initialTotalTokens, cumulativeExpProvs int64) { calculatedTotalTokens := initialTotalTokens + cumulativeExpProvs - assert.Equal(t, calculatedTotalTokens, pool.TokenSupply()) + require.Equal(t, calculatedTotalTokens, pool.TokenSupply()) } // Processes provisions are added to the pool correctly every hour @@ -332,14 +331,14 @@ func setupTestValidators(pool types.Pool, keeper Keeper, ctx sdk.Context, valida // Checks that the deterministic validator setup you wanted matches the values in the pool func checkValidatorSetup(t *testing.T, pool types.Pool, initialTotalTokens, initialBondedTokens, initialUnbondedTokens int64) { - assert.Equal(t, initialTotalTokens, pool.TokenSupply(), "%v", pool) - assert.Equal(t, initialBondedTokens, pool.BondedTokens, "%v", pool) - assert.Equal(t, initialUnbondedTokens, pool.UnbondedTokens, "%v", pool) + require.Equal(t, initialTotalTokens, pool.TokenSupply(), "%v", pool) + require.Equal(t, initialBondedTokens, pool.BondedTokens, "%v", pool) + require.Equal(t, initialUnbondedTokens, pool.UnbondedTokens, "%v", pool) // test initial bonded ratio - assert.True(t, pool.BondedRatio().Equal(sdk.NewRat(initialBondedTokens, initialTotalTokens)), "%v", pool.BondedRatio()) + require.True(t, pool.BondedRatio().Equal(sdk.NewRat(initialBondedTokens, initialTotalTokens)), "%v", pool.BondedRatio()) // test the value of validator shares - assert.True(t, pool.BondedShareExRate().Equal(sdk.OneRat()), "%v", pool.BondedShareExRate()) + require.True(t, pool.BondedShareExRate().Equal(sdk.OneRat()), "%v", pool.BondedShareExRate()) } // Checks that The inflation will correctly increase or decrease after an update to the pool @@ -349,30 +348,30 @@ func checkInflation(t *testing.T, pool types.Pool, previousInflation, updatedInf switch { //BELOW 67% - Rate of change positive and increasing, while we are between 7% <= and < 20% inflation case pool.BondedRatio().LT(sdk.NewRat(67, 100)) && updatedInflation.LT(sdk.NewRat(20, 100)): - assert.Equal(t, true, inflationChange.GT(sdk.ZeroRat()), msg) + require.Equal(t, true, inflationChange.GT(sdk.ZeroRat()), msg) //BELOW 67% - Rate of change should be 0 while inflation continually stays at 20% until we reach 67% bonded ratio case pool.BondedRatio().LT(sdk.NewRat(67, 100)) && updatedInflation.Equal(sdk.NewRat(20, 100)): if previousInflation.Equal(sdk.NewRat(20, 100)) { - assert.Equal(t, true, inflationChange.IsZero(), msg) + require.Equal(t, true, inflationChange.IsZero(), msg) //This else statement covers the one off case where we first hit 20%, but we still needed a positive ROC to get to 67% bonded ratio (i.e. we went from 19.99999% to 20%) } else { - assert.Equal(t, true, inflationChange.GT(sdk.ZeroRat()), msg) + require.Equal(t, true, inflationChange.GT(sdk.ZeroRat()), msg) } //ABOVE 67% - Rate of change should be negative while the bond is above 67, and should stay negative until we reach inflation of 7% case pool.BondedRatio().GT(sdk.NewRat(67, 100)) && updatedInflation.LT(sdk.NewRat(20, 100)) && updatedInflation.GT(sdk.NewRat(7, 100)): - assert.Equal(t, true, inflationChange.LT(sdk.ZeroRat()), msg) + require.Equal(t, true, inflationChange.LT(sdk.ZeroRat()), msg) //ABOVE 67% - Rate of change should be 0 while inflation continually stays at 7%. case pool.BondedRatio().GT(sdk.NewRat(67, 100)) && updatedInflation.Equal(sdk.NewRat(7, 100)): if previousInflation.Equal(sdk.NewRat(7, 100)) { - assert.Equal(t, true, inflationChange.IsZero(), msg) + require.Equal(t, true, inflationChange.IsZero(), msg) //This else statement covers the one off case where we first hit 7%, but we still needed a negative ROC to continue to get down to 67%. (i.e. we went from 7.00001% to 7%) } else { - assert.Equal(t, true, inflationChange.LT(sdk.ZeroRat()), msg) + require.Equal(t, true, inflationChange.LT(sdk.ZeroRat()), msg) } } } diff --git a/x/stake/keeper/keeper_test.go b/x/stake/keeper/keeper_test.go index 1be5872850..15fecf3f25 100644 --- a/x/stake/keeper/keeper_test.go +++ b/x/stake/keeper/keeper_test.go @@ -3,7 +3,7 @@ package keeper import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/x/stake/types" ) @@ -14,13 +14,13 @@ func TestParams(t *testing.T) { //check that the empty keeper loads the default resParams := keeper.GetParams(ctx) - assert.True(t, expParams.Equal(resParams)) + require.True(t, expParams.Equal(resParams)) //modify a params, save, and retrieve expParams.MaxValidators = 777 keeper.SetParams(ctx, expParams) resParams = keeper.GetParams(ctx) - assert.True(t, expParams.Equal(resParams)) + require.True(t, expParams.Equal(resParams)) } func TestPool(t *testing.T) { @@ -29,11 +29,11 @@ func TestPool(t *testing.T) { //check that the empty keeper loads the default resPool := keeper.GetPool(ctx) - assert.True(t, expPool.Equal(resPool)) + require.True(t, expPool.Equal(resPool)) //modify a params, save, and retrieve expPool.BondedTokens = 777 keeper.SetPool(ctx, expPool) resPool = keeper.GetPool(ctx) - assert.True(t, expPool.Equal(resPool)) + require.True(t, expPool.Equal(resPool)) } diff --git a/x/stake/keeper/validator_test.go b/x/stake/keeper/validator_test.go index 098c17e75f..cf26d055f6 100644 --- a/x/stake/keeper/validator_test.go +++ b/x/stake/keeper/validator_test.go @@ -34,7 +34,7 @@ func TestSetValidator(t *testing.T) { // Check each store for being saved resVal, found := keeper.GetValidator(ctx, addrVals[0]) assert.True(ValEq(t, validator, resVal)) - assert.True(t, found) + require.True(t, found) resVals := keeper.GetValidatorsBonded(ctx) require.Equal(t, 1, len(resVals)) @@ -46,7 +46,7 @@ func TestSetValidator(t *testing.T) { updates := keeper.GetTendermintUpdates(ctx) require.Equal(t, 1, len(updates)) - assert.Equal(t, validator.ABCIValidator(), updates[0]) + require.Equal(t, validator.ABCIValidator(), updates[0]) } @@ -68,29 +68,29 @@ func TestUpdateValidatorByPowerIndex(t *testing.T) { validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) validator, pool, delSharesCreated := validator.AddTokensFromDel(pool, 100) require.Equal(t, sdk.Unbonded, validator.Status()) - assert.Equal(t, int64(100), validator.PoolShares.Tokens(pool).Evaluate()) + require.Equal(t, int64(100), validator.PoolShares.Tokens(pool).Evaluate()) keeper.SetPool(ctx, pool) keeper.UpdateValidator(ctx, validator) validator, found := keeper.GetValidator(ctx, addrVals[0]) require.True(t, found) - assert.Equal(t, int64(100), validator.PoolShares.Tokens(pool).Evaluate(), "\nvalidator %v\npool %v", validator, pool) + require.Equal(t, int64(100), validator.PoolShares.Tokens(pool).Evaluate(), "\nvalidator %v\npool %v", validator, pool) pool = keeper.GetPool(ctx) power := GetValidatorsByPowerIndexKey(validator, pool) - assert.True(t, keeper.validatorByPowerIndexExists(ctx, power)) + require.True(t, keeper.validatorByPowerIndexExists(ctx, power)) // burn half the delegator shares validator, pool, burned := validator.RemoveDelShares(pool, delSharesCreated.Quo(sdk.NewRat(2))) - assert.Equal(t, int64(50), burned) + require.Equal(t, int64(50), burned) keeper.SetPool(ctx, pool) // update the pool keeper.UpdateValidator(ctx, validator) // update the validator, possibly kicking it out - assert.False(t, keeper.validatorByPowerIndexExists(ctx, power)) + require.False(t, keeper.validatorByPowerIndexExists(ctx, power)) pool = keeper.GetPool(ctx) validator, found = keeper.GetValidator(ctx, addrVals[0]) - assert.True(t, found) + require.True(t, found) power = GetValidatorsByPowerIndexKey(validator, pool) - assert.True(t, keeper.validatorByPowerIndexExists(ctx, power)) + require.True(t, keeper.validatorByPowerIndexExists(ctx, power)) } // This function tests UpdateValidator, GetValidator, GetValidatorsBonded, RemoveValidator @@ -109,7 +109,7 @@ func TestValidatorBasics(t *testing.T) { // check the empty keeper first _, found := keeper.GetValidator(ctx, addrVals[0]) - assert.False(t, found) + require.False(t, found) resVals := keeper.GetValidatorsBonded(ctx) assert.Zero(t, len(resVals)) @@ -154,7 +154,7 @@ func TestValidatorBasics(t *testing.T) { // remove a record keeper.RemoveValidator(ctx, validators[1].Owner) _, found = keeper.GetValidator(ctx, addrVals[1]) - assert.False(t, found) + require.False(t, found) } // test how the validators are sorted, tests GetValidatorsByPower @@ -174,7 +174,7 @@ func GetValidatorSortingUnmixed(t *testing.T) { // first make sure everything made it in to the gotValidator group resValidators := keeper.GetValidatorsByPower(ctx) - require.Equal(t, n, len(resValidators)) + assert.Equal(t, n, len(resValidators)) assert.Equal(t, sdk.NewRat(400), resValidators[0].PoolShares.Bonded(), "%v", resValidators) assert.Equal(t, sdk.NewRat(200), resValidators[1].PoolShares.Bonded(), "%v", resValidators) assert.Equal(t, sdk.NewRat(100), resValidators[2].PoolShares.Bonded(), "%v", resValidators) @@ -209,8 +209,8 @@ func GetValidatorSortingUnmixed(t *testing.T) { require.Equal(t, len(resValidators), n) assert.True(ValEq(t, validators[3], resValidators[0])) assert.True(ValEq(t, validators[4], resValidators[1])) - assert.Equal(t, int64(0), resValidators[0].BondHeight, "%v", resValidators) - assert.Equal(t, int64(0), resValidators[1].BondHeight, "%v", resValidators) + require.Equal(t, int64(0), resValidators[0].BondHeight, "%v", resValidators) + require.Equal(t, int64(0), resValidators[1].BondHeight, "%v", resValidators) // no change in voting power - no change in sort ctx = ctx.WithBlockHeight(20) @@ -269,15 +269,15 @@ func GetValidatorSortingMixed(t *testing.T) { require.True(t, found) val4, found := keeper.GetValidator(ctx, Addrs[4]) require.True(t, found) - assert.Equal(t, sdk.Unbonded, val0.Status()) - assert.Equal(t, sdk.Unbonded, val1.Status()) - assert.Equal(t, sdk.Unbonded, val2.Status()) - assert.Equal(t, sdk.Bonded, val3.Status()) - assert.Equal(t, sdk.Bonded, val4.Status()) + require.Equal(t, sdk.Unbonded, val0.Status()) + require.Equal(t, sdk.Unbonded, val1.Status()) + require.Equal(t, sdk.Unbonded, val2.Status()) + require.Equal(t, sdk.Bonded, val3.Status()) + require.Equal(t, sdk.Bonded, val4.Status()) // first make sure everything made it in to the gotValidator group resValidators := keeper.GetValidatorsByPower(ctx) - require.Equal(t, n, len(resValidators)) + assert.Equal(t, n, len(resValidators)) assert.Equal(t, sdk.NewRat(400), resValidators[0].PoolShares.Bonded(), "%v", resValidators) assert.Equal(t, sdk.NewRat(200), resValidators[1].PoolShares.Bonded(), "%v", resValidators) assert.Equal(t, sdk.NewRat(100), resValidators[2].PoolShares.Bonded(), "%v", resValidators) @@ -438,7 +438,7 @@ func TestFullValidatorSetPowerChange(t *testing.T) { assert.Equal(t, sdk.Bonded, validators[3].Status()) assert.Equal(t, sdk.Unbonded, validators[4].Status()) resValidators := keeper.GetValidatorsByPower(ctx) - require.Equal(t, max, len(resValidators)) + assert.Equal(t, max, len(resValidators)) assert.True(ValEq(t, validators[2], resValidators[0])) // in the order of txs assert.True(ValEq(t, validators[3], resValidators[1])) @@ -448,7 +448,7 @@ func TestFullValidatorSetPowerChange(t *testing.T) { keeper.SetPool(ctx, pool) validators[0] = keeper.UpdateValidator(ctx, validators[0]) resValidators = keeper.GetValidatorsByPower(ctx) - require.Equal(t, max, len(resValidators)) + assert.Equal(t, max, len(resValidators)) assert.True(ValEq(t, validators[0], resValidators[0])) assert.True(ValEq(t, validators[2], resValidators[1])) } @@ -468,10 +468,10 @@ func TestClearTendermintUpdates(t *testing.T) { } updates := keeper.GetTendermintUpdates(ctx) - assert.Equal(t, len(amts), len(updates)) + require.Equal(t, len(amts), len(updates)) keeper.ClearTendermintUpdates(ctx) updates = keeper.GetTendermintUpdates(ctx) - assert.Equal(t, 0, len(updates)) + require.Equal(t, 0, len(updates)) } func TestGetTendermintUpdatesAllNone(t *testing.T) { @@ -488,25 +488,25 @@ func TestGetTendermintUpdatesAllNone(t *testing.T) { // test from nothing to something // tendermintUpdate set: {} -> {c1, c3} - assert.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) + require.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) validators[0] = keeper.UpdateValidator(ctx, validators[0]) validators[1] = keeper.UpdateValidator(ctx, validators[1]) updates := keeper.GetTendermintUpdates(ctx) - require.Equal(t, 2, len(updates)) + assert.Equal(t, 2, len(updates)) assert.Equal(t, validators[0].ABCIValidator(), updates[0]) assert.Equal(t, validators[1].ABCIValidator(), updates[1]) // test from something to nothing // tendermintUpdate set: {} -> {c1, c2, c3, c4} keeper.ClearTendermintUpdates(ctx) - assert.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) + require.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) keeper.RemoveValidator(ctx, validators[0].Owner) keeper.RemoveValidator(ctx, validators[1].Owner) updates = keeper.GetTendermintUpdates(ctx) - require.Equal(t, 2, len(updates)) + assert.Equal(t, 2, len(updates)) assert.Equal(t, tmtypes.TM2PB.PubKey(validators[0].PubKey), updates[0].PubKey) assert.Equal(t, tmtypes.TM2PB.PubKey(validators[1].PubKey), updates[1].PubKey) assert.Equal(t, int64(0), updates[0].Power) @@ -527,13 +527,13 @@ func TestGetTendermintUpdatesIdentical(t *testing.T) { validators[0] = keeper.UpdateValidator(ctx, validators[0]) validators[1] = keeper.UpdateValidator(ctx, validators[1]) keeper.ClearTendermintUpdates(ctx) - assert.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) + require.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) // test identical, // tendermintUpdate set: {} -> {} validators[0] = keeper.UpdateValidator(ctx, validators[0]) validators[1] = keeper.UpdateValidator(ctx, validators[1]) - assert.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) + require.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) } func TestGetTendermintUpdatesSingleValueChange(t *testing.T) { @@ -550,7 +550,7 @@ func TestGetTendermintUpdatesSingleValueChange(t *testing.T) { validators[0] = keeper.UpdateValidator(ctx, validators[0]) validators[1] = keeper.UpdateValidator(ctx, validators[1]) keeper.ClearTendermintUpdates(ctx) - assert.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) + require.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) // test single value change // tendermintUpdate set: {} -> {c1'} @@ -560,7 +560,7 @@ func TestGetTendermintUpdatesSingleValueChange(t *testing.T) { updates := keeper.GetTendermintUpdates(ctx) require.Equal(t, 1, len(updates)) - assert.Equal(t, validators[0].ABCIValidator(), updates[0]) + require.Equal(t, validators[0].ABCIValidator(), updates[0]) } func TestGetTendermintUpdatesMultipleValueChange(t *testing.T) { @@ -577,7 +577,7 @@ func TestGetTendermintUpdatesMultipleValueChange(t *testing.T) { validators[0] = keeper.UpdateValidator(ctx, validators[0]) validators[1] = keeper.UpdateValidator(ctx, validators[1]) keeper.ClearTendermintUpdates(ctx) - assert.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) + require.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) // test multiple value change // tendermintUpdate set: {c1, c3} -> {c1', c3'} @@ -608,7 +608,7 @@ func TestGetTendermintUpdatesInserted(t *testing.T) { validators[0] = keeper.UpdateValidator(ctx, validators[0]) validators[1] = keeper.UpdateValidator(ctx, validators[1]) keeper.ClearTendermintUpdates(ctx) - assert.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) + require.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) // test validtor added at the beginning // tendermintUpdate set: {} -> {c0} @@ -651,7 +651,7 @@ func TestGetTendermintUpdatesNotValidatorCliff(t *testing.T) { validators[0] = keeper.UpdateValidator(ctx, validators[0]) validators[1] = keeper.UpdateValidator(ctx, validators[1]) keeper.ClearTendermintUpdates(ctx) - assert.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) + require.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) // test validator added at the end but not inserted in the valset // tendermintUpdate set: {} -> {} @@ -662,7 +662,7 @@ func TestGetTendermintUpdatesNotValidatorCliff(t *testing.T) { // test validator change its power and become a gotValidator (pushing out an existing) // tendermintUpdate set: {} -> {c0, c4} keeper.ClearTendermintUpdates(ctx) - assert.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) + require.Equal(t, 0, len(keeper.GetTendermintUpdates(ctx))) pool := keeper.GetPool(ctx) validators[2], pool, _ = validators[2].AddTokensFromDel(pool, 10) diff --git a/x/stake/types/msg_test.go b/x/stake/types/msg_test.go index 343ceb79f3..f3d8bc686f 100644 --- a/x/stake/types/msg_test.go +++ b/x/stake/types/msg_test.go @@ -3,7 +3,6 @@ package types import ( "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" @@ -39,9 +38,9 @@ func TestMsgCreateValidator(t *testing.T) { description := NewDescription(tc.moniker, tc.identity, tc.website, tc.details) msg := NewMsgCreateValidator(tc.validatorAddr, tc.pubkey, tc.bond, description) if tc.expectPass { - assert.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) + require.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) } else { - assert.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) + require.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) } } } @@ -63,9 +62,9 @@ func TestMsgEditValidator(t *testing.T) { description := NewDescription(tc.moniker, tc.identity, tc.website, tc.details) msg := NewMsgEditValidator(tc.validatorAddr, description) if tc.expectPass { - assert.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) + require.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) } else { - assert.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) + require.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) } } } @@ -90,9 +89,9 @@ func TestMsgDelegate(t *testing.T) { for _, tc := range tests { msg := NewMsgDelegate(tc.delegatorAddr, tc.validatorAddr, tc.bond) if tc.expectPass { - assert.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) + require.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) } else { - assert.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) + require.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) } } } @@ -219,8 +218,8 @@ func TestMsgCompleteUnbonding(t *testing.T) { //var tx sdk.Tx //bs := wire.BinaryBytes(tc.tx) //err := wire.ReadBinaryBytes(bs, &tx) -//if assert.NoError(t, err, "%d", i) { -//assert.Equal(t, tc.tx, tx, "%d", i) +//if require.NoError(t, err, "%d", i) { +//require.Equal(t, tc.tx, tx, "%d", i) //} //} //} diff --git a/x/stake/types/pool_test.go b/x/stake/types/pool_test.go index 21dd4ff4d8..a62c69d468 100644 --- a/x/stake/types/pool_test.go +++ b/x/stake/types/pool_test.go @@ -3,7 +3,6 @@ package types import ( "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" @@ -66,48 +65,48 @@ func TestAddTokensBonded(t *testing.T) { poolA := InitialPool() poolA.LooseTokens = 10 - assert.Equal(t, poolA.BondedShareExRate(), sdk.OneRat()) + require.Equal(t, poolA.BondedShareExRate(), sdk.OneRat()) poolB, sharesB := poolA.addTokensBonded(10) - assert.Equal(t, poolB.BondedShareExRate(), sdk.OneRat()) + require.Equal(t, poolB.BondedShareExRate(), sdk.OneRat()) // correct changes to bonded shares and bonded pool - assert.Equal(t, poolB.BondedShares, poolA.BondedShares.Add(sharesB.Amount)) - assert.Equal(t, poolB.BondedTokens, poolA.BondedTokens+10) + require.Equal(t, poolB.BondedShares, poolA.BondedShares.Add(sharesB.Amount)) + require.Equal(t, poolB.BondedTokens, poolA.BondedTokens+10) // same number of bonded shares / tokens when exchange rate is one - assert.True(t, poolB.BondedShares.Equal(sdk.NewRat(poolB.BondedTokens))) + require.True(t, poolB.BondedShares.Equal(sdk.NewRat(poolB.BondedTokens))) } func TestRemoveSharesBonded(t *testing.T) { poolA := InitialPool() poolA.LooseTokens = 10 - assert.Equal(t, poolA.BondedShareExRate(), sdk.OneRat()) + require.Equal(t, poolA.BondedShareExRate(), sdk.OneRat()) poolB, tokensB := poolA.removeSharesBonded(sdk.NewRat(10)) - assert.Equal(t, poolB.BondedShareExRate(), sdk.OneRat()) + require.Equal(t, poolB.BondedShareExRate(), sdk.OneRat()) // correct changes to bonded shares and bonded pool - assert.Equal(t, poolB.BondedShares, poolA.BondedShares.Sub(sdk.NewRat(10))) - assert.Equal(t, poolB.BondedTokens, poolA.BondedTokens-tokensB) + require.Equal(t, poolB.BondedShares, poolA.BondedShares.Sub(sdk.NewRat(10))) + require.Equal(t, poolB.BondedTokens, poolA.BondedTokens-tokensB) // same number of bonded shares / tokens when exchange rate is one - assert.True(t, poolB.BondedShares.Equal(sdk.NewRat(poolB.BondedTokens))) + require.True(t, poolB.BondedShares.Equal(sdk.NewRat(poolB.BondedTokens))) } func TestAddTokensUnbonded(t *testing.T) { poolA := InitialPool() poolA.LooseTokens = 10 - assert.Equal(t, poolA.UnbondedShareExRate(), sdk.OneRat()) + require.Equal(t, poolA.UnbondedShareExRate(), sdk.OneRat()) poolB, sharesB := poolA.addTokensUnbonded(10) - assert.Equal(t, poolB.UnbondedShareExRate(), sdk.OneRat()) + require.Equal(t, poolB.UnbondedShareExRate(), sdk.OneRat()) // correct changes to unbonded shares and unbonded pool - assert.Equal(t, poolB.UnbondedShares, poolA.UnbondedShares.Add(sharesB.Amount)) - assert.Equal(t, poolB.UnbondedTokens, poolA.UnbondedTokens+10) + require.Equal(t, poolB.UnbondedShares, poolA.UnbondedShares.Add(sharesB.Amount)) + require.Equal(t, poolB.UnbondedTokens, poolA.UnbondedTokens+10) // same number of unbonded shares / tokens when exchange rate is one - assert.True(t, poolB.UnbondedShares.Equal(sdk.NewRat(poolB.UnbondedTokens))) + require.True(t, poolB.UnbondedShares.Equal(sdk.NewRat(poolB.UnbondedTokens))) } func TestRemoveSharesUnbonded(t *testing.T) { @@ -115,14 +114,14 @@ func TestRemoveSharesUnbonded(t *testing.T) { poolA := InitialPool() poolA.UnbondedTokens = 10 poolA.UnbondedShares = sdk.NewRat(10) - assert.Equal(t, poolA.UnbondedShareExRate(), sdk.OneRat()) + require.Equal(t, poolA.UnbondedShareExRate(), sdk.OneRat()) poolB, tokensB := poolA.removeSharesUnbonded(sdk.NewRat(10)) - assert.Equal(t, poolB.UnbondedShareExRate(), sdk.OneRat()) + require.Equal(t, poolB.UnbondedShareExRate(), sdk.OneRat()) // correct changes to unbonded shares and bonded pool - assert.Equal(t, poolB.UnbondedShares, poolA.UnbondedShares.Sub(sdk.NewRat(10))) - assert.Equal(t, poolB.UnbondedTokens, poolA.UnbondedTokens-tokensB) + require.Equal(t, poolB.UnbondedShares, poolA.UnbondedShares.Sub(sdk.NewRat(10))) + require.Equal(t, poolB.UnbondedTokens, poolA.UnbondedTokens-tokensB) // same number of unbonded shares / tokens when exchange rate is one - assert.True(t, poolB.UnbondedShares.Equal(sdk.NewRat(poolB.UnbondedTokens))) + require.True(t, poolB.UnbondedShares.Equal(sdk.NewRat(poolB.UnbondedTokens))) } diff --git a/x/stake/types/validator_test.go b/x/stake/types/validator_test.go index 2af3ace407..6a8ff777a6 100644 --- a/x/stake/types/validator_test.go +++ b/x/stake/types/validator_test.go @@ -18,10 +18,10 @@ func TestAddTokensValidatorBonded(t *testing.T) { val, pool = val.UpdateStatus(pool, sdk.Bonded) val, pool, delShares := val.AddTokensFromDel(pool, 10) - assert.Equal(t, sdk.OneRat(), val.DelegatorShareExRate(pool)) - assert.Equal(t, sdk.OneRat(), pool.BondedShareExRate()) - assert.Equal(t, sdk.OneRat(), pool.UnbondingShareExRate()) - assert.Equal(t, sdk.OneRat(), pool.UnbondedShareExRate()) + require.Equal(t, sdk.OneRat(), val.DelegatorShareExRate(pool)) + require.Equal(t, sdk.OneRat(), pool.BondedShareExRate()) + require.Equal(t, sdk.OneRat(), pool.UnbondingShareExRate()) + require.Equal(t, sdk.OneRat(), pool.UnbondedShareExRate()) assert.True(sdk.RatEq(t, sdk.NewRat(10), delShares)) assert.True(sdk.RatEq(t, sdk.NewRat(10), val.PoolShares.Bonded())) @@ -34,10 +34,10 @@ func TestAddTokensValidatorUnbonding(t *testing.T) { val, pool = val.UpdateStatus(pool, sdk.Unbonding) val, pool, delShares := val.AddTokensFromDel(pool, 10) - assert.Equal(t, sdk.OneRat(), val.DelegatorShareExRate(pool)) - assert.Equal(t, sdk.OneRat(), pool.BondedShareExRate()) - assert.Equal(t, sdk.OneRat(), pool.UnbondingShareExRate()) - assert.Equal(t, sdk.OneRat(), pool.UnbondedShareExRate()) + require.Equal(t, sdk.OneRat(), val.DelegatorShareExRate(pool)) + require.Equal(t, sdk.OneRat(), pool.BondedShareExRate()) + require.Equal(t, sdk.OneRat(), pool.UnbondingShareExRate()) + require.Equal(t, sdk.OneRat(), pool.UnbondedShareExRate()) assert.True(sdk.RatEq(t, sdk.NewRat(10), delShares)) assert.True(sdk.RatEq(t, sdk.NewRat(10), val.PoolShares.Unbonding())) @@ -50,10 +50,10 @@ func TestAddTokensValidatorUnbonded(t *testing.T) { val, pool = val.UpdateStatus(pool, sdk.Unbonded) val, pool, delShares := val.AddTokensFromDel(pool, 10) - assert.Equal(t, sdk.OneRat(), val.DelegatorShareExRate(pool)) - assert.Equal(t, sdk.OneRat(), pool.BondedShareExRate()) - assert.Equal(t, sdk.OneRat(), pool.UnbondingShareExRate()) - assert.Equal(t, sdk.OneRat(), pool.UnbondedShareExRate()) + require.Equal(t, sdk.OneRat(), val.DelegatorShareExRate(pool)) + require.Equal(t, sdk.OneRat(), pool.BondedShareExRate()) + require.Equal(t, sdk.OneRat(), pool.UnbondingShareExRate()) + require.Equal(t, sdk.OneRat(), pool.UnbondedShareExRate()) assert.True(sdk.RatEq(t, sdk.NewRat(10), delShares)) assert.True(sdk.RatEq(t, sdk.NewRat(10), val.PoolShares.Unbonded())) @@ -71,17 +71,17 @@ func TestRemoveDelShares(t *testing.T) { } poolA.BondedTokens = valA.PoolShares.Bonded().Evaluate() poolA.BondedShares = valA.PoolShares.Bonded() - assert.Equal(t, valA.DelegatorShareExRate(poolA), sdk.OneRat()) - assert.Equal(t, poolA.BondedShareExRate(), sdk.OneRat()) - assert.Equal(t, poolA.UnbondedShareExRate(), sdk.OneRat()) + require.Equal(t, valA.DelegatorShareExRate(poolA), sdk.OneRat()) + require.Equal(t, poolA.BondedShareExRate(), sdk.OneRat()) + require.Equal(t, poolA.UnbondedShareExRate(), sdk.OneRat()) valB, poolB, coinsB := valA.RemoveDelShares(poolA, sdk.NewRat(10)) // coins were created - assert.Equal(t, coinsB, int64(10)) + require.Equal(t, coinsB, int64(10)) // pool shares were removed - assert.Equal(t, valB.PoolShares.Bonded(), valA.PoolShares.Bonded().Sub(sdk.NewRat(10).Mul(valA.DelegatorShareExRate(poolA)))) + require.Equal(t, valB.PoolShares.Bonded(), valA.PoolShares.Bonded().Sub(sdk.NewRat(10).Mul(valA.DelegatorShareExRate(poolA)))) // conservation of tokens - assert.Equal(t, poolB.UnbondedTokens+poolB.BondedTokens+coinsB, poolA.UnbondedTokens+poolA.BondedTokens) + require.Equal(t, poolB.UnbondedTokens+poolB.BondedTokens+coinsB, poolA.UnbondedTokens+poolA.BondedTokens) // specific case from random tests poolShares := sdk.NewRat(5102) @@ -117,28 +117,28 @@ func TestUpdateStatus(t *testing.T) { val := NewValidator(addr1, pk1, Description{}) val, pool, _ = val.AddTokensFromDel(pool, 100) - assert.Equal(t, int64(0), val.PoolShares.Bonded().Evaluate()) - assert.Equal(t, int64(0), val.PoolShares.Unbonding().Evaluate()) - assert.Equal(t, int64(100), val.PoolShares.Unbonded().Evaluate()) - assert.Equal(t, int64(0), pool.BondedTokens) - assert.Equal(t, int64(0), pool.UnbondingTokens) - assert.Equal(t, int64(100), pool.UnbondedTokens) + require.Equal(t, int64(0), val.PoolShares.Bonded().Evaluate()) + require.Equal(t, int64(0), val.PoolShares.Unbonding().Evaluate()) + require.Equal(t, int64(100), val.PoolShares.Unbonded().Evaluate()) + require.Equal(t, int64(0), pool.BondedTokens) + require.Equal(t, int64(0), pool.UnbondingTokens) + require.Equal(t, int64(100), pool.UnbondedTokens) val, pool = val.UpdateStatus(pool, sdk.Unbonding) - assert.Equal(t, int64(0), val.PoolShares.Bonded().Evaluate()) - assert.Equal(t, int64(100), val.PoolShares.Unbonding().Evaluate()) - assert.Equal(t, int64(0), val.PoolShares.Unbonded().Evaluate()) - assert.Equal(t, int64(0), pool.BondedTokens) - assert.Equal(t, int64(100), pool.UnbondingTokens) - assert.Equal(t, int64(0), pool.UnbondedTokens) + require.Equal(t, int64(0), val.PoolShares.Bonded().Evaluate()) + require.Equal(t, int64(100), val.PoolShares.Unbonding().Evaluate()) + require.Equal(t, int64(0), val.PoolShares.Unbonded().Evaluate()) + require.Equal(t, int64(0), pool.BondedTokens) + require.Equal(t, int64(100), pool.UnbondingTokens) + require.Equal(t, int64(0), pool.UnbondedTokens) val, pool = val.UpdateStatus(pool, sdk.Bonded) - assert.Equal(t, int64(100), val.PoolShares.Bonded().Evaluate()) - assert.Equal(t, int64(0), val.PoolShares.Unbonding().Evaluate()) - assert.Equal(t, int64(0), val.PoolShares.Unbonded().Evaluate()) - assert.Equal(t, int64(100), pool.BondedTokens) - assert.Equal(t, int64(0), pool.UnbondingTokens) - assert.Equal(t, int64(0), pool.UnbondedTokens) + require.Equal(t, int64(100), val.PoolShares.Bonded().Evaluate()) + require.Equal(t, int64(0), val.PoolShares.Unbonding().Evaluate()) + require.Equal(t, int64(0), val.PoolShares.Unbonded().Evaluate()) + require.Equal(t, int64(100), pool.BondedTokens) + require.Equal(t, int64(0), pool.UnbondingTokens) + require.Equal(t, int64(0), pool.UnbondedTokens) } func TestPossibleOverflow(t *testing.T) { From 2f508f5b2852c3f08bb6c332d58aae4a01bb593e Mon Sep 17 00:00:00 2001 From: Rigel Date: Fri, 29 Jun 2018 22:04:29 -0400 Subject: [PATCH 6/9] Merge PR #1422: Add Contributing Guidelines * Merge pull request #1422: Add Contributing Guidelines * cwgoes comments --- CHANGELOG.md | 1 + CONTRIBUTING.md | 105 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 6393dd4d53..ae0759e5a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -79,6 +79,7 @@ IMPROVEMENTS * [stake] edit-validator changes now can use the keyword [do-not-modify] to not modify unspecified `--flag` (aka won't set them to `""` value) * [types] added common tag constants * [stake] offload more generic functionality from the handler into the keeper +* added contributing guidelines ## 0.19.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000..c9831cc865 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,105 @@ +# Contributing + +Thank you for considering making contributions to Cosmos-SDK and related repositories! Start by taking a look at this [coding repo](https://github.com/tendermint/coding) for overall information on repository workflow and standards. + +Please follow standard github best practices: fork the repo, branch from the tip of develop, make some commits, and submit a pull request to develop. See the [open issues](https://github.com/cosmos/cosmos-sdk/issues) for things we need help with! + +Please make sure to use `gofmt` before every commit - the easiest way to do this is have your editor run it for you upon saving a file. Additionally please ensure that your code is lint compliant by running `make lint` + +Looking for a good place to start contributing? How about checking out some [good first issues](https://github.com/cosmos/cosmos-sdk/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) + +## Forking + +Please note that Go requires code to live under absolute paths, which complicates forking. +While my fork lives at `https://github.com/rigeyrigerige/cosmos-sdk`, +the code should never exist at `$GOPATH/src/github.com/rigeyrigerige/cosmos-sdk`. +Instead, we use `git remote` to add the fork as a new remote for the original repo, +`$GOPATH/src/github.com/cosmos/cosmos-sdk `, and do all the work there. + +For instance, to create a fork and work on a branch of it, I would: + + * Create the fork on github, using the fork button. + * Go to the original repo checked out locally (i.e. `$GOPATH/src/github.com/cosmos/cosmos-sdk`) + * `git remote rename origin upstream` + * `git remote add origin git@github.com:ebuchman/basecoin.git` + +Now `origin` refers to my fork and `upstream` refers to the Cosmos-SDK version. +So I can `git push -u origin master` to update my fork, and make pull requests to Cosmos-SDK from there. +Of course, replace `ebuchman` with your git handle. + +To pull in updates from the origin repo, run + + * `git fetch upstream` + * `git rebase upstream/master` (or whatever branch you want) + +Please don't make Pull Requests to `master`. + +## Dependencies + +We use [dep](https://github.com/golang/dep) to manage dependencies. + +That said, the master branch of every Cosmos repository should just build +with `go get`, which means they should be kept up-to-date with their +dependencies so we can get away with telling people they can just `go get` our +software. + +Since some dependencies are not under our control, a third party may break our +build, in which case we can fall back on `dep ensure` (or `make +get_vendor_deps`). Even for dependencies under our control, dep helps us to +keep multiple repos in sync as they evolve. Anything with an executable, such +as apps, tools, and the core, should use dep. + +Run `dep status` to get a list of vendor dependencies that may not be +up-to-date. + +## Testing + +All repos should be hooked up to [CircleCI](https://circleci.com/). + +If they have `.go` files in the root directory, they will be automatically +tested by circle using `go test -v -race ./...`. If not, they will need a +`circle.yml`. Ideally, every repo has a `Makefile` that defines `make test` and +includes its continuous integration status using a badge in the `README.md`. + +## Branching Model and Release + +User-facing repos should adhere to the branching model: http://nvie.com/posts/a-successful-git-branching-model/. +That is, these repos should be well versioned, and any merge to master requires a version bump and tagged release. + +Libraries need not follow the model strictly, but would be wise to. + +The SDK utilizes [semantic versioning](https://semver.org/). + +### Development Procedure: +- the latest state of development is on `develop` +- `develop` must never fail `make test` or `make test_cli` +- `develop` should not fail `make test_lint` +- no --force onto `develop` (except when reverting a broken commit, which should seldom happen) +- create a development branch either on github.com/cosmos/cosmos-sdk, or your fork (using `git remote add origin`) +- before submitting a pull request, begin `git rebase` on top of `develop` + +### Pull Merge Procedure: +- ensure pull branch is rebased on develop +- run `make test` and `make test_cli` to ensure that all tests pass +- merge pull request +- push master may request that pull requests be rebased on top of `unstable` + +### Release Procedure: +- start on `develop` +- prepare changelog/release issue +- bump versions +- push to release-vX.X.X to run CI +- merge to master +- merge master back to develop + +### Hotfix Procedure: +- start on `master` +- checkout a new branch named hotfix-vX.X.X +- make the required changes + - these changes should be small and an absolute necessity + - add a note to CHANGELOG.md +- bump versions +- push to hotfix-vX.X.X to run the extended integration tests on the CI +- merge hotfix-vX.X.X to master +- merge hotfix-vX.X.X to develop +- delete the hotfix-vX.X.X branch From 3654579ea79473f7f306816f4fe0c3e0437c6d58 Mon Sep 17 00:00:00 2001 From: Christopher Goes Date: Sat, 30 Jun 2018 05:34:55 +0200 Subject: [PATCH 7/9] Merge PR #1278: Slashing v2 Implement semifinal Gaia slashing spec (#1263), less #1348, #1378, and #1440 which are TBD. --- .circleci/config.yml | 3 +- CHANGELOG.md | 7 + Gopkg.lock | 2 +- client/lcd/lcd_test.go | 24 ++ client/lcd/root.go | 2 + docs/spec/slashing/end_block.md | 53 +-- examples/democoin/mock/validator.go | 7 +- types/stake.go | 8 +- x/slashing/client/rest/query.go | 62 ++++ x/slashing/client/rest/rest.go | 15 + x/slashing/client/rest/tx.go | 103 ++++++ x/slashing/handler.go | 2 +- x/slashing/keeper.go | 35 +- x/slashing/keeper_test.go | 83 +++-- x/slashing/params.go | 17 +- x/slashing/tick.go | 28 +- x/slashing/tick_test.go | 8 +- x/stake/handler_test.go | 85 ++++- x/stake/keeper/delegation.go | 54 +++- x/stake/keeper/slash.go | 236 ++++++++++++-- x/stake/keeper/slash_test.go | 481 ++++++++++++++++++++++++++++ x/stake/types/delegation.go | 3 + x/stake/types/validator.go | 1 + 23 files changed, 1197 insertions(+), 122 deletions(-) create mode 100644 x/slashing/client/rest/query.go create mode 100644 x/slashing/client/rest/rest.go create mode 100644 x/slashing/client/rest/tx.go create mode 100644 x/stake/keeper/slash_test.go diff --git a/.circleci/config.yml b/.circleci/config.yml index d58cbad5fc..cf679fe75f 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -101,7 +101,7 @@ jobs: test_cover: <<: *defaults - parallelism: 1 + parallelism: 2 steps: - attach_workspace: at: /tmp/workspace @@ -126,6 +126,7 @@ jobs: upload_coverage: <<: *defaults + parallelism: 1 steps: - attach_workspace: at: /tmp/workspace diff --git a/CHANGELOG.md b/CHANGELOG.md index ae0759e5a1..e0b543247a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,13 @@ BREAKING CHANGES * `gaiacli stake complete-unbonding` * `gaiacli stake begin-redelegation` * `gaiacli stake complete-redelegation` +* [slashing] update slashing for unbonding period + * Slash according to power at time of infraction instead of power at + time of discovery + * Iterate through unbonding delegations & redelegations which contributed + to an infraction, slash them proportional to their stake at the time + * Add REST endpoint to unrevoke a validator previously revoked for downtime + * Add REST endpoint to retrieve liveness signing information for a validator FEATURES * [gaiacli] You can now attach a simple text-only memo to any transaction, with the `--memo` flag diff --git a/Gopkg.lock b/Gopkg.lock index a974602f74..c48188cb8d 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -443,7 +443,7 @@ "netutil", "trace" ] - revision = "e514e69ffb8bc3c76a71ae40de0118d794855992" + revision = "97aa3a539ec716117a9d15a4659a911f50d13c3c" [[projects]] branch = "master" diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 37d7e91916..049fa04bef 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -25,6 +25,7 @@ import ( "github.com/cosmos/cosmos-sdk/wire" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/stake" stakerest "github.com/cosmos/cosmos-sdk/x/stake/client/rest" ) @@ -521,6 +522,19 @@ func TestVote(t *testing.T) { require.Equal(t, gov.VoteOptionToString(gov.OptionYes), vote.Option) } +func TestUnrevoke(t *testing.T) { + _, password := "test", "1234567890" + addr, _ := CreateAddr(t, "test", password, GetKB(t)) + cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.Address{addr}) + defer cleanup() + + signingInfo := getSigningInfo(t, port, pks[0].Address()) + tests.WaitForHeight(4, port) + require.Equal(t, true, signingInfo.IndexOffset > 0) + require.Equal(t, int64(0), signingInfo.JailedUntil) + require.Equal(t, true, signingInfo.SignedBlocksCounter > 0) +} + func TestProposalsQuery(t *testing.T) { name, password1 := "test", "1234567890" name2, password2 := "test2", "1234567890" @@ -679,6 +693,16 @@ func doIBCTransfer(t *testing.T, port, seed, name, password string, addr sdk.Add return resultTx } +func getSigningInfo(t *testing.T, port string, validatorAddr sdk.Address) slashing.ValidatorSigningInfo { + validatorAddrBech := sdk.MustBech32ifyVal(validatorAddr) + res, body := Request(t, port, "GET", "/slashing/signing_info/"+validatorAddrBech, nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + var signingInfo slashing.ValidatorSigningInfo + err := cdc.UnmarshalJSON([]byte(body), &signingInfo) + require.Nil(t, err) + return signingInfo +} + func getDelegation(t *testing.T, port string, delegatorAddr, validatorAddr sdk.Address) stake.Delegation { delegatorAddrBech := sdk.MustBech32ifyAcc(delegatorAddr) diff --git a/client/lcd/root.go b/client/lcd/root.go index d84e7d9f1c..472c914060 100644 --- a/client/lcd/root.go +++ b/client/lcd/root.go @@ -22,6 +22,7 @@ import ( bank "github.com/cosmos/cosmos-sdk/x/bank/client/rest" gov "github.com/cosmos/cosmos-sdk/x/gov/client/rest" ibc "github.com/cosmos/cosmos-sdk/x/ibc/client/rest" + slashing "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" stake "github.com/cosmos/cosmos-sdk/x/stake/client/rest" ) @@ -84,6 +85,7 @@ func createHandler(cdc *wire.Codec) http.Handler { bank.RegisterRoutes(ctx, r, cdc, kb) ibc.RegisterRoutes(ctx, r, cdc, kb) stake.RegisterRoutes(ctx, r, cdc, kb) + slashing.RegisterRoutes(ctx, r, cdc, kb) gov.RegisterRoutes(ctx, r, cdc) return r } diff --git a/docs/spec/slashing/end_block.md b/docs/spec/slashing/end_block.md index 6ac24138ba..e923fd8444 100644 --- a/docs/spec/slashing/end_block.md +++ b/docs/spec/slashing/end_block.md @@ -15,33 +15,28 @@ For some `evidence` to be valid, it must satisfy: where `evidence.Timestamp` is the timestamp in the block at height `evidence.Height` and `block.Timestamp` is the current block timestamp. -If valid evidence is included in a block, the validator's stake is reduced by `SLASH_PROPORTION` of -what their stake was when the equivocation occurred (rather than when the evidence was discovered): +If valid evidence is included in a block, the validator's stake is reduced by `SLASH_PROPORTION` of +what their stake was when the infraction occurred (rather than when the evidence was discovered). +We want to "follow the stake": the stake which contributed to the infraction should be +slashed, even if it has since been redelegated or started unbonding. + +We first need to loop through the unbondings and redelegations from the slashed validator +and track how much stake has since moved: ``` -curVal := validator -oldVal := loadValidator(evidence.Height, evidence.Address) +slashAmountUnbondings := 0 +slashAmountRedelegations := 0 -slashAmount := SLASH_PROPORTION * oldVal.Shares - -curVal.Shares = max(0, curVal.Shares - slashAmount) -``` - -This ensures that offending validators are punished the same amount whether they -act as a single validator with X stake or as N validators with collectively X -stake. - -We also need to loop through the unbondings and redelegations to slash them as -well: - -``` unbondings := getUnbondings(validator.Address) for unbond in unbondings { - if was not bonded before evidence.Height { + + if was not bonded before evidence.Height or started unbonding before unbonding period ago { continue } - unbond.InitialTokens + burn := unbond.InitialTokens * SLASH_PROPORTION + slashAmountUnbondings += burn + unbond.Tokens = max(0, unbond.Tokens - burn) } @@ -51,17 +46,35 @@ for unbond in unbondings { redels := getRedelegationsBySource(validator.Address) for redel in redels { - if was not bonded before evidence.Height { + if was not bonded before evidence.Height or started redelegating before unbonding period ago { continue } burn := redel.InitialTokens * SLASH_PROPORTION + slashAmountRedelegations += burn amount := unbondFromValidator(redel.Destination, burn) destroy(amount) } ``` +We then slash the validator: + +``` +curVal := validator +oldVal := loadValidator(evidence.Height, evidence.Address) + +slashAmount := SLASH_PROPORTION * oldVal.Shares +slashAmount -= slashAmountUnbondings +slashAmount -= slashAmountRedelegations + +curVal.Shares = max(0, curVal.Shares - slashAmount) +``` + +This ensures that offending validators are punished the same amount whether they +act as a single validator with X stake or as N validators with collectively X +stake. + ## Automatic Unbonding At the beginning of each block, we update the signing info for each validator and check if they should be automatically unbonded: diff --git a/examples/democoin/mock/validator.go b/examples/democoin/mock/validator.go index 869c48dcb6..8b1d34c7b4 100644 --- a/examples/democoin/mock/validator.go +++ b/examples/democoin/mock/validator.go @@ -38,6 +38,11 @@ func (v Validator) GetDelegatorShares() sdk.Rat { return sdk.ZeroRat() } +// Implements sdk.Validator +func (v Validator) GetRevoked() bool { + return false +} + // Implements sdk.Validator func (v Validator) GetBondHeight() int64 { return 0 @@ -107,7 +112,7 @@ func (vs *ValidatorSet) RemoveValidator(addr sdk.Address) { } // Implements sdk.ValidatorSet -func (vs *ValidatorSet) Slash(ctx sdk.Context, pubkey crypto.PubKey, height int64, amt sdk.Rat) { +func (vs *ValidatorSet) Slash(ctx sdk.Context, pubkey crypto.PubKey, height int64, power int64, amt sdk.Rat) { panic("not implemented") } diff --git a/types/stake.go b/types/stake.go index 0f0855b37f..8625b617e5 100644 --- a/types/stake.go +++ b/types/stake.go @@ -32,6 +32,7 @@ func BondStatusToString(b BondStatus) string { // validator for a delegated proof of stake system type Validator interface { + GetRevoked() bool // whether the validator is revoked GetMoniker() string // moniker of the validator GetStatus() BondStatus // status of the validator GetOwner() Address // owner address to receive/return validators coins @@ -62,9 +63,10 @@ type ValidatorSet interface { Validator(Context, Address) Validator // get a particular validator by owner address TotalPower(Context) Rat // total power of the validator set - Slash(Context, crypto.PubKey, int64, Rat) // slash the validator and delegators of the validator, specifying offence height & slash fraction - Revoke(Context, crypto.PubKey) // revoke a validator - Unrevoke(Context, crypto.PubKey) // unrevoke a validator + // slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction + Slash(Context, crypto.PubKey, int64, int64, Rat) + Revoke(Context, crypto.PubKey) // revoke a validator + Unrevoke(Context, crypto.PubKey) // unrevoke a validator } //_______________________________________________________________________________ diff --git a/x/slashing/client/rest/query.go b/x/slashing/client/rest/query.go new file mode 100644 index 0000000000..9842ada732 --- /dev/null +++ b/x/slashing/client/rest/query.go @@ -0,0 +1,62 @@ +package rest + +import ( + "fmt" + "net/http" + + "github.com/gorilla/mux" + + "github.com/cosmos/cosmos-sdk/client/context" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/x/slashing" +) + +func registerQueryRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec) { + r.HandleFunc( + "/slashing/signing_info/{validator}", + signingInfoHandlerFn(ctx, "slashing", cdc), + ).Methods("GET") +} + +// http request handler to query signing info +func signingInfoHandlerFn(ctx context.CoreContext, storeName string, cdc *wire.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + // read parameters + vars := mux.Vars(r) + bech32validator := vars["validator"] + + validatorAddr, err := sdk.GetValAddressBech32(bech32validator) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + + key := slashing.GetValidatorSigningInfoKey(validatorAddr) + res, err := ctx.QueryStore(key, storeName) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't query signing info. Error: %s", err.Error()))) + return + } + + var signingInfo slashing.ValidatorSigningInfo + err = cdc.UnmarshalBinary(res, &signingInfo) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("couldn't decode signing info. Error: %s", err.Error()))) + return + } + + output, err := cdc.MarshalJSON(signingInfo) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + w.Write(output) + } +} diff --git a/x/slashing/client/rest/rest.go b/x/slashing/client/rest/rest.go new file mode 100644 index 0000000000..156d400334 --- /dev/null +++ b/x/slashing/client/rest/rest.go @@ -0,0 +1,15 @@ +package rest + +import ( + "github.com/gorilla/mux" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/crypto/keys" + "github.com/cosmos/cosmos-sdk/wire" +) + +// RegisterRoutes registers staking-related REST handlers to a router +func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { + registerQueryRoutes(ctx, r, cdc) + registerTxRoutes(ctx, r, cdc, kb) +} diff --git a/x/slashing/client/rest/tx.go b/x/slashing/client/rest/tx.go new file mode 100644 index 0000000000..212487ddf1 --- /dev/null +++ b/x/slashing/client/rest/tx.go @@ -0,0 +1,103 @@ +package rest + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + + "github.com/gorilla/mux" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/crypto/keys" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/wire" + "github.com/cosmos/cosmos-sdk/x/slashing" +) + +func registerTxRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { + r.HandleFunc( + "/slashing/unrevoke", + unrevokeRequestHandlerFn(cdc, kb, ctx), + ).Methods("POST") +} + +// Unrevoke TX body +type UnrevokeBody struct { + LocalAccountName string `json:"name"` + Password string `json:"password"` + ChainID string `json:"chain_id"` + AccountNumber int64 `json:"account_number"` + Sequence int64 `json:"sequence"` + Gas int64 `json:"gas"` + ValidatorAddr string `json:"validator_addr"` +} + +func unrevokeRequestHandlerFn(cdc *wire.Codec, kb keys.Keybase, ctx context.CoreContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var m UnrevokeBody + body, err := ioutil.ReadAll(r.Body) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + err = json.Unmarshal(body, &m) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(err.Error())) + return + } + + info, err := kb.Get(m.LocalAccountName) + if err != nil { + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte(err.Error())) + return + } + + validatorAddr, err := sdk.GetAccAddressBech32(m.ValidatorAddr) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("Couldn't decode validator. Error: %s", err.Error()))) + return + } + + if !bytes.Equal(info.GetPubKey().Address(), validatorAddr) { + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte("Must use own validator address")) + return + } + + ctx = ctx.WithGas(m.Gas) + ctx = ctx.WithChainID(m.ChainID) + ctx = ctx.WithAccountNumber(m.AccountNumber) + ctx = ctx.WithSequence(m.Sequence) + + msg := slashing.NewMsgUnrevoke(validatorAddr) + + txBytes, err := ctx.SignAndBuild(m.LocalAccountName, m.Password, []sdk.Msg{msg}, cdc) + if err != nil { + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte(err.Error())) + return + } + + res, err := ctx.BroadcastTx(txBytes) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + output, err := json.MarshalIndent(res, "", " ") + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + w.Write(output) + } +} diff --git a/x/slashing/handler.go b/x/slashing/handler.go index 5994bb8f19..e786f34aca 100644 --- a/x/slashing/handler.go +++ b/x/slashing/handler.go @@ -50,7 +50,7 @@ func handleMsgUnrevoke(ctx sdk.Context, msg MsgUnrevoke, k Keeper) sdk.Result { // Unrevoke the validator k.validatorSet.Unrevoke(ctx, validator.GetPubKey()) - tags := sdk.NewTags("action", []byte("unrevoke"), "validator", msg.ValidatorAddr.Bytes()) + tags := sdk.NewTags("action", []byte("unrevoke"), "validator", []byte(msg.ValidatorAddr.String())) return sdk.Result{ Tags: tags, diff --git a/x/slashing/keeper.go b/x/slashing/keeper.go index 1d62e6daff..9ad1c1ea25 100644 --- a/x/slashing/keeper.go +++ b/x/slashing/keeper.go @@ -30,28 +30,40 @@ func NewKeeper(cdc *wire.Codec, key sdk.StoreKey, vs sdk.ValidatorSet, codespace } // handle a validator signing two blocks at the same height -func (k Keeper) handleDoubleSign(ctx sdk.Context, height int64, timestamp int64, pubkey crypto.PubKey) { +func (k Keeper) handleDoubleSign(ctx sdk.Context, pubkey crypto.PubKey, infractionHeight int64, timestamp int64, power int64) { logger := ctx.Logger().With("module", "x/slashing") - age := ctx.BlockHeader().Time - timestamp + time := ctx.BlockHeader().Time + age := time - timestamp + address := pubkey.Address() // Double sign too old if age > MaxEvidenceAge { - logger.Info(fmt.Sprintf("Ignored double sign from %s at height %d, age of %d past max age of %d", pubkey.Address(), height, age, MaxEvidenceAge)) + logger.Info(fmt.Sprintf("Ignored double sign from %s at height %d, age of %d past max age of %d", pubkey.Address(), infractionHeight, age, MaxEvidenceAge)) return } // Double sign confirmed - logger.Info(fmt.Sprintf("Confirmed double sign from %s at height %d, age of %d less than max age of %d", pubkey.Address(), height, age, MaxEvidenceAge)) - k.validatorSet.Slash(ctx, pubkey, height, SlashFractionDoubleSign) + logger.Info(fmt.Sprintf("Confirmed double sign from %s at height %d, age of %d less than max age of %d", pubkey.Address(), infractionHeight, age, MaxEvidenceAge)) + + // Slash validator + k.validatorSet.Slash(ctx, pubkey, infractionHeight, power, SlashFractionDoubleSign) + + // Revoke validator + k.validatorSet.Revoke(ctx, pubkey) + + // Jail validator + signInfo, found := k.getValidatorSigningInfo(ctx, address) + if !found { + panic(fmt.Sprintf("Expected signing info for validator %s but not found", address)) + } + signInfo.JailedUntil = time + DoubleSignUnbondDuration + k.setValidatorSigningInfo(ctx, address, signInfo) } // handle a validator signature, must be called once per validator per block -func (k Keeper) handleValidatorSignature(ctx sdk.Context, pubkey crypto.PubKey, signed bool) { +func (k Keeper) handleValidatorSignature(ctx sdk.Context, pubkey crypto.PubKey, power int64, signed bool) { logger := ctx.Logger().With("module", "x/slashing") height := ctx.BlockHeight() - if !signed { - logger.Info(fmt.Sprintf("Absent validator %s at height %d", pubkey.Address(), height)) - } address := pubkey.Address() // Local index, so counts blocks validator *should* have signed @@ -80,11 +92,14 @@ func (k Keeper) handleValidatorSignature(ctx sdk.Context, pubkey crypto.PubKey, signInfo.SignedBlocksCounter++ } + if !signed { + logger.Info(fmt.Sprintf("Absent validator %s at height %d, %d signed, threshold %d", pubkey.Address(), height, signInfo.SignedBlocksCounter, MinSignedPerWindow)) + } minHeight := signInfo.StartHeight + SignedBlocksWindow if height > minHeight && signInfo.SignedBlocksCounter < MinSignedPerWindow { // Downtime confirmed, slash, revoke, and jail the validator logger.Info(fmt.Sprintf("Validator %s past min height of %d and below signed blocks threshold of %d", pubkey.Address(), minHeight, MinSignedPerWindow)) - k.validatorSet.Slash(ctx, pubkey, height, SlashFractionDowntime) + k.validatorSet.Slash(ctx, pubkey, height, power, SlashFractionDowntime) k.validatorSet.Revoke(ctx, pubkey) signInfo.JailedUntil = ctx.BlockHeader().Time + DowntimeUnbondDuration } diff --git a/x/slashing/keeper_test.go b/x/slashing/keeper_test.go index 2a722a2bad..debeda6cca 100644 --- a/x/slashing/keeper_test.go +++ b/x/slashing/keeper_test.go @@ -11,26 +11,45 @@ import ( "github.com/cosmos/cosmos-sdk/x/stake" ) +// Have to change these parameters for tests +// lest the tests take forever +func init() { + SignedBlocksWindow = 1000 + MinSignedPerWindow = SignedBlocksWindow / 2 + DowntimeUnbondDuration = 60 * 60 + DoubleSignUnbondDuration = 60 * 60 +} + // Test that a validator is slashed correctly -// when we discover evidence of equivocation +// when we discover evidence of infraction func TestHandleDoubleSign(t *testing.T) { // initial setup ctx, ck, sk, keeper := createTestInput(t) - addr, val, amt := addrs[0], pks[0], sdk.NewInt(100) + amtInt := int64(100) + addr, val, amt := addrs[0], pks[0], sdk.NewInt(amtInt) got := stake.NewHandler(sk)(ctx, newTestMsgCreateValidator(addr, val, amt)) require.True(t, got.IsOK()) stake.EndBlocker(ctx, sk) require.Equal(t, ck.GetCoins(ctx, addr), sdk.Coins{{sk.GetParams(ctx).BondDenom, initCoins.Sub(amt)}}) require.True(t, sdk.NewRatFromInt(amt).Equal(sk.Validator(ctx, addr).GetPower())) + // handle a signature to set signing info + keeper.handleValidatorSignature(ctx, val, amtInt, true) + // double sign less than max age - keeper.handleDoubleSign(ctx, 0, 0, val) + keeper.handleDoubleSign(ctx, val, 0, 0, amtInt) + + // should be revoked + require.True(t, sk.Validator(ctx, addr).GetRevoked()) + // unrevoke to measure power + sk.Unrevoke(ctx, val) + // power should be reduced require.Equal(t, sdk.NewRatFromInt(amt).Mul(sdk.NewRat(19).Quo(sdk.NewRat(20))), sk.Validator(ctx, addr).GetPower()) - ctx = ctx.WithBlockHeader(abci.Header{Time: 300}) + ctx = ctx.WithBlockHeader(abci.Header{Time: 1 + MaxEvidenceAge}) // double sign past max age - keeper.handleDoubleSign(ctx, 0, 0, val) + keeper.handleDoubleSign(ctx, val, 0, 0, amtInt) require.Equal(t, sdk.NewRatFromInt(amt).Mul(sdk.NewRat(19).Quo(sdk.NewRat(20))), sk.Validator(ctx, addr).GetPower()) } @@ -40,7 +59,8 @@ func TestHandleAbsentValidator(t *testing.T) { // initial setup ctx, ck, sk, keeper := createTestInput(t) - addr, val, amt := addrs[0], pks[0], sdk.NewInt(100) + amtInt := int64(100) + addr, val, amt := addrs[0], pks[0], sdk.NewInt(amtInt) sh := stake.NewHandler(sk) slh := NewHandler(keeper) got := sh(ctx, newTestMsgCreateValidator(addr, val, amt)) @@ -57,38 +77,38 @@ func TestHandleAbsentValidator(t *testing.T) { height := int64(0) // 1000 first blocks OK - for ; height < 1000; height++ { + for ; height < SignedBlocksWindow; height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val, true) + keeper.handleValidatorSignature(ctx, val, amtInt, true) } info, found = keeper.getValidatorSigningInfo(ctx, val.Address()) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) require.Equal(t, SignedBlocksWindow, info.SignedBlocksCounter) - // 50 blocks missed - for ; height < 1050; height++ { + // 500 blocks missed + for ; height < SignedBlocksWindow+(SignedBlocksWindow-MinSignedPerWindow); height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val, false) + keeper.handleValidatorSignature(ctx, val, amtInt, false) } info, found = keeper.getValidatorSigningInfo(ctx, val.Address()) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) - require.Equal(t, SignedBlocksWindow-50, info.SignedBlocksCounter) + require.Equal(t, SignedBlocksWindow-MinSignedPerWindow, info.SignedBlocksCounter) // validator should be bonded still validator, _ := sk.GetValidatorByPubKey(ctx, val) require.Equal(t, sdk.Bonded, validator.GetStatus()) pool := sk.GetPool(ctx) - require.Equal(t, int64(100), pool.BondedTokens) + require.Equal(t, int64(amtInt), pool.BondedTokens) - // 51st block missed + // 501st block missed ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val, false) + keeper.handleValidatorSignature(ctx, val, amtInt, false) info, found = keeper.getValidatorSigningInfo(ctx, val.Address()) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) - require.Equal(t, SignedBlocksWindow-51, info.SignedBlocksCounter) + require.Equal(t, SignedBlocksWindow-MinSignedPerWindow-1, info.SignedBlocksCounter) // validator should have been revoked validator, _ = sk.GetValidatorByPubKey(ctx, val) @@ -99,7 +119,7 @@ func TestHandleAbsentValidator(t *testing.T) { require.False(t, got.IsOK()) // unrevocation should succeed after jail expiration - ctx = ctx.WithBlockHeader(abci.Header{Time: int64(86400 * 2)}) + ctx = ctx.WithBlockHeader(abci.Header{Time: DowntimeUnbondDuration + 1}) got = slh(ctx, NewMsgUnrevoke(addr)) require.True(t, got.IsOK()) @@ -109,26 +129,33 @@ func TestHandleAbsentValidator(t *testing.T) { // validator should have been slashed pool = sk.GetPool(ctx) - require.Equal(t, int64(99), pool.BondedTokens) + require.Equal(t, int64(amtInt-1), pool.BondedTokens) // validator start height should have been changed info, found = keeper.getValidatorSigningInfo(ctx, val.Address()) require.True(t, found) require.Equal(t, height, info.StartHeight) - require.Equal(t, SignedBlocksWindow-51, info.SignedBlocksCounter) + require.Equal(t, SignedBlocksWindow-MinSignedPerWindow-1, info.SignedBlocksCounter) // validator should not be immediately revoked again height++ ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val, false) + keeper.handleValidatorSignature(ctx, val, amtInt, false) validator, _ = sk.GetValidatorByPubKey(ctx, val) require.Equal(t, sdk.Bonded, validator.GetStatus()) - // validator should be revoked again after 100 unsigned blocks - nextHeight := height + 100 + // 500 signed blocks + nextHeight := height + MinSignedPerWindow + 1 + for ; height < nextHeight; height++ { + ctx = ctx.WithBlockHeight(height) + keeper.handleValidatorSignature(ctx, val, amtInt, false) + } + + // validator should be revoked again after 500 unsigned blocks + nextHeight = height + MinSignedPerWindow + 1 for ; height <= nextHeight; height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val, false) + keeper.handleValidatorSignature(ctx, val, amtInt, false) } validator, _ = sk.GetValidatorByPubKey(ctx, val) require.Equal(t, sdk.Unbonded, validator.GetStatus()) @@ -149,16 +176,16 @@ func TestHandleNewValidator(t *testing.T) { require.Equal(t, sdk.NewRat(amt), sk.Validator(ctx, addr).GetPower()) // 1000 first blocks not a validator - ctx = ctx.WithBlockHeight(1001) + ctx = ctx.WithBlockHeight(SignedBlocksWindow + 1) // Now a validator, for two blocks - keeper.handleValidatorSignature(ctx, val, true) - ctx = ctx.WithBlockHeight(1002) - keeper.handleValidatorSignature(ctx, val, false) + keeper.handleValidatorSignature(ctx, val, 100, true) + ctx = ctx.WithBlockHeight(SignedBlocksWindow + 2) + keeper.handleValidatorSignature(ctx, val, 100, false) info, found := keeper.getValidatorSigningInfo(ctx, val.Address()) require.True(t, found) - require.Equal(t, int64(1001), info.StartHeight) + require.Equal(t, int64(SignedBlocksWindow+1), info.StartHeight) require.Equal(t, int64(2), info.IndexOffset) require.Equal(t, int64(1), info.SignedBlocksCounter) require.Equal(t, int64(0), info.JailedUntil) diff --git a/x/slashing/params.go b/x/slashing/params.go index 3bba85fa66..ebf14f283d 100644 --- a/x/slashing/params.go +++ b/x/slashing/params.go @@ -4,7 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -const ( +var ( // MaxEvidenceAge - Max age for evidence - 21 days (3 weeks) // TODO Should this be a governance parameter or just modifiable with SoftwareUpgradeProposals? // MaxEvidenceAge = 60 * 60 * 24 * 7 * 3 @@ -13,17 +13,22 @@ const ( // SignedBlocksWindow - sliding window for downtime slashing // TODO Governance parameter? - // TODO Temporarily set to 100 blocks for testnets - SignedBlocksWindow int64 = 100 + // TODO Temporarily set to 40000 blocks for testnets + SignedBlocksWindow int64 = 40000 // Downtime slashing threshold - 50% // TODO Governance parameter? - MinSignedPerWindow int64 = SignedBlocksWindow / 2 + MinSignedPerWindow = SignedBlocksWindow / 2 // Downtime unbond duration // TODO Governance parameter? - // TODO Temporarily set to 10 minutes for testnets - DowntimeUnbondDuration int64 = 60 * 10 + // TODO Temporarily set to five minutes for testnets + DowntimeUnbondDuration int64 = 60 * 5 + + // Double-sign unbond duration + // TODO Governance parameter? + // TODO Temporarily set to five minutes for testnets + DoubleSignUnbondDuration int64 = 60 * 5 ) var ( diff --git a/x/slashing/tick.go b/x/slashing/tick.go index 43ffdb947c..01984f870b 100644 --- a/x/slashing/tick.go +++ b/x/slashing/tick.go @@ -16,7 +16,21 @@ func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, sk Keeper) (tags binary.LittleEndian.PutUint64(heightBytes, uint64(req.Header.Height)) tags = sdk.NewTags("height", heightBytes) - // Deal with any equivocation evidence + // Iterate over all the validators which *should* have signed this block + // Store whether or not they have actually signed it and slash/unbond any + // which have missed too many blocks in a row (downtime slashing) + for _, signingValidator := range req.Validators { + present := signingValidator.SignedLastBlock + pubkey, err := tmtypes.PB2TM.PubKey(signingValidator.Validator.PubKey) + if err != nil { + panic(err) + } + sk.handleValidatorSignature(ctx, pubkey, signingValidator.Validator.Power, present) + } + + // Iterate through any newly discovered evidence of infraction + // Slash any validators (and since-unbonded stake within the unbonding period) + // who contributed to valid infractions for _, evidence := range req.ByzantineValidators { pk, err := tmtypes.PB2TM.PubKey(evidence.Validator.PubKey) if err != nil { @@ -24,21 +38,11 @@ func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, sk Keeper) (tags } switch evidence.Type { case tmtypes.ABCIEvidenceTypeDuplicateVote: - sk.handleDoubleSign(ctx, evidence.Height, evidence.Time, pk) + sk.handleDoubleSign(ctx, pk, evidence.Height, evidence.Time, evidence.Validator.Power) default: ctx.Logger().With("module", "x/slashing").Error(fmt.Sprintf("ignored unknown evidence type: %s", evidence.Type)) } } - // Iterate over all the validators which *should* have signed this block - for _, validator := range req.Validators { - present := validator.SignedLastBlock - pubkey, err := tmtypes.PB2TM.PubKey(validator.Validator.PubKey) - if err != nil { - panic(err) - } - sk.handleValidatorSignature(ctx, pubkey, present) - } - return } diff --git a/x/slashing/tick_test.go b/x/slashing/tick_test.go index a5cf47de50..42a476a4ce 100644 --- a/x/slashing/tick_test.go +++ b/x/slashing/tick_test.go @@ -46,8 +46,8 @@ func TestBeginBlocker(t *testing.T) { height := int64(0) - // for 50 blocks, mark the validator as having signed - for ; height < 50; height++ { + // for 1000 blocks, mark the validator as having signed + for ; height < SignedBlocksWindow; height++ { ctx = ctx.WithBlockHeight(height) req = abci.RequestBeginBlock{ Validators: []abci.SigningValidator{{ @@ -58,8 +58,8 @@ func TestBeginBlocker(t *testing.T) { BeginBlocker(ctx, req, keeper) } - // for 51 blocks, mark the validator as having not signed - for ; height < 102; height++ { + // for 500 blocks, mark the validator as having not signed + for ; height < ((SignedBlocksWindow * 2) - MinSignedPerWindow + 1); height++ { ctx = ctx.WithBlockHeight(height) req = abci.RequestBeginBlock{ Validators: []abci.SigningValidator{{ diff --git a/x/stake/handler_test.go b/x/stake/handler_test.go index ef47318c68..e6cd6f4ca7 100644 --- a/x/stake/handler_test.go +++ b/x/stake/handler_test.go @@ -74,7 +74,7 @@ func TestValidatorByPowerIndex(t *testing.T) { require.True(t, got.IsOK(), "expected create-validator to be ok, got %v", got) // slash and revoke the first validator - keeper.Slash(ctx, keep.PKs[0], 0, sdk.NewRat(1, 2)) + keeper.Slash(ctx, keep.PKs[0], 0, initBond, sdk.NewRat(1, 2)) keeper.Revoke(ctx, keep.PKs[0]) validator, found = keeper.GetValidator(ctx, validatorAddr) require.True(t, found) @@ -559,3 +559,86 @@ func TestTransitiveRedelegation(t *testing.T) { got = handleMsgBeginRedelegate(ctx, msgBeginRedelegate, keeper) require.True(t, got.IsOK(), "expected no error") } + +func TestBondUnbondRedelegateSlashTwice(t *testing.T) { + ctx, _, keeper := keep.CreateTestInput(t, false, 1000) + valA, valB, del := keep.Addrs[0], keep.Addrs[1], keep.Addrs[2] + + msgCreateValidator := newTestMsgCreateValidator(valA, keep.PKs[0], 10) + got := handleMsgCreateValidator(ctx, msgCreateValidator, keeper) + require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") + + msgCreateValidator = newTestMsgCreateValidator(valB, keep.PKs[1], 10) + got = handleMsgCreateValidator(ctx, msgCreateValidator, keeper) + require.True(t, got.IsOK(), "expected no error on runMsgCreateValidator") + + // delegate 10 stake + msgDelegate := newTestMsgDelegate(del, valA, 10) + got = handleMsgDelegate(ctx, msgDelegate, keeper) + require.True(t, got.IsOK(), "expected no error on runMsgDelegate") + + // a block passes + ctx = ctx.WithBlockHeight(1) + + // begin unbonding 4 stake + msgBeginUnbonding := NewMsgBeginUnbonding(del, valA, sdk.NewRat(4)) + got = handleMsgBeginUnbonding(ctx, msgBeginUnbonding, keeper) + require.True(t, got.IsOK(), "expected no error on runMsgBeginUnbonding") + + // begin redelegate 6 stake + msgBeginRedelegate := NewMsgBeginRedelegate(del, valA, valB, sdk.NewRat(6)) + got = handleMsgBeginRedelegate(ctx, msgBeginRedelegate, keeper) + require.True(t, got.IsOK(), "expected no error on runMsgBeginRedelegate") + + // destination delegation should have 6 shares + delegation, found := keeper.GetDelegation(ctx, del, valB) + require.True(t, found) + require.Equal(t, sdk.NewRat(6), delegation.Shares) + + // slash the validator by half + keeper.Slash(ctx, keep.PKs[0], 0, 20, sdk.NewRat(1, 2)) + + // unbonding delegation should have been slashed by half + unbonding, found := keeper.GetUnbondingDelegation(ctx, del, valA) + require.True(t, found) + require.Equal(t, int64(2), unbonding.Balance.Amount.Int64()) + + // redelegation should have been slashed by half + redelegation, found := keeper.GetRedelegation(ctx, del, valA, valB) + require.True(t, found) + require.Equal(t, int64(3), redelegation.Balance.Amount.Int64()) + + // destination delegation should have been slashed by half + delegation, found = keeper.GetDelegation(ctx, del, valB) + require.True(t, found) + require.Equal(t, sdk.NewRat(3), delegation.Shares) + + // validator power should have been reduced by half + validator, found := keeper.GetValidator(ctx, valA) + require.True(t, found) + require.Equal(t, sdk.NewRat(5), validator.GetPower()) + + // slash the validator for an infraction committed after the unbonding and redelegation begin + ctx = ctx.WithBlockHeight(3) + keeper.Slash(ctx, keep.PKs[0], 2, 10, sdk.NewRat(1, 2)) + + // unbonding delegation should be unchanged + unbonding, found = keeper.GetUnbondingDelegation(ctx, del, valA) + require.True(t, found) + require.Equal(t, int64(2), unbonding.Balance.Amount.Int64()) + + // redelegation should be unchanged + redelegation, found = keeper.GetRedelegation(ctx, del, valA, valB) + require.True(t, found) + require.Equal(t, int64(3), redelegation.Balance.Amount.Int64()) + + // destination delegation should be unchanged + delegation, found = keeper.GetDelegation(ctx, del, valB) + require.True(t, found) + require.Equal(t, sdk.NewRat(3), delegation.Shares) + + // validator power should have been reduced to zero + validator, found = keeper.GetValidator(ctx, valA) + require.True(t, found) + require.Equal(t, sdk.NewRat(0), validator.GetPower()) +} diff --git a/x/stake/keeper/delegation.go b/x/stake/keeper/delegation.go index aab1dda90c..514939e17f 100644 --- a/x/stake/keeper/delegation.go +++ b/x/stake/keeper/delegation.go @@ -95,6 +95,26 @@ func (k Keeper) GetUnbondingDelegation(ctx sdk.Context, return ubd, true } +// load all unbonding delegations from a particular validator +func (k Keeper) GetUnbondingDelegationsFromValidator(ctx sdk.Context, valAddr sdk.Address) (unbondingDelegations []types.UnbondingDelegation) { + store := ctx.KVStore(k.storeKey) + iterator := sdk.KVStorePrefixIterator(store, GetUBDsByValIndexKey(valAddr, k.cdc)) + i := 0 + for ; ; i++ { + if !iterator.Valid() { + break + } + unbondingKey := iterator.Value() + unbondingBytes := store.Get(unbondingKey) + var unbondingDelegation types.UnbondingDelegation + k.cdc.MustUnmarshalBinary(unbondingBytes, &unbondingDelegation) + unbondingDelegations = append(unbondingDelegations, unbondingDelegation) + iterator.Next() + } + iterator.Close() + return unbondingDelegations +} + // set the unbonding delegation and associated index func (k Keeper) SetUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDelegation) { store := ctx.KVStore(k.storeKey) @@ -129,6 +149,26 @@ func (k Keeper) GetRedelegation(ctx sdk.Context, return red, true } +// load all redelegations from a particular validator +func (k Keeper) GetRedelegationsFromValidator(ctx sdk.Context, valAddr sdk.Address) (redelegations []types.Redelegation) { + store := ctx.KVStore(k.storeKey) + iterator := sdk.KVStorePrefixIterator(store, GetREDsFromValSrcIndexKey(valAddr, k.cdc)) + i := 0 + for ; ; i++ { + if !iterator.Valid() { + break + } + redelegationKey := iterator.Value() + redelegationBytes := store.Get(redelegationKey) + var redelegation types.Redelegation + k.cdc.MustUnmarshalBinary(redelegationBytes, &redelegation) + redelegations = append(redelegations, redelegation) + iterator.Next() + } + iterator.Close() + return redelegations +} + // has a redelegation func (k Keeper) HasReceivingRedelegation(ctx sdk.Context, DelegatorAddr, ValidatorDstAddr sdk.Address) bool { @@ -254,7 +294,7 @@ func (k Keeper) unbond(ctx sdk.Context, delegatorAddr, validatorAddr sdk.Address k.RemoveValidator(ctx, validator.Owner) } - return amount, nil + return } //______________________________________________________________________________________________________ @@ -270,12 +310,14 @@ func (k Keeper) BeginUnbonding(ctx sdk.Context, delegatorAddr, validatorAddr sdk // create the unbonding delegation params := k.GetParams(ctx) minTime := ctx.BlockHeader().Time + params.UnbondingTime + balance := sdk.Coin{params.BondDenom, sdk.NewInt(returnAmount)} ubd := types.UnbondingDelegation{ - DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, - MinTime: minTime, - Balance: sdk.Coin{params.BondDenom, sdk.NewInt(returnAmount)}, + DelegatorAddr: delegatorAddr, + ValidatorAddr: validatorAddr, + MinTime: minTime, + Balance: balance, + InitialBalance: balance, } k.SetUnbondingDelegation(ctx, ubd) return nil @@ -338,6 +380,8 @@ func (k Keeper) BeginRedelegation(ctx sdk.Context, delegatorAddr, validatorSrcAd MinTime: minTime, SharesDst: sharesCreated, SharesSrc: sharesAmount, + Balance: returnCoin, + InitialBalance: returnCoin, } k.SetRedelegation(ctx, red) return nil diff --git a/x/stake/keeper/slash.go b/x/stake/keeper/slash.go index 3abfe455cd..9d4c9af62e 100644 --- a/x/stake/keeper/slash.go +++ b/x/stake/keeper/slash.go @@ -4,56 +4,234 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/x/stake/types" "github.com/tendermint/tendermint/crypto" ) -// NOTE the current slash functionality doesn't take into consideration unbonding/rebonding records -// or the time of breach. This will be updated in slashing v2 -// slash a validator -func (k Keeper) Slash(ctx sdk.Context, pubkey crypto.PubKey, height int64, fraction sdk.Rat) { +// Slash a validator for an infraction committed at a known height +// Find the contributing stake at that height and burn the specified slashFactor +// of it, updating unbonding delegation & redelegations appropriately +// +// CONTRACT: +// slashFactor is non-negative +// CONTRACT: +// Validator exists and can be looked up by public key +// CONTRACT: +// Infraction committed equal to or less than an unbonding period in the past, +// so all unbonding delegations and redelegations from that height are stored +// CONTRACT: +// Infraction committed at the current height or at a past height, +// not at a height in the future +func (k Keeper) Slash(ctx sdk.Context, pubkey crypto.PubKey, infractionHeight int64, power int64, slashFactor sdk.Rat) { + logger := ctx.Logger().With("module", "x/stake") + + if slashFactor.LT(sdk.ZeroRat()) { + panic(fmt.Errorf("attempted to slash with a negative slashFactor: %v", slashFactor)) + } + + // Amount of slashing = slash slashFactor * power at time of infraction + slashAmount := sdk.NewRat(power).Mul(slashFactor).EvaluateInt() + // ref https://github.com/cosmos/cosmos-sdk/issues/1348 + // ref https://github.com/cosmos/cosmos-sdk/issues/1471 - // TODO height ignored for now, see https://github.com/cosmos/cosmos-sdk/pull/1011#issuecomment-390253957 validator, found := k.GetValidatorByPubKey(ctx, pubkey) if !found { - panic(fmt.Errorf("Attempted to slash a nonexistent validator with address %s", pubkey.Address())) + panic(fmt.Errorf("attempted to slash a nonexistent validator with address %s", pubkey.Address())) } - sharesToRemove := validator.PoolShares.Amount.Mul(fraction) - pool := k.GetPool(ctx) - validator, pool, burned := validator.RemovePoolShares(pool, sharesToRemove) - k.SetPool(ctx, pool) // update the pool - k.UpdateValidator(ctx, validator) // update the validator, possibly kicking it out + ownerAddress := validator.GetOwner() - logger := ctx.Logger().With("module", "x/stake") - logger.Info(fmt.Sprintf("Validator %s slashed by fraction %v, removed %v shares and burned %d tokens", pubkey.Address(), fraction, sharesToRemove, burned)) + // Track remaining slash amount for the validator + // This will decrease when we slash unbondings and + // redelegations, as that stake has since unbonded + remainingSlashAmount := slashAmount + + switch { + case infractionHeight > ctx.BlockHeight(): + // Can't slash infractions in the future + panic(fmt.Sprintf("impossible attempt to slash future infraction at height %d but we are at height %d", infractionHeight, ctx.BlockHeight())) + + case infractionHeight == ctx.BlockHeight(): + // Special-case slash at current height for efficiency - we don't need to look through unbonding delegations or redelegations + logger.Info(fmt.Sprintf("Slashing at current height %d, not scanning unbonding delegations & redelegations", infractionHeight)) + + case infractionHeight < ctx.BlockHeight(): + // Iterate through unbonding delegations from slashed validator + unbondingDelegations := k.GetUnbondingDelegationsFromValidator(ctx, ownerAddress) + for _, unbondingDelegation := range unbondingDelegations { + amountSlashed := k.slashUnbondingDelegation(ctx, unbondingDelegation, infractionHeight, slashFactor) + if amountSlashed.IsZero() { + continue + } + remainingSlashAmount = remainingSlashAmount.Sub(amountSlashed) + } + + // Iterate through redelegations from slashed validator + redelegations := k.GetRedelegationsFromValidator(ctx, ownerAddress) + for _, redelegation := range redelegations { + amountSlashed := k.slashRedelegation(ctx, validator, redelegation, infractionHeight, slashFactor) + if amountSlashed.IsZero() { + continue + } + remainingSlashAmount = remainingSlashAmount.Sub(amountSlashed) + } + + } + + // Cannot decrease balance below zero + sharesToRemove := remainingSlashAmount + if sharesToRemove.GT(validator.PoolShares.Amount.EvaluateInt()) { + sharesToRemove = validator.PoolShares.Amount.EvaluateInt() + } + + // Get the current pool + pool := k.GetPool(ctx) + // remove shares from the validator + validator, pool, burned := validator.RemovePoolShares(pool, sdk.NewRatFromInt(sharesToRemove)) + // burn tokens + pool.LooseTokens -= burned + // update the pool + k.SetPool(ctx, pool) + // update the validator, possibly kicking it out + k.UpdateValidator(ctx, validator) + + // Log that a slash occurred! + logger.Info(fmt.Sprintf("Validator %s slashed by slashFactor %v, removed %v shares and burned %d tokens", pubkey.Address(), slashFactor, sharesToRemove, burned)) + + // TODO Return event(s), blocked on https://github.com/tendermint/tendermint/pull/1803 return } // revoke a validator func (k Keeper) Revoke(ctx sdk.Context, pubkey crypto.PubKey) { - - validator, found := k.GetValidatorByPubKey(ctx, pubkey) - if !found { - panic(fmt.Errorf("Validator with pubkey %s not found, cannot revoke", pubkey)) - } - validator.Revoked = true - k.UpdateValidator(ctx, validator) // update the validator, now revoked - + k.setRevoked(ctx, pubkey, true) logger := ctx.Logger().With("module", "x/stake") logger.Info(fmt.Sprintf("Validator %s revoked", pubkey.Address())) + // TODO Return event(s), blocked on https://github.com/tendermint/tendermint/pull/1803 return } // unrevoke a validator func (k Keeper) Unrevoke(ctx sdk.Context, pubkey crypto.PubKey) { - - validator, found := k.GetValidatorByPubKey(ctx, pubkey) - if !found { - panic(fmt.Errorf("Validator with pubkey %s not found, cannot unrevoke", pubkey)) - } - validator.Revoked = false - k.UpdateValidator(ctx, validator) // update the validator, now unrevoked - + k.setRevoked(ctx, pubkey, false) logger := ctx.Logger().With("module", "x/stake") logger.Info(fmt.Sprintf("Validator %s unrevoked", pubkey.Address())) + // TODO Return event(s), blocked on https://github.com/tendermint/tendermint/pull/1803 return } + +// set the revoked flag on a validator +func (k Keeper) setRevoked(ctx sdk.Context, pubkey crypto.PubKey, revoked bool) { + validator, found := k.GetValidatorByPubKey(ctx, pubkey) + if !found { + panic(fmt.Errorf("Validator with pubkey %s not found, cannot set revoked to %v", pubkey, revoked)) + } + validator.Revoked = revoked + k.UpdateValidator(ctx, validator) // update validator, possibly unbonding or bonding it + return +} + +// slash an unbonding delegation and update the pool +// return the amount that would have been slashed assuming +// the unbonding delegation had enough stake to slash +// (the amount actually slashed may be less if there's +// insufficient stake remaining) +func (k Keeper) slashUnbondingDelegation(ctx sdk.Context, unbondingDelegation types.UnbondingDelegation, infractionHeight int64, slashFactor sdk.Rat) (slashAmount sdk.Int) { + now := ctx.BlockHeader().Time + + // If unbonding started before this height, stake didn't contribute to infraction + if unbondingDelegation.CreationHeight < infractionHeight { + return sdk.ZeroInt() + } + + if unbondingDelegation.MinTime < now { + // Unbonding delegation no longer eligible for slashing, skip it + // TODO Settle and delete it automatically? + return sdk.ZeroInt() + } + + // Calculate slash amount proportional to stake contributing to infraction + slashAmount = sdk.NewRatFromInt(unbondingDelegation.InitialBalance.Amount, sdk.OneInt()).Mul(slashFactor).EvaluateInt() + + // Don't slash more tokens than held + // Possible since the unbonding delegation may already + // have been slashed, and slash amounts are calculated + // according to stake held at time of infraction + unbondingSlashAmount := slashAmount + if unbondingSlashAmount.GT(unbondingDelegation.Balance.Amount) { + unbondingSlashAmount = unbondingDelegation.Balance.Amount + } + + // Update unbonding delegation if necessary + if !unbondingSlashAmount.IsZero() { + unbondingDelegation.Balance.Amount = unbondingDelegation.Balance.Amount.Sub(unbondingSlashAmount) + k.SetUnbondingDelegation(ctx, unbondingDelegation) + pool := k.GetPool(ctx) + // Burn loose tokens + // Ref https://github.com/cosmos/cosmos-sdk/pull/1278#discussion_r198657760 + pool.LooseTokens -= slashAmount.Int64() + k.SetPool(ctx, pool) + } + + return +} + +// slash a redelegation and update the pool +// return the amount that would have been slashed assuming +// the unbonding delegation had enough stake to slash +// (the amount actually slashed may be less if there's +// insufficient stake remaining) +func (k Keeper) slashRedelegation(ctx sdk.Context, validator types.Validator, redelegation types.Redelegation, infractionHeight int64, slashFactor sdk.Rat) (slashAmount sdk.Int) { + now := ctx.BlockHeader().Time + + // If redelegation started before this height, stake didn't contribute to infraction + if redelegation.CreationHeight < infractionHeight { + return sdk.ZeroInt() + } + + if redelegation.MinTime < now { + // Redelegation no longer eligible for slashing, skip it + // TODO Delete it automatically? + return sdk.ZeroInt() + } + + // Calculate slash amount proportional to stake contributing to infraction + slashAmount = sdk.NewRatFromInt(redelegation.InitialBalance.Amount, sdk.OneInt()).Mul(slashFactor).EvaluateInt() + + // Don't slash more tokens than held + // Possible since the redelegation may already + // have been slashed, and slash amounts are calculated + // according to stake held at time of infraction + redelegationSlashAmount := slashAmount + if redelegationSlashAmount.GT(redelegation.Balance.Amount) { + redelegationSlashAmount = redelegation.Balance.Amount + } + + // Update redelegation if necessary + if !redelegationSlashAmount.IsZero() { + redelegation.Balance.Amount = redelegation.Balance.Amount.Sub(redelegationSlashAmount) + k.SetRedelegation(ctx, redelegation) + } + + // Unbond from target validator + sharesToUnbond := slashFactor.Mul(redelegation.SharesDst) + if !sharesToUnbond.IsZero() { + delegation, found := k.GetDelegation(ctx, redelegation.DelegatorAddr, redelegation.ValidatorDstAddr) + if !found { + // If deleted, delegation has zero shares, and we can't unbond any more + return slashAmount + } + if sharesToUnbond.GT(delegation.Shares) { + sharesToUnbond = delegation.Shares + } + tokensToBurn, err := k.unbond(ctx, redelegation.DelegatorAddr, redelegation.ValidatorDstAddr, sharesToUnbond) + if err != nil { + panic(fmt.Errorf("error unbonding delegator: %v", err)) + } + // Burn loose tokens + pool := k.GetPool(ctx) + pool.LooseTokens -= tokensToBurn + k.SetPool(ctx, pool) + } + + return slashAmount +} diff --git a/x/stake/keeper/slash_test.go b/x/stake/keeper/slash_test.go new file mode 100644 index 0000000000..9e53151a18 --- /dev/null +++ b/x/stake/keeper/slash_test.go @@ -0,0 +1,481 @@ +package keeper + +import ( + "testing" + + "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/stake/types" + abci "github.com/tendermint/tendermint/abci/types" +) + +// setup helper function +// creates two validators +func setupHelper(t *testing.T, amt int64) (sdk.Context, Keeper, types.Params) { + // setup + ctx, _, keeper := CreateTestInput(t, false, amt) + params := keeper.GetParams(ctx) + pool := keeper.GetPool(ctx) + numVals := 3 + pool.LooseTokens = amt * int64(numVals) + + // add numVals validators + for i := 0; i < numVals; i++ { + validator := types.NewValidator(addrVals[i], PKs[i], types.Description{}) + validator, pool, _ = validator.AddTokensFromDel(pool, amt) + keeper.SetPool(ctx, pool) + keeper.UpdateValidator(ctx, validator) + keeper.SetValidatorByPubKeyIndex(ctx, validator) + } + + return ctx, keeper, params +} + +// tests Revoke, Unrevoke +func TestRevocation(t *testing.T) { + // setup + ctx, keeper, _ := setupHelper(t, 10) + addr := addrVals[0] + pk := PKs[0] + + // initial state + val, found := keeper.GetValidator(ctx, addr) + require.True(t, found) + require.False(t, val.GetRevoked()) + + // test revoke + keeper.Revoke(ctx, pk) + val, found = keeper.GetValidator(ctx, addr) + require.True(t, found) + require.True(t, val.GetRevoked()) + + // test unrevoke + keeper.Unrevoke(ctx, pk) + val, found = keeper.GetValidator(ctx, addr) + require.True(t, found) + require.False(t, val.GetRevoked()) + +} + +// tests slashUnbondingDelegation +func TestSlashUnbondingDelegation(t *testing.T) { + ctx, keeper, params := setupHelper(t, 10) + fraction := sdk.NewRat(1, 2) + + // set an unbonding delegation + ubd := types.UnbondingDelegation{ + DelegatorAddr: addrDels[0], + ValidatorAddr: addrVals[0], + CreationHeight: 0, + // expiration timestamp (beyond which the unbonding delegation shouldn't be slashed) + MinTime: 0, + InitialBalance: sdk.NewCoin(params.BondDenom, 10), + Balance: sdk.NewCoin(params.BondDenom, 10), + } + keeper.SetUnbondingDelegation(ctx, ubd) + + // unbonding started prior to the infraction height, stake didn't contribute + slashAmount := keeper.slashUnbondingDelegation(ctx, ubd, 1, fraction) + require.Equal(t, int64(0), slashAmount.Int64()) + + // after the expiration time, no longer eligible for slashing + ctx = ctx.WithBlockHeader(abci.Header{Time: int64(10)}) + keeper.SetUnbondingDelegation(ctx, ubd) + slashAmount = keeper.slashUnbondingDelegation(ctx, ubd, 0, fraction) + require.Equal(t, int64(0), slashAmount.Int64()) + + // test valid slash, before expiration timestamp and to which stake contributed + oldPool := keeper.GetPool(ctx) + ctx = ctx.WithBlockHeader(abci.Header{Time: int64(0)}) + keeper.SetUnbondingDelegation(ctx, ubd) + slashAmount = keeper.slashUnbondingDelegation(ctx, ubd, 0, fraction) + require.Equal(t, int64(5), slashAmount.Int64()) + ubd, found := keeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0]) + require.True(t, found) + // initialbalance unchanged + require.Equal(t, sdk.NewCoin(params.BondDenom, 10), ubd.InitialBalance) + // balance decreased + require.Equal(t, sdk.NewCoin(params.BondDenom, 5), ubd.Balance) + newPool := keeper.GetPool(ctx) + require.Equal(t, int64(5), oldPool.LooseTokens-newPool.LooseTokens) +} + +// tests slashRedelegation +func TestSlashRedelegation(t *testing.T) { + ctx, keeper, params := setupHelper(t, 10) + fraction := sdk.NewRat(1, 2) + + // set a redelegation + rd := types.Redelegation{ + DelegatorAddr: addrDels[0], + ValidatorSrcAddr: addrVals[0], + ValidatorDstAddr: addrVals[1], + CreationHeight: 0, + // expiration timestamp (beyond which the redelegation shouldn't be slashed) + MinTime: 0, + SharesSrc: sdk.NewRat(10), + SharesDst: sdk.NewRat(10), + InitialBalance: sdk.NewCoin(params.BondDenom, 10), + Balance: sdk.NewCoin(params.BondDenom, 10), + } + keeper.SetRedelegation(ctx, rd) + + // set the associated delegation + del := types.Delegation{ + DelegatorAddr: addrDels[0], + ValidatorAddr: addrVals[1], + Shares: sdk.NewRat(10), + } + keeper.SetDelegation(ctx, del) + + // started redelegating prior to the current height, stake didn't contribute to infraction + validator, found := keeper.GetValidator(ctx, addrVals[1]) + require.True(t, found) + slashAmount := keeper.slashRedelegation(ctx, validator, rd, 1, fraction) + require.Equal(t, int64(0), slashAmount.Int64()) + + // after the expiration time, no longer eligible for slashing + ctx = ctx.WithBlockHeader(abci.Header{Time: int64(10)}) + keeper.SetRedelegation(ctx, rd) + validator, found = keeper.GetValidator(ctx, addrVals[1]) + require.True(t, found) + slashAmount = keeper.slashRedelegation(ctx, validator, rd, 0, fraction) + require.Equal(t, int64(0), slashAmount.Int64()) + + // test valid slash, before expiration timestamp and to which stake contributed + oldPool := keeper.GetPool(ctx) + ctx = ctx.WithBlockHeader(abci.Header{Time: int64(0)}) + keeper.SetRedelegation(ctx, rd) + validator, found = keeper.GetValidator(ctx, addrVals[1]) + require.True(t, found) + slashAmount = keeper.slashRedelegation(ctx, validator, rd, 0, fraction) + require.Equal(t, int64(5), slashAmount.Int64()) + rd, found = keeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1]) + require.True(t, found) + // initialbalance unchanged + require.Equal(t, sdk.NewCoin(params.BondDenom, 10), rd.InitialBalance) + // balance decreased + require.Equal(t, sdk.NewCoin(params.BondDenom, 5), rd.Balance) + // shares decreased + del, found = keeper.GetDelegation(ctx, addrDels[0], addrVals[1]) + require.True(t, found) + require.Equal(t, int64(5), del.Shares.Evaluate()) + // pool bonded tokens decreased + newPool := keeper.GetPool(ctx) + require.Equal(t, int64(5), oldPool.BondedTokens-newPool.BondedTokens) +} + +// tests Slash at a future height (must panic) +func TestSlashAtFutureHeight(t *testing.T) { + ctx, keeper, _ := setupHelper(t, 10) + pk := PKs[0] + fraction := sdk.NewRat(1, 2) + require.Panics(t, func() { keeper.Slash(ctx, pk, 1, 10, fraction) }) +} + +// tests Slash at the current height +func TestSlashAtCurrentHeight(t *testing.T) { + ctx, keeper, _ := setupHelper(t, 10) + pk := PKs[0] + fraction := sdk.NewRat(1, 2) + + oldPool := keeper.GetPool(ctx) + validator, found := keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + keeper.Slash(ctx, pk, ctx.BlockHeight(), 10, fraction) + + // read updated state + validator, found = keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + newPool := keeper.GetPool(ctx) + + // power decreased + require.Equal(t, sdk.NewRat(5), validator.GetPower()) + // pool bonded shares decreased + require.Equal(t, sdk.NewRat(5).Evaluate(), oldPool.BondedShares.Sub(newPool.BondedShares).Evaluate()) +} + +// tests Slash at a previous height with an unbonding delegation +func TestSlashWithUnbondingDelegation(t *testing.T) { + ctx, keeper, params := setupHelper(t, 10) + pk := PKs[0] + fraction := sdk.NewRat(1, 2) + + // set an unbonding delegation + ubd := types.UnbondingDelegation{ + DelegatorAddr: addrDels[0], + ValidatorAddr: addrVals[0], + CreationHeight: 11, + // expiration timestamp (beyond which the unbonding delegation shouldn't be slashed) + MinTime: 0, + InitialBalance: sdk.NewCoin(params.BondDenom, 4), + Balance: sdk.NewCoin(params.BondDenom, 4), + } + keeper.SetUnbondingDelegation(ctx, ubd) + + // slash validator for the first time + ctx = ctx.WithBlockHeight(12) + oldPool := keeper.GetPool(ctx) + validator, found := keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + keeper.Slash(ctx, pk, 10, 10, fraction) + + // read updating unbonding delegation + ubd, found = keeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0]) + require.True(t, found) + // balance decreased + require.Equal(t, sdk.NewInt(2), ubd.Balance.Amount) + // read updated pool + newPool := keeper.GetPool(ctx) + // bonded tokens burned + require.Equal(t, int64(3), oldPool.BondedTokens-newPool.BondedTokens) + // read updated validator + validator, found = keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + // power decreased by 3 - 6 stake originally bonded at the time of infraction + // was still bonded at the time of discovery and was slashed by half, 4 stake + // bonded at the time of discovery hadn't been bonded at the time of infraction + // and wasn't slashed + require.Equal(t, sdk.NewRat(7), validator.GetPower()) + + // slash validator again + ctx = ctx.WithBlockHeight(13) + keeper.Slash(ctx, pk, 9, 10, fraction) + ubd, found = keeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0]) + require.True(t, found) + // balance decreased again + require.Equal(t, sdk.NewInt(0), ubd.Balance.Amount) + // read updated pool + newPool = keeper.GetPool(ctx) + // bonded tokens burned again + require.Equal(t, int64(6), oldPool.BondedTokens-newPool.BondedTokens) + // read updated validator + validator, found = keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + // power decreased by 3 again + require.Equal(t, sdk.NewRat(4), validator.GetPower()) + + // slash validator again + // all originally bonded stake has been slashed, so this will have no effect + // on the unbonding delegation, but it will slash stake bonded since the infraction + // this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440 + ctx = ctx.WithBlockHeight(13) + keeper.Slash(ctx, pk, 9, 10, fraction) + ubd, found = keeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0]) + require.True(t, found) + // balance unchanged + require.Equal(t, sdk.NewInt(0), ubd.Balance.Amount) + // read updated pool + newPool = keeper.GetPool(ctx) + // bonded tokens burned again + require.Equal(t, int64(9), oldPool.BondedTokens-newPool.BondedTokens) + // read updated validator + validator, found = keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + // power decreased by 3 again + require.Equal(t, sdk.NewRat(1), validator.GetPower()) + + // slash validator again + // all originally bonded stake has been slashed, so this will have no effect + // on the unbonding delegation, but it will slash stake bonded since the infraction + // this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440 + ctx = ctx.WithBlockHeight(13) + keeper.Slash(ctx, pk, 9, 10, fraction) + ubd, found = keeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0]) + require.True(t, found) + // balance unchanged + require.Equal(t, sdk.NewInt(0), ubd.Balance.Amount) + // read updated pool + newPool = keeper.GetPool(ctx) + // just 1 bonded token burned again since that's all the validator now has + require.Equal(t, int64(10), oldPool.BondedTokens-newPool.BondedTokens) + // read updated validator + validator, found = keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + // power decreased by 1 again, validator is out of stake + require.Equal(t, sdk.NewRat(0), validator.GetPower()) +} + +// tests Slash at a previous height with a redelegation +func TestSlashWithRedelegation(t *testing.T) { + ctx, keeper, params := setupHelper(t, 10) + pk := PKs[0] + fraction := sdk.NewRat(1, 2) + + // set a redelegation + rd := types.Redelegation{ + DelegatorAddr: addrDels[0], + ValidatorSrcAddr: addrVals[0], + ValidatorDstAddr: addrVals[1], + CreationHeight: 11, + MinTime: 0, + SharesSrc: sdk.NewRat(6), + SharesDst: sdk.NewRat(6), + InitialBalance: sdk.NewCoin(params.BondDenom, 6), + Balance: sdk.NewCoin(params.BondDenom, 6), + } + keeper.SetRedelegation(ctx, rd) + + // set the associated delegation + del := types.Delegation{ + DelegatorAddr: addrDels[0], + ValidatorAddr: addrVals[1], + Shares: sdk.NewRat(6), + } + keeper.SetDelegation(ctx, del) + + // slash validator + ctx = ctx.WithBlockHeight(12) + oldPool := keeper.GetPool(ctx) + validator, found := keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + keeper.Slash(ctx, pk, 10, 10, fraction) + + // read updating redelegation + rd, found = keeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1]) + require.True(t, found) + // balance decreased + require.Equal(t, sdk.NewInt(3), rd.Balance.Amount) + // read updated pool + newPool := keeper.GetPool(ctx) + // bonded tokens burned + require.Equal(t, int64(5), oldPool.BondedTokens-newPool.BondedTokens) + // read updated validator + validator, found = keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + // power decreased by 2 - 4 stake originally bonded at the time of infraction + // was still bonded at the time of discovery and was slashed by half, 4 stake + // bonded at the time of discovery hadn't been bonded at the time of infraction + // and wasn't slashed + require.Equal(t, sdk.NewRat(8), validator.GetPower()) + + // slash the validator again + ctx = ctx.WithBlockHeight(12) + validator, found = keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + keeper.Slash(ctx, pk, 10, 10, sdk.NewRat(3, 4)) + + // read updating redelegation + rd, found = keeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1]) + require.True(t, found) + // balance decreased, now zero + require.Equal(t, sdk.NewInt(0), rd.Balance.Amount) + // read updated pool + newPool = keeper.GetPool(ctx) + // 7 bonded tokens burned + require.Equal(t, int64(12), oldPool.BondedTokens-newPool.BondedTokens) + // read updated validator + validator, found = keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + // power decreased by 4 + require.Equal(t, sdk.NewRat(4), validator.GetPower()) + + // slash the validator again, by 100% + ctx = ctx.WithBlockHeight(12) + validator, found = keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + keeper.Slash(ctx, pk, 10, 10, sdk.OneRat()) + + // read updating redelegation + rd, found = keeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1]) + require.True(t, found) + // balance still zero + require.Equal(t, sdk.NewInt(0), rd.Balance.Amount) + // read updated pool + newPool = keeper.GetPool(ctx) + // four more bonded tokens burned + require.Equal(t, int64(16), oldPool.BondedTokens-newPool.BondedTokens) + // read updated validator + validator, found = keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + // power decreased by 4, down to 0 + require.Equal(t, sdk.NewRat(0), validator.GetPower()) + + // slash the validator again, by 100% + // no stake remains to be slashed + ctx = ctx.WithBlockHeight(12) + validator, found = keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + keeper.Slash(ctx, pk, 10, 10, sdk.OneRat()) + + // read updating redelegation + rd, found = keeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1]) + require.True(t, found) + // balance still zero + require.Equal(t, sdk.NewInt(0), rd.Balance.Amount) + // read updated pool + newPool = keeper.GetPool(ctx) + // no more bonded tokens burned + require.Equal(t, int64(16), oldPool.BondedTokens-newPool.BondedTokens) + // read updated validator + validator, found = keeper.GetValidatorByPubKey(ctx, pk) + require.True(t, found) + // power still zero + require.Equal(t, sdk.NewRat(0), validator.GetPower()) +} + +// tests Slash at a previous height with both an unbonding delegation and a redelegation +func TestSlashBoth(t *testing.T) { + ctx, keeper, params := setupHelper(t, 10) + fraction := sdk.NewRat(1, 2) + + // set a redelegation + rdA := types.Redelegation{ + DelegatorAddr: addrDels[0], + ValidatorSrcAddr: addrVals[0], + ValidatorDstAddr: addrVals[1], + CreationHeight: 11, + // expiration timestamp (beyond which the redelegation shouldn't be slashed) + MinTime: 0, + SharesSrc: sdk.NewRat(6), + SharesDst: sdk.NewRat(6), + InitialBalance: sdk.NewCoin(params.BondDenom, 6), + Balance: sdk.NewCoin(params.BondDenom, 6), + } + keeper.SetRedelegation(ctx, rdA) + + // set the associated delegation + delA := types.Delegation{ + DelegatorAddr: addrDels[0], + ValidatorAddr: addrVals[1], + Shares: sdk.NewRat(6), + } + keeper.SetDelegation(ctx, delA) + + // set an unbonding delegation + ubdA := types.UnbondingDelegation{ + DelegatorAddr: addrDels[0], + ValidatorAddr: addrVals[0], + CreationHeight: 11, + // expiration timestamp (beyond which the unbonding delegation shouldn't be slashed) + MinTime: 0, + InitialBalance: sdk.NewCoin(params.BondDenom, 4), + Balance: sdk.NewCoin(params.BondDenom, 4), + } + keeper.SetUnbondingDelegation(ctx, ubdA) + + // slash validator + ctx = ctx.WithBlockHeight(12) + oldPool := keeper.GetPool(ctx) + validator, found := keeper.GetValidatorByPubKey(ctx, PKs[0]) + require.True(t, found) + keeper.Slash(ctx, PKs[0], 10, 10, fraction) + + // read updating redelegation + rdA, found = keeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1]) + require.True(t, found) + // balance decreased + require.Equal(t, sdk.NewInt(3), rdA.Balance.Amount) + // read updated pool + newPool := keeper.GetPool(ctx) + // loose tokens burned + require.Equal(t, int64(2), oldPool.LooseTokens-newPool.LooseTokens) + // bonded tokens burned + require.Equal(t, int64(3), oldPool.BondedTokens-newPool.BondedTokens) + // read updated validator + validator, found = keeper.GetValidatorByPubKey(ctx, PKs[0]) + require.True(t, found) + // power not decreased, all stake was bonded since + require.Equal(t, sdk.NewRat(10), validator.GetPower()) +} diff --git a/x/stake/types/delegation.go b/x/stake/types/delegation.go index 410cfbe1d8..eb38a50a7a 100644 --- a/x/stake/types/delegation.go +++ b/x/stake/types/delegation.go @@ -61,6 +61,7 @@ type UnbondingDelegation struct { ValidatorAddr sdk.Address `json:"validator_addr"` // validator unbonding from owner addr CreationHeight int64 `json:"creation_height"` // height which the unbonding took place MinTime int64 `json:"min_time"` // unix time for unbonding completion + InitialBalance sdk.Coin `json:"initial_balance"` // atoms initially scheduled to receive at completion Balance sdk.Coin `json:"balance"` // atoms to receive at completion } @@ -101,6 +102,8 @@ type Redelegation struct { ValidatorDstAddr sdk.Address `json:"validator_dst_addr"` // validator redelegation destination owner addr CreationHeight int64 `json:"creation_height"` // height which the redelegation took place MinTime int64 `json:"min_time"` // unix time for redelegation completion + InitialBalance sdk.Coin `json:"initial_balance"` // initial balance when redelegation started + Balance sdk.Coin `json:"balance"` // current balance SharesSrc sdk.Rat `json:"shares_src"` // amount of source shares redelegating SharesDst sdk.Rat `json:"shares_dst"` // amount of destination shares redelegating } diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index 652fd9e6e8..c98ebce62a 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -284,6 +284,7 @@ func (v Validator) DelegatorShareExRate(pool Pool) sdk.Rat { var _ sdk.Validator = Validator{} // nolint - for sdk.Validator +func (v Validator) GetRevoked() bool { return v.Revoked } func (v Validator) GetMoniker() string { return v.Description.Moniker } func (v Validator) GetStatus() sdk.BondStatus { return v.Status() } func (v Validator) GetOwner() sdk.Address { return v.Owner } From feb3acdbe9c7fdca41570db9971759ce0e34a457 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Sat, 30 Jun 2018 19:32:52 -0400 Subject: [PATCH 8/9] Merge PR #1491: client/lcd: fix tests * client/lcd: fix tests * circle: drop test_unit. store artifacts in test_cover * hack fix in TestUnrevoke --- .circleci/config.yml | 24 +++++----------------- client/lcd/lcd_test.go | 3 +++ client/lcd/test_helpers.go | 2 +- tests/util.go | 42 ++++++++++++++++---------------------- 4 files changed, 27 insertions(+), 44 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index cf679fe75f..0a6b28673e 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -8,6 +8,7 @@ defaults: &defaults GOBIN: /tmp/workspace/bin jobs: + setup_dependencies: <<: *defaults steps: @@ -67,21 +68,6 @@ jobs: command: | export PATH="$GOBIN:$PATH" make test_lint - test_unit: - <<: *defaults - parallelism: 1 - steps: - - attach_workspace: - at: /tmp/workspace - - restore_cache: - key: v1-pkg-cache - - restore_cache: - key: v1-tree-{{ .Environment.CIRCLE_SHA1 }} - - run: - name: Test unit - command: | - export PATH="$GOBIN:$PATH" - make test_unit test_cli: <<: *defaults @@ -109,6 +95,7 @@ jobs: key: v1-pkg-cache - restore_cache: key: v1-tree-{{ .Environment.CIRCLE_SHA1 }} + - run: mkdir -p /tmp/logs - run: name: Run tests command: | @@ -117,12 +104,14 @@ jobs: for pkg in $(go list github.com/cosmos/cosmos-sdk/... | grep -v /vendor/ | grep -v github.com/cosmos/cosmos-sdk/cmd/gaia/cli_test | circleci tests split --split-by=timings); do id=$(basename "$pkg") - go test -timeout 8m -race -coverprofile=/tmp/workspace/profiles/$id.out -covermode=atomic "$pkg" + GOCACHE=off go test -v -timeout 8m -race -coverprofile=/tmp/workspace/profiles/$id.out -covermode=atomic "$pkg" | tee "/tmp/logs/$id-$RANDOM.log" done - persist_to_workspace: root: /tmp/workspace paths: - "profiles/*" + - store_artifacts: + path: /tmp/logs upload_coverage: <<: *defaults @@ -156,9 +145,6 @@ workflows: - test_cli: requires: - setup_dependencies - - test_unit: - requires: - - setup_dependencies - test_cover: requires: - setup_dependencies diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index 049fa04bef..1b1a02fefb 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -528,6 +528,9 @@ func TestUnrevoke(t *testing.T) { cleanup, pks, port := InitializeTestLCD(t, 1, []sdk.Address{addr}) defer cleanup() + // XXX: any less than this and it fails + tests.WaitForHeight(3, port) + signingInfo := getSigningInfo(t, port, pks[0].Address()) tests.WaitForHeight(4, port) require.Equal(t, true, signingInfo.IndexOffset > 0) diff --git a/client/lcd/test_helpers.go b/client/lcd/test_helpers.go index ecf6748a57..dbdf9b724d 100644 --- a/client/lcd/test_helpers.go +++ b/client/lcd/test_helpers.go @@ -95,7 +95,7 @@ func CreateAddr(t *testing.T, name, password string, kb crkeys.Keybase) (addr sd func InitializeTestLCD(t *testing.T, nValidators int, initAddrs []sdk.Address) (cleanup func(), validatorsPKs []crypto.PubKey, port string) { config := GetConfig() - config.Consensus.TimeoutCommit = 1000 + config.Consensus.TimeoutCommit = 100 config.Consensus.SkipTimeoutCommit = false config.TxIndex.IndexAllTags = true diff --git a/tests/util.go b/tests/util.go index 54432f9927..afa127bf01 100644 --- a/tests/util.go +++ b/tests/util.go @@ -82,17 +82,10 @@ func StatusOK(statusCode int) bool { } func waitForHeight(height int64, url string) { + var res *http.Response + var err error for { - // get url, try a few times - var res *http.Response - var err error - for i := 0; i < 5; i++ { - res, err = http.Get(url) - if err == nil && StatusOK(res.StatusCode) { - break - } - time.Sleep(time.Millisecond * 200) - } + res, err = http.Get(url) if err != nil { panic(err) } @@ -125,30 +118,31 @@ func waitForHeight(height int64, url string) { // wait for tendermint to start func WaitForStart(port string) { var err error - for i := 0; i < 5; i++ { - time.Sleep(time.Second) + url := fmt.Sprintf("http://localhost:%v/blocks/latest", port) - url := fmt.Sprintf("http://localhost:%v/blocks/latest", port) + // ping the status endpoint a few times a second + // for a few seconds until we get a good response. + // otherwise something probably went wrong + for i := 0; i < 50; i++ { + time.Sleep(time.Millisecond * 100) - // get url, try a few times var res *http.Response res, err = http.Get(url) - if err == nil || res == nil { + if err != nil || res == nil { continue } + err = res.Body.Close() + if err != nil { + panic(err) + } - // waiting for server to start ... - if res.StatusCode != http.StatusOK { - err = res.Body.Close() - if err != nil { - panic(err) - } + if res.StatusCode == http.StatusOK { + // good! return } } - if err != nil { - panic(err) - } + // still haven't started up?! panic! + panic(err) } // TODO: these functions just print to Stdout. From 6a864923fa40f3e8cc934e58e58b8a78a188de4d Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Mon, 2 Jul 2018 08:57:33 -0700 Subject: [PATCH 9/9] types: Rename rational.Evaluate to rational.Round (#1487) * rational.Evaluate -> rational.RoundInt64 * rational.EvaluateInt -> rational.RoundInt This done to improve clarity of the code. Closes #1485 --- CHANGELOG.md | 1 + types/rational.go | 10 ++++----- types/rational_test.go | 4 ++-- types/stake.go | 2 +- x/stake/genesis.go | 2 +- x/stake/handler_test.go | 34 +++++++++++++++---------------- x/stake/keeper/delegation_test.go | 8 ++++---- x/stake/keeper/inflation.go | 2 +- x/stake/keeper/inflation_test.go | 4 ++-- x/stake/keeper/slash.go | 10 ++++----- x/stake/keeper/slash_test.go | 4 ++-- x/stake/keeper/validator_test.go | 4 ++-- x/stake/types/pool.go | 6 +++--- x/stake/types/test_common.go | 8 ++++---- x/stake/types/validator.go | 2 +- x/stake/types/validator_test.go | 22 ++++++++++---------- 16 files changed, 62 insertions(+), 61 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e0b543247a..b261e7d84b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,7 @@ BREAKING CHANGES to an infraction, slash them proportional to their stake at the time * Add REST endpoint to unrevoke a validator previously revoked for downtime * Add REST endpoint to retrieve liveness signing information for a validator +* [types] renamed rational.Evaluate to rational.Round{Int64, Int} FEATURES * [gaiacli] You can now attach a simple text-only memo to any transaction, with the `--memo` flag diff --git a/types/rational.go b/types/rational.go index f24831f89e..ab400868d4 100644 --- a/types/rational.go +++ b/types/rational.go @@ -174,20 +174,20 @@ func (r Rat) EvaluateBig() *big.Int { return d } -// evaluate the rational using bankers rounding -func (r Rat) Evaluate() int64 { +// RoundInt64 rounds the rational using bankers rounding +func (r Rat) RoundInt64() int64 { return r.EvaluateBig().Int64() } -// EvaulateInt evaludates the rational using EvaluateBig -func (r Rat) EvaluateInt() Int { +// RoundInt round the rational using bankers rounding +func (r Rat) RoundInt() Int { return NewIntFromBigInt(r.EvaluateBig()) } // round Rat with the provided precisionFactor func (r Rat) Round(precisionFactor int64) Rat { rTen := Rat{new(big.Rat).Mul(r.Rat, big.NewRat(precisionFactor, 1))} - return Rat{big.NewRat(rTen.Evaluate(), precisionFactor)} + return Rat{big.NewRat(rTen.RoundInt64(), precisionFactor)} } // TODO panic if negative or if totalDigits < len(initStr)??? diff --git a/types/rational_test.go b/types/rational_test.go index db875c83e8..3215313e09 100644 --- a/types/rational_test.go +++ b/types/rational_test.go @@ -168,8 +168,8 @@ func TestEvaluate(t *testing.T) { } for _, tc := range tests { - require.Equal(t, tc.res, tc.r1.Evaluate(), "%v", tc.r1) - require.Equal(t, tc.res*-1, tc.r1.Mul(NewRat(-1)).Evaluate(), "%v", tc.r1.Mul(NewRat(-1))) + require.Equal(t, tc.res, tc.r1.RoundInt64(), "%v", tc.r1) + require.Equal(t, tc.res*-1, tc.r1.Mul(NewRat(-1)).RoundInt64(), "%v", tc.r1.Mul(NewRat(-1))) } } diff --git a/types/stake.go b/types/stake.go index 8625b617e5..7cb7ccf6d8 100644 --- a/types/stake.go +++ b/types/stake.go @@ -46,7 +46,7 @@ type Validator interface { func ABCIValidator(v Validator) abci.Validator { return abci.Validator{ PubKey: tmtypes.TM2PB.PubKey(v.GetPubKey()), - Power: v.GetPower().Evaluate(), + Power: v.GetPower().RoundInt64(), } } diff --git a/x/stake/genesis.go b/x/stake/genesis.go index 6a15ebeb42..55dd06f76f 100644 --- a/x/stake/genesis.go +++ b/x/stake/genesis.go @@ -49,7 +49,7 @@ func WriteValidators(ctx sdk.Context, keeper Keeper) (vals []tmtypes.GenesisVali keeper.IterateValidatorsBonded(ctx, func(_ int64, validator sdk.Validator) (stop bool) { vals = append(vals, tmtypes.GenesisValidator{ PubKey: validator.GetPubKey(), - Power: validator.GetPower().Evaluate(), + Power: validator.GetPower().RoundInt64(), Name: validator.GetMoniker(), }) return false diff --git a/x/stake/handler_test.go b/x/stake/handler_test.go index e6cd6f4ca7..b18b3c98b2 100644 --- a/x/stake/handler_test.go +++ b/x/stake/handler_test.go @@ -56,7 +56,7 @@ func TestValidatorByPowerIndex(t *testing.T) { // verify the self-delegation exists bond, found := keeper.GetDelegation(ctx, validatorAddr, validatorAddr) require.True(t, found) - gotBond := bond.Shares.Evaluate() + gotBond := bond.Shares.RoundInt64() require.Equal(t, initBond, gotBond, "initBond: %v\ngotBond: %v\nbond: %v\n", initBond, gotBond, bond) @@ -78,8 +78,8 @@ func TestValidatorByPowerIndex(t *testing.T) { keeper.Revoke(ctx, keep.PKs[0]) validator, found = keeper.GetValidator(ctx, validatorAddr) require.True(t, found) - require.Equal(t, sdk.Unbonded, validator.PoolShares.Status) // ensure is unbonded - require.Equal(t, int64(500000), validator.PoolShares.Amount.Evaluate()) // ensure is unbonded + require.Equal(t, sdk.Unbonded, validator.PoolShares.Status) // ensure is unbonded + require.Equal(t, int64(500000), validator.PoolShares.Amount.RoundInt64()) // ensure is unbonded // the old power record should have been deleted as the power changed require.False(t, keep.ValidatorByPowerIndexExists(ctx, keeper, power)) @@ -155,20 +155,20 @@ func TestIncrementsMsgDelegate(t *testing.T) { validator, found := keeper.GetValidator(ctx, validatorAddr) require.True(t, found) require.Equal(t, sdk.Bonded, validator.Status()) - require.Equal(t, bondAmount, validator.DelegatorShares.Evaluate()) - require.Equal(t, bondAmount, validator.PoolShares.Bonded().Evaluate(), "validator: %v", validator) + require.Equal(t, bondAmount, validator.DelegatorShares.RoundInt64()) + require.Equal(t, bondAmount, validator.PoolShares.Bonded().RoundInt64(), "validator: %v", validator) _, found = keeper.GetDelegation(ctx, delegatorAddr, validatorAddr) require.False(t, found) bond, found := keeper.GetDelegation(ctx, validatorAddr, validatorAddr) require.True(t, found) - require.Equal(t, bondAmount, bond.Shares.Evaluate()) + require.Equal(t, bondAmount, bond.Shares.RoundInt64()) pool := keeper.GetPool(ctx) exRate := validator.DelegatorShareExRate(pool) require.True(t, exRate.Equal(sdk.OneRat()), "expected exRate 1 got %v", exRate) - require.Equal(t, bondAmount, pool.BondedShares.Evaluate()) + require.Equal(t, bondAmount, pool.BondedShares.RoundInt64()) require.Equal(t, bondAmount, pool.BondedTokens) // just send the same msgbond multiple times @@ -196,8 +196,8 @@ func TestIncrementsMsgDelegate(t *testing.T) { require.Equal(t, bond.Height, int64(i), "Incorrect bond height") - gotBond := bond.Shares.Evaluate() - gotDelegatorShares := validator.DelegatorShares.Evaluate() + gotBond := bond.Shares.RoundInt64() + gotDelegatorShares := validator.DelegatorShares.RoundInt64() gotDelegatorAcc := accMapper.GetAccount(ctx, delegatorAddr).GetCoins().AmountOf(params.BondDenom) require.Equal(t, expBond, gotBond, @@ -230,8 +230,8 @@ func TestIncrementsMsgUnbond(t *testing.T) { validator, found := keeper.GetValidator(ctx, validatorAddr) require.True(t, found) - require.Equal(t, initBond*2, validator.DelegatorShares.Evaluate()) - require.Equal(t, initBond*2, validator.PoolShares.Bonded().Evaluate()) + require.Equal(t, initBond*2, validator.DelegatorShares.RoundInt64()) + require.Equal(t, initBond*2, validator.PoolShares.Bonded().RoundInt64()) // just send the same msgUnbond multiple times // TODO use decimals here @@ -251,12 +251,12 @@ func TestIncrementsMsgUnbond(t *testing.T) { bond, found := keeper.GetDelegation(ctx, delegatorAddr, validatorAddr) require.True(t, found) - expBond := initBond - int64(i+1)*unbondShares.Evaluate() - expDelegatorShares := 2*initBond - int64(i+1)*unbondShares.Evaluate() + expBond := initBond - int64(i+1)*unbondShares.RoundInt64() + expDelegatorShares := 2*initBond - int64(i+1)*unbondShares.RoundInt64() expDelegatorAcc := sdk.NewInt(initBond - expBond) - gotBond := bond.Shares.Evaluate() - gotDelegatorShares := validator.DelegatorShares.Evaluate() + gotBond := bond.Shares.RoundInt64() + gotDelegatorShares := validator.DelegatorShares.RoundInt64() gotDelegatorAcc := accMapper.GetAccount(ctx, delegatorAddr).GetCoins().AmountOf(params.BondDenom) require.Equal(t, expBond, gotBond, @@ -285,7 +285,7 @@ func TestIncrementsMsgUnbond(t *testing.T) { require.False(t, got.IsOK(), "expected unbond msg to fail") } - leftBonded := initBond - int64(numUnbonds)*unbondShares.Evaluate() + leftBonded := initBond - int64(numUnbonds)*unbondShares.RoundInt64() // should be unable to unbond one more than we have unbondShares = sdk.NewRat(leftBonded + 1) @@ -322,7 +322,7 @@ func TestMultipleMsgCreateValidator(t *testing.T) { balanceExpd := sdk.NewInt(initBond - 10) balanceGot := accMapper.GetAccount(ctx, val.Owner).GetCoins().AmountOf(params.BondDenom) require.Equal(t, i+1, len(validators), "expected %d validators got %d, validators: %v", i+1, len(validators), validators) - require.Equal(t, 10, int(val.DelegatorShares.Evaluate()), "expected %d shares, got %d", 10, val.DelegatorShares) + require.Equal(t, 10, int(val.DelegatorShares.RoundInt64()), "expected %d shares, got %d", 10, val.DelegatorShares) require.Equal(t, balanceExpd, balanceGot, "expected account to have %d, got %d", balanceExpd, balanceGot) } diff --git a/x/stake/keeper/delegation_test.go b/x/stake/keeper/delegation_test.go index f20188ccdc..eb318df4d3 100644 --- a/x/stake/keeper/delegation_test.go +++ b/x/stake/keeper/delegation_test.go @@ -146,13 +146,13 @@ func TestUnbondDelegation(t *testing.T) { //create a validator and a delegator to that validator validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) validator, pool, issuedShares := validator.AddTokensFromDel(pool, 10) - require.Equal(t, int64(10), issuedShares.Evaluate()) + require.Equal(t, int64(10), issuedShares.RoundInt64()) keeper.SetPool(ctx, pool) validator = keeper.UpdateValidator(ctx, validator) pool = keeper.GetPool(ctx) require.Equal(t, int64(10), pool.BondedTokens) - require.Equal(t, int64(10), validator.PoolShares.Bonded().Evaluate()) + require.Equal(t, int64(10), validator.PoolShares.Bonded().RoundInt64()) delegation := types.Delegation{ DelegatorAddr: addrDels[0], @@ -173,8 +173,8 @@ func TestUnbondDelegation(t *testing.T) { require.True(t, found) pool = keeper.GetPool(ctx) - require.Equal(t, int64(4), delegation.Shares.Evaluate()) - require.Equal(t, int64(4), validator.PoolShares.Bonded().Evaluate()) + require.Equal(t, int64(4), delegation.Shares.RoundInt64()) + require.Equal(t, int64(4), validator.PoolShares.Bonded().RoundInt64()) require.Equal(t, int64(6), pool.LooseTokens, "%v", pool) require.Equal(t, int64(4), pool.BondedTokens) } diff --git a/x/stake/keeper/inflation.go b/x/stake/keeper/inflation.go index 0574b8ecbf..26b5158791 100644 --- a/x/stake/keeper/inflation.go +++ b/x/stake/keeper/inflation.go @@ -18,7 +18,7 @@ func (k Keeper) ProcessProvisions(ctx sdk.Context) types.Pool { pool := k.GetPool(ctx) pool.Inflation = k.NextInflation(ctx) - provisions := pool.Inflation.Mul(sdk.NewRat(pool.TokenSupply())).Quo(hrsPerYrRat).Evaluate() + provisions := pool.Inflation.Mul(sdk.NewRat(pool.TokenSupply())).Quo(hrsPerYrRat).RoundInt64() // TODO add to the fees provisions pool.LooseTokens += provisions diff --git a/x/stake/keeper/inflation_test.go b/x/stake/keeper/inflation_test.go index 944559dfc2..2fee8154a0 100644 --- a/x/stake/keeper/inflation_test.go +++ b/x/stake/keeper/inflation_test.go @@ -167,7 +167,7 @@ func TestLargeUnbond(t *testing.T) { _, expProvisionsAfter, pool := updateProvisions(t, keeper, pool, ctx, 0) bondedShares = bondedShares.Sub(bondSharesVal0) - val0UnbondedTokens = pool.UnbondedShareExRate().Mul(validator.PoolShares.Unbonded()).Evaluate() + val0UnbondedTokens = pool.UnbondedShareExRate().Mul(validator.PoolShares.Unbonded()).RoundInt64() unbondedShares = unbondedShares.Add(sdk.NewRat(val0UnbondedTokens, 1).Mul(pool.UnbondedShareExRate())) // unbonded shares should increase @@ -295,7 +295,7 @@ func checkFinalPoolValues(t *testing.T, pool types.Pool, initialTotalTokens, cum // Returns expected Provisions, expected Inflation, and pool, to help with cumulative calculations back in main Tests func updateProvisions(t *testing.T, keeper Keeper, pool types.Pool, ctx sdk.Context, hr int) (sdk.Rat, int64, types.Pool) { expInflation := keeper.NextInflation(ctx) - expProvisions := (expInflation.Mul(sdk.NewRat(pool.TokenSupply())).Quo(hrsPerYrRat)).Evaluate() + expProvisions := (expInflation.Mul(sdk.NewRat(pool.TokenSupply())).Quo(hrsPerYrRat)).RoundInt64() startTotalSupply := pool.TokenSupply() pool = keeper.ProcessProvisions(ctx) keeper.SetPool(ctx, pool) diff --git a/x/stake/keeper/slash.go b/x/stake/keeper/slash.go index 9d4c9af62e..b12360fc3f 100644 --- a/x/stake/keeper/slash.go +++ b/x/stake/keeper/slash.go @@ -30,7 +30,7 @@ func (k Keeper) Slash(ctx sdk.Context, pubkey crypto.PubKey, infractionHeight in } // Amount of slashing = slash slashFactor * power at time of infraction - slashAmount := sdk.NewRat(power).Mul(slashFactor).EvaluateInt() + slashAmount := sdk.NewRat(power).Mul(slashFactor).RoundInt() // ref https://github.com/cosmos/cosmos-sdk/issues/1348 // ref https://github.com/cosmos/cosmos-sdk/issues/1471 @@ -79,8 +79,8 @@ func (k Keeper) Slash(ctx sdk.Context, pubkey crypto.PubKey, infractionHeight in // Cannot decrease balance below zero sharesToRemove := remainingSlashAmount - if sharesToRemove.GT(validator.PoolShares.Amount.EvaluateInt()) { - sharesToRemove = validator.PoolShares.Amount.EvaluateInt() + if sharesToRemove.GT(validator.PoolShares.Amount.RoundInt()) { + sharesToRemove = validator.PoolShares.Amount.RoundInt() } // Get the current pool @@ -150,7 +150,7 @@ func (k Keeper) slashUnbondingDelegation(ctx sdk.Context, unbondingDelegation ty } // Calculate slash amount proportional to stake contributing to infraction - slashAmount = sdk.NewRatFromInt(unbondingDelegation.InitialBalance.Amount, sdk.OneInt()).Mul(slashFactor).EvaluateInt() + slashAmount = sdk.NewRatFromInt(unbondingDelegation.InitialBalance.Amount, sdk.OneInt()).Mul(slashFactor).RoundInt() // Don't slash more tokens than held // Possible since the unbonding delegation may already @@ -195,7 +195,7 @@ func (k Keeper) slashRedelegation(ctx sdk.Context, validator types.Validator, re } // Calculate slash amount proportional to stake contributing to infraction - slashAmount = sdk.NewRatFromInt(redelegation.InitialBalance.Amount, sdk.OneInt()).Mul(slashFactor).EvaluateInt() + slashAmount = sdk.NewRatFromInt(redelegation.InitialBalance.Amount, sdk.OneInt()).Mul(slashFactor).RoundInt() // Don't slash more tokens than held // Possible since the redelegation may already diff --git a/x/stake/keeper/slash_test.go b/x/stake/keeper/slash_test.go index 9e53151a18..dcd38e15e2 100644 --- a/x/stake/keeper/slash_test.go +++ b/x/stake/keeper/slash_test.go @@ -160,7 +160,7 @@ func TestSlashRedelegation(t *testing.T) { // shares decreased del, found = keeper.GetDelegation(ctx, addrDels[0], addrVals[1]) require.True(t, found) - require.Equal(t, int64(5), del.Shares.Evaluate()) + require.Equal(t, int64(5), del.Shares.RoundInt64()) // pool bonded tokens decreased newPool := keeper.GetPool(ctx) require.Equal(t, int64(5), oldPool.BondedTokens-newPool.BondedTokens) @@ -193,7 +193,7 @@ func TestSlashAtCurrentHeight(t *testing.T) { // power decreased require.Equal(t, sdk.NewRat(5), validator.GetPower()) // pool bonded shares decreased - require.Equal(t, sdk.NewRat(5).Evaluate(), oldPool.BondedShares.Sub(newPool.BondedShares).Evaluate()) + require.Equal(t, sdk.NewRat(5).RoundInt64(), oldPool.BondedShares.Sub(newPool.BondedShares).RoundInt64()) } // tests Slash at a previous height with an unbonding delegation diff --git a/x/stake/keeper/validator_test.go b/x/stake/keeper/validator_test.go index cf26d055f6..c4d197a36b 100644 --- a/x/stake/keeper/validator_test.go +++ b/x/stake/keeper/validator_test.go @@ -68,12 +68,12 @@ func TestUpdateValidatorByPowerIndex(t *testing.T) { validator := types.NewValidator(addrVals[0], PKs[0], types.Description{}) validator, pool, delSharesCreated := validator.AddTokensFromDel(pool, 100) require.Equal(t, sdk.Unbonded, validator.Status()) - require.Equal(t, int64(100), validator.PoolShares.Tokens(pool).Evaluate()) + require.Equal(t, int64(100), validator.PoolShares.Tokens(pool).RoundInt64()) keeper.SetPool(ctx, pool) keeper.UpdateValidator(ctx, validator) validator, found := keeper.GetValidator(ctx, addrVals[0]) require.True(t, found) - require.Equal(t, int64(100), validator.PoolShares.Tokens(pool).Evaluate(), "\nvalidator %v\npool %v", validator, pool) + require.Equal(t, int64(100), validator.PoolShares.Tokens(pool).RoundInt64(), "\nvalidator %v\npool %v", validator, pool) pool = keeper.GetPool(ctx) power := GetValidatorsByPowerIndexKey(validator, pool) diff --git a/x/stake/types/pool.go b/x/stake/types/pool.go index cb2ad240ae..8ef187f078 100644 --- a/x/stake/types/pool.go +++ b/x/stake/types/pool.go @@ -104,7 +104,7 @@ func (p Pool) addTokensUnbonded(amount int64) (p2 Pool, issuedShares PoolShares) } func (p Pool) removeSharesUnbonded(shares sdk.Rat) (p2 Pool, removedTokens int64) { - removedTokens = p.UnbondedShareExRate().Mul(shares).Evaluate() // (tokens/shares) * shares + removedTokens = p.UnbondedShareExRate().Mul(shares).RoundInt64() // (tokens/shares) * shares p.UnbondedShares = p.UnbondedShares.Sub(shares) p.UnbondedTokens -= removedTokens p.LooseTokens += removedTokens @@ -126,7 +126,7 @@ func (p Pool) addTokensUnbonding(amount int64) (p2 Pool, issuedShares PoolShares } func (p Pool) removeSharesUnbonding(shares sdk.Rat) (p2 Pool, removedTokens int64) { - removedTokens = p.UnbondingShareExRate().Mul(shares).Evaluate() // (tokens/shares) * shares + removedTokens = p.UnbondingShareExRate().Mul(shares).RoundInt64() // (tokens/shares) * shares p.UnbondingShares = p.UnbondingShares.Sub(shares) p.UnbondingTokens -= removedTokens p.LooseTokens += removedTokens @@ -148,7 +148,7 @@ func (p Pool) addTokensBonded(amount int64) (p2 Pool, issuedShares PoolShares) { } func (p Pool) removeSharesBonded(shares sdk.Rat) (p2 Pool, removedTokens int64) { - removedTokens = p.BondedShareExRate().Mul(shares).Evaluate() // (tokens/shares) * shares + removedTokens = p.BondedShareExRate().Mul(shares).RoundInt64() // (tokens/shares) * shares p.BondedShares = p.BondedShares.Sub(shares) p.BondedTokens -= removedTokens p.LooseTokens += removedTokens diff --git a/x/stake/types/test_common.go b/x/stake/types/test_common.go index 5edb5568d8..12f11f864b 100644 --- a/x/stake/types/test_common.go +++ b/x/stake/types/test_common.go @@ -118,12 +118,12 @@ func AssertInvariants(t *testing.T, msg string, // nonnegative bonded ex rate require.False(t, pMod.BondedShareExRate().LT(sdk.ZeroRat()), "Applying operation \"%s\" resulted in negative BondedShareExRate: %d", - msg, pMod.BondedShareExRate().Evaluate()) + msg, pMod.BondedShareExRate().RoundInt64()) // nonnegative unbonded ex rate require.False(t, pMod.UnbondedShareExRate().LT(sdk.ZeroRat()), "Applying operation \"%s\" resulted in negative UnbondedShareExRate: %d", - msg, pMod.UnbondedShareExRate().Evaluate()) + msg, pMod.UnbondedShareExRate().RoundInt64()) for _, vMod := range vMods { @@ -193,10 +193,10 @@ func RandomSetup(r *rand.Rand, numValidators int) (Pool, []Validator) { validator := randomValidator(r, i) if validator.Status() == sdk.Bonded { pool.BondedShares = pool.BondedShares.Add(validator.PoolShares.Bonded()) - pool.BondedTokens += validator.PoolShares.Bonded().Evaluate() + pool.BondedTokens += validator.PoolShares.Bonded().RoundInt64() } else if validator.Status() == sdk.Unbonded { pool.UnbondedShares = pool.UnbondedShares.Add(validator.PoolShares.Unbonded()) - pool.UnbondedTokens += validator.PoolShares.Unbonded().Evaluate() + pool.UnbondedTokens += validator.PoolShares.Unbonded().RoundInt64() } validators[i] = validator } diff --git a/x/stake/types/validator.go b/x/stake/types/validator.go index c98ebce62a..c2c19439be 100644 --- a/x/stake/types/validator.go +++ b/x/stake/types/validator.go @@ -137,7 +137,7 @@ func (d Description) EnsureLength() (Description, sdk.Error) { func (v Validator) ABCIValidator() abci.Validator { return abci.Validator{ PubKey: tmtypes.TM2PB.PubKey(v.PubKey), - Power: v.PoolShares.Bonded().Evaluate(), + Power: v.PoolShares.Bonded().RoundInt64(), } } diff --git a/x/stake/types/validator_test.go b/x/stake/types/validator_test.go index 6a8ff777a6..4fcfa6e17d 100644 --- a/x/stake/types/validator_test.go +++ b/x/stake/types/validator_test.go @@ -69,7 +69,7 @@ func TestRemoveDelShares(t *testing.T) { PoolShares: NewBondedShares(sdk.NewRat(100)), DelegatorShares: sdk.NewRat(100), } - poolA.BondedTokens = valA.PoolShares.Bonded().Evaluate() + poolA.BondedTokens = valA.PoolShares.Bonded().RoundInt64() poolA.BondedShares = valA.PoolShares.Bonded() require.Equal(t, valA.DelegatorShareExRate(poolA), sdk.OneRat()) require.Equal(t, poolA.BondedShareExRate(), sdk.OneRat()) @@ -117,25 +117,25 @@ func TestUpdateStatus(t *testing.T) { val := NewValidator(addr1, pk1, Description{}) val, pool, _ = val.AddTokensFromDel(pool, 100) - require.Equal(t, int64(0), val.PoolShares.Bonded().Evaluate()) - require.Equal(t, int64(0), val.PoolShares.Unbonding().Evaluate()) - require.Equal(t, int64(100), val.PoolShares.Unbonded().Evaluate()) + require.Equal(t, int64(0), val.PoolShares.Bonded().RoundInt64()) + require.Equal(t, int64(0), val.PoolShares.Unbonding().RoundInt64()) + require.Equal(t, int64(100), val.PoolShares.Unbonded().RoundInt64()) require.Equal(t, int64(0), pool.BondedTokens) require.Equal(t, int64(0), pool.UnbondingTokens) require.Equal(t, int64(100), pool.UnbondedTokens) val, pool = val.UpdateStatus(pool, sdk.Unbonding) - require.Equal(t, int64(0), val.PoolShares.Bonded().Evaluate()) - require.Equal(t, int64(100), val.PoolShares.Unbonding().Evaluate()) - require.Equal(t, int64(0), val.PoolShares.Unbonded().Evaluate()) + require.Equal(t, int64(0), val.PoolShares.Bonded().RoundInt64()) + require.Equal(t, int64(100), val.PoolShares.Unbonding().RoundInt64()) + require.Equal(t, int64(0), val.PoolShares.Unbonded().RoundInt64()) require.Equal(t, int64(0), pool.BondedTokens) require.Equal(t, int64(100), pool.UnbondingTokens) require.Equal(t, int64(0), pool.UnbondedTokens) val, pool = val.UpdateStatus(pool, sdk.Bonded) - require.Equal(t, int64(100), val.PoolShares.Bonded().Evaluate()) - require.Equal(t, int64(0), val.PoolShares.Unbonding().Evaluate()) - require.Equal(t, int64(0), val.PoolShares.Unbonded().Evaluate()) + require.Equal(t, int64(100), val.PoolShares.Bonded().RoundInt64()) + require.Equal(t, int64(0), val.PoolShares.Unbonding().RoundInt64()) + require.Equal(t, int64(0), val.PoolShares.Unbonded().RoundInt64()) require.Equal(t, int64(100), pool.BondedTokens) require.Equal(t, int64(0), pool.UnbondingTokens) require.Equal(t, int64(0), pool.UnbondedTokens) @@ -154,7 +154,7 @@ func TestPossibleOverflow(t *testing.T) { LooseTokens: 100, BondedShares: poolShares, UnbondedShares: sdk.ZeroRat(), - BondedTokens: poolShares.Evaluate(), + BondedTokens: poolShares.RoundInt64(), UnbondedTokens: 0, InflationLastTime: 0, Inflation: sdk.NewRat(7, 100),