-
Notifications
You must be signed in to change notification settings - Fork 54
/
server.go
317 lines (290 loc) · 6.91 KB
/
server.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package p2p
import (
"bytes"
"crypto/ecdsa"
"errors"
"github.com/xfs-network/xlibp2p/discover"
"github.com/xfs-network/xlibp2p/log"
"github.com/xfs-network/xlibp2p/nat"
"net"
"sync"
"time"
)
const (
flagInbound = 1
flagOutbound = 1 << 1
flagStatic = 1 << 2
flagDynamic = 1 << 3
)
type Server interface {
Node() *discover.Node
NodeId() discover.NodeId
Peers() []Peer
AddPeer(node *discover.Node)
RemovePeer(node discover.NodeId)
Bind(p Protocol)
Start() error
Stop()
}
// server manages all peer connections.
//
// The fields of Server are used as configuration parameters.
// You should set them before starting the Server. Fields may not be
// modified while the server is running.
type server struct {
nodeId discover.NodeId
node *discover.Node
config Config
mu sync.Mutex
running bool
//protocols contains the protocols supported by the server.
//Matching protocols are launched for each peer.
protocols []Protocol
close chan struct{}
addpeer chan *peerConn
addstatic chan *discover.Node
rmstatic chan discover.NodeId
delpeer chan Peer
peers map[discover.NodeId]Peer
table *discover.Table
logger log.Logger
lastLookup time.Time
}
// Config Background network service configuration
type Config struct {
Nat nat.Mapper
ListenAddr string
Key *ecdsa.PrivateKey
Discover bool
NodeDBPath string
StaticNodes []*discover.Node
BootstrapNodes []*discover.Node
MaxPeers int
Logger log.Logger
Encoder encoder
}
// NewServer Creates background service object
func NewServer(config Config) Server {
srv := &server{
config: config,
logger: config.Logger,
}
if config.Logger == nil {
srv.logger = log.DefaultLogger()
}
currentKey := srv.config.Key
srv.nodeId = discover.PubKey2NodeId(currentKey.PublicKey)
return srv
}
// Bind network protocol function
func (srv *server) Bind(p Protocol) {
if srv.protocols == nil {
srv.protocols = make([]Protocol, 0)
}
// Add network protocol
srv.protocols = append(srv.protocols, p)
}
// Stop background network function
func (srv *server) Stop() {
close(srv.close)
srv.table.Close()
}
type udpcnn interface {
LocalAddr() net.Addr
}
func (srv *server) listenUDP() (*discover.Table, udpcnn, error ) {
addr, err := net.ResolveUDPAddr("udp", srv.config.ListenAddr)
if err != nil {
return nil, nil, err
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
return nil, nil, err
}
table, _ := discover.NewUDP(srv.config.Key, conn, srv.config.NodeDBPath, srv.config.Nat)
return table, conn, nil
}
// Start start running the server.
func (srv *server) Start() error {
srv.mu.Lock()
defer srv.mu.Unlock()
if srv.running {
return errors.New("server already running")
}
srv.running = true
// Peer to peer session entity
srv.addpeer = make(chan *peerConn)
srv.addstatic = make(chan *discover.Node)
srv.rmstatic = make(chan discover.NodeId)
srv.delpeer = make(chan Peer)
srv.close = make(chan struct{})
var err error
var uconn udpcnn = nil
// launch node discovery and UDP listener
if srv.config.Discover {
srv.table, uconn, err = srv.listenUDP()
if err != nil {
return err
}
}
dynPeers := srv.config.MaxPeers / 2
if !srv.config.Discover {
dynPeers = 0
}
dialer := newDialState(srv.config.StaticNodes, srv.table, dynPeers)
// launch TCP listener to accept connection
realaddr := uconn.LocalAddr().(*net.UDPAddr)
if err = srv.listenAndServe(realaddr.Port); err != nil {
return err
}
go srv.run(dialer)
srv.running = true
return nil
}
func (srv *server) run(dialer *dialstate) {
srv.peers = make(map[discover.NodeId]Peer)
tasks := make([]task, 0)
pendingTasks := make([]task, 0)
taskdone := make(chan task)
delTask := func(t task) {
for i := range tasks {
if tasks[i] == t {
tasks = append(tasks[:i], tasks[i+1:]...)
break
}
}
}
scheduleTasks := func(new []task) {
pt := append(pendingTasks, new...)
start := 16 - len(tasks)
if len(pt) < start {
start = len(pt)
}
if start > 0 {
tasks = append(tasks, pt[:start]...)
for _, t := range pt[:start] {
tt := t
go func() {
tt.Do(srv)
taskdone <- tt
}()
}
copy(pt, pt[start:])
// pending tasks
pendingTasks = pt[:len(pt)-start]
}
}
for {
now := time.Now()
nt := dialer.newTasks(len(pendingTasks)+len(tasks), srv.peers, now)
// schedule tasks
scheduleTasks(nt)
select {
case n := <-srv.addstatic:
dialer.addStatic(n)
case n := <-srv.rmstatic:
dialer.removeStatic(n)
for k, v := range srv.peers {
if bytes.Equal(k[:], n[:]) {
v.Close()
}
}
delete(srv.peers, n)
// add peer
case c := <-srv.addpeer:
p := newPeer(c, srv.protocols, srv.config.Encoder)
srv.peers[c.id] = p
srv.logger.Infof("save peer id to peers: %s", c.id)
go srv.runPeer(p)
// task is done
case t := <-taskdone:
dialer.taskDone(t, now)
delTask(t)
// delete peer
case p := <-srv.delpeer:
pId := p.ID()
delete(srv.peers, pId)
}
}
}
func (srv *server) runPeer(peer Peer) {
peer.Run()
srv.delpeer <- peer
}
func (srv *server) listenAndServe(realPort int) error {
addr, err := net.ResolveTCPAddr("tcp", srv.config.ListenAddr)
addr.Port = realPort
ln, err := net.ListenTCP("tcp", addr)
laddr := ln.Addr().(*net.TCPAddr)
if err != nil {
srv.logger.Errorf("p2p listen and serve on %s err: %v", laddr, err)
return err
}
srv.logger.Infof("p2p listen and serve on %s", laddr)
srv.node = discover.NewNode(addr.IP, uint16(addr.Port), uint16(addr.Port), srv.nodeId)
srv.logger.Infof("p2p server node id: %s", srv.nodeId)
go srv.listenLoop(ln)
if !laddr.IP.IsLoopback() && srv.config.Nat != nil {
//srv.loopWG.Add(1)
go func() {
srv.logger.Debugf("nat mapping \"xlibp2p server\" port: %d", laddr.Port)
nat.Map(srv.config.Nat, srv.close, "tcp", laddr.Port, laddr.Port, "xlibp2p server")
//srv.loopWG.Done()
}()
}
return nil
}
// listenLoop runs in its own goroutine and accepts
// request of connections.
func (srv *server) listenLoop(ln net.Listener) {
defer func() {
if err := ln.Close(); err != nil {
srv.logger.Errorln(err)
}
}()
for {
rw, err := ln.Accept()
if err != nil {
srv.logger.Errorf("p2p listenner accept err %v", err)
return
}
c := srv.newPeerConn(rw, flagInbound, nil)
go c.serve()
}
}
func (srv *server) AddPeer(node *discover.Node) {
srv.addstatic <- node
}
func (srv *server) Peers() []Peer {
tmp := make([]Peer, 0)
for _, v := range srv.peers {
tmp = append(tmp, v)
}
return tmp
}
func (srv *server) RemovePeer(nId discover.NodeId) {
srv.rmstatic <- nId
}
func (srv *server) NodeId() discover.NodeId {
return srv.nodeId
}
func (srv *server) Node() *discover.Node {
return srv.node
}
func (srv *server) newPeerConn(rw net.Conn, flag int, dst *discover.NodeId) *peerConn {
pubKey := srv.config.Key.PublicKey
mId := discover.PubKey2NodeId(pubKey)
c := &peerConn{
logger: srv.logger,
self: mId,
flag: flag,
server: srv,
key: srv.config.Key,
rw: rw,
version: version1,
}
if dst != nil {
c.id = *dst
}
return c
}