Merge pull request #1049 from cosmos/std_to_auth

Move stuff from types to auth
This commit is contained in:
Rigel 2018-05-26 04:43:27 -04:00 committed by GitHub
commit ae82931b7c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
45 changed files with 507 additions and 383 deletions

View File

@ -2,6 +2,18 @@
## 0.18.1
BREAKING CHANGES
* [x/auth] move stuff specific to auth anteHandler to the auth module rather than the types folder. This includes:
* StdTx (and its related stuff i.e. StdSignDoc, etc)
* StdFee
* StdSignature
* Account interface
* Related to this organization, I also:
* [x/auth] got rid of AccountMapper interface (in favor of the struct already in auth module)
* [x/auth] removed the FeeHandler function from the AnteHandler, Replaced with FeeKeeper
* [x/auth] Removed GetSignatures() from Tx interface (as different Tx styles might use something different than StdSignature)
BUG FIXES
* auto-sequencing transactions correctly

47
Gopkg.lock generated
View File

@ -13,51 +13,6 @@
packages = ["btcec"]
revision = "1432d294a5b055c297457c25434efbf13384cc46"
[[projects]]
name = "github.com/cosmos/cosmos-sdk"
packages = [
"baseapp",
"client",
"client/context",
"client/keys",
"client/lcd",
"client/rpc",
"client/tx",
"cmd/gaia/app",
"examples/basecoin/app",
"examples/basecoin/types",
"examples/democoin/app",
"examples/democoin/types",
"examples/democoin/x/cool",
"examples/democoin/x/cool/client/cli",
"examples/democoin/x/pow",
"examples/democoin/x/pow/client/cli",
"examples/democoin/x/simplestake",
"examples/democoin/x/simplestake/client/cli",
"examples/democoin/x/sketchy",
"mock",
"server",
"store",
"tests",
"types",
"version",
"wire",
"x/auth",
"x/auth/client/cli",
"x/auth/client/rest",
"x/bank",
"x/bank/client",
"x/bank/client/cli",
"x/bank/client/rest",
"x/ibc",
"x/ibc/client/cli",
"x/ibc/client/rest",
"x/stake",
"x/stake/client/cli"
]
revision = "187be1a5df81de1fd71da9053102d3a4868ec979"
version = "v0.17.2"
[[projects]]
name = "github.com/davecgh/go-spew"
packages = ["spew"]
@ -502,6 +457,6 @@
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "9b6ee069da61cf1815c332c5624e8af99b51ea72e2e9b91d780db92299598dcc"
inputs-digest = "7540d2ecdb5d7d5084ab4e6132e929bbd501bd6add3006d8f08a6b2c127e0c7d"
solver-name = "gps-cdcl"
solver-version = 1

View File

@ -15,6 +15,7 @@ import (
"github.com/cosmos/cosmos-sdk/store"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/wire"
"github.com/cosmos/cosmos-sdk/x/auth"
)
// Key to store the header in the DB itself.
@ -125,7 +126,7 @@ func (app *BaseApp) SetTxDecoder(txDecoder sdk.TxDecoder) {
// default custom logic for transaction decoding
func defaultTxDecoder(cdc *wire.Codec) sdk.TxDecoder {
return func(txBytes []byte) (sdk.Tx, sdk.Error) {
var tx = sdk.StdTx{}
var tx = auth.StdTx{}
if len(txBytes) == 0 {
return nil, sdk.ErrTxDecode("txBytes are empty")

View File

@ -11,13 +11,14 @@ import (
"github.com/stretchr/testify/require"
abci "github.com/tendermint/abci/types"
"github.com/tendermint/go-crypto"
crypto "github.com/tendermint/go-crypto"
cmn "github.com/tendermint/tmlibs/common"
dbm "github.com/tendermint/tmlibs/db"
"github.com/tendermint/tmlibs/log"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/wire"
"github.com/cosmos/cosmos-sdk/x/auth"
)
func defaultLogger() log.Logger {
@ -451,7 +452,7 @@ func (tx testUpdatePowerTx) GetMsg() sdk.Msg { return tx }
func (tx testUpdatePowerTx) GetSignBytes() []byte { return nil }
func (tx testUpdatePowerTx) ValidateBasic() sdk.Error { return nil }
func (tx testUpdatePowerTx) GetSigners() []sdk.Address { return nil }
func (tx testUpdatePowerTx) GetSignatures() []sdk.StdSignature { return nil }
func (tx testUpdatePowerTx) GetSignatures() []auth.StdSignature { return nil }
func TestValidatorChange(t *testing.T) {

View File

@ -6,6 +6,7 @@ import (
"github.com/pkg/errors"
"github.com/cosmos/cosmos-sdk/wire"
"github.com/cosmos/cosmos-sdk/x/auth"
rpcclient "github.com/tendermint/tendermint/rpc/client"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
cmn "github.com/tendermint/tmlibs/common"
@ -109,11 +110,11 @@ func (ctx CoreContext) SignAndBuild(name, passphrase string, msg sdk.Msg, cdc *w
return nil, errors.Errorf("Chain ID required but not specified")
}
sequence := ctx.Sequence
signMsg := sdk.StdSignMsg{
signMsg := auth.StdSignMsg{
ChainID: chainID,
Sequences: []int64{sequence},
Msg: msg,
Fee: sdk.NewStdFee(10000, sdk.Coin{}), // TODO run simulate to estimate gas?
Fee: auth.NewStdFee(10000, sdk.Coin{}), // TODO run simulate to estimate gas?
}
keybase, err := keys.GetKeyBase()
@ -128,14 +129,14 @@ func (ctx CoreContext) SignAndBuild(name, passphrase string, msg sdk.Msg, cdc *w
if err != nil {
return nil, err
}
sigs := []sdk.StdSignature{{
sigs := []auth.StdSignature{{
PubKey: pubkey,
Signature: sig,
Sequence: sequence,
}}
// marshal bytes
tx := sdk.NewStdTx(signMsg.Msg, signMsg.Fee, sigs)
tx := auth.NewStdTx(signMsg.Msg, signMsg.Fee, sigs)
return cdc.MarshalBinary(tx)
}

View File

@ -3,7 +3,7 @@ package context
import (
rpcclient "github.com/tendermint/tendermint/rpc/client"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
)
// typical context created in sdk modules for transactions/queries
@ -15,7 +15,7 @@ type CoreContext struct {
FromAddressName string
Sequence int64
Client rpcclient.Client
Decoder sdk.AccountDecoder
Decoder auth.AccountDecoder
AccountStore string
}
@ -63,7 +63,7 @@ func (c CoreContext) WithClient(client rpcclient.Client) CoreContext {
}
// WithDecoder - return a copy of the context with an updated Decoder
func (c CoreContext) WithDecoder(decoder sdk.AccountDecoder) CoreContext {
func (c CoreContext) WithDecoder(decoder auth.AccountDecoder) CoreContext {
c.Decoder = decoder
return c
}

View File

@ -35,6 +35,7 @@ import (
btypes "github.com/cosmos/cosmos-sdk/examples/basecoin/types"
tests "github.com/cosmos/cosmos-sdk/tests"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
)
var (
@ -436,11 +437,11 @@ func request(t *testing.T, port, method, path string, payload []byte) (*http.Res
return res, string(output)
}
func getAccount(t *testing.T, sendAddr string) sdk.Account {
func getAccount(t *testing.T, sendAddr string) auth.Account {
// get the account to get the sequence
res, body := request(t, port, "GET", "/accounts/"+sendAddr, nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
var acc sdk.Account
var acc auth.Account
err := cdc.UnmarshalJSON([]byte(body), &acc)
require.Nil(t, err)
return acc

View File

@ -17,6 +17,7 @@ import (
"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/auth"
)
// Get the default command for a tx query
@ -95,7 +96,7 @@ type txInfo struct {
}
func parseTx(cdc *wire.Codec, txBytes []byte) (sdk.Tx, error) {
var tx sdk.StdTx
var tx auth.StdTx
err := cdc.UnmarshalBinary(txBytes, &tx)
if err != nil {
return nil, err

View File

@ -14,7 +14,6 @@ import (
"github.com/cosmos/cosmos-sdk/wire"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/bank"
feed "github.com/cosmos/cosmos-sdk/x/fee_distribution"
"github.com/cosmos/cosmos-sdk/x/ibc"
"github.com/cosmos/cosmos-sdk/x/stake"
)
@ -41,7 +40,8 @@ type GaiaApp struct {
keyStake *sdk.KVStoreKey
// Manage getting and setting accounts
accountMapper sdk.AccountMapper
accountMapper auth.AccountMapper
feeCollectionKeeper auth.FeeCollectionKeeper
coinKeeper bank.Keeper
ibcMapper ibc.Mapper
stakeKeeper stake.Keeper
@ -82,7 +82,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB) *GaiaApp {
app.SetInitChainer(app.initChainer)
app.SetEndBlocker(stake.NewEndBlocker(app.stakeKeeper))
app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake)
app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, feed.BurnFeeHandler))
app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper))
err := app.LoadLatestVersion(app.keyMain)
if err != nil {
cmn.Exit(err.Error())
@ -132,7 +132,7 @@ func (app *GaiaApp) ExportAppStateJSON() (appState json.RawMessage, err error) {
// iterate to get the accounts
accounts := []GenesisAccount{}
appendAccount := func(acc sdk.Account) (stop bool) {
appendAccount := func(acc auth.Account) (stop bool) {
account := NewGenesisAccountI(acc)
accounts = append(accounts, account)
return false

View File

@ -38,7 +38,7 @@ var (
coins = sdk.Coins{{"foocoin", 10}}
halfCoins = sdk.Coins{{"foocoin", 5}}
manyCoins = sdk.Coins{{"foocoin", 1}, {"barcoin", 1}}
fee = sdk.StdFee{
fee = auth.StdFee{
sdk.Coins{{"foocoin", 0}},
100000,
}
@ -463,17 +463,17 @@ func CheckBalance(t *testing.T, gapp *GaiaApp, addr sdk.Address, balExpected str
assert.Equal(t, balExpected, fmt.Sprintf("%v", res2.GetCoins()))
}
func genTx(msg sdk.Msg, seq []int64, priv ...crypto.PrivKeyEd25519) sdk.StdTx {
sigs := make([]sdk.StdSignature, len(priv))
func genTx(msg sdk.Msg, seq []int64, priv ...crypto.PrivKeyEd25519) auth.StdTx {
sigs := make([]auth.StdSignature, len(priv))
for i, p := range priv {
sigs[i] = sdk.StdSignature{
sigs[i] = auth.StdSignature{
PubKey: p.PubKey(),
Signature: p.Sign(sdk.StdSignBytes(chainID, seq, fee, msg)),
Signature: p.Sign(auth.StdSignBytes(chainID, seq, fee, msg)),
Sequence: seq[i],
}
}
return sdk.NewStdTx(msg, fee, sigs)
return auth.NewStdTx(msg, fee, sigs)
}

View File

@ -35,7 +35,7 @@ func NewGenesisAccount(acc *auth.BaseAccount) GenesisAccount {
}
}
func NewGenesisAccountI(acc sdk.Account) GenesisAccount {
func NewGenesisAccountI(acc auth.Account) GenesisAccount {
return GenesisAccount{
Address: acc.GetAddress(),
Coins: acc.GetCoins(),

View File

@ -35,7 +35,8 @@ type BasecoinApp struct {
keyStake *sdk.KVStoreKey
// Manage getting and setting accounts
accountMapper sdk.AccountMapper
accountMapper auth.AccountMapper
feeCollectionKeeper auth.FeeCollectionKeeper
coinKeeper bank.Keeper
ibcMapper ibc.Mapper
stakeKeeper stake.Keeper
@ -70,7 +71,7 @@ func NewBasecoinApp(logger log.Logger, db dbm.DB) *BasecoinApp {
// register message routes
app.Router().
AddRoute("auth", auth.NewHandler(app.accountMapper.(auth.AccountMapper))).
AddRoute("auth", auth.NewHandler(app.accountMapper)).
AddRoute("bank", bank.NewHandler(app.coinKeeper)).
AddRoute("ibc", ibc.NewHandler(app.ibcMapper, app.coinKeeper)).
AddRoute("stake", stake.NewHandler(app.stakeKeeper))
@ -78,7 +79,7 @@ func NewBasecoinApp(logger log.Logger, db dbm.DB) *BasecoinApp {
// Initialize BaseApp.
app.SetInitChainer(app.initChainer)
app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake)
app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, auth.BurnFeeHandler))
app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper))
err := app.LoadLatestVersion(app.keyMain)
if err != nil {
cmn.Exit(err.Error())
@ -96,7 +97,7 @@ func MakeCodec() *wire.Codec {
ibc.RegisterWire(cdc)
// register custom AppAccount
cdc.RegisterInterface((*sdk.Account)(nil), nil)
cdc.RegisterInterface((*auth.Account)(nil), nil)
cdc.RegisterConcrete(&types.AppAccount{}, "basecoin/Account", nil)
return cdc
}
@ -129,7 +130,7 @@ func (app *BasecoinApp) ExportAppStateJSON() (appState json.RawMessage, err erro
// iterate to get the accounts
accounts := []*types.GenesisAccount{}
appendAccount := func(acc sdk.Account) (stop bool) {
appendAccount := func(acc auth.Account) (stop bool) {
account := &types.GenesisAccount{
Address: acc.GetAddress(),
Coins: acc.GetCoins(),

View File

@ -37,7 +37,7 @@ var (
coins = sdk.Coins{{"foocoin", 10}}
halfCoins = sdk.Coins{{"foocoin", 5}}
manyCoins = sdk.Coins{{"foocoin", 1}, {"barcoin", 1}}
fee = sdk.StdFee{
fee = auth.StdFee{
sdk.Coins{{"foocoin", 0}},
100000,
}
@ -471,17 +471,17 @@ func TestIBCMsgs(t *testing.T) {
SignCheckDeliver(t, bapp, receiveMsg, []int64{3}, false, priv1)
}
func genTx(msg sdk.Msg, seq []int64, priv ...crypto.PrivKeyEd25519) sdk.StdTx {
sigs := make([]sdk.StdSignature, len(priv))
func genTx(msg sdk.Msg, seq []int64, priv ...crypto.PrivKeyEd25519) auth.StdTx {
sigs := make([]auth.StdSignature, len(priv))
for i, p := range priv {
sigs[i] = sdk.StdSignature{
sigs[i] = auth.StdSignature{
PubKey: p.PubKey(),
Signature: p.Sign(sdk.StdSignBytes(chainID, seq, fee, msg)),
Signature: p.Sign(auth.StdSignBytes(chainID, seq, fee, msg)),
Sequence: seq[i],
}
}
return sdk.NewStdTx(msg, fee, sigs)
return auth.NewStdTx(msg, fee, sigs)
}

View File

@ -6,7 +6,7 @@ import (
"github.com/cosmos/cosmos-sdk/x/auth"
)
var _ sdk.Account = (*AppAccount)(nil)
var _ auth.Account = (*AppAccount)(nil)
// Custom extensions for this application. This is just an example of
// extending auth.BaseAccount with custom fields.
@ -23,8 +23,8 @@ func (acc AppAccount) GetName() string { return acc.Name }
func (acc *AppAccount) SetName(name string) { acc.Name = name }
// Get the AccountDecoder function for the custom AppAccount
func GetAccountDecoder(cdc *wire.Codec) sdk.AccountDecoder {
return func(accBytes []byte) (res sdk.Account, err error) {
func GetAccountDecoder(cdc *wire.Codec) auth.AccountDecoder {
return func(accBytes []byte) (res auth.Account, err error) {
if len(accBytes) == 0 {
return nil, sdk.ErrTxDecode("accBytes are empty")
}

View File

@ -39,6 +39,7 @@ type DemocoinApp struct {
capKeyStakingStore *sdk.KVStoreKey
// keepers
feeCollectionKeeper auth.FeeCollectionKeeper
coinKeeper bank.Keeper
coolKeeper cool.Keeper
powKeeper pow.Keeper
@ -46,7 +47,7 @@ type DemocoinApp struct {
stakeKeeper simplestake.Keeper
// Manage getting and setting accounts
accountMapper sdk.AccountMapper
accountMapper auth.AccountMapper
}
func NewDemocoinApp(logger log.Logger, db dbm.DB) *DemocoinApp {
@ -89,7 +90,7 @@ func NewDemocoinApp(logger log.Logger, db dbm.DB) *DemocoinApp {
// Initialize BaseApp.
app.SetInitChainer(app.initChainerFn(app.coolKeeper, app.powKeeper))
app.MountStoresIAVL(app.capKeyMainStore, app.capKeyAccountStore, app.capKeyPowStore, app.capKeyIBCStore, app.capKeyStakingStore)
app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, auth.BurnFeeHandler))
app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper))
err := app.LoadLatestVersion(app.capKeyMainStore)
if err != nil {
cmn.Exit(err.Error())
@ -109,7 +110,7 @@ func MakeCodec() *wire.Codec {
simplestake.RegisterWire(cdc)
// Register AppAccount
cdc.RegisterInterface((*sdk.Account)(nil), nil)
cdc.RegisterInterface((*auth.Account)(nil), nil)
cdc.RegisterConcrete(&types.AppAccount{}, "democoin/Account", nil)
return cdc
}
@ -158,7 +159,7 @@ func (app *DemocoinApp) ExportAppStateJSON() (appState json.RawMessage, err erro
// iterate to get the accounts
accounts := []*types.GenesisAccount{}
appendAccount := func(acc sdk.Account) (stop bool) {
appendAccount := func(acc auth.Account) (stop bool) {
account := &types.GenesisAccount{
Address: acc.GetAddress(),
Coins: acc.GetCoins(),

View File

@ -31,7 +31,7 @@ var (
addr1 = priv1.PubKey().Address()
addr2 = crypto.GenPrivKeyEd25519().PubKey().Address()
coins = sdk.Coins{{"foocoin", 10}}
fee = sdk.StdFee{
fee = auth.StdFee{
sdk.Coins{{"foocoin", 0}},
1000000,
}
@ -93,8 +93,8 @@ func TestMsgs(t *testing.T) {
sequences := []int64{0}
for i, m := range msgs {
sig := priv1.Sign(sdk.StdSignBytes(chainID, sequences, fee, m.msg))
tx := sdk.NewStdTx(m.msg, fee, []sdk.StdSignature{{
sig := priv1.Sign(auth.StdSignBytes(chainID, sequences, fee, m.msg))
tx := auth.NewStdTx(m.msg, fee, []auth.StdSignature{{
PubKey: priv1.PubKey(),
Signature: sig,
}})
@ -194,8 +194,8 @@ func TestMsgSendWithAccounts(t *testing.T) {
// Sign the tx
sequences := []int64{0}
sig := priv1.Sign(sdk.StdSignBytes(chainID, sequences, fee, sendMsg))
tx := sdk.NewStdTx(sendMsg, fee, []sdk.StdSignature{{
sig := priv1.Sign(auth.StdSignBytes(chainID, sequences, fee, sendMsg))
tx := auth.NewStdTx(sendMsg, fee, []auth.StdSignature{{
PubKey: priv1.PubKey(),
Signature: sig,
}})
@ -227,7 +227,7 @@ func TestMsgSendWithAccounts(t *testing.T) {
// resigning the tx with the bumped sequence should work
sequences = []int64{1}
sig = priv1.Sign(sdk.StdSignBytes(chainID, sequences, fee, tx.Msg))
sig = priv1.Sign(auth.StdSignBytes(chainID, sequences, fee, tx.Msg))
tx.Signatures[0].Signature = sig
res = bapp.Deliver(tx)
assert.Equal(t, sdk.ABCICodeOK, res.Code, res.Log)
@ -394,9 +394,9 @@ func TestHandler(t *testing.T) {
func SignCheckDeliver(t *testing.T, bapp *DemocoinApp, msg sdk.Msg, seq int64, expPass bool) {
// Sign the tx
tx := sdk.NewStdTx(msg, fee, []sdk.StdSignature{{
tx := auth.NewStdTx(msg, fee, []auth.StdSignature{{
PubKey: priv1.PubKey(),
Signature: priv1.Sign(sdk.StdSignBytes(chainID, []int64{seq}, fee, msg)),
Signature: priv1.Sign(auth.StdSignBytes(chainID, []int64{seq}, fee, msg)),
Sequence: seq,
}})

View File

@ -9,7 +9,7 @@ import (
"github.com/cosmos/cosmos-sdk/examples/democoin/x/pow"
)
var _ sdk.Account = (*AppAccount)(nil)
var _ auth.Account = (*AppAccount)(nil)
// Custom extensions for this application. This is just an example of
// extending auth.BaseAccount with custom fields.
@ -26,8 +26,8 @@ func (acc AppAccount) GetName() string { return acc.Name }
func (acc *AppAccount) SetName(name string) { acc.Name = name }
// Get the AccountDecoder function for the custom AppAccount
func GetAccountDecoder(cdc *wire.Codec) sdk.AccountDecoder {
return func(accBytes []byte) (res sdk.Account, err error) {
func GetAccountDecoder(cdc *wire.Codec) auth.AccountDecoder {
return func(accBytes []byte) (res auth.Account, err error) {
if len(accBytes) == 0 {
return nil, sdk.ErrTxDecode("accBytes are empty")
}

View File

@ -31,10 +31,13 @@ func setupMultiStore() (sdk.MultiStore, *sdk.KVStoreKey, *sdk.KVStoreKey) {
}
func TestKeeperGetSet(t *testing.T) {
ms, _, capKey := setupMultiStore()
ms, authKey, capKey := setupMultiStore()
cdc := wire.NewCodec()
auth.RegisterBaseAccount(cdc)
ctx := sdk.NewContext(ms, abci.Header{}, false, nil, log.NewNopLogger())
stakeKeeper := NewKeeper(capKey, bank.NewKeeper(nil), DefaultCodespace)
accountMapper := auth.NewAccountMapper(cdc, authKey, &auth.BaseAccount{})
stakeKeeper := NewKeeper(capKey, bank.NewKeeper(accountMapper), DefaultCodespace)
addr := sdk.Address([]byte("some-address"))
bi := stakeKeeper.getBondInfo(ctx, addr)

View File

@ -4,6 +4,7 @@ import (
"bytes"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
)
// An sdk.Tx which is its own sdk.Msg.
@ -34,7 +35,7 @@ func (tx kvstoreTx) GetSigners() []sdk.Address {
return nil
}
func (tx kvstoreTx) GetSignatures() []sdk.StdSignature {
func (tx kvstoreTx) GetSignatures() []auth.StdSignature {
return nil
}

View File

@ -6,6 +6,7 @@ import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
)
// An sdk.Tx which is its own sdk.Msg.
@ -47,7 +48,7 @@ func (tx kvstoreTx) GetSigners() []sdk.Address {
return nil
}
func (tx kvstoreTx) GetSignatures() []sdk.StdSignature {
func (tx kvstoreTx) GetSignatures() []auth.StdSignature {
return nil
}

View File

@ -4,7 +4,6 @@ import (
"encoding/hex"
"errors"
crypto "github.com/tendermint/go-crypto"
cmn "github.com/tendermint/tmlibs/common"
)
@ -22,31 +21,3 @@ func GetAddress(address string) (addr Address, err error) {
}
return Address(bz), nil
}
// Account is a standard account using a sequence number for replay protection
// and a pubkey for authentication.
type Account interface {
GetAddress() Address
SetAddress(Address) error // errors if already set.
GetPubKey() crypto.PubKey // can return nil.
SetPubKey(crypto.PubKey) error
GetSequence() int64
SetSequence(int64) error
GetCoins() Coins
SetCoins(Coins) error
}
// AccountMapper stores and retrieves accounts from stores
// retrieved from the context.
type AccountMapper interface {
NewAccountWithAddress(ctx Context, addr Address) Account
GetAccount(ctx Context, addr Address) Account
SetAccount(ctx Context, acc Account)
IterateAccounts(ctx Context, process func(Account) (stop bool))
}
// AccountDecoder unmarshals account bytes
type AccountDecoder func(accountBytes []byte) (Account, error)

View File

@ -3,8 +3,5 @@ package types
// core function variable which application runs for transactions
type Handler func(ctx Context, msg Msg) Result
// core function variable which application runs to handle fees
type FeeHandler func(ctx Context, tx Tx, fee Coins)
// If newCtx.IsZero(), ctx is used instead.
type AnteHandler func(ctx Context, tx Tx) (newCtx Context, result Result, abort bool)

View File

@ -1,10 +0,0 @@
package types
import crypto "github.com/tendermint/go-crypto"
// Standard Signature
type StdSignature struct {
crypto.PubKey `json:"pub_key"` // optional
crypto.Signature `json:"signature"`
Sequence int64 `json:"sequence"`
}

View File

@ -31,123 +31,6 @@ type Tx interface {
// Gets the Msg.
GetMsg() Msg
// Signatures returns the signature of signers who signed the Msg.
// CONTRACT: Length returned is same as length of
// pubkeys returned from MsgKeySigners, and the order
// matches.
// CONTRACT: If the signature is missing (ie the Msg is
// invalid), then the corresponding signature is
// .Empty().
GetSignatures() []StdSignature
}
var _ Tx = (*StdTx)(nil)
// StdTx is a standard way to wrap a Msg with Fee and Signatures.
// NOTE: the first signature is the FeePayer (Signatures must not be nil).
type StdTx struct {
Msg `json:"msg"`
Fee StdFee `json:"fee"`
Signatures []StdSignature `json:"signatures"`
}
func NewStdTx(msg Msg, fee StdFee, sigs []StdSignature) StdTx {
return StdTx{
Msg: msg,
Fee: fee,
Signatures: sigs,
}
}
//nolint
func (tx StdTx) GetMsg() Msg { return tx.Msg }
func (tx StdTx) GetSignatures() []StdSignature { return tx.Signatures }
// FeePayer returns the address responsible for paying the fees
// for the transactions. It's the first address returned by msg.GetSigners().
// If GetSigners() is empty, this panics.
func FeePayer(tx Tx) Address {
return tx.GetMsg().GetSigners()[0]
}
//__________________________________________________________
// StdFee includes the amount of coins paid in fees and the maximum
// gas to be used by the transaction. The ratio yields an effective "gasprice",
// which must be above some miminum to be accepted into the mempool.
type StdFee struct {
Amount Coins `json:"amount"`
Gas int64 `json:"gas"`
}
func NewStdFee(gas int64, amount ...Coin) StdFee {
return StdFee{
Amount: amount,
Gas: gas,
}
}
// fee bytes for signing later
func (fee StdFee) Bytes() []byte {
// normalize. XXX
// this is a sign of something ugly
// (in the lcd_test, client side its null,
// server side its [])
if len(fee.Amount) == 0 {
fee.Amount = Coins{}
}
bz, err := json.Marshal(fee) // TODO
if err != nil {
panic(err)
}
return bz
}
//__________________________________________________________
// StdSignDoc is replay-prevention structure.
// It includes the result of msg.GetSignBytes(),
// as well as the ChainID (prevent cross chain replay)
// and the Sequence numbers for each signature (prevent
// inchain replay and enforce tx ordering per account).
type StdSignDoc struct {
ChainID string `json:"chain_id"`
Sequences []int64 `json:"sequences"`
FeeBytes []byte `json:"fee_bytes"`
MsgBytes []byte `json:"msg_bytes"`
AltBytes []byte `json:"alt_bytes"`
}
// StdSignBytes returns the bytes to sign for a transaction.
// TODO: change the API to just take a chainID and StdTx ?
func StdSignBytes(chainID string, sequences []int64, fee StdFee, msg Msg) []byte {
bz, err := json.Marshal(StdSignDoc{
ChainID: chainID,
Sequences: sequences,
FeeBytes: fee.Bytes(),
MsgBytes: msg.GetSignBytes(),
})
if err != nil {
panic(err)
}
return bz
}
// StdSignMsg is a convenience structure for passing along
// a Msg with the other requirements for a StdSignDoc before
// it is signed. For use in the CLI.
type StdSignMsg struct {
ChainID string
Sequences []int64
Fee StdFee
Msg Msg
// XXX: Alt
}
// get message bytes
func (msg StdSignMsg) Bytes() []byte {
return StdSignBytes(msg.ChainID, msg.Sequences, msg.Fee, msg.Msg)
}
//__________________________________________________________

View File

@ -3,16 +3,34 @@ package auth
import (
"errors"
"github.com/tendermint/go-crypto"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/wire"
crypto "github.com/tendermint/go-crypto"
)
// Account is a standard account using a sequence number for replay protection
// and a pubkey for authentication.
type Account interface {
GetAddress() sdk.Address
SetAddress(sdk.Address) error // errors if already set.
GetPubKey() crypto.PubKey // can return nil.
SetPubKey(crypto.PubKey) error
GetSequence() int64
SetSequence(int64) error
GetCoins() sdk.Coins
SetCoins(sdk.Coins) error
}
// AccountDecoder unmarshals account bytes
type AccountDecoder func(accountBytes []byte) (Account, error)
//-----------------------------------------------------------
// BaseAccount
var _ sdk.Account = (*BaseAccount)(nil)
var _ Account = (*BaseAccount)(nil)
// BaseAccount - base account structure.
// Extend this by embedding this in your AppAccount.
@ -82,7 +100,7 @@ func (acc *BaseAccount) SetSequence(seq int64) error {
// Most users shouldn't use this, but this comes handy for tests.
func RegisterBaseAccount(cdc *wire.Codec) {
cdc.RegisterInterface((*sdk.Account)(nil), nil)
cdc.RegisterInterface((*Account)(nil), nil)
cdc.RegisterConcrete(&BaseAccount{}, "cosmos-sdk/BaseAccount", nil)
wire.RegisterCrypto(cdc)
}

View File

@ -9,19 +9,27 @@ import (
)
const (
deductFeesCost sdk.Gas = 10
verifyCost = 100
)
// NewAnteHandler returns an AnteHandler that checks
// and increments sequence numbers, checks signatures,
// and deducts fees from the first signer.
func NewAnteHandler(am sdk.AccountMapper, feeHandler sdk.FeeHandler) sdk.AnteHandler {
func NewAnteHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.AnteHandler {
return func(
ctx sdk.Context, tx sdk.Tx,
) (_ sdk.Context, _ sdk.Result, abort bool) {
// This AnteHandler requires Txs to be StdTxs
stdTx, ok := tx.(StdTx)
if !ok {
return ctx, sdk.ErrInternal("tx must be StdTx").Result(), true
}
// Assert that there are signatures.
var sigs = tx.GetSignatures()
var sigs = stdTx.GetSignatures()
if len(sigs) == 0 {
return ctx,
sdk.ErrUnauthorized("no signers").Result(),
@ -30,12 +38,6 @@ func NewAnteHandler(am sdk.AccountMapper, feeHandler sdk.FeeHandler) sdk.AnteHan
msg := tx.GetMsg()
// TODO: will this always be a stdtx? should that be used in the function signature?
stdTx, ok := tx.(sdk.StdTx)
if !ok {
return ctx, sdk.ErrInternal("tx must be sdk.StdTx").Result(), true
}
// Assert that number of signatures is correct.
var signerAddrs = msg.GetSigners()
if len(sigs) != len(signerAddrs) {
@ -56,10 +58,10 @@ func NewAnteHandler(am sdk.AccountMapper, feeHandler sdk.FeeHandler) sdk.AnteHan
if chainID == "" {
chainID = viper.GetString("chain-id")
}
signBytes := sdk.StdSignBytes(ctx.ChainID(), sequences, fee, msg)
signBytes := StdSignBytes(ctx.ChainID(), sequences, fee, msg)
// Check sig and nonce and collect signer accounts.
var signerAccs = make([]sdk.Account, len(signerAddrs))
var signerAccs = make([]Account, len(signerAddrs))
for i := 0; i < len(sigs); i++ {
signerAddr, sig := signerAddrs[i], sigs[i]
@ -76,11 +78,12 @@ func NewAnteHandler(am sdk.AccountMapper, feeHandler sdk.FeeHandler) sdk.AnteHan
if i == 0 {
// TODO: min fee
if !fee.Amount.IsZero() {
ctx.GasMeter().ConsumeGas(deductFeesCost, "deductFees")
signerAcc, res = deductFees(signerAcc, fee)
feeHandler(ctx, tx, fee.Amount)
if !res.IsOK() {
return ctx, res, true
}
fck.addCollectedFees(ctx, fee.Amount)
}
}
@ -104,9 +107,9 @@ func NewAnteHandler(am sdk.AccountMapper, feeHandler sdk.FeeHandler) sdk.AnteHan
// verify the signature and increment the sequence.
// if the account doesn't have a pubkey, set it.
func processSig(
ctx sdk.Context, am sdk.AccountMapper,
addr sdk.Address, sig sdk.StdSignature, signBytes []byte) (
acc sdk.Account, res sdk.Result) {
ctx sdk.Context, am AccountMapper,
addr sdk.Address, sig StdSignature, signBytes []byte) (
acc Account, res sdk.Result) {
// Get the account.
acc = am.GetAccount(ctx, addr)
@ -152,7 +155,7 @@ func processSig(
// Deduct the fee from the account.
// We could use the CoinKeeper (in addition to the AccountMapper,
// because the CoinKeeper doesn't give us accounts), but it seems easier to do this.
func deductFees(acc sdk.Account, fee sdk.StdFee) (sdk.Account, sdk.Result) {
func deductFees(acc Account, fee StdFee) (Account, sdk.Result) {
coins := acc.GetCoins()
feeAmount := fee.Amount

View File

@ -17,8 +17,8 @@ func newTestMsg(addrs ...sdk.Address) *sdk.TestMsg {
return sdk.NewTestMsg(addrs...)
}
func newStdFee() sdk.StdFee {
return sdk.NewStdFee(100,
func newStdFee() StdFee {
return NewStdFee(100,
sdk.Coin{"atom", 150},
)
}
@ -52,28 +52,29 @@ func checkInvalidTx(t *testing.T, anteHandler sdk.AnteHandler, ctx sdk.Context,
assert.Equal(t, sdk.ToABCICode(sdk.CodespaceRoot, code), result.Code)
}
func newTestTx(ctx sdk.Context, msg sdk.Msg, privs []crypto.PrivKey, seqs []int64, fee sdk.StdFee) sdk.Tx {
signBytes := sdk.StdSignBytes(ctx.ChainID(), seqs, fee, msg)
func newTestTx(ctx sdk.Context, msg sdk.Msg, privs []crypto.PrivKey, seqs []int64, fee StdFee) sdk.Tx {
signBytes := StdSignBytes(ctx.ChainID(), seqs, fee, msg)
return newTestTxWithSignBytes(msg, privs, seqs, fee, signBytes)
}
func newTestTxWithSignBytes(msg sdk.Msg, privs []crypto.PrivKey, seqs []int64, fee sdk.StdFee, signBytes []byte) sdk.Tx {
sigs := make([]sdk.StdSignature, len(privs))
func newTestTxWithSignBytes(msg sdk.Msg, privs []crypto.PrivKey, seqs []int64, fee StdFee, signBytes []byte) sdk.Tx {
sigs := make([]StdSignature, len(privs))
for i, priv := range privs {
sigs[i] = sdk.StdSignature{PubKey: priv.PubKey(), Signature: priv.Sign(signBytes), Sequence: seqs[i]}
sigs[i] = StdSignature{PubKey: priv.PubKey(), Signature: priv.Sign(signBytes), Sequence: seqs[i]}
}
tx := sdk.NewStdTx(msg, fee, sigs)
tx := NewStdTx(msg, fee, sigs)
return tx
}
// Test various error cases in the AnteHandler control flow.
func TestAnteHandlerSigErrors(t *testing.T) {
// setup
ms, capKey := setupMultiStore()
ms, capKey, capKey2 := setupMultiStore()
cdc := wire.NewCodec()
RegisterBaseAccount(cdc)
mapper := NewAccountMapper(cdc, capKey, &BaseAccount{})
anteHandler := NewAnteHandler(mapper, BurnFeeHandler)
feeCollector := NewFeeCollectionKeeper(cdc, capKey2)
anteHandler := NewAnteHandler(mapper, feeCollector)
ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil, log.NewNopLogger())
// keys and addresses
@ -110,11 +111,12 @@ func TestAnteHandlerSigErrors(t *testing.T) {
// Test logic around sequence checking with one signer and many signers.
func TestAnteHandlerSequences(t *testing.T) {
// setup
ms, capKey := setupMultiStore()
ms, capKey, capKey2 := setupMultiStore()
cdc := wire.NewCodec()
RegisterBaseAccount(cdc)
mapper := NewAccountMapper(cdc, capKey, &BaseAccount{})
anteHandler := NewAnteHandler(mapper, BurnFeeHandler)
feeCollector := NewFeeCollectionKeeper(cdc, capKey2)
anteHandler := NewAnteHandler(mapper, feeCollector)
ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil, log.NewNopLogger())
// keys and addresses
@ -176,11 +178,12 @@ func TestAnteHandlerSequences(t *testing.T) {
// Test logic around fee deduction.
func TestAnteHandlerFees(t *testing.T) {
// setup
ms, capKey := setupMultiStore()
ms, capKey, capKey2 := setupMultiStore()
cdc := wire.NewCodec()
RegisterBaseAccount(cdc)
mapper := NewAccountMapper(cdc, capKey, &BaseAccount{})
anteHandler := NewAnteHandler(mapper, BurnFeeHandler)
feeCollector := NewFeeCollectionKeeper(cdc, capKey2)
anteHandler := NewAnteHandler(mapper, feeCollector)
ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil, log.NewNopLogger())
// keys and addresses
@ -194,7 +197,7 @@ func TestAnteHandlerFees(t *testing.T) {
var tx sdk.Tx
msg := newTestMsg(addr1)
privs, seqs := []crypto.PrivKey{priv1}, []int64{0}
fee := sdk.NewStdFee(100,
fee := NewStdFee(100,
sdk.Coin{"atom", 150},
)
@ -206,18 +209,23 @@ func TestAnteHandlerFees(t *testing.T) {
mapper.SetAccount(ctx, acc1)
checkInvalidTx(t, anteHandler, ctx, tx, sdk.CodeInsufficientFunds)
assert.True(t, feeCollector.GetCollectedFees(ctx).IsEqual(emptyCoins))
acc1.SetCoins(sdk.Coins{{"atom", 150}})
mapper.SetAccount(ctx, acc1)
checkValidTx(t, anteHandler, ctx, tx)
assert.True(t, feeCollector.GetCollectedFees(ctx).IsEqual(sdk.Coins{{"atom", 150}}))
}
func TestAnteHandlerBadSignBytes(t *testing.T) {
// setup
ms, capKey := setupMultiStore()
ms, capKey, capKey2 := setupMultiStore()
cdc := wire.NewCodec()
RegisterBaseAccount(cdc)
mapper := NewAccountMapper(cdc, capKey, &BaseAccount{})
anteHandler := NewAnteHandler(mapper, BurnFeeHandler)
feeCollector := NewFeeCollectionKeeper(cdc, capKey2)
anteHandler := NewAnteHandler(mapper, feeCollector)
ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil, log.NewNopLogger())
// keys and addresses
@ -252,7 +260,7 @@ func TestAnteHandlerBadSignBytes(t *testing.T) {
cases := []struct {
chainID string
seqs []int64
fee sdk.StdFee
fee StdFee
msg sdk.Msg
code sdk.CodeType
}{
@ -268,7 +276,7 @@ func TestAnteHandlerBadSignBytes(t *testing.T) {
for _, cs := range cases {
tx := newTestTxWithSignBytes(
msg, privs, seqs, fee,
sdk.StdSignBytes(cs.chainID, cs.seqs, cs.fee, cs.msg),
StdSignBytes(cs.chainID, cs.seqs, cs.fee, cs.msg),
)
checkInvalidTx(t, anteHandler, ctx, tx, cs.code)
}
@ -288,11 +296,12 @@ func TestAnteHandlerBadSignBytes(t *testing.T) {
func TestAnteHandlerSetPubKey(t *testing.T) {
// setup
ms, capKey := setupMultiStore()
ms, capKey, capKey2 := setupMultiStore()
cdc := wire.NewCodec()
RegisterBaseAccount(cdc)
mapper := NewAccountMapper(cdc, capKey, &BaseAccount{})
anteHandler := NewAnteHandler(mapper, BurnFeeHandler)
feeCollector := NewFeeCollectionKeeper(cdc, capKey2)
anteHandler := NewAnteHandler(mapper, feeCollector)
ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil, log.NewNopLogger())
// keys and addresses
@ -322,7 +331,7 @@ func TestAnteHandlerSetPubKey(t *testing.T) {
// test public key not found
msg = newTestMsg(addr2)
tx = newTestTx(ctx, msg, privs, seqs, fee)
sigs := tx.GetSignatures()
sigs := tx.(StdTx).GetSignatures()
sigs[0].PubKey = nil
checkInvalidTx(t, anteHandler, ctx, tx, sdk.CodeInvalidPubKey)

View File

@ -9,6 +9,7 @@ import (
"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/auth"
)
// GetAccountCmd for the auth.BaseAccount type
@ -17,8 +18,8 @@ func GetAccountCmdDefault(storeName string, cdc *wire.Codec) *cobra.Command {
}
// Get account decoder for auth.DefaultAccount
func GetAccountDecoder(cdc *wire.Codec) sdk.AccountDecoder {
return func(accBytes []byte) (acct sdk.Account, err error) {
func GetAccountDecoder(cdc *wire.Codec) auth.AccountDecoder {
return func(accBytes []byte) (acct auth.Account, err error) {
// acct := new(auth.BaseAccount)
err = cdc.UnmarshalBinaryBare(accBytes, &acct)
if err != nil {
@ -30,7 +31,7 @@ func GetAccountDecoder(cdc *wire.Codec) sdk.AccountDecoder {
// GetAccountCmd returns a query account that will display the
// state of the account at a given address
func GetAccountCmd(storeName string, cdc *wire.Codec, decoder sdk.AccountDecoder) *cobra.Command {
func GetAccountCmd(storeName string, cdc *wire.Codec, decoder auth.AccountDecoder) *cobra.Command {
return &cobra.Command{
Use: "account [address]",
Short: "Query account balance",

View File

@ -10,19 +10,20 @@ import (
"github.com/cosmos/cosmos-sdk/client/context"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/wire"
auth "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
"github.com/cosmos/cosmos-sdk/x/auth"
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
)
// register REST routes
func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, storeName string) {
r.HandleFunc(
"/accounts/{address}",
QueryAccountRequestHandlerFn(storeName, cdc, auth.GetAccountDecoder(cdc), ctx),
QueryAccountRequestHandlerFn(storeName, cdc, authcmd.GetAccountDecoder(cdc), ctx),
).Methods("GET")
}
// query accountREST Handler
func QueryAccountRequestHandlerFn(storeName string, cdc *wire.Codec, decoder sdk.AccountDecoder, ctx context.CoreContext) http.HandlerFunc {
func QueryAccountRequestHandlerFn(storeName string, cdc *wire.Codec, decoder auth.AccountDecoder, ctx context.CoreContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
addr := vars["address"]

View File

@ -34,15 +34,15 @@ const (
)
// add the signers to the context
func WithSigners(ctx types.Context, accounts []types.Account) types.Context {
func WithSigners(ctx types.Context, accounts []Account) types.Context {
return ctx.WithValue(contextKeySigners, accounts)
}
// get the signers from the context
func GetSigners(ctx types.Context) []types.Account {
func GetSigners(ctx types.Context) []Account {
v := ctx.Value(contextKeySigners)
if v == nil {
return []types.Account{}
return []Account{}
}
return v.([]types.Account)
return v.([]Account)
}

View File

@ -12,7 +12,7 @@ import (
)
func TestContextWithSigners(t *testing.T) {
ms, _ := setupMultiStore()
ms, _, _ := setupMultiStore()
ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, nil, log.NewNopLogger())
_, _, addr1 := keyPubAddr()
@ -26,7 +26,7 @@ func TestContextWithSigners(t *testing.T) {
signers := GetSigners(ctx)
assert.Equal(t, 0, len(signers))
ctx2 := WithSigners(ctx, []sdk.Account{&acc1, &acc2})
ctx2 := WithSigners(ctx, []Account{&acc1, &acc2})
// original context is unchanged
signers = GetSigners(ctx)

62
x/auth/feekeeper.go Normal file
View File

@ -0,0 +1,62 @@
package auth
import (
sdk "github.com/cosmos/cosmos-sdk/types"
wire "github.com/cosmos/cosmos-sdk/wire"
)
var (
collectedFeesKey = []byte("collectedFees")
)
// This FeeCollectionKeeper handles collection of fees in the anteHandler
// and setting of MinFees for different fee tokens
type FeeCollectionKeeper struct {
// The (unexposed) key used to access the fee store from the Context.
key sdk.StoreKey
// The wire codec for binary encoding/decoding of accounts.
cdc *wire.Codec
}
// NewFeeKeeper returns a new FeeKeeper
func NewFeeCollectionKeeper(cdc *wire.Codec, key sdk.StoreKey) FeeCollectionKeeper {
return FeeCollectionKeeper{
key: key,
cdc: cdc,
}
}
// Adds to Collected Fee Pool
func (fck FeeCollectionKeeper) GetCollectedFees(ctx sdk.Context) sdk.Coins {
store := ctx.KVStore(fck.key)
bz := store.Get(collectedFeesKey)
if bz == nil {
return sdk.Coins{}
}
feePool := &(sdk.Coins{})
fck.cdc.MustUnmarshalBinary(bz, feePool)
return *feePool
}
// Sets to Collected Fee Pool
func (fck FeeCollectionKeeper) setCollectedFees(ctx sdk.Context, coins sdk.Coins) {
bz := fck.cdc.MustMarshalBinary(coins)
store := ctx.KVStore(fck.key)
store.Set(collectedFeesKey, bz)
}
// Adds to Collected Fee Pool
func (fck FeeCollectionKeeper) addCollectedFees(ctx sdk.Context, coins sdk.Coins) sdk.Coins {
newCoins := fck.GetCollectedFees(ctx).Plus(coins)
fck.setCollectedFees(ctx, newCoins)
return newCoins
}
// Clears the collected Fee Pool
func (fck FeeCollectionKeeper) ClearCollectedFees(ctx sdk.Context) {
fck.setCollectedFees(ctx, sdk.Coins{})
}

75
x/auth/feekeeper_test.go Normal file
View File

@ -0,0 +1,75 @@
package auth
import (
"testing"
"github.com/stretchr/testify/assert"
abci "github.com/tendermint/abci/types"
"github.com/tendermint/tmlibs/log"
sdk "github.com/cosmos/cosmos-sdk/types"
wire "github.com/cosmos/cosmos-sdk/wire"
)
var (
emptyCoins = sdk.Coins{}
oneCoin = sdk.Coins{{"foocoin", 1}}
twoCoins = sdk.Coins{{"foocoin", 2}}
)
func TestFeeCollectionKeeperGetSet(t *testing.T) {
ms, _, capKey2 := setupMultiStore()
cdc := wire.NewCodec()
// make context and keeper
ctx := sdk.NewContext(ms, abci.Header{}, false, nil, log.NewNopLogger())
fck := NewFeeCollectionKeeper(cdc, capKey2)
// no coins initially
currFees := fck.GetCollectedFees(ctx)
assert.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))
}
func TestFeeCollectionKeeperAdd(t *testing.T) {
ms, _, capKey2 := setupMultiStore()
cdc := wire.NewCodec()
// make context and keeper
ctx := sdk.NewContext(ms, abci.Header{}, false, nil, log.NewNopLogger())
fck := NewFeeCollectionKeeper(cdc, capKey2)
// no coins initially
assert.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))
// add oneCoin again and check that pool is now twoCoins
fck.addCollectedFees(ctx, oneCoin)
assert.True(t, fck.GetCollectedFees(ctx).IsEqual(twoCoins))
}
func TestFeeCollectionKeeperClear(t *testing.T) {
ms, _, capKey2 := setupMultiStore()
cdc := wire.NewCodec()
// make context and keeper
ctx := sdk.NewContext(ms, abci.Header{}, false, nil, log.NewNopLogger())
fck := NewFeeCollectionKeeper(cdc, capKey2)
// set coins initially
fck.setCollectedFees(ctx, twoCoins)
assert.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))
}

View File

@ -6,14 +6,14 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
// NewHandler returns a handler for "auth" type messages.
// NewHandler returns a handler for "baseaccount" type messages.
func NewHandler(am AccountMapper) sdk.Handler {
return func(ctx sdk.Context, msg sdk.Msg) sdk.Result {
switch msg := msg.(type) {
case MsgChangeKey:
return handleMsgChangeKey(ctx, am, msg)
default:
errMsg := "Unrecognized auth Msg type: " + reflect.TypeOf(msg).Name()
errMsg := "Unrecognized baseaccount Msg type: " + reflect.TypeOf(msg).Name()
return sdk.ErrUnknownRequest(errMsg).Result()
}
}
@ -23,7 +23,7 @@ func NewHandler(am AccountMapper) sdk.Handler {
// Should be very expensive, because once this happens, an account is un-prunable
func handleMsgChangeKey(ctx sdk.Context, am AccountMapper, msg MsgChangeKey) sdk.Result {
err := am.setPubKey(ctx, msg.Address, msg.NewPubKey)
err := am.SetPubKey(ctx, msg.Address, msg.NewPubKey)
if err != nil {
return err.Result()
}

View File

@ -9,9 +9,6 @@ import (
crypto "github.com/tendermint/go-crypto"
)
var _ sdk.AccountMapper = (*AccountMapper)(nil)
// Implements sdk.AccountMapper.
// This AccountMapper encodes/decodes accounts using the
// go-amino (binary) encoding/decoding library.
type AccountMapper struct {
@ -19,8 +16,8 @@ type AccountMapper struct {
// The (unexposed) key used to access the store from the Context.
key sdk.StoreKey
// The prototypical sdk.Account concrete type.
proto sdk.Account
// The prototypical Account concrete type.
proto Account
// The wire codec for binary encoding/decoding of accounts.
cdc *wire.Codec
@ -29,7 +26,7 @@ type AccountMapper struct {
// NewAccountMapper returns a new sdk.AccountMapper that
// uses go-amino to (binary) encode and decode concrete sdk.Accounts.
// nolint
func NewAccountMapper(cdc *wire.Codec, key sdk.StoreKey, proto sdk.Account) AccountMapper {
func NewAccountMapper(cdc *wire.Codec, key sdk.StoreKey, proto Account) AccountMapper {
return AccountMapper{
key: key,
proto: proto,
@ -38,14 +35,14 @@ func NewAccountMapper(cdc *wire.Codec, key sdk.StoreKey, proto sdk.Account) Acco
}
// Implaements sdk.AccountMapper.
func (am AccountMapper) NewAccountWithAddress(ctx sdk.Context, addr sdk.Address) sdk.Account {
func (am AccountMapper) NewAccountWithAddress(ctx sdk.Context, addr sdk.Address) Account {
acc := am.clonePrototype()
acc.SetAddress(addr)
return acc
}
// Implements sdk.AccountMapper.
func (am AccountMapper) GetAccount(ctx sdk.Context, addr sdk.Address) sdk.Account {
func (am AccountMapper) GetAccount(ctx sdk.Context, addr sdk.Address) Account {
store := ctx.KVStore(am.key)
bz := store.Get(addr)
if bz == nil {
@ -56,7 +53,7 @@ func (am AccountMapper) GetAccount(ctx sdk.Context, addr sdk.Address) sdk.Accoun
}
// Implements sdk.AccountMapper.
func (am AccountMapper) SetAccount(ctx sdk.Context, acc sdk.Account) {
func (am AccountMapper) SetAccount(ctx sdk.Context, acc Account) {
addr := acc.GetAddress()
store := ctx.KVStore(am.key)
bz := am.encodeAccount(acc)
@ -64,7 +61,7 @@ func (am AccountMapper) SetAccount(ctx sdk.Context, acc sdk.Account) {
}
// Implements sdk.AccountMapper.
func (am AccountMapper) IterateAccounts(ctx sdk.Context, process func(sdk.Account) (stop bool)) {
func (am AccountMapper) IterateAccounts(ctx sdk.Context, process func(Account) (stop bool)) {
store := ctx.KVStore(am.key)
iter := store.Iterator(nil, nil)
for {
@ -89,7 +86,8 @@ func (am AccountMapper) GetPubKey(ctx sdk.Context, addr sdk.Address) (crypto.Pub
return acc.GetPubKey(), nil
}
func (am AccountMapper) setPubKey(ctx sdk.Context, addr sdk.Address, newPubKey crypto.PubKey) sdk.Error {
// Sets the PubKey of the account at address
func (am AccountMapper) SetPubKey(ctx sdk.Context, addr sdk.Address, newPubKey crypto.PubKey) sdk.Error {
acc := am.GetAccount(ctx, addr)
if acc == nil {
return sdk.ErrUnknownAddress(addr.String())
@ -122,7 +120,7 @@ func (am AccountMapper) setSequence(ctx sdk.Context, addr sdk.Address, newSequen
// misc.
// Creates a new struct (or pointer to struct) from am.proto.
func (am AccountMapper) clonePrototype() sdk.Account {
func (am AccountMapper) clonePrototype() Account {
protoRt := reflect.TypeOf(am.proto)
if protoRt.Kind() == reflect.Ptr {
protoCrt := protoRt.Elem()
@ -130,7 +128,7 @@ func (am AccountMapper) clonePrototype() sdk.Account {
panic("accountMapper requires a struct proto sdk.Account, or a pointer to one")
}
protoRv := reflect.New(protoCrt)
clone, ok := protoRv.Interface().(sdk.Account)
clone, ok := protoRv.Interface().(Account)
if !ok {
panic(fmt.Sprintf("accountMapper requires a proto sdk.Account, but %v doesn't implement sdk.Account", protoRt))
}
@ -138,14 +136,14 @@ func (am AccountMapper) clonePrototype() sdk.Account {
}
protoRv := reflect.New(protoRt).Elem()
clone, ok := protoRv.Interface().(sdk.Account)
clone, ok := protoRv.Interface().(Account)
if !ok {
panic(fmt.Sprintf("accountMapper requires a proto sdk.Account, but %v doesn't implement sdk.Account", protoRt))
}
return clone
}
func (am AccountMapper) encodeAccount(acc sdk.Account) []byte {
func (am AccountMapper) encodeAccount(acc Account) []byte {
bz, err := am.cdc.MarshalBinaryBare(acc)
if err != nil {
panic(err)
@ -153,7 +151,7 @@ func (am AccountMapper) encodeAccount(acc sdk.Account) []byte {
return bz
}
func (am AccountMapper) decodeAccount(bz []byte) (acc sdk.Account) {
func (am AccountMapper) decodeAccount(bz []byte) (acc Account) {
err := am.cdc.UnmarshalBinaryBare(bz, &acc)
if err != nil {
panic(err)

View File

@ -14,17 +14,19 @@ import (
wire "github.com/cosmos/cosmos-sdk/wire"
)
func setupMultiStore() (sdk.MultiStore, *sdk.KVStoreKey) {
func setupMultiStore() (sdk.MultiStore, *sdk.KVStoreKey, *sdk.KVStoreKey) {
db := dbm.NewMemDB()
capKey := sdk.NewKVStoreKey("capkey")
capKey2 := sdk.NewKVStoreKey("capkey2")
ms := store.NewCommitMultiStore(db)
ms.MountStoreWithDB(capKey, sdk.StoreTypeIAVL, db)
ms.MountStoreWithDB(capKey2, sdk.StoreTypeIAVL, db)
ms.LoadLatestVersion()
return ms, capKey
return ms, capKey, capKey2
}
func TestAccountMapperGetSet(t *testing.T) {
ms, capKey := setupMultiStore()
ms, capKey, _ := setupMultiStore()
cdc := wire.NewCodec()
RegisterBaseAccount(cdc)

View File

@ -3,9 +3,8 @@ package auth
import (
"encoding/json"
"github.com/tendermint/go-crypto"
sdk "github.com/cosmos/cosmos-sdk/types"
crypto "github.com/tendermint/go-crypto"
)
// MsgChangeKey - high level transaction of the auth module

131
x/auth/stdtx.go Normal file
View File

@ -0,0 +1,131 @@
package auth
import (
"encoding/json"
sdk "github.com/cosmos/cosmos-sdk/types"
crypto "github.com/tendermint/go-crypto"
)
var _ sdk.Tx = (*StdTx)(nil)
// StdTx is a standard way to wrap a Msg with Fee and Signatures.
// NOTE: the first signature is the FeePayer (Signatures must not be nil).
type StdTx struct {
Msg sdk.Msg `json:"msg"`
Fee StdFee `json:"fee"`
Signatures []StdSignature `json:"signatures"`
}
func NewStdTx(msg sdk.Msg, fee StdFee, sigs []StdSignature) StdTx {
return StdTx{
Msg: msg,
Fee: fee,
Signatures: sigs,
}
}
//nolint
func (tx StdTx) GetMsg() sdk.Msg { return tx.Msg }
// Signatures returns the signature of signers who signed the Msg.
// CONTRACT: Length returned is same as length of
// pubkeys returned from MsgKeySigners, and the order
// matches.
// CONTRACT: If the signature is missing (ie the Msg is
// invalid), then the corresponding signature is
// .Empty().
func (tx StdTx) GetSignatures() []StdSignature { return tx.Signatures }
// FeePayer returns the address responsible for paying the fees
// for the transactions. It's the first address returned by msg.GetSigners().
// If GetSigners() is empty, this panics.
func FeePayer(tx sdk.Tx) sdk.Address {
return tx.GetMsg().GetSigners()[0]
}
//__________________________________________________________
// StdFee includes the amount of coins paid in fees and the maximum
// gas to be used by the transaction. The ratio yields an effective "gasprice",
// which must be above some miminum to be accepted into the mempool.
type StdFee struct {
Amount sdk.Coins `json:"amount"`
Gas int64 `json:"gas"`
}
func NewStdFee(gas int64, amount ...sdk.Coin) StdFee {
return StdFee{
Amount: amount,
Gas: gas,
}
}
// fee bytes for signing later
func (fee StdFee) Bytes() []byte {
// normalize. XXX
// this is a sign of something ugly
// (in the lcd_test, client side its null,
// server side its [])
if len(fee.Amount) == 0 {
fee.Amount = sdk.Coins{}
}
bz, err := json.Marshal(fee) // TODO
if err != nil {
panic(err)
}
return bz
}
//__________________________________________________________
// StdSignDoc is replay-prevention structure.
// It includes the result of msg.GetSignBytes(),
// as well as the ChainID (prevent cross chain replay)
// and the Sequence numbers for each signature (prevent
// inchain replay and enforce tx ordering per account).
type StdSignDoc struct {
ChainID string `json:"chain_id"`
Sequences []int64 `json:"sequences"`
FeeBytes []byte `json:"fee_bytes"`
MsgBytes []byte `json:"msg_bytes"`
AltBytes []byte `json:"alt_bytes"`
}
// StdSignBytes returns the bytes to sign for a transaction.
// TODO: change the API to just take a chainID and StdTx ?
func StdSignBytes(chainID string, sequences []int64, fee StdFee, msg sdk.Msg) []byte {
bz, err := json.Marshal(StdSignDoc{
ChainID: chainID,
Sequences: sequences,
FeeBytes: fee.Bytes(),
MsgBytes: msg.GetSignBytes(),
})
if err != nil {
panic(err)
}
return bz
}
// StdSignMsg is a convenience structure for passing along
// a Msg with the other requirements for a StdSignDoc before
// it is signed. For use in the CLI.
type StdSignMsg struct {
ChainID string
Sequences []int64
Fee StdFee
Msg sdk.Msg
// XXX: Alt
}
// get message bytes
func (msg StdSignMsg) Bytes() []byte {
return StdSignBytes(msg.ChainID, msg.Sequences, msg.Fee, msg.Msg)
}
// Standard Signature
type StdSignature struct {
crypto.PubKey `json:"pub_key"` // optional
crypto.Signature `json:"signature"`
Sequence int64 `json:"sequence"`
}

View File

@ -1,4 +1,4 @@
package types
package auth
import (
"testing"
@ -6,18 +6,20 @@ import (
"github.com/stretchr/testify/assert"
crypto "github.com/tendermint/go-crypto"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func newStdFee() StdFee {
return NewStdFee(100,
Coin{"atom", 150},
)
}
// func newStdFee() StdFee {
// return NewStdFee(100,
// Coin{"atom", 150},
// )
// }
func TestStdTx(t *testing.T) {
priv := crypto.GenPrivKeyEd25519()
addr := priv.PubKey().Address()
msg := NewTestMsg(addr)
msg := sdk.NewTestMsg(addr)
fee := newStdFee()
sigs := []StdSignature{}

View File

@ -1,12 +1,12 @@
package auth
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/wire"
)
// Register concrete types on wire codec for default AppAccount
func RegisterWire(cdc *wire.Codec) {
cdc.RegisterInterface((*sdk.Account)(nil), nil)
cdc.RegisterInterface((*Account)(nil), nil)
cdc.RegisterConcrete(&BaseAccount{}, "auth/Account", nil)
cdc.RegisterConcrete(MsgChangeKey{}, "auth/ChangeKey", nil)
}

View File

@ -4,6 +4,7 @@ import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
)
const (
@ -16,11 +17,11 @@ const (
// Keeper manages transfers between accounts
type Keeper struct {
am sdk.AccountMapper
am auth.AccountMapper
}
// NewKeeper returns a new Keeper
func NewKeeper(am sdk.AccountMapper) Keeper {
func NewKeeper(am auth.AccountMapper) Keeper {
return Keeper{am: am}
}
@ -63,11 +64,11 @@ func (keeper Keeper) InputOutputCoins(ctx sdk.Context, inputs []Input, outputs [
// SendKeeper only allows transfers between accounts, without the possibility of creating coins
type SendKeeper struct {
am sdk.AccountMapper
am auth.AccountMapper
}
// NewSendKeeper returns a new Keeper
func NewSendKeeper(am sdk.AccountMapper) SendKeeper {
func NewSendKeeper(am auth.AccountMapper) SendKeeper {
return SendKeeper{am: am}
}
@ -95,11 +96,11 @@ func (keeper SendKeeper) InputOutputCoins(ctx sdk.Context, inputs []Input, outpu
// ViewKeeper only allows reading of balances
type ViewKeeper struct {
am sdk.AccountMapper
am auth.AccountMapper
}
// NewViewKeeper returns a new Keeper
func NewViewKeeper(am sdk.AccountMapper) ViewKeeper {
func NewViewKeeper(am auth.AccountMapper) ViewKeeper {
return ViewKeeper{am: am}
}
@ -115,7 +116,7 @@ func (keeper ViewKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coi
//______________________________________________________________________________________________
func getCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address) sdk.Coins {
func getCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address) sdk.Coins {
ctx.GasMeter().ConsumeGas(costGetCoins, "getCoins")
acc := am.GetAccount(ctx, addr)
if acc == nil {
@ -124,7 +125,7 @@ func getCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address) sdk.Coins
return acc.GetCoins()
}
func setCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) sdk.Error {
func setCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt sdk.Coins) sdk.Error {
ctx.GasMeter().ConsumeGas(costSetCoins, "setCoins")
acc := am.GetAccount(ctx, addr)
if acc == nil {
@ -136,13 +137,13 @@ func setCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.C
}
// HasCoins returns whether or not an account has at least amt coins.
func hasCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) bool {
func hasCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt sdk.Coins) bool {
ctx.GasMeter().ConsumeGas(costHasCoins, "hasCoins")
return getCoins(ctx, am, addr).IsGTE(amt)
}
// SubtractCoins subtracts amt from the coins at the addr.
func subtractCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
func subtractCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
ctx.GasMeter().ConsumeGas(costSubtractCoins, "subtractCoins")
oldCoins := getCoins(ctx, am, addr)
newCoins := oldCoins.Minus(amt)
@ -155,7 +156,7 @@ func subtractCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt
}
// AddCoins adds amt to the coins at the addr.
func addCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
func addCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) {
ctx.GasMeter().ConsumeGas(costAddCoins, "addCoins")
oldCoins := getCoins(ctx, am, addr)
newCoins := oldCoins.Plus(amt)
@ -169,7 +170,7 @@ func addCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.C
// SendCoins moves coins from one account to another
// NOTE: Make sure to revert state changes from tx on error
func sendCoins(ctx sdk.Context, am sdk.AccountMapper, fromAddr sdk.Address, toAddr sdk.Address, amt sdk.Coins) (sdk.Tags, sdk.Error) {
func sendCoins(ctx sdk.Context, am auth.AccountMapper, fromAddr sdk.Address, toAddr sdk.Address, amt sdk.Coins) (sdk.Tags, sdk.Error) {
_, subTags, err := subtractCoins(ctx, am, fromAddr, amt)
if err != nil {
return nil, err
@ -185,7 +186,7 @@ func sendCoins(ctx sdk.Context, am sdk.AccountMapper, fromAddr sdk.Address, toAd
// InputOutputCoins handles a list of inputs and outputs
// NOTE: Make sure to revert state changes from tx on error
func inputOutputCoins(ctx sdk.Context, am sdk.AccountMapper, inputs []Input, outputs []Output) (sdk.Tags, sdk.Error) {
func inputOutputCoins(ctx sdk.Context, am auth.AccountMapper, inputs []Input, outputs []Output) (sdk.Tags, sdk.Error) {
allTags := sdk.EmptyTags()
for _, in := range inputs {

View File

@ -12,6 +12,7 @@ import (
"github.com/cosmos/cosmos-sdk/client/context"
sdk "github.com/cosmos/cosmos-sdk/types"
wire "github.com/cosmos/cosmos-sdk/wire"
"github.com/cosmos/cosmos-sdk/x/auth"
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
"github.com/cosmos/cosmos-sdk/x/ibc"
)
@ -27,7 +28,7 @@ const (
type relayCommander struct {
cdc *wire.Codec
address sdk.Address
decoder sdk.AccountDecoder
decoder auth.AccountDecoder
mainStore string
ibcStore string
accStore string

View File

@ -6,7 +6,7 @@ import (
"github.com/stretchr/testify/assert"
abci "github.com/tendermint/abci/types"
"github.com/tendermint/go-crypto"
crypto "github.com/tendermint/go-crypto"
dbm "github.com/tendermint/tmlibs/db"
"github.com/tendermint/tmlibs/log"
@ -49,7 +49,7 @@ func makeCodec() *wire.Codec {
cdc.RegisterConcrete(IBCReceiveMsg{}, "test/ibc/IBCReceiveMsg", nil)
// Register AppAccount
cdc.RegisterInterface((*sdk.Account)(nil), nil)
cdc.RegisterInterface((*auth.Account)(nil), nil)
cdc.RegisterConcrete(&auth.BaseAccount{}, "test/ibc/Account", nil)
wire.RegisterCrypto(cdc)

View File

@ -72,7 +72,7 @@ func makeTestCodec() *wire.Codec {
cdc.RegisterConcrete(MsgUnbond{}, "test/stake/Unbond", nil)
// Register AppAccount
cdc.RegisterInterface((*sdk.Account)(nil), nil)
cdc.RegisterInterface((*auth.Account)(nil), nil)
cdc.RegisterConcrete(&auth.BaseAccount{}, "test/stake/Account", nil)
wire.RegisterCrypto(cdc)
@ -91,7 +91,8 @@ func paramsNoInflation() Params {
}
// hogpodge of all sorts of input required for testing
func createTestInput(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context, sdk.AccountMapper, Keeper) {
func createTestInput(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context, auth.AccountMapper, Keeper) {
keyStake := sdk.NewKVStoreKey("stake")
keyAcc := sdk.NewKVStoreKey("acc")