diff --git a/client/context/helpers.go b/client/context/helpers.go index 509ec09dc..ded70cb5c 100644 --- a/client/context/helpers.go +++ b/client/context/helpers.go @@ -126,7 +126,14 @@ func (ctx CoreContext) SignAndBuild(name, passphrase string, msg sdk.Msg, cdc *w } // sign and build the transaction from the msg -func (ctx CoreContext) SignBuildBroadcast(name string, msg sdk.Msg, cdc *wire.Codec) (*ctypes.ResultBroadcastTxCommit, error) { +func (ctx CoreContext) EnsureSignBuildBroadcast(name string, msg sdk.Msg, cdc *wire.Codec) (res *ctypes.ResultBroadcastTxCommit, err error) { + + // default to next sequence number if none provided + ctx, err = EnsureSequence(ctx) + if err != nil { + return nil, err + } + passphrase, err := ctx.GetPassphraseFromStdin(name) if err != nil { return nil, err diff --git a/client/keys/add.go b/client/keys/add.go index d68983028..da368a3a6 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -135,14 +135,17 @@ func printCreate(info keys.Info, seed string) { } } +///////////////////////////// // REST +// new key request REST body type NewKeyBody struct { Name string `json:"name"` Password string `json:"password"` Seed string `json:"seed"` } +// add new key REST handler func AddNewKeyRequestHandler(w http.ResponseWriter, r *http.Request) { var kb keys.Keybase var m NewKeyBody @@ -208,6 +211,7 @@ func getSeed(algo keys.CryptoAlgo) string { return seed } +// Seed REST request handler func SeedRequestHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) algoType := vars["type"] diff --git a/client/keys/delete.go b/client/keys/delete.go index b0327771b..cd2016bd2 100644 --- a/client/keys/delete.go +++ b/client/keys/delete.go @@ -48,12 +48,15 @@ func runDeleteCmd(cmd *cobra.Command, args []string) error { return nil } +//////////////////////// // REST +// delete key request REST body type DeleteKeyBody struct { Password string `json:"password"` } +// delete key REST handler func DeleteKeyRequestHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) name := vars["name"] diff --git a/client/keys/list.go b/client/keys/list.go index 97ccf8a90..26e06d9da 100644 --- a/client/keys/list.go +++ b/client/keys/list.go @@ -31,8 +31,10 @@ func runListCmd(cmd *cobra.Command, args []string) error { return err } -//REST +///////////////////////// +// REST +// query key list REST handler func QueryKeysRequestHandler(w http.ResponseWriter, r *http.Request) { kb, err := GetKeyBase() if err != nil { diff --git a/client/keys/root.go b/client/keys/root.go index 48b50d5e9..c8f6aea69 100644 --- a/client/keys/root.go +++ b/client/keys/root.go @@ -29,6 +29,7 @@ func Commands() *cobra.Command { return cmd } +// resgister REST routes func RegisterRoutes(r *mux.Router) { r.HandleFunc("/keys", QueryKeysRequestHandler).Methods("GET") r.HandleFunc("/keys", AddNewKeyRequestHandler).Methods("POST") diff --git a/client/keys/show.go b/client/keys/show.go index bb60b5bc0..76966cd19 100644 --- a/client/keys/show.go +++ b/client/keys/show.go @@ -42,8 +42,10 @@ func runShowCmd(cmd *cobra.Command, args []string) error { return err } +/////////////////////////// // REST +// get key REST handler func GetKeyRequestHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) name := vars["name"] diff --git a/client/keys/update.go b/client/keys/update.go index d95be78bf..c0edc5fe6 100644 --- a/client/keys/update.go +++ b/client/keys/update.go @@ -53,13 +53,16 @@ func runUpdateCmd(cmd *cobra.Command, args []string) error { return nil } +/////////////////////// // REST +// update key request REST body type UpdateKeyBody struct { NewPassword string `json:"new_password"` OldPassword string `json:"old_password"` } +// update key REST handler func UpdateKeyRequestHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) name := vars["name"] diff --git a/client/lcd/root.go b/client/lcd/root.go index 9464081e0..81eca333e 100644 --- a/client/lcd/root.go +++ b/client/lcd/root.go @@ -66,7 +66,7 @@ func startRESTServerFn(cdc *wire.Codec) func(cmd *cobra.Command, args []string) func createHandler(cdc *wire.Codec) http.Handler { r := mux.NewRouter() - r.HandleFunc("/version", version.VersionRequestHandler).Methods("GET") + r.HandleFunc("/version", version.RequestHandler).Methods("GET") kb, err := keys.GetKeyBase() //XXX if err != nil { diff --git a/client/rpc/block.go b/client/rpc/block.go index 8df26edda..200dc668e 100644 --- a/client/rpc/block.go +++ b/client/rpc/block.go @@ -55,6 +55,7 @@ func getBlock(height *int64) ([]byte, error) { return output, nil } +// get the current blockchain height func GetChainHeight() (int64, error) { node, err := context.NewCoreContextFromViper().GetNode() if err != nil { @@ -94,6 +95,7 @@ func printBlock(cmd *cobra.Command, args []string) error { // REST +// REST handler to get a block func BlockRequestHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) height, err := strconv.ParseInt(vars["height"], 10, 64) @@ -117,6 +119,7 @@ func BlockRequestHandler(w http.ResponseWriter, r *http.Request) { w.Write(output) } +// REST handler to get the latest block func LatestBlockRequestHandler(w http.ResponseWriter, r *http.Request) { height, err := GetChainHeight() if err != nil { diff --git a/client/rpc/root.go b/client/rpc/root.go index 8b04c044f..43e9097f0 100644 --- a/client/rpc/root.go +++ b/client/rpc/root.go @@ -44,11 +44,12 @@ func initClientCommand() *cobra.Command { return cmd } +// Register REST endpoints func RegisterRoutes(r *mux.Router) { r.HandleFunc("/node_info", NodeInfoRequestHandler).Methods("GET") r.HandleFunc("/syncing", NodeSyncingRequestHandler).Methods("GET") r.HandleFunc("/blocks/latest", LatestBlockRequestHandler).Methods("GET") r.HandleFunc("/blocks/{height}", BlockRequestHandler).Methods("GET") - r.HandleFunc("/validatorsets/latest", LatestValidatorsetRequestHandler).Methods("GET") - r.HandleFunc("/validatorsets/{height}", ValidatorsetRequestHandler).Methods("GET") + r.HandleFunc("/validatorsets/latest", LatestValidatorSetRequestHandler).Methods("GET") + r.HandleFunc("/validatorsets/{height}", ValidatorSetRequestHandler).Methods("GET") } diff --git a/client/rpc/status.go b/client/rpc/status.go index 83fc01c56..3b143d9c5 100644 --- a/client/rpc/status.go +++ b/client/rpc/status.go @@ -51,6 +51,7 @@ func printNodeStatus(cmd *cobra.Command, args []string) error { // REST +// REST handler for node info func NodeInfoRequestHandler(w http.ResponseWriter, r *http.Request) { status, err := getNodeStatus() if err != nil { @@ -69,6 +70,7 @@ func NodeInfoRequestHandler(w http.ResponseWriter, r *http.Request) { w.Write(output) } +// REST handler for node syncing func NodeSyncingRequestHandler(w http.ResponseWriter, r *http.Request) { status, err := getNodeStatus() if err != nil { diff --git a/client/rpc/validators.go b/client/rpc/validators.go index cdaf3be93..6937e4a89 100644 --- a/client/rpc/validators.go +++ b/client/rpc/validators.go @@ -12,6 +12,8 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" ) +// TODO these next two functions feel kinda hacky based on their placement + func validatorCommand() *cobra.Command { cmd := &cobra.Command{ Use: "validatorset ", @@ -24,7 +26,7 @@ func validatorCommand() *cobra.Command { return cmd } -func GetValidators(height *int64) ([]byte, error) { +func getValidators(height *int64) ([]byte, error) { // get the node node, err := context.NewCoreContextFromViper().GetNode() if err != nil { @@ -59,7 +61,7 @@ func printValidators(cmd *cobra.Command, args []string) error { } } - output, err := GetValidators(height) + output, err := getValidators(height) if err != nil { return err } @@ -70,7 +72,8 @@ func printValidators(cmd *cobra.Command, args []string) error { // REST -func ValidatorsetRequestHandler(w http.ResponseWriter, r *http.Request) { +// Validator Set at a height REST handler +func ValidatorSetRequestHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) height, err := strconv.ParseInt(vars["height"], 10, 64) if err != nil { @@ -84,7 +87,7 @@ func ValidatorsetRequestHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ERROR: Requested block height is bigger then the chain length.")) return } - output, err := GetValidators(&height) + output, err := getValidators(&height) if err != nil { w.WriteHeader(500) w.Write([]byte(err.Error())) @@ -93,14 +96,15 @@ func ValidatorsetRequestHandler(w http.ResponseWriter, r *http.Request) { w.Write(output) } -func LatestValidatorsetRequestHandler(w http.ResponseWriter, r *http.Request) { +// Latest Validator Set REST handler +func LatestValidatorSetRequestHandler(w http.ResponseWriter, r *http.Request) { height, err := GetChainHeight() if err != nil { w.WriteHeader(500) w.Write([]byte(err.Error())) return } - output, err := GetValidators(&height) + output, err := getValidators(&height) if err != nil { w.WriteHeader(500) w.Write([]byte(err.Error())) diff --git a/client/tx/broadcast.go b/client/tx/broadcast.go index 998e2b0f1..9e9eaae70 100644 --- a/client/tx/broadcast.go +++ b/client/tx/broadcast.go @@ -7,10 +7,12 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" ) +// Tx Broadcast Body type BroadcastTxBody struct { TxBytes string `json="tx"` } +// BroadcastTx REST Handler func BroadcastTxRequestHandler(w http.ResponseWriter, r *http.Request) { var m BroadcastTxBody diff --git a/client/tx/query.go b/client/tx/query.go index 63ab2ff04..cc252bacc 100644 --- a/client/tx/query.go +++ b/client/tx/query.go @@ -21,19 +21,37 @@ import ( ) // Get the default command for a tx query -func QueryTxCmd(cmdr commander) *cobra.Command { +func QueryTxCmd(cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "tx [hash]", Short: "Matches this txhash over all committed blocks", - RunE: cmdr.queryAndPrintTx, + RunE: func(cmd *cobra.Command, args []string) error { + if len(args) != 1 || len(args[0]) == 0 { + return errors.New("You must provide a tx hash") + } + + // find the key to look up the account + hashHexStr := args[0] + trustNode := viper.GetBool(client.FlagTrustNode) + + output, err := queryTx(cdc, hashHexStr, trustNode) + if err != nil { + return err + } + fmt.Println(string(output)) + + return nil + }, } + cmd.Flags().StringP(client.FlagNode, "n", "tcp://localhost:46657", "Node to connect to") + // TODO: change this to false when we can cmd.Flags().Bool(client.FlagTrustNode, true, "Don't verify proofs for responses") return cmd } -func (c commander) queryTx(hashHexStr string, trustNode bool) ([]byte, error) { +func queryTx(cdc *wire.Codec, hashHexStr string, trustNode bool) ([]byte, error) { hash, err := hex.DecodeString(hashHexStr) if err != nil { return nil, err @@ -49,7 +67,7 @@ func (c commander) queryTx(hashHexStr string, trustNode bool) ([]byte, error) { if err != nil { return nil, err } - info, err := formatTxResult(c.cdc, res) + info, err := formatTxResult(cdc, res) if err != nil { return nil, err } @@ -88,31 +106,10 @@ func parseTx(cdc *wire.Codec, txBytes []byte) (sdk.Tx, error) { return tx, nil } -// CMD - -// command to query for a transaction -func (c commander) queryAndPrintTx(cmd *cobra.Command, args []string) error { - if len(args) != 1 || len(args[0]) == 0 { - return errors.New("You must provide a tx hash") - } - - // find the key to look up the account - hashHexStr := args[0] - trustNode := viper.GetBool(client.FlagTrustNode) - - output, err := c.queryTx(hashHexStr, trustNode) - if err != nil { - return err - } - fmt.Println(string(output)) - - return nil -} - // REST +// transaction query REST handler func QueryTxRequestHandler(cdc *wire.Codec) func(http.ResponseWriter, *http.Request) { - c := commander{cdc} return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) hashHexStr := vars["hash"] @@ -122,7 +119,7 @@ func QueryTxRequestHandler(cdc *wire.Codec) func(http.ResponseWriter, *http.Requ trustNode = true } - output, err := c.queryTx(hashHexStr, trustNode) + output, err := queryTx(cdc, hashHexStr, trustNode) if err != nil { w.WriteHeader(500) w.Write([]byte(err.Error())) diff --git a/client/tx/root.go b/client/tx/root.go index f7d2cf945..2a87113b3 100644 --- a/client/tx/root.go +++ b/client/tx/root.go @@ -7,23 +7,18 @@ import ( "github.com/cosmos/cosmos-sdk/wire" ) -// type used to pass around the provided cdc -type commander struct { - cdc *wire.Codec -} - // AddCommands adds a number of tx-query related subcommands func AddCommands(cmd *cobra.Command, cdc *wire.Codec) { - cmdr := commander{cdc} cmd.AddCommand( - SearchTxCmd(cmdr), - QueryTxCmd(cmdr), + SearchTxCmd(cdc), + QueryTxCmd(cdc), ) } +// register REST routes func RegisterRoutes(r *mux.Router, cdc *wire.Codec) { - // r.HandleFunc("/txs", SearchTxRequestHandler(cdc)).Methods("GET") r.HandleFunc("/txs/{hash}", QueryTxRequestHandler(cdc)).Methods("GET") + // r.HandleFunc("/txs", SearchTxRequestHandler(cdc)).Methods("GET") // r.HandleFunc("/txs/sign", SignTxRequstHandler).Methods("POST") // r.HandleFunc("/txs/broadcast", BroadcastTxRequestHandler).Methods("POST") } diff --git a/client/tx/search.go b/client/tx/search.go index df3be5077..1687d3bbd 100644 --- a/client/tx/search.go +++ b/client/tx/search.go @@ -22,13 +22,24 @@ const ( ) // default client command to search through tagged transactions -func SearchTxCmd(cmdr commander) *cobra.Command { +func SearchTxCmd(cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "txs", Short: "Search for all transactions that match the given tags", - RunE: cmdr.searchAndPrintTx, + RunE: func(cmd *cobra.Command, args []string) error { + tags := viper.GetStringSlice(flagTags) + + output, err := searchTx(cdc, tags) + if err != nil { + return err + } + fmt.Println(string(output)) + return nil + }, } + cmd.Flags().StringP(client.FlagNode, "n", "tcp://localhost:46657", "Node to connect to") + // TODO: change this to false once proofs built in cmd.Flags().Bool(client.FlagTrustNode, true, "Don't verify proofs for responses") cmd.Flags().StringSlice(flagTags, nil, "Tags that must match (may provide multiple)") @@ -36,7 +47,7 @@ func SearchTxCmd(cmdr commander) *cobra.Command { return cmd } -func (c commander) searchTx(tags []string) ([]byte, error) { +func searchTx(cdc *wire.Codec, tags []string) ([]byte, error) { if len(tags) == 0 { return nil, errors.New("Must declare at least one tag to search") } @@ -55,12 +66,12 @@ func (c commander) searchTx(tags []string) ([]byte, error) { return nil, err } - info, err := formatTxResults(c.cdc, res) + info, err := formatTxResults(cdc, res) if err != nil { return nil, err } - output, err := c.cdc.MarshalJSON(info) + output, err := cdc.MarshalJSON(info) if err != nil { return nil, err } @@ -79,24 +90,11 @@ func formatTxResults(cdc *wire.Codec, res []*ctypes.ResultTx) ([]txInfo, error) return out, nil } -// CMD - -func (c commander) searchAndPrintTx(cmd *cobra.Command, args []string) error { - tags := viper.GetStringSlice(flagTags) - - output, err := c.searchTx(tags) - if err != nil { - return err - } - - fmt.Println(string(output)) - return nil -} - +///////////////////////////////////////// // REST +// Search Tx REST Handler func SearchTxRequestHandler(cdc *wire.Codec) func(http.ResponseWriter, *http.Request) { - c := commander{cdc} return func(w http.ResponseWriter, r *http.Request) { tag := r.FormValue("tag") if tag == "" { @@ -106,7 +104,7 @@ func SearchTxRequestHandler(cdc *wire.Codec) func(http.ResponseWriter, *http.Req } tags := []string{tag} - output, err := c.searchTx(tags) + output, err := searchTx(cdc, tags) if err != nil { w.WriteHeader(500) w.Write([]byte(err.Error())) diff --git a/client/tx/sign.go b/client/tx/sign.go index 3a3fff4a0..2d885b049 100644 --- a/client/tx/sign.go +++ b/client/tx/sign.go @@ -8,12 +8,15 @@ import ( keys "github.com/tendermint/go-crypto/keys" ) +// REST request body +// TODO does this need to be exposed? type SignTxBody struct { Name string `json="name"` Password string `json="password"` TxBytes string `json="tx"` } +// sign transaction REST Handler func SignTxRequstHandler(w http.ResponseWriter, r *http.Request) { var kb keys.Keybase var m SignTxBody diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 57a5d672c..e780c08bf 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -27,15 +27,15 @@ type GaiaApp struct { cdc *wire.Codec // keys to access the substores - capKeyMainStore *sdk.KVStoreKey - capKeyAccountStore *sdk.KVStoreKey - capKeyIBCStore *sdk.KVStoreKey - capKeyStakeStore *sdk.KVStoreKey + keyMain *sdk.KVStoreKey + keyAccount *sdk.KVStoreKey + keyIBC *sdk.KVStoreKey + keyStake *sdk.KVStoreKey // Manage getting and setting accounts accountMapper sdk.AccountMapper - coinKeeper bank.CoinKeeper - ibcMapper ibc.IBCMapper + coinKeeper bank.Keeper + ibcMapper ibc.Mapper stakeKeeper stake.Keeper // Handle fees @@ -45,25 +45,25 @@ type GaiaApp struct { func NewGaiaApp(logger log.Logger, db dbm.DB) *GaiaApp { // create your application object var app = &GaiaApp{ - BaseApp: bam.NewBaseApp(appName, logger, db), - cdc: MakeCodec(), - capKeyMainStore: sdk.NewKVStoreKey("main"), - capKeyAccountStore: sdk.NewKVStoreKey("acc"), - capKeyIBCStore: sdk.NewKVStoreKey("ibc"), - capKeyStakeStore: sdk.NewKVStoreKey("stake"), + BaseApp: bam.NewBaseApp(appName, logger, db), + cdc: MakeCodec(), + keyMain: sdk.NewKVStoreKey("main"), + keyAccount: sdk.NewKVStoreKey("acc"), + keyIBC: sdk.NewKVStoreKey("ibc"), + keyStake: sdk.NewKVStoreKey("stake"), } // define the accountMapper app.accountMapper = auth.NewAccountMapper( app.cdc, - app.capKeyMainStore, // target store + app.keyMain, // target store &auth.BaseAccount{}, // prototype ).Seal() // add handlers - app.coinKeeper = bank.NewCoinKeeper(app.accountMapper) - app.ibcMapper = ibc.NewIBCMapper(app.cdc, app.capKeyIBCStore, app.RegisterCodespace(ibc.DefaultCodespace)) - app.stakeKeeper = stake.NewKeeper(app.cdc, app.capKeyStakeStore, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) + app.coinKeeper = bank.NewKeeper(app.accountMapper) + app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace)) + app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.coinKeeper, app.RegisterCodespace(stake.DefaultCodespace)) app.Router(). AddRoute("bank", bank.NewHandler(app.coinKeeper)). @@ -77,9 +77,9 @@ func NewGaiaApp(logger log.Logger, db dbm.DB) *GaiaApp { app.SetTxDecoder(app.txDecoder) app.SetInitChainer(app.initChainer) app.SetEndBlocker(stake.NewEndBlocker(app.stakeKeeper)) - app.MountStoresIAVL(app.capKeyMainStore, app.capKeyAccountStore, app.capKeyIBCStore, app.capKeyStakeStore) + app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC, app.keyStake) app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeHandler)) - err := app.LoadLatestVersion(app.capKeyMainStore) + err := app.LoadLatestVersion(app.keyMain) if err != nil { cmn.Exit(err.Error()) } diff --git a/cmd/gaia/app/app_test.go b/cmd/gaia/app/app_test.go index b3350b503..721215999 100644 --- a/cmd/gaia/app/app_test.go +++ b/cmd/gaia/app/app_test.go @@ -42,12 +42,12 @@ var ( 0, } - sendMsg1 = bank.SendMsg{ + sendMsg1 = bank.MsgSend{ Inputs: []bank.Input{bank.NewInput(addr1, coins)}, Outputs: []bank.Output{bank.NewOutput(addr2, coins)}, } - sendMsg2 = bank.SendMsg{ + sendMsg2 = bank.MsgSend{ Inputs: []bank.Input{bank.NewInput(addr1, coins)}, Outputs: []bank.Output{ bank.NewOutput(addr2, halfCoins), @@ -55,7 +55,7 @@ var ( }, } - sendMsg3 = bank.SendMsg{ + sendMsg3 = bank.MsgSend{ Inputs: []bank.Input{ bank.NewInput(addr1, coins), bank.NewInput(addr4, coins), @@ -66,7 +66,7 @@ var ( }, } - sendMsg4 = bank.SendMsg{ + sendMsg4 = bank.MsgSend{ Inputs: []bank.Input{ bank.NewInput(addr2, coins), }, @@ -75,7 +75,7 @@ var ( }, } - sendMsg5 = bank.SendMsg{ + sendMsg5 = bank.MsgSend{ Inputs: []bank.Input{ bank.NewInput(addr1, manyCoins), }, @@ -191,7 +191,7 @@ func TestGenesis(t *testing.T) { assert.Equal(t, baseAcc, res1) } -func TestSendMsgWithAccounts(t *testing.T) { +func TestMsgSendWithAccounts(t *testing.T) { gapp := newGaiaApp() // Construct some genesis bytes to reflect GaiaAccount @@ -233,7 +233,7 @@ func TestSendMsgWithAccounts(t *testing.T) { SignCheckDeliver(t, gapp, sendMsg1, []int64{1}, true, priv1) } -func TestSendMsgMultipleOut(t *testing.T) { +func TestMsgSendMultipleOut(t *testing.T) { gapp := newGaiaApp() genCoins, err := sdk.ParseCoins("42foocoin") @@ -293,7 +293,7 @@ func TestSengMsgMultipleInOut(t *testing.T) { CheckBalance(t, gapp, addr3, "10foocoin") } -func TestSendMsgDependent(t *testing.T) { +func TestMsgSendDependent(t *testing.T) { gapp := newGaiaApp() genCoins, err := sdk.ParseCoins("42foocoin") diff --git a/cmd/gaia/cmd/gaiacli/main.go b/cmd/gaia/cmd/gaiacli/main.go index 1e5528308..45818b36b 100644 --- a/cmd/gaia/cmd/gaiacli/main.go +++ b/cmd/gaia/cmd/gaiacli/main.go @@ -12,7 +12,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/lcd" "github.com/cosmos/cosmos-sdk/client/rpc" "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/version" authcmd "github.com/cosmos/cosmos-sdk/x/auth/commands" bankcmd "github.com/cosmos/cosmos-sdk/x/bank/commands" diff --git a/docs/guide.md b/docs/guide.md index fe28a09cb..9f8329835 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -69,12 +69,12 @@ but this is mostly for convenience and not type-safe. For instance, the `Basecoin` message types are defined in `x/bank/tx.go`: ```go -type SendMsg struct { +type MsgSend struct { Inputs []Input `json:"inputs"` Outputs []Output `json:"outputs"` } -type IssueMsg struct { +type MsgIssue struct { Banker sdk.Address `json:"banker"` Outputs []Output `json:"outputs"` } @@ -83,7 +83,7 @@ type IssueMsg struct { Each specifies the addresses that must sign the message: ```go -func (msg SendMsg) GetSigners() []sdk.Address { +func (msg MsgSend) GetSigners() []sdk.Address { addrs := make([]sdk.Address, len(msg.Inputs)) for i, in := range msg.Inputs { addrs[i] = in.Address @@ -91,7 +91,7 @@ func (msg SendMsg) GetSigners() []sdk.Address { return addrs } -func (msg IssueMsg) GetSigners() []sdk.Address { +func (msg MsgIssue) GetSigners() []sdk.Address { return []sdk.Address{msg.Banker} } ``` @@ -174,13 +174,13 @@ property that it can unmarshal into interface types, but it requires the relevant types to be registered ahead of type. Registration happens on a `Codec` object, so as not to taint the global name space. -For instance, in `Basecoin`, we wish to register the `SendMsg` and `IssueMsg` +For instance, in `Basecoin`, we wish to register the `MsgSend` and `MsgIssue` types: ```go cdc.RegisterInterface((*sdk.Msg)(nil), nil) -cdc.RegisterConcrete(bank.SendMsg{}, "cosmos-sdk/SendMsg", nil) -cdc.RegisterConcrete(bank.IssueMsg{}, "cosmos-sdk/IssueMsg", nil) +cdc.RegisterConcrete(bank.MsgSend{}, "cosmos-sdk/MsgSend", nil) +cdc.RegisterConcrete(bank.MsgIssue{}, "cosmos-sdk/MsgIssue", nil) ``` Note how each concrete type is given a name - these name determine the type's @@ -319,8 +319,8 @@ func NewHandler(am sdk.AccountMapper) sdk.Handler { The quintessential SDK application is Basecoin - a simple multi-asset cryptocurrency. Basecoin consists of a set of accounts stored in a Merkle tree, where each account may have -many coins. There are two message types: SendMsg and IssueMsg. -SendMsg allows coins to be sent around, while IssueMsg allows a +many coins. There are two message types: MsgSend and MsgIssue. +MsgSend allows coins to be sent around, while MsgIssue allows a set of predefined users to issue new coins. ## Conclusion diff --git a/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index bb3ef05ac..e9f5b6e5a 100644 --- a/examples/basecoin/app/app.go +++ b/examples/basecoin/app/app.go @@ -64,8 +64,8 @@ func NewBasecoinApp(logger log.Logger, db dbm.DB) *BasecoinApp { ).Seal() // Add handlers. - coinKeeper := bank.NewCoinKeeper(app.accountMapper) - ibcMapper := ibc.NewIBCMapper(app.cdc, app.capKeyIBCStore, app.RegisterCodespace(ibc.DefaultCodespace)) + coinKeeper := bank.NewKeeper(app.accountMapper) + ibcMapper := ibc.NewMapper(app.cdc, app.capKeyIBCStore, app.RegisterCodespace(ibc.DefaultCodespace)) stakeKeeper := simplestake.NewKeeper(app.capKeyStakingStore, coinKeeper, app.RegisterCodespace(simplestake.DefaultCodespace)) app.Router(). AddRoute("bank", bank.NewHandler(coinKeeper)). @@ -94,12 +94,12 @@ func MakeCodec() *wire.Codec { // Register Msgs cdc.RegisterInterface((*sdk.Msg)(nil), nil) - cdc.RegisterConcrete(bank.SendMsg{}, "basecoin/Send", nil) - cdc.RegisterConcrete(bank.IssueMsg{}, "basecoin/Issue", nil) + cdc.RegisterConcrete(bank.MsgSend{}, "basecoin/Send", nil) + cdc.RegisterConcrete(bank.MsgIssue{}, "basecoin/Issue", nil) cdc.RegisterConcrete(ibc.IBCTransferMsg{}, "basecoin/IBCTransferMsg", nil) cdc.RegisterConcrete(ibc.IBCReceiveMsg{}, "basecoin/IBCReceiveMsg", nil) - cdc.RegisterConcrete(simplestake.BondMsg{}, "basecoin/BondMsg", nil) - cdc.RegisterConcrete(simplestake.UnbondMsg{}, "basecoin/UnbondMsg", nil) + cdc.RegisterConcrete(simplestake.MsgBond{}, "basecoin/BondMsg", nil) + cdc.RegisterConcrete(simplestake.MsgUnbond{}, "basecoin/UnbondMsg", nil) // Register AppAccount cdc.RegisterInterface((*sdk.Account)(nil), nil) diff --git a/examples/basecoin/app/app_test.go b/examples/basecoin/app/app_test.go index bc1735dde..b502aae46 100644 --- a/examples/basecoin/app/app_test.go +++ b/examples/basecoin/app/app_test.go @@ -42,12 +42,12 @@ var ( 0, } - sendMsg1 = bank.SendMsg{ + sendMsg1 = bank.MsgSend{ Inputs: []bank.Input{bank.NewInput(addr1, coins)}, Outputs: []bank.Output{bank.NewOutput(addr2, coins)}, } - sendMsg2 = bank.SendMsg{ + sendMsg2 = bank.MsgSend{ Inputs: []bank.Input{bank.NewInput(addr1, coins)}, Outputs: []bank.Output{ bank.NewOutput(addr2, halfCoins), @@ -55,7 +55,7 @@ var ( }, } - sendMsg3 = bank.SendMsg{ + sendMsg3 = bank.MsgSend{ Inputs: []bank.Input{ bank.NewInput(addr1, coins), bank.NewInput(addr4, coins), @@ -66,7 +66,7 @@ var ( }, } - sendMsg4 = bank.SendMsg{ + sendMsg4 = bank.MsgSend{ Inputs: []bank.Input{ bank.NewInput(addr2, coins), }, @@ -75,7 +75,7 @@ var ( }, } - sendMsg5 = bank.SendMsg{ + sendMsg5 = bank.MsgSend{ Inputs: []bank.Input{ bank.NewInput(addr1, manyCoins), }, @@ -208,7 +208,7 @@ func TestGenesis(t *testing.T) { assert.Equal(t, acc, res1) } -func TestSendMsgWithAccounts(t *testing.T) { +func TestMsgSendWithAccounts(t *testing.T) { bapp := newBasecoinApp() // Construct some genesis bytes to reflect basecoin/types/AppAccount @@ -249,7 +249,7 @@ func TestSendMsgWithAccounts(t *testing.T) { SignCheckDeliver(t, bapp, sendMsg1, []int64{1}, true, priv1) } -func TestSendMsgMultipleOut(t *testing.T) { +func TestMsgSendMultipleOut(t *testing.T) { bapp := newBasecoinApp() genCoins, err := sdk.ParseCoins("42foocoin") @@ -311,7 +311,7 @@ func TestSengMsgMultipleInOut(t *testing.T) { CheckBalance(t, bapp, addr3, "10foocoin") } -func TestSendMsgDependent(t *testing.T) { +func TestMsgSendDependent(t *testing.T) { bapp := newBasecoinApp() genCoins, err := sdk.ParseCoins("42foocoin") @@ -339,7 +339,7 @@ func TestSendMsgDependent(t *testing.T) { CheckBalance(t, bapp, addr1, "42foocoin") } -func TestQuizMsg(t *testing.T) { +func TestMsgQuiz(t *testing.T) { bapp := newBasecoinApp() // Construct genesis state diff --git a/examples/democoin/app/app.go b/examples/democoin/app/app.go index 4e5e4e22f..290a04d66 100644 --- a/examples/democoin/app/app.go +++ b/examples/democoin/app/app.go @@ -69,10 +69,10 @@ func NewDemocoinApp(logger log.Logger, db dbm.DB) *DemocoinApp { ).Seal() // Add handlers. - coinKeeper := bank.NewCoinKeeper(app.accountMapper) + coinKeeper := bank.NewKeeper(app.accountMapper) coolKeeper := cool.NewKeeper(app.capKeyMainStore, coinKeeper, app.RegisterCodespace(cool.DefaultCodespace)) - powKeeper := pow.NewKeeper(app.capKeyPowStore, pow.NewPowConfig("pow", int64(1)), coinKeeper, app.RegisterCodespace(pow.DefaultCodespace)) - ibcMapper := ibc.NewIBCMapper(app.cdc, app.capKeyIBCStore, app.RegisterCodespace(ibc.DefaultCodespace)) + powKeeper := pow.NewKeeper(app.capKeyPowStore, pow.NewConfig("pow", int64(1)), coinKeeper, app.RegisterCodespace(pow.DefaultCodespace)) + ibcMapper := ibc.NewMapper(app.cdc, app.capKeyIBCStore, app.RegisterCodespace(ibc.DefaultCodespace)) stakeKeeper := simplestake.NewKeeper(app.capKeyStakingStore, coinKeeper, app.RegisterCodespace(simplestake.DefaultCodespace)) app.Router(). AddRoute("bank", bank.NewHandler(coinKeeper)). @@ -104,15 +104,15 @@ func MakeCodec() *wire.Codec { // Register Msgs cdc.RegisterInterface((*sdk.Msg)(nil), nil) - cdc.RegisterConcrete(bank.SendMsg{}, "democoin/Send", nil) - cdc.RegisterConcrete(bank.IssueMsg{}, "democoin/Issue", nil) - cdc.RegisterConcrete(cool.QuizMsg{}, "democoin/Quiz", nil) - cdc.RegisterConcrete(cool.SetTrendMsg{}, "democoin/SetTrend", nil) - cdc.RegisterConcrete(pow.MineMsg{}, "democoin/Mine", nil) + cdc.RegisterConcrete(bank.MsgSend{}, "democoin/Send", nil) + cdc.RegisterConcrete(bank.MsgIssue{}, "democoin/Issue", nil) + cdc.RegisterConcrete(cool.MsgQuiz{}, "democoin/Quiz", nil) + cdc.RegisterConcrete(cool.MsgSetTrend{}, "democoin/SetTrend", nil) + cdc.RegisterConcrete(pow.MsgMine{}, "democoin/Mine", nil) cdc.RegisterConcrete(ibc.IBCTransferMsg{}, "democoin/IBCTransferMsg", nil) cdc.RegisterConcrete(ibc.IBCReceiveMsg{}, "democoin/IBCReceiveMsg", nil) - cdc.RegisterConcrete(simplestake.BondMsg{}, "democoin/BondMsg", nil) - cdc.RegisterConcrete(simplestake.UnbondMsg{}, "democoin/UnbondMsg", nil) + cdc.RegisterConcrete(simplestake.MsgBond{}, "democoin/BondMsg", nil) + cdc.RegisterConcrete(simplestake.MsgUnbond{}, "democoin/UnbondMsg", nil) // Register AppAccount cdc.RegisterInterface((*sdk.Account)(nil), nil) @@ -169,7 +169,7 @@ func (app *DemocoinApp) initChainerFn(coolKeeper cool.Keeper, powKeeper pow.Keep // return sdk.ErrGenesisParse("").TraceCause(err, "") } - err = powKeeper.InitGenesis(ctx, genesisState.PowGenesis) + err = powKeeper.InitGenesis(ctx, genesisState.POWGenesis) if err != nil { panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 // return sdk.ErrGenesisParse("").TraceCause(err, "") diff --git a/examples/democoin/app/app_test.go b/examples/democoin/app/app_test.go index f17e2a9b0..c67782d92 100644 --- a/examples/democoin/app/app_test.go +++ b/examples/democoin/app/app_test.go @@ -36,32 +36,32 @@ var ( 0, } - sendMsg = bank.SendMsg{ + sendMsg = bank.MsgSend{ Inputs: []bank.Input{bank.NewInput(addr1, coins)}, Outputs: []bank.Output{bank.NewOutput(addr2, coins)}, } - quizMsg1 = cool.QuizMsg{ + quizMsg1 = cool.MsgQuiz{ Sender: addr1, CoolAnswer: "icecold", } - quizMsg2 = cool.QuizMsg{ + quizMsg2 = cool.MsgQuiz{ Sender: addr1, CoolAnswer: "badvibesonly", } - setTrendMsg1 = cool.SetTrendMsg{ + setTrendMsg1 = cool.MsgSetTrend{ Sender: addr1, Cool: "icecold", } - setTrendMsg2 = cool.SetTrendMsg{ + setTrendMsg2 = cool.MsgSetTrend{ Sender: addr1, Cool: "badvibesonly", } - setTrendMsg3 = cool.SetTrendMsg{ + setTrendMsg3 = cool.MsgSetTrend{ Sender: addr1, Cool: "warmandkind", } @@ -157,7 +157,7 @@ func TestGenesis(t *testing.T) { assert.Equal(t, acc, res1) } -func TestSendMsgWithAccounts(t *testing.T) { +func TestMsgSendWithAccounts(t *testing.T) { bapp := newDemocoinApp() // Construct some genesis bytes to reflect democoin/types/AppAccount @@ -233,7 +233,7 @@ func TestSendMsgWithAccounts(t *testing.T) { assert.Equal(t, sdk.ABCICodeOK, res.Code, res.Log) } -func TestMineMsg(t *testing.T) { +func TestMsgMine(t *testing.T) { bapp := newDemocoinApp() // Construct genesis state @@ -271,11 +271,11 @@ func TestMineMsg(t *testing.T) { assert.Equal(t, acc1, res1) // Mine and check for reward - mineMsg1 := pow.GenerateMineMsg(addr1, 1, 2) + mineMsg1 := pow.GenerateMsgMine(addr1, 1, 2) SignCheckDeliver(t, bapp, mineMsg1, 0, true) CheckBalance(t, bapp, "1pow") // Mine again and check for reward - mineMsg2 := pow.GenerateMineMsg(addr1, 2, 3) + mineMsg2 := pow.GenerateMsgMine(addr1, 2, 3) SignCheckDeliver(t, bapp, mineMsg2, 1, true) CheckBalance(t, bapp, "2pow") // Mine again - should be invalid @@ -284,7 +284,7 @@ func TestMineMsg(t *testing.T) { } -func TestQuizMsg(t *testing.T) { +func TestMsgQuiz(t *testing.T) { bapp := newDemocoinApp() // Construct genesis state diff --git a/examples/democoin/types/account.go b/examples/democoin/types/account.go index d90525f1d..8a744229a 100644 --- a/examples/democoin/types/account.go +++ b/examples/democoin/types/account.go @@ -45,8 +45,8 @@ func GetAccountDecoder(cdc *wire.Codec) sdk.AccountDecoder { // State to Unmarshal type GenesisState struct { Accounts []*GenesisAccount `json:"accounts"` - PowGenesis pow.PowGenesis `json:"pow"` - CoolGenesis cool.CoolGenesis `json:"cool"` + POWGenesis pow.Genesis `json:"pow"` + CoolGenesis cool.Genesis `json:"cool"` } // GenesisAccount doesn't need pubkey or sequence diff --git a/examples/democoin/x/cool/commands/tx.go b/examples/democoin/x/cool/commands/tx.go index 88c5e4e68..90f31d283 100644 --- a/examples/democoin/x/cool/commands/tx.go +++ b/examples/democoin/x/cool/commands/tx.go @@ -34,19 +34,13 @@ func QuizTxCmd(cdc *wire.Codec) *cobra.Command { } // create the message - msg := cool.NewQuizMsg(from, args[0]) + msg := cool.NewMsgQuiz(from, args[0]) // get account name name := viper.GetString(client.FlagName) - // default to next sequence number if none provided - ctx, err = context.EnsureSequence(ctx) - if err != nil { - return err - } - // build and sign the transaction, then broadcast to Tendermint - res, err := ctx.SignBuildBroadcast(name, msg, cdc) + res, err := ctx.EnsureSignBuildBroadcast(name, msg, cdc) if err != nil { return err } @@ -78,17 +72,11 @@ func SetTrendTxCmd(cdc *wire.Codec) *cobra.Command { // get account name name := viper.GetString(client.FlagName) - // default to next sequence number if none provided - ctx, err = context.EnsureSequence(ctx) - if err != nil { - return err - } - // create the message - msg := cool.NewSetTrendMsg(from, args[0]) + msg := cool.NewMsgSetTrend(from, args[0]) // build and sign the transaction, then broadcast to Tendermint - res, err := ctx.SignBuildBroadcast(name, msg, cdc) + res, err := ctx.EnsureSignBuildBroadcast(name, msg, cdc) if err != nil { return err } diff --git a/examples/democoin/x/cool/errors.go b/examples/democoin/x/cool/errors.go index 4c28f94ba..7a5e62c5d 100644 --- a/examples/democoin/x/cool/errors.go +++ b/examples/democoin/x/cool/errors.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// Cool errors reserve 400 ~ 499. const ( DefaultCodespace sdk.CodespaceType = 6 diff --git a/examples/democoin/x/cool/handler.go b/examples/democoin/x/cool/handler.go index e2b36b218..c82fa4ae4 100644 --- a/examples/democoin/x/cool/handler.go +++ b/examples/democoin/x/cool/handler.go @@ -21,10 +21,10 @@ import ( func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { switch msg := msg.(type) { - case SetTrendMsg: - return handleSetTrendMsg(ctx, k, msg) - case QuizMsg: - return handleQuizMsg(ctx, k, msg) + case MsgSetTrend: + return handleMsgSetTrend(ctx, k, msg) + case MsgQuiz: + return handleMsgQuiz(ctx, k, msg) default: errMsg := fmt.Sprintf("Unrecognized cool Msg type: %v", reflect.TypeOf(msg).Name()) return sdk.ErrUnknownRequest(errMsg).Result() @@ -32,14 +32,14 @@ func NewHandler(k Keeper) sdk.Handler { } } -// Handle QuizMsg This is the engine of your module -func handleSetTrendMsg(ctx sdk.Context, k Keeper, msg SetTrendMsg) sdk.Result { +// Handle MsgQuiz This is the engine of your module +func handleMsgSetTrend(ctx sdk.Context, k Keeper, msg MsgSetTrend) sdk.Result { k.setTrend(ctx, msg.Cool) return sdk.Result{} } -// Handle QuizMsg This is the engine of your module -func handleQuizMsg(ctx sdk.Context, k Keeper, msg QuizMsg) sdk.Result { +// Handle MsgQuiz This is the engine of your module +func handleMsgQuiz(ctx sdk.Context, k Keeper, msg MsgQuiz) sdk.Result { correct := k.CheckTrend(ctx, msg.CoolAnswer) diff --git a/examples/democoin/x/cool/keeper.go b/examples/democoin/x/cool/keeper.go index 3b6c8e9ae..b180cd23c 100644 --- a/examples/democoin/x/cool/keeper.go +++ b/examples/democoin/x/cool/keeper.go @@ -7,7 +7,7 @@ import ( // Keeper - handlers sets/gets of custom variables for your module type Keeper struct { - ck bank.CoinKeeper + ck bank.Keeper storeKey sdk.StoreKey // The (unexposed) key used to access the store from the Context. @@ -15,7 +15,7 @@ type Keeper struct { } // NewKeeper - Returns the Keeper -func NewKeeper(key sdk.StoreKey, bankKeeper bank.CoinKeeper, codespace sdk.CodespaceType) Keeper { +func NewKeeper(key sdk.StoreKey, bankKeeper bank.Keeper, codespace sdk.CodespaceType) Keeper { return Keeper{bankKeeper, key, codespace} } @@ -44,7 +44,7 @@ func (k Keeper) CheckTrend(ctx sdk.Context, guessedTrend string) bool { } // InitGenesis - store the genesis trend -func (k Keeper) InitGenesis(ctx sdk.Context, data CoolGenesis) error { +func (k Keeper) InitGenesis(ctx sdk.Context, data Genesis) error { k.setTrend(ctx, data.Trend) return nil } diff --git a/examples/democoin/x/cool/types.go b/examples/democoin/x/cool/types.go index e24c363ac..caaf8610f 100644 --- a/examples/democoin/x/cool/types.go +++ b/examples/democoin/x/cool/types.go @@ -8,39 +8,39 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// A really cool msg type, these fields are can be entirely arbitrary and +// a really cool msg type, these fields are can be entirely arbitrary and // custom to your message -type SetTrendMsg struct { +type MsgSetTrend struct { Sender sdk.Address Cool string } -// Genesis state - specify genesis trend -type CoolGenesis struct { +// genesis state - specify genesis trend +type Genesis struct { Trend string `json:"trend"` } -// New cool message -func NewSetTrendMsg(sender sdk.Address, cool string) SetTrendMsg { - return SetTrendMsg{ +// new cool message +func NewMsgSetTrend(sender sdk.Address, cool string) MsgSetTrend { + return MsgSetTrend{ Sender: sender, Cool: cool, } } // enforce the msg type at compile time -var _ sdk.Msg = SetTrendMsg{} +var _ sdk.Msg = MsgSetTrend{} // nolint -func (msg SetTrendMsg) Type() string { return "cool" } -func (msg SetTrendMsg) Get(key interface{}) (value interface{}) { return nil } -func (msg SetTrendMsg) GetSigners() []sdk.Address { return []sdk.Address{msg.Sender} } -func (msg SetTrendMsg) String() string { - return fmt.Sprintf("SetTrendMsg{Sender: %v, Cool: %v}", msg.Sender, msg.Cool) +func (msg MsgSetTrend) Type() string { return "cool" } +func (msg MsgSetTrend) Get(key interface{}) (value interface{}) { return nil } +func (msg MsgSetTrend) GetSigners() []sdk.Address { return []sdk.Address{msg.Sender} } +func (msg MsgSetTrend) String() string { + return fmt.Sprintf("MsgSetTrend{Sender: %v, Cool: %v}", msg.Sender, msg.Cool) } // Validate Basic is used to quickly disqualify obviously invalid messages quickly -func (msg SetTrendMsg) ValidateBasic() sdk.Error { +func (msg MsgSetTrend) ValidateBasic() sdk.Error { if len(msg.Sender) == 0 { return sdk.ErrUnknownAddress(msg.Sender.String()).Trace("") } @@ -54,7 +54,7 @@ func (msg SetTrendMsg) ValidateBasic() sdk.Error { } // Get the bytes for the message signer to sign on -func (msg SetTrendMsg) GetSignBytes() []byte { +func (msg MsgSetTrend) GetSignBytes() []byte { b, err := json.Marshal(msg) if err != nil { panic(err) @@ -66,32 +66,32 @@ func (msg SetTrendMsg) GetSignBytes() []byte { // A message type to quiz how cool you are. these fields are can be entirely // arbitrary and custom to your message -type QuizMsg struct { +type MsgQuiz struct { Sender sdk.Address CoolAnswer string } // New cool message -func NewQuizMsg(sender sdk.Address, coolerthancool string) QuizMsg { - return QuizMsg{ +func NewMsgQuiz(sender sdk.Address, coolerthancool string) MsgQuiz { + return MsgQuiz{ Sender: sender, CoolAnswer: coolerthancool, } } // enforce the msg type at compile time -var _ sdk.Msg = QuizMsg{} +var _ sdk.Msg = MsgQuiz{} // nolint -func (msg QuizMsg) Type() string { return "cool" } -func (msg QuizMsg) Get(key interface{}) (value interface{}) { return nil } -func (msg QuizMsg) GetSigners() []sdk.Address { return []sdk.Address{msg.Sender} } -func (msg QuizMsg) String() string { - return fmt.Sprintf("QuizMsg{Sender: %v, CoolAnswer: %v}", msg.Sender, msg.CoolAnswer) +func (msg MsgQuiz) Type() string { return "cool" } +func (msg MsgQuiz) Get(key interface{}) (value interface{}) { return nil } +func (msg MsgQuiz) GetSigners() []sdk.Address { return []sdk.Address{msg.Sender} } +func (msg MsgQuiz) String() string { + return fmt.Sprintf("MsgQuiz{Sender: %v, CoolAnswer: %v}", msg.Sender, msg.CoolAnswer) } // Validate Basic is used to quickly disqualify obviously invalid messages quickly -func (msg QuizMsg) ValidateBasic() sdk.Error { +func (msg MsgQuiz) ValidateBasic() sdk.Error { if len(msg.Sender) == 0 { return sdk.ErrUnknownAddress(msg.Sender.String()).Trace("") } @@ -99,7 +99,7 @@ func (msg QuizMsg) ValidateBasic() sdk.Error { } // Get the bytes for the message signer to sign on -func (msg QuizMsg) GetSignBytes() []byte { +func (msg MsgQuiz) GetSignBytes() []byte { b, err := json.Marshal(msg) if err != nil { panic(err) diff --git a/examples/democoin/x/pow/commands/tx.go b/examples/democoin/x/pow/commands/tx.go index 5fa11a476..017047d08 100644 --- a/examples/democoin/x/pow/commands/tx.go +++ b/examples/democoin/x/pow/commands/tx.go @@ -14,6 +14,7 @@ import ( authcmd "github.com/cosmos/cosmos-sdk/x/auth/commands" ) +// command to mine some pow! func MineCmd(cdc *wire.Codec) *cobra.Command { return &cobra.Command{ Use: "mine [difficulty] [count] [nonce] [solution]", @@ -36,12 +37,10 @@ func MineCmd(cdc *wire.Codec) *cobra.Command { if err != nil { return err } - count, err := strconv.ParseUint(args[1], 0, 64) if err != nil { return err } - nonce, err := strconv.ParseUint(args[2], 0, 64) if err != nil { return err @@ -49,19 +48,13 @@ func MineCmd(cdc *wire.Codec) *cobra.Command { solution := []byte(args[3]) - msg := pow.NewMineMsg(from, difficulty, count, nonce, solution) + msg := pow.NewMsgMine(from, difficulty, count, nonce, solution) // get account name name := ctx.FromAddressName - // default to next sequence number if none provided - ctx, err = context.EnsureSequence(ctx) - if err != nil { - return err - } - // build and sign the transaction, then broadcast to Tendermint - res, err := ctx.SignBuildBroadcast(name, msg, cdc) + res, err := ctx.EnsureSignBuildBroadcast(name, msg, cdc) if err != nil { return err } diff --git a/examples/democoin/x/pow/errors.go b/examples/democoin/x/pow/errors.go index d387f9b9a..a499e0d9f 100644 --- a/examples/democoin/x/pow/errors.go +++ b/examples/democoin/x/pow/errors.go @@ -4,19 +4,20 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// TODO remove, seems hacky type CodeType = sdk.CodeType +// POW errors reserve 200 ~ 299 const ( - DefaultCodespace sdk.CodespaceType = 5 - - CodeInvalidDifficulty CodeType = 201 - CodeNonexistentDifficulty CodeType = 202 - CodeNonexistentReward CodeType = 203 - CodeNonexistentCount CodeType = 204 - CodeInvalidProof CodeType = 205 - CodeNotBelowTarget CodeType = 206 - CodeInvalidCount CodeType = 207 - CodeUnknownRequest CodeType = sdk.CodeUnknownRequest + DefaultCodespace sdk.CodespaceType = 5 + CodeInvalidDifficulty CodeType = 201 + CodeNonexistentDifficulty CodeType = 202 + CodeNonexistentReward CodeType = 203 + CodeNonexistentCount CodeType = 204 + CodeInvalidProof CodeType = 205 + CodeNotBelowTarget CodeType = 206 + CodeInvalidCount CodeType = 207 + CodeUnknownRequest CodeType = sdk.CodeUnknownRequest ) func codeToDefaultMsg(code CodeType) string { @@ -42,30 +43,25 @@ func codeToDefaultMsg(code CodeType) string { } } +// nolint func ErrInvalidDifficulty(codespace sdk.CodespaceType, msg string) sdk.Error { return newError(codespace, CodeInvalidDifficulty, msg) } - func ErrNonexistentDifficulty(codespace sdk.CodespaceType) sdk.Error { return newError(codespace, CodeNonexistentDifficulty, "") } - func ErrNonexistentReward(codespace sdk.CodespaceType) sdk.Error { return newError(codespace, CodeNonexistentReward, "") } - func ErrNonexistentCount(codespace sdk.CodespaceType) sdk.Error { return newError(codespace, CodeNonexistentCount, "") } - func ErrInvalidProof(codespace sdk.CodespaceType, msg string) sdk.Error { return newError(codespace, CodeInvalidProof, msg) } - func ErrNotBelowTarget(codespace sdk.CodespaceType, msg string) sdk.Error { return newError(codespace, CodeNotBelowTarget, msg) } - func ErrInvalidCount(codespace sdk.CodespaceType, msg string) sdk.Error { return newError(codespace, CodeInvalidCount, msg) } @@ -73,9 +69,8 @@ func ErrInvalidCount(codespace sdk.CodespaceType, msg string) sdk.Error { func msgOrDefaultMsg(msg string, code CodeType) string { if msg != "" { return msg - } else { - return codeToDefaultMsg(code) } + return codeToDefaultMsg(code) } func newError(codespace sdk.CodespaceType, code CodeType, msg string) sdk.Error { diff --git a/examples/democoin/x/pow/handler.go b/examples/democoin/x/pow/handler.go index d1a691139..2dd549bde 100644 --- a/examples/democoin/x/pow/handler.go +++ b/examples/democoin/x/pow/handler.go @@ -6,17 +6,18 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// POW handler func (pk Keeper) Handler(ctx sdk.Context, msg sdk.Msg) sdk.Result { switch msg := msg.(type) { - case MineMsg: - return handleMineMsg(ctx, pk, msg) + case MsgMine: + return handleMsgMine(ctx, pk, msg) default: errMsg := "Unrecognized pow Msg type: " + reflect.TypeOf(msg).Name() return sdk.ErrUnknownRequest(errMsg).Result() } } -func handleMineMsg(ctx sdk.Context, pk Keeper, msg MineMsg) sdk.Result { +func handleMsgMine(ctx sdk.Context, pk Keeper, msg MsgMine) sdk.Result { // precondition: msg has passed ValidateBasic diff --git a/examples/democoin/x/pow/handler_test.go b/examples/democoin/x/pow/handler_test.go index 4b1a571f7..8a4f81de2 100644 --- a/examples/democoin/x/pow/handler_test.go +++ b/examples/democoin/x/pow/handler_test.go @@ -20,8 +20,8 @@ func TestPowHandler(t *testing.T) { am := auth.NewAccountMapper(cdc, capKey, &auth.BaseAccount{}) ctx := sdk.NewContext(ms, abci.Header{}, false, nil) - config := NewPowConfig("pow", int64(1)) - ck := bank.NewCoinKeeper(am) + config := NewConfig("pow", int64(1)) + ck := bank.NewKeeper(am) keeper := NewKeeper(capKey, config, ck, DefaultCodespace) handler := keeper.Handler @@ -30,11 +30,11 @@ func TestPowHandler(t *testing.T) { count := uint64(1) difficulty := uint64(2) - err := keeper.InitGenesis(ctx, PowGenesis{uint64(1), uint64(0)}) + err := keeper.InitGenesis(ctx, Genesis{uint64(1), uint64(0)}) assert.Nil(t, err) nonce, proof := mine(addr, count, difficulty) - msg := NewMineMsg(addr, difficulty, count, nonce, proof) + msg := NewMsgMine(addr, difficulty, count, nonce, proof) result := handler(ctx, msg) assert.Equal(t, result, sdk.Result{}) @@ -51,7 +51,7 @@ func TestPowHandler(t *testing.T) { difficulty = uint64(4) nonce, proof = mine(addr, count, difficulty) - msg = NewMineMsg(addr, difficulty, count, nonce, proof) + msg = NewMsgMine(addr, difficulty, count, nonce, proof) result = handler(ctx, msg) assert.NotEqual(t, result, sdk.Result{}) diff --git a/examples/democoin/x/pow/keeper.go b/examples/democoin/x/pow/keeper.go index 70453d6d6..9a5edf0b5 100644 --- a/examples/democoin/x/pow/keeper.go +++ b/examples/democoin/x/pow/keeper.go @@ -9,42 +9,45 @@ import ( ) // module users must specify coin denomination and reward (constant) per PoW solution -type PowConfig struct { +type Config struct { Denomination string Reward int64 } // genesis info must specify starting difficulty and starting count -type PowGenesis struct { +type Genesis struct { Difficulty uint64 `json:"difficulty"` Count uint64 `json:"count"` } +// POW Keeper type Keeper struct { key sdk.StoreKey - config PowConfig - ck bank.CoinKeeper + config Config + ck bank.Keeper codespace sdk.CodespaceType } -func NewPowConfig(denomination string, reward int64) PowConfig { - return PowConfig{denomination, reward} +func NewConfig(denomination string, reward int64) Config { + return Config{denomination, reward} } -func NewKeeper(key sdk.StoreKey, config PowConfig, ck bank.CoinKeeper, codespace sdk.CodespaceType) Keeper { +func NewKeeper(key sdk.StoreKey, config Config, ck bank.Keeper, codespace sdk.CodespaceType) Keeper { return Keeper{key, config, ck, codespace} } -func (pk Keeper) InitGenesis(ctx sdk.Context, genesis PowGenesis) error { - pk.SetLastDifficulty(ctx, genesis.Difficulty) - pk.SetLastCount(ctx, genesis.Count) +// Init Genessis for the POW module +func (k Keeper) InitGenesis(ctx sdk.Context, genesis Genesis) error { + k.SetLastDifficulty(ctx, genesis.Difficulty) + k.SetLastCount(ctx, genesis.Count) return nil } var lastDifficultyKey = []byte("lastDifficultyKey") -func (pk Keeper) GetLastDifficulty(ctx sdk.Context) (uint64, error) { - store := ctx.KVStore(pk.key) +// get the last mining difficulty +func (k Keeper) GetLastDifficulty(ctx sdk.Context) (uint64, error) { + store := ctx.KVStore(k.key) stored := store.Get(lastDifficultyKey) if stored == nil { panic("no stored difficulty") @@ -53,15 +56,17 @@ func (pk Keeper) GetLastDifficulty(ctx sdk.Context) (uint64, error) { } } -func (pk Keeper) SetLastDifficulty(ctx sdk.Context, diff uint64) { - store := ctx.KVStore(pk.key) +// set the last mining difficulty +func (k Keeper) SetLastDifficulty(ctx sdk.Context, diff uint64) { + store := ctx.KVStore(k.key) store.Set(lastDifficultyKey, []byte(strconv.FormatUint(diff, 16))) } var countKey = []byte("count") -func (pk Keeper) GetLastCount(ctx sdk.Context) (uint64, error) { - store := ctx.KVStore(pk.key) +// get the last count +func (k Keeper) GetLastCount(ctx sdk.Context) (uint64, error) { + store := ctx.KVStore(k.key) stored := store.Get(countKey) if stored == nil { panic("no stored count") @@ -70,45 +75,45 @@ func (pk Keeper) GetLastCount(ctx sdk.Context) (uint64, error) { } } -func (pk Keeper) SetLastCount(ctx sdk.Context, count uint64) { - store := ctx.KVStore(pk.key) +// set the last count +func (k Keeper) SetLastCount(ctx sdk.Context, count uint64) { + store := ctx.KVStore(k.key) store.Set(countKey, []byte(strconv.FormatUint(count, 16))) } -func (pk Keeper) CheckValid(ctx sdk.Context, difficulty uint64, count uint64) (uint64, uint64, sdk.Error) { +// Is the keeper state valid? +func (k Keeper) CheckValid(ctx sdk.Context, difficulty uint64, count uint64) (uint64, uint64, sdk.Error) { - lastDifficulty, err := pk.GetLastDifficulty(ctx) + lastDifficulty, err := k.GetLastDifficulty(ctx) if err != nil { - return 0, 0, ErrNonexistentDifficulty(pk.codespace) + return 0, 0, ErrNonexistentDifficulty(k.codespace) } newDifficulty := lastDifficulty + 1 - lastCount, err := pk.GetLastCount(ctx) + lastCount, err := k.GetLastCount(ctx) if err != nil { - return 0, 0, ErrNonexistentCount(pk.codespace) + return 0, 0, ErrNonexistentCount(k.codespace) } newCount := lastCount + 1 if count != newCount { - return 0, 0, ErrInvalidCount(pk.codespace, fmt.Sprintf("invalid count: was %d, should have been %d", count, newCount)) + return 0, 0, ErrInvalidCount(k.codespace, fmt.Sprintf("invalid count: was %d, should have been %d", count, newCount)) } - if difficulty != newDifficulty { - return 0, 0, ErrInvalidDifficulty(pk.codespace, fmt.Sprintf("invalid difficulty: was %d, should have been %d", difficulty, newDifficulty)) + return 0, 0, ErrInvalidDifficulty(k.codespace, fmt.Sprintf("invalid difficulty: was %d, should have been %d", difficulty, newDifficulty)) } - return newDifficulty, newCount, nil - } -func (pk Keeper) ApplyValid(ctx sdk.Context, sender sdk.Address, newDifficulty uint64, newCount uint64) sdk.Error { - _, ckErr := pk.ck.AddCoins(ctx, sender, []sdk.Coin{sdk.Coin{pk.config.Denomination, pk.config.Reward}}) +// Add some coins for a POW well done +func (k Keeper) ApplyValid(ctx sdk.Context, sender sdk.Address, newDifficulty uint64, newCount uint64) sdk.Error { + _, ckErr := k.ck.AddCoins(ctx, sender, []sdk.Coin{sdk.Coin{k.config.Denomination, k.config.Reward}}) if ckErr != nil { return ckErr } - pk.SetLastDifficulty(ctx, newDifficulty) - pk.SetLastCount(ctx, newCount) + k.SetLastDifficulty(ctx, newDifficulty) + k.SetLastCount(ctx, newCount) return nil } diff --git a/examples/democoin/x/pow/keeper_test.go b/examples/democoin/x/pow/keeper_test.go index d0b60fa17..4c01559f6 100644 --- a/examples/democoin/x/pow/keeper_test.go +++ b/examples/democoin/x/pow/keeper_test.go @@ -33,11 +33,11 @@ func TestPowKeeperGetSet(t *testing.T) { am := auth.NewAccountMapper(cdc, capKey, &auth.BaseAccount{}) ctx := sdk.NewContext(ms, abci.Header{}, false, nil) - config := NewPowConfig("pow", int64(1)) - ck := bank.NewCoinKeeper(am) + config := NewConfig("pow", int64(1)) + ck := bank.NewKeeper(am) keeper := NewKeeper(capKey, config, ck, DefaultCodespace) - err := keeper.InitGenesis(ctx, PowGenesis{uint64(1), uint64(0)}) + err := keeper.InitGenesis(ctx, Genesis{uint64(1), uint64(0)}) assert.Nil(t, err) res, err := keeper.GetLastDifficulty(ctx) diff --git a/examples/democoin/x/pow/mine.go b/examples/democoin/x/pow/mine.go index ff2264aaa..21d389a1d 100644 --- a/examples/democoin/x/pow/mine.go +++ b/examples/democoin/x/pow/mine.go @@ -9,9 +9,10 @@ import ( crypto "github.com/tendermint/go-crypto" ) -func GenerateMineMsg(sender sdk.Address, count uint64, difficulty uint64) MineMsg { +// generate the mine message +func GenerateMsgMine(sender sdk.Address, count uint64, difficulty uint64) MsgMine { nonce, hash := mine(sender, count, difficulty) - return NewMineMsg(sender, difficulty, count, nonce, hash) + return NewMsgMine(sender, difficulty, count, nonce, hash) } func hash(sender sdk.Address, count uint64, nonce uint64) []byte { diff --git a/examples/democoin/x/pow/types.go b/examples/democoin/x/pow/types.go index 69d56e4f1..999dd4197 100644 --- a/examples/democoin/x/pow/types.go +++ b/examples/democoin/x/pow/types.go @@ -13,8 +13,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// MineMsg - mine some coins with PoW -type MineMsg struct { +// MsgMine - mine some coins with PoW +type MsgMine struct { Sender sdk.Address `json:"sender"` Difficulty uint64 `json:"difficulty"` Count uint64 `json:"count"` @@ -23,21 +23,23 @@ type MineMsg struct { } // enforce the msg type at compile time -var _ sdk.Msg = MineMsg{} +var _ sdk.Msg = MsgMine{} -// NewMineMsg - construct mine message -func NewMineMsg(sender sdk.Address, difficulty uint64, count uint64, nonce uint64, proof []byte) MineMsg { - return MineMsg{sender, difficulty, count, nonce, proof} +// NewMsgMine - construct mine message +func NewMsgMine(sender sdk.Address, difficulty uint64, count uint64, nonce uint64, proof []byte) MsgMine { + return MsgMine{sender, difficulty, count, nonce, proof} } -func (msg MineMsg) Type() string { return "pow" } -func (msg MineMsg) Get(key interface{}) (value interface{}) { return nil } -func (msg MineMsg) GetSigners() []sdk.Address { return []sdk.Address{msg.Sender} } -func (msg MineMsg) String() string { - return fmt.Sprintf("MineMsg{Sender: %v, Difficulty: %d, Count: %d, Nonce: %d, Proof: %s}", msg.Sender, msg.Difficulty, msg.Count, msg.Nonce, msg.Proof) +// nolint +func (msg MsgMine) Type() string { return "pow" } +func (msg MsgMine) Get(key interface{}) (value interface{}) { return nil } +func (msg MsgMine) GetSigners() []sdk.Address { return []sdk.Address{msg.Sender} } +func (msg MsgMine) String() string { + return fmt.Sprintf("MsgMine{Sender: %v, Difficulty: %d, Count: %d, Nonce: %d, Proof: %s}", msg.Sender, msg.Difficulty, msg.Count, msg.Nonce, msg.Proof) } -func (msg MineMsg) ValidateBasic() sdk.Error { +// validate the mine message +func (msg MsgMine) ValidateBasic() sdk.Error { // check hash var data []byte // hash must include sender, so no other users can race the tx @@ -69,7 +71,8 @@ func (msg MineMsg) ValidateBasic() sdk.Error { return nil } -func (msg MineMsg) GetSignBytes() []byte { +// get the mine message sign bytes +func (msg MsgMine) GetSignBytes() []byte { b, err := json.Marshal(msg) if err != nil { panic(err) diff --git a/examples/democoin/x/pow/types_test.go b/examples/democoin/x/pow/types_test.go index 34ab8914e..bf2e9169b 100644 --- a/examples/democoin/x/pow/types_test.go +++ b/examples/democoin/x/pow/types_test.go @@ -9,70 +9,72 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -func TestNewMineMsg(t *testing.T) { +func TestNewMsgMine(t *testing.T) { addr := sdk.Address([]byte("sender")) - msg := MineMsg{addr, 0, 0, 0, []byte("")} - equiv := NewMineMsg(addr, 0, 0, 0, []byte("")) + msg := MsgMine{addr, 0, 0, 0, []byte("")} + equiv := NewMsgMine(addr, 0, 0, 0, []byte("")) assert.Equal(t, msg, equiv, "%s != %s", msg, equiv) } -func TestMineMsgType(t *testing.T) { +func TestMsgMineType(t *testing.T) { addr := sdk.Address([]byte("sender")) - msg := MineMsg{addr, 0, 0, 0, []byte("")} + msg := MsgMine{addr, 0, 0, 0, []byte("")} assert.Equal(t, msg.Type(), "pow") } -func TestMineMsgValidation(t *testing.T) { +func TestMsgMineValidation(t *testing.T) { addr := sdk.Address([]byte("sender")) otherAddr := sdk.Address([]byte("another")) count := uint64(0) + for difficulty := uint64(1); difficulty < 1000; difficulty += 100 { - count += 1 + + count++ nonce, proof := mine(addr, count, difficulty) - msg := MineMsg{addr, difficulty, count, nonce, proof} + msg := MsgMine{addr, difficulty, count, nonce, proof} err := msg.ValidateBasic() assert.Nil(t, err, "error with difficulty %d - %+v", difficulty, err) - msg.Count += 1 + msg.Count++ err = msg.ValidateBasic() assert.NotNil(t, err, "count was wrong, should have thrown error with msg %s", msg) - msg.Count -= 1 - msg.Nonce += 1 + msg.Count-- + msg.Nonce++ err = msg.ValidateBasic() assert.NotNil(t, err, "nonce was wrong, should have thrown error with msg %s", msg) - msg.Nonce -= 1 + msg.Nonce-- msg.Sender = otherAddr err = msg.ValidateBasic() assert.NotNil(t, err, "sender was wrong, should have thrown error with msg %s", msg) } } -func TestMineMsgString(t *testing.T) { +func TestMsgMineString(t *testing.T) { addr := sdk.Address([]byte("sender")) - msg := MineMsg{addr, 0, 0, 0, []byte("abc")} + msg := MsgMine{addr, 0, 0, 0, []byte("abc")} res := msg.String() - assert.Equal(t, res, "MineMsg{Sender: 73656E646572, Difficulty: 0, Count: 0, Nonce: 0, Proof: abc}") + assert.Equal(t, res, "MsgMine{Sender: 73656E646572, Difficulty: 0, Count: 0, Nonce: 0, Proof: abc}") } -func TestMineMsgGet(t *testing.T) { +func TestMsgMineGet(t *testing.T) { addr := sdk.Address([]byte("sender")) - msg := MineMsg{addr, 0, 0, 0, []byte("")} + msg := MsgMine{addr, 0, 0, 0, []byte("")} res := msg.Get(nil) assert.Nil(t, res) } -func TestMineMsgGetSignBytes(t *testing.T) { +func TestMsgMineGetSignBytes(t *testing.T) { addr := sdk.Address([]byte("sender")) - msg := MineMsg{addr, 1, 1, 1, []byte("abc")} + msg := MsgMine{addr, 1, 1, 1, []byte("abc")} res := msg.GetSignBytes() assert.Equal(t, string(res), `{"sender":"73656E646572","difficulty":1,"count":1,"nonce":1,"proof":"YWJj"}`) } -func TestMineMsgGetSigners(t *testing.T) { +func TestMsgMineGetSigners(t *testing.T) { addr := sdk.Address([]byte("sender")) - msg := MineMsg{addr, 1, 1, 1, []byte("abc")} + msg := MsgMine{addr, 1, 1, 1, []byte("abc")} res := msg.GetSigners() assert.Equal(t, fmt.Sprintf("%v", res), "[73656E646572]") } diff --git a/examples/kvstore/main.go b/examples/kvstore/main.go index 0d80826ed..d6b71171d 100644 --- a/examples/kvstore/main.go +++ b/examples/kvstore/main.go @@ -41,7 +41,7 @@ func main() { baseApp.SetTxDecoder(decodeTx) // Set a handler Route. - baseApp.Router().AddRoute("kvstore", KVStoreHandler(capKeyMainStore)) + baseApp.Router().AddRoute("kvstore", Handler(capKeyMainStore)) // Load latest version. if err := baseApp.LoadLatestVersion(capKeyMainStore); err != nil { @@ -65,11 +65,12 @@ func main() { return } -func KVStoreHandler(storeKey sdk.StoreKey) sdk.Handler { +// KVStore Handler +func Handler(storeKey sdk.StoreKey) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { dTx, ok := msg.(kvstoreTx) if !ok { - panic("KVStoreHandler should only receive kvstoreTx") + panic("Handler should only receive kvstoreTx") } // tx is already unmarshalled diff --git a/server/init.go b/server/init.go index f2578cb19..a68566cdf 100644 --- a/server/init.go +++ b/server/init.go @@ -76,10 +76,10 @@ func (c initCmd) run(cmd *cobra.Command, args []string) error { return err } - var DEFAULT_DENOM = "mycoin" + var defaultDenom = "mycoin" // Now, we want to add the custom app_state - appState, err := c.genAppState(args, addr, DEFAULT_DENOM) + appState, err := c.genAppState(args, addr, defaultDenom) if err != nil { return err } diff --git a/server/tm_cmds.go b/server/tm_cmds.go index 2a9b680e5..67504fa6b 100644 --- a/server/tm_cmds.go +++ b/server/tm_cmds.go @@ -12,7 +12,7 @@ import ( // ShowNodeIDCmd - ported from Tendermint, dump node ID to stdout func ShowNodeIDCmd(ctx *Context) *cobra.Command { - cmd := showNodeId{ctx} + cmd := showNodeID{ctx} return &cobra.Command{ Use: "show_node_id", Short: "Show this node's ID", @@ -20,11 +20,11 @@ func ShowNodeIDCmd(ctx *Context) *cobra.Command { } } -type showNodeId struct { +type showNodeID struct { context *Context } -func (s showNodeId) run(cmd *cobra.Command, args []string) error { +func (s showNodeID) run(cmd *cobra.Command, args []string) error { cfg := s.context.Config nodeKey, err := p2p.LoadOrGenNodeKey(cfg.NodeKeyFile()) if err != nil { diff --git a/server/util.go b/server/util.go index 95dc4b30d..cf37ec5cc 100644 --- a/server/util.go +++ b/server/util.go @@ -14,6 +14,7 @@ import ( "github.com/tendermint/tmlibs/log" ) +// server context type Context struct { Config *cfg.Config Logger log.Logger @@ -59,6 +60,7 @@ func PersistentPreRunEFn(context *Context) func(*cobra.Command, []string) error } } +// add server commands func AddCommands( rootCmd *cobra.Command, appState GenAppState, appCreator AppCreator, diff --git a/store/cachekvstore.go b/store/cachekvstore.go index 6c5cc9542..772b59305 100644 --- a/store/cachekvstore.go +++ b/store/cachekvstore.go @@ -26,13 +26,12 @@ type cacheKVStore struct { var _ CacheKVStore = (*cacheKVStore)(nil) +// nolint func NewCacheKVStore(parent KVStore) *cacheKVStore { - ci := &cacheKVStore{ cache: make(map[string]cValue), parent: parent, } - return ci } @@ -170,9 +169,8 @@ func (ci *cacheKVStore) dirtyItems(ascending bool) []cmn.KVPair { sort.Slice(items, func(i, j int) bool { if ascending { return bytes.Compare(items[i].Key, items[j].Key) < 0 - } else { - return bytes.Compare(items[i].Key, items[j].Key) > 0 } + return bytes.Compare(items[i].Key, items[j].Key) > 0 }) return items } diff --git a/store/cachekvstore_test.go b/store/cachekvstore_test.go index e29cd6156..0c88ca27d 100644 --- a/store/cachekvstore_test.go +++ b/store/cachekvstore_test.go @@ -105,7 +105,7 @@ func TestCacheKVIteratorBounds(t *testing.T) { k, v := itr.Key(), itr.Value() assert.Equal(t, keyFmt(i), k) assert.Equal(t, valFmt(i), v) - i += 1 + i++ } assert.Equal(t, nItems, i) @@ -113,7 +113,7 @@ func TestCacheKVIteratorBounds(t *testing.T) { itr = st.Iterator(bz("money"), nil) i = 0 for ; itr.Valid(); itr.Next() { - i += 1 + i++ } assert.Equal(t, 0, i) @@ -124,7 +124,7 @@ func TestCacheKVIteratorBounds(t *testing.T) { k, v := itr.Key(), itr.Value() assert.Equal(t, keyFmt(i), k) assert.Equal(t, valFmt(i), v) - i += 1 + i++ } assert.Equal(t, 3, i) @@ -135,7 +135,7 @@ func TestCacheKVIteratorBounds(t *testing.T) { k, v := itr.Key(), itr.Value() assert.Equal(t, keyFmt(i), k) assert.Equal(t, valFmt(i), v) - i += 1 + i++ } assert.Equal(t, 4, i) } @@ -369,7 +369,7 @@ func assertIterateDomain(t *testing.T, st KVStore, expectedN int) { k, v := itr.Key(), itr.Value() assert.Equal(t, keyFmt(i), k) assert.Equal(t, valFmt(i), v) - i += 1 + i++ } assert.Equal(t, expectedN, i) } @@ -397,7 +397,7 @@ func assertIterateDomainCheck(t *testing.T, st KVStore, mem dbm.DB, r []keyRange itr.Next() itr2.Next() - i += 1 + i++ } assert.False(t, itr.Valid()) @@ -479,10 +479,10 @@ func (krc *keyRangeCounter) valid() bool { func (krc *keyRangeCounter) next() { thisKeyRange := krc.keyRanges[krc.rangeIdx] if krc.idx == thisKeyRange.len()-1 { - krc.rangeIdx += 1 + krc.rangeIdx++ krc.idx = 0 } else { - krc.idx += 1 + krc.idx++ } } diff --git a/store/cachemergeiterator.go b/store/cachemergeiterator.go index b6c50c42c..cd739500d 100644 --- a/store/cachemergeiterator.go +++ b/store/cachemergeiterator.go @@ -151,9 +151,8 @@ func (iter *cacheMergeIterator) Close() { func (iter *cacheMergeIterator) compare(a, b []byte) int { if iter.ascending { return bytes.Compare(a, b) - } else { - return bytes.Compare(a, b) * -1 } + return bytes.Compare(a, b) * -1 } // Skip all delete-items from the cache w/ `key < until`. After this function, diff --git a/store/dbstoreadapter.go b/store/dbstoreadapter.go index 10c175a99..7a299471f 100644 --- a/store/dbstoreadapter.go +++ b/store/dbstoreadapter.go @@ -10,7 +10,7 @@ type dbStoreAdapter struct { } // Implements Store. -func (_ dbStoreAdapter) GetStoreType() StoreType { +func (dbStoreAdapter) GetStoreType() StoreType { return sdk.StoreTypeDB } diff --git a/store/firstlast.go b/store/firstlast.go index e0c8b11bb..e6cb08432 100644 --- a/store/firstlast.go +++ b/store/firstlast.go @@ -2,6 +2,7 @@ package store import ( "bytes" + cmn "github.com/tendermint/tmlibs/common" ) @@ -22,9 +23,8 @@ func Last(st KVStore, start, end []byte) (kv cmn.KVPair, ok bool) { if !iter.Valid() { if v := st.Get(start); v != nil { return cmn.KVPair{cp(start), cp(v)}, true - } else { - return kv, false } + return kv, false } defer iter.Close() diff --git a/store/iavlstore.go b/store/iavlstore.go index 7d006d3c1..de32e27e1 100644 --- a/store/iavlstore.go +++ b/store/iavlstore.go @@ -17,6 +17,7 @@ const ( defaultIAVLNumHistory = 1<<53 - 1 // DEPRECATED ) +// load the iavl store func LoadIAVLStore(db dbm.DB, id CommitID) (CommitStore, error) { tree := iavl.NewVersionedTree(db, defaultIAVLCacheSize) _, err := tree.LoadVersion(id.Version) diff --git a/store/iavlstore_test.go b/store/iavlstore_test.go index 824617c26..4557dea06 100644 --- a/store/iavlstore_test.go +++ b/store/iavlstore_test.go @@ -80,7 +80,7 @@ func TestIAVLIterator(t *testing.T) { key, value := iter.Key(), iter.Value() assert.EqualValues(t, key, expectedKey) assert.EqualValues(t, value, treeData[expectedKey]) - i += 1 + i++ } assert.Equal(t, len(expected), i) @@ -91,7 +91,7 @@ func TestIAVLIterator(t *testing.T) { key, value := iter.Key(), iter.Value() assert.EqualValues(t, key, expectedKey) assert.EqualValues(t, value, treeData[expectedKey]) - i += 1 + i++ } assert.Equal(t, len(expected), i) @@ -102,7 +102,7 @@ func TestIAVLIterator(t *testing.T) { key, value := iter.Key(), iter.Value() assert.EqualValues(t, key, expectedKey) assert.EqualValues(t, value, treeData[expectedKey]) - i += 1 + i++ } assert.Equal(t, len(expected), i) @@ -113,7 +113,7 @@ func TestIAVLIterator(t *testing.T) { key, value := iter.Key(), iter.Value() assert.EqualValues(t, key, expectedKey) assert.EqualValues(t, value, treeData[expectedKey]) - i += 1 + i++ } assert.Equal(t, len(expected), i) @@ -124,7 +124,7 @@ func TestIAVLIterator(t *testing.T) { key, value := iter.Key(), iter.Value() assert.EqualValues(t, key, expectedKey) assert.EqualValues(t, value, treeData[expectedKey]) - i += 1 + i++ } assert.Equal(t, len(expected), i) @@ -135,7 +135,7 @@ func TestIAVLIterator(t *testing.T) { key, value := iter.Key(), iter.Value() assert.EqualValues(t, key, expectedKey) assert.EqualValues(t, value, treeData[expectedKey]) - i += 1 + i++ } assert.Equal(t, len(expected), i) } @@ -164,7 +164,7 @@ func TestIAVLSubspaceIterator(t *testing.T) { key, value := iter.Key(), iter.Value() assert.EqualValues(t, key, expectedKey) assert.EqualValues(t, value, expectedKey) - i += 1 + i++ } assert.Equal(t, len(expected), i) @@ -179,7 +179,7 @@ func TestIAVLSubspaceIterator(t *testing.T) { key, value := iter.Key(), iter.Value() assert.EqualValues(t, key, expectedKey) assert.EqualValues(t, value, []byte("test4")) - i += 1 + i++ } assert.Equal(t, len(expected), i) @@ -194,7 +194,7 @@ func TestIAVLSubspaceIterator(t *testing.T) { key, value := iter.Key(), iter.Value() assert.EqualValues(t, key, expectedKey) assert.EqualValues(t, value, []byte("test4")) - i += 1 + i++ } assert.Equal(t, len(expected), i) } @@ -223,7 +223,7 @@ func TestIAVLReverseSubspaceIterator(t *testing.T) { key, value := iter.Key(), iter.Value() assert.EqualValues(t, key, expectedKey) assert.EqualValues(t, value, expectedKey) - i += 1 + i++ } assert.Equal(t, len(expected), i) @@ -238,7 +238,7 @@ func TestIAVLReverseSubspaceIterator(t *testing.T) { key, value := iter.Key(), iter.Value() assert.EqualValues(t, key, expectedKey) assert.EqualValues(t, value, []byte("test4")) - i += 1 + i++ } assert.Equal(t, len(expected), i) @@ -253,7 +253,7 @@ func TestIAVLReverseSubspaceIterator(t *testing.T) { key, value := iter.Key(), iter.Value() assert.EqualValues(t, key, expectedKey) assert.EqualValues(t, value, []byte("test4")) - i += 1 + i++ } assert.Equal(t, len(expected), i) } diff --git a/store/rootmultistore.go b/store/rootmultistore.go index 3e094712b..217e8eb14 100644 --- a/store/rootmultistore.go +++ b/store/rootmultistore.go @@ -33,6 +33,7 @@ type rootMultiStore struct { var _ CommitMultiStore = (*rootMultiStore)(nil) var _ Queryable = (*rootMultiStore)(nil) +// nolint func NewCommitMultiStore(db dbm.DB) *rootMultiStore { return &rootMultiStore{ db: db, @@ -267,7 +268,7 @@ func (rs *rootMultiStore) loadCommitStoreFromParams(id CommitID, params storePar } func (rs *rootMultiStore) nameToKey(name string) StoreKey { - for key, _ := range rs.storesParams { + for key := range rs.storesParams { if key.Name() == name { return key } diff --git a/store/types.go b/store/types.go index fa27e94da..ca43dab6b 100644 --- a/store/types.go +++ b/store/types.go @@ -5,6 +5,7 @@ import ( ) // Import cosmos-sdk/types/store.go for convenience. +// nolint type Store = types.Store type Committer = types.Committer type CommitStore = types.CommitStore diff --git a/types/errors.go b/types/errors.go index c2fe726a2..059a0dd74 100644 --- a/types/errors.go +++ b/types/errors.go @@ -25,6 +25,7 @@ func (code ABCICodeType) IsOK() bool { return false } +// get the abci code from the local code and codespace func ToABCICode(space CodespaceType, code CodeType) ABCICodeType { // TODO: Make Tendermint more aware of codespaces. if space == CodespaceRoot && code == CodeOK { @@ -33,6 +34,7 @@ func ToABCICode(space CodespaceType, code CodeType) ABCICodeType { return ABCICodeType((uint32(space) << 16) | uint32(code)) } +// SDK error codes const ( // ABCI error codes ABCICodeOK ABCICodeType = 0 diff --git a/version/command.go b/version/command.go index e28cbe57e..b505414b1 100644 --- a/version/command.go +++ b/version/command.go @@ -25,15 +25,13 @@ func getVersion() string { } // CMD - func printVersion(cmd *cobra.Command, args []string) { v := getVersion() fmt.Println(v) } -// REST - -func VersionRequestHandler(w http.ResponseWriter, r *http.Request) { +// version REST handler endpoint +func RequestHandler(w http.ResponseWriter, r *http.Request) { v := getVersion() w.Write([]byte(v)) } diff --git a/wire/wire.go b/wire/wire.go index 32c82a676..0ee01939d 100644 --- a/wire/wire.go +++ b/wire/wire.go @@ -8,6 +8,7 @@ import ( "github.com/tendermint/go-crypto" ) +// amino codec to marshal/unmarshal type Codec = amino.Codec func NewCodec() *Codec { @@ -15,10 +16,12 @@ func NewCodec() *Codec { return cdc } +// Register the go-crypto to the codec func RegisterCrypto(cdc *Codec) { crypto.RegisterAmino(cdc) } +// attempt to make some pretty json func MarshalJSONIndent(cdc *Codec, obj interface{}) ([]byte, error) { bz, err := cdc.MarshalJSON(obj) if err != nil { diff --git a/x/auth/commands/account.go b/x/auth/commands/account.go index 56f441f35..4da601df8 100644 --- a/x/auth/commands/account.go +++ b/x/auth/commands/account.go @@ -17,6 +17,7 @@ func GetAccountCmdDefault(storeName string, cdc *wire.Codec) *cobra.Command { return GetAccountCmd(storeName, cdc, GetAccountDecoder(cdc)) } +// Get account decoder for auth.DefaultAccount func GetAccountDecoder(cdc *wire.Codec) sdk.AccountDecoder { return func(accBytes []byte) (acct sdk.Account, err error) { // acct := new(auth.BaseAccount) diff --git a/x/auth/context.go b/x/auth/context.go index 91259d9e6..b233f1e86 100644 --- a/x/auth/context.go +++ b/x/auth/context.go @@ -33,10 +33,12 @@ const ( contextKeySigners contextKey = iota ) +// add the signers to the context func WithSigners(ctx types.Context, accounts []types.Account) types.Context { return ctx.WithValue(contextKeySigners, accounts) } +// get the signers from the context func GetSigners(ctx types.Context) []types.Account { v := ctx.Value(contextKeySigners) if v == nil { diff --git a/x/auth/mapper.go b/x/auth/mapper.go index 7bc23aee1..ed69034be 100644 --- a/x/auth/mapper.go +++ b/x/auth/mapper.go @@ -28,6 +28,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 { return accountMapper{ key: key, @@ -107,14 +108,14 @@ func (am accountMapper) clonePrototype() sdk.Account { panic(fmt.Sprintf("accountMapper requires a proto sdk.Account, but %v doesn't implement sdk.Account", protoRt)) } return clone - } else { - protoRv := reflect.New(protoRt).Elem() - clone, ok := protoRv.Interface().(sdk.Account) - if !ok { - panic(fmt.Sprintf("accountMapper requires a proto sdk.Account, but %v doesn't implement sdk.Account", protoRt)) - } - return clone } + + protoRv := reflect.New(protoRt).Elem() + clone, ok := protoRv.Interface().(sdk.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 { diff --git a/x/auth/rest/query.go b/x/auth/rest/query.go index c401fe47f..b97f883f9 100644 --- a/x/auth/rest/query.go +++ b/x/auth/rest/query.go @@ -10,16 +10,19 @@ 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/commands" ) -type commander struct { - storeName string - cdc *wire.Codec - decoder sdk.AccountDecoder +// register REST routes +func RegisterRoutes(r *mux.Router, cdc *wire.Codec, storeName string) { + r.HandleFunc( + "/accounts/{address}", + QueryAccountRequestHandler(storeName, cdc, auth.GetAccountDecoder(cdc)), + ).Methods("GET") } +// query accountREST Handler func QueryAccountRequestHandler(storeName string, cdc *wire.Codec, decoder sdk.AccountDecoder) func(http.ResponseWriter, *http.Request) { - c := commander{storeName, cdc, decoder} ctx := context.NewCoreContextFromViper() return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) @@ -33,7 +36,7 @@ func QueryAccountRequestHandler(storeName string, cdc *wire.Codec, decoder sdk.A } key := sdk.Address(bz) - res, err := ctx.Query(key, c.storeName) + res, err := ctx.Query(key, storeName) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Could't query account. Error: %s", err.Error()))) @@ -47,7 +50,7 @@ func QueryAccountRequestHandler(storeName string, cdc *wire.Codec, decoder sdk.A } // decode the value - account, err := c.decoder(res) + account, err := decoder(res) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(fmt.Sprintf("Could't parse query result. Result: %s. Error: %s", res, err.Error()))) diff --git a/x/auth/rest/root.go b/x/auth/rest/root.go deleted file mode 100644 index 5417cf868..000000000 --- a/x/auth/rest/root.go +++ /dev/null @@ -1,11 +0,0 @@ -package rest - -import ( - "github.com/cosmos/cosmos-sdk/wire" - auth "github.com/cosmos/cosmos-sdk/x/auth/commands" - "github.com/gorilla/mux" -) - -func RegisterRoutes(r *mux.Router, cdc *wire.Codec, storeName string) { - r.HandleFunc("/accounts/{address}", QueryAccountRequestHandler(storeName, cdc, auth.GetAccountDecoder(cdc))).Methods("GET") -} diff --git a/x/bank/commands/sendtx.go b/x/bank/commands/sendtx.go index 56048262d..dbf2bb3c9 100644 --- a/x/bank/commands/sendtx.go +++ b/x/bank/commands/sendtx.go @@ -20,68 +20,53 @@ const ( ) // SendTxCommand will create a send tx and sign it with the given key -func SendTxCmd(Cdc *wire.Codec) *cobra.Command { - cmdr := Commander{Cdc} +func SendTxCmd(cdc *wire.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "send", Short: "Create and sign a send tx", - RunE: cmdr.sendTxCmd, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) + + // get the from/to address + from, err := ctx.GetFromAddress() + if err != nil { + return err + } + + toStr := viper.GetString(flagTo) + bz, err := hex.DecodeString(toStr) + if err != nil { + return err + } + to := sdk.Address(bz) + + // parse coins + amount := viper.GetString(flagAmount) + coins, err := sdk.ParseCoins(amount) + if err != nil { + return err + } + + // build and sign the transaction, then broadcast to Tendermint + msg := BuildMsg(from, to, coins) + res, err := ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, msg, cdc) + if err != nil { + return err + } + fmt.Printf("Committed at block %d. Hash: %s\n", res.Height, res.Hash.String()) + return nil + }, } + cmd.Flags().String(flagTo, "", "Address to send coins") cmd.Flags().String(flagAmount, "", "Amount of coins to send") return cmd } -type Commander struct { - Cdc *wire.Codec -} - -func (c Commander) sendTxCmd(cmd *cobra.Command, args []string) error { - ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(c.Cdc)) - - // get the from address - from, err := ctx.GetFromAddress() - if err != nil { - return err - } - - // parse coins - amount := viper.GetString(flagAmount) - coins, err := sdk.ParseCoins(amount) - if err != nil { - return err - } - - // parse destination address - dest := viper.GetString(flagTo) - bz, err := hex.DecodeString(dest) - if err != nil { - return err - } - to := sdk.Address(bz) - - // build message - msg := BuildMsg(from, to, coins) - - // default to next sequence number if none provided - ctx, err = context.EnsureSequence(ctx) - if err != nil { - return err - } - - // build and sign the transaction, then broadcast to Tendermint - res, err := ctx.SignBuildBroadcast(ctx.FromAddressName, msg, c.Cdc) - if err != nil { - return err - } - - fmt.Printf("Committed at block %d. Hash: %s\n", res.Height, res.Hash.String()) - return nil -} - +// build the sendTx msg func BuildMsg(from sdk.Address, to sdk.Address, coins sdk.Coins) sdk.Msg { input := bank.NewInput(from, coins) output := bank.NewOutput(to, coins) - msg := bank.NewSendMsg([]bank.Input{input}, []bank.Output{output}) + msg := bank.NewMsgSend([]bank.Input{input}, []bank.Output{output}) return msg } diff --git a/x/bank/errors.go b/x/bank/errors.go index d7c7e9748..bf2a3ef26 100644 --- a/x/bank/errors.go +++ b/x/bank/errors.go @@ -5,7 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// Coin errors reserve 100 ~ 199. +// Bank errors reserve 100 ~ 199. const ( DefaultCodespace sdk.CodespaceType = 2 diff --git a/x/bank/handler.go b/x/bank/handler.go index 8eca94a86..a50b0afcf 100644 --- a/x/bank/handler.go +++ b/x/bank/handler.go @@ -7,13 +7,13 @@ import ( ) // NewHandler returns a handler for "bank" type messages. -func NewHandler(ck CoinKeeper) sdk.Handler { +func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { switch msg := msg.(type) { - case SendMsg: - return handleSendMsg(ctx, ck, msg) - case IssueMsg: - return handleIssueMsg(ctx, ck, msg) + case MsgSend: + return handleMsgSend(ctx, k, msg) + case MsgIssue: + return handleMsgIssue(ctx, k, msg) default: errMsg := "Unrecognized bank Msg type: " + reflect.TypeOf(msg).Name() return sdk.ErrUnknownRequest(errMsg).Result() @@ -21,11 +21,11 @@ func NewHandler(ck CoinKeeper) sdk.Handler { } } -// Handle SendMsg. -func handleSendMsg(ctx sdk.Context, ck CoinKeeper, msg SendMsg) sdk.Result { +// Handle MsgSend. +func handleMsgSend(ctx sdk.Context, k Keeper, msg MsgSend) sdk.Result { // NOTE: totalIn == totalOut should already have been checked - err := ck.InputOutputCoins(ctx, msg.Inputs, msg.Outputs) + err := k.InputOutputCoins(ctx, msg.Inputs, msg.Outputs) if err != nil { return err.Result() } @@ -34,7 +34,7 @@ func handleSendMsg(ctx sdk.Context, ck CoinKeeper, msg SendMsg) sdk.Result { return sdk.Result{} // TODO } -// Handle IssueMsg. -func handleIssueMsg(ctx sdk.Context, ck CoinKeeper, msg IssueMsg) sdk.Result { +// Handle MsgIssue. +func handleMsgIssue(ctx sdk.Context, k Keeper, msg MsgIssue) sdk.Result { panic("not implemented yet") } diff --git a/x/bank/keeper.go b/x/bank/keeper.go index a5fabdbb0..d1fdeaea0 100644 --- a/x/bank/keeper.go +++ b/x/bank/keeper.go @@ -6,7 +6,106 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -const moduleName = "bank" +// Keeper manages transfers between accounts +type Keeper struct { + am sdk.AccountMapper +} + +// NewKeeper returns a new Keeper +func NewKeeper(am sdk.AccountMapper) Keeper { + return Keeper{am: am} +} + +// GetCoins returns the coins at the addr. +func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins { + return getCoins(ctx, keeper.am, addr) +} + +// SetCoins sets the coins at the addr. +func (keeper Keeper) SetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Error { + return setCoins(ctx, keeper.am, addr, amt) +} + +// HasCoins returns whether or not an account has at least amt coins. +func (keeper Keeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool { + return hasCoins(ctx, keeper.am, addr, amt) +} + +// SubtractCoins subtracts amt from the coins at the addr. +func (keeper Keeper) SubtractCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) { + return subtractCoins(ctx, keeper.am, addr, amt) +} + +// AddCoins adds amt to the coins at the addr. +func (keeper Keeper) AddCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) { + return addCoins(ctx, keeper.am, addr, amt) +} + +// SendCoins moves coins from one account to another +func (keeper Keeper) SendCoins(ctx sdk.Context, fromAddr sdk.Address, toAddr sdk.Address, amt sdk.Coins) sdk.Error { + return sendCoins(ctx, keeper.am, fromAddr, toAddr, amt) +} + +// InputOutputCoins handles a list of inputs and outputs +func (keeper Keeper) InputOutputCoins(ctx sdk.Context, inputs []Input, outputs []Output) sdk.Error { + return inputOutputCoins(ctx, keeper.am, inputs, outputs) +} + +//______________________________________________________________________________________________ + +// SendKeeper only allows transfers between accounts, without the possibility of creating coins +type SendKeeper struct { + am sdk.AccountMapper +} + +// NewSendKeeper returns a new Keeper +func NewSendKeeper(am sdk.AccountMapper) SendKeeper { + return SendKeeper{am: am} +} + +// GetCoins returns the coins at the addr. +func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins { + return getCoins(ctx, keeper.am, addr) +} + +// HasCoins returns whether or not an account has at least amt coins. +func (keeper SendKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool { + return hasCoins(ctx, keeper.am, addr, amt) +} + +// SendCoins moves coins from one account to another +func (keeper SendKeeper) SendCoins(ctx sdk.Context, fromAddr sdk.Address, toAddr sdk.Address, amt sdk.Coins) sdk.Error { + return sendCoins(ctx, keeper.am, fromAddr, toAddr, amt) +} + +// InputOutputCoins handles a list of inputs and outputs +func (keeper SendKeeper) InputOutputCoins(ctx sdk.Context, inputs []Input, outputs []Output) sdk.Error { + return inputOutputCoins(ctx, keeper.am, inputs, outputs) +} + +//______________________________________________________________________________________________ + +// ViewKeeper only allows reading of balances +type ViewKeeper struct { + am sdk.AccountMapper +} + +// NewViewKeeper returns a new Keeper +func NewViewKeeper(am sdk.AccountMapper) ViewKeeper { + return ViewKeeper{am: am} +} + +// GetCoins returns the coins at the addr. +func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins { + return getCoins(ctx, keeper.am, addr) +} + +// HasCoins returns whether or not an account has at least amt coins. +func (keeper ViewKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool { + return hasCoins(ctx, keeper.am, addr, amt) +} + +//______________________________________________________________________________________________ func getCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address) sdk.Coins { acc := am.GetAccount(ctx, addr) @@ -88,102 +187,3 @@ func inputOutputCoins(ctx sdk.Context, am sdk.AccountMapper, inputs []Input, out return nil } - -// CoinKeeper manages transfers between accounts -type CoinKeeper struct { - am sdk.AccountMapper -} - -// NewCoinKeeper returns a new CoinKeeper -func NewCoinKeeper(am sdk.AccountMapper) CoinKeeper { - return CoinKeeper{am: am} -} - -// GetCoins returns the coins at the addr. -func (keeper CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins { - return getCoins(ctx, keeper.am, addr) -} - -// SetCoins sets the coins at the addr. -func (keeper CoinKeeper) SetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Error { - return setCoins(ctx, keeper.am, addr, amt) -} - -// HasCoins returns whether or not an account has at least amt coins. -func (keeper CoinKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool { - return hasCoins(ctx, keeper.am, addr, amt) -} - -// SubtractCoins subtracts amt from the coins at the addr. -func (keeper CoinKeeper) SubtractCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) { - return subtractCoins(ctx, keeper.am, addr, amt) -} - -// AddCoins adds amt to the coins at the addr. -func (keeper CoinKeeper) AddCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) { - return addCoins(ctx, keeper.am, addr, amt) -} - -// SendCoins moves coins from one account to another -func (keeper CoinKeeper) SendCoins(ctx sdk.Context, fromAddr sdk.Address, toAddr sdk.Address, amt sdk.Coins) sdk.Error { - return sendCoins(ctx, keeper.am, fromAddr, toAddr, amt) -} - -// InputOutputCoins handles a list of inputs and outputs -func (keeper CoinKeeper) InputOutputCoins(ctx sdk.Context, inputs []Input, outputs []Output) sdk.Error { - return inputOutputCoins(ctx, keeper.am, inputs, outputs) -} - -// -------------------------------------------------- - -// SendKeeper only allows transfers between accounts, without the possibility of creating coins -type SendKeeper struct { - am sdk.AccountMapper -} - -// NewSendKeeper returns a new CoinKeeper -func NewSendKeeper(am sdk.AccountMapper) SendKeeper { - return SendKeeper{am: am} -} - -// GetCoins returns the coins at the addr. -func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins { - return getCoins(ctx, keeper.am, addr) -} - -// HasCoins returns whether or not an account has at least amt coins. -func (keeper SendKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool { - return hasCoins(ctx, keeper.am, addr, amt) -} - -// SendCoins moves coins from one account to another -func (keeper SendKeeper) SendCoins(ctx sdk.Context, fromAddr sdk.Address, toAddr sdk.Address, amt sdk.Coins) sdk.Error { - return sendCoins(ctx, keeper.am, fromAddr, toAddr, amt) -} - -// InputOutputCoins handles a list of inputs and outputs -func (keeper SendKeeper) InputOutputCoins(ctx sdk.Context, inputs []Input, outputs []Output) sdk.Error { - return inputOutputCoins(ctx, keeper.am, inputs, outputs) -} - -// -------------------------------------------------- - -// ViewKeeper only allows reading of balances -type ViewKeeper struct { - am sdk.AccountMapper -} - -// NewViewKeeper returns a new CoinKeeper -func NewViewKeeper(am sdk.AccountMapper) ViewKeeper { - return ViewKeeper{am: am} -} - -// GetCoins returns the coins at the addr. -func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins { - return getCoins(ctx, keeper.am, addr) -} - -// HasCoins returns whether or not an account has at least amt coins. -func (keeper ViewKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool { - return hasCoins(ctx, keeper.am, addr, amt) -} diff --git a/x/bank/keeper_test.go b/x/bank/keeper_test.go index 1e160d472..7db9c275d 100644 --- a/x/bank/keeper_test.go +++ b/x/bank/keeper_test.go @@ -24,7 +24,7 @@ func setupMultiStore() (sdk.MultiStore, *sdk.KVStoreKey) { return ms, authKey } -func TestCoinKeeper(t *testing.T) { +func TestKeeper(t *testing.T) { ms, authKey := setupMultiStore() cdc := wire.NewCodec() @@ -32,7 +32,7 @@ func TestCoinKeeper(t *testing.T) { ctx := sdk.NewContext(ms, abci.Header{}, false, nil) accountMapper := auth.NewAccountMapper(cdc, authKey, &auth.BaseAccount{}) - coinKeeper := NewCoinKeeper(accountMapper) + coinKeeper := NewKeeper(accountMapper) addr := sdk.Address([]byte("addr1")) addr2 := sdk.Address([]byte("addr2")) @@ -118,7 +118,7 @@ func TestSendKeeper(t *testing.T) { ctx := sdk.NewContext(ms, abci.Header{}, false, nil) accountMapper := auth.NewAccountMapper(cdc, authKey, &auth.BaseAccount{}) - coinKeeper := NewCoinKeeper(accountMapper) + coinKeeper := NewKeeper(accountMapper) sendKeeper := NewSendKeeper(accountMapper) addr := sdk.Address([]byte("addr1")) @@ -187,7 +187,7 @@ func TestViewKeeper(t *testing.T) { ctx := sdk.NewContext(ms, abci.Header{}, false, nil) accountMapper := auth.NewAccountMapper(cdc, authKey, &auth.BaseAccount{}) - coinKeeper := NewCoinKeeper(accountMapper) + coinKeeper := NewKeeper(accountMapper) viewKeeper := NewViewKeeper(accountMapper) addr := sdk.Address([]byte("addr1")) diff --git a/x/bank/msgs.go b/x/bank/msgs.go index c0f2ad46a..0b0ea471e 100644 --- a/x/bank/msgs.go +++ b/x/bank/msgs.go @@ -2,29 +2,28 @@ package bank import ( "encoding/json" - "fmt" sdk "github.com/cosmos/cosmos-sdk/types" ) -// SendMsg - high level transaction of the coin module -type SendMsg struct { +// MsgSend - high level transaction of the coin module +type MsgSend struct { Inputs []Input `json:"inputs"` Outputs []Output `json:"outputs"` } -var _ sdk.Msg = SendMsg{} +var _ sdk.Msg = MsgSend{} -// NewSendMsg - construct arbitrary multi-in, multi-out send msg. -func NewSendMsg(in []Input, out []Output) SendMsg { - return SendMsg{Inputs: in, Outputs: out} +// NewMsgSend - construct arbitrary multi-in, multi-out send msg. +func NewMsgSend(in []Input, out []Output) MsgSend { + return MsgSend{Inputs: in, Outputs: out} } // Implements Msg. -func (msg SendMsg) Type() string { return "bank" } // TODO: "bank/send" +func (msg MsgSend) Type() string { return "bank" } // TODO: "bank/send" // Implements Msg. -func (msg SendMsg) ValidateBasic() sdk.Error { +func (msg MsgSend) ValidateBasic() sdk.Error { // this just makes sure all the inputs and outputs are properly formatted, // not that they actually have the money inside if len(msg.Inputs) == 0 { @@ -54,17 +53,13 @@ func (msg SendMsg) ValidateBasic() sdk.Error { return nil } -func (msg SendMsg) String() string { - return fmt.Sprintf("SendMsg{%v->%v}", msg.Inputs, msg.Outputs) -} - // Implements Msg. -func (msg SendMsg) Get(key interface{}) (value interface{}) { +func (msg MsgSend) Get(key interface{}) (value interface{}) { return nil } // Implements Msg. -func (msg SendMsg) GetSignBytes() []byte { +func (msg MsgSend) GetSignBytes() []byte { b, err := json.Marshal(msg) // XXX: ensure some canonical form if err != nil { panic(err) @@ -73,7 +68,7 @@ func (msg SendMsg) GetSignBytes() []byte { } // Implements Msg. -func (msg SendMsg) GetSigners() []sdk.Address { +func (msg MsgSend) GetSigners() []sdk.Address { addrs := make([]sdk.Address, len(msg.Inputs)) for i, in := range msg.Inputs { addrs[i] = in.Address @@ -82,24 +77,24 @@ func (msg SendMsg) GetSigners() []sdk.Address { } //---------------------------------------- -// IssueMsg +// MsgIssue -// IssueMsg - high level transaction of the coin module -type IssueMsg struct { +// MsgIssue - high level transaction of the coin module +type MsgIssue struct { Banker sdk.Address `json:"banker"` Outputs []Output `json:"outputs"` } -// NewIssueMsg - construct arbitrary multi-in, multi-out send msg. -func NewIssueMsg(banker sdk.Address, out []Output) IssueMsg { - return IssueMsg{Banker: banker, Outputs: out} +// NewMsgIssue - construct arbitrary multi-in, multi-out send msg. +func NewMsgIssue(banker sdk.Address, out []Output) MsgIssue { + return MsgIssue{Banker: banker, Outputs: out} } // Implements Msg. -func (msg IssueMsg) Type() string { return "bank" } // TODO: "bank/issue" +func (msg MsgIssue) Type() string { return "bank" } // TODO: "bank/issue" // Implements Msg. -func (msg IssueMsg) ValidateBasic() sdk.Error { +func (msg MsgIssue) ValidateBasic() sdk.Error { // XXX if len(msg.Outputs) == 0 { return ErrNoOutputs(DefaultCodespace).Trace("") @@ -112,17 +107,13 @@ func (msg IssueMsg) ValidateBasic() sdk.Error { return nil } -func (msg IssueMsg) String() string { - return fmt.Sprintf("IssueMsg{%v#%v}", msg.Banker, msg.Outputs) -} - // Implements Msg. -func (msg IssueMsg) Get(key interface{}) (value interface{}) { +func (msg MsgIssue) Get(key interface{}) (value interface{}) { return nil } // Implements Msg. -func (msg IssueMsg) GetSignBytes() []byte { +func (msg MsgIssue) GetSignBytes() []byte { b, err := json.Marshal(msg) // XXX: ensure some canonical form if err != nil { panic(err) @@ -131,7 +122,7 @@ func (msg IssueMsg) GetSignBytes() []byte { } // Implements Msg. -func (msg IssueMsg) GetSigners() []sdk.Address { +func (msg MsgIssue) GetSigners() []sdk.Address { return []sdk.Address{msg.Banker} } @@ -158,11 +149,7 @@ func (in Input) ValidateBasic() sdk.Error { return nil } -func (in Input) String() string { - return fmt.Sprintf("Input{%v,%v}", in.Address, in.Coins) -} - -// NewInput - create a transaction input, used with SendMsg +// NewInput - create a transaction input, used with MsgSend func NewInput(addr sdk.Address, coins sdk.Coins) Input { input := Input{ Address: addr, @@ -194,11 +181,7 @@ func (out Output) ValidateBasic() sdk.Error { return nil } -func (out Output) String() string { - return fmt.Sprintf("Output{%v,%v}", out.Address, out.Coins) -} - -// NewOutput - create a transaction output, used with SendMsg +// NewOutput - create a transaction output, used with MsgSend func NewOutput(addr sdk.Address, coins sdk.Coins) Output { output := Output{ Address: addr, diff --git a/x/bank/msgs_test.go b/x/bank/msgs_test.go index b158405d9..d3e1ef4f6 100644 --- a/x/bank/msgs_test.go +++ b/x/bank/msgs_test.go @@ -9,14 +9,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -func TestNewSendMsg(t *testing.T) {} +func TestNewMsgSend(t *testing.T) {} -func TestSendMsgType(t *testing.T) { - // Construct a SendMsg +func TestMsgSendType(t *testing.T) { + // Construct a MsgSend addr1 := sdk.Address([]byte("input")) addr2 := sdk.Address([]byte("output")) coins := sdk.Coins{{"atom", 10}} - var msg = SendMsg{ + var msg = MsgSend{ Inputs: []Input{NewInput(addr1, coins)}, Outputs: []Output{NewOutput(addr2, coins)}, } @@ -109,7 +109,7 @@ func TestOutputValidation(t *testing.T) { } } -func TestSendMsgValidation(t *testing.T) { +func TestMsgSendValidation(t *testing.T) { addr1 := sdk.Address([]byte{1, 2}) addr2 := sdk.Address([]byte{7, 8}) atom123 := sdk.Coins{{"atom", 123}} @@ -128,40 +128,40 @@ func TestSendMsgValidation(t *testing.T) { cases := []struct { valid bool - tx SendMsg + tx MsgSend }{ - {false, SendMsg{}}, // no input or output - {false, SendMsg{Inputs: []Input{input1}}}, // just input - {false, SendMsg{Outputs: []Output{output1}}}, // just ouput - {false, SendMsg{ + {false, MsgSend{}}, // no input or output + {false, MsgSend{Inputs: []Input{input1}}}, // just input + {false, MsgSend{Outputs: []Output{output1}}}, // just ouput + {false, MsgSend{ Inputs: []Input{NewInput(emptyAddr, atom123)}, // invalid input Outputs: []Output{output1}}}, - {false, SendMsg{ + {false, MsgSend{ Inputs: []Input{input1}, Outputs: []Output{{emptyAddr, atom123}}}, // invalid ouput }, - {false, SendMsg{ + {false, MsgSend{ Inputs: []Input{input1}, Outputs: []Output{output2}}, // amounts dont match }, - {false, SendMsg{ + {false, MsgSend{ Inputs: []Input{input1}, Outputs: []Output{output3}}, // amounts dont match }, - {false, SendMsg{ + {false, MsgSend{ Inputs: []Input{input1}, Outputs: []Output{outputMulti}}, // amounts dont match }, - {false, SendMsg{ + {false, MsgSend{ Inputs: []Input{input2}, Outputs: []Output{output1}}, // amounts dont match }, - {true, SendMsg{ + {true, MsgSend{ Inputs: []Input{input1}, Outputs: []Output{output1}}, }, - {true, SendMsg{ + {true, MsgSend{ Inputs: []Input{input1, input2}, Outputs: []Output{outputMulti}}, }, @@ -177,29 +177,11 @@ func TestSendMsgValidation(t *testing.T) { } } -func TestSendMsgString(t *testing.T) { - // Construct a SendMsg - addr1String := "input" - addr2String := "output" - addr1 := sdk.Address([]byte(addr1String)) - addr2 := sdk.Address([]byte(addr2String)) - coins := sdk.Coins{{"atom", 10}} - var msg = SendMsg{ - Inputs: []Input{NewInput(addr1, coins)}, - Outputs: []Output{NewOutput(addr2, coins)}, - } - - res := msg.String() - expected := fmt.Sprintf("SendMsg{[Input{%X,10atom}]->[Output{%X,10atom}]}", addr1String, addr2String) - // TODO some failures for bad results - assert.Equal(t, expected, res) -} - -func TestSendMsgGet(t *testing.T) { +func TestMsgSendGet(t *testing.T) { addr1 := sdk.Address([]byte("input")) addr2 := sdk.Address([]byte("output")) coins := sdk.Coins{{"atom", 10}} - var msg = SendMsg{ + var msg = MsgSend{ Inputs: []Input{NewInput(addr1, coins)}, Outputs: []Output{NewOutput(addr2, coins)}, } @@ -207,11 +189,11 @@ func TestSendMsgGet(t *testing.T) { assert.Nil(t, res) } -func TestSendMsgGetSignBytes(t *testing.T) { +func TestMsgSendGetSignBytes(t *testing.T) { addr1 := sdk.Address([]byte("input")) addr2 := sdk.Address([]byte("output")) coins := sdk.Coins{{"atom", 10}} - var msg = SendMsg{ + var msg = MsgSend{ Inputs: []Input{NewInput(addr1, coins)}, Outputs: []Output{NewOutput(addr2, coins)}, } @@ -220,8 +202,8 @@ func TestSendMsgGetSignBytes(t *testing.T) { assert.Equal(t, string(res), `{"inputs":[{"address":"696E707574","coins":[{"denom":"atom","amount":10}]}],"outputs":[{"address":"6F7574707574","coins":[{"denom":"atom","amount":10}]}]}`) } -func TestSendMsgGetSigners(t *testing.T) { - var msg = SendMsg{ +func TestMsgSendGetSigners(t *testing.T) { + var msg = MsgSend{ Inputs: []Input{ NewInput(sdk.Address([]byte("input1")), nil), NewInput(sdk.Address([]byte("input2")), nil), @@ -235,7 +217,7 @@ func TestSendMsgGetSigners(t *testing.T) { /* // what to do w/ this test? -func TestSendMsgSigners(t *testing.T) { +func TestMsgSendSigners(t *testing.T) { signers := []sdk.Address{ {1, 2, 3}, {4, 5, 6}, @@ -247,24 +229,24 @@ func TestSendMsgSigners(t *testing.T) { for i, signer := range signers { inputs[i] = NewInput(signer, someCoins) } - tx := NewSendMsg(inputs, nil) + tx := NewMsgSend(inputs, nil) assert.Equal(t, signers, tx.Signers()) } */ // ---------------------------------------- -// IssueMsg Tests +// MsgIssue Tests -func TestNewIssueMsg(t *testing.T) { +func TestNewMsgIssue(t *testing.T) { // TODO } -func TestIssueMsgType(t *testing.T) { - // Construct an IssueMsg +func TestMsgIssueType(t *testing.T) { + // Construct an MsgIssue addr := sdk.Address([]byte("loan-from-bank")) coins := sdk.Coins{{"atom", 10}} - var msg = IssueMsg{ + var msg = MsgIssue{ Banker: sdk.Address([]byte("input")), Outputs: []Output{NewOutput(addr, coins)}, } @@ -273,29 +255,14 @@ func TestIssueMsgType(t *testing.T) { assert.Equal(t, msg.Type(), "bank") } -func TestIssueMsgValidation(t *testing.T) { +func TestMsgIssueValidation(t *testing.T) { // TODO } -func TestIssueMsgString(t *testing.T) { - addrString := "loan-from-bank" - bankerString := "input" - // Construct a IssueMsg - addr := sdk.Address([]byte(addrString)) - coins := sdk.Coins{{"atom", 10}} - var msg = IssueMsg{ - Banker: sdk.Address([]byte(bankerString)), - Outputs: []Output{NewOutput(addr, coins)}, - } - res := msg.String() - expected := fmt.Sprintf("IssueMsg{%X#[Output{%X,10atom}]}", bankerString, addrString) - assert.Equal(t, expected, res) -} - -func TestIssueMsgGet(t *testing.T) { +func TestMsgIssueGet(t *testing.T) { addr := sdk.Address([]byte("loan-from-bank")) coins := sdk.Coins{{"atom", 10}} - var msg = IssueMsg{ + var msg = MsgIssue{ Banker: sdk.Address([]byte("input")), Outputs: []Output{NewOutput(addr, coins)}, } @@ -303,10 +270,10 @@ func TestIssueMsgGet(t *testing.T) { assert.Nil(t, res) } -func TestIssueMsgGetSignBytes(t *testing.T) { +func TestMsgIssueGetSignBytes(t *testing.T) { addr := sdk.Address([]byte("loan-from-bank")) coins := sdk.Coins{{"atom", 10}} - var msg = IssueMsg{ + var msg = MsgIssue{ Banker: sdk.Address([]byte("input")), Outputs: []Output{NewOutput(addr, coins)}, } @@ -315,8 +282,8 @@ func TestIssueMsgGetSignBytes(t *testing.T) { assert.Equal(t, string(res), `{"banker":"696E707574","outputs":[{"address":"6C6F616E2D66726F6D2D62616E6B","coins":[{"denom":"atom","amount":10}]}]}`) } -func TestIssueMsgGetSigners(t *testing.T) { - var msg = IssueMsg{ +func TestMsgIssueGetSigners(t *testing.T) { + var msg = MsgIssue{ Banker: sdk.Address([]byte("onlyone")), } res := msg.GetSigners() diff --git a/x/bank/rest/root.go b/x/bank/rest/root.go deleted file mode 100644 index 4534482a9..000000000 --- a/x/bank/rest/root.go +++ /dev/null @@ -1,14 +0,0 @@ -package rest - -import ( - "github.com/gorilla/mux" - - keys "github.com/tendermint/go-crypto/keys" - - "github.com/cosmos/cosmos-sdk/wire" -) - -// RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { - r.HandleFunc("/accounts/{address}/send", SendRequestHandler(cdc, kb)).Methods("POST") -} diff --git a/x/bank/rest/sendtx.go b/x/bank/rest/sendtx.go index b1f8516f3..eec487a3d 100644 --- a/x/bank/rest/sendtx.go +++ b/x/bank/rest/sendtx.go @@ -15,6 +15,11 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank/commands" ) +// RegisterRoutes - Central function to define routes that get registered by the main application +func RegisterRoutes(r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { + r.HandleFunc("/accounts/{address}/send", SendRequestHandler(cdc, kb)).Methods("POST") +} + type sendBody struct { // fees is not used currently // Fees sdk.Coin `json="fees"` @@ -27,7 +32,6 @@ type sendBody struct { // SendRequestHandler - http request handler to send coins to a address func SendRequestHandler(cdc *wire.Codec, kb keys.Keybase) func(http.ResponseWriter, *http.Request) { - c := commands.Commander{cdc} ctx := context.NewCoreContextFromViper() return func(w http.ResponseWriter, r *http.Request) { // collect data @@ -73,7 +77,7 @@ func SendRequestHandler(cdc *wire.Codec, kb keys.Keybase) func(http.ResponseWrit // sign ctx = ctx.WithSequence(m.Sequence) - txBytes, err := ctx.SignAndBuild(m.LocalAccountName, m.Password, msg, c.Cdc) + txBytes, err := ctx.SignAndBuild(m.LocalAccountName, m.Password, msg, cdc) if err != nil { w.WriteHeader(http.StatusUnauthorized) w.Write([]byte(err.Error())) diff --git a/x/bank/wire.go b/x/bank/wire.go index c53f06564..fdb6c252b 100644 --- a/x/bank/wire.go +++ b/x/bank/wire.go @@ -6,6 +6,6 @@ import ( // Register concrete types on wire codec func RegisterWire(cdc *wire.Codec) { - cdc.RegisterConcrete(SendMsg{}, "cosmos-sdk/Send", nil) - cdc.RegisterConcrete(IssueMsg{}, "cosmos-sdk/Issue", nil) + cdc.RegisterConcrete(MsgSend{}, "cosmos-sdk/Send", nil) + cdc.RegisterConcrete(MsgIssue{}, "cosmos-sdk/Issue", nil) } diff --git a/x/ibc/commands/ibctx.go b/x/ibc/commands/ibctx.go index d17b40b21..1fc53b7e6 100644 --- a/x/ibc/commands/ibctx.go +++ b/x/ibc/commands/ibctx.go @@ -23,53 +23,42 @@ const ( flagChain = "chain" ) +// IBC transfer command func IBCTransferCmd(cdc *wire.Codec) *cobra.Command { - cmdr := sendCommander{cdc} cmd := &cobra.Command{ - Use: "transfer", - RunE: cmdr.sendIBCTransfer, + Use: "transfer", + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) + + // get the from address + from, err := ctx.GetFromAddress() + if err != nil { + return err + } + + // build the message + msg, err := buildMsg(from) + if err != nil { + return err + } + + // get password + res, err := ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, msg, cdc) + if err != nil { + return err + } + + fmt.Printf("Committed at block %d. Hash: %s\n", res.Height, res.Hash.String()) + return nil + }, } + cmd.Flags().String(flagTo, "", "Address to send coins") cmd.Flags().String(flagAmount, "", "Amount of coins to send") cmd.Flags().String(flagChain, "", "Destination chain to send coins") return cmd } -type sendCommander struct { - cdc *wire.Codec -} - -func (c sendCommander) sendIBCTransfer(cmd *cobra.Command, args []string) error { - ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(c.cdc)) - - // get the from address - from, err := ctx.GetFromAddress() - if err != nil { - return err - } - - // build the message - msg, err := buildMsg(from) - if err != nil { - return err - } - - // default to next sequence number if none provided - ctx, err = context.EnsureSequence(ctx) - if err != nil { - return err - } - - // get password - res, err := ctx.SignBuildBroadcast(ctx.FromAddressName, msg, c.cdc) - if err != nil { - return err - } - - fmt.Printf("Committed at block %d. Hash: %s\n", res.Height, res.Hash.String()) - return nil -} - func buildMsg(from sdk.Address) (sdk.Msg, error) { amount := viper.GetString(flagAmount) coins, err := sdk.ParseCoins(amount) diff --git a/x/ibc/commands/relay.go b/x/ibc/commands/relay.go index d652e306f..d772735bb 100644 --- a/x/ibc/commands/relay.go +++ b/x/ibc/commands/relay.go @@ -18,6 +18,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/ibc" ) +// flags const ( FlagFromChainID = "from-chain-id" FlagFromChainNode = "from-chain-node" @@ -35,6 +36,7 @@ type relayCommander struct { logger log.Logger } +// IBC relay command func IBCRelayCmd(cdc *wire.Codec) *cobra.Command { cmdr := relayCommander{ cdc: cdc, @@ -91,6 +93,7 @@ func (c relayCommander) loop(fromChainID, fromChainNode, toChainID, toChainNode } ingressKey := ibc.IngressSequenceKey(fromChainID) + OUTER: for { time.Sleep(5 * time.Second) @@ -111,7 +114,7 @@ OUTER: egressLengthbz, err := query(fromChainNode, lengthKey, c.ibcStore) if err != nil { c.logger.Error("Error querying outgoing packet list length", "err", err) - continue OUTER + continue OUTER //TODO replace with continue (I think it should just to the correct place where OUTER is now) } var egressLength int64 if egressLengthbz == nil { @@ -129,14 +132,14 @@ OUTER: egressbz, err := query(fromChainNode, ibc.EgressKey(toChainID, i), c.ibcStore) if err != nil { c.logger.Error("Error querying egress packet", "err", err) - continue OUTER + continue OUTER // TODO replace to break, will break first loop then send back to the beginning (aka OUTER) } err = c.broadcastTx(seq, toChainNode, c.refine(egressbz, i, passphrase)) seq++ if err != nil { c.logger.Error("Error broadcasting ingress packet", "err", err) - continue OUTER + continue OUTER // TODO replace to break, will break first loop then send back to the beginning (aka OUTER) } c.logger.Info("Relayed IBC packet", "number", i) diff --git a/x/ibc/errors.go b/x/ibc/errors.go index 3c52bed7b..60a141eba 100644 --- a/x/ibc/errors.go +++ b/x/ibc/errors.go @@ -4,6 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// IBC errors reserve 200 ~ 299. const ( DefaultCodespace sdk.CodespaceType = 3 @@ -24,10 +25,10 @@ func codeToDefaultMsg(code sdk.CodeType) string { } } +// nolint func ErrInvalidSequence(codespace sdk.CodespaceType) sdk.Error { return newError(codespace, CodeInvalidSequence, "") } - func ErrIdenticalChains(codespace sdk.CodespaceType) sdk.Error { return newError(codespace, CodeIdenticalChains, "") } @@ -43,7 +44,6 @@ func newError(codespace sdk.CodespaceType, code sdk.CodeType, msg string) sdk.Er func msgOrDefaultMsg(msg string, code sdk.CodeType) string { if msg != "" { return msg - } else { - return codeToDefaultMsg(code) } + return codeToDefaultMsg(code) } diff --git a/x/ibc/handler.go b/x/ibc/handler.go index dcd00359f..46cbf1e30 100644 --- a/x/ibc/handler.go +++ b/x/ibc/handler.go @@ -7,7 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank" ) -func NewHandler(ibcm IBCMapper, ck bank.CoinKeeper) sdk.Handler { +func NewHandler(ibcm Mapper, ck bank.Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { switch msg := msg.(type) { case IBCTransferMsg: @@ -22,7 +22,7 @@ func NewHandler(ibcm IBCMapper, ck bank.CoinKeeper) sdk.Handler { } // IBCTransferMsg deducts coins from the account and creates an egress IBC packet. -func handleIBCTransferMsg(ctx sdk.Context, ibcm IBCMapper, ck bank.CoinKeeper, msg IBCTransferMsg) sdk.Result { +func handleIBCTransferMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCTransferMsg) sdk.Result { packet := msg.IBCPacket _, err := ck.SubtractCoins(ctx, packet.SrcAddr, packet.Coins) @@ -39,7 +39,7 @@ func handleIBCTransferMsg(ctx sdk.Context, ibcm IBCMapper, ck bank.CoinKeeper, m } // IBCReceiveMsg adds coins to the destination address and creates an ingress IBC packet. -func handleIBCReceiveMsg(ctx sdk.Context, ibcm IBCMapper, ck bank.CoinKeeper, msg IBCReceiveMsg) sdk.Result { +func handleIBCReceiveMsg(ctx sdk.Context, ibcm Mapper, ck bank.Keeper, msg IBCReceiveMsg) sdk.Result { packet := msg.IBCPacket seq := ibcm.GetIngressSequence(ctx, packet.SrcChain) diff --git a/x/ibc/ibc_test.go b/x/ibc/ibc_test.go index 1fc724e54..61b9182f1 100644 --- a/x/ibc/ibc_test.go +++ b/x/ibc/ibc_test.go @@ -16,7 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank" ) -// AccountMapper(/CoinKeeper) and IBCMapper should use different StoreKey later +// AccountMapper(/Keeper) and IBCMapper should use different StoreKey later func defaultContext(key sdk.StoreKey) sdk.Context { db := dbm.NewMemDB() @@ -31,7 +31,7 @@ func newAddress() crypto.Address { return crypto.GenPrivKeyEd25519().PubKey().Address() } -func getCoins(ck bank.CoinKeeper, ctx sdk.Context, addr crypto.Address) (sdk.Coins, sdk.Error) { +func getCoins(ck bank.Keeper, ctx sdk.Context, addr crypto.Address) (sdk.Coins, sdk.Error) { zero := sdk.Coins(nil) return ck.AddCoins(ctx, addr, zero) } @@ -41,8 +41,8 @@ func makeCodec() *wire.Codec { // Register Msgs cdc.RegisterInterface((*sdk.Msg)(nil), nil) - cdc.RegisterConcrete(bank.SendMsg{}, "test/ibc/Send", nil) - cdc.RegisterConcrete(bank.IssueMsg{}, "test/ibc/Issue", nil) + cdc.RegisterConcrete(bank.MsgSend{}, "test/ibc/Send", nil) + cdc.RegisterConcrete(bank.MsgIssue{}, "test/ibc/Issue", nil) cdc.RegisterConcrete(IBCTransferMsg{}, "test/ibc/IBCTransferMsg", nil) cdc.RegisterConcrete(IBCReceiveMsg{}, "test/ibc/IBCReceiveMsg", nil) @@ -61,7 +61,7 @@ func TestIBC(t *testing.T) { ctx := defaultContext(key) am := auth.NewAccountMapper(cdc, key, &auth.BaseAccount{}) - ck := bank.NewCoinKeeper(am) + ck := bank.NewKeeper(am) src := newAddress() dest := newAddress() @@ -73,7 +73,7 @@ func TestIBC(t *testing.T) { assert.Nil(t, err) assert.Equal(t, mycoins, coins) - ibcm := NewIBCMapper(cdc, key, DefaultCodespace) + ibcm := NewMapper(cdc, key, DefaultCodespace) h := NewHandler(ibcm, ck) packet := IBCPacket{ SrcAddr: src, diff --git a/x/ibc/mapper.go b/x/ibc/mapper.go index d3ecc779d..06631179b 100644 --- a/x/ibc/mapper.go +++ b/x/ibc/mapper.go @@ -7,17 +7,18 @@ import ( wire "github.com/cosmos/cosmos-sdk/wire" ) -type IBCMapper struct { +// IBC Mapper +type Mapper struct { key sdk.StoreKey cdc *wire.Codec codespace sdk.CodespaceType } -// XXX: The IBCMapper should not take a CoinKeeper. Rather have the CoinKeeper -// take an IBCMapper. -func NewIBCMapper(cdc *wire.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) IBCMapper { +// XXX: The Mapper should not take a CoinKeeper. Rather have the CoinKeeper +// take an Mapper. +func NewMapper(cdc *wire.Codec, key sdk.StoreKey, codespace sdk.CodespaceType) Mapper { // XXX: How are these codecs supposed to work? - return IBCMapper{ + return Mapper{ key: key, cdc: cdc, codespace: codespace, @@ -28,7 +29,7 @@ func NewIBCMapper(cdc *wire.Codec, key sdk.StoreKey, codespace sdk.CodespaceType // only be invoked from another module directly and not through a user // transaction. // TODO: Handle invalid IBC packets and return errors. -func (ibcm IBCMapper) PostIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error { +func (ibcm Mapper) PostIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error { // write everything into the state store := ctx.KVStore(ibcm.key) index := ibcm.getEgressLength(store, packet.DestChain) @@ -52,7 +53,7 @@ func (ibcm IBCMapper) PostIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error // to the appropriate callbacks. // XXX: For now this handles all interactions with the CoinKeeper. // XXX: This needs to do some authentication checking. -func (ibcm IBCMapper) ReceiveIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error { +func (ibcm Mapper) ReceiveIBCPacket(ctx sdk.Context, packet IBCPacket) sdk.Error { return nil } @@ -74,7 +75,8 @@ func unmarshalBinaryPanic(cdc *wire.Codec, bz []byte, ptr interface{}) { } } -func (ibcm IBCMapper) GetIngressSequence(ctx sdk.Context, srcChain string) int64 { +// TODO add description +func (ibcm Mapper) GetIngressSequence(ctx sdk.Context, srcChain string) int64 { store := ctx.KVStore(ibcm.key) key := IngressSequenceKey(srcChain) @@ -90,7 +92,8 @@ func (ibcm IBCMapper) GetIngressSequence(ctx sdk.Context, srcChain string) int64 return res } -func (ibcm IBCMapper) SetIngressSequence(ctx sdk.Context, srcChain string, sequence int64) { +// TODO add description +func (ibcm Mapper) SetIngressSequence(ctx sdk.Context, srcChain string, sequence int64) { store := ctx.KVStore(ibcm.key) key := IngressSequenceKey(srcChain) @@ -99,7 +102,7 @@ func (ibcm IBCMapper) SetIngressSequence(ctx sdk.Context, srcChain string, seque } // Retrieves the index of the currently stored outgoing IBC packets. -func (ibcm IBCMapper) getEgressLength(store sdk.KVStore, destChain string) int64 { +func (ibcm Mapper) getEgressLength(store sdk.KVStore, destChain string) int64 { bz := store.Get(EgressLengthKey(destChain)) if bz == nil { zero := marshalBinaryPanic(ibcm.cdc, int64(0)) diff --git a/x/ibc/rest/root.go b/x/ibc/rest/root.go deleted file mode 100644 index 81e74d031..000000000 --- a/x/ibc/rest/root.go +++ /dev/null @@ -1,14 +0,0 @@ -package rest - -import ( - "github.com/gorilla/mux" - - keys "github.com/tendermint/go-crypto/keys" - - "github.com/cosmos/cosmos-sdk/wire" -) - -// RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { - r.HandleFunc("/ibc/{destchain}/{address}/send", TransferRequestHandler(cdc, kb)).Methods("POST") -} diff --git a/x/ibc/rest/transfer.go b/x/ibc/rest/transfer.go index 1317730e7..c0f70b517 100644 --- a/x/ibc/rest/transfer.go +++ b/x/ibc/rest/transfer.go @@ -11,10 +11,14 @@ 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/bank/commands" "github.com/cosmos/cosmos-sdk/x/ibc" ) +// RegisterRoutes - Central function to define routes that get registered by the main application +func RegisterRoutes(r *mux.Router, cdc *wire.Codec, kb keys.Keybase) { + r.HandleFunc("/ibc/{destchain}/{address}/send", TransferRequestHandler(cdc, kb)).Methods("POST") +} + type transferBody struct { // Fees sdk.Coin `json="fees"` Amount sdk.Coins `json:"amount"` @@ -27,7 +31,6 @@ type transferBody struct { // TransferRequestHandler - http request handler to transfer coins to a address // on a different chain via IBC func TransferRequestHandler(cdc *wire.Codec, kb keys.Keybase) func(http.ResponseWriter, *http.Request) { - c := commands.Commander{cdc} ctx := context.NewCoreContextFromViper() return func(w http.ResponseWriter, r *http.Request) { // collect data @@ -70,7 +73,7 @@ func TransferRequestHandler(cdc *wire.Codec, kb keys.Keybase) func(http.Response // sign ctx = ctx.WithSequence(m.Sequence) - txBytes, err := ctx.SignAndBuild(m.LocalAccountName, m.Password, msg, c.Cdc) + txBytes, err := ctx.SignAndBuild(m.LocalAccountName, m.Password, msg, cdc) if err != nil { w.WriteHeader(http.StatusUnauthorized) w.Write([]byte(err.Error())) diff --git a/x/ibc/types.go b/x/ibc/types.go index 2bf2c4267..6102a2a9f 100644 --- a/x/ibc/types.go +++ b/x/ibc/types.go @@ -9,6 +9,7 @@ import ( // ------------------------------ // IBCPacket +// nolint - TODO rename to Packet as IBCPacket stutters (golint) // IBCPacket defines a piece of data that can be send between two separate // blockchains. type IBCPacket struct { @@ -31,6 +32,7 @@ func NewIBCPacket(srcAddr sdk.Address, destAddr sdk.Address, coins sdk.Coins, } } +// validator the ibc packey func (ibcp IBCPacket) ValidateBasic() sdk.Error { if ibcp.SrcChain == ibcp.DestChain { return ErrIdenticalChains(DefaultCodespace).Trace("") @@ -44,19 +46,20 @@ func (ibcp IBCPacket) ValidateBasic() sdk.Error { // ---------------------------------- // IBCTransferMsg +// nolint - TODO rename to TransferMsg as folks will reference with ibc.TransferMsg // IBCTransferMsg defines how another module can send an IBCPacket. type IBCTransferMsg struct { IBCPacket } -func (msg IBCTransferMsg) Type() string { - return "ibc" -} +// nolint +func (msg IBCTransferMsg) Type() string { return "ibc" } +func (msg IBCTransferMsg) Get(key interface{}) interface{} { return nil } -func (msg IBCTransferMsg) Get(key interface{}) interface{} { - return nil -} +// x/bank/tx.go MsgSend.GetSigners() +func (msg IBCTransferMsg) GetSigners() []sdk.Address { return []sdk.Address{msg.SrcAddr} } +// get the sign bytes for ibc transfer message func (msg IBCTransferMsg) GetSignBytes() []byte { cdc := wire.NewCodec() bz, err := cdc.MarshalBinary(msg) @@ -66,18 +69,15 @@ func (msg IBCTransferMsg) GetSignBytes() []byte { return bz } +// validate ibc transfer message func (msg IBCTransferMsg) ValidateBasic() sdk.Error { return msg.IBCPacket.ValidateBasic() } -// x/bank/tx.go SendMsg.GetSigners() -func (msg IBCTransferMsg) GetSigners() []sdk.Address { - return []sdk.Address{msg.SrcAddr} -} - // ---------------------------------- // IBCReceiveMsg +// nolint - TODO rename to ReceiveMsg as folks will reference with ibc.ReceiveMsg // IBCReceiveMsg defines the message that a relayer uses to post an IBCPacket // to the destination chain. type IBCReceiveMsg struct { @@ -86,14 +86,15 @@ type IBCReceiveMsg struct { Sequence int64 } -func (msg IBCReceiveMsg) Type() string { - return "ibc" -} +// nolint +func (msg IBCReceiveMsg) Type() string { return "ibc" } +func (msg IBCReceiveMsg) Get(key interface{}) interface{} { return nil } +func (msg IBCReceiveMsg) ValidateBasic() sdk.Error { return msg.IBCPacket.ValidateBasic() } -func (msg IBCReceiveMsg) Get(key interface{}) interface{} { - return nil -} +// x/bank/tx.go MsgSend.GetSigners() +func (msg IBCReceiveMsg) GetSigners() []sdk.Address { return []sdk.Address{msg.Relayer} } +// get the sign bytes for ibc receive message func (msg IBCReceiveMsg) GetSignBytes() []byte { cdc := wire.NewCodec() bz, err := cdc.MarshalBinary(msg) @@ -102,12 +103,3 @@ func (msg IBCReceiveMsg) GetSignBytes() []byte { } return bz } - -func (msg IBCReceiveMsg) ValidateBasic() sdk.Error { - return msg.IBCPacket.ValidateBasic() -} - -// x/bank/tx.go SendMsg.GetSigners() -func (msg IBCReceiveMsg) GetSigners() []sdk.Address { - return []sdk.Address{msg.Relayer} -} diff --git a/x/ibc/types_test.go b/x/ibc/types_test.go index c16839ddc..199270b29 100644 --- a/x/ibc/types_test.go +++ b/x/ibc/types_test.go @@ -106,7 +106,6 @@ func constructIBCPacket(valid bool) IBCPacket { if valid { return NewIBCPacket(srcAddr, destAddr, coins, srcChain, destChain) - } else { - return NewIBCPacket(srcAddr, destAddr, coins, srcChain, srcChain) } + return NewIBCPacket(srcAddr, destAddr, coins, srcChain, srcChain) } diff --git a/x/simplestake/commands/commands.go b/x/simplestake/commands/commands.go index ba6602028..78144fdac 100644 --- a/x/simplestake/commands/commands.go +++ b/x/simplestake/commands/commands.go @@ -21,89 +21,72 @@ const ( flagValidator = "validator" ) +// simple bond tx func BondTxCmd(cdc *wire.Codec) *cobra.Command { - cmdr := commander{cdc} cmd := &cobra.Command{ Use: "bond", Short: "Bond to a validator", - RunE: cmdr.bondTxCmd, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.NewCoreContextFromViper() + + from, err := ctx.GetFromAddress() + if err != nil { + return err + } + + stakeString := viper.GetString(flagStake) + if len(stakeString) == 0 { + return fmt.Errorf("specify coins to bond with --stake") + } + + valString := viper.GetString(flagValidator) + if len(valString) == 0 { + return fmt.Errorf("specify pubkey to bond to with --validator") + } + + stake, err := sdk.ParseCoin(stakeString) + if err != nil { + return err + } + + // TODO: bech32 ... + rawPubKey, err := hex.DecodeString(valString) + if err != nil { + return err + } + var pubKeyEd crypto.PubKeyEd25519 + copy(pubKeyEd[:], rawPubKey) + + msg := simplestake.NewMsgBond(from, stake, pubKeyEd) + + return sendMsg(cdc, msg) + }, } cmd.Flags().String(flagStake, "", "Amount of coins to stake") cmd.Flags().String(flagValidator, "", "Validator address to stake") return cmd } +// simple unbond tx func UnbondTxCmd(cdc *wire.Codec) *cobra.Command { - cmdr := commander{cdc} cmd := &cobra.Command{ Use: "unbond", Short: "Unbond from a validator", - RunE: cmdr.unbondTxCmd, + RunE: func(cmd *cobra.Command, args []string) error { + from, err := context.NewCoreContextFromViper().GetFromAddress() + if err != nil { + return err + } + msg := simplestake.NewMsgUnbond(from) + return sendMsg(cdc, msg) + }, } return cmd } -type commander struct { - cdc *wire.Codec -} - -func (co commander) bondTxCmd(cmd *cobra.Command, args []string) error { - ctx := context.NewCoreContextFromViper() - - from, err := ctx.GetFromAddress() - if err != nil { - return err - } - - stakeString := viper.GetString(flagStake) - if len(stakeString) == 0 { - return fmt.Errorf("specify coins to bond with --stake") - } - - valString := viper.GetString(flagValidator) - if len(valString) == 0 { - return fmt.Errorf("specify pubkey to bond to with --validator") - } - - stake, err := sdk.ParseCoin(stakeString) - if err != nil { - return err - } - - // TODO: bech32 ... - rawPubKey, err := hex.DecodeString(valString) - if err != nil { - return err - } - var pubKeyEd crypto.PubKeyEd25519 - copy(pubKeyEd[:], rawPubKey) - - msg := simplestake.NewBondMsg(from, stake, pubKeyEd) - - return co.sendMsg(msg) -} - -func (co commander) unbondTxCmd(cmd *cobra.Command, args []string) error { - from, err := context.NewCoreContextFromViper().GetFromAddress() - if err != nil { - return err - } - - msg := simplestake.NewUnbondMsg(from) - - return co.sendMsg(msg) -} - -func (co commander) sendMsg(msg sdk.Msg) error { - ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(co.cdc)) - - // default to next sequence number if none provided - ctx, err := context.EnsureSequence(ctx) - if err != nil { - return err - } - - res, err := ctx.SignBuildBroadcast(ctx.FromAddressName, msg, co.cdc) +func sendMsg(cdc *wire.Codec, msg sdk.Msg) error { + ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) + res, err := ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, msg, cdc) if err != nil { return err } diff --git a/x/simplestake/errors.go b/x/simplestake/errors.go index 0fb7eebce..0effba9c0 100644 --- a/x/simplestake/errors.go +++ b/x/simplestake/errors.go @@ -4,6 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// simple stake errors reserve 300 ~ 399. const ( DefaultCodespace sdk.CodespaceType = 4 @@ -14,18 +15,16 @@ const ( CodeIncorrectStakingToken sdk.CodeType = 303 ) +// nolint func ErrIncorrectStakingToken(codespace sdk.CodespaceType) sdk.Error { return newError(codespace, CodeIncorrectStakingToken, "") } - func ErrEmptyValidator(codespace sdk.CodespaceType) sdk.Error { return newError(codespace, CodeEmptyValidator, "") } - func ErrInvalidUnbond(codespace sdk.CodespaceType) sdk.Error { return newError(codespace, CodeInvalidUnbond, "") } - func ErrEmptyStake(codespace sdk.CodespaceType) sdk.Error { return newError(codespace, CodeEmptyStake, "") } diff --git a/x/simplestake/handler.go b/x/simplestake/handler.go index 894da04b2..a84e8b07b 100644 --- a/x/simplestake/handler.go +++ b/x/simplestake/handler.go @@ -10,17 +10,17 @@ import ( func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { switch msg := msg.(type) { - case BondMsg: - return handleBondMsg(ctx, k, msg) - case UnbondMsg: - return handleUnbondMsg(ctx, k, msg) + case MsgBond: + return handleMsgBond(ctx, k, msg) + case MsgUnbond: + return handleMsgUnbond(ctx, k, msg) default: return sdk.ErrUnknownRequest("No match for message type.").Result() } } } -func handleBondMsg(ctx sdk.Context, k Keeper, msg BondMsg) sdk.Result { +func handleMsgBond(ctx sdk.Context, k Keeper, msg MsgBond) sdk.Result { power, err := k.Bond(ctx, msg.Address, msg.PubKey, msg.Stake) if err != nil { return err.Result() @@ -37,7 +37,7 @@ func handleBondMsg(ctx sdk.Context, k Keeper, msg BondMsg) sdk.Result { } } -func handleUnbondMsg(ctx sdk.Context, k Keeper, msg UnbondMsg) sdk.Result { +func handleMsgUnbond(ctx sdk.Context, k Keeper, msg MsgUnbond) sdk.Result { pubKey, _, err := k.Unbond(ctx, msg.Address) if err != nil { return err.Result() diff --git a/x/simplestake/keeper.go b/x/simplestake/keeper.go index 934d0b5a0..7b61c3623 100644 --- a/x/simplestake/keeper.go +++ b/x/simplestake/keeper.go @@ -12,15 +12,16 @@ const stakingToken = "steak" const moduleName = "simplestake" +// simple stake keeper type Keeper struct { - ck bank.CoinKeeper + ck bank.Keeper key sdk.StoreKey cdc *wire.Codec codespace sdk.CodespaceType } -func NewKeeper(key sdk.StoreKey, coinKeeper bank.CoinKeeper, codespace sdk.CodespaceType) Keeper { +func NewKeeper(key sdk.StoreKey, coinKeeper bank.Keeper, codespace sdk.CodespaceType) Keeper { cdc := wire.NewCodec() wire.RegisterCrypto(cdc) return Keeper{ @@ -59,6 +60,7 @@ func (k Keeper) deleteBondInfo(ctx sdk.Context, addr sdk.Address) { store.Delete(addr) } +// register a bond with the keeper func (k Keeper) Bond(ctx sdk.Context, addr sdk.Address, pubKey crypto.PubKey, stake sdk.Coin) (int64, sdk.Error) { if stake.Denom != stakingToken { return 0, ErrIncorrectStakingToken(k.codespace) @@ -83,6 +85,7 @@ func (k Keeper) Bond(ctx sdk.Context, addr sdk.Address, pubKey crypto.PubKey, st return bi.Power, nil } +// register an unbond with the keeper func (k Keeper) Unbond(ctx sdk.Context, addr sdk.Address) (crypto.PubKey, int64, sdk.Error) { bi := k.getBondInfo(ctx, addr) if bi.isEmpty() { diff --git a/x/simplestake/keeper_test.go b/x/simplestake/keeper_test.go index 833227968..75e9fcded 100644 --- a/x/simplestake/keeper_test.go +++ b/x/simplestake/keeper_test.go @@ -33,7 +33,7 @@ func TestKeeperGetSet(t *testing.T) { ms, _, capKey := setupMultiStore() ctx := sdk.NewContext(ms, abci.Header{}, false, nil) - stakeKeeper := NewKeeper(capKey, bank.NewCoinKeeper(nil), DefaultCodespace) + stakeKeeper := NewKeeper(capKey, bank.NewKeeper(nil), DefaultCodespace) addr := sdk.Address([]byte("some-address")) bi := stakeKeeper.getBondInfo(ctx, addr) @@ -62,7 +62,7 @@ func TestBonding(t *testing.T) { ctx := sdk.NewContext(ms, abci.Header{}, false, nil) accountMapper := auth.NewAccountMapper(cdc, authKey, &auth.BaseAccount{}) - coinKeeper := bank.NewCoinKeeper(accountMapper) + coinKeeper := bank.NewKeeper(accountMapper) stakeKeeper := NewKeeper(capKey, coinKeeper, DefaultCodespace) addr := sdk.Address([]byte("some-address")) privKey := crypto.GenPrivKeyEd25519() diff --git a/x/simplestake/msgs.go b/x/simplestake/msgs.go index 963bfae7b..512d571c5 100644 --- a/x/simplestake/msgs.go +++ b/x/simplestake/msgs.go @@ -8,44 +8,43 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// ------------------------- -// BondMsg +//_________________________________________________________---- -type BondMsg struct { +// simple bond message +type MsgBond struct { Address sdk.Address `json:"address"` Stake sdk.Coin `json:"coins"` PubKey crypto.PubKey `json:"pub_key"` } -func NewBondMsg(addr sdk.Address, stake sdk.Coin, pubKey crypto.PubKey) BondMsg { - return BondMsg{ +func NewMsgBond(addr sdk.Address, stake sdk.Coin, pubKey crypto.PubKey) MsgBond { + return MsgBond{ Address: addr, Stake: stake, PubKey: pubKey, } } -func (msg BondMsg) Type() string { - return moduleName -} +//nolint +func (msg MsgBond) Type() string { return moduleName } //TODO update "stake/declarecandidacy" +func (msg MsgBond) Get(key interface{}) (value interface{}) { return nil } +func (msg MsgBond) GetSigners() []sdk.Address { return []sdk.Address{msg.Address} } -func (msg BondMsg) ValidateBasic() sdk.Error { +// basic validation of the bond message +func (msg MsgBond) ValidateBasic() sdk.Error { if msg.Stake.IsZero() { return ErrEmptyStake(DefaultCodespace) } if msg.PubKey == nil { - return sdk.ErrInvalidPubKey("BondMsg.PubKey must not be empty") + return sdk.ErrInvalidPubKey("MsgBond.PubKey must not be empty") } return nil } -func (msg BondMsg) Get(key interface{}) interface{} { - return nil -} - -func (msg BondMsg) GetSignBytes() []byte { +// get bond message sign bytes +func (msg MsgBond) GetSignBytes() []byte { bz, err := json.Marshal(msg) if err != nil { panic(err) @@ -53,43 +52,30 @@ func (msg BondMsg) GetSignBytes() []byte { return bz } -func (msg BondMsg) GetSigners() []sdk.Address { - return []sdk.Address{msg.Address} -} +//_______________________________________________________________ -// ------------------------- -// UnbondMsg - -type UnbondMsg struct { +// simple unbond message +type MsgUnbond struct { Address sdk.Address `json:"address"` } -func NewUnbondMsg(addr sdk.Address) UnbondMsg { - return UnbondMsg{ +func NewMsgUnbond(addr sdk.Address) MsgUnbond { + return MsgUnbond{ Address: addr, } } -func (msg UnbondMsg) Type() string { - return moduleName -} +//nolint +func (msg MsgUnbond) Type() string { return moduleName } //TODO update "stake/declarecandidacy" +func (msg MsgUnbond) Get(key interface{}) (value interface{}) { return nil } +func (msg MsgUnbond) GetSigners() []sdk.Address { return []sdk.Address{msg.Address} } +func (msg MsgUnbond) ValidateBasic() sdk.Error { return nil } -func (msg UnbondMsg) ValidateBasic() sdk.Error { - return nil -} - -func (msg UnbondMsg) Get(key interface{}) interface{} { - return nil -} - -func (msg UnbondMsg) GetSignBytes() []byte { +// get unbond message sign bytes +func (msg MsgUnbond) GetSignBytes() []byte { bz, err := json.Marshal(msg) if err != nil { panic(err) } return bz } - -func (msg UnbondMsg) GetSigners() []sdk.Address { - return []sdk.Address{msg.Address} -} diff --git a/x/simplestake/msgs_test.go b/x/simplestake/msgs_test.go index 49a8feec5..c71ebe7fc 100644 --- a/x/simplestake/msgs_test.go +++ b/x/simplestake/msgs_test.go @@ -14,14 +14,14 @@ func TestBondMsgValidation(t *testing.T) { privKey := crypto.GenPrivKeyEd25519() cases := []struct { valid bool - bondMsg BondMsg + msgBond MsgBond }{ - {true, NewBondMsg(sdk.Address{}, sdk.Coin{"mycoin", 5}, privKey.PubKey())}, - {false, NewBondMsg(sdk.Address{}, sdk.Coin{"mycoin", 0}, privKey.PubKey())}, + {true, NewMsgBond(sdk.Address{}, sdk.Coin{"mycoin", 5}, privKey.PubKey())}, + {false, NewMsgBond(sdk.Address{}, sdk.Coin{"mycoin", 0}, privKey.PubKey())}, } for i, tc := range cases { - err := tc.bondMsg.ValidateBasic() + err := tc.msgBond.ValidateBasic() if tc.valid { assert.Nil(t, err, "%d: %+v", i, err) } else { diff --git a/x/stake/commands/tx.go b/x/stake/commands/tx.go index 4a1983743..e04a81885 100644 --- a/x/stake/commands/tx.go +++ b/x/stake/commands/tx.go @@ -48,13 +48,7 @@ func GetCmdDeclareCandidacy(cdc *wire.Codec) *cobra.Command { // build and sign the transaction, then broadcast to Tendermint ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) - // default to next sequence number if none provided - ctx, err = context.EnsureSequence(ctx) - if err != nil { - return err - } - - res, err := ctx.SignBuildBroadcast(ctx.FromAddressName, msg, cdc) + res, err := ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, msg, cdc) if err != nil { return err } @@ -93,13 +87,7 @@ func GetCmdEditCandidacy(cdc *wire.Codec) *cobra.Command { // build and sign the transaction, then broadcast to Tendermint ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) - // default to next sequence number if none provided - ctx, err = context.EnsureSequence(ctx) - if err != nil { - return err - } - - res, err := ctx.SignBuildBroadcast(ctx.FromAddressName, msg, cdc) + res, err := ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, msg, cdc) if err != nil { return err } @@ -136,13 +124,7 @@ func GetCmdDelegate(cdc *wire.Codec) *cobra.Command { // build and sign the transaction, then broadcast to Tendermint ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) - // default to next sequence number if none provided - ctx, err = context.EnsureSequence(ctx) - if err != nil { - return err - } - - res, err := ctx.SignBuildBroadcast(ctx.FromAddressName, msg, cdc) + res, err := ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, msg, cdc) if err != nil { return err } @@ -190,13 +172,7 @@ func GetCmdUnbond(cdc *wire.Codec) *cobra.Command { // build and sign the transaction, then broadcast to Tendermint ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc)) - // default to next sequence number if none provided - ctx, err = context.EnsureSequence(ctx) - if err != nil { - return err - } - - res, err := ctx.SignBuildBroadcast(ctx.FromAddressName, msg, cdc) + res, err := ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, msg, cdc) if err != nil { return err } diff --git a/x/stake/keeper.go b/x/stake/keeper.go index 751b84017..49806f9b9 100644 --- a/x/stake/keeper.go +++ b/x/stake/keeper.go @@ -13,7 +13,7 @@ import ( type Keeper struct { storeKey sdk.StoreKey cdc *wire.Codec - coinKeeper bank.CoinKeeper + coinKeeper bank.Keeper // caches gs Pool @@ -23,7 +23,7 @@ type Keeper struct { codespace sdk.CodespaceType } -func NewKeeper(cdc *wire.Codec, key sdk.StoreKey, ck bank.CoinKeeper, codespace sdk.CodespaceType) Keeper { +func NewKeeper(cdc *wire.Codec, key sdk.StoreKey, ck bank.Keeper, codespace sdk.CodespaceType) Keeper { keeper := Keeper{ storeKey: key, cdc: cdc, diff --git a/x/stake/msg.go b/x/stake/msg.go index b5ba09b5a..10cea3fa8 100644 --- a/x/stake/msg.go +++ b/x/stake/msg.go @@ -2,7 +2,6 @@ package stake import ( "encoding/json" - "fmt" sdk "github.com/cosmos/cosmos-sdk/types" crypto "github.com/tendermint/go-crypto" @@ -44,9 +43,6 @@ func NewMsgDeclareCandidacy(candidateAddr sdk.Address, pubkey crypto.PubKey, func (msg MsgDeclareCandidacy) Type() string { return MsgType } //TODO update "stake/declarecandidacy" func (msg MsgDeclareCandidacy) Get(key interface{}) (value interface{}) { return nil } func (msg MsgDeclareCandidacy) GetSigners() []sdk.Address { return []sdk.Address{msg.CandidateAddr} } -func (msg MsgDeclareCandidacy) String() string { - return fmt.Sprintf("CandidateAddr{Address: %v}", msg.CandidateAddr) // XXX fix -} // get the bytes for the message signer to sign on func (msg MsgDeclareCandidacy) GetSignBytes() []byte { @@ -67,7 +63,6 @@ func (msg MsgDeclareCandidacy) ValidateBasic() sdk.Error { } if msg.Bond.Amount <= 0 { return ErrBadBondingAmount(DefaultCodespace) - // return sdk.ErrInvalidCoins(sdk.Coins{msg.Bond}.String()) } empty := Description{} if msg.Description == empty { @@ -95,9 +90,6 @@ func NewMsgEditCandidacy(candidateAddr sdk.Address, description Description) Msg func (msg MsgEditCandidacy) Type() string { return MsgType } //TODO update "stake/msgeditcandidacy" func (msg MsgEditCandidacy) Get(key interface{}) (value interface{}) { return nil } func (msg MsgEditCandidacy) GetSigners() []sdk.Address { return []sdk.Address{msg.CandidateAddr} } -func (msg MsgEditCandidacy) String() string { - return fmt.Sprintf("CandidateAddr{Address: %v}", msg.CandidateAddr) // XXX fix -} // get the bytes for the message signer to sign on func (msg MsgEditCandidacy) GetSignBytes() []byte { @@ -141,9 +133,6 @@ func NewMsgDelegate(delegatorAddr, candidateAddr sdk.Address, bond sdk.Coin) Msg func (msg MsgDelegate) Type() string { return MsgType } //TODO update "stake/msgeditcandidacy" func (msg MsgDelegate) Get(key interface{}) (value interface{}) { return nil } func (msg MsgDelegate) GetSigners() []sdk.Address { return []sdk.Address{msg.DelegatorAddr} } -func (msg MsgDelegate) String() string { - return fmt.Sprintf("Addr{Address: %v}", msg.DelegatorAddr) // XXX fix -} // get the bytes for the message signer to sign on func (msg MsgDelegate) GetSignBytes() []byte { @@ -167,7 +156,6 @@ func (msg MsgDelegate) ValidateBasic() sdk.Error { } if msg.Bond.Amount <= 0 { return ErrBadBondingAmount(DefaultCodespace) - // return sdk.ErrInvalidCoins(sdk.Coins{msg.Bond}.String()) } return nil } @@ -193,9 +181,6 @@ func NewMsgUnbond(delegatorAddr, candidateAddr sdk.Address, shares string) MsgUn func (msg MsgUnbond) Type() string { return MsgType } //TODO update "stake/msgeditcandidacy" func (msg MsgUnbond) Get(key interface{}) (value interface{}) { return nil } func (msg MsgUnbond) GetSigners() []sdk.Address { return []sdk.Address{msg.DelegatorAddr} } -func (msg MsgUnbond) String() string { - return fmt.Sprintf("Addr{Address: %v}", msg.DelegatorAddr) // XXX fix -} // get the bytes for the message signer to sign on func (msg MsgUnbond) GetSignBytes() []byte { diff --git a/x/stake/test_common.go b/x/stake/test_common.go index 1de86c912..9d7b13e7c 100644 --- a/x/stake/test_common.go +++ b/x/stake/test_common.go @@ -96,8 +96,8 @@ func makeTestCodec() *wire.Codec { // Register Msgs cdc.RegisterInterface((*sdk.Msg)(nil), nil) - cdc.RegisterConcrete(bank.SendMsg{}, "test/stake/Send", nil) - cdc.RegisterConcrete(bank.IssueMsg{}, "test/stake/Issue", nil) + cdc.RegisterConcrete(bank.MsgSend{}, "test/stake/Send", nil) + cdc.RegisterConcrete(bank.MsgIssue{}, "test/stake/Issue", nil) cdc.RegisterConcrete(MsgDeclareCandidacy{}, "test/stake/DeclareCandidacy", nil) cdc.RegisterConcrete(MsgEditCandidacy{}, "test/stake/EditCandidacy", nil) cdc.RegisterConcrete(MsgUnbond{}, "test/stake/Unbond", nil) @@ -139,7 +139,7 @@ func createTestInput(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context keyMain, // target store &auth.BaseAccount{}, // prototype ).Seal() - ck := bank.NewCoinKeeper(accountMapper) + ck := bank.NewKeeper(accountMapper) keeper := NewKeeper(cdc, keyStake, ck, DefaultCodespace) keeper.setPool(ctx, initialPool()) keeper.setParams(ctx, defaultParams())