Merge PR #4086: Merge release/v0.34.0

This commit is contained in:
Alexander Bezobchuk 2019-04-15 10:48:11 -04:00 committed by GitHub
commit ea8539ee5e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
60 changed files with 390 additions and 108 deletions

1
.gitignore vendored
View File

@ -7,6 +7,7 @@
*.swn
.vscode
.idea
*.pyc
# Build
vendor

View File

@ -1 +0,0 @@
#3463 Revert bank module handler fork (re-enables transfers)

View File

@ -1,3 +0,0 @@
#3875 Replace `async` flag with `--broadcast-mode` flag where the default
value is `sync`. The `block` mode should not be used. The REST client now
uses `mode` parameter instead of the `return` parameter.

View File

@ -1 +0,0 @@
#3938 Remove REST server's SSL support altogether.

View File

@ -1 +0,0 @@
#3245 Rename validator.GetJailed() to validator.IsJailed()

View File

@ -1,2 +0,0 @@
#3516 Remove concept of shares from staking unbonding and redelegation UX;
replaced by direct coin amount.

View File

@ -1 +0,0 @@
#4029 Upgrade Tendermint to v0.31.3

View File

@ -1 +0,0 @@
#3825 Validate genesis before running gentx

View File

@ -1,2 +0,0 @@
#3889 When `--generate-only` is provided, the Keybase is not used and as a result
the `--from` value must be a valid Bech32 cosmos address.

View File

@ -1 +0,0 @@
3974 Fix go env setting in installation.md

View File

@ -1 +0,0 @@
3996 Change 'make get_tools' to 'make tools' in DOCS_README.md.

View File

@ -1 +0,0 @@
#3883 Remove Height Flag from CLI Queries

View File

@ -1 +0,0 @@
#3899 Using 'gaiacli config node' breaks ~/config/config.toml

View File

@ -1 +0,0 @@
#3837 Fix `WithdrawValidatorCommission` to properly set the validator's remaining commission.

View File

@ -1,2 +0,0 @@
#3870 Fix DecCoins#TruncateDecimal to never return zero coins in
either the truncated coins or the change coins.

View File

@ -1 +0,0 @@
#3915 Remove ';' delimiting support from ParseDecCoins

View File

@ -1 +0,0 @@
#3977 Fix docker image build

View File

@ -1 +0,0 @@
#2935 Optionally assert invariants on a blockly basis using `gaiad --assert-invariants-blockly`

View File

@ -1 +0,0 @@
#3886 Implement minting module querier and CLI/REST clients.

View File

@ -1 +0,0 @@
#3937 Add command to query community-pool

View File

@ -1 +0,0 @@
#3937 Add route to fetch community-pool

View File

@ -1 +0,0 @@
#3949 added /slashing/signing_infos to get signing_info for all validators

View File

@ -1 +0,0 @@
#2935 New module Crisis which can test broken invariant with messages

View File

@ -1 +0,0 @@
#3813 New sdk.NewCoins safe constructor to replace bare sdk.Coins{} declarations.

View File

@ -1 +0,0 @@
#3858 add website, details and identity to gentx cli command

View File

@ -1 +0,0 @@
Implement coin conversion and denomination registration utilities

View File

@ -1 +0,0 @@
#3808 `gaiad` and `gaiacli` integration tests use ./build/ binaries.

View File

@ -1,7 +0,0 @@
\#3819 Simulation refactor, log output now stored in ~/.gaiad/simulation/
* Simulation moved to its own module (not a part of mock)
* Logger type instead of passing function variables everywhere
* Logger json output (for reloadable simulation running)
* Cleanup bank simulation messages / remove dup code in bank simulation
* Simulations saved in `~/.gaiad/simulations/`
* "Lean" simulation output option to exclude No-ops and !ok functions (`--SimulationLean` flag)

View File

@ -1,4 +0,0 @@
#3893 Improve `gaiacli tx sign` command
* Add shorthand flags -a and -s for the account and sequence numbers respectively
* Mark the account and sequence numbers required during "offline" mode
* Always do an RPC query for account and sequence number during "online" mode

View File

@ -1 +0,0 @@
#3833 Modify stake to atom in gaia's doc.

View File

@ -1 +0,0 @@
#3841 Add indent to JSON of `gaiacli keys [add|show|list]`

View File

@ -1 +0,0 @@
#3859 Add newline to echo of `gaiacli keys ...`

View File

@ -1 +0,0 @@
#3959 Improving error messages when signing with ledger devices fails

View File

@ -1,2 +0,0 @@
#3238 Add block time to tx responses when querying for
txs by tags or hash.

View File

@ -1 +0,0 @@
\#3752 Explanatory docs for minting mechanism (`docs/spec/mint/01_concepts.md`)

View File

@ -1 +0,0 @@
#3801 `baseapp` safety improvements

View File

@ -1 +0,0 @@
#3820 Make Coins.IsAllGT() more robust and consistent.

View File

@ -1 +0,0 @@
#3828 New sdkch tool to maintain changelogs

View File

@ -1 +0,0 @@
#3864 Make Coins.IsAllGTE() more consistent.

View File

@ -1,3 +0,0 @@
#3907: dep -> go mod migration
- Drop dep in favor of go modules.
- Upgrade to Go 1.12.1.

View File

@ -1 +0,0 @@
#3917 Allow arbitrary decreases to validator commission rates.

View File

@ -1 +0,0 @@
#3937 Implement community pool querier.

View File

@ -1 +0,0 @@
#3940 Codespace should be lowercase.

View File

@ -1 +0,0 @@
#3986 Update the Stringer implementation of the Proposal type.

View File

@ -1 +0,0 @@
\#926 circuit breaker high level explanation

View File

@ -1 +0,0 @@
Fixed various linters warnings in the context of the gometalinter -> golangci-lint migration #3896.

View File

@ -1,5 +1,169 @@
# Changelog
* [0.34.0](#0340)
* [Breaking Changes](#breaking-changes)
* [Gaia](#gaia)
* [Gaia CLI](#gaia-cli)
* [SDK](#sdk)
* [Tendermint](#tendermint)
* [New features](#new-features)
* [SDK](#sdk-1)
* [Gaia](#gaia-1)
* [Gaia CLI](#gaia-cli-1)
* [Gaia REST API](#gaia-rest-api)
* [Improvements](#improvements)
* [Gaia](#gaia-2)
* [Gaia CLI](#gaia-cli-2)
* [SDK](#sdk-2)
* [Bug Fixes](#bug-fixes)
* [Gaia](#gaia-3)
* [Gaia CLI](#gaia-cli-3)
* [SDK](#sdk-3)
* [0.33.2](#0332)
* [Improvements](#improvements-1)
* [Tendermint](#tendermint-1)
* [0.33.1](#0331)
* [Bug Fixes](#bug-fixes-1)
* [Gaia](#gaia-4)
## 0.34.0
### Breaking Changes
#### Gaia
* [\#3463](https://github.com/cosmos/cosmos-sdk/issues/3463) Revert bank module handler fork (re-enables transfers)
* [\#3875](https://github.com/cosmos/cosmos-sdk/issues/3875) Replace `async` flag with `--broadcast-mode` flag where the default
value is `sync`. The `block` mode should not be used. The REST client now
uses `mode` parameter instead of the `return` parameter.
#### Gaia CLI
* [\#3938](https://github.com/cosmos/cosmos-sdk/issues/3938) Remove REST server's SSL support altogether.
#### SDK
* [\#3245](https://github.com/cosmos/cosmos-sdk/issues/3245) Rename validator.GetJailed() to validator.IsJailed()
* [\#3516](https://github.com/cosmos/cosmos-sdk/issues/3516) Remove concept of shares from staking unbonding and redelegation UX;
replaced by direct coin amount.
#### Tendermint
* [\#4029](https://github.com/cosmos/cosmos-sdk/issues/4029) Upgrade Tendermint to v0.31.3
### New features
#### SDK
* [\#2935](https://github.com/cosmos/cosmos-sdk/issues/2935) New module Crisis which can test broken invariant with messages
* [\#3813](https://github.com/cosmos/cosmos-sdk/issues/3813) New sdk.NewCoins safe constructor to replace bare sdk.Coins{} declarations.
* [\#3858](https://github.com/cosmos/cosmos-sdk/issues/3858) add website, details and identity to gentx cli command
* Implement coin conversion and denomination registration utilities
#### Gaia
* [\#2935](https://github.com/cosmos/cosmos-sdk/issues/2935) Optionally assert invariants on a blockly basis using `gaiad --assert-invariants-blockly`
* [\#3886](https://github.com/cosmos/cosmos-sdk/issues/3886) Implement minting module querier and CLI/REST clients.
#### Gaia CLI
* [\#3937](https://github.com/cosmos/cosmos-sdk/issues/3937) Add command to query community-pool
#### Gaia REST API
* [\#3937](https://github.com/cosmos/cosmos-sdk/issues/3937) Add route to fetch community-pool
* [\#3949](https://github.com/cosmos/cosmos-sdk/issues/3949) added /slashing/signing_infos to get signing_info for all validators
### Improvements
#### Gaia
* [\#3808](https://github.com/cosmos/cosmos-sdk/issues/3808) `gaiad` and `gaiacli` integration tests use ./build/ binaries.
* \[\#3819](https://github.com/cosmos/cosmos-sdk/issues/3819) Simulation refactor, log output now stored in ~/.gaiad/simulation/
* Simulation moved to its own module (not a part of mock)
* Logger type instead of passing function variables everywhere
* Logger json output (for reloadable simulation running)
* Cleanup bank simulation messages / remove dup code in bank simulation
* Simulations saved in `~/.gaiad/simulations/`
* "Lean" simulation output option to exclude No-ops and !ok functions (`--SimulationLean` flag)
* [\#3893](https://github.com/cosmos/cosmos-sdk/issues/3893) Improve `gaiacli tx sign` command
* Add shorthand flags -a and -s for the account and sequence numbers respectively
* Mark the account and sequence numbers required during "offline" mode
* Always do an RPC query for account and sequence number during "online" mode
* [\#4018](https://github.com/cosmos/cosmos-sdk/issues/4018) create genesis port script for release v.0.34.0
#### Gaia CLI
* [\#3833](https://github.com/cosmos/cosmos-sdk/issues/3833) Modify stake to atom in gaia's doc.
* [\#3841](https://github.com/cosmos/cosmos-sdk/issues/3841) Add indent to JSON of `gaiacli keys [add|show|list]`
* [\#3859](https://github.com/cosmos/cosmos-sdk/issues/3859) Add newline to echo of `gaiacli keys ...`
* [\#3959](https://github.com/cosmos/cosmos-sdk/issues/3959) Improving error messages when signing with ledger devices fails
#### SDK
* [\#3238](https://github.com/cosmos/cosmos-sdk/issues/3238) Add block time to tx responses when querying for
txs by tags or hash.
* \[\#3752](https://github.com/cosmos/cosmos-sdk/issues/3752) Explanatory docs for minting mechanism (`docs/spec/mint/01_concepts.md`)
* [\#3801](https://github.com/cosmos/cosmos-sdk/issues/3801) `baseapp` safety improvements
* [\#3820](https://github.com/cosmos/cosmos-sdk/issues/3820) Make Coins.IsAllGT() more robust and consistent.
* [\#3828](https://github.com/cosmos/cosmos-sdk/issues/3828) New sdkch tool to maintain changelogs
* [\#3864](https://github.com/cosmos/cosmos-sdk/issues/3864) Make Coins.IsAllGTE() more consistent.
* [\#3907](https://github.com/cosmos/cosmos-sdk/issues/3907): dep -> go mod migration
* Drop dep in favor of go modules.
* Upgrade to Go 1.12.1.
* [\#3917](https://github.com/cosmos/cosmos-sdk/issues/3917) Allow arbitrary decreases to validator commission rates.
* [\#3937](https://github.com/cosmos/cosmos-sdk/issues/3937) Implement community pool querier.
* [\#3940](https://github.com/cosmos/cosmos-sdk/issues/3940) Codespace should be lowercase.
* [\#3986](https://github.com/cosmos/cosmos-sdk/issues/3986) Update the Stringer implementation of the Proposal type.
* [\#926](https://github.com/cosmos/cosmos-sdk/issues/926) circuit breaker high level explanation
* [\#3896](https://github.com/cosmos/cosmos-sdk/issues/3896) Fixed various linters warnings in the context of the gometalinter -> golangci-lint migration
* [\#3916](https://github.com/cosmos/cosmos-sdk/issues/3916) Hex encode data in tx responses
### Bug Fixes
#### Gaia
* [\#3825](https://github.com/cosmos/cosmos-sdk/issues/3825) Validate genesis before running gentx
* [\#3889](https://github.com/cosmos/cosmos-sdk/issues/3889) When `--generate-only` is provided, the Keybase is not used and as a result
the `--from` value must be a valid Bech32 cosmos address.
* 3974 Fix go env setting in installation.md
* 3996 Change 'make get_tools' to 'make tools' in DOCS_README.md.
#### Gaia CLI
* [\#3883](https://github.com/cosmos/cosmos-sdk/issues/3883) Remove Height Flag from CLI Queries
* [\#3899](https://github.com/cosmos/cosmos-sdk/issues/3899) Using 'gaiacli config node' breaks ~/config/config.toml
#### SDK
* [\#3837](https://github.com/cosmos/cosmos-sdk/issues/3837) Fix `WithdrawValidatorCommission` to properly set the validator's remaining commission.
* [\#3870](https://github.com/cosmos/cosmos-sdk/issues/3870) Fix DecCoins#TruncateDecimal to never return zero coins in
either the truncated coins or the change coins.
* [\#3915](https://github.com/cosmos/cosmos-sdk/issues/3915) Remove ';' delimiting support from ParseDecCoins
* [\#3977](https://github.com/cosmos/cosmos-sdk/issues/3977) Fix docker image build
* [\#4020](https://github.com/cosmos/cosmos-sdk/issues/4020) Fix queryDelegationRewards by returning an error
when the validator or delegation do not exist.
* [\#4050](https://github.com/cosmos/cosmos-sdk/issues/4050) Fix DecCoins APIs
where rounding or truncation could result in zero decimal coins.
* [\#4088](https://github.com/cosmos/cosmos-sdk/issues/4088) Fix `calculateDelegationRewards`
by accounting for rounding errors when multiplying stake by slashing fractions.
## 0.33.2
### Improvements
#### Tendermint
* Upgrade Tendermint to `v0.31.0-dev0-fix0` which includes critical security fixes.
## 0.33.1
### Bug Fixes
#### Gaia
* [\#3999](https://github.com/cosmos/cosmos-sdk/pull/3999) Fix distribution delegation for zero height export bug
## 0.33.0
BREAKING CHANGES

View File

@ -610,7 +610,9 @@ func TestSubmitProposal(t *testing.T) {
require.Equal(t, uint32(0), resultTx.Code)
var proposalID uint64
cdc.MustUnmarshalBinaryLengthPrefixed(resultTx.Data, &proposalID)
bz, err := hex.DecodeString(resultTx.Data)
require.NoError(t, err)
cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID)
// verify balance
acc = getAccount(t, port, addr)
@ -645,7 +647,9 @@ func TestDeposit(t *testing.T) {
require.Equal(t, uint32(0), resultTx.Code)
var proposalID uint64
cdc.MustUnmarshalBinaryLengthPrefixed(resultTx.Data, &proposalID)
bz, err := hex.DecodeString(resultTx.Data)
require.NoError(t, err)
cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID)
// verify balance
acc = getAccount(t, port, addr)
@ -702,7 +706,9 @@ func TestVote(t *testing.T) {
require.Equal(t, uint32(0), resultTx.Code)
var proposalID uint64
cdc.MustUnmarshalBinaryLengthPrefixed(resultTx.Data, &proposalID)
bz, err := hex.DecodeString(resultTx.Data)
require.NoError(t, err)
cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID)
// verify balance
acc = getAccount(t, port, addr)
@ -803,18 +809,24 @@ func TestProposalsQuery(t *testing.T) {
// Addr1 proposes (and deposits) proposals #1 and #2
resultTx := doSubmitProposal(t, port, seeds[0], names[0], passwords[0], addrs[0], halfMinDeposit, fees)
var proposalID1 uint64
cdc.MustUnmarshalBinaryLengthPrefixed(resultTx.Data, &proposalID1)
bz, err := hex.DecodeString(resultTx.Data)
require.NoError(t, err)
cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID1)
tests.WaitForHeight(resultTx.Height+1, port)
resultTx = doSubmitProposal(t, port, seeds[0], names[0], passwords[0], addrs[0], halfMinDeposit, fees)
var proposalID2 uint64
cdc.MustUnmarshalBinaryLengthPrefixed(resultTx.Data, &proposalID2)
bz, err = hex.DecodeString(resultTx.Data)
require.NoError(t, err)
cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID2)
tests.WaitForHeight(resultTx.Height+1, port)
// Addr2 proposes (and deposits) proposals #3
resultTx = doSubmitProposal(t, port, seeds[1], names[1], passwords[1], addrs[1], halfMinDeposit, fees)
var proposalID3 uint64
cdc.MustUnmarshalBinaryLengthPrefixed(resultTx.Data, &proposalID3)
bz, err = hex.DecodeString(resultTx.Data)
require.NoError(t, err)
cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID3)
tests.WaitForHeight(resultTx.Height+1, port)
// Addr2 deposits on proposals #2 & #3

28
contrib/export/lib.py Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env python3
import argparse
import json
import sys
def init_default_argument_parser(prog_desc, default_chain_id, default_start_time):
parser = argparse.ArgumentParser(description=prog_desc)
parser.add_argument(
'exported_genesis',
help='exported genesis.json file',
type=argparse.FileType('r'), default=sys.stdin,
)
parser.add_argument('--chain-id', type=str, default=default_chain_id)
parser.add_argument('--start-time', type=str, default=default_start_time)
return parser
def main(argument_parser, process_genesis_func):
args = argument_parser.parse_args()
if args.chain_id.strip() == '':
sys.exit('chain-id required')
genesis = json.loads(args.exported_genesis.read())
print(json.dumps(process_genesis_func(
genesis=genesis, parsed_args=args,), indent=True))

View File

@ -0,0 +1,45 @@
#!/usr/bin/env python3
import lib
def process_raw_genesis(genesis, parsed_args):
# update genesis with breaking changes
genesis['consensus_params']['block'] = genesis['consensus_params']['block_size']
del genesis['consensus_params']['block_size']
genesis['app_state']['crisis'] = {
'constant_fee': {
'amount': '1333000000', # ~$5,000 worth of uatoms
'denom': 'uatom',
},
}
# default tm value
genesis['consensus_params']['block']['time_iota_ms'] = '1000'
# proposal #1 updates
genesis['app_state']['mint']['params']['blocks_per_year'] = '4855015'
# proposal #2 updates
genesis['consensus_params']['block']['max_gas'] = '2000000'
genesis['consensus_params']['block']['max_bytes'] = '200000'
# enable transfers
genesis['app_state']['bank']['send_enabled'] = True
genesis['app_state']['distr']['withdraw_addr_enabled'] = True
# Set new chain ID and genesis start time
genesis['chain_id'] = parsed_args.chain_id.strip()
genesis['genesis_time'] = parsed_args.start_time
return genesis
if __name__ == '__main__':
parser = lib.init_default_argument_parser(
prog_desc='Convert genesis.json from v0.33.x to v0.34.0',
default_chain_id='cosmoshub-n',
default_start_time='2019-02-11T12:00:00Z',
)
lib.main(parser, process_raw_genesis)

2
go.mod
View File

@ -46,7 +46,7 @@ require (
github.com/tendermint/btcd v0.1.1
github.com/tendermint/go-amino v0.14.1
github.com/tendermint/iavl v0.12.1
github.com/tendermint/tendermint v0.31.3
github.com/tendermint/tendermint v0.31.4
github.com/zondax/hid v0.9.0 // indirect
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793
google.golang.org/grpc v1.19.0 // indirect

4
go.sum
View File

@ -147,8 +147,8 @@ github.com/tendermint/go-amino v0.14.1 h1:o2WudxNfdLNBwMyl2dqOJxiro5rfrEaU0Ugs6o
github.com/tendermint/go-amino v0.14.1/go.mod h1:i/UKE5Uocn+argJJBb12qTZsCDBcAYMbR92AaJVmKso=
github.com/tendermint/iavl v0.12.1 h1:JDfyhM/Hhrumu1CL1Nxrypm8sNTPYqmeHo1IZLiJoXM=
github.com/tendermint/iavl v0.12.1/go.mod h1:EoKMMv++tDOL5qKKVnoIqtVPshRrEPeJ0WsgDOLAauM=
github.com/tendermint/tendermint v0.31.3 h1:IlehDNREaGdt/VVZTjs978R/lhmnIf4NOH3j+ZhhbZA=
github.com/tendermint/tendermint v0.31.3/go.mod h1:ymcPyWblXCplCPQjbOYbrF1fWnpslATMVqiGgWbZrlc=
github.com/tendermint/tendermint v0.31.4 h1:F/vZ/fMHZJriAkDLjf9ZrReJQsuELiTmJLqigmbE5NU=
github.com/tendermint/tendermint v0.31.4/go.mod h1:ymcPyWblXCplCPQjbOYbrF1fWnpslATMVqiGgWbZrlc=
github.com/zondax/hid v0.9.0 h1:eiT3P6vNxAEVxXMw66eZUAAnU2zD33JBkfG/EnfAKl8=
github.com/zondax/hid v0.9.0/go.mod h1:l5wttcP0jwtdLjqjMMWFVEE7d1zO0jvSPA9OPZxWpEM=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=

View File

@ -312,55 +312,90 @@ func (coins DecCoins) IsAnyNegative() bool {
return false
}
// multiply all the coins by a decimal
// MulDec multiplies all the coins by a decimal.
//
// CONTRACT: No zero coins will be returned.
func (coins DecCoins) MulDec(d Dec) DecCoins {
res := make([]DecCoin, len(coins))
for i, coin := range coins {
var res DecCoins
for _, coin := range coins {
product := DecCoin{
Denom: coin.Denom,
Amount: coin.Amount.Mul(d),
}
res[i] = product
if !product.IsZero() {
res = res.Add(DecCoins{product})
}
}
return res
}
// multiply all the coins by a decimal, truncating
// MulDecTruncate multiplies all the decimal coins by a decimal, truncating. It
// panics if d is zero.
//
// CONTRACT: No zero coins will be returned.
func (coins DecCoins) MulDecTruncate(d Dec) DecCoins {
res := make([]DecCoin, len(coins))
for i, coin := range coins {
var res DecCoins
for _, coin := range coins {
product := DecCoin{
Denom: coin.Denom,
Amount: coin.Amount.MulTruncate(d),
}
res[i] = product
if !product.IsZero() {
res = res.Add(DecCoins{product})
}
}
return res
}
// divide all the coins by a decimal
// QuoDec divides all the decimal coins by a decimal. It panics if d is zero.
//
// CONTRACT: No zero coins will be returned.
func (coins DecCoins) QuoDec(d Dec) DecCoins {
res := make([]DecCoin, len(coins))
for i, coin := range coins {
if d.IsZero() {
panic("invalid zero decimal")
}
var res DecCoins
for _, coin := range coins {
quotient := DecCoin{
Denom: coin.Denom,
Amount: coin.Amount.Quo(d),
}
res[i] = quotient
if !quotient.IsZero() {
res = res.Add(DecCoins{quotient})
}
}
return res
}
// divide all the coins by a decimal, truncating
// QuoDecTruncate divides all the decimal coins by a decimal, truncating. It
// panics if d is zero.
//
// CONTRACT: No zero coins will be returned.
func (coins DecCoins) QuoDecTruncate(d Dec) DecCoins {
res := make([]DecCoin, len(coins))
for i, coin := range coins {
if d.IsZero() {
panic("invalid zero decimal")
}
var res DecCoins
for _, coin := range coins {
quotient := DecCoin{
Denom: coin.Denom,
Amount: coin.Amount.QuoTruncate(d),
}
res[i] = quotient
if !quotient.IsZero() {
res = res.Add(DecCoins{quotient})
}
}
return res
}

View File

@ -290,3 +290,28 @@ func TestDecCoinsTruncateDecimal(t *testing.T) {
)
}
}
func TestDecCoinsQuoDecTruncate(t *testing.T) {
x := MustNewDecFromStr("1.00")
y := MustNewDecFromStr("10000000000000000000.00")
testCases := []struct {
coins DecCoins
input Dec
result DecCoins
panics bool
}{
{DecCoins{}, ZeroDec(), DecCoins(nil), true},
{DecCoins{NewDecCoinFromDec("foo", x)}, y, DecCoins(nil), false},
{DecCoins{NewInt64DecCoin("foo", 5)}, NewDec(2), DecCoins{NewDecCoinFromDec("foo", MustNewDecFromStr("2.5"))}, false},
}
for i, tc := range testCases {
if tc.panics {
require.Panics(t, func() { tc.coins.QuoDecTruncate(tc.input) })
} else {
res := tc.coins.QuoDecTruncate(tc.input)
require.Equal(t, tc.result, res, "unexpected result; tc #%d, coins: %s, input: %s", i, tc.coins, tc.input)
}
}
}

View File

@ -1,6 +1,7 @@
package types
import (
"encoding/hex"
"encoding/json"
"fmt"
"strings"
@ -67,7 +68,7 @@ type TxResponse struct {
Height int64 `json:"height"`
TxHash string `json:"txhash"`
Code uint32 `json:"code,omitempty"`
Data []byte `json:"data,omitempty"`
Data string `json:"data,omitempty"`
RawLog string `json:"raw_log,omitempty"`
Logs ABCIMessageLogs `json:"logs,omitempty"`
Info string `json:"info,omitempty"`
@ -91,7 +92,7 @@ func NewResponseResultTx(res *ctypes.ResultTx, tx Tx, timestamp string) TxRespon
TxHash: res.Hash.String(),
Height: res.Height,
Code: res.TxResult.Code,
Data: res.TxResult.Data,
Data: strings.ToUpper(hex.EncodeToString(res.TxResult.Data)),
RawLog: res.TxResult.Log,
Logs: parsedLogs,
Info: res.TxResult.Info,
@ -129,7 +130,7 @@ func newTxResponseCheckTx(res *ctypes.ResultBroadcastTxCommit) TxResponse {
Height: res.Height,
TxHash: txHash,
Code: res.CheckTx.Code,
Data: res.CheckTx.Data,
Data: strings.ToUpper(hex.EncodeToString(res.CheckTx.Data)),
RawLog: res.CheckTx.Log,
Logs: parsedLogs,
Info: res.CheckTx.Info,
@ -156,7 +157,7 @@ func newTxResponseDeliverTx(res *ctypes.ResultBroadcastTxCommit) TxResponse {
Height: res.Height,
TxHash: txHash,
Code: res.DeliverTx.Code,
Data: res.DeliverTx.Data,
Data: strings.ToUpper(hex.EncodeToString(res.DeliverTx.Data)),
RawLog: res.DeliverTx.Log,
Logs: parsedLogs,
Info: res.DeliverTx.Info,
@ -177,7 +178,7 @@ func NewResponseFormatBroadcastTx(res *ctypes.ResultBroadcastTx) TxResponse {
return TxResponse{
Code: res.Code,
Data: res.Data.Bytes(),
Data: res.Data.String(),
RawLog: res.Log,
Logs: parsedLogs,
TxHash: res.Hash.String(),
@ -200,8 +201,8 @@ func (r TxResponse) String() string {
sb.WriteString(fmt.Sprintf(" Code: %d\n", r.Code))
}
if r.Data != nil {
sb.WriteString(fmt.Sprintf(" Data: %s\n", string(r.Data)))
if r.Data != "" {
sb.WriteString(fmt.Sprintf(" Data: %s\n", r.Data))
}
if r.RawLog != "" {

View File

@ -75,6 +75,7 @@ type Validator interface {
GetDelegatorShares() Dec // total outstanding delegator shares
TokensFromShares(Dec) Dec // token worth of provided delegator shares
TokensFromSharesTruncated(Dec) Dec // token worth of provided delegator shares, truncated
TokensFromSharesRoundUp(Dec) Dec // token worth of provided delegator shares, rounded up
SharesFromTokens(amt Int) (Dec, Error) // shares worth of delegator's bond
SharesFromTokensTruncated(amt Int) (Dec, Error) // truncated shares worth of delegator's bond
}

View File

@ -64,13 +64,16 @@ func (k Keeper) calculateDelegationRewards(ctx sdk.Context, val sdk.Validator, d
startingPeriod := startingInfo.PreviousPeriod
stake := startingInfo.Stake
// iterate through slashes and withdraw with calculated staking for sub-intervals
// these offsets are dependent on *when* slashes happen - namely, in BeginBlock, after rewards are allocated...
// slashes which happened in the first block would have been before this delegation existed,
// UNLESS they were slashes of a redelegation to this validator which was itself slashed
// (from a fault committed by the redelegation source validator) earlier in the same BeginBlock
// Iterate through slashes and withdraw with calculated staking for
// distribution periods. These period offsets are dependent on *when* slashes
// happen - namely, in BeginBlock, after rewards are allocated...
// Slashes which happened in the first block would have been before this
// delegation existed, UNLESS they were slashes of a redelegation to this
// validator which was itself slashed (from a fault committed by the
// redelegation source validator) earlier in the same BeginBlock.
startingHeight := startingInfo.Height
// slashes this block happened after reward allocation, but we have to account for them for the stake sanity check below
// Slashes this block happened after reward allocation, but we have to account
// for them for the stake sanity check below.
endingHeight := uint64(ctx.BlockHeight())
if endingHeight > startingHeight {
k.IterateValidatorSlashEventsBetween(ctx, del.GetValidatorAddr(), startingHeight, endingHeight,
@ -78,7 +81,9 @@ func (k Keeper) calculateDelegationRewards(ctx sdk.Context, val sdk.Validator, d
endingPeriod := event.ValidatorPeriod
if endingPeriod > startingPeriod {
rewards = rewards.Add(k.calculateDelegationRewardsBetween(ctx, val, startingPeriod, endingPeriod, stake))
// note: necessary to truncate so we don't allow withdrawing more rewards than owed
// Note: It is necessary to truncate so we don't allow withdrawing
// more rewards than owed.
stake = stake.MulTruncate(sdk.OneDec().Sub(event.Fraction))
startingPeriod = endingPeriod
}
@ -87,18 +92,26 @@ func (k Keeper) calculateDelegationRewards(ctx sdk.Context, val sdk.Validator, d
)
}
// a stake sanity check - recalculated final stake should be less than or equal to current stake
// here we cannot use Equals because stake is truncated when multiplied by slash fractions
// we could only use equals if we had arbitrary-precision rationals
// A total stake sanity check; Recalculated final stake should be less than or
// equal to current stake here. We cannot use Equals because stake is truncated
// when multiplied by slash fractions (see above). We could only use equals if
// we had arbitrary-precision rationals.
currentStake := val.TokensFromShares(del.GetShares())
if stake.GT(currentStake) {
panic(fmt.Sprintf("calculated final stake for delegator %s greater than current stake: %s, %s",
del.GetDelegatorAddr(), stake, currentStake))
// account for rounding errors due to stake being multiplied by slash fractions
currentStakeRoundUp := val.TokensFromSharesRoundUp(del.GetShares())
if stake.Equal(currentStakeRoundUp) {
stake = currentStake
} else {
panic(fmt.Sprintf("calculated final stake for delegator %s greater than current stake"+
"\n\tfinal stake:\t%s"+
"\n\tcurrent stake:\t%s",
del.GetDelegatorAddr(), stake, currentStake))
}
}
// calculate rewards for final period
rewards = rewards.Add(k.calculateDelegationRewardsBetween(ctx, val, startingPeriod, endingPeriod, stake))
return rewards
}

View File

@ -207,7 +207,17 @@ func queryDelegationRewards(ctx sdk.Context, _ []string, req abci.RequestQuery,
ctx, _ = ctx.CacheContext()
val := k.stakingKeeper.Validator(ctx, params.ValidatorAddress)
if val == nil {
// TODO: Should use ErrNoValidatorFound from staking/types
return nil, sdk.ErrInternal(fmt.Sprintf("validator %s does not exist", params.ValidatorAddress))
}
del := k.stakingKeeper.Delegation(ctx, params.DelegatorAddress, params.ValidatorAddress)
if del == nil {
// TODO: Should use ErrNoDelegation from staking/types
return nil, sdk.ErrInternal("delegation does not exist")
}
endingPeriod := k.incrementValidatorPeriod(ctx, val)
rewards := k.calculateDelegationRewards(ctx, val, del, endingPeriod)

View File

@ -106,7 +106,10 @@ func (k Keeper) updateValidatorSlashFraction(ctx sdk.Context, valAddr sdk.ValAdd
}
currentMultiplicand := sdk.OneDec().Sub(currentFraction)
newMultiplicand := sdk.OneDec().Sub(fraction)
updatedFraction := sdk.OneDec().Sub(currentMultiplicand.Mul(newMultiplicand))
// using MulTruncate here conservatively increases the slashing amount
updatedFraction := sdk.OneDec().Sub(currentMultiplicand.MulTruncate(newMultiplicand))
if updatedFraction.LT(sdk.ZeroDec()) {
panic("negative slash fraction")
}

View File

@ -421,6 +421,12 @@ func (v Validator) TokensFromSharesTruncated(shares sdk.Dec) sdk.Dec {
return (shares.MulInt(v.Tokens)).QuoTruncate(v.DelegatorShares)
}
// TokensFromSharesRoundUp returns the token worth of provided shares, rounded
// up.
func (v Validator) TokensFromSharesRoundUp(shares sdk.Dec) sdk.Dec {
return (shares.MulInt(v.Tokens)).QuoRoundUp(v.DelegatorShares)
}
// SharesFromTokens returns the shares of a delegation given a bond amount. It
// returns an error if the validator has no tokens.
func (v Validator) SharesFromTokens(amt sdk.Int) (sdk.Dec, sdk.Error) {