/
server.go
1403 lines (1241 loc) · 43.2 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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// Package p2p implements the Ethereum p2p network protocols.
package p2p
import (
"bytes"
"crypto/ecdsa"
"encoding/hex"
"errors"
"fmt"
"net"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/DxChainNetwork/godx/common"
"github.com/DxChainNetwork/godx/common/mclock"
"github.com/DxChainNetwork/godx/crypto"
"github.com/DxChainNetwork/godx/event"
"github.com/DxChainNetwork/godx/log"
"github.com/DxChainNetwork/godx/p2p/discover"
"github.com/DxChainNetwork/godx/p2p/discv5"
"github.com/DxChainNetwork/godx/p2p/enode"
"github.com/DxChainNetwork/godx/p2p/enr"
"github.com/DxChainNetwork/godx/p2p/nat"
"github.com/DxChainNetwork/godx/p2p/netutil"
"github.com/DxChainNetwork/godx/rlp"
)
const (
defaultDialTimeout = 15 * time.Second
// Connectivity defaults.
maxActiveDialTasks = 16
defaultMaxPendingPeers = 50
defaultDialRatio = 3
// Maximum time allowed for reading a complete message.
// This is effectively the amount of time a connection can be idle.
frameReadTimeout = 30 * time.Second
// Maximum amount of time allowed for writing a complete message.
frameWriteTimeout = 20 * time.Second
)
var errServerStopped = errors.New("server stopped")
// Config holds Server options.
type Config struct {
// This field must be set to a valid secp256k1 private key.
//REQUIRED
PrivateKey *ecdsa.PrivateKey `toml:"-"`
// MaxPeers is the maximum number of peers that can be
// connected. It must be greater than zero.
MaxPeers int
// MaxPendingPeers is the maximum number of peers that can be pending in the
// handshake phase, counted separately for inbound and outbound connections.
// Zero defaults to preset values.
MaxPendingPeers int `toml:",omitempty"`
// DialRatio controls the ratio of inbound to dialed connections.
// Example: a DialRatio of 2 allows 1/2 of connections to be dialed.
// Setting DialRatio to zero defaults it to 3.
DialRatio int `toml:",omitempty"`
// NoDiscovery can be used to disable the peer discovery mechanism.
// Disabling is useful for protocol debugging (manual topology).
NoDiscovery bool
// DiscoveryV5 specifies whether the new topic-discovery based V5 discovery
// protocol should be started or not.
DiscoveryV5 bool `toml:",omitempty"`
// Name sets the node name of this server.
// Use common.MakeName to create a name that follows existing conventions.
Name string `toml:"-"`
// BootstrapNodes are used to establish connectivity
// with the rest of the network.
BootstrapNodes []*enode.Node
// BootstrapNodesV5 are used to establish connectivity
// with the rest of the network using the V5 discovery
// protocol.
BootstrapNodesV5 []*discv5.Node `toml:",omitempty"`
// Static nodes are used as pre-configured connections which are always
// maintained and re-connected on disconnects.
StaticNodes []*enode.Node
// Trusted nodes are used as pre-configured connections which are always
// allowed to connect, even above the peer limit.
TrustedNodes []*enode.Node
// Connectivity can be restricted to certain IP networks.
// If this option is set to a non-nil value, only hosts which match one of the
// IP networks contained in the list are considered.
NetRestrict *netutil.Netlist `toml:",omitempty"`
// NodeDatabase is the path to the database containing the previously seen
// live nodes in the network.
NodeDatabase string `toml:",omitempty"`
// Protocols should contain the protocols supported
// by the server. Matching protocols are launched for
// each peer.
Protocols []Protocol `toml:"-"`
// If ListenAddr is set to a non-nil address, the server
// will listen for incoming connections.
//
// If the port is zero, the operating system will pick a port. The
// ListenAddr field will be updated with the actual address when
// the server is started.
ListenAddr string
// If set to a non-nil value, the given NAT port mapper
// is used to make the listening port available to the
// Internet.
NAT nat.Interface `toml:",omitempty"`
// If Dialer is set to a non-nil value, the given Dialer
// is used to dial outbound peer connections.
Dialer NodeDialer `toml:"-"`
// If NoDial is true, the server will not dial any peers.
NoDial bool `toml:",omitempty"`
// If EnableMsgEvents is set then the server will emit PeerEvents
// whenever a message is sent to or received from a peer
EnableMsgEvents bool
// Logger is a custom logger to use with the p2p.Server.
Logger log.Logger `toml:",omitempty"`
}
// Server manages all peer connections.
type Server struct {
// Config fields may not be modified while the server is running.
Config
// Hooks for testing. These are useful because we can inhibit
// the whole protocol stack.
newTransport func(net.Conn) transport
newPeerHook func(*Peer)
lock sync.Mutex // protects running
running bool // indicate if the server is currently running
nodedb *enode.DB // node db created using the NodeDatabase defined in configuration
localnode *enode.LocalNode
ntab discoverTable // discovery table contains neighbor nodes
listener net.Listener // connection listener
ourHandshake *protoHandshake // serve as a wrapper and wrapped the protocols supported by the server
lastLookup time.Time // last time that server run the discovery task for looking up random nodes
DiscV5 *discv5.Network
// These are for Peers, PeerCount (and nothing else).
peerOp chan peerOpFunc
peerOpDone chan struct{}
// bunch of channels used for communication among different go routines
quit chan struct{}
addstatic chan *enode.Node // used for adding static peers
removestatic chan *enode.Node // used for static peer disconnection
addtrusted chan *enode.Node // used to add a node to trusted peer
removetrusted chan *enode.Node // used to remove a node from trusted peer
posthandshake chan *conn
addpeer chan *conn
delpeer chan peerDrop
// staticNode added by the user
staticNodesByUser map[enode.ID]struct{}
deleteStatic chan *enode.Node
setstatic chan *enode.Node
loopWG sync.WaitGroup // loop, listenLoop
peerFeed event.Feed
log log.Logger
}
type peerOpFunc func(map[enode.ID]*Peer)
type peerDrop struct {
*Peer
err error
requested bool // true if signaled by the peer
}
type connFlag uint32
const (
dynDialedConn connFlag = 1 << iota
staticDialedConn
inboundConn
trustedConn
)
// conn wraps a network connection with information gathered
// during the two handshakes.
type conn struct {
fd net.Conn
transport
node *enode.Node // node that I am trying to establish the connection to
flags connFlag
cont chan error // The run loop uses cont to signal errors to SetupConn.
// caps contain protocol supported by the peer node
caps []Cap // valid after the protocol handshake
name string // valid after the protocol handshake
}
type transport interface {
// The two handshakes.
doEncHandshake(prv *ecdsa.PrivateKey, dialDest *ecdsa.PublicKey) (*ecdsa.PublicKey, error)
doProtoHandshake(our *protoHandshake) (*protoHandshake, error)
// The MsgReadWriter can only be used after the encryption
// handshake has completed. The code uses conn.id to track this
// by setting it to a non-nil value after the encryption handshake.
MsgReadWriter
// transports must provide Close because we use MsgPipe in some of
// the tests. Closing the actual network connection doesn't do
// anything in those tests because MsgPipe doesn't use it.
close(err error)
}
// returns connection information
// including connection flag, node id if not empty, and node's public address
func (c *conn) String() string {
// stringified connection flag
s := c.flags.String()
// if node id is not empty, then add the node id to string
if (c.node.ID() != enode.ID{}) {
s += " " + c.node.ID().String()
}
// add the remote address to string
// RemoteAddr == public address
s += " " + c.fd.RemoteAddr().String()
return s
}
// returns connection flag in string format
func (f connFlag) String() string {
s := ""
if f&trustedConn != 0 {
s += "-trusted"
}
if f&dynDialedConn != 0 {
s += "-dyndial"
}
if f&staticDialedConn != 0 {
s += "-staticdial"
}
if f&inboundConn != 0 {
s += "-inbound"
}
if s != "" {
s = s[1:]
}
return s
}
// check if the connection Flags are equivalent
func (c *conn) is(f connFlag) bool {
flags := connFlag(atomic.LoadUint32((*uint32)(&c.flags)))
return flags&f != 0
}
// mark/unmark the connection flag
func (c *conn) set(f connFlag, val bool) {
for {
oldFlags := connFlag(atomic.LoadUint32((*uint32)(&c.flags)))
flags := oldFlags
if val {
flags |= f
} else {
flags &= ^f
}
if atomic.CompareAndSwapUint32((*uint32)(&c.flags), uint32(oldFlags), uint32(flags)) {
return
}
}
}
func (c *conn) GetNetConn() net.Conn {
return c.fd
}
// Peers returns all connected peers.
// by passing the peerOp function to srv.peerOp channel
// what peerOp function did here is take a map of peers and
// put them into the list
func (srv *Server) Peers() []*Peer {
var ps []*Peer
select {
// Note: We'd love to put this function into a variable but
// that seems to cause a weird compiler error in some
// environments.
case srv.peerOp <- func(peers map[enode.ID]*Peer) {
for _, p := range peers {
ps = append(ps, p)
}
}:
<-srv.peerOpDone
case <-srv.quit:
}
return ps
}
// PeerCount returns the number of connected peers.
func (srv *Server) PeerCount() int {
var count int
select {
case srv.peerOp <- func(ps map[enode.ID]*Peer) { count = len(ps) }:
<-srv.peerOpDone
case <-srv.quit:
}
return count
}
// AddPeer connects to the given node and maintains the connection until the
// server is shut down. If the connection fails for any reason, the server will
// attempt to reconnect the peer.
//
// Peer added is a static peer because the connection will be maintained
func (srv *Server) AddPeer(node *enode.Node) {
select {
case srv.addstatic <- node:
case <-srv.quit:
}
}
// RemovePeer disconnects from the given node
func (srv *Server) RemovePeer(node *enode.Node) {
select {
case srv.removestatic <- node:
case <-srv.quit:
}
}
// AddTrustedPeer adds the given node to a reserved whitelist which allows the
// node to always connect, even if the slot are full.
func (srv *Server) AddTrustedPeer(node *enode.Node) {
select {
case srv.addtrusted <- node:
case <-srv.quit:
}
}
// RemoveTrustedPeer removes the given node from the trusted peer set.
func (srv *Server) RemoveTrustedPeer(node *enode.Node) {
select {
case srv.removetrusted <- node:
case <-srv.quit:
}
}
// SubscribePeers subscribes the given channel to peer events
// Subscribed a peerEvent, this event will be emitted when
// peers added or dropped from the p2p.Server or message is sent or received
// on a peer connection. The message will be passed through the channel object
func (srv *Server) SubscribeEvents(ch chan *PeerEvent) event.Subscription {
return srv.peerFeed.Subscribe(ch)
}
// Self returns the local node's endpoint information.
// localnode represent myself
func (srv *Server) Self() *enode.Node {
srv.lock.Lock()
ln := srv.localnode
srv.lock.Unlock()
if ln == nil {
return enode.NewV4(&srv.PrivateKey.PublicKey, net.ParseIP("0.0.0.0"), 0, 0)
}
return ln.Node()
}
// Stop terminates the server and all active peer connections.
// It blocks until all active connections have been closed.
func (srv *Server) Stop() {
srv.lock.Lock()
if !srv.running {
srv.lock.Unlock()
return
}
srv.running = false
if srv.listener != nil {
// this unblocks listener Accept
srv.listener.Close()
}
close(srv.quit)
srv.lock.Unlock()
srv.loopWG.Wait()
}
// sharedUDPConn implements a shared connection. Write sends messages to the underlying connection while read returns
// messages that were found unprocessable and sent to the unhandled channel by the primary listener.
type sharedUDPConn struct {
*net.UDPConn
unhandled chan discover.ReadPacket
}
// ReadFromUDP implements discv5.conn
func (s *sharedUDPConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) {
packet, ok := <-s.unhandled
if !ok {
return 0, nil, errors.New("Connection was closed")
}
l := len(packet.Data)
if l > len(b) {
l = len(b)
}
copy(b[:l], packet.Data[:l])
return l, packet.Addr, nil
}
// Close implements discv5.conn
func (s *sharedUDPConn) Close() error {
return nil
}
// SetStatic will convert the existed connection
// to the static connection. In addition, the node
// will be added to the static dialstate
func (srv *Server) SetStatic(node *enode.Node) {
select {
case srv.setstatic <- node:
case <-srv.quit:
}
}
// AddStaticByUser will add the static node added by the user
// to the staticNodeByUser map
func (srv *Server) AddStaticByUser(nodeID enode.ID) {
srv.lock.Lock()
defer srv.lock.Unlock()
srv.staticNodesByUser[nodeID] = struct{}{}
}
// RemoveStaticByUser will remove the static node removed by the user
// from the staticNodeByUser map
func (srv *Server) RemoveStaticByUser(nodeID enode.ID) {
srv.lock.Lock()
defer srv.lock.Unlock()
delete(srv.staticNodesByUser, nodeID)
}
// IsAddedByUser checks if the static connection is declared
// by the user
func (srv *Server) IsAddedByUser(nodeID enode.ID) bool {
srv.lock.Lock()
defer srv.lock.Unlock()
_, exists := srv.staticNodesByUser[nodeID]
return exists
}
// DeleteStatic will remove the static task from the dialtask
// it will also set the static connection to dynamic connection
func (srv *Server) DeleteStatic(nodeURL string) error {
node, err := enode.ParseV4(nodeURL)
if err != nil {
return fmt.Errorf("failed to delete the static, the enodeURL is not valid: %s", err.Error())
}
// add it to the delete static channel
select {
case srv.deleteStatic <- node:
case <-srv.quit:
}
return nil
}
// Start starts running the server.
// Servers can not be re-used after stopping.
func (srv *Server) Start() (err error) {
srv.lock.Lock()
defer srv.lock.Unlock()
// checking if the server is currently running
if srv.running {
return errors.New("server already running")
}
srv.running = true
// try to get the logger from the server configuration first
srv.log = srv.Config.Logger
if srv.log == nil {
srv.log = log.New()
}
// useless server if it is not dialing nor listing
// meaning not sending message nor accepting message
if srv.NoDial && srv.ListenAddr == "" {
srv.log.Warn("P2P server will be useless, neither dialing nor listening")
}
// static fields, server's private key must be set in the configuration
if srv.PrivateKey == nil {
return errors.New("Server.PrivateKey must be set to a non-nil key")
}
// if the transport function is not set
// then use newRLPx transport protocol for secure communication
// NOTE: THIS IS A FUNCTION, NOT FUNCTION CALL
if srv.newTransport == nil {
srv.newTransport = newRLPX
}
// if Dialer is not defined, then use the DCP dialer
// with 15 seconds timeout
if srv.Dialer == nil {
srv.Dialer = TCPDialer{&net.Dialer{Timeout: defaultDialTimeout}}
}
// declaring unbuffered channels
srv.quit = make(chan struct{})
srv.addpeer = make(chan *conn)
srv.delpeer = make(chan peerDrop)
srv.posthandshake = make(chan *conn)
srv.addstatic = make(chan *enode.Node)
srv.removestatic = make(chan *enode.Node)
srv.addtrusted = make(chan *enode.Node)
srv.removetrusted = make(chan *enode.Node)
srv.peerOp = make(chan peerOpFunc)
srv.peerOpDone = make(chan struct{})
srv.setstatic = make(chan *enode.Node)
srv.staticNodesByUser = make(map[enode.ID]struct{})
srv.deleteStatic = make(chan *enode.Node)
// add the pre-configured static nodes to the staticNodesByUser
// map
for _, node := range srv.Config.StaticNodes {
srv.staticNodesByUser[node.ID()] = struct{}{}
}
// setupLocalNode, setupListening, and setupDiscovery
if err := srv.setupLocalNode(); err != nil {
return err
}
// listen to the address, set up connection for any inbound connections
// (connections requested from another node)
if srv.ListenAddr != "" {
if err := srv.setupListening(); err != nil {
return err
}
}
// setupDiscovery
if err := srv.setupDiscovery(); err != nil {
return err
}
// set the max outbound connection allowed
dynPeers := srv.maxDialedConns()
// this dialer schedules dials and discovery lookups.
// where dynPeers specified max number of dials allowed
dialer := newDialState(srv.localnode.ID(), srv.StaticNodes, srv.BootstrapNodes, srv.ntab, dynPeers, srv.NetRestrict)
srv.loopWG.Add(1)
go srv.run(dialer)
return nil
}
// initialized a bunch of staffs
// 1. server's ourHandshake field, which stores all the protocols supported by the server (sorted)
// 2. create and assigned nodeDB to server's nodedb field
// 3. create localNode object, assign it to server's localNode field
// 4. set up fallbackIP, node record (supported protocols, protocol attributes, static IP if NAT configured)
func (srv *Server) setupLocalNode() error {
// Create the devp2p handshake.
// encrypt localNode's public key
pubkey := crypto.FromECDSAPub(&srv.PrivateKey.PublicKey)
// create protoHandshake object with the version, name, and ID
srv.ourHandshake = &protoHandshake{Version: baseProtocolVersion, Name: srv.Name, ID: pubkey[1:]}
// assign list of protocols supported to protoHandshake Caps
// and sort them in order
// based on debugging: the server will only contain one protocol, which is eth with latest version 63
for _, p := range srv.Protocols {
srv.ourHandshake.Caps = append(srv.ourHandshake.Caps, p.cap())
}
sort.Sort(capsByNameAndVersion(srv.ourHandshake.Caps))
// Create the local node based on the path provided in the configuration
db, err := enode.OpenDB(srv.Config.NodeDatabase)
if err != nil {
return err
}
srv.nodedb = db
// create and initialize new localDB object with fallBackIP be 127.0.0.1
// and store the supported protocols information into node record
srv.localnode = enode.NewLocalNode(db, srv.PrivateKey)
srv.localnode.SetFallbackIP(net.IP{127, 0, 0, 1})
srv.localnode.Set(capsByNameAndVersion(srv.ourHandshake.Caps))
// TODO: check conflicts
// for each protocol's each attribute will be stored in the node record as well
for _, p := range srv.Protocols {
for _, e := range p.Attributes {
srv.localnode.Set(e)
}
}
// if NAT was used, set the static IP address
// based on the type of NAT used
// otherwise, do nothing (meaning static IP will not be set)
switch srv.NAT.(type) {
case nil:
// No NAT interface, do nothing.
case nat.ExtIP:
// ExtIP doesn't block, set the IP right away.
ip, _ := srv.NAT.ExternalIP()
srv.localnode.SetStaticIP(ip)
default:
// Ask the router about the IP. This takes a while and blocks startup,
// do it in the background.
srv.loopWG.Add(1)
go func() {
defer srv.loopWG.Done()
if ip, err := srv.NAT.ExternalIP(); err == nil {
srv.localnode.SetStaticIP(ip)
}
}()
}
return nil
}
// establish UDP connection, get and set the discovery table
// set the discovery table to server ntab field
// FallBackUDP port was set for the localnode object
func (srv *Server) setupDiscovery() error {
// if disallowed running discovery protocol (V4)
// and discoveryV5 is not set, return
if srv.NoDiscovery && !srv.DiscoveryV5 {
return nil
}
// convert the listening address to UDP address format
// default ListenAddr: :30303
addr, err := net.ResolveUDPAddr("udp", srv.ListenAddr)
if err != nil {
return err
}
// listen to the address over udp network
// even it returned UDPConn, but it serves as listener
conn, err := net.ListenUDP("udp", addr)
if err != nil {
return err
}
// get the internal IP address in UDPAddr format
realaddr := conn.LocalAddr().(*net.UDPAddr)
srv.log.Debug("UDP listener up", "addr", realaddr)
// map the address to nat if the IP is not loopback
if srv.NAT != nil {
if !realaddr.IP.IsLoopback() {
go nat.Map(srv.NAT, srv.quit, "udp", realaddr.Port, realaddr.Port, "ethereum discovery")
}
}
// set up localnode's fallback UDP port
srv.localnode.SetFallbackUDP(realaddr.Port)
// Discovery V4
var unhandled chan discover.ReadPacket
var sconn *sharedUDPConn
if !srv.NoDiscovery {
// IGNORE THIS
if srv.DiscoveryV5 {
unhandled = make(chan discover.ReadPacket, 100)
sconn = &sharedUDPConn{conn, unhandled}
}
// START HERE
cfg := discover.Config{
PrivateKey: srv.PrivateKey,
NetRestrict: srv.NetRestrict,
Bootnodes: srv.BootstrapNodes,
Unhandled: unhandled,
}
ntab, err := discover.ListenUDP(conn, srv.localnode, cfg)
if err != nil {
return err
}
srv.ntab = ntab
}
// Discovery V5
if srv.DiscoveryV5 {
var ntab *discv5.Network
var err error
if sconn != nil {
ntab, err = discv5.ListenUDP(srv.PrivateKey, sconn, "", srv.NetRestrict, srv.localnode)
} else {
ntab, err = discv5.ListenUDP(srv.PrivateKey, conn, "", srv.NetRestrict, srv.localnode)
}
if err != nil {
return err
}
if err := ntab.SetFallbackNodes(srv.BootstrapNodesV5); err != nil {
return err
}
srv.DiscV5 = ntab
}
return nil
}
// listen to the ListenAddr stored in the server configuration
func (srv *Server) setupListening() error {
// Launch the TCP listener.
listener, err := net.Listen("tcp", srv.ListenAddr)
if err != nil {
return err
}
// convert the listen address to TCPAddr format, and then update the ListenAddr in the configuration
// localnode Node Record: set TCP port
laddr := listener.Addr().(*net.TCPAddr)
srv.ListenAddr = laddr.String()
srv.listener = listener
srv.localnode.Set(enr.TCP(laddr.Port))
// add one too wait group
srv.loopWG.Add(1)
// handle inbound connection
// there should have another go routine established connection to and inbound connection
go srv.listenLoop()
// Map the TCP listening port if NAT is configured
// and the IP address is not loopback ip address (127.0.0.1)
if !laddr.IP.IsLoopback() && srv.NAT != nil {
srv.loopWG.Add(1)
go func() {
nat.Map(srv.NAT, srv.quit, "tcp", laddr.Port, laddr.Port, "ethereum p2p")
srv.loopWG.Done()
}()
}
return nil
}
type dialer interface {
newTasks(running int, peers map[enode.ID]*Peer, now time.Time) []task
taskDone(task, time.Time)
addStatic(*enode.Node)
removeStatic(*enode.Node)
}
func (srv *Server) run(dialstate dialer) {
srv.log.Info("Started P2P networking", "self", srv.localnode.Node())
defer srv.loopWG.Done()
defer srv.nodedb.Close()
var (
peers = make(map[enode.ID]*Peer)
inboundCount = 0 // number of inbound connections
trusted = make(map[enode.ID]bool, len(srv.TrustedNodes))
taskdone = make(chan task, maxActiveDialTasks)
runningTasks []task
queuedTasks []task // tasks that can't run yet
)
// Put trusted nodes into a map to speed up checks.
// Trusted peers are loaded on startup or added via AddTrustedPeer RPC.
for _, n := range srv.TrustedNodes {
trusted[n.ID()] = true
}
// removes task t from runningTasks
delTask := func(t task) {
for i := range runningTasks {
if runningTasks[i] == t {
runningTasks = append(runningTasks[:i], runningTasks[i+1:]...)
break
}
}
}
// starts until max number of active tasks is satisfied
// max active dial task will 16
// ts contains a list of task that are not started
startTasks := func(ts []task) (rest []task) {
i := 0
// start task (note: there are three different tasks)
// add the task to the runningTasks list
// return the rest of tasks
for ; len(runningTasks) < maxActiveDialTasks && i < len(ts); i++ {
t := ts[i]
srv.log.Trace("New dial task", "task", t)
go func() { t.Do(srv); taskdone <- t }()
runningTasks = append(runningTasks, t)
}
return ts[i:]
}
// queued the tasks that does not has a chance to start
// or newly created tasks from dialer if current amount of running
// task is not reach to max yet
scheduleTasks := func() {
// put the tasks that doe not have a chance to run yet (16 max running task)
// to queued task. NOTE: queuedTasks got emptied before placing remaining
// tasks
queuedTasks = append(queuedTasks[:0], startTasks(queuedTasks)...)
// if runningTasks is not reach to the max number, asking dialer to create
// new tasks (as many as possible, reach to the max active dial tasks)
// append those tasks to qeuedtask as well
if len(runningTasks) < maxActiveDialTasks {
nt := dialstate.newTasks(len(runningTasks)+len(queuedTasks), peers, time.Now())
queuedTasks = append(queuedTasks, startTasks(nt)...)
}
}
running:
for {
// when it first runs, it will ask dialer to creat a bunch of new tasks
// stored in the queuedTasks list
scheduleTasks()
select {
case <-srv.quit:
// The server was stopped. Run the cleanup logic.
break running
// node information was passed in through AddPeer function
// which will be added to the dialstate object static field
case n := <-srv.addstatic:
// This channel is used by AddPeer to add to the
// ephemeral static peer list. Add it to the dialer,
// it will keep the node connected.
// add node to dialstate static field, which contains a list of static fields
// waiting for the connection
dialstate.addStatic(n)
// node information was passed in through RemovePeer function
// node will be removed from both dialstate static nodes list
// and dialed history. Moreover, it will send peer disconnect
// request to disconnect with that node
case n := <-srv.removestatic:
// This channel is used by RemovePeer to send a
// disconnect request to a peer and begin the
// stop keeping the node connected.
dialstate.removeStatic(n)
if p, ok := peers[n.ID()]; ok {
p.Disconnect(DiscRequested)
}
case n := <-srv.deleteStatic:
// remove the static node from the dialstate
// and change the connection type from static
// to dynamic
dialstate.removeStatic(n)
if p, ok := peers[n.ID()]; ok {
p.rw.set(dynDialedConn, true)
p.rw.set(staticDialedConn, false)
}
// Add node to trusted node list
// node information will be acquired from AddTrustedPeer function
// check if the node already connected, if so, modify the peer's connection flag
case n := <-srv.addtrusted:
// This channel is used by AddTrustedPeer to add an enode
// to the trusted node set.
trusted[n.ID()] = true
// Mark any already-connected peer as trusted
if p, ok := peers[n.ID()]; ok {
p.rw.set(trustedConn, true)
}
// by setting the connection to static connection, the
// node information will be added to the dialstate. If
// the connection already existed, change the connection type
// to static
case n := <-srv.setstatic:
dialstate.addStatic(n)
if p, ok := peers[n.ID()]; ok {
p.rw.set(staticDialedConn, true)
p.rw.set(inboundConn, false)
p.rw.set(dynDialedConn, false)
}
// remove the node from trusted node list
// if the node already connected, unmark it
case n := <-srv.removetrusted:
// This channel is used by RemoveTrustedPeer to remove an enode
// from the trusted node set.
if _, ok := trusted[n.ID()]; ok {
delete(trusted, n.ID())
}
// Unmark any already-connected peer as trusted
if p, ok := peers[n.ID()]; ok {
p.rw.set(trustedConn, false)
}
// it will either get peer count or peers
// run the function, and send the done signal
// to notify the result is ready
case op := <-srv.peerOp:
// This channel is used by Peers and PeerCount.
op(peers)
srv.peerOpDone <- struct{}{}
// signal will be received from the startTask function
// where another go routine is used to do the task and
// signal the taskdone channel
// task will be deleted from runningtask list and handled by taskDone function
case t := <-taskdone:
// A task got done. Tell dialstate about it so it
// can update its state and remove it from the active
// tasks list.
srv.log.Trace("Dial task done", "task", t)
dialstate.taskDone(t, time.Now())
delTask(t)
// checking connection after encHandshake
// if the node connected is in trusted node list, then,
// make sure its' flag is set. Then do the encode handshake
// check, mainly check if the connection is allowed to be connected
// by checking if exceed max amount of connection, and etc.
case c := <-srv.posthandshake:
// A connection has passed the encryption handshake so
// the remote identity is known (but hasn't been verified yet).
if trusted[c.node.ID()] {
// Ensure that the trusted flag is set before checking against MaxPeers.
c.flags |= trustedConn
}
// TODO: track in-progress inbound node IDs (pre-Peer) to avoid dialing them.
select {
case c.cont <- srv.encHandshakeChecks(peers, inboundCount, c):
case <-srv.quit:
break running
}
// after the protoHandshake, check the connection, create peer, run peer with
// another go routine, add to peer list, and increase the inboundCount if it is
// inbound connection
case c := <-srv.addpeer:
// At this point the connection is past the protocol handshake.
// Its capabilities are known and the remote identity is verified.
err := srv.protoHandshakeChecks(peers, inboundCount, c)
// create new peer, run peer, add it to peer list, and increase the inboundCount if
// it is inbound connection
if err == nil {
// The handshakes are done and it passed all checks.
p := newPeer(c, srv.Protocols)
// If message events are enabled, pass the peerFeed
// to the peer
if srv.EnableMsgEvents {
p.events = &srv.peerFeed
}
name := truncateName(c.name)
srv.log.Debug("Adding p2p peer", "name", name, "addr", c.fd.RemoteAddr(), "peers", len(peers)+1)
go srv.runPeer(p)
peers[c.node.ID()] = p
if p.Inbound() {
inboundCount++
}
}
// The dialer logic relies on the assumption that
// dial tasks complete after the peer has been added or
// discarded. Unblock the task last.
select {
// assumption is that before added peer, the dial task must complete
// cont channel space is allocated in the setup connection function
// and setup connection function is called while doing dial task
case c.cont <- err:
case <-srv.quit:
break running
}
// This message will be received from runPeer function
// which will only return if error or disconnect request was received
case pd := <-srv.delpeer:
// A peer disconnected.
d := common.PrettyDuration(mclock.Now() - pd.created)