forked from NebulousLabs/Sia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peers.go
288 lines (255 loc) · 7.49 KB
/
peers.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package gateway
import (
"errors"
"net"
"time"
"github.com/NebulousLabs/Sia/build"
"github.com/NebulousLabs/Sia/crypto"
"github.com/NebulousLabs/Sia/encoding"
"github.com/NebulousLabs/Sia/modules"
"github.com/inconshreveable/muxado"
)
const (
// the gateway will abort a connection attempt after this long
dialTimeout = 2 * time.Minute
// the gateway will sleep this long between incoming connections
acceptInterval = 3 * time.Second
// the gateway will not make outbound connections above this threshold
wellConnectedThreshold = 8
// the gateway will not accept inbound connections above this threshold
fullyConnectedThreshold = 128
// the gateway will ask for more addresses below this threshold
minNodeListLen = 100
)
type peer struct {
addr modules.NetAddress
sess muxado.Session
inbound bool
}
func (p *peer) open() (modules.PeerConn, error) {
conn, err := p.sess.Open()
if err != nil {
return nil, err
}
return &peerConn{conn}, nil
}
func (p *peer) accept() (modules.PeerConn, error) {
conn, err := p.sess.Accept()
if err != nil {
return nil, err
}
return &peerConn{conn}, nil
}
// addPeer adds a peer to the Gateway's peer list and spawns a listener thread
// to handle its requests.
func (g *Gateway) addPeer(p *peer) {
g.peers[p.addr] = p
go g.listenPeer(p)
}
// randomPeer returns a random peer from the gateway's peer list.
func (g *Gateway) randomPeer() (modules.NetAddress, error) {
if len(g.peers) > 0 {
r, _ := crypto.RandIntn(len(g.peers))
for addr := range g.peers {
if r <= 0 {
return addr, nil
}
r--
}
}
return "", errNoPeers
}
// randomInboundPeer returns a random peer that initiated its connection.
func (g *Gateway) randomInboundPeer() (modules.NetAddress, error) {
if len(g.peers) > 0 {
r, _ := crypto.RandIntn(len(g.peers))
for addr, peer := range g.peers {
// only select inbound peers
if !peer.inbound {
continue
}
if r <= 0 {
return addr, nil
}
r--
}
}
return "", errNoPeers
}
// listen handles incoming connection requests. If the connection is accepted,
// the peer will be added to the Gateway's peer list.
func (g *Gateway) listen() {
for {
conn, err := g.listener.Accept()
if err != nil {
return
}
go g.acceptConn(conn)
// Sleep after each accept. This limits the rate at which the Gateway
// will accept new connections. The intent here is to prevent new
// incoming connections from kicking out old ones before they have a
// chance to request additional nodes.
time.Sleep(acceptInterval)
}
}
// acceptConn adds a connecting node as a peer.
func (g *Gateway) acceptConn(conn net.Conn) {
addr := modules.NetAddress(conn.RemoteAddr().String())
g.log.Printf("INFO: %v wants to connect", addr)
// read version
var remoteVersion string
if err := encoding.ReadObject(conn, &remoteVersion, maxAddrLength); err != nil {
conn.Close()
g.log.Printf("INFO: %v wanted to connect, but we could not read their version: %v", addr, err)
return
}
// check that version is acceptable
// NOTE: this version must be bumped whenever the gateway or consensus
// breaks compatibility.
if build.VersionCmp(remoteVersion, "0.3.3") < 0 {
encoding.WriteObject(conn, "reject")
conn.Close()
g.log.Printf("INFO: %v wanted to connect, but their version (%v) was unacceptable", addr, remoteVersion)
return
}
// respond with our version
if err := encoding.WriteObject(conn, build.Version); err != nil {
conn.Close()
g.log.Printf("INFO: could not write version ack to %v: %v", addr, err)
return
}
// If we are already fully connected, kick out an old peer to make room
// for the new one. Importantly, prioritize kicking a peer with the same
// IP as the connecting peer. This protects against Sybil attacks.
id := g.mu.Lock()
if len(g.peers) >= fullyConnectedThreshold {
// first choose a random peer, preferably inbound. If have only
// outbound peers, we'll wind up kicking an outbound peer; but
// subsequent inbound connections will kick each other instead of
// continuing to replace outbound peers.
kick, err := g.randomInboundPeer()
if err != nil {
kick, _ = g.randomPeer()
}
// if another peer shares this IP, choose that one instead
for p := range g.peers {
if p.Host() == addr.Host() {
kick = p
break
}
}
g.peers[kick].sess.Close()
delete(g.peers, kick)
g.log.Printf("INFO: disconnected from %v to make room for %v", kick, addr)
}
// add the peer
g.addPeer(&peer{addr: addr, sess: muxado.Server(conn), inbound: true})
g.mu.Unlock(id)
g.log.Printf("INFO: accepted connection from new peer %v (v%v)", addr, remoteVersion)
}
// Connect establishes a persistent connection to a peer, and adds it to the
// Gateway's peer list.
func (g *Gateway) Connect(addr modules.NetAddress) error {
if addr == g.Address() {
return errors.New("can't connect to our own address")
}
id := g.mu.RLock()
_, exists := g.peers[addr]
g.mu.RUnlock(id)
if exists {
return errors.New("peer already added")
}
conn, err := net.DialTimeout("tcp", string(addr), dialTimeout)
if err != nil {
return err
}
// send our version
if err := encoding.WriteObject(conn, build.Version); err != nil {
return err
}
// read version ack
var remoteVersion string
if err := encoding.ReadObject(conn, &remoteVersion, maxAddrLength); err != nil {
return err
} else if remoteVersion == "reject" {
return errors.New("peer rejected connection")
}
// decide whether to accept this version
if build.VersionCmp(remoteVersion, "0.3.3") < 0 {
conn.Close()
return errors.New("unacceptable version: " + remoteVersion)
}
g.log.Println("INFO: connected to new peer", addr)
id = g.mu.Lock()
g.addPeer(&peer{addr: addr, sess: muxado.Client(conn), inbound: false})
g.mu.Unlock(id)
// call initRPCs
id = g.mu.RLock()
for name, fn := range g.initRPCs {
go g.RPC(addr, name, fn)
}
g.mu.RUnlock(id)
return nil
}
// Disconnect terminates a connection to a peer and removes it from the
// Gateway's peer list. The peer's address remains in the node list.
func (g *Gateway) Disconnect(addr modules.NetAddress) error {
id := g.mu.RLock()
p, exists := g.peers[addr]
g.mu.RUnlock(id)
if !exists {
return errors.New("not connected to that node")
}
p.sess.Close()
id = g.mu.Lock()
delete(g.peers, addr)
g.mu.Unlock(id)
g.log.Println("INFO: disconnected from peer", addr)
return nil
}
// threadedPeerManager tries to keep the Gateway well-connected. As long as
// the Gateway is not well-connected, it tries to connect to random nodes.
func (g *Gateway) threadedPeerManager() {
for {
// If we are well-connected, sleep in increments of five minutes until
// we are no longer well-connected.
id := g.mu.RLock()
numOutboundPeers := 0
for _, p := range g.peers {
if !p.inbound {
numOutboundPeers++
}
}
addr, err := g.randomNode()
g.mu.RUnlock(id)
if numOutboundPeers >= wellConnectedThreshold {
select {
case <-time.After(5 * time.Minute):
case <-g.closeChan:
return
}
continue
}
// Try to connect to a random node. Instead of blocking on Connect, we
// spawn a goroutine and sleep for five seconds. This allows us to
// continue making connections if the node is unresponsive.
if err == nil {
go g.Connect(addr)
}
select {
case <-time.After(5 * time.Second):
case <-g.closeChan:
return
}
}
}
// Peers returns the addresses currently connected to the Gateway.
func (g *Gateway) Peers() []modules.NetAddress {
id := g.mu.RLock()
defer g.mu.RUnlock(id)
var peers []modules.NetAddress
for addr := range g.peers {
peers = append(peers, addr)
}
return peers
}