From 277041d53ebf3dbdfe67d60d7d38f7140e66bf85 Mon Sep 17 00:00:00 2001 From: Luca Moser <moser.luca@gmail.com> Date: Mon, 27 Jan 2020 20:22:22 +0100 Subject: [PATCH] use correct http codes for given responses (#189) --- client/lib.go | 3 ++ plugins/webapi/broadcastData/plugin.go | 32 ++++------- .../webapi/findTransactionHashes/plugin.go | 18 ++----- plugins/webapi/getNeighbors/plugin.go | 21 ++------ .../getTransactionObjectsByHash/plugin.go | 54 +++++++------------ .../getTransactionTrytesByHash/plugin.go | 30 +++-------- plugins/webapi/spammer/plugin.go | 25 ++------- 7 files changed, 52 insertions(+), 131 deletions(-) diff --git a/client/lib.go b/client/lib.go index 09a47878..9f2da124 100644 --- a/client/lib.go +++ b/client/lib.go @@ -29,6 +29,7 @@ var ( ErrNotFound = errors.New("not found") ErrUnauthorized = errors.New("unauthorized") ErrUnknownError = errors.New("unknown error") + ErrNotImplemented = errors.New("operation not implemented/supported/available") ) const ( @@ -87,6 +88,8 @@ func interpretBody(res *http.Response, decodeTo interface{}) error { return fmt.Errorf("%w: %s", ErrBadRequest, errRes.Error) case http.StatusUnauthorized: return fmt.Errorf("%w: %s", ErrUnauthorized, errRes.Error) + case http.StatusNotImplemented: + return fmt.Errorf("%w: %s", ErrNotImplemented, errRes.Error) } return fmt.Errorf("%w: %s", ErrUnknownError, errRes.Error) diff --git a/plugins/webapi/broadcastData/plugin.go b/plugins/webapi/broadcastData/plugin.go index 0ed2562f..2e30888e 100644 --- a/plugins/webapi/broadcastData/plugin.go +++ b/plugins/webapi/broadcastData/plugin.go @@ -33,7 +33,7 @@ func broadcastData(c echo.Context) error { var request Request if err := c.Bind(&request); err != nil { log.Info(err.Error()) - return requestFailed(c, err.Error()) + return c.JSON(http.StatusBadRequest, Response{Error: err.Error()}) } log.Debug("Received - address:", request.Address, " data:", request.Data) @@ -44,22 +44,22 @@ func broadcastData(c echo.Context) error { buffer := make([]byte, 2187) if len(request.Data) > 2187 { - log.Warn("Data exceeding 2187 byte limit -", len(request.Data)) - return requestFailed(c, "Data exceeding 2187 byte limit") + log.Warnf("data exceeds 2187 byte limit - (payload data size: %d)", len(request.Data)) + return c.JSON(http.StatusBadRequest, Response{Error: "data exceeds 2187 byte limit"}) } copy(buffer, typeutils.StringToBytes(request.Data)) trytes, err := trinary.BytesToTrytes(buffer) if err != nil { - log.Warn("Trytes conversion failed", err.Error()) - return requestFailed(c, err.Error()) + log.Warnf("trytes conversion failed: %s", err.Error()) + return c.JSON(http.StatusBadRequest, Response{Error: err.Error()}) } err = address.ValidAddress(request.Address) if err != nil { - log.Warn("Invalid Address:", request.Address) - return requestFailed(c, err.Error()) + log.Warnf("invalid Address: %s", request.Address) + return c.JSON(http.StatusBadRequest, Response{Error: err.Error()}) } tx.SetAddress(request.Address) @@ -69,24 +69,12 @@ func broadcastData(c echo.Context) error { tx.SetTrunkTransactionHash(tipselection.GetRandomTip()) tx.SetTimestamp(uint(time.Now().Unix())) if err := tx.DoProofOfWork(meta_transaction.MIN_WEIGHT_MAGNITUDE); err != nil { - log.Warn("PoW failed", err) - return requestFailed(c, err.Error()) + log.Warnf("PoW failed: %s", err) + return c.JSON(http.StatusInternalServerError, Response{Error: err.Error()}) } gossip.Events.TransactionReceived.Trigger(&gossip.TransactionReceivedEvent{Data: tx.GetBytes(), Peer: &local.GetInstance().Peer}) - return requestSuccessful(c, tx.GetHash()) -} - -func requestSuccessful(c echo.Context, txHash string) error { - return c.JSON(http.StatusCreated, Response{ - Hash: txHash, - }) -} - -func requestFailed(c echo.Context, message string) error { - return c.JSON(http.StatusBadRequest, Response{ - Error: message, - }) + return c.JSON(http.StatusOK, Response{Hash: tx.GetHash()}) } type Response struct { diff --git a/plugins/webapi/findTransactionHashes/plugin.go b/plugins/webapi/findTransactionHashes/plugin.go index 07a626d9..7ae655f8 100644 --- a/plugins/webapi/findTransactionHashes/plugin.go +++ b/plugins/webapi/findTransactionHashes/plugin.go @@ -28,7 +28,7 @@ func findTransactionHashes(c echo.Context) error { if err := c.Bind(&request); err != nil { log.Info(err.Error()) - return requestFailed(c, err.Error()) + return c.JSON(http.StatusBadRequest, Response{Error: err.Error()}) } log.Debug("Received:", request.Addresses) result := make([][]trinary.Trytes, len(request.Addresses)) @@ -36,24 +36,12 @@ func findTransactionHashes(c echo.Context) error { for i, address := range request.Addresses { txs, err := tangle.ReadTransactionHashesForAddressFromDatabase(address) if err != nil { - return requestFailed(c, err.Error()) + return c.JSON(http.StatusInternalServerError, Response{Error: err.Error()}) } result[i] = append(result[i], txs...) } - return requestSuccessful(c, result) -} - -func requestSuccessful(c echo.Context, txHashes [][]trinary.Trytes) error { - return c.JSON(http.StatusOK, Response{ - Transactions: txHashes, - }) -} - -func requestFailed(c echo.Context, message string) error { - return c.JSON(http.StatusNotFound, Response{ - Error: message, - }) + return c.JSON(http.StatusOK, Response{Transactions: result}) } type Response struct { diff --git a/plugins/webapi/getNeighbors/plugin.go b/plugins/webapi/getNeighbors/plugin.go index 71e718ff..1ac033ce 100644 --- a/plugins/webapi/getNeighbors/plugin.go +++ b/plugins/webapi/getNeighbors/plugin.go @@ -26,11 +26,11 @@ func getNeighbors(c echo.Context) error { knownPeers := []Neighbor{} if autopeering.Selection == nil { - return requestFailed(c, "Neighbor Selection is not enabled") + return c.JSON(http.StatusNotImplemented, Response{Error: "Neighbor Selection is not enabled"}) } if autopeering.Discovery == nil { - return requestFailed(c, "Neighbor Discovery is not enabled") + return c.JSON(http.StatusNotImplemented, Response{Error: "Neighbor Discovery is not enabled"}) } if c.QueryParam("known") == "1" { @@ -45,7 +45,6 @@ func getNeighbors(c echo.Context) error { } for _, peer := range autopeering.Selection.GetOutgoingNeighbors() { - n := Neighbor{ ID: peer.ID().String(), PublicKey: base64.StdEncoding.EncodeToString(peer.PublicKey()), @@ -62,21 +61,7 @@ func getNeighbors(c echo.Context) error { accepted = append(accepted, n) } - return requestSuccessful(c, knownPeers, chosen, accepted) -} - -func requestSuccessful(c echo.Context, knownPeers, chosen, accepted []Neighbor) error { - return c.JSON(http.StatusOK, Response{ - KnownPeers: knownPeers, - Chosen: chosen, - Accepted: accepted, - }) -} - -func requestFailed(c echo.Context, message string) error { - return c.JSON(http.StatusNotFound, Response{ - Error: message, - }) + return c.JSON(http.StatusOK, Response{KnownPeers: knownPeers, Chosen: chosen, Accepted: accepted}) } type Response struct { diff --git a/plugins/webapi/getTransactionObjectsByHash/plugin.go b/plugins/webapi/getTransactionObjectsByHash/plugin.go index 221def3c..e2b0e766 100644 --- a/plugins/webapi/getTransactionObjectsByHash/plugin.go +++ b/plugins/webapi/getTransactionObjectsByHash/plugin.go @@ -1,6 +1,7 @@ package getTransactionObjectsByHash import ( + "fmt" "net/http" "github.com/iotaledger/goshimmer/plugins/tangle" @@ -30,7 +31,7 @@ func getTransactionObjectsByHash(c echo.Context) error { if err := c.Bind(&request); err != nil { log.Info(err.Error()) - return requestFailed(c, err.Error()) + return c.JSON(http.StatusBadRequest, Response{Error: err.Error()}) } log.Debug("Received:", request.Hashes) @@ -38,43 +39,28 @@ func getTransactionObjectsByHash(c echo.Context) error { for _, hash := range request.Hashes { tx, err := tangle.GetTransaction(hash) if err != nil { - return requestFailed(c, err.Error()) + return c.JSON(http.StatusInternalServerError, Response{Error: err.Error()}) } - if tx != nil { - t := Transaction{ - Hash: tx.GetHash(), - WeightMagnitude: tx.GetWeightMagnitude(), - TrunkTransactionHash: tx.GetTrunkTransactionHash(), - BranchTransactionHash: tx.GetBranchTransactionHash(), - Head: tx.IsHead(), - Tail: tx.IsTail(), - Nonce: tx.GetNonce(), - Address: tx.GetAddress(), - Value: tx.GetValue(), - Timestamp: tx.GetTimestamp(), - SignatureMessageFragment: tx.GetSignatureMessageFragment(), - } - result = append(result, t) - } else { - //tx not found - result = append(result, Transaction{}) + if tx == nil { + return c.JSON(http.StatusNotFound, Response{Error: fmt.Sprintf("transaction not found: %s", hash)}) } - + t := Transaction{ + Hash: tx.GetHash(), + WeightMagnitude: tx.GetWeightMagnitude(), + TrunkTransactionHash: tx.GetTrunkTransactionHash(), + BranchTransactionHash: tx.GetBranchTransactionHash(), + Head: tx.IsHead(), + Tail: tx.IsTail(), + Nonce: tx.GetNonce(), + Address: tx.GetAddress(), + Value: tx.GetValue(), + Timestamp: tx.GetTimestamp(), + SignatureMessageFragment: tx.GetSignatureMessageFragment(), + } + result = append(result, t) } - return requestSuccessful(c, result) -} - -func requestSuccessful(c echo.Context, txs []Transaction) error { - return c.JSON(http.StatusOK, Response{ - Transactions: txs, - }) -} - -func requestFailed(c echo.Context, message string) error { - return c.JSON(http.StatusNotFound, Response{ - Error: message, - }) + return c.JSON(http.StatusOK, Response{Transactions: result}) } type Response struct { diff --git a/plugins/webapi/getTransactionTrytesByHash/plugin.go b/plugins/webapi/getTransactionTrytesByHash/plugin.go index b4bb3613..3b9a00b4 100644 --- a/plugins/webapi/getTransactionTrytesByHash/plugin.go +++ b/plugins/webapi/getTransactionTrytesByHash/plugin.go @@ -1,6 +1,7 @@ package getTransactionTrytesByHash import ( + "fmt" "net/http" "github.com/iotaledger/goshimmer/plugins/tangle" @@ -29,38 +30,23 @@ func getTransactionTrytesByHash(c echo.Context) error { result := []trinary.Trytes{} if err := c.Bind(&request); err != nil { log.Info(err.Error()) - return requestFailed(c, err.Error()) + return c.JSON(http.StatusBadRequest, Response{Error: err.Error()}) } log.Debug("Received:", request.Hashes) for _, hash := range request.Hashes { tx, err := tangle.GetTransaction(hash) if err != nil { - return requestFailed(c, err.Error()) + return c.JSON(http.StatusInternalServerError, Response{Error: err.Error()}) } - if tx != nil { - trytes := trinary.MustTritsToTrytes(tx.GetTrits()) - result = append(result, trytes) - } else { - //tx not found - result = append(result, "") + if tx == nil { + return c.JSON(http.StatusNotFound, Response{Error: fmt.Sprintf("transaction not found: %s", hash)}) } - + trytes := trinary.MustTritsToTrytes(tx.GetTrits()) + result = append(result, trytes) } - return requestSuccessful(c, result) -} - -func requestSuccessful(c echo.Context, txTrytes []trinary.Trytes) error { - return c.JSON(http.StatusOK, Response{ - Trytes: txTrytes, - }) -} - -func requestFailed(c echo.Context, message string) error { - return c.JSON(http.StatusNotFound, Response{ - Error: message, - }) + return c.JSON(http.StatusOK, Response{Trytes: result}) } type Response struct { diff --git a/plugins/webapi/spammer/plugin.go b/plugins/webapi/spammer/plugin.go index fdc1aca3..7aa057fc 100644 --- a/plugins/webapi/spammer/plugin.go +++ b/plugins/webapi/spammer/plugin.go @@ -19,7 +19,7 @@ func WebApiHandler(c echo.Context) error { var request Request if err := c.Bind(&request); err != nil { - return requestFailed(c, err.Error()) + return c.JSON(http.StatusBadRequest, Response{Error: err.Error()}) } switch request.Cmd { @@ -30,33 +30,18 @@ func WebApiHandler(c echo.Context) error { transactionspammer.Stop() transactionspammer.Start(request.Tps) - - return requestSuccessful(c, "started spamming transactions") - + return c.JSON(http.StatusOK, Response{Message: "started spamming transactions"}) case "stop": transactionspammer.Stop() - - return requestSuccessful(c, "stopped spamming transactions") - + return c.JSON(http.StatusOK, Response{Message: "stopped spamming transactions"}) default: - return requestFailed(c, "invalid cmd in request") + return c.JSON(http.StatusBadRequest, Response{Error: "invalid cmd in request"}) } } -func requestSuccessful(c echo.Context, message string) error { - return c.JSON(http.StatusOK, Response{ - Message: message, - }) -} - -func requestFailed(c echo.Context, message string) error { - return c.JSON(http.StatusNotFound, Response{ - Message: message, - }) -} - type Response struct { Message string `json:"message"` + Error string `json:"error"` } type Request struct { -- GitLab