Merge branch 'develop' into joon/673-am-constructor

This commit is contained in:
Christopher Goes 2018-07-11 00:57:46 +02:00
commit 75b4f4104a
16 changed files with 334 additions and 188 deletions

View File

@ -13,26 +13,22 @@ BREAKING CHANGES
* Default ports changed from 466xx to 266xx
* Amino JSON uses type names instead of prefix bytes
* ED25519 addresses are the first 20-bytes of the SHA256 of the raw 32-byte
pubkey
pubkey (Instead of RIPEMD160)
* go-crypto, abci, tmlibs have been merged into Tendermint
* The keys sub-module is now in the SDK
* Various other fixes
* [auth] Signers of a transaction now only sign over their own account and sequence number
* [auth] Removed MsgChangePubKey
* [auth] Removed MsgChangePubKey
* [auth] Removed SetPubKey from account mapper
* [auth] AltBytes renamed to Memo, now a string, max 100 characters, costs a bit of gas
* [baseapp] NewBaseApp now takes option functions as parameters
* [types] `GetMsg()` -> `GetMsgs()` as txs wrap many messages
* [types] Removed GetMemo from Tx (it is still on StdTx)
* [types] renamed rational.Evaluate to rational.Round{Int64, Int}
* [types] Renamed `sdk.Address` to `sdk.AccAddress`/`sdk.ValAddress`
* [types] `sdk.AccAddress`/`sdk.ValAddress` natively marshals to Bech32 in String, Sprintf (when used with `%s`), and MarshalJSON
* [keys] Keybase and Ledger support from go-crypto merged into the SDK in the `crypto` folder
* [cli] Rearranged commands under subcommands
* [x/gov] Gov module REST endpoints changed to be more RESTful
* [x/stake] Remove Tick and add EndBlocker
* [x/stake] Introduce concept of unbonding for delegations and validators
* `gaiacli stake unbond` replaced with `gaiacli stake begin-unbonding`
* Introduced:
* `gaiacli stake complete-unbonding`
* `gaiacli stake begin-redelegation`
* `gaiacli stake complete-redelegation`
* [x/slashing] Update slashing for unbonding period
* Slash according to power at time of infraction instead of power at
time of discovery
@ -40,27 +36,38 @@ BREAKING CHANGES
to an infraction, slash them proportional to their stake at the time
* Add REST endpoint to unrevoke a validator previously revoked for downtime
* Add REST endpoint to retrieve liveness signing information for a validator
* [types] renamed rational.Evaluate to rational.Round{Int64, Int}
* [x/stake] Remove Tick and add EndBlocker
* [x/stake] most index keys nolonger hold a value - inputs are rearranged to form the desired key
* [lcd] Switch key creation output to return bech32
* [x/stake] store-value for delegation, validator, ubd, and red do not hold duplicate information contained store-key
* [gaiad] genesis transactions now use bech32 addresses / pubkeys
* [x/stake] Introduce concept of unbonding for delegations and validators
* `gaiacli stake unbond` replaced with `gaiacli stake begin-unbonding`
* Introduced:
* `gaiacli stake complete-unbonding`
* `gaiacli stake begin-redelegation`
* `gaiacli stake complete-redelegation`
* [lcd] Switch key creation output to return bech32
* [lcd] Removed shorthand CLI flags (`a`, `c`, `n`, `o`)
* [types] Renamed `sdk.Address` to `sdk.AccAddress`/`sdk.ValAddress`
* [types] `sdk.AccAddress`/`sdk.ValAddress` natively marshals to Bech32 in String, Sprintf (when used with `%s`), and MarshalJSON
* [gaiad] genesis transactions now use bech32 addresses / pubkeys
DEPRECATED
* [cli] Deprecate `--name` flag in commands that send txs, in favor of `--from`
* [cli] Deprecated `--name` flag in commands that send txs, in favor of `--from`
FEATURES
* [gaiacli] You can now attach a simple text-only memo to any transaction, with the `--memo` flag
* [lcd] Queried TXs now include the tx hash to identify each tx
* [mockapp] CompleteSetup() no longer takes a testing parameter
* [x/gov] Implemented MVP
* Supported proposal types: just binary (pass/fail) TextProposals for now
* Proposals need deposits to be votable; deposits are burned if proposal fails
* Delegators delegate votes to validator by default but can override (for their stake)
* Add benchmarks for signing and delivering a block with a single bank transaction
* [gaiacli] Ledger support added
- You can now use a Ledger with `gaiacli --ledger` for all key-related commands
- Ledger keys can be named and tracked locally in the key DB
* [gaiacli] You can now attach a simple text-only memo to any transaction, with the `--memo` flag
* [gaiacli] added the following flags for commands that post transactions to the chain:
* async -- send the tx without waiting for a tendermint response
* json -- return the output in json format for increased readability
* print-response -- return the tx response. (includes fields like gas cost)
* [lcd] Queried TXs now include the tx hash to identify each tx
* [mockapp] CompleteSetup() no longer takes a testing parameter
* [x/bank] Add benchmarks for signing and delivering a block with a single bank transaction
* Run with `cd x/bank && go test --bench=.`
* [tools] make get_tools installs tendermint's linter, and gometalinter
* [tools] Switch gometalinter to the stable version
@ -73,26 +80,21 @@ FEATURES
* errcheck
* unparam
* gocyclo
* [tools] Add `make format` command to automate fixing misspell and gofmt errors.
* [tools] Added `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
* [types] Switches internal representation of Int/Uint/Rat to use pointers
* [types] Added MinInt and MinUint functions
* [gaiad] `unsafe_reset_all` now resets addrbook.json
* [democoin] add x/oracle, x/assoc
* [gaiacli] Ledger support added
- You can now use a Ledger with `gaiacli --ledger` for all key-related commands
- Ledger keys can be named and tracked locally in the key DB
* [testing] created a randomized testing framework.
* [tests] created a randomized testing framework.
- Currently bank has limited functionality in the framework
- Auth has its invariants checked within the framework
* [gaiacli] added the following flags for commands that post transactions to the chain:
* async -- send the tx without waiting for a tendermint response
* json -- return the output in json format for increased readability
* print-response -- return the tx response. (includes fields like gas cost)
* [tests] Add WaitForNextNBlocksTM helper method
* [keys] New keys now have 24 word recovery keys, for heightened security
IMPROVEMENTS
* bank module uses go-wire codec instead of 'encoding/json'
* auth module uses go-wire codec instead of 'encoding/json'
* [x/bank] Now uses go-wire codec instead of 'encoding/json'
* [x/auth] Now uses go-wire codec instead of 'encoding/json'
* revised use of endblock and beginblock
* [stake] module reorganized to include `types` and `keeper` package
* [stake] keeper always loads the store (instead passing around which doesn't really boost efficiency)
@ -102,32 +104,37 @@ IMPROVEMENTS
* [keys] improve error message when deleting non-existent key
* [gaiacli] improve error messages on `send` and `account` commands
* added contributing guidelines
* [docs] Added commands for governance CLI on testnet README
BUG FIXES
* [x/slashing] \#1510 Unrevoked validators cannot un-revoke themselves
* [x/stake] \#1513 Validators slashed to zero power are unbonded and removed from the store
* [x/stake] \#1567 Validators decreased in power but not unbonded are now updated in Tendermint
* [x/stake] error strings lower case
* [x/stake] pool loose tokens now accounts for unbonding and unbonding tokens not associated with any validator
* [x/stake] fix revoke bytes ordering (was putting revoked candidates at the top of the list)
* [x/stake] bond count was counting revoked validators as bonded, fixed
* [gaia] Added self delegation for validators in the genesis creation
* [lcd] tests now don't depend on raw json text
* [stake] error strings lower case
* [stake] pool loose tokens now accounts for unbonding and unbonding tokens not associated with any validator
* \#1259 - fix bug where certain tests that could have a nil pointer in defer
* \#1052 - Make all now works
* Retry on HTTP request failure in CLI tests, add option to retry tests in Makefile
* Fixed bug where chain ID wasn't passed properly in x/bank REST handler, removed Viper hack from ante handler
* Fixed bug where `democli account` didn't decode the account data correctly
* \#1343 - fixed unnecessary parallelism in CI
* \#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
* \#872 - recovery phrases no longer all end in `abandon`
* \#887 - limit the size of rationals that can be passed in from user input
* \#1052 - Make all now works
* \#1258 - printing big.rat's can no longer overflow int64
* \#1259 - fix bug where certain tests that could have a nil pointer in defer
* \#1343 - fixed unnecessary parallelism in CI
* \#1353 - CLI: Show pool shares fractions in human-readable format
* \#1367 - set ChainID in InitChain
* \#1461 - CLI tests now no longer reset your local environment data
* \#1505 - `gaiacli stake validator` no longer panics if validator doesn't exist
* [x/stake] fix revoke bytes ordering (was putting revoked candidates at the top of the list)
* [x/stake] bond count was counting revoked validators as bonded, fixed
* \#1565 - fix cliff validator persisting when validator set shrinks from max
* \#1287 - prevent zero power validators at genesis
* [x/stake] fix bug when unbonding/redelegating using `--shares-percent`
* \#1010 - two validators can't bond with the same pubkey anymore
## 0.19.0
*June 13, 2018*

View File

@ -73,7 +73,8 @@ var _ abci.Application = (*BaseApp)(nil)
// Create and name new BaseApp
// NOTE: The db is used to store the version number for now.
func NewBaseApp(name string, cdc *wire.Codec, logger log.Logger, db dbm.DB) *BaseApp {
// Accepts variable number of option functions, which act on the BaseApp to set configuration choices
func NewBaseApp(name string, cdc *wire.Codec, logger log.Logger, db dbm.DB, options ...func(*BaseApp)) *BaseApp {
app := &BaseApp{
Logger: logger,
name: name,
@ -86,6 +87,9 @@ func NewBaseApp(name string, cdc *wire.Codec, logger log.Logger, db dbm.DB) *Bas
}
// Register the undefined & root codespaces, which should not be used by any modules
app.codespacer.RegisterOrPanic(sdk.CodespaceRoot)
for _, option := range options {
option(app)
}
return app
}
@ -204,36 +208,6 @@ func (app *BaseApp) initFromStore(mainKey sdk.StoreKey) error {
return errors.New("baseapp expects MultiStore with 'main' KVStore")
}
// XXX: Do we really need the header? What does it have that we want
// here that's not already in the CommitID ? If an app wants to have it,
// they can do so in their BeginBlocker. If we force it in baseapp,
// then either we force the AppHash to change with every block (since the header
// will be in the merkle store) or we can't write the state and the header to the
// db atomically without doing some surgery on the store interfaces ...
// if we've committed before, we expect <dbHeaderKey> to exist in the db
/*
var lastCommitID = app.cms.LastCommitID()
var header abci.Header
if !lastCommitID.IsZero() {
headerBytes := app.db.Get(dbHeaderKey)
if len(headerBytes) == 0 {
errStr := fmt.Sprintf("Version > 0 but missing key %s", dbHeaderKey)
return errors.New(errStr)
}
err := proto.Unmarshal(headerBytes, &header)
if err != nil {
return errors.Wrap(err, "failed to parse Header")
}
lastVersion := lastCommitID.Version
if header.Height != lastVersion {
errStr := fmt.Sprintf("expected db://%s.Height %v but got %v", dbHeaderKey, lastVersion, header.Height)
return errors.New(errStr)
}
}
*/
return nil
}
@ -490,21 +464,7 @@ func (app *BaseApp) DeliverTx(txBytes []byte) (res abci.ResponseDeliverTx) {
}
}
// nolint - Mostly for testing
func (app *BaseApp) Check(tx sdk.Tx) (result sdk.Result) {
return app.runTx(runTxModeCheck, nil, tx)
}
// nolint - full tx execution
func (app *BaseApp) Simulate(tx sdk.Tx) (result sdk.Result) {
return app.runTx(runTxModeSimulate, nil, tx)
}
// nolint
func (app *BaseApp) Deliver(tx sdk.Tx) (result sdk.Result) {
return app.runTx(runTxModeDeliver, nil, tx)
}
// Basic validator for msgs
func validateBasicTxMsgs(msgs []sdk.Msg) sdk.Error {
if msgs == nil || len(msgs) == 0 {
// TODO: probably shouldn't be ErrInternal. Maybe new ErrInvalidMessage, or ?
@ -519,67 +479,29 @@ func validateBasicTxMsgs(msgs []sdk.Msg) sdk.Error {
return err
}
}
return nil
}
// Returns deliverState if app is in runTxModeDeliver, otherwhise returns checkstate
func getState(app *BaseApp, mode runTxMode) *state {
func (app *BaseApp) getContextForAnte(mode runTxMode, txBytes []byte) (ctx sdk.Context) {
// Get the context
if mode == runTxModeCheck || mode == runTxModeSimulate {
return app.checkState
ctx = app.checkState.ctx.WithTxBytes(txBytes)
} else {
ctx = app.deliverState.ctx.WithTxBytes(txBytes)
ctx = ctx.WithSigningValidators(app.signedValidators)
}
return app.deliverState
// Simulate a DeliverTx for gas calculation
if mode == runTxModeSimulate {
ctx = ctx.WithIsCheckTx(false)
}
return
}
// txBytes may be nil in some cases, eg. in tests.
// Also, in the future we may support "internal" transactions.
// nolint: gocyclo
func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk.Result) {
//NOTE: GasWanted should be returned by the AnteHandler.
// GasUsed is determined by the GasMeter.
// We need access to the context to get the gas meter so
// we initialize upfront
var gasWanted int64
ctx := app.getContextForAnte(mode, txBytes)
// Handle any panics.
defer func() {
if r := recover(); r != nil {
switch rType := r.(type) {
case sdk.ErrorOutOfGas:
log := fmt.Sprintf("out of gas in location: %v", rType.Descriptor)
result = sdk.ErrOutOfGas(log).Result()
default:
log := fmt.Sprintf("recovered: %v\nstack:\n%v", r, string(debug.Stack()))
result = sdk.ErrInternal(log).Result()
}
}
result.GasWanted = gasWanted
result.GasUsed = ctx.GasMeter().GasConsumed()
}()
// Get the Msg.
var msgs = tx.GetMsgs()
err := validateBasicTxMsgs(msgs)
if err != nil {
return err.Result()
}
// Run the ante handler.
if app.anteHandler != nil {
newCtx, anteResult, abort := app.anteHandler(ctx, tx)
if abort {
return anteResult
}
if !newCtx.IsZero() {
ctx = newCtx
}
gasWanted = anteResult.GasWanted
}
// Get the correct cache, CacheWrap app.checkState.ms in case it fails.
msCache := getState(app, mode).CacheMultiStore()
ctx = ctx.WithMultiStore(msCache)
// Iterates through msgs and executes them
func (app *BaseApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg) (result sdk.Result) {
// accumulate results
logs := make([]string, 0, len(msgs))
var data []byte // NOTE: we just append them all (?!)
@ -615,39 +537,84 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk
// Set the final gas values.
result = sdk.Result{
Code: code,
Data: data,
Log: strings.Join(logs, "\n"),
GasWanted: gasWanted,
GasUsed: ctx.GasMeter().GasConsumed(),
Code: code,
Data: data,
Log: strings.Join(logs, "\n"),
GasUsed: ctx.GasMeter().GasConsumed(),
// TODO: FeeAmount/FeeDenom
Tags: tags,
}
return result
}
// Returns deliverState if app is in runTxModeDeliver, otherwhise returns checkstate
func getState(app *BaseApp, mode runTxMode) *state {
if mode == runTxModeCheck || mode == runTxModeSimulate {
return app.checkState
}
return app.deliverState
}
// txBytes may be nil in some cases, eg. in tests.
// Also, in the future we may support "internal" transactions.
func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk.Result) {
//NOTE: GasWanted should be returned by the AnteHandler.
// GasUsed is determined by the GasMeter.
// We need access to the context to get the gas meter so
// we initialize upfront
var gasWanted int64
ctx := app.getContextForAnte(mode, txBytes)
// Handle any panics.
defer func() {
if r := recover(); r != nil {
switch rType := r.(type) {
case sdk.ErrorOutOfGas:
log := fmt.Sprintf("out of gas in location: %v", rType.Descriptor)
result = sdk.ErrOutOfGas(log).Result()
default:
log := fmt.Sprintf("recovered: %v\nstack:\n%v", r, string(debug.Stack()))
result = sdk.ErrInternal(log).Result()
}
}
result.GasWanted = gasWanted
result.GasUsed = ctx.GasMeter().GasConsumed()
}()
// Get the Msg.
var msgs = tx.GetMsgs()
err := validateBasicTxMsgs(msgs)
if err != nil {
return err.Result()
}
// Run the ante handler.
if app.anteHandler != nil {
newCtx, anteResult, abort := app.anteHandler(ctx, tx)
if abort {
return anteResult
}
if !newCtx.IsZero() {
ctx = newCtx
}
gasWanted = result.GasWanted
}
// CacheWrap the state in case it fails.
msCache := getState(app, mode).CacheMultiStore()
ctx = ctx.WithMultiStore(msCache)
result = app.runMsgs(ctx, msgs)
result.GasWanted = gasWanted
// Only update state if all messages pass and we're not in a simulation.
if result.IsOK() && mode != runTxModeSimulate {
msCache.Write()
}
return result
}
func (app *BaseApp) getContextForAnte(mode runTxMode, txBytes []byte) sdk.Context {
var ctx sdk.Context
// Get the context.
if mode == runTxModeCheck || mode == runTxModeSimulate {
ctx = app.checkState.ctx.WithTxBytes(txBytes)
} else {
ctx = app.deliverState.ctx.WithTxBytes(txBytes)
ctx = ctx.WithSigningValidators(app.signedValidators)
}
// Simulate a DeliverTx for gas calculation.
if mode == runTxModeSimulate {
ctx = ctx.WithIsCheckTx(false)
}
return ctx
return
}
// Implements ABCI

View File

@ -139,6 +139,21 @@ func testLoadVersionHelper(t *testing.T, app *BaseApp, expectedHeight int64, exp
require.Equal(t, expectedID, lastID)
}
func TestOptionFunction(t *testing.T) {
logger := defaultLogger()
db := dbm.NewMemDB()
codec := wire.NewCodec()
registerTestCodec(codec)
bap := NewBaseApp("starting name", codec, logger, db, testChangeNameHelper("new name"))
require.Equal(t, bap.name, "new name", "BaseApp should have had name changed via option function")
}
func testChangeNameHelper(name string) func(*BaseApp) {
return func(bap *BaseApp) {
bap.name = name
}
}
// Test that the app hash is static
// TODO: https://github.com/cosmos/cosmos-sdk/issues/520
/*func TestStaticAppHash(t *testing.T) {

View File

@ -1,11 +1,27 @@
package baseapp
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tendermint/tendermint/abci/server"
abci "github.com/tendermint/tendermint/abci/types"
cmn "github.com/tendermint/tendermint/libs/common"
)
// nolint - Mostly for testing
func (app *BaseApp) Check(tx sdk.Tx) (result sdk.Result) {
return app.runTx(runTxModeCheck, nil, tx)
}
// nolint - full tx execution
func (app *BaseApp) Simulate(tx sdk.Tx) (result sdk.Result) {
return app.runTx(runTxModeSimulate, nil, tx)
}
// nolint
func (app *BaseApp) Deliver(tx sdk.Tx) (result sdk.Result) {
return app.runTx(runTxModeDeliver, nil, tx)
}
// RunForever - BasecoinApp execution and cleanup
func RunForever(app abci.Application) {

View File

@ -164,7 +164,11 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci
}
// load the initial stake information
stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData)
err = stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData)
if err != nil {
panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468
// return sdk.ErrGenesisParse("").TraceCause(err, "")
}
gov.InitGenesis(ctx, app.govKeeper, gov.DefaultGenesisState())

View File

@ -228,8 +228,7 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci
var genesisState gaia.GenesisState
err := app.cdc.UnmarshalJSON(stateJSON, &genesisState)
if err != nil {
panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468
// return sdk.ErrGenesisParse("").TraceCause(err, "")
panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 // return sdk.ErrGenesisParse("").TraceCause(err, "")
}
// load the accounts
@ -239,7 +238,10 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci
}
// load the initial stake information
stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData)
return abci.ResponseInitChain{}
err = stake.InitGenesis(ctx, app.stakeKeeper, genesisState.StakeData)
if err != nil {
panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 // return sdk.ErrGenesisParse("").TraceCause(err, "")
}
return abci.ResponseInitChain{}
}

View File

@ -310,11 +310,11 @@ WantedBy=multi-user.target
## Delegating to a Validator
On the upcoming mainnet, you can delegate `atom` to a validator. These [delegators](https://cosmos.network/resources/delegators) can receive part of the validator's fee revenue. Read more about the [Cosmos Token Model](https://github.com/cosmos/cosmos/raw/master/Cosmos_Token_Model.pdf).
On the upcoming mainnet, you can delegate `Atom` to a validator. These [delegators](https://cosmos.network/resources/delegators) can receive part of the validator's fee revenue. Read more about the [Cosmos Token Model](https://github.com/cosmos/cosmos/raw/master/Cosmos_Token_Model.pdf).
### Bond Tokens
On the testnet, we delegate `steak` instead of `atom`. Here's how you can bond tokens to a testnet validator:
On the testnet, we delegate `steak` instead of `Atom`. Here's how you can bond tokens to a testnet validator:
```bash
gaiacli stake delegate \
@ -353,6 +353,90 @@ gaiacli stake delegation \
--chain-id=gaia-6002
```
## Governance
Governance is the process from which users in the Cosmos Hub can come to consensus on software upgrades, parameters of the mainnet or on custom text proposals. This is done through voting on proposals, which will be submitted by `Atom` holders on the mainnet.
Some considerations about the voting process:
- Voting is done by bonded `Atom` holders on a 1 bonded `Atom` 1 vote basis
- Delegators inherit the vote of their validator if they don't vote
- **Validators MUST vote on every proposal**. If a validator does not vote on a proposal, they will be **partially slashed**
- Votes are tallied at the end of the voting period (2 weeks on mainnet). Each address can vote multiple times to update its `Option` value (paying the transaction fee each time), only the last casted vote will count as valid
- Voters can choose between options `Yes`, `No`, `NoWithVeto` and `Abstain`
At the end of the voting period, a proposal is accepted if `(YesVotes/(YesVotes+NoVotes+NoWithVetoVotes))>1/2` and `(NoWithVetoVotes/(YesVotes+NoVotes+NoWithVetoVotes))<1/3`. It is rejected otherwise
For more information about the governance process and how it works, please check out the Governance module [specification](https://github.com/cosmos/cosmos-sdk/tree/develop/docs/spec/governance).
### Create a Governance proposal
In order to create a governance proposal, you must submit an initial deposit along with the proposal details:
- `title`: Title of the proposal
- `description`: Description of the proposal
- `type`: Type of proposal. Must be of value _Text_ (types _SoftwareUpgrade_ and _ParameterChange_ not supported yet).
```bash
gaiacli gov submit-proposal \
--title=<title> \
--description=<description> \
--type=<Text/ParameterChange/SoftwareUpgrade> \
--proposer=<account_cosmosaccaddr> \
--deposit=<40steak> \
--from=<name> \
--chain-id=gaia-7000
```
### Increase deposit
In order for a proposal to be broadcasted to the network, the amount deposited must be above a `minDeposit` value (default: `10 steak`). If the proposal you previously created didn't meet this requirement, you can still increase the total amount deposited to activate it. Once the minimum deposit is reached, the proposal enters voting period:
```bash
gaiacli gov deposit \
--proposalID=<proposal_id> \
--depositer=<account_cosmosaccaddr> \
--deposit=<200steak> \
--from=<name> \
--chain-id=gaia-7000
```
> _NOTE_: Proposals that don't meet this requirement will be deleted after `MaxDepositPeriod` is reached.
#### Query proposal
Once created, you can now query information of the proposal:
```bash
gaiacli gov query-proposal \
--proposalID=<proposal_id> \
--chain-id=gaia-7000
```
### Vote on a proposal
After a proposal's deposit reaches the `MinDeposit` value, the voting period opens. Bonded `Atom` holders can then cast vote on it:
```bash
gaiacli gov vote \
--proposalID=<proposal_id> \
--voter=<account_cosmosaccaddr> \
--option=<Yes/No/NoWithVeto/Abstain> \
--from=<name> \
--chain-id=gaia-7000
```
#### Query vote
Check the vote with the option you just submitted:
```bash
gaiacli gov query-vote \
--proposalID=<proposal_id> \
--voter=<account_cosmosaccaddr> \
--chain-id=gaia-7000
```
## Other Operations
### Send Tokens
@ -365,7 +449,7 @@ gaiacli send \
--to=<destination_cosmosaccaddr>
```
> _*Note:*_ The `--amount` flag accepts the format `--amount=<value|coin_name>`.
> _*NOTE:*_ The `--amount` flag accepts the format `--amount=<value|coin_name>`.
Now, view the updated balances of the origin and destination accounts:

View File

@ -61,7 +61,10 @@ func getInitChainer(mapp *mock.App, keeper Keeper, stakeKeeper stake.Keeper) sdk
stakeGenesis := stake.DefaultGenesisState()
stakeGenesis.Pool.LooseTokens = 100000
stake.InitGenesis(ctx, stakeKeeper, stakeGenesis)
err := stake.InitGenesis(ctx, stakeKeeper, stakeGenesis)
if err != nil {
panic(err)
}
InitGenesis(ctx, keeper, DefaultGenesisState())
return abci.ResponseInitChain{}
}

View File

@ -27,7 +27,7 @@ func (tx testMsg) Type() string { return msgType }
func (tx testMsg) GetMsg() sdk.Msg { return tx }
func (tx testMsg) GetMemo() string { return "" }
func (tx testMsg) GetSignBytes() []byte { return nil }
func (tx testMsg) GetSigners() []sdk.AccAddress { return tx.signers }
func (tx testMsg) GetSigners() []sdk.AccAddress { return tx.signers }
func (tx testMsg) GetSignatures() []auth.StdSignature { return nil }
func (tx testMsg) ValidateBasic() sdk.Error {
if tx.positiveNum >= 0 {

View File

@ -55,7 +55,10 @@ func getInitChainer(mapp *mock.App, keeper stake.Keeper) sdk.InitChainer {
mapp.InitChainer(ctx, req)
stakeGenesis := stake.DefaultGenesisState()
stakeGenesis.Pool.LooseTokens = 100000
stake.InitGenesis(ctx, keeper, stakeGenesis)
err := stake.InitGenesis(ctx, keeper, stakeGenesis)
if err != nil {
panic(err)
}
return abci.ResponseInitChain{}
}
}

View File

@ -64,7 +64,9 @@ func createTestInput(t *testing.T) (sdk.Context, bank.Keeper, stake.Keeper, Keep
sk := stake.NewKeeper(cdc, keyStake, ck, stake.DefaultCodespace)
genesis := stake.DefaultGenesisState()
genesis.Pool.LooseTokens = initCoins.MulRaw(int64(len(addrs))).Int64()
stake.InitGenesis(ctx, sk, genesis)
err = stake.InitGenesis(ctx, sk, genesis)
require.Nil(t, err)
for _, addr := range addrs {
_, _, err = ck.AddCoins(ctx, addr, sdk.Coins{
{sk.GetParams(ctx).BondDenom, initCoins},

View File

@ -65,7 +65,10 @@ func getInitChainer(mapp *mock.App, keeper Keeper) sdk.InitChainer {
stakeGenesis := DefaultGenesisState()
stakeGenesis.Pool.LooseTokens = 100000
InitGenesis(ctx, keeper, stakeGenesis)
err := InitGenesis(ctx, keeper, stakeGenesis)
if err != nil {
panic(err)
}
return abci.ResponseInitChain{}
}
@ -83,7 +86,6 @@ func checkValidator(t *testing.T, mapp *mock.App, keeper Keeper,
return validator
}
func checkDelegation(
t *testing.T, mapp *mock.App, keeper Keeper, delegatorAddr,
validatorAddr sdk.AccAddress, expFound bool, expShares sdk.Rat,

View File

@ -240,15 +240,10 @@ func getShares(storeName string, cdc *wire.Codec, sharesAmountStr, sharesPercent
key := stake.GetDelegationKey(delegatorAddr, validatorAddr)
ctx := context.NewCoreContextFromViper()
resQuery, err := ctx.QueryStore(key, storeName)
if err != nil {
return sharesAmount, err
}
var delegation stake.Delegation
err = cdc.UnmarshalBinary(resQuery, &delegation)
if err != nil {
return sharesAmount, errors.Errorf("cannot find delegation to determine percent Error: %v", err)
}
delegation := types.MustUnmarshalDelegation(cdc, key, resQuery)
sharesAmount = sharesPercent.Mul(delegation.Shares)
}
return

View File

@ -3,6 +3,7 @@ package stake
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/stake/types"
"github.com/pkg/errors"
tmtypes "github.com/tendermint/tendermint/types"
)
@ -11,7 +12,7 @@ import (
// validator in the keeper along with manually setting the indexes. In
// addition, it also sets any delegations found in data. Finally, it updates
// the bonded validators.
func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) {
func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) error {
keeper.SetPool(ctx, data.Pool)
keeper.SetNewParams(ctx, data.Params)
keeper.InitIntraTxCounter(ctx)
@ -19,6 +20,13 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) {
for _, validator := range data.Validators {
keeper.SetValidator(ctx, validator)
if validator.PoolShares.Amount.IsZero() {
return errors.Errorf("genesis validator cannot have zero pool shares, validator: %v", validator)
}
if validator.DelegatorShares.IsZero() {
return errors.Errorf("genesis validator cannot have zero delegator shares, validator: %v", validator)
}
// Manually set indexes for the first time
keeper.SetValidatorByPubKeyIndex(ctx, validator)
keeper.SetValidatorByPowerIndex(ctx, validator, data.Pool)
@ -33,6 +41,7 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) {
}
keeper.UpdateBondedValidatorsFull(ctx)
return nil
}
// WriteGenesis returns a GenesisState for a given context and keeper. The

37
x/stake/genesis_test.go Normal file
View File

@ -0,0 +1,37 @@
package stake
import (
"testing"
"github.com/stretchr/testify/require"
sdk "github.com/cosmos/cosmos-sdk/types"
keep "github.com/cosmos/cosmos-sdk/x/stake/keeper"
"github.com/cosmos/cosmos-sdk/x/stake/types"
)
func TestInitGenesis(t *testing.T) {
ctx, _, keeper := keep.CreateTestInput(t, false, 1000)
pool := keeper.GetPool(ctx)
pool.UnbondedTokens = 1
pool.UnbondedShares = sdk.OneRat()
params := keeper.GetParams(ctx)
var delegations []Delegation
validators := []Validator{
NewValidator(keep.Addrs[0], keep.PKs[0], Description{Moniker: "hoop"}),
}
genesisState := types.NewGenesisState(pool, params, validators, delegations)
err := InitGenesis(ctx, keeper, genesisState)
require.Error(t, err)
validators[0].PoolShares.Amount = sdk.OneRat()
validators[0].DelegatorShares = sdk.OneRat()
genesisState = types.NewGenesisState(pool, params, validators, delegations)
err = InitGenesis(ctx, keeper, genesisState)
require.NoError(t, err)
}

View File

@ -156,7 +156,7 @@ func GetUBDsByValIndexKey(validatorAddr sdk.AccAddress) []byte {
// get the key for a redelegation
// VALUE: stake/types.RedelegationKey
func GetREDKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte {
func GetREDKey(delegatorAddr, validatorSrcAddr, validatorDstAddr sdk.AccAddress) []byte {
return append(append(
GetREDsKey(delegatorAddr.Bytes()),
validatorSrcAddr.Bytes()...),