Skip to content
Snippets Groups Projects
Unverified Commit ba49caf7 authored by Angelo Capossele's avatar Angelo Capossele Committed by GitHub
Browse files

Fix: webapi, client lib and relay-checker linter warnings (#369)

* :rotating_light: Fixes linter warnings

* :construction: removes newline

* :construction: WIP

* :construction: restore folder

* :white_check_mark: Fixes integration test
parent 6f949637
No related branches found
No related tags found
No related merge requests found
Showing
with 107 additions and 89 deletions
......@@ -19,5 +19,5 @@ func (api *GoShimmerAPI) Data(data []byte) (string, error) {
return "", err
}
return res.Id, nil
return res.ID, nil
}
......@@ -3,7 +3,7 @@ package client
import (
"net/http"
webapi_collectiveBeacon "github.com/iotaledger/goshimmer/plugins/webapi/drng/collectiveBeacon"
webapi_collectiveBeacon "github.com/iotaledger/goshimmer/plugins/webapi/drng/collectivebeacon"
webapi_committee "github.com/iotaledger/goshimmer/plugins/webapi/drng/info/committee"
webapi_randomness "github.com/iotaledger/goshimmer/plugins/webapi/drng/info/randomness"
)
......@@ -23,7 +23,7 @@ func (api *GoShimmerAPI) BroadcastCollectiveBeacon(payload []byte) (string, erro
return "", err
}
return res.Id, nil
return res.ID, nil
}
// GetRandomness gets the current randomness.
......
// Implements a very simple wrapper for GoShimmer's web API .
// Package client implements a very simple wrapper for GoShimmer's web API.
package client
import (
......@@ -12,29 +12,36 @@ import (
)
var (
ErrBadRequest = errors.New("bad request")
// ErrBadRequest defines the "bad request" error.
ErrBadRequest = errors.New("bad request")
// ErrInternalServerError defines the "internal server error" error.
ErrInternalServerError = errors.New("internal server error")
ErrNotFound = errors.New("not found")
ErrUnauthorized = errors.New("unauthorized")
ErrUnknownError = errors.New("unknown error")
ErrNotImplemented = errors.New("operation not implemented/supported/available")
// ErrNotFound defines the "not found" error.
ErrNotFound = errors.New("not found")
// ErrUnauthorized defines the "unauthorized" error.
ErrUnauthorized = errors.New("unauthorized")
// ErrUnknownError defines the "unknown error" error.
ErrUnknownError = errors.New("unknown error")
// ErrNotImplemented defines the "operation not implemented/supported/available" error.
ErrNotImplemented = errors.New("operation not implemented/supported/available")
)
const (
contentTypeJSON = "application/json"
)
func NewGoShimmerAPI(baseUrl string, httpClient ...http.Client) *GoShimmerAPI {
// NewGoShimmerAPI returns a new *GoShimmerAPI with the given baseURL and httpClient.
func NewGoShimmerAPI(baseURL string, httpClient ...http.Client) *GoShimmerAPI {
if len(httpClient) > 0 {
return &GoShimmerAPI{baseUrl: baseUrl, httpClient: httpClient[0]}
return &GoShimmerAPI{baseURL: baseURL, httpClient: httpClient[0]}
}
return &GoShimmerAPI{baseUrl: baseUrl}
return &GoShimmerAPI{baseURL: baseURL}
}
// GoShimmerAPI is an API wrapper over the web API of GoShimmer.
type GoShimmerAPI struct {
httpClient http.Client
baseUrl string
baseURL string
jwt string
}
......@@ -86,7 +93,7 @@ func (api *GoShimmerAPI) do(method string, route string, reqObj interface{}, res
}
// construct request
req, err := http.NewRequest(method, fmt.Sprintf("%s/%s", api.baseUrl, route), func() io.Reader {
req, err := http.NewRequest(method, fmt.Sprintf("%s/%s", api.baseURL, route), func() io.Reader {
if data == nil {
return nil
}
......@@ -122,6 +129,7 @@ func (api *GoShimmerAPI) do(method string, route string, reqObj interface{}, res
return nil
}
func (api *GoShimmerAPI) BaseUrl() string {
return api.baseUrl
// BaseURL returns the baseURL of the API.
func (api *GoShimmerAPI) BaseURL() string {
return api.baseURL
}
......@@ -7,18 +7,18 @@ import (
)
const (
routeFindById = "message/findById"
routeFindByID = "message/findById"
)
// FindMessageById finds messages by the given ids. The messages are returned in the same order as
// the given ids. Non available messages are empty at their corresponding index.
func (api *GoShimmerAPI) FindMessageById(base58EncodedIds []string) (*webapi_message.Response, error) {
// FindMessageByID finds messages by the given base58 encoded IDs. The messages are returned in the same order as
// the given IDs. Non available messages are empty at their corresponding index.
func (api *GoShimmerAPI) FindMessageByID(base58EncodedIDs []string) (*webapi_message.Response, error) {
res := &webapi_message.Response{}
if err := api.do(
http.MethodPost,
routeFindById,
&webapi_message.Request{Ids: base58EncodedIds},
routeFindByID,
&webapi_message.Request{IDs: base58EncodedIDs},
res,
); err != nil {
return nil, err
......
......@@ -70,6 +70,7 @@ func getNeighbors(c echo.Context) error {
return c.JSON(http.StatusOK, Response{KnownPeers: knownPeers, Chosen: chosen, Accepted: accepted})
}
// Response contains information of the autopeering.
type Response struct {
KnownPeers []Neighbor `json:"known,omitempty"`
Chosen []Neighbor `json:"chosen"`
......@@ -77,6 +78,7 @@ type Response struct {
Error string `json:"error,omitempty"`
}
// Neighbor contains information of a neighbor peer.
type Neighbor struct {
ID string `json:"id"` // comparable node identifier
PublicKey string `json:"publicKey"` // public key used to verify signatures
......
......@@ -36,14 +36,16 @@ func broadcastData(c echo.Context) error {
//TODO: to check max payload size allowed, if exceeding return an error
msg := messagelayer.MessageFactory.IssuePayload(payload.NewData(request.Data))
return c.JSON(http.StatusOK, Response{Id: msg.Id().String()})
return c.JSON(http.StatusOK, Response{ID: msg.Id().String()})
}
// Response contains the ID of the message sent.
type Response struct {
Id string `json:"id,omitempty"`
ID string `json:"id,omitempty"`
Error string `json:"error,omitempty"`
}
// Request contains the data of the message to send.
type Request struct {
Data []byte `json:"data"`
}
package collectiveBeacon
package collectivebeacon
import (
"net/http"
......@@ -19,7 +19,6 @@ func Handler(c echo.Context) error {
}
//TODO: to check max payload size allowed, if exceeding return an error
marshalUtil := marshalutil.New(request.Payload)
parsedPayload, err := payload.Parse(marshalUtil)
if err != nil {
......@@ -27,12 +26,12 @@ func Handler(c echo.Context) error {
}
msg := messagelayer.MessageFactory.IssuePayload(parsedPayload)
return c.JSON(http.StatusOK, Response{Id: msg.Id().String()})
return c.JSON(http.StatusOK, Response{ID: msg.Id().String()})
}
// Response is the HTTP response from broadcasting a collective beacon message.
type Response struct {
Id string `json:"id,omitempty"`
ID string `json:"id,omitempty"`
Error string `json:"error,omitempty"`
}
......
......@@ -2,7 +2,7 @@ package drng
import (
"github.com/iotaledger/goshimmer/plugins/webapi"
"github.com/iotaledger/goshimmer/plugins/webapi/drng/collectiveBeacon"
"github.com/iotaledger/goshimmer/plugins/webapi/drng/collectivebeacon"
"github.com/iotaledger/goshimmer/plugins/webapi/drng/info/committee"
"github.com/iotaledger/goshimmer/plugins/webapi/drng/info/randomness"
"github.com/iotaledger/hive.go/node"
......@@ -17,7 +17,7 @@ var (
)
func configure(_ *node.Plugin) {
webapi.Server.POST("drng/collectiveBeacon", collectiveBeacon.Handler)
webapi.Server.POST("drng/collectiveBeacon", collectivebeacon.Handler)
webapi.Server.GET("drng/info/committee", committee.Handler)
webapi.Server.GET("drng/info/randomness", randomness.Handler)
}
......@@ -6,6 +6,7 @@ import (
"github.com/labstack/echo"
)
// IndexRequest returns INDEX
func IndexRequest(c echo.Context) error {
return c.String(http.StatusOK, "INDEX")
}
......@@ -22,14 +22,14 @@ var (
func configure(plugin *node.Plugin) {
log = logger.NewLogger(PluginName)
webapi.Server.POST("message/findById", findMessageById)
webapi.Server.POST("message/findById", findMessageByID)
}
// findMessageById returns the array of messages for the
// findMessageByID returns the array of messages for the
// given message ids (MUST be encoded in base58), in the same order as the parameters.
// If a node doesn't have the message for a given ID in its ledger,
// the value at the index of that message ID is empty.
func findMessageById(c echo.Context) error {
func findMessageByID(c echo.Context) error {
var request Request
if err := c.Bind(&request); err != nil {
log.Info(err.Error())
......@@ -37,20 +37,20 @@ func findMessageById(c echo.Context) error {
}
var result []Message
for _, id := range request.Ids {
for _, id := range request.IDs {
log.Info("Received:", id)
msgId, err := message.NewId(id)
msgID, err := message.NewId(id)
if err != nil {
log.Info(err)
continue
}
msgObject := messagelayer.Tangle.Message(msgId)
msgObject := messagelayer.Tangle.Message(msgID)
if !msgObject.Exists() {
continue
}
msgMetadataObject := messagelayer.Tangle.MessageMetadata(msgId)
msgMetadataObject := messagelayer.Tangle.MessageMetadata(msgID)
if !msgMetadataObject.Exists() {
continue
}
......@@ -63,9 +63,9 @@ func findMessageById(c echo.Context) error {
Solid: msgMetadata.IsSolid(),
SolidificationTime: msgMetadata.SoldificationTime().Unix(),
},
Id: msg.Id().String(),
TrunkId: msg.TrunkId().String(),
BranchId: msg.BranchId().String(),
ID: msg.Id().String(),
TrunkID: msg.TrunkId().String(),
BranchID: msg.BranchId().String(),
IssuerPublicKey: msg.IssuerPublicKey().String(),
IssuingTime: msg.IssuingTime().Unix(),
SequenceNumber: msg.SequenceNumber(),
......@@ -89,15 +89,15 @@ type Response struct {
// Request holds the message ids to query.
type Request struct {
Ids []string `json:"ids"`
IDs []string `json:"ids"`
}
// Message contains information about a given message.
type Message struct {
Metadata `json:"metadata,omitempty"`
Id string `json:"Id,omitempty"`
TrunkId string `json:"trunkId,omitempty"`
BranchId string `json:"branchId,omitempty"`
ID string `json:"Id,omitempty"`
TrunkID string `json:"trunkId,omitempty"`
BranchID string `json:"branchId,omitempty"`
IssuerPublicKey string `json:"issuerPublicKey,omitempty"`
IssuingTime int64 `json:"issuingTime,omitempty"`
SequenceNumber uint64 `json:"sequenceNumber,omitempty"`
......
......@@ -5,9 +5,10 @@ import (
)
const (
BIND_ADDRESS = "webapi.bindAddress"
// CfgBindAddress defines the config flag of the web API binding address.
CfgBindAddress = "webapi.bindAddress"
)
func init() {
flag.String(BIND_ADDRESS, "127.0.0.1:8080", "the bind address for the web API")
flag.String(CfgBindAddress, "127.0.0.1:8080", "the bind address for the web API")
}
......@@ -4,13 +4,12 @@ import (
"context"
"time"
"github.com/iotaledger/goshimmer/packages/shutdown"
"github.com/iotaledger/goshimmer/plugins/config"
"github.com/iotaledger/hive.go/daemon"
"github.com/iotaledger/hive.go/logger"
"github.com/iotaledger/hive.go/node"
"github.com/labstack/echo"
"github.com/iotaledger/goshimmer/packages/shutdown"
"github.com/iotaledger/goshimmer/plugins/config"
)
// PluginName is the name of the web API plugin.
......@@ -20,6 +19,7 @@ var (
// Plugin is the plugin instance of the web API plugin.
Plugin = node.NewPlugin(PluginName, node.Enabled, configure, run)
log *logger.Logger
// Server is the web API server.
Server = echo.New()
)
......@@ -37,7 +37,7 @@ func run(plugin *node.Plugin) {
log.Info("Starting Web Server ... done")
go func() {
if err := Server.Start(config.Node.GetString(BIND_ADDRESS)); err != nil {
if err := Server.Start(config.Node.GetString(CfgBindAddress)); err != nil {
log.Info("Stopping Web Server ... done")
}
}()
......
package spammer
import (
"github.com/iotaledger/hive.go/daemon"
"github.com/iotaledger/goshimmer/packages/binary/spammer"
"github.com/iotaledger/goshimmer/packages/shutdown"
"github.com/iotaledger/goshimmer/plugins/messagelayer"
"github.com/iotaledger/goshimmer/plugins/webapi"
"github.com/iotaledger/hive.go/daemon"
"github.com/iotaledger/hive.go/node"
)
......
......@@ -29,11 +29,13 @@ func handleRequest(c echo.Context) error {
}
}
// Response is the HTTP response of a spammer request.
type Response struct {
Message string `json:"message"`
Error string `json:"error"`
}
// Request contains the parameters of a spammer request.
type Request struct {
Cmd string `json:"cmd"`
MPS int `json:"mps"`
......
......@@ -38,7 +38,7 @@ func newPeer(name string, identity *identity.Identity, dockerContainer *DockerCo
}
func (p *Peer) String() string {
return fmt.Sprintf("Peer:{%s, %s, %s, %d}", p.name, p.identity.ID().String(), p.BaseUrl(), p.TotalNeighbors())
return fmt.Sprintf("Peer:{%s, %s, %s, %d}", p.name, p.identity.ID().String(), p.BaseURL(), p.TotalNeighbors())
}
// TotalNeighbors returns the total number of neighbors the peer has.
......
......@@ -34,7 +34,7 @@ func TestRelayMessages(t *testing.T) {
// check for messages on every peer
for _, peer := range n.Peers() {
resp, err := peer.FindMessageById(ids)
resp, err := peer.FindMessageByID(ids)
require.NoError(t, err)
// check for the count of messages
......@@ -45,7 +45,7 @@ func TestRelayMessages(t *testing.T) {
for _, id := range ids {
for _, msg := range resp.Messages {
// if message found skip to next
if msg.Id == id {
if msg.ID == id {
continue outer
}
}
......
......@@ -10,25 +10,25 @@ var (
repeat = 1
)
func InitConfig() {
if config.Node.GetString(CFG_TARGET_NODE) == "" {
func initConfig() {
if config.Node.GetString(CfgTargetNode) == "" {
panic("Set the target node address\n")
}
target = config.Node.GetString(CFG_TARGET_NODE)
target = config.Node.GetString(CfgTargetNode)
if len(config.Node.GetStringSlice(CFG_TEST_NODES)) == 0 {
if len(config.Node.GetStringSlice(CfgTestNodes)) == 0 {
panic("Set node addresses\n")
}
nodes = append(nodes, config.Node.GetStringSlice(CFG_TEST_NODES)...)
nodes = append(nodes, config.Node.GetStringSlice(CfgTestNodes)...)
// optional settings
if config.Node.GetString(CFG_DATA) != "" {
msgData = config.Node.GetString(CFG_DATA)
if config.Node.GetString(CfgData) != "" {
msgData = config.Node.GetString(CfgData)
}
if config.Node.GetInt(CFG_COOLDOWN_TIME) > 0 {
cooldownTime = config.Node.GetInt(CFG_COOLDOWN_TIME)
if config.Node.GetInt(CfgCooldownTime) > 0 {
cooldownTime = config.Node.GetInt(CfgCooldownTime)
}
if config.Node.GetInt(CFG_REPEAT) > 0 {
repeat = config.Node.GetInt(CFG_REPEAT)
if config.Node.GetInt(CfgRepeat) > 0 {
repeat = config.Node.GetInt(CfgRepeat)
}
}
......@@ -10,26 +10,26 @@ import (
)
func testBroadcastData(api *client.GoShimmerAPI) (string, error) {
msgId, err := api.Data([]byte(msgData))
msgID, err := api.Data([]byte(msgData))
if err != nil {
return "", fmt.Errorf("broadcast failed: %w", err)
}
return msgId, nil
return msgID, nil
}
func testTargetGetMessagess(api *client.GoShimmerAPI, msgId string) error {
func testTargetGetMessagess(api *client.GoShimmerAPI, msgID string) error {
// query target node for broadcasted data
if _, err := api.FindMessageById([]string{msgId}); err != nil {
if _, err := api.FindMessageByID([]string{msgID}); err != nil {
return fmt.Errorf("querying the target node failed: %w", err)
}
return nil
}
func testNodesGetMessages(msgId string) error {
func testNodesGetMessages(msgID string) error {
// query nodes node for broadcasted data
for _, n := range nodes {
nodesApi := client.NewGoShimmerAPI(n)
if _, err := nodesApi.FindMessageById([]string{msgId}); err != nil {
nodesAPI := client.NewGoShimmerAPI(n)
if _, err := nodesAPI.FindMessageByID([]string{msgID}); err != nil {
return fmt.Errorf("querying node %s failed: %w", n, err)
}
fmt.Printf("msg found in node %s\n", n)
......@@ -41,29 +41,29 @@ func main() {
config.Init()
logger.Init()
InitConfig()
initConfig()
api := client.NewGoShimmerAPI(target)
for i := 0; i < repeat; i++ {
msgId, err := testBroadcastData(api)
msgID, err := testBroadcastData(api)
if err != nil {
fmt.Printf("%s\n", err)
break
}
fmt.Printf("msgId: %s\n", msgId)
fmt.Printf("msgID: %s\n", msgID)
// cooldown time
time.Sleep(time.Duration(cooldownTime) * time.Second)
// query target node
err = testTargetGetMessagess(api, msgId)
err = testTargetGetMessagess(api, msgID)
if err != nil {
fmt.Printf("%s\n", err)
break
}
// query test nodes
err = testNodesGetMessages(msgId)
err = testNodesGetMessages(msgID)
if err != nil {
fmt.Printf("%s\n", err)
break
......
......@@ -5,17 +5,22 @@ import (
)
const (
CFG_TARGET_NODE = "relayChecker.targetNode"
CFG_TEST_NODES = "relayChecker.testNodes"
CFG_DATA = "relayChecker.data"
CFG_COOLDOWN_TIME = "relayChecker.cooldownTime"
CFG_REPEAT = "relayChecker.repeat"
// CfgTargetNode defines the config flag of the target node.
CfgTargetNode = "relayChecker.targetNode"
// CfgTestNodes defines the config flag of the test nodes.
CfgTestNodes = "relayChecker.testNodes"
// CfgData defines the config flag of the data.
CfgData = "relayChecker.data"
// CfgCooldownTime defines the config flag of the cooldown time.
CfgCooldownTime = "relayChecker.cooldownTime"
// CfgRepeat defines the config flag of the repeat.
CfgRepeat = "relayChecker.repeat"
)
func init() {
flag.StringSlice(CFG_TEST_NODES, []string{""}, "the list of nodes to check after the cooldown")
flag.String(CFG_TARGET_NODE, "http://127.0.0.1:8080", "the target node from the which message will be broadcasted from")
flag.String(CFG_DATA, "TEST99BROADCAST99DATA", "data to broadcast")
flag.Int(CFG_COOLDOWN_TIME, 10, "the cooldown time after broadcasting the data on the specified target node")
flag.Int(CFG_REPEAT, 1, "the amount of times to repeat the relay-checker queries")
flag.StringSlice(CfgTargetNode, []string{""}, "the list of nodes to check after the cooldown")
flag.String(CfgTestNodes, "http://127.0.0.1:8080", "the target node from the which message will be broadcasted from")
flag.String(CfgData, "TEST99BROADCAST99DATA", "data to broadcast")
flag.Int(CfgCooldownTime, 10, "the cooldown time after broadcasting the data on the specified target node")
flag.Int(CfgRepeat, 1, "the amount of times to repeat the relay-checker queries")
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment