cosmos-sdk/client/tx/broadcast.go

85 lines
2.2 KiB
Go
Raw Normal View History

2018-03-09 01:15:56 -08:00
package tx
import (
"net/http"
"github.com/cosmos/cosmos-sdk/client/context"
2018-09-27 07:06:40 -07:00
"io/ioutil"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/client/utils"
2018-03-09 01:15:56 -08:00
)
2018-09-27 07:06:40 -07:00
const (
// Returns with the response from CheckTx.
flagSync = "sync"
// Returns right away, with no response
flagAsync = "async"
// Only returns error if mempool.BroadcastTx errs (ie. problem with the app) or if we timeout waiting for tx to commit.
flagBlock = "block"
)
// BroadcastBody Tx Broadcast Body
type BroadcastBody struct {
2018-09-29 20:42:12 -07:00
TxBytes []byte `json:"tx"`
2018-09-27 07:06:40 -07:00
Return string `json:"return"`
2018-03-09 01:15:56 -08:00
}
2018-09-27 07:06:40 -07:00
// BroadcastTxRequest REST Handler
// nolint: gocyclo
func BroadcastTxRequest(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
2018-09-27 07:06:40 -07:00
var m BroadcastBody
body, err := ioutil.ReadAll(r.Body)
if err != nil {
2018-09-27 07:06:40 -07:00
utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
2018-09-27 07:06:40 -07:00
err = cdc.UnmarshalJSON(body, &m)
if err != nil {
2018-09-27 07:06:40 -07:00
utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
var output []byte
switch m.Return {
case flagBlock:
2018-09-29 20:42:12 -07:00
res, err := cliCtx.BroadcastTx(m.TxBytes)
2018-09-27 07:06:40 -07:00
if err != nil {
utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
output, err = cdc.MarshalJSON(res)
if err != nil {
utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
case flagSync:
2018-09-29 20:42:12 -07:00
res, err := cliCtx.BroadcastTxSync(m.TxBytes)
2018-09-27 07:06:40 -07:00
if err != nil {
utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
output, err = cdc.MarshalJSON(res)
if err != nil {
utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
case flagAsync:
2018-09-29 20:42:12 -07:00
res, err := cliCtx.BroadcastTxAsync(m.TxBytes)
2018-09-27 07:06:40 -07:00
if err != nil {
utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
output, err = cdc.MarshalJSON(res)
if err != nil {
utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
default:
utils.WriteErrorResponse(w, http.StatusInternalServerError, "unsupported return type. supported types: block, sync, async")
return
}
2018-03-09 01:15:56 -08:00
2018-09-27 07:06:40 -07:00
w.Write(output)
}
2018-03-09 01:15:56 -08:00
}