Merge branch 'develop' into rigel/stake-spec-compliance
This commit is contained in:
commit
f1937bc0e7
|
@ -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
|
||||
|
@ -101,7 +87,7 @@ jobs:
|
|||
|
||||
test_cover:
|
||||
<<: *defaults
|
||||
parallelism: 1
|
||||
parallelism: 2
|
||||
steps:
|
||||
- attach_workspace:
|
||||
at: /tmp/workspace
|
||||
|
@ -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,15 +104,18 @@ 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
|
||||
parallelism: 1
|
||||
steps:
|
||||
- attach_workspace:
|
||||
at: /tmp/workspace
|
||||
|
@ -155,9 +145,6 @@ workflows:
|
|||
- test_cli:
|
||||
requires:
|
||||
- setup_dependencies
|
||||
- test_unit:
|
||||
requires:
|
||||
- setup_dependencies
|
||||
- test_cover:
|
||||
requires:
|
||||
- setup_dependencies
|
||||
|
|
11
CHANGELOG.md
11
CHANGELOG.md
|
@ -22,6 +22,14 @@ 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
|
||||
* [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
|
||||
|
@ -42,6 +50,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
|
||||
|
@ -67,6 +76,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'
|
||||
|
@ -77,6 +87,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
|
||||
|
||||
|
|
|
@ -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
|
|
@ -443,7 +443,7 @@
|
|||
"netutil",
|
||||
"trace"
|
||||
]
|
||||
revision = "e514e69ffb8bc3c76a71ae40de0118d794855992"
|
||||
revision = "97aa3a539ec716117a9d15a4659a911f50d13c3c"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
|
|
2
Makefile
2
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
|
||||
|
||||
|
|
|
@ -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")
|
||||
}
|
||||
|
||||
//----------------------------------------
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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"
|
||||
)
|
||||
|
@ -46,7 +47,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 +75,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 +88,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 +121,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 +130,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 +145,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 +167,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 +177,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 +197,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 +210,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 +240,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 +275,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 +302,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 +324,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 +343,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 +353,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 +362,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 +374,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 +391,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 +413,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 +439,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 +461,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 +477,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 +495,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 +511,31 @@ 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 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()
|
||||
|
||||
// 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)
|
||||
require.Equal(t, int64(0), signingInfo.JailedUntil)
|
||||
require.Equal(t, true, signingInfo.SignedBlocksCounter > 0)
|
||||
}
|
||||
|
||||
func TestProposalsQuery(t *testing.T) {
|
||||
|
@ -563,31 +580,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)
|
||||
}
|
||||
|
||||
//_____________________________________________________________________________
|
||||
|
@ -679,6 +696,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)
|
||||
|
|
|
@ -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"
|
||||
)
|
||||
|
||||
|
@ -76,7 +77,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 +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)
|
||||
gov.RegisterRoutes(ctx, r, cdc, kb)
|
||||
slashing.RegisterRoutes(ctx, r, cdc, kb)
|
||||
gov.RegisterRoutes(ctx, r, cdc)
|
||||
return r
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
||||
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
||||
//___________________________________________________________________________________
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
|
@ -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)
|
||||
|
||||
}
|
||||
|
|
|
@ -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")
|
||||
}
|
||||
|
|
|
@ -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))
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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() {
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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"
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
# End-Block
|
||||
# End-Block
|
||||
|
||||
## Slashing
|
||||
|
||||
|
@ -6,9 +6,9 @@ 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`
|
||||
|
||||
|
@ -16,32 +16,27 @@ 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):
|
||||
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:
|
||||
|
@ -89,7 +102,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
|
||||
|
|
|
@ -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 <https://github.com/tendermint/go-crypto>`__. The Merkle tree
|
||||
library <https://github.com/tendermint/tendermint/crypto>`__. The Merkle tree
|
||||
used in Basecoin is a balanced, binary search tree, which we call an
|
||||
`IAVL tree <https://github.com/tendermint/iavl>`__.
|
||||
|
||||
|
@ -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.
|
||||
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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")
|
||||
}
|
||||
|
||||
|
|
|
@ -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))
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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")
|
||||
}
|
||||
|
|
|
@ -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))
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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{})
|
||||
}
|
||||
|
|
|
@ -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))
|
||||
}
|
||||
|
|
|
@ -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]")
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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,
|
||||
}
|
||||
|
|
|
@ -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))
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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)}
|
||||
}
|
||||
|
|
|
@ -3,7 +3,7 @@ package mock
|
|||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
dbm "github.com/tendermint/tmlibs/db"
|
||||
|
||||
|
@ -12,22 +12,22 @@ import (
|
|||
|
||||
func TestStore(t *testing.T) {
|
||||
db := dbm.NewMemDB()
|
||||
cms := NewCommitMultiStore(db)
|
||||
cms := NewCommitMultiStore()
|
||||
|
||||
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))
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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())
|
||||
}
|
||||
|
||||
//--------------------------------------------------------
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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()
|
||||
}
|
||||
|
|
|
@ -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())
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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))
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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) })
|
||||
}
|
||||
|
|
|
@ -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())
|
||||
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
@ -159,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)???
|
||||
|
|
|
@ -5,22 +5,23 @@ 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) {
|
||||
largeBigInt, success := new(big.Int).SetString("3109736052979742687701388262607869", 10)
|
||||
require.True(t, success)
|
||||
tests := []struct {
|
||||
decimalStr string
|
||||
expErr bool
|
||||
|
@ -31,7 +32,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 +48,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)
|
||||
require.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)
|
||||
require.NotNil(t, err, tc.decimalStr)
|
||||
} else {
|
||||
assert.Nil(t, err)
|
||||
assert.True(t, res.Equal(tc.exp.Mul(NewRat(-1))))
|
||||
require.Nil(t, err, tc.decimalStr)
|
||||
require.True(t, res.Equal(tc.exp.Mul(NewRat(-1))), tc.decimalStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -93,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))
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -129,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() == 0 { // panic for divide by zero
|
||||
assert.Panics(t, func() { tc.r1.Quo(tc.r2) })
|
||||
if tc.r2.Num().IsZero() { // panic for divide by zero
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -162,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.RoundInt64(), "%v", tc.r1)
|
||||
require.Equal(t, tc.res*-1, tc.r1.Mul(NewRat(-1)).RoundInt64(), "%v", tc.r1.Mul(NewRat(-1)))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -186,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)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -205,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))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -214,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) {
|
||||
|
@ -232,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) {
|
||||
|
@ -243,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) {
|
||||
|
@ -254,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 {
|
||||
|
@ -272,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) {
|
||||
|
@ -292,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))
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -303,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(),
|
||||
)
|
||||
|
|
|
@ -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
|
||||
|
@ -45,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(),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
//_______________________________________________________________________________
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
||||
}
|
||||
|
|
|
@ -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())
|
||||
}
|
||||
|
|
|
@ -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)))
|
||||
}
|
||||
|
|
|
@ -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))
|
||||
}
|
||||
|
|
|
@ -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())
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
@ -76,7 +75,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
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)}))
|
||||
}
|
||||
|
|
|
@ -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]")
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
//}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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())
|
||||
}
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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())
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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()) {
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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))
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
||||
|
@ -108,6 +107,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)
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
}
|
|
@ -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)
|
||||
}
|
||||
}
|
|
@ -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,
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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"}`)
|
||||
}
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue