From 2c9a5bc308c0683f26c4c22d338f8e8197066ae1 Mon Sep 17 00:00:00 2001 From: Jack Zampolin Date: Fri, 8 Feb 2019 13:35:19 -0800 Subject: [PATCH] Merge PR #3554: x/auth and x/bank review results --- client/rest/rest.go | 2 +- client/utils/utils.go | 2 +- x/auth/account.go | 53 +++++++++------------- x/auth/ante.go | 7 ++- x/auth/client/txbuilder/txbuilder.go | 10 ++--- x/auth/client/txbuilder/txbuilder_test.go | 2 +- x/auth/codec.go | 13 +++++- x/auth/feekeeper.go | 9 ++-- x/auth/genesis.go | 11 +++-- x/auth/keeper.go | 46 +++++++++---------- x/auth/params.go | 27 +---------- x/auth/stdtx.go | 15 ++++--- x/bank/errors.go | 55 +++++------------------ x/bank/genesis.go | 2 +- x/bank/keeper.go | 19 ++------ x/bank/msgs.go | 43 ++++++++---------- x/bank/params.go | 6 +-- 17 files changed, 119 insertions(+), 203 deletions(-) diff --git a/client/rest/rest.go b/client/rest/rest.go index f7310835c974..80f48ff298a2 100644 --- a/client/rest/rest.go +++ b/client/rest/rest.go @@ -237,7 +237,7 @@ func WriteGenerateStdTxResponse( } } - stdMsg, err := txBldr.Build(msgs) + stdMsg, err := txBldr.BuildSignMsg(msgs) if err != nil { WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return diff --git a/client/utils/utils.go b/client/utils/utils.go index 2840b045117c..8f4283088885 100644 --- a/client/utils/utils.go +++ b/client/utils/utils.go @@ -294,7 +294,7 @@ func buildUnsignedStdTxOffline(txBldr authtxb.TxBuilder, cliCtx context.CLIConte fmt.Fprintf(os.Stderr, "estimated gas = %v\n", txBldr.Gas()) } - stdSignMsg, err := txBldr.Build(msgs) + stdSignMsg, err := txBldr.BuildSignMsg(msgs) if err != nil { return } diff --git a/x/auth/account.go b/x/auth/account.go index bb4e98684128..5c60c59a8d44 100644 --- a/x/auth/account.go +++ b/x/auth/account.go @@ -7,7 +7,6 @@ import ( "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -62,6 +61,7 @@ type VestingAccount interface { } // AccountDecoder unmarshals account bytes +// TODO: Think about removing type AccountDecoder func(accountBytes []byte) (Account, error) //----------------------------------------------------------------------------- @@ -90,8 +90,8 @@ func (acc BaseAccount) String() string { } return fmt.Sprintf(`Account: - Address: %s - Pubkey: %s + Address: %s + Pubkey: %s Coins: %s AccountNumber: %d Sequence: %d`, @@ -99,23 +99,24 @@ func (acc BaseAccount) String() string { ) } -// Prototype function for BaseAccount +// ProtoBaseAccount - a prototype function for BaseAccount func ProtoBaseAccount() Account { return &BaseAccount{} } +// NewBaseAccountWithAddress - returns a new base account with a given address func NewBaseAccountWithAddress(addr sdk.AccAddress) BaseAccount { return BaseAccount{ Address: addr, } } -// Implements sdk.Account. +// GetAddress - Implements sdk.Account. func (acc BaseAccount) GetAddress() sdk.AccAddress { return acc.Address } -// Implements sdk.Account. +// SetAddress - Implements sdk.Account. func (acc *BaseAccount) SetAddress(addr sdk.AccAddress) error { if len(acc.Address) != 0 { return errors.New("cannot override BaseAccount address") @@ -124,45 +125,45 @@ func (acc *BaseAccount) SetAddress(addr sdk.AccAddress) error { return nil } -// Implements sdk.Account. +// GetPubKey - Implements sdk.Account. func (acc BaseAccount) GetPubKey() crypto.PubKey { return acc.PubKey } -// Implements sdk.Account. +// SetPubKey - Implements sdk.Account. func (acc *BaseAccount) SetPubKey(pubKey crypto.PubKey) error { acc.PubKey = pubKey return nil } -// Implements sdk.Account. +// GetCoins - Implements sdk.Account. func (acc *BaseAccount) GetCoins() sdk.Coins { return acc.Coins } -// Implements sdk.Account. +// SetCoins - Implements sdk.Account. func (acc *BaseAccount) SetCoins(coins sdk.Coins) error { acc.Coins = coins return nil } -// Implements Account +// GetAccountNumber - Implements Account func (acc *BaseAccount) GetAccountNumber() uint64 { return acc.AccountNumber } -// Implements Account +// SetAccountNumber - Implements Account func (acc *BaseAccount) SetAccountNumber(accNumber uint64) error { acc.AccountNumber = accNumber return nil } -// Implements sdk.Account. +// GetSequence - Implements sdk.Account. func (acc *BaseAccount) GetSequence() uint64 { return acc.Sequence } -// Implements sdk.Account. +// SetSequence - Implements sdk.Account. func (acc *BaseAccount) SetSequence(seq uint64) error { acc.Sequence = seq return nil @@ -198,8 +199,8 @@ func (bva BaseVestingAccount) String() string { } return fmt.Sprintf(`Vesting Account: - Address: %s - Pubkey: %s + Address: %s + Pubkey: %s Coins: %s AccountNumber: %d Sequence: %d @@ -345,6 +346,7 @@ type ContinuousVestingAccount struct { StartTime int64 // when the coins start to vest } +// NewContinuousVestingAccount returns a new ContinuousVestingAccount func NewContinuousVestingAccount( baseAcc *BaseAccount, StartTime, EndTime int64, ) *ContinuousVestingAccount { @@ -369,8 +371,8 @@ func (cva ContinuousVestingAccount) String() string { } return fmt.Sprintf(`Continuous Vesting Account: - Address: %s - Pubkey: %s + Address: %s + Pubkey: %s Coins: %s AccountNumber: %d Sequence: %d @@ -454,6 +456,7 @@ type DelayedVestingAccount struct { *BaseVestingAccount } +// NewDelayedVestingAccount returns a DelayedVestingAccount func NewDelayedVestingAccount(baseAcc *BaseAccount, EndTime int64) *DelayedVestingAccount { baseVestingAcc := &BaseVestingAccount{ BaseAccount: baseAcc, @@ -502,17 +505,3 @@ func (dva *DelayedVestingAccount) GetStartTime() int64 { func (dva *DelayedVestingAccount) GetEndTime() int64 { return dva.EndTime } - -//----------------------------------------------------------------------------- -// Codec - -// Most users shouldn't use this, but this comes in handy for tests. -func RegisterBaseAccount(cdc *codec.Codec) { - cdc.RegisterInterface((*Account)(nil), nil) - cdc.RegisterInterface((*VestingAccount)(nil), nil) - cdc.RegisterConcrete(&BaseAccount{}, "cosmos-sdk/BaseAccount", nil) - cdc.RegisterConcrete(&BaseVestingAccount{}, "cosmos-sdk/BaseVestingAccount", nil) - cdc.RegisterConcrete(&ContinuousVestingAccount{}, "cosmos-sdk/ContinuousVestingAccount", nil) - cdc.RegisterConcrete(&DelayedVestingAccount{}, "cosmos-sdk/DelayedVestingAccount", nil) - codec.RegisterCrypto(cdc) -} diff --git a/x/auth/ante.go b/x/auth/ante.go index 90ed43f692a2..ca09e3210a12 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -22,6 +22,7 @@ var ( ) func init() { + // This decodes a valid hex string into a sepc256k1Pubkey for use in transaction simulation bz, _ := hex.DecodeString("035AD6810A47F073553FF30D2FCC7E0D3B1C0B74B61A1AAA2582344037151E143A") copy(simSecp256k1Pubkey[:], bz) } @@ -192,9 +193,7 @@ func processSig( return nil, sdk.ErrUnauthorized("signature verification failed").Result() } - err = acc.SetSequence(acc.GetSequence() + 1) - if err != nil { - // Handle w/ #870 + if err := acc.SetSequence(acc.GetSequence() + 1); err != nil { panic(err) } @@ -327,7 +326,7 @@ func DeductFees(blockTime time.Time, acc Account, fee StdFee) (Account, sdk.Resu } // EnsureSufficientMempoolFees verifies that the given transaction has supplied -// enough fees to cover a proposer's minimum fees. An result object is returned +// enough fees to cover a proposer's minimum fees. A result object is returned // indicating success or failure. // // Contract: This should only be called during CheckTx as it cannot be part of diff --git a/x/auth/client/txbuilder/txbuilder.go b/x/auth/client/txbuilder/txbuilder.go index 5f2a76f523f8..7ac59426e7eb 100644 --- a/x/auth/client/txbuilder/txbuilder.go +++ b/x/auth/client/txbuilder/txbuilder.go @@ -174,11 +174,9 @@ func (bldr TxBuilder) WithAccountNumber(accnum uint64) TxBuilder { return bldr } -// Build builds a single message to be signed from a TxBuilder given a set of +// BuildSignMsg builds a single message to be signed from a TxBuilder given a set of // messages. It returns an error if a fee is supplied but cannot be parsed. -// -// TODO: Should consider renaming to BuildSignMsg. -func (bldr TxBuilder) Build(msgs []sdk.Msg) (StdSignMsg, error) { +func (bldr TxBuilder) BuildSignMsg(msgs []sdk.Msg) (StdSignMsg, error) { chainID := bldr.chainID if chainID == "" { return StdSignMsg{}, fmt.Errorf("chain ID required but not specified") @@ -226,7 +224,7 @@ func (bldr TxBuilder) Sign(name, passphrase string, msg StdSignMsg) ([]byte, err // with the built message given a name, passphrase, and a set of // messages. func (bldr TxBuilder) BuildAndSign(name, passphrase string, msgs []sdk.Msg) ([]byte, error) { - msg, err := bldr.Build(msgs) + msg, err := bldr.BuildSignMsg(msgs) if err != nil { return nil, err } @@ -237,7 +235,7 @@ func (bldr TxBuilder) BuildAndSign(name, passphrase string, msgs []sdk.Msg) ([]b // BuildTxForSim creates a StdSignMsg and encodes a transaction with the // StdSignMsg with a single empty StdSignature for tx simulation. func (bldr TxBuilder) BuildTxForSim(msgs []sdk.Msg) ([]byte, error) { - signMsg, err := bldr.Build(msgs) + signMsg, err := bldr.BuildSignMsg(msgs) if err != nil { return nil, err } diff --git a/x/auth/client/txbuilder/txbuilder_test.go b/x/auth/client/txbuilder/txbuilder_test.go index fd2eeefc3491..cddd1314143f 100644 --- a/x/auth/client/txbuilder/txbuilder_test.go +++ b/x/auth/client/txbuilder/txbuilder_test.go @@ -94,7 +94,7 @@ func TestTxBuilderBuild(t *testing.T) { tc.fields.ChainID, tc.fields.Memo, tc.fields.Fees, tc.fields.GasPrices, ) - got, err := bldr.Build(tc.msgs) + got, err := bldr.BuildSignMsg(tc.msgs) require.Equal(t, tc.wantErr, (err != nil), "TxBuilder.Build() error = %v, wantErr %v, tc %d", err, tc.wantErr, i) if !reflect.DeepEqual(got, tc.want) { t.Errorf("TxBuilder.Build() = %v, want %v", got, tc.want) diff --git a/x/auth/codec.go b/x/auth/codec.go index 0c8374d5ea7a..0d7694300f1f 100644 --- a/x/auth/codec.go +++ b/x/auth/codec.go @@ -4,7 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -// Register concrete types on codec codec for default AppAccount +// RegisterCodec registers concrete types on the codec func RegisterCodec(cdc *codec.Codec) { cdc.RegisterInterface((*Account)(nil), nil) cdc.RegisterConcrete(&BaseAccount{}, "auth/Account", nil) @@ -15,6 +15,17 @@ func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(StdTx{}, "auth/StdTx", nil) } +// RegisterBaseAccount most users shouldn't use this, but this comes in handy for tests. +func RegisterBaseAccount(cdc *codec.Codec) { + cdc.RegisterInterface((*Account)(nil), nil) + cdc.RegisterInterface((*VestingAccount)(nil), nil) + cdc.RegisterConcrete(&BaseAccount{}, "cosmos-sdk/BaseAccount", nil) + cdc.RegisterConcrete(&BaseVestingAccount{}, "cosmos-sdk/BaseVestingAccount", nil) + cdc.RegisterConcrete(&ContinuousVestingAccount{}, "cosmos-sdk/ContinuousVestingAccount", nil) + cdc.RegisterConcrete(&DelayedVestingAccount{}, "cosmos-sdk/DelayedVestingAccount", nil) + codec.RegisterCrypto(cdc) +} + var msgCdc = codec.New() func init() { diff --git a/x/auth/feekeeper.go b/x/auth/feekeeper.go index 0006a918529c..2b37a1402612 100644 --- a/x/auth/feekeeper.go +++ b/x/auth/feekeeper.go @@ -9,7 +9,7 @@ var ( collectedFeesKey = []byte("collectedFees") ) -// This FeeCollectionKeeper handles collection of fees in the anteHandler +// FeeCollectionKeeper handles collection of fees in the anteHandler // and setting of MinFees for different fee tokens type FeeCollectionKeeper struct { @@ -20,6 +20,7 @@ type FeeCollectionKeeper struct { cdc *codec.Codec } +// NewFeeCollectionKeeper returns a new FeeCollectionKeeper func NewFeeCollectionKeeper(cdc *codec.Codec, key sdk.StoreKey) FeeCollectionKeeper { return FeeCollectionKeeper{ key: key, @@ -27,7 +28,7 @@ func NewFeeCollectionKeeper(cdc *codec.Codec, key sdk.StoreKey) FeeCollectionKee } } -// retrieves the collected fee pool +// GetCollectedFees - retrieves the collected fee pool func (fck FeeCollectionKeeper) GetCollectedFees(ctx sdk.Context) sdk.Coins { store := ctx.KVStore(fck.key) bz := store.Get(collectedFeesKey) @@ -46,7 +47,7 @@ func (fck FeeCollectionKeeper) setCollectedFees(ctx sdk.Context, coins sdk.Coins store.Set(collectedFeesKey, bz) } -// add to the fee pool +// AddCollectedFees - add to the fee pool func (fck FeeCollectionKeeper) AddCollectedFees(ctx sdk.Context, coins sdk.Coins) sdk.Coins { newCoins := fck.GetCollectedFees(ctx).Plus(coins) fck.setCollectedFees(ctx, newCoins) @@ -54,7 +55,7 @@ func (fck FeeCollectionKeeper) AddCollectedFees(ctx sdk.Context, coins sdk.Coins return newCoins } -// clear the fee pool +// ClearCollectedFees - clear the fee pool func (fck FeeCollectionKeeper) ClearCollectedFees(ctx sdk.Context) { fck.setCollectedFees(ctx, sdk.Coins{}) } diff --git a/x/auth/genesis.go b/x/auth/genesis.go index 2836fd899c1b..da2beb0d7129 100644 --- a/x/auth/genesis.go +++ b/x/auth/genesis.go @@ -8,24 +8,24 @@ import ( // GenesisState - all auth state that must be provided at genesis type GenesisState struct { - CollectedFees sdk.Coins `json:"collected_fees"` // collected fees + CollectedFees sdk.Coins `json:"collected_fees"` Params Params `json:"params"` } -// Create a new genesis state +// NewGenesisState - Create a new genesis state func NewGenesisState(collectedFees sdk.Coins, params Params) GenesisState { return GenesisState{ - CollectedFees: collectedFees, Params: params, + CollectedFees: collectedFees, } } -// Return a default genesis state +// DefaultGenesisState - Return a default genesis state func DefaultGenesisState() GenesisState { return NewGenesisState(sdk.Coins{}, DefaultParams()) } -// Init store state from genesis data +// InitGenesis - Init store state from genesis data func InitGenesis(ctx sdk.Context, ak AccountKeeper, fck FeeCollectionKeeper, data GenesisState) { ak.SetParams(ctx, data.Params) fck.setCollectedFees(ctx, data.CollectedFees) @@ -57,6 +57,5 @@ func ValidateGenesis(data GenesisState) error { if data.Params.TxSizeCostPerByte == 0 { return fmt.Errorf("invalid tx size cost per byte: %d", data.Params.TxSizeCostPerByte) } - return nil } diff --git a/x/auth/keeper.go b/x/auth/keeper.go index 7167cc32d85b..e01c5c9a8286 100644 --- a/x/auth/keeper.go +++ b/x/auth/keeper.go @@ -9,7 +9,7 @@ import ( ) var ( - // Prefix for account-by-address store + // AddressStoreKeyPrefix prefix for account-by-address store AddressStoreKeyPrefix = []byte{0x01} globalAccountNumberKey = []byte("globalAccountNumber") @@ -21,7 +21,7 @@ var ( FeeStoreKey = "fee" ) -// This AccountKeeper encodes/decodes accounts using the go-amino (binary) +// AccountKeeper encodes/decodes accounts using the go-amino (binary) // encoding/decoding library. type AccountKeeper struct { // The (unexposed) key used to access the store from the Context. @@ -51,7 +51,7 @@ func NewAccountKeeper( } } -// Implaements sdk.AccountKeeper. +// NewAccountWithAddress implements sdk.AccountKeeper. func (ak AccountKeeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) Account { acc := ak.proto() err := acc.SetAddress(addr) @@ -67,22 +67,20 @@ func (ak AccountKeeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddre return acc } -// New Account +// NewAccount creates a new account func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc Account) Account { - err := acc.SetAccountNumber(ak.GetNextAccountNumber(ctx)) - if err != nil { - // TODO: Handle with #870 + if err := acc.SetAccountNumber(ak.GetNextAccountNumber(ctx)); err != nil { panic(err) } return acc } -// Turn an address to key used to get it from the account store +// AddressStoreKey turn an address to key used to get it from the account store func AddressStoreKey(addr sdk.AccAddress) []byte { return append(AddressStoreKeyPrefix, addr.Bytes()...) } -// Implements sdk.AccountKeeper. +// GetAccount implements sdk.AccountKeeper. func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) Account { store := ctx.KVStore(ak.key) bz := store.Get(AddressStoreKey(addr)) @@ -93,22 +91,26 @@ func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) Account return acc } -// Implements sdk.AccountKeeper. +// SetAccount implements sdk.AccountKeeper. func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc Account) { addr := acc.GetAddress() store := ctx.KVStore(ak.key) - bz := ak.encodeAccount(acc) + bz, err := ak.cdc.MarshalBinaryBare(acc) + if err != nil { + panic(err) + } store.Set(AddressStoreKey(addr), bz) } // RemoveAccount removes an account for the account mapper store. +// NOTE: this will cause supply invariant violation if called func (ak AccountKeeper) RemoveAccount(ctx sdk.Context, acc Account) { addr := acc.GetAddress() store := ctx.KVStore(ak.key) store.Delete(AddressStoreKey(addr)) } -// Implements sdk.AccountKeeper. +// IterateAccounts implements sdk.AccountKeeper. func (ak AccountKeeper) IterateAccounts(ctx sdk.Context, process func(Account) (stop bool)) { store := ctx.KVStore(ak.key) iter := sdk.KVStorePrefixIterator(store, AddressStoreKeyPrefix) @@ -126,7 +128,7 @@ func (ak AccountKeeper) IterateAccounts(ctx sdk.Context, process func(Account) ( } } -// Returns the PubKey of the account at address +// GetPubKey Returns the PubKey of the account at address func (ak AccountKeeper) GetPubKey(ctx sdk.Context, addr sdk.AccAddress) (crypto.PubKey, sdk.Error) { acc := ak.GetAccount(ctx, addr) if acc == nil { @@ -135,7 +137,7 @@ func (ak AccountKeeper) GetPubKey(ctx sdk.Context, addr sdk.AccAddress) (crypto. return acc.GetPubKey(), nil } -// Returns the Sequence of the account at address +// GetSequence Returns the Sequence of the account at address func (ak AccountKeeper) GetSequence(ctx sdk.Context, addr sdk.AccAddress) (uint64, sdk.Error) { acc := ak.GetAccount(ctx, addr) if acc == nil { @@ -149,16 +151,16 @@ func (ak AccountKeeper) setSequence(ctx sdk.Context, addr sdk.AccAddress, newSeq if acc == nil { return sdk.ErrUnknownAddress(addr.String()) } - err := acc.SetSequence(newSequence) - if err != nil { - // Handle w/ #870 + + if err := acc.SetSequence(newSequence); err != nil { panic(err) } + ak.SetAccount(ctx, acc) return nil } -// Returns and increments the global account number counter +// GetNextAccountNumber Returns and increments the global account number counter func (ak AccountKeeper) GetNextAccountNumber(ctx sdk.Context) uint64 { var accNumber uint64 store := ctx.KVStore(ak.key) @@ -195,14 +197,6 @@ func (ak AccountKeeper) GetParams(ctx sdk.Context) (params Params) { //----------------------------------------------------------------------------- // Misc. -func (ak AccountKeeper) encodeAccount(acc Account) []byte { - bz, err := ak.cdc.MarshalBinaryBare(acc) - if err != nil { - panic(err) - } - return bz -} - func (ak AccountKeeper) decodeAccount(bz []byte) (acc Account) { err := ak.cdc.UnmarshalBinaryBare(bz, &acc) if err != nil { diff --git a/x/auth/params.go b/x/auth/params.go index 11374bd8b6db..0e098d5852cc 100644 --- a/x/auth/params.go +++ b/x/auth/params.go @@ -5,7 +5,6 @@ import ( "fmt" "strings" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/params" ) @@ -41,7 +40,7 @@ type Params struct { SigVerifyCostSecp256k1 uint64 `json:"sig_verify_cost_secp256k1"` } -// ParamTable for staking module +// ParamKeyTable for auth module func ParamKeyTable() params.KeyTable { return params.NewKeyTable().RegisterParamSet(&Params{}) } @@ -80,35 +79,11 @@ func DefaultParams() Params { // String implements the stringer interface. func (p Params) String() string { var sb strings.Builder - sb.WriteString("Params: \n") sb.WriteString(fmt.Sprintf("MaxMemoCharacters: %d\n", p.MaxMemoCharacters)) sb.WriteString(fmt.Sprintf("TxSigLimit: %d\n", p.TxSigLimit)) sb.WriteString(fmt.Sprintf("TxSizeCostPerByte: %d\n", p.TxSizeCostPerByte)) sb.WriteString(fmt.Sprintf("SigVerifyCostED25519: %d\n", p.SigVerifyCostED25519)) sb.WriteString(fmt.Sprintf("SigVerifyCostSecp256k1: %d\n", p.SigVerifyCostSecp256k1)) - return sb.String() } - -// MustUnmarshalParams deserializes raw Params bytes into a Params structure. It -// will panic upon failure. -func MustUnmarshalParams(cdc *codec.Codec, value []byte) Params { - params, err := UnmarshalParams(cdc, value) - if err != nil { - panic(err) - } - - return params -} - -// UnmarshalParams deserializes raw Params bytes into a Params structure. It will -// return an error upon failure. -func UnmarshalParams(cdc *codec.Codec, value []byte) (params Params, err error) { - err = cdc.UnmarshalBinaryLengthPrefixed(value, ¶ms) - if err != nil { - return Params{}, err - } - - return -} diff --git a/x/auth/stdtx.go b/x/auth/stdtx.go index c3bc7b703e7f..4ca318635440 100644 --- a/x/auth/stdtx.go +++ b/x/auth/stdtx.go @@ -103,10 +103,10 @@ func (tx StdTx) GetSigners() []sdk.AccAddress { return signers } -//nolint +// GetMemo returns the memo func (tx StdTx) GetMemo() string { return tx.Memo } -// Signatures returns the signature of signers who signed the Msg. +// GetSignatures returns the signature of signers who signed the Msg. // GetSignatures returns the signature of signers who signed the Msg. // CONTRACT: Length returned is same as length of // pubkeys returned from MsgKeySigners, and the order @@ -126,6 +126,7 @@ type StdFee struct { Gas uint64 `json:"gas"` } +// NewStdFee returns a new instance of StdFee func NewStdFee(gas uint64, amount sdk.Coins) StdFee { return StdFee{ Amount: amount, @@ -133,7 +134,7 @@ func NewStdFee(gas uint64, amount sdk.Coins) StdFee { } } -// fee bytes for signing later +// Bytes for signing later func (fee StdFee) Bytes() []byte { // normalize. XXX // this is a sign of something ugly @@ -185,13 +186,13 @@ func StdSignBytes(chainID string, accnum uint64, sequence uint64, fee StdFee, ms return sdk.MustSortJSON(bz) } -// Standard Signature +// StdSignature represents a sig type StdSignature struct { crypto.PubKey `json:"pub_key"` // optional Signature []byte `json:"signature"` } -// logic for standard transaction decoding +// DefaultTxDecoder logic for standard transaction decoding func DefaultTxDecoder(cdc *codec.Codec) sdk.TxDecoder { return func(txBytes []byte) (sdk.Tx, sdk.Error) { var tx = StdTx{} @@ -204,14 +205,14 @@ func DefaultTxDecoder(cdc *codec.Codec) sdk.TxDecoder { // are registered by MakeTxCodec err := cdc.UnmarshalBinaryLengthPrefixed(txBytes, &tx) if err != nil { - return nil, sdk.ErrTxDecode("").TraceSDK(err.Error()) + return nil, sdk.ErrTxDecode("error decoding transaction").TraceSDK(err.Error()) } return tx, nil } } -// logic for standard transaction encoding +// DefaultTxEncoder logic for standard transaction encoding func DefaultTxEncoder(cdc *codec.Codec) sdk.TxEncoder { return func(tx sdk.Tx) ([]byte, error) { return cdc.MarshalBinaryLengthPrefixed(tx) diff --git a/x/bank/errors.go b/x/bank/errors.go index fd4211899521..e76debe30394 100644 --- a/x/bank/errors.go +++ b/x/bank/errors.go @@ -1,4 +1,3 @@ -//nolint package bank import ( @@ -9,56 +8,26 @@ import ( const ( DefaultCodespace sdk.CodespaceType = "bank" - CodeInvalidInput sdk.CodeType = 101 - CodeInvalidOutput sdk.CodeType = 102 - CodeSendDisabled sdk.CodeType = 103 + CodeSendDisabled sdk.CodeType = 101 + CodeInvalidInputsOutputs sdk.CodeType = 102 ) -// NOTE: Don't stringer this, we'll put better messages in later. -func codeToDefaultMsg(code sdk.CodeType) string { - switch code { - case CodeInvalidInput: - return "invalid input coins" - case CodeInvalidOutput: - return "invalid output coins" - default: - return sdk.CodeToDefaultMsg(code) - } -} - -//---------------------------------------- -// Error constructors - -func ErrInvalidInput(codespace sdk.CodespaceType, msg string) sdk.Error { - return newError(codespace, CodeInvalidInput, msg) -} - +// ErrNoInputs is an error func ErrNoInputs(codespace sdk.CodespaceType) sdk.Error { - return newError(codespace, CodeInvalidInput, "") -} - -func ErrInvalidOutput(codespace sdk.CodespaceType, msg string) sdk.Error { - return newError(codespace, CodeInvalidOutput, msg) + return sdk.NewError(codespace, CodeInvalidInputsOutputs, "no inputs to send transacction") } +// ErrNoOutputs is an error func ErrNoOutputs(codespace sdk.CodespaceType) sdk.Error { - return newError(codespace, CodeInvalidOutput, "") -} - -func ErrSendDisabled(codespace sdk.CodespaceType) sdk.Error { - return newError(codespace, CodeSendDisabled, "") + return sdk.NewError(codespace, CodeInvalidInputsOutputs, "no outputs to send transaction") } -//---------------------------------------- - -func msgOrDefaultMsg(msg string, code sdk.CodeType) string { - if msg != "" { - return msg - } - return codeToDefaultMsg(code) +// ErrInputOutputMismatch is an error +func ErrInputOutputMismatch(codespace sdk.CodespaceType) sdk.Error { + return sdk.NewError(codespace, CodeInvalidInputsOutputs, "sum inputs != sum outputs") } -func newError(codespace sdk.CodespaceType, code sdk.CodeType, msg string) sdk.Error { - msg = msgOrDefaultMsg(msg, code) - return sdk.NewError(codespace, code, msg) +// ErrSendDisabled is an error +func ErrSendDisabled(codespace sdk.CodespaceType) sdk.Error { + return sdk.NewError(codespace, CodeSendDisabled, "send transactions are currently disabled") } diff --git a/x/bank/genesis.go b/x/bank/genesis.go index b85ba21937c3..1bdf4e7ff92a 100644 --- a/x/bank/genesis.go +++ b/x/bank/genesis.go @@ -14,7 +14,7 @@ func NewGenesisState(sendEnabled bool) GenesisState { return GenesisState{SendEnabled: sendEnabled} } -// Return a default genesis state +// DefaultGenesisState returns a default genesis state func DefaultGenesisState() GenesisState { return NewGenesisState(true) } // InitGenesis sets distribution information for genesis. diff --git a/x/bank/keeper.go b/x/bank/keeper.go index b4ae07a60dc2..bc4fa787c9ce 100644 --- a/x/bank/keeper.go +++ b/x/bank/keeper.go @@ -9,9 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/params" ) -//----------------------------------------------------------------------------- -// Keeper - var _ Keeper = (*BaseKeeper)(nil) // Keeper defines a module interface that facilitates the transfer of coins @@ -28,8 +25,7 @@ type Keeper interface { UndelegateCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Tags, sdk.Error) } -// BaseKeeper manages transfers between accounts. It implements the Keeper -// interface. +// BaseKeeper manages transfers between accounts. It implements the Keeper interface. type BaseKeeper struct { BaseSendKeeper @@ -93,9 +89,6 @@ func (keeper BaseKeeper) UndelegateCoins(ctx sdk.Context, addr sdk.AccAddress, a return undelegateCoins(ctx, keeper.ak, addr, amt) } -//----------------------------------------------------------------------------- -// Send Keeper - // SendKeeper defines a module interface that facilitates the transfer of coins // between accounts without the possibility of creating coins. type SendKeeper interface { @@ -109,7 +102,7 @@ type SendKeeper interface { var _ SendKeeper = (*BaseSendKeeper)(nil) -// SendKeeper only allows transfers between accounts without the possibility of +// BaseSendKeeper only allows transfers between accounts without the possibility of // creating coins. It implements the SendKeeper interface. type BaseSendKeeper struct { BaseViewKeeper @@ -144,14 +137,11 @@ func (keeper BaseSendKeeper) GetSendEnabled(ctx sdk.Context) bool { return enabled } -// nolint: errcheck +// SetSendEnabled sets the send enabled func (keeper BaseSendKeeper) SetSendEnabled(ctx sdk.Context, enabled bool) { keeper.paramSpace.Set(ctx, ParamStoreKeySendEnabled, &enabled) } -//----------------------------------------------------------------------------- -// View Keeper - var _ ViewKeeper = (*BaseViewKeeper)(nil) // ViewKeeper defines a module interface that facilitates read only access to @@ -189,9 +179,6 @@ func (keeper BaseViewKeeper) Codespace() sdk.CodespaceType { return keeper.codespace } -//----------------------------------------------------------------------------- -// Auxiliary - func getCoins(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress) sdk.Coins { acc := am.GetAccount(ctx, addr) if acc == nil { diff --git a/x/bank/msgs.go b/x/bank/msgs.go index 83bdc6633eea..8b3ee2cb4471 100644 --- a/x/bank/msgs.go +++ b/x/bank/msgs.go @@ -4,7 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// name to identify transaction routes +// RouterKey is they name of the bank module const RouterKey = "bank" // MsgSend - high level transaction of the coin module @@ -21,12 +21,13 @@ func NewMsgSend(fromAddr, toAddr sdk.AccAddress, amount sdk.Coins) MsgSend { return MsgSend{FromAddress: fromAddr, ToAddress: toAddr, Amount: amount} } -// Implements Msg. -// nolint +// Route Implements Msg. func (msg MsgSend) Route() string { return RouterKey } -func (msg MsgSend) Type() string { return "send" } -// Implements Msg. +// Type Implements Msg. +func (msg MsgSend) Type() string { return "send" } + +// ValidateBasic Implements Msg. func (msg MsgSend) ValidateBasic() sdk.Error { if msg.FromAddress.Empty() { return sdk.ErrInvalidAddress("missing sender address") @@ -40,12 +41,12 @@ func (msg MsgSend) ValidateBasic() sdk.Error { return nil } -// Implements Msg. +// GetSignBytes Implements Msg. func (msg MsgSend) GetSignBytes() []byte { return sdk.MustSortJSON(msgCdc.MustMarshalJSON(msg)) } -// Implements Msg. +// GetSigners Implements Msg. func (msg MsgSend) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.FromAddress} } @@ -63,12 +64,13 @@ func NewMsgMultiSend(in []Input, out []Output) MsgMultiSend { return MsgMultiSend{Inputs: in, Outputs: out} } -// Implements Msg. -// nolint +// Route Implements Msg func (msg MsgMultiSend) Route() string { return RouterKey } -func (msg MsgMultiSend) Type() string { return "multisend" } -// Implements Msg. +// Type Implements Msg +func (msg MsgMultiSend) Type() string { return "multisend" } + +// ValidateBasic Implements Msg. func (msg MsgMultiSend) ValidateBasic() sdk.Error { // this just makes sure all the inputs and outputs are properly formatted, // not that they actually have the money inside @@ -82,12 +84,12 @@ func (msg MsgMultiSend) ValidateBasic() sdk.Error { return ValidateInputsOutputs(msg.Inputs, msg.Outputs) } -// Implements Msg. +// GetSignBytes Implements Msg. func (msg MsgMultiSend) GetSignBytes() []byte { return sdk.MustSortJSON(msgCdc.MustMarshalJSON(msg)) } -// Implements Msg. +// GetSigners Implements Msg. func (msg MsgMultiSend) GetSigners() []sdk.AccAddress { addrs := make([]sdk.AccAddress, len(msg.Inputs)) for i, in := range msg.Inputs { @@ -96,10 +98,7 @@ func (msg MsgMultiSend) GetSigners() []sdk.AccAddress { return addrs } -//---------------------------------------- -// Input - -// Transaction Input +// Input models transaction input type Input struct { Address sdk.AccAddress `json:"address"` Coins sdk.Coins `json:"coins"` @@ -127,10 +126,7 @@ func NewInput(addr sdk.AccAddress, coins sdk.Coins) Input { } } -//---------------------------------------- -// Output - -// Transaction Output +// Output models transaction outputs type Output struct { Address sdk.AccAddress `json:"address"` Coins sdk.Coins `json:"coins"` @@ -158,9 +154,6 @@ func NewOutput(addr sdk.AccAddress, coins sdk.Coins) Output { } } -// ---------------------------------------------------------------------------- -// Auxiliary - // ValidateInputsOutputs validates that each respective input and output is // valid and that the sum of inputs is equal to the sum of outputs. func ValidateInputsOutputs(inputs []Input, outputs []Output) sdk.Error { @@ -182,7 +175,7 @@ func ValidateInputsOutputs(inputs []Input, outputs []Output) sdk.Error { // make sure inputs and outputs match if !totalIn.IsEqual(totalOut) { - return sdk.ErrInvalidCoins(totalIn.String()).TraceSDK("inputs and outputs don't match") + return ErrInputOutputMismatch(DefaultCodespace) } return nil diff --git a/x/bank/params.go b/x/bank/params.go index fcd2c0beaad6..b381e4e847e5 100644 --- a/x/bank/params.go +++ b/x/bank/params.go @@ -5,16 +5,16 @@ import ( ) const ( - // default paramspace for params keeper + // DefaultParamspace for params keeper DefaultParamspace = "bank" - // default send enabled + // DefaultSendEnabled enabled DefaultSendEnabled = true ) // ParamStoreKeySendEnabled is store's key for SendEnabled var ParamStoreKeySendEnabled = []byte("sendenabled") -// type declaration for parameters +// ParamKeyTable type declaration for parameters func ParamKeyTable() params.KeyTable { return params.NewKeyTable( ParamStoreKeySendEnabled, false,