From fba813034dedccd09603e8ee52775be4abe4d788 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Wed, 23 Jun 2021 03:58:58 +0530 Subject: [PATCH] Refactored code added error logs --- context/context.go | 30 +++++----- context/service.go | 46 ++++++++++++++ context/tx.go | 96 ++++++++++++++++++++++++++++++ lite/tx.go | 7 ++- main.go | 9 +-- node/jobs.go | 11 ++-- node/node.go | 4 +- node/service.go | 49 --------------- node/tx.go | 77 ------------------------ rest/session/handlers.go | 60 +++++++++---------- rest/status/handlers.go | 2 +- rest/status/responses.go | 2 +- services/wireguard/cli/cli.go | 5 +- services/wireguard/types/config.go | 11 +--- services/wireguard/types/peer.go | 50 +++++++++------- services/wireguard/wireguard.go | 12 ++-- types/config.go | 28 ++++----- utils/rand/int.go | 15 +++++ 18 files changed, 270 insertions(+), 244 deletions(-) create mode 100644 context/service.go create mode 100644 context/tx.go delete mode 100644 node/service.go delete mode 100644 node/tx.go create mode 100644 utils/rand/int.go diff --git a/context/context.go b/context/context.go index 1189e57..19fe893 100644 --- a/context/context.go +++ b/context/context.go @@ -36,21 +36,21 @@ func (c *Context) WithRouter(v *mux.Router) *Context { c.router = v; func (c *Context) WithService(v types.Service) *Context { c.service = v; return c } func (c *Context) WithSessions(v *types.Sessions) *Context { c.sessions = v; return c } -func (c *Context) Address() hubtypes.NodeAddress { return c.Operator().Bytes() } -func (c *Context) Bandwidth() *hubtypes.Bandwidth { return c.bandwidth } -func (c *Context) Client() *lite.Client { return c.client } -func (c *Context) Config() *types.Config { return c.config } -func (c *Context) IntervalSetSessions() time.Duration { return c.Config().Node.IntervalSetSessions } -func (c *Context) IntervalSetStatus() time.Duration { return c.Config().Node.IntervalSetStatus } -func (c *Context) ListenOn() string { return c.Config().Node.ListenOn } -func (c *Context) Location() *types.GeoIPLocation { return c.location } -func (c *Context) Log() tmlog.Logger { return c.logger } -func (c *Context) Moniker() string { return c.Config().Node.Moniker } -func (c *Context) Operator() sdk.AccAddress { return c.client.FromAddress() } -func (c *Context) RemoteURL() string { return c.Config().Node.RemoteURL } -func (c *Context) Router() *mux.Router { return c.router } -func (c *Context) Service() types.Service { return c.service } -func (c *Context) Sessions() *types.Sessions { return c.sessions } +func (c *Context) Address() hubtypes.NodeAddress { return c.Operator().Bytes() } +func (c *Context) Bandwidth() *hubtypes.Bandwidth { return c.bandwidth } +func (c *Context) Client() *lite.Client { return c.client } +func (c *Context) Config() *types.Config { return c.config } +func (c *Context) IntervalSetSessions() time.Duration { return c.Config().Node.IntervalSetSessions } +func (c *Context) IntervalUpdateStatus() time.Duration { return c.Config().Node.IntervalUpdateStatus } +func (c *Context) ListenOn() string { return c.Config().Node.ListenOn } +func (c *Context) Location() *types.GeoIPLocation { return c.location } +func (c *Context) Log() tmlog.Logger { return c.logger } +func (c *Context) Moniker() string { return c.Config().Node.Moniker } +func (c *Context) Operator() sdk.AccAddress { return c.client.FromAddress() } +func (c *Context) RemoteURL() string { return c.Config().Node.RemoteURL } +func (c *Context) Router() *mux.Router { return c.router } +func (c *Context) Service() types.Service { return c.service } +func (c *Context) Sessions() *types.Sessions { return c.sessions } func (c *Context) IntervalUpdateSessions() time.Duration { return c.Config().Node.IntervalUpdateSessions diff --git a/context/service.go b/context/service.go new file mode 100644 index 0000000..672b954 --- /dev/null +++ b/context/service.go @@ -0,0 +1,46 @@ +package context + +import ( + "encoding/base64" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func (c *Context) RemovePeer(key string) error { + c.Log().Info("Removing peer from service", "key", key) + + data, err := base64.StdEncoding.DecodeString(key) + if err != nil { + c.Log().Error("Failed to decode the key", "error", err) + return err + } + + if err := c.Service().RemovePeer(data); err != nil { + c.Log().Error("Failed to remove the peer from service", "error", err) + return err + } + + c.Log().Info("Removed peer from service...") + return nil +} + +func (c *Context) RemoveSession(key string, address sdk.AccAddress) error { + c.Log().Info("Removing session from list", "key", key, "address", address) + + c.Sessions().DeleteByKey(key) + c.Sessions().DeleteByAddress(address) + + c.Log().Info("Removed session from list...") + return nil +} + +func (c *Context) RemovePeerAndSession(key string, address sdk.AccAddress) error { + if err := c.RemovePeer(key); err != nil { + return err + } + if err := c.RemoveSession(key, address); err != nil { + return err + } + + return nil +} diff --git a/context/tx.go b/context/tx.go new file mode 100644 index 0000000..a9ad346 --- /dev/null +++ b/context/tx.go @@ -0,0 +1,96 @@ +package context + +import ( + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + hubtypes "github.com/sentinel-official/hub/types" + nodetypes "github.com/sentinel-official/hub/x/node/types" + sessiontypes "github.com/sentinel-official/hub/x/session/types" + + "github.com/sentinel-official/dvpn-node/types" +) + +func (c *Context) RegisterNode() error { + c.Log().Info("Registering node...") + + _, err := c.Client().BroadcastTx( + nodetypes.NewMsgRegisterRequest( + c.Operator(), + c.Provider(), + c.Price(), + c.RemoteURL(), + ), + ) + if err != nil { + c.Log().Error("Failed to register node", "error", err) + return err + } + + return nil +} + +func (c *Context) UpdateNodeInfo() error { + c.Log().Info("Updating node info...") + + _, err := c.Client().BroadcastTx( + nodetypes.NewMsgUpdateRequest( + c.Address(), + c.Provider(), + c.Price(), + c.RemoteURL(), + ), + ) + if err != nil { + c.Log().Error("Failed to update node info", "error", err) + return err + } + + return nil +} + +func (c *Context) UpdateNodeStatus() error { + c.Log().Info("Updating node status...") + + _, err := c.Client().BroadcastTx( + nodetypes.NewMsgSetStatusRequest( + c.Address(), + hubtypes.StatusActive, + ), + ) + if err != nil { + c.Log().Error("Failed to update node status", "error", err) + return err + } + + return nil +} + +func (c *Context) UpdateSessions(items ...types.Session) error { + c.Log().Info("Updating sessions...") + + var messages []sdk.Msg + for _, item := range items { + messages = append(messages, + sessiontypes.NewMsgUpdateRequest( + c.Address(), + sessiontypes.Proof{ + Id: item.ID, + Duration: time.Since(item.ConnectedAt), + Bandwidth: hubtypes.NewBandwidthFromInt64(item.Download, item.Upload), + }, + nil, + ), + ) + } + + _, err := c.Client().BroadcastTx( + messages..., + ) + if err != nil { + c.Log().Error("Failed to update sessions", "error", err) + return err + } + + return nil +} diff --git a/lite/tx.go b/lite/tx.go index 90bbe30..25ed391 100644 --- a/lite/tx.go +++ b/lite/tx.go @@ -25,9 +25,11 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro ) if c.SimulateAndExecute() { - c.Log().Info("Calculating the gas by simulating the transaction...") + c.Log().Info("Calculating the Gas by simulating the transaction...") + _, adjusted, err := tx.CalculateGas(c.ctx.QueryWithData, txf, messages...) if err != nil { + c.Log().Error("Failed to calculate the Gas", "error", err) return nil, err } @@ -39,15 +41,18 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro txb, err := tx.BuildUnsignedTx(txf, messages...) if err != nil { + c.Log().Error("Failed to build the unsigned transaction", "error", err) return nil, err } if err := tx.Sign(txf, c.From(), txb, true); err != nil { + c.Log().Error("Failed to sign the transaction", "error", err) return nil, err } txBytes, err := c.TxConfig().TxEncoder()(txb.GetTx()) if err != nil { + c.Log().Error("Failed to encode the transaction", "error", err) return nil, err } diff --git a/main.go b/main.go index ead551b..10c961a 100644 --- a/main.go +++ b/main.go @@ -12,12 +12,8 @@ import ( "github.com/sentinel-official/dvpn-node/types" ) -func init() { - hubtypes.GetConfig().Seal() - cobra.EnableCommandSorting = false -} - func main() { + hubtypes.GetConfig().Seal() root := &cobra.Command{ Use: "sentinel-dvpn-node", SilenceUsage: true, @@ -26,11 +22,8 @@ func main() { root.AddCommand( cmd.ConfigCmd(), cmd.KeysCmd(), - flags.LineBreak, wireguard.Command(), - flags.LineBreak, cmd.StartCmd(), - flags.LineBreak, version.NewVersionCommand(), ) diff --git a/node/jobs.go b/node/jobs.go index e6a191b..c2f45d8 100644 --- a/node/jobs.go +++ b/node/jobs.go @@ -16,6 +16,7 @@ func (n *Node) jobSetSessions() error { for ; ; <-t.C { peers, err := n.Service().Peers() if err != nil { + n.Log().Error("Failed to get connected peers", "error", err) return err } n.Log().Info("Connected peers", "count", len(peers)) @@ -48,11 +49,11 @@ func (n *Node) jobSetSessions() error { } func (n *Node) jobUpdateStatus() error { - n.Log().Info("Starting job", "name", "update_status", "interval", n.IntervalSetStatus()) + n.Log().Info("Starting job", "name", "update_status", "interval", n.IntervalUpdateStatus()) - t := time.NewTicker(n.IntervalSetStatus()) + t := time.NewTicker(n.IntervalUpdateStatus()) for ; ; <-t.C { - if err := n.updateStatus(); err != nil { + if err := n.UpdateNodeStatus(); err != nil { return err } } @@ -98,7 +99,7 @@ func (n *Node) jobUpdateSessions() error { }() if remove { - if err := n.RemovePeerAndSession(items[i]); err != nil { + if err := n.RemovePeerAndSession(items[i].Key, items[i].Address); err != nil { return err } } @@ -110,7 +111,7 @@ func (n *Node) jobUpdateSessions() error { if len(items) == 0 { continue } - if err := n.updateSessions(items...); err != nil { + if err := n.UpdateSessions(items...); err != nil { return err } } diff --git a/node/node.go b/node/node.go index b1c06ba..13bf2c8 100644 --- a/node/node.go +++ b/node/node.go @@ -27,10 +27,10 @@ func (n *Node) Initialize() error { } if result == nil { - return n.register() + return n.RegisterNode() } - return n.updateInfo() + return n.UpdateNodeInfo() } func (n *Node) Start() error { diff --git a/node/service.go b/node/service.go deleted file mode 100644 index 3504abe..0000000 --- a/node/service.go +++ /dev/null @@ -1,49 +0,0 @@ -package node - -import ( - "encoding/base64" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/sentinel-official/dvpn-node/types" -) - -func (n *Node) RemovePeer(key string) error { - n.Log().Info("Removing peer from underlying service", "key", key) - - data, err := base64.StdEncoding.DecodeString(key) - if err != nil { - return err - } - - if err := n.Service().RemovePeer(data); err != nil { - return err - } - - n.Log().Debug("Removed peer from underlying service...") - return nil -} - -func (n *Node) RemoveSession(key string, address sdk.AccAddress) error { - n.Log().Info("Removing session", "key", key, "address", address) - - n.Sessions().DeleteByKey(key) - n.Sessions().DeleteByAddress(address) - - n.Log().Debug("Removed session...") - return nil -} - -func (n *Node) RemovePeerAndSession(v types.Session) error { - n.Log().Info("Removing peer and session", "id", v.ID, "key", v.Key) - - if err := n.RemovePeer(v.Key); err != nil { - return err - } - if err := n.RemoveSession(v.Key, v.Address); err != nil { - return err - } - - n.Log().Debug("Removed peer and session...") - return nil -} diff --git a/node/tx.go b/node/tx.go deleted file mode 100644 index 4714d9a..0000000 --- a/node/tx.go +++ /dev/null @@ -1,77 +0,0 @@ -package node - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - hubtypes "github.com/sentinel-official/hub/types" - nodetypes "github.com/sentinel-official/hub/x/node/types" - sessiontypes "github.com/sentinel-official/hub/x/session/types" - - "github.com/sentinel-official/dvpn-node/types" -) - -func (n *Node) register() error { - n.Log().Info("Registering node...") - - _, err := n.Client().BroadcastTx( - nodetypes.NewMsgRegisterRequest( - n.Operator(), - n.Provider(), - n.Price(), - n.RemoteURL(), - ), - ) - - return err -} - -func (n *Node) updateInfo() error { - n.Log().Info("Updating node info...") - - _, err := n.Client().BroadcastTx( - nodetypes.NewMsgUpdateRequest( - n.Address(), - n.Provider(), - n.Price(), - n.RemoteURL(), - ), - ) - - return err -} - -func (n *Node) updateStatus() error { - n.Log().Info("Updating node status...") - - _, err := n.Client().BroadcastTx( - nodetypes.NewMsgSetStatusRequest( - n.Address(), - hubtypes.StatusActive, - ), - ) - - return err -} - -func (n *Node) updateSessions(items ...types.Session) error { - n.Log().Info("Updating sessions...") - - var messages []sdk.Msg - for _, item := range items { - messages = append(messages, - sessiontypes.NewMsgUpdateRequest( - n.Address(), - sessiontypes.Proof{ - Id: item.ID, - Duration: time.Since(item.ConnectedAt), - Bandwidth: hubtypes.NewBandwidthFromInt64(item.Download, item.Upload), - }, - nil, - ), - ) - } - - _, err := n.Client().BroadcastTx(messages...) - return err -} diff --git a/rest/session/handlers.go b/rest/session/handlers.go index 287a54c..f21f561 100644 --- a/rest/session/handlers.go +++ b/rest/session/handlers.go @@ -61,11 +61,16 @@ func handlerAddSession(ctx *context.Context) http.HandlerFunc { return } if ok := account.GetPubKey().VerifySignature(sdk.Uint64ToBigEndian(id), signature); !ok { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 2, "failed to verify signature") + utils.WriteErrorToResponse(w, http.StatusBadRequest, 2, "failed to verify the signature") return } - if item := ctx.Sessions().GetByAddress(address); !item.Empty() { + item := ctx.Sessions().GetByAddress(address) + if item.Empty() { + item = ctx.Sessions().GetByKey(body.Key) + } + + if !item.Empty() { session, err := ctx.Client().QuerySession(item.ID) if err != nil { utils.WriteErrorToResponse(w, http.StatusInternalServerError, 3, err.Error()) @@ -80,94 +85,85 @@ func handlerAddSession(ctx *context.Context) http.HandlerFunc { return } - ctx.Sessions().DeleteByAddress(address) - } - - if item := ctx.Sessions().GetByKey(body.Key); !item.Empty() { - session, err := ctx.Client().QuerySession(item.ID) - if err != nil { - utils.WriteErrorToResponse(w, http.StatusInternalServerError, 4, err.Error()) - return - } - if session == nil { - utils.WriteErrorToResponse(w, http.StatusNotFound, 4, "session does not exist") - return - } - if session.Status.Equal(hubtypes.StatusActive) { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 4, fmt.Sprintf("invalid session status %s", session.Status)) + if err := ctx.RemovePeerAndSession(item.Key, item.Address); err != nil { + utils.WriteErrorToResponse(w, http.StatusInternalServerError, 3, err.Error()) return } - ctx.Sessions().DeleteByKey(body.Key) + if session.Status.Equal(hubtypes.StatusInactivePending) { + go func() { + _ = ctx.UpdateSessions(item) + }() + } } session, err := ctx.Client().QuerySession(id) if err != nil { - utils.WriteErrorToResponse(w, http.StatusInternalServerError, 5, err.Error()) + utils.WriteErrorToResponse(w, http.StatusInternalServerError, 4, err.Error()) return } if session == nil { - utils.WriteErrorToResponse(w, http.StatusNotFound, 5, "session does not exist") + utils.WriteErrorToResponse(w, http.StatusNotFound, 4, "session does not exist") return } if !session.Status.Equal(hubtypes.StatusActive) { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 5, fmt.Sprintf("invalid session status %s", session.Status)) + utils.WriteErrorToResponse(w, http.StatusBadRequest, 4, fmt.Sprintf("invalid session status %s", session.Status)) return } if session.Address != address.String() { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 5, "account address mismatch") + utils.WriteErrorToResponse(w, http.StatusBadRequest, 4, "account address mismatch") return } subscription, err := ctx.Client().QuerySubscription(session.Subscription) if err != nil { - utils.WriteErrorToResponse(w, http.StatusInternalServerError, 6, err.Error()) + utils.WriteErrorToResponse(w, http.StatusInternalServerError, 5, err.Error()) return } if subscription == nil { - utils.WriteErrorToResponse(w, http.StatusNotFound, 6, "subscription does not exist") + utils.WriteErrorToResponse(w, http.StatusNotFound, 5, "subscription does not exist") return } if !subscription.Status.Equal(hubtypes.Active) { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 6, fmt.Sprintf("invalid subscription status %s", subscription.Status)) + utils.WriteErrorToResponse(w, http.StatusBadRequest, 5, fmt.Sprintf("invalid subscription status %s", subscription.Status)) return } if subscription.Plan == 0 { if subscription.Node != ctx.Address().String() { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 7, "node address mismatch") + utils.WriteErrorToResponse(w, http.StatusBadRequest, 6, "node address mismatch") return } } else { ok, err := ctx.Client().HasNodeForPlan(id, ctx.Address()) if err != nil { - utils.WriteErrorToResponse(w, http.StatusInternalServerError, 7, err.Error()) + utils.WriteErrorToResponse(w, http.StatusInternalServerError, 6, err.Error()) return } if !ok { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 7, "node does not exist for plan") + utils.WriteErrorToResponse(w, http.StatusBadRequest, 6, "node does not exist for plan") return } } quota, err := ctx.Client().QueryQuota(subscription.Id, address) if err != nil { - utils.WriteErrorToResponse(w, http.StatusInternalServerError, 8, err.Error()) + utils.WriteErrorToResponse(w, http.StatusInternalServerError, 7, err.Error()) return } if quota == nil { - utils.WriteErrorToResponse(w, http.StatusNotFound, 8, "quota does not exist") + utils.WriteErrorToResponse(w, http.StatusNotFound, 7, "quota does not exist") return } if quota.Consumed.GTE(quota.Allocated) { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 8, "quota exceeded") + utils.WriteErrorToResponse(w, http.StatusBadRequest, 7, "quota exceeded") return } ctx.Log().Info("Adding new peer", "key", body.Key) result, err := ctx.Service().AddPeer(key) if err != nil { - utils.WriteErrorToResponse(w, http.StatusInternalServerError, 9, err.Error()) + utils.WriteErrorToResponse(w, http.StatusInternalServerError, 8, err.Error()) return } ctx.Log().Info("Added new peer", "key", body.Key, "count", ctx.Service().PeersCount()) diff --git a/rest/status/handlers.go b/rest/status/handlers.go index f662c43..0233bd3 100644 --- a/rest/status/handlers.go +++ b/rest/status/handlers.go @@ -22,8 +22,8 @@ func HandlerGetStatus(ctx *context.Context) http.HandlerFunc { Peers: ctx.Config().Handshake.Peers, }, IntervalSetSessions: ctx.IntervalSetSessions(), - IntervalSetStatus: ctx.IntervalSetStatus(), IntervalUpdateSessions: ctx.IntervalUpdateSessions(), + IntervalUpdateStatus: ctx.IntervalUpdateStatus(), Location: &Location{ City: ctx.Location().City, Country: ctx.Location().Country, diff --git a/rest/status/responses.go b/rest/status/responses.go index 5479471..2df9df0 100644 --- a/rest/status/responses.go +++ b/rest/status/responses.go @@ -27,8 +27,8 @@ type ( Bandwidth *Bandwidth `json:"bandwidth"` Handshake *Handshake `json:"handshake"` IntervalSetSessions time.Duration `json:"interval_set_sessions"` - IntervalSetStatus time.Duration `json:"interval_set_status"` IntervalUpdateSessions time.Duration `json:"interval_update_sessions"` + IntervalUpdateStatus time.Duration `json:"interval_update_status"` Location *Location `json:"location"` Moniker string `json:"moniker"` Operator string `json:"operator"` diff --git a/services/wireguard/cli/cli.go b/services/wireguard/cli/cli.go index 31cfdf8..3c68d20 100644 --- a/services/wireguard/cli/cli.go +++ b/services/wireguard/cli/cli.go @@ -6,8 +6,9 @@ import ( func Command() *cobra.Command { cmd := &cobra.Command{ - Use: "wireguard", - Short: "WireGuard sub-commands", + Use: "wireguard", + Aliases: []string{"wg"}, + Short: "WireGuard sub-commands", } cmd.AddCommand( diff --git a/services/wireguard/types/config.go b/services/wireguard/types/config.go index 2bcdf48..ac04f20 100644 --- a/services/wireguard/types/config.go +++ b/services/wireguard/types/config.go @@ -2,14 +2,14 @@ package types import ( "bytes" - "crypto/rand" "io/ioutil" - "math/big" "strings" "text/template" "github.com/pkg/errors" "github.com/spf13/viper" + + randutil "github.com/sentinel-official/dvpn-node/utils/rand" ) var ( @@ -62,18 +62,13 @@ func (c *Config) Validate() error { } func (c *Config) WithDefaultValues() *Config { - n, err := rand.Int(rand.Reader, big.NewInt(1<<16-1<<10)) - if err != nil { - panic(err) - } - key, err := NewPrivateKey() if err != nil { panic(err) } c.Interface = "wg0" - c.ListenPort = uint16(n.Int64() + 1<<10) + c.ListenPort = randutil.RandomPort() c.PrivateKey = key.String() return c diff --git a/services/wireguard/types/peer.go b/services/wireguard/types/peer.go index 9dc0951..2a7b557 100644 --- a/services/wireguard/types/peer.go +++ b/services/wireguard/types/peer.go @@ -10,45 +10,55 @@ type Peer struct { IPv6 IPv6 } +func (p Peer) Empty() bool { + return p.Identity == "" +} + type Peers struct { - m map[string]Peer - mutex *sync.RWMutex + sync.RWMutex + m map[string]Peer } func NewPeers() *Peers { return &Peers{ - m: make(map[string]Peer), - mutex: &sync.RWMutex{}, + m: make(map[string]Peer), } } -func (p *Peers) Get(key string) (Peer, bool) { - p.mutex.Lock() - defer p.mutex.Unlock() +func (p *Peers) Get(key string) Peer { + p.RLock() + defer p.RUnlock() - peer, ok := p.m[key] - return peer, ok + v, ok := p.m[key] + if !ok { + return Peer{} + } + + return v } -func (p *Peers) Put(item Peer) { - p.mutex.Lock() - defer p.mutex.Unlock() +func (p *Peers) Put(v Peer) { + p.Lock() + defer p.Unlock() - if _, ok := p.m[item.Identity]; !ok { - p.m[item.Identity] = item + _, ok := p.m[v.Identity] + if ok { + return } + + p.m[v.Identity] = v } -func (p *Peers) Delete(key string) { - p.mutex.Lock() - defer p.mutex.Unlock() +func (p *Peers) Delete(v string) { + p.Lock() + defer p.Unlock() - delete(p.m, key) + delete(p.m, v) } func (p *Peers) Len() int { - p.mutex.Lock() - defer p.mutex.Unlock() + p.RLock() + defer p.RUnlock() return len(p.m) } diff --git a/services/wireguard/wireguard.go b/services/wireguard/wireguard.go index 15604a1..3e048dc 100644 --- a/services/wireguard/wireguard.go +++ b/services/wireguard/wireguard.go @@ -123,9 +123,9 @@ func (w *WireGuard) AddPeer(data []byte) (result []byte, err error) { return nil, err } - if peer, ok := w.peers.Get(identity); ok { - w.peers.Delete(identity) - w.pool.Release(peer.IPv4, peer.IPv6) + if v := w.peers.Get(identity); !v.Empty() { + w.peers.Delete(v.Identity) + w.pool.Release(v.IPv4, v.IPv6) } w.peers.Put( @@ -154,9 +154,9 @@ func (w *WireGuard) RemovePeer(data []byte) error { return err } - if peer, ok := w.peers.Get(identity); ok { - w.peers.Delete(identity) - w.pool.Release(peer.IPv4, peer.IPv6) + if v := w.peers.Get(identity); !v.Empty() { + w.peers.Delete(v.Identity) + w.pool.Release(v.IPv4, v.IPv6) } return nil diff --git a/types/config.go b/types/config.go index 69d8156..fc0ac40 100644 --- a/types/config.go +++ b/types/config.go @@ -2,10 +2,8 @@ package types import ( "bytes" - "crypto/rand" "fmt" "io/ioutil" - "math/big" "strings" "text/template" "time" @@ -15,6 +13,8 @@ import ( "github.com/pkg/errors" hubtypes "github.com/sentinel-official/hub/types" "github.com/spf13/viper" + + randutil "github.com/sentinel-official/dvpn-node/utils/rand" ) var ( @@ -56,12 +56,12 @@ from = "{{ .Keyring.From }}" # Time interval between each set_sessions operation interval_set_sessions = "{{ .Node.IntervalSetSessions }}" -# Time interval between each set_status transaction -interval_set_status = "{{ .Node.IntervalSetStatus }}" - # Time interval between each update_sessions transaction interval_update_sessions = "{{ .Node.IntervalUpdateSessions }}" +# Time interval between each set_status transaction +interval_update_status = "{{ .Node.IntervalUpdateStatus }}" + # API listen-address listen_on = "{{ .Node.ListenOn }}" @@ -189,8 +189,8 @@ func (c *KeyringConfig) WithDefaultValues() *KeyringConfig { type NodeConfig struct { IntervalSetSessions time.Duration `json:"interval_set_sessions" mapstructure:"interval_set_sessions"` - IntervalSetStatus time.Duration `json:"interval_set_status" mapstructure:"interval_set_status"` IntervalUpdateSessions time.Duration `json:"interval_update_sessions" mapstructure:"interval_update_sessions"` + IntervalUpdateStatus time.Duration `json:"interval_update_status" mapstructure:"interval_update_status"` ListenOn string `json:"listen_on" mapstructure:"listen_on"` Moniker string `json:"moniker" mapstructure:"moniker"` Price string `json:"price" mapstructure:"price"` @@ -206,12 +206,12 @@ func (c *NodeConfig) Validate() error { if c.IntervalSetSessions <= 0 { return errors.New("interval_set_sessions must be positive") } - if c.IntervalSetStatus <= 0 { - return errors.New("interval_set_status must be positive") - } if c.IntervalUpdateSessions <= 0 { return errors.New("interval_update_sessions must be positive") } + if c.IntervalUpdateStatus <= 0 { + return errors.New("interval_update_status must be positive") + } if c.ListenOn == "" { return errors.New("listen_on cannot be empty") } @@ -240,15 +240,9 @@ func (c *NodeConfig) Validate() error { func (c *NodeConfig) WithDefaultValues() *NodeConfig { c.IntervalSetSessions = 1 * 120 * time.Second - c.IntervalSetStatus = 0.9 * 60 * time.Minute c.IntervalUpdateSessions = 0.9 * 120 * time.Minute - - n, err := rand.Int(rand.Reader, big.NewInt(1<<16-1<<10)) - if err != nil { - panic(err) - } - - c.ListenOn = fmt.Sprintf("0.0.0.0:%d", uint16(n.Int64()+1<<10)) + c.IntervalUpdateStatus = 0.9 * 60 * time.Minute + c.ListenOn = fmt.Sprintf("0.0.0.0:%d", randutil.RandomPort()) return c } diff --git a/utils/rand/int.go b/utils/rand/int.go new file mode 100644 index 0000000..c35085f --- /dev/null +++ b/utils/rand/int.go @@ -0,0 +1,15 @@ +package rand + +import ( + "crypto/rand" + "math/big" +) + +func RandomPort() uint16 { + n, err := rand.Int(rand.Reader, big.NewInt(1<<16-1<<10)) + if err != nil { + panic(err) + } + + return uint16(n.Int64() + 1<<10) +}