-
Notifications
You must be signed in to change notification settings - Fork 47
/
connector.go
257 lines (201 loc) · 5.98 KB
/
connector.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT License was not distributed with this
// file, you can obtain one at https://opensource.org/licenses/MIT.
//
// Copyright (c) DUSK NETWORK. All rights reserved.
package peer
import (
"bytes"
"context"
"errors"
"net"
"sync"
"time"
"github.com/dusk-network/dusk-blockchain/pkg/config"
"github.com/dusk-network/dusk-blockchain/pkg/core/consensus/capi"
"github.com/dusk-network/dusk-blockchain/pkg/p2p/wire/message"
"github.com/dusk-network/dusk-blockchain/pkg/p2p/wire/protocol"
"github.com/dusk-network/dusk-blockchain/pkg/p2p/wire/topics"
"github.com/dusk-network/dusk-blockchain/pkg/util/nativeutils/eventbus"
"github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus"
)
const (
defaultDialTimeout = 5
defaultMaxConnections = 50
peerCountTime = 30 * time.Second
)
var plog = logrus.WithField("process", "peer_conn")
type connectFunc func(context.Context, *Reader, *Writer)
// Connector is responsible for accepting incoming connection requests, and
// establishing outward connections with desired peers.
type Connector struct {
eventBus eventbus.Broker
gossip *protocol.Gossip
readerFactory *ReaderFactory
l net.Listener
lock sync.RWMutex
registry map[string]struct{}
services protocol.ServiceFlag
connectFunc connectFunc
}
// NewConnector creates a new peer connector, and spawns a goroutine that will
// accept incoming connection requests on the current address, with the given port.
func NewConnector(eb eventbus.Broker, gossip *protocol.Gossip, port string,
processor *MessageProcessor, services protocol.ServiceFlag,
connectFunc connectFunc,
) *Connector {
addrPort := ":" + port
listener, err := net.Listen("tcp", addrPort)
if err != nil {
plog.WithError(err).
Panic("could not establish a listener")
}
c := &Connector{
eventBus: eb,
gossip: gossip,
readerFactory: NewReaderFactory(processor),
l: listener,
registry: make(map[string]struct{}),
services: services,
connectFunc: connectFunc,
}
processor.Register(topics.Addr, c.ProcessNewAddress)
go func(c *Connector) {
for {
conn, err := c.l.Accept()
if err != nil {
plog.WithField("r_addr", conn.RemoteAddr().String()).
WithError(err).
Warnln("error accepting conn request")
return
}
c.acceptConnection(conn)
}
}(c)
if config.Get().API.Enabled {
go c.logPeerCount()
}
return c
}
// Close the listener.
func (c *Connector) Close() error {
return c.l.Close()
}
func (c *Connector) logPeerCount() {
ticker := time.NewTicker(peerCountTime)
for {
<-ticker.C
store := capi.GetStormDBInstance()
for addr := range c.registry {
// save count
peerCount := capi.PeerCount{
ID: addr,
LastSeen: time.Now(),
}
if err := store.Save(&peerCount); err != nil {
log.Error("failed to save peerCount into StormDB")
}
}
}
}
// ProcessNewAddress will handle a new Addr message from the network.
// Satisfies the peer.ProcessorFunc interface.
func (c *Connector) ProcessNewAddress(srcPeerID string, m message.Message) ([]bytes.Buffer, error) {
maxConn := 0
if maxConn == 0 {
maxConn = defaultMaxConnections
}
if c.GetConnectionsCount() > maxConn {
return nil, errors.New("max amount of connections reached")
}
a := m.Payload().(message.Addr)
return nil, c.Connect(a.NetAddr)
}
// Connect dials a connection with its string, then on succession
// we pass the connection and the address to the OnConn method.
func (c *Connector) Connect(addr string) error {
conn, err := c.Dial(addr)
if err != nil {
return err
}
c.proposeConnection(conn)
return nil
}
// Dial dials up a connection, given its address string.
func (c *Connector) Dial(addr string) (net.Conn, error) {
t := defaultDialTimeout
dialTimeout := time.Duration(t) * time.Second
conn, err := net.DialTimeout("tcp", addr, dialTimeout)
if err != nil {
return nil, err
}
return conn, nil
}
func (c *Connector) acceptConnection(conn net.Conn) {
pConn := NewConnection(conn, c.gossip)
peerReader := c.readerFactory.SpawnReader(pConn)
raddr := conn.RemoteAddr().String()
if err := peerReader.Accept(c.services); err != nil {
plog.WithField("r_addr", raddr).
WithError(err).
WithField("type", "inbound").
Warnln("error performing handshake")
return
}
plog.WithField("r_addr", raddr).WithField("type", "inbound").
Infoln("peer_connection established")
c.addPeer(peerReader.Addr())
peerWriter := NewWriter(pConn, c.eventBus)
go func() {
c.connectFunc(context.Background(), peerReader, peerWriter)
c.removePeer(peerReader.Addr())
}()
}
func (c *Connector) proposeConnection(conn net.Conn) {
pConn := NewConnection(conn, c.gossip)
peerWriter := NewWriter(pConn, c.eventBus)
if err := peerWriter.Connect(c.services); err != nil {
plog.WithField("r_addr", conn.RemoteAddr().String()).
WithField("type", "outbound").
WithError(err).Warnln("error performing handshake")
return
}
address := peerWriter.Addr()
plog.WithField("r_addr", address).WithField("type", "outbound").
Infoln("peer_connection established")
peerReader := c.readerFactory.SpawnReader(pConn)
c.addPeer(peerWriter.Addr())
go func() {
c.connectFunc(context.Background(), peerReader, peerWriter)
c.removePeer(peerWriter.Addr())
}()
}
func (c *Connector) addPeer(address string) {
c.lock.Lock()
defer c.lock.Unlock()
c.registry[address] = struct{}{}
}
func (c *Connector) removePeer(address string) {
c.lock.Lock()
defer c.lock.Unlock()
delete(c.registry, address)
if config.Get().API.Enabled {
go func() {
peerCount := capi.PeerCount{
ID: address,
}
store := capi.GetStormDBInstance()
// delete count
if err := store.Delete(&peerCount); err != nil {
plog.Error("failed to Delete peerCount into StormDB")
}
}()
}
}
// GetConnectionsCount returns the amount of active connections the node has.
func (c *Connector) GetConnectionsCount() int {
c.lock.RLock()
defer c.lock.RUnlock()
return len(c.registry)
}