github.com/xfers/quorum@v21.1.0+incompatible/p2p/server.go (about) 1 // Copyright 2014 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package p2p implements the Ethereum p2p network protocols. 18 package p2p 19 20 import ( 21 "bytes" 22 "crypto/ecdsa" 23 "encoding/hex" 24 "errors" 25 "fmt" 26 "net" 27 "sort" 28 "sync" 29 "sync/atomic" 30 "time" 31 32 "github.com/ethereum/go-ethereum/common" 33 "github.com/ethereum/go-ethereum/common/mclock" 34 "github.com/ethereum/go-ethereum/crypto" 35 "github.com/ethereum/go-ethereum/event" 36 "github.com/ethereum/go-ethereum/log" 37 "github.com/ethereum/go-ethereum/p2p/discover" 38 "github.com/ethereum/go-ethereum/p2p/discv5" 39 "github.com/ethereum/go-ethereum/p2p/enode" 40 "github.com/ethereum/go-ethereum/p2p/enr" 41 "github.com/ethereum/go-ethereum/p2p/nat" 42 "github.com/ethereum/go-ethereum/p2p/netutil" 43 "github.com/ethereum/go-ethereum/permission/core" 44 ) 45 46 const ( 47 defaultDialTimeout = 15 * time.Second 48 49 // This is the fairness knob for the discovery mixer. When looking for peers, we'll 50 // wait this long for a single source of candidates before moving on and trying other 51 // sources. 52 discmixTimeout = 5 * time.Second 53 54 // Connectivity defaults. 55 maxActiveDialTasks = 16 56 defaultMaxPendingPeers = 50 57 defaultDialRatio = 3 58 59 // This time limits inbound connection attempts per source IP. 60 inboundThrottleTime = 30 * time.Second 61 62 // Maximum time allowed for reading a complete message. 63 // This is effectively the amount of time a connection can be idle. 64 frameReadTimeout = 30 * time.Second 65 66 // Maximum amount of time allowed for writing a complete message. 67 frameWriteTimeout = 20 * time.Second 68 ) 69 70 var errServerStopped = errors.New("server stopped") 71 72 // Config holds Server options. 73 type Config struct { 74 // This field must be set to a valid secp256k1 private key. 75 PrivateKey *ecdsa.PrivateKey `toml:"-"` 76 77 // MaxPeers is the maximum number of peers that can be 78 // connected. It must be greater than zero. 79 MaxPeers int 80 81 // MaxPendingPeers is the maximum number of peers that can be pending in the 82 // handshake phase, counted separately for inbound and outbound connections. 83 // Zero defaults to preset values. 84 MaxPendingPeers int `toml:",omitempty"` 85 86 // DialRatio controls the ratio of inbound to dialed connections. 87 // Example: a DialRatio of 2 allows 1/2 of connections to be dialed. 88 // Setting DialRatio to zero defaults it to 3. 89 DialRatio int `toml:",omitempty"` 90 91 // NoDiscovery can be used to disable the peer discovery mechanism. 92 // Disabling is useful for protocol debugging (manual topology). 93 NoDiscovery bool 94 95 // DiscoveryV5 specifies whether the new topic-discovery based V5 discovery 96 // protocol should be started or not. 97 DiscoveryV5 bool `toml:",omitempty"` 98 99 // Name sets the node name of this server. 100 // Use common.MakeName to create a name that follows existing conventions. 101 Name string `toml:"-"` 102 103 // BootstrapNodes are used to establish connectivity 104 // with the rest of the network. 105 BootstrapNodes []*enode.Node 106 107 // BootstrapNodesV5 are used to establish connectivity 108 // with the rest of the network using the V5 discovery 109 // protocol. 110 BootstrapNodesV5 []*discv5.Node `toml:",omitempty"` 111 112 // Static nodes are used as pre-configured connections which are always 113 // maintained and re-connected on disconnects. 114 StaticNodes []*enode.Node 115 116 // Trusted nodes are used as pre-configured connections which are always 117 // allowed to connect, even above the peer limit. 118 TrustedNodes []*enode.Node 119 120 // Connectivity can be restricted to certain IP networks. 121 // If this option is set to a non-nil value, only hosts which match one of the 122 // IP networks contained in the list are considered. 123 NetRestrict *netutil.Netlist `toml:",omitempty"` 124 125 // NodeDatabase is the path to the database containing the previously seen 126 // live nodes in the network. 127 NodeDatabase string `toml:",omitempty"` 128 129 // Protocols should contain the protocols supported 130 // by the server. Matching protocols are launched for 131 // each peer. 132 Protocols []Protocol `toml:"-"` 133 134 // If ListenAddr is set to a non-nil address, the server 135 // will listen for incoming connections. 136 // 137 // If the port is zero, the operating system will pick a port. The 138 // ListenAddr field will be updated with the actual address when 139 // the server is started. 140 ListenAddr string 141 142 // If set to a non-nil value, the given NAT port mapper 143 // is used to make the listening port available to the 144 // Internet. 145 NAT nat.Interface `toml:",omitempty"` 146 147 // If Dialer is set to a non-nil value, the given Dialer 148 // is used to dial outbound peer connections. 149 Dialer NodeDialer `toml:"-"` 150 151 // If NoDial is true, the server will not dial any peers. 152 NoDial bool `toml:",omitempty"` 153 154 // If EnableMsgEvents is set then the server will emit PeerEvents 155 // whenever a message is sent to or received from a peer 156 EnableMsgEvents bool 157 158 EnableNodePermission bool `toml:",omitempty"` 159 160 DataDir string `toml:",omitempty"` 161 // Logger is a custom logger to use with the p2p.Server. 162 Logger log.Logger `toml:",omitempty"` 163 } 164 165 // Server manages all peer connections. 166 type Server struct { 167 // Config fields may not be modified while the server is running. 168 Config 169 170 // Hooks for testing. These are useful because we can inhibit 171 // the whole protocol stack. 172 newTransport func(net.Conn) transport 173 newPeerHook func(*Peer) 174 listenFunc func(network, addr string) (net.Listener, error) 175 176 lock sync.Mutex // protects running 177 running bool 178 179 listener net.Listener 180 ourHandshake *protoHandshake 181 loopWG sync.WaitGroup // loop, listenLoop 182 peerFeed event.Feed 183 log log.Logger 184 185 nodedb *enode.DB 186 localnode *enode.LocalNode 187 ntab *discover.UDPv4 188 DiscV5 *discv5.Network 189 discmix *enode.FairMix 190 191 staticNodeResolver nodeResolver 192 193 // Channels into the run loop. 194 quit chan struct{} 195 addstatic chan *enode.Node 196 removestatic chan *enode.Node 197 addtrusted chan *enode.Node 198 removetrusted chan *enode.Node 199 peerOp chan peerOpFunc 200 peerOpDone chan struct{} 201 delpeer chan peerDrop 202 checkpointPostHandshake chan *conn 203 checkpointAddPeer chan *conn 204 205 // State of run loop and listenLoop. 206 lastLookup time.Time 207 inboundHistory expHeap 208 209 // raft peers info 210 checkPeerInRaft func(*enode.Node) bool 211 212 // permissions - check if node is permissioned 213 isNodePermissionedFunc func(node *enode.Node, nodename string, currentNode string, datadir string, direction string) bool 214 } 215 216 type peerOpFunc func(map[enode.ID]*Peer) 217 218 type peerDrop struct { 219 *Peer 220 err error 221 requested bool // true if signaled by the peer 222 } 223 224 type connFlag int32 225 226 const ( 227 dynDialedConn connFlag = 1 << iota 228 staticDialedConn 229 inboundConn 230 trustedConn 231 ) 232 233 // conn wraps a network connection with information gathered 234 // during the two handshakes. 235 type conn struct { 236 fd net.Conn 237 transport 238 node *enode.Node 239 flags connFlag 240 cont chan error // The run loop uses cont to signal errors to SetupConn. 241 caps []Cap // valid after the protocol handshake 242 name string // valid after the protocol handshake 243 } 244 245 type transport interface { 246 // The two handshakes. 247 doEncHandshake(prv *ecdsa.PrivateKey, dialDest *ecdsa.PublicKey) (*ecdsa.PublicKey, error) 248 doProtoHandshake(our *protoHandshake) (*protoHandshake, error) 249 // The MsgReadWriter can only be used after the encryption 250 // handshake has completed. The code uses conn.id to track this 251 // by setting it to a non-nil value after the encryption handshake. 252 MsgReadWriter 253 // transports must provide Close because we use MsgPipe in some of 254 // the tests. Closing the actual network connection doesn't do 255 // anything in those tests because MsgPipe doesn't use it. 256 close(err error) 257 } 258 259 func (c *conn) String() string { 260 s := c.flags.String() 261 if (c.node.ID() != enode.ID{}) { 262 s += " " + c.node.ID().String() 263 } 264 s += " " + c.fd.RemoteAddr().String() 265 return s 266 } 267 268 func (f connFlag) String() string { 269 s := "" 270 if f&trustedConn != 0 { 271 s += "-trusted" 272 } 273 if f&dynDialedConn != 0 { 274 s += "-dyndial" 275 } 276 if f&staticDialedConn != 0 { 277 s += "-staticdial" 278 } 279 if f&inboundConn != 0 { 280 s += "-inbound" 281 } 282 if s != "" { 283 s = s[1:] 284 } 285 return s 286 } 287 288 func (c *conn) is(f connFlag) bool { 289 flags := connFlag(atomic.LoadInt32((*int32)(&c.flags))) 290 return flags&f != 0 291 } 292 293 func (c *conn) set(f connFlag, val bool) { 294 for { 295 oldFlags := connFlag(atomic.LoadInt32((*int32)(&c.flags))) 296 flags := oldFlags 297 if val { 298 flags |= f 299 } else { 300 flags &= ^f 301 } 302 if atomic.CompareAndSwapInt32((*int32)(&c.flags), int32(oldFlags), int32(flags)) { 303 return 304 } 305 } 306 } 307 308 // LocalNode returns the local node record. 309 func (srv *Server) LocalNode() *enode.LocalNode { 310 return srv.localnode 311 } 312 313 // Peers returns all connected peers. 314 func (srv *Server) Peers() []*Peer { 315 var ps []*Peer 316 select { 317 // Note: We'd love to put this function into a variable but 318 // that seems to cause a weird compiler error in some 319 // environments. 320 case srv.peerOp <- func(peers map[enode.ID]*Peer) { 321 for _, p := range peers { 322 ps = append(ps, p) 323 } 324 }: 325 <-srv.peerOpDone 326 case <-srv.quit: 327 } 328 return ps 329 } 330 331 // PeerCount returns the number of connected peers. 332 func (srv *Server) PeerCount() int { 333 var count int 334 select { 335 case srv.peerOp <- func(ps map[enode.ID]*Peer) { count = len(ps) }: 336 <-srv.peerOpDone 337 case <-srv.quit: 338 } 339 return count 340 } 341 342 // AddPeer connects to the given node and maintains the connection until the 343 // server is shut down. If the connection fails for any reason, the server will 344 // attempt to reconnect the peer. 345 func (srv *Server) AddPeer(node *enode.Node) { 346 select { 347 case srv.addstatic <- node: 348 case <-srv.quit: 349 } 350 } 351 352 // RemovePeer disconnects from the given node 353 func (srv *Server) RemovePeer(node *enode.Node) { 354 select { 355 case srv.removestatic <- node: 356 case <-srv.quit: 357 } 358 } 359 360 // AddTrustedPeer adds the given node to a reserved whitelist which allows the 361 // node to always connect, even if the slot are full. 362 func (srv *Server) AddTrustedPeer(node *enode.Node) { 363 select { 364 case srv.addtrusted <- node: 365 case <-srv.quit: 366 } 367 } 368 369 // RemoveTrustedPeer removes the given node from the trusted peer set. 370 func (srv *Server) RemoveTrustedPeer(node *enode.Node) { 371 select { 372 case srv.removetrusted <- node: 373 case <-srv.quit: 374 } 375 } 376 377 // SubscribePeers subscribes the given channel to peer events 378 func (srv *Server) SubscribeEvents(ch chan *PeerEvent) event.Subscription { 379 return srv.peerFeed.Subscribe(ch) 380 } 381 382 // Self returns the local node's endpoint information. 383 func (srv *Server) Self() *enode.Node { 384 srv.lock.Lock() 385 ln := srv.localnode 386 srv.lock.Unlock() 387 388 if ln == nil { 389 return enode.NewV4(&srv.PrivateKey.PublicKey, net.ParseIP("0.0.0.0"), 0, 0) 390 } 391 return ln.Node() 392 } 393 394 // Stop terminates the server and all active peer connections. 395 // It blocks until all active connections have been closed. 396 func (srv *Server) Stop() { 397 srv.lock.Lock() 398 if !srv.running { 399 srv.lock.Unlock() 400 return 401 } 402 srv.running = false 403 if srv.listener != nil { 404 // this unblocks listener Accept 405 srv.listener.Close() 406 } 407 close(srv.quit) 408 srv.lock.Unlock() 409 srv.loopWG.Wait() 410 } 411 412 // sharedUDPConn implements a shared connection. Write sends messages to the underlying connection while read returns 413 // messages that were found unprocessable and sent to the unhandled channel by the primary listener. 414 type sharedUDPConn struct { 415 *net.UDPConn 416 unhandled chan discover.ReadPacket 417 } 418 419 // ReadFromUDP implements discv5.conn 420 func (s *sharedUDPConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) { 421 packet, ok := <-s.unhandled 422 if !ok { 423 return 0, nil, errors.New("Connection was closed") 424 } 425 l := len(packet.Data) 426 if l > len(b) { 427 l = len(b) 428 } 429 copy(b[:l], packet.Data[:l]) 430 return l, packet.Addr, nil 431 } 432 433 // Close implements discv5.conn 434 func (s *sharedUDPConn) Close() error { 435 return nil 436 } 437 438 // Start starts running the server. 439 // Servers can not be re-used after stopping. 440 func (srv *Server) Start() (err error) { 441 srv.lock.Lock() 442 defer srv.lock.Unlock() 443 if srv.running { 444 return errors.New("server already running") 445 } 446 srv.running = true 447 srv.log = srv.Config.Logger 448 if srv.log == nil { 449 srv.log = log.Root() 450 } 451 if srv.NoDial && srv.ListenAddr == "" { 452 srv.log.Warn("P2P server will be useless, neither dialing nor listening") 453 } 454 455 // static fields 456 if srv.PrivateKey == nil { 457 return errors.New("Server.PrivateKey must be set to a non-nil key") 458 } 459 if srv.newTransport == nil { 460 srv.newTransport = newRLPX 461 } 462 if srv.listenFunc == nil { 463 srv.listenFunc = net.Listen 464 } 465 if srv.Dialer == nil { 466 srv.Dialer = TCPDialer{&net.Dialer{Timeout: defaultDialTimeout}} 467 } 468 srv.quit = make(chan struct{}) 469 srv.delpeer = make(chan peerDrop) 470 srv.checkpointPostHandshake = make(chan *conn) 471 srv.checkpointAddPeer = make(chan *conn) 472 srv.addstatic = make(chan *enode.Node) 473 srv.removestatic = make(chan *enode.Node) 474 srv.addtrusted = make(chan *enode.Node) 475 srv.removetrusted = make(chan *enode.Node) 476 srv.peerOp = make(chan peerOpFunc) 477 srv.peerOpDone = make(chan struct{}) 478 479 if err := srv.setupLocalNode(); err != nil { 480 return err 481 } 482 if srv.ListenAddr != "" { 483 if err := srv.setupListening(); err != nil { 484 return err 485 } 486 } 487 if err := srv.setupDiscovery(); err != nil { 488 return err 489 } 490 491 dynPeers := srv.maxDialedConns() 492 dialer := newDialState(srv.localnode.ID(), dynPeers, &srv.Config) 493 srv.loopWG.Add(1) 494 go srv.run(dialer) 495 return nil 496 } 497 498 func (srv *Server) setupLocalNode() error { 499 // Create the devp2p handshake. 500 pubkey := crypto.FromECDSAPub(&srv.PrivateKey.PublicKey) 501 srv.ourHandshake = &protoHandshake{Version: baseProtocolVersion, Name: srv.Name, ID: pubkey[1:]} 502 for _, p := range srv.Protocols { 503 srv.ourHandshake.Caps = append(srv.ourHandshake.Caps, p.cap()) 504 } 505 sort.Sort(capsByNameAndVersion(srv.ourHandshake.Caps)) 506 507 // Create the local node. 508 db, err := enode.OpenDB(srv.Config.NodeDatabase) 509 if err != nil { 510 return err 511 } 512 srv.nodedb = db 513 srv.localnode = enode.NewLocalNode(db, srv.PrivateKey) 514 srv.localnode.SetFallbackIP(net.IP{127, 0, 0, 1}) 515 // TODO: check conflicts 516 for _, p := range srv.Protocols { 517 for _, e := range p.Attributes { 518 srv.localnode.Set(e) 519 } 520 } 521 switch srv.NAT.(type) { 522 case nil: 523 // No NAT interface, do nothing. 524 case nat.ExtIP: 525 // ExtIP doesn't block, set the IP right away. 526 ip, _ := srv.NAT.ExternalIP() 527 srv.localnode.SetStaticIP(ip) 528 default: 529 // Ask the router about the IP. This takes a while and blocks startup, 530 // do it in the background. 531 srv.loopWG.Add(1) 532 go func() { 533 defer srv.loopWG.Done() 534 if ip, err := srv.NAT.ExternalIP(); err == nil { 535 srv.localnode.SetStaticIP(ip) 536 } 537 }() 538 } 539 return nil 540 } 541 542 func (srv *Server) setupDiscovery() error { 543 srv.discmix = enode.NewFairMix(discmixTimeout) 544 545 // Add protocol-specific discovery sources. 546 added := make(map[string]bool) 547 for _, proto := range srv.Protocols { 548 if proto.DialCandidates != nil && !added[proto.Name] { 549 srv.discmix.AddSource(proto.DialCandidates) 550 added[proto.Name] = true 551 } 552 } 553 554 // Don't listen on UDP endpoint if DHT is disabled. 555 if srv.NoDiscovery && !srv.DiscoveryV5 { 556 return nil 557 } 558 559 addr, err := net.ResolveUDPAddr("udp", srv.ListenAddr) 560 if err != nil { 561 return err 562 } 563 conn, err := net.ListenUDP("udp", addr) 564 if err != nil { 565 return err 566 } 567 realaddr := conn.LocalAddr().(*net.UDPAddr) 568 srv.log.Debug("UDP listener up", "addr", realaddr) 569 if srv.NAT != nil { 570 if !realaddr.IP.IsLoopback() { 571 go nat.Map(srv.NAT, srv.quit, "udp", realaddr.Port, realaddr.Port, "ethereum discovery") 572 } 573 } 574 srv.localnode.SetFallbackUDP(realaddr.Port) 575 576 // Discovery V4 577 var unhandled chan discover.ReadPacket 578 var sconn *sharedUDPConn 579 if !srv.NoDiscovery { 580 if srv.DiscoveryV5 { 581 unhandled = make(chan discover.ReadPacket, 100) 582 sconn = &sharedUDPConn{conn, unhandled} 583 } 584 cfg := discover.Config{ 585 PrivateKey: srv.PrivateKey, 586 NetRestrict: srv.NetRestrict, 587 Bootnodes: srv.BootstrapNodes, 588 Unhandled: unhandled, 589 Log: srv.log, 590 } 591 ntab, err := discover.ListenUDP(conn, srv.localnode, cfg) 592 if err != nil { 593 return err 594 } 595 srv.ntab = ntab 596 srv.discmix.AddSource(ntab.RandomNodes()) 597 srv.staticNodeResolver = ntab 598 } 599 600 // Discovery V5 601 if srv.DiscoveryV5 { 602 var ntab *discv5.Network 603 var err error 604 if sconn != nil { 605 ntab, err = discv5.ListenUDP(srv.PrivateKey, sconn, "", srv.NetRestrict) 606 } else { 607 ntab, err = discv5.ListenUDP(srv.PrivateKey, conn, "", srv.NetRestrict) 608 } 609 if err != nil { 610 return err 611 } 612 if err := ntab.SetFallbackNodes(srv.BootstrapNodesV5); err != nil { 613 return err 614 } 615 srv.DiscV5 = ntab 616 } 617 return nil 618 } 619 620 func (srv *Server) setupListening() error { 621 // Launch the listener. 622 listener, err := srv.listenFunc("tcp", srv.ListenAddr) 623 if err != nil { 624 return err 625 } 626 srv.listener = listener 627 srv.ListenAddr = listener.Addr().String() 628 629 // Update the local node record and map the TCP listening port if NAT is configured. 630 if tcp, ok := listener.Addr().(*net.TCPAddr); ok { 631 srv.localnode.Set(enr.TCP(tcp.Port)) 632 if !tcp.IP.IsLoopback() && srv.NAT != nil { 633 srv.loopWG.Add(1) 634 go func() { 635 nat.Map(srv.NAT, srv.quit, "tcp", tcp.Port, tcp.Port, "ethereum p2p") 636 srv.loopWG.Done() 637 }() 638 } 639 } 640 641 srv.loopWG.Add(1) 642 go srv.listenLoop() 643 return nil 644 } 645 646 type dialer interface { 647 newTasks(running int, peers map[enode.ID]*Peer, now time.Time) []task 648 taskDone(task, time.Time) 649 addStatic(*enode.Node) 650 removeStatic(*enode.Node) 651 } 652 653 func (srv *Server) run(dialstate dialer) { 654 srv.log.Info("Started P2P networking", "self", srv.localnode.Node().URLv4()) 655 defer srv.loopWG.Done() 656 defer srv.nodedb.Close() 657 defer srv.discmix.Close() 658 659 var ( 660 peers = make(map[enode.ID]*Peer) 661 inboundCount = 0 662 trusted = make(map[enode.ID]bool, len(srv.TrustedNodes)) 663 taskdone = make(chan task, maxActiveDialTasks) 664 runningTasks []task 665 queuedTasks []task // tasks that can't run yet 666 ) 667 // Put trusted nodes into a map to speed up checks. 668 // Trusted peers are loaded on startup or added via AddTrustedPeer RPC. 669 for _, n := range srv.TrustedNodes { 670 trusted[n.ID()] = true 671 } 672 673 // removes t from runningTasks 674 delTask := func(t task) { 675 for i := range runningTasks { 676 if runningTasks[i] == t { 677 runningTasks = append(runningTasks[:i], runningTasks[i+1:]...) 678 break 679 } 680 } 681 } 682 // starts until max number of active tasks is satisfied 683 startTasks := func(ts []task) (rest []task) { 684 i := 0 685 for ; len(runningTasks) < maxActiveDialTasks && i < len(ts); i++ { 686 t := ts[i] 687 srv.log.Trace("New dial task", "task", t) 688 go func() { t.Do(srv); taskdone <- t }() 689 runningTasks = append(runningTasks, t) 690 } 691 return ts[i:] 692 } 693 scheduleTasks := func() { 694 // Start from queue first. 695 queuedTasks = append(queuedTasks[:0], startTasks(queuedTasks)...) 696 // Query dialer for new tasks and start as many as possible now. 697 if len(runningTasks) < maxActiveDialTasks { 698 nt := dialstate.newTasks(len(runningTasks)+len(queuedTasks), peers, time.Now()) 699 queuedTasks = append(queuedTasks, startTasks(nt)...) 700 } 701 } 702 703 running: 704 for { 705 scheduleTasks() 706 707 select { 708 case <-srv.quit: 709 // The server was stopped. Run the cleanup logic. 710 break running 711 712 case n := <-srv.addstatic: 713 // This channel is used by AddPeer to add to the 714 // ephemeral static peer list. Add it to the dialer, 715 // it will keep the node connected. 716 srv.log.Trace("Adding static node", "node", n) 717 dialstate.addStatic(n) 718 719 case n := <-srv.removestatic: 720 // This channel is used by RemovePeer to send a 721 // disconnect request to a peer and begin the 722 // stop keeping the node connected. 723 srv.log.Trace("Removing static node", "node", n) 724 dialstate.removeStatic(n) 725 if p, ok := peers[n.ID()]; ok { 726 p.Disconnect(DiscRequested) 727 } 728 729 case n := <-srv.addtrusted: 730 // This channel is used by AddTrustedPeer to add an enode 731 // to the trusted node set. 732 srv.log.Trace("Adding trusted node", "node", n) 733 trusted[n.ID()] = true 734 // Mark any already-connected peer as trusted 735 if p, ok := peers[n.ID()]; ok { 736 p.rw.set(trustedConn, true) 737 } 738 739 case n := <-srv.removetrusted: 740 // This channel is used by RemoveTrustedPeer to remove an enode 741 // from the trusted node set. 742 srv.log.Trace("Removing trusted node", "node", n) 743 delete(trusted, n.ID()) 744 745 // Unmark any already-connected peer as trusted 746 if p, ok := peers[n.ID()]; ok { 747 p.rw.set(trustedConn, false) 748 } 749 750 case op := <-srv.peerOp: 751 // This channel is used by Peers and PeerCount. 752 op(peers) 753 srv.peerOpDone <- struct{}{} 754 755 case t := <-taskdone: 756 // A task got done. Tell dialstate about it so it 757 // can update its state and remove it from the active 758 // tasks list. 759 srv.log.Trace("Dial task done", "task", t) 760 dialstate.taskDone(t, time.Now()) 761 delTask(t) 762 763 case c := <-srv.checkpointPostHandshake: 764 // A connection has passed the encryption handshake so 765 // the remote identity is known (but hasn't been verified yet). 766 if trusted[c.node.ID()] { 767 // Ensure that the trusted flag is set before checking against MaxPeers. 768 c.flags |= trustedConn 769 } 770 // TODO: track in-progress inbound node IDs (pre-Peer) to avoid dialing them. 771 c.cont <- srv.postHandshakeChecks(peers, inboundCount, c) 772 773 case c := <-srv.checkpointAddPeer: 774 // At this point the connection is past the protocol handshake. 775 // Its capabilities are known and the remote identity is verified. 776 err := srv.addPeerChecks(peers, inboundCount, c) 777 if err == nil { 778 // The handshakes are done and it passed all checks. 779 p := newPeer(srv.log, c, srv.Protocols) 780 // If message events are enabled, pass the peerFeed 781 // to the peer 782 if srv.EnableMsgEvents { 783 p.events = &srv.peerFeed 784 } 785 name := truncateName(c.name) 786 p.log.Debug("Adding p2p peer", "addr", p.RemoteAddr(), "peers", len(peers)+1, "name", name) 787 go srv.runPeer(p) 788 peers[c.node.ID()] = p 789 if p.Inbound() { 790 inboundCount++ 791 } 792 } 793 // The dialer logic relies on the assumption that 794 // dial tasks complete after the peer has been added or 795 // discarded. Unblock the task last. 796 c.cont <- err 797 798 case pd := <-srv.delpeer: 799 // A peer disconnected. 800 d := common.PrettyDuration(mclock.Now() - pd.created) 801 pd.log.Debug("Removing p2p peer", "addr", pd.RemoteAddr(), "peers", len(peers)-1, "duration", d, "req", pd.requested, "err", pd.err) 802 delete(peers, pd.ID()) 803 if pd.Inbound() { 804 inboundCount-- 805 } 806 } 807 } 808 809 srv.log.Trace("P2P networking is spinning down") 810 811 // Terminate discovery. If there is a running lookup it will terminate soon. 812 if srv.ntab != nil { 813 srv.ntab.Close() 814 } 815 if srv.DiscV5 != nil { 816 srv.DiscV5.Close() 817 } 818 // Disconnect all peers. 819 for _, p := range peers { 820 p.Disconnect(DiscQuitting) 821 } 822 // Wait for peers to shut down. Pending connections and tasks are 823 // not handled here and will terminate soon-ish because srv.quit 824 // is closed. 825 for len(peers) > 0 { 826 p := <-srv.delpeer 827 p.log.Trace("<-delpeer (spindown)", "remainingTasks", len(runningTasks)) 828 delete(peers, p.ID()) 829 } 830 } 831 832 func (srv *Server) postHandshakeChecks(peers map[enode.ID]*Peer, inboundCount int, c *conn) error { 833 switch { 834 case !c.is(trustedConn|staticDialedConn) && len(peers) >= srv.MaxPeers: 835 return DiscTooManyPeers 836 case !c.is(trustedConn) && c.is(inboundConn) && inboundCount >= srv.maxInboundConns(): 837 return DiscTooManyPeers 838 case peers[c.node.ID()] != nil: 839 return DiscAlreadyConnected 840 case c.node.ID() == srv.localnode.ID(): 841 return DiscSelf 842 default: 843 return nil 844 } 845 } 846 847 func (srv *Server) addPeerChecks(peers map[enode.ID]*Peer, inboundCount int, c *conn) error { 848 // Drop connections with no matching protocols. 849 if len(srv.Protocols) > 0 && countMatchingProtocols(srv.Protocols, c.caps) == 0 { 850 return DiscUselessPeer 851 } 852 // Repeat the post-handshake checks because the 853 // peer set might have changed since those checks were performed. 854 return srv.postHandshakeChecks(peers, inboundCount, c) 855 } 856 857 func (srv *Server) maxInboundConns() int { 858 return srv.MaxPeers - srv.maxDialedConns() 859 } 860 861 func (srv *Server) maxDialedConns() int { 862 if srv.NoDiscovery || srv.NoDial { 863 return 0 864 } 865 r := srv.DialRatio 866 if r == 0 { 867 r = defaultDialRatio 868 } 869 return srv.MaxPeers / r 870 } 871 872 // listenLoop runs in its own goroutine and accepts 873 // inbound connections. 874 func (srv *Server) listenLoop() { 875 defer srv.loopWG.Done() 876 srv.log.Debug("TCP listener up", "addr", srv.listener.Addr()) 877 878 tokens := defaultMaxPendingPeers 879 if srv.MaxPendingPeers > 0 { 880 tokens = srv.MaxPendingPeers 881 } 882 slots := make(chan struct{}, tokens) 883 for i := 0; i < tokens; i++ { 884 slots <- struct{}{} 885 } 886 887 for { 888 // Wait for a free slot before accepting. 889 <-slots 890 891 var ( 892 fd net.Conn 893 err error 894 ) 895 for { 896 fd, err = srv.listener.Accept() 897 if netutil.IsTemporaryError(err) { 898 srv.log.Debug("Temporary read error", "err", err) 899 continue 900 } else if err != nil { 901 srv.log.Debug("Read error", "err", err) 902 return 903 } 904 break 905 } 906 907 remoteIP := netutil.AddrIP(fd.RemoteAddr()) 908 if err := srv.checkInboundConn(fd, remoteIP); err != nil { 909 srv.log.Debug("Rejected inbound connnection", "addr", fd.RemoteAddr(), "err", err) 910 fd.Close() 911 slots <- struct{}{} 912 continue 913 } 914 if remoteIP != nil { 915 fd = newMeteredConn(fd, true, remoteIP) 916 } 917 srv.log.Trace("Accepted connection", "addr", fd.RemoteAddr()) 918 go func() { 919 srv.SetupConn(fd, inboundConn, nil) 920 slots <- struct{}{} 921 }() 922 } 923 } 924 925 func (srv *Server) checkInboundConn(fd net.Conn, remoteIP net.IP) error { 926 if remoteIP != nil { 927 // Reject connections that do not match NetRestrict. 928 if srv.NetRestrict != nil && !srv.NetRestrict.Contains(remoteIP) { 929 return fmt.Errorf("not whitelisted in NetRestrict") 930 } 931 // Reject Internet peers that try too often. 932 srv.inboundHistory.expire(time.Now()) 933 if !netutil.IsLAN(remoteIP) && srv.inboundHistory.contains(remoteIP.String()) { 934 return fmt.Errorf("too many attempts") 935 } 936 srv.inboundHistory.add(remoteIP.String(), time.Now().Add(inboundThrottleTime)) 937 } 938 return nil 939 } 940 941 // SetupConn runs the handshakes and attempts to add the connection 942 // as a peer. It returns when the connection has been added as a peer 943 // or the handshakes have failed. 944 func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *enode.Node) error { 945 c := &conn{fd: fd, transport: srv.newTransport(fd), flags: flags, cont: make(chan error)} 946 err := srv.setupConn(c, flags, dialDest) 947 if err != nil { 948 c.close(err) 949 srv.log.Trace("Setting up connection failed", "addr", fd.RemoteAddr(), "err", err) 950 } 951 return err 952 } 953 954 func (srv *Server) setupConn(c *conn, flags connFlag, dialDest *enode.Node) error { 955 // Prevent leftover pending conns from entering the handshake. 956 srv.lock.Lock() 957 running := srv.running 958 srv.lock.Unlock() 959 if !running { 960 return errServerStopped 961 } 962 963 // If dialing, figure out the remote public key. 964 var dialPubkey *ecdsa.PublicKey 965 if dialDest != nil { 966 dialPubkey = new(ecdsa.PublicKey) 967 if err := dialDest.Load((*enode.Secp256k1)(dialPubkey)); err != nil { 968 return errors.New("dial destination doesn't have a secp256k1 public key") 969 } 970 } 971 972 // Run the RLPx handshake. 973 remotePubkey, err := c.doEncHandshake(srv.PrivateKey, dialPubkey) 974 if err != nil { 975 srv.log.Trace("Failed RLPx handshake", "addr", c.fd.RemoteAddr(), "conn", c.flags, "err", err) 976 return err 977 } 978 979 if dialDest != nil { 980 // For dialed connections, check that the remote public key matches. 981 if dialPubkey.X.Cmp(remotePubkey.X) != 0 || dialPubkey.Y.Cmp(remotePubkey.Y) != 0 { 982 return DiscUnexpectedIdentity 983 } 984 c.node = dialDest 985 } else { 986 c.node = nodeFromConn(remotePubkey, c.fd) 987 } 988 clog := srv.log.New("id", c.node.ID(), "addr", c.fd.RemoteAddr(), "conn", c.flags) 989 990 // If raft is running, check if the dialing node is in the raft cluster 991 // Node doesn't belong to raft cluster is not allowed to join the p2p network 992 if srv.checkPeerInRaft != nil && !srv.checkPeerInRaft(c.node) { 993 node := c.node.ID().String() 994 log.Trace("incoming connection peer is not in the raft cluster", "enode.id", node) 995 return newPeerError(errNotInRaftCluster, "id=%s…%s", node[:4], node[len(node)-4:]) 996 } 997 998 //START - QUORUM Permissioning 999 currentNode := srv.NodeInfo().ID 1000 cnodeName := srv.NodeInfo().Name 1001 clog.Trace("Quorum permissioning", 1002 "EnableNodePermission", srv.EnableNodePermission, 1003 "DataDir", srv.DataDir, 1004 "Current Node ID", currentNode, 1005 "Node Name", cnodeName, 1006 "Dialed Dest", dialDest, 1007 "Connection ID", c.node.ID(), 1008 "Connection String", c.node.ID().String()) 1009 1010 if srv.EnableNodePermission { 1011 clog.Trace("Node Permissioning is Enabled.") 1012 nodeId := c.node.ID().String() 1013 node := c.node 1014 direction := "INCOMING" 1015 if dialDest != nil { 1016 node = dialDest 1017 nodeId = dialDest.ID().String() 1018 direction = "OUTGOING" 1019 log.Trace("Node Permissioning", "Connection Direction", direction) 1020 } 1021 1022 if srv.isNodePermissionedFunc == nil { 1023 if !core.IsNodePermissioned(nodeId, currentNode, srv.DataDir, direction) { 1024 return newPeerError(errPermissionDenied, "id=%s…%s %s id=%s…%s", currentNode[:4], currentNode[len(currentNode)-4:], direction, nodeId[:4], nodeId[len(nodeId)-4:]) 1025 } 1026 } else if !srv.isNodePermissionedFunc(node, nodeId, currentNode, srv.DataDir, direction) { 1027 return newPeerError(errPermissionDenied, "id=%s…%s %s id=%s…%s", currentNode[:4], currentNode[len(currentNode)-4:], direction, nodeId[:4], nodeId[len(nodeId)-4:]) 1028 } 1029 } else { 1030 clog.Trace("Node Permissioning is Disabled.") 1031 } 1032 1033 //END - QUORUM Permissioning 1034 1035 if conn, ok := c.fd.(*meteredConn); ok { 1036 conn.handshakeDone(c.node.ID()) 1037 } 1038 1039 err = srv.checkpoint(c, srv.checkpointPostHandshake) 1040 if err != nil { 1041 clog.Trace("Rejected peer", "err", err) 1042 return err 1043 } 1044 1045 // Run the capability negotiation handshake. 1046 phs, err := c.doProtoHandshake(srv.ourHandshake) 1047 if err != nil { 1048 clog.Trace("Failed proto handshake", "err", err) 1049 return err 1050 } 1051 if id := c.node.ID(); !bytes.Equal(crypto.Keccak256(phs.ID), id[:]) { 1052 clog.Trace("Wrong devp2p handshake identity", "phsid", hex.EncodeToString(phs.ID)) 1053 return DiscUnexpectedIdentity 1054 } 1055 c.caps, c.name = phs.Caps, phs.Name 1056 err = srv.checkpoint(c, srv.checkpointAddPeer) 1057 if err != nil { 1058 clog.Trace("Rejected peer", "err", err) 1059 return err 1060 } 1061 1062 // If the checks completed successfully, the connection has been added as a peer and 1063 // runPeer has been launched. 1064 clog.Trace("Connection set up", "inbound", dialDest == nil) 1065 return nil 1066 } 1067 1068 func nodeFromConn(pubkey *ecdsa.PublicKey, conn net.Conn) *enode.Node { 1069 var ip net.IP 1070 var port int 1071 if tcp, ok := conn.RemoteAddr().(*net.TCPAddr); ok { 1072 ip = tcp.IP 1073 port = tcp.Port 1074 } 1075 return enode.NewV4(pubkey, ip, port, port) 1076 } 1077 1078 func truncateName(s string) string { 1079 if len(s) > 20 { 1080 return s[:20] + "..." 1081 } 1082 return s 1083 } 1084 1085 // checkpoint sends the conn to run, which performs the 1086 // post-handshake checks for the stage (posthandshake, addpeer). 1087 func (srv *Server) checkpoint(c *conn, stage chan<- *conn) error { 1088 select { 1089 case stage <- c: 1090 case <-srv.quit: 1091 return errServerStopped 1092 } 1093 return <-c.cont 1094 } 1095 1096 // runPeer runs in its own goroutine for each peer. 1097 // it waits until the Peer logic returns and removes 1098 // the peer. 1099 func (srv *Server) runPeer(p *Peer) { 1100 if srv.newPeerHook != nil { 1101 srv.newPeerHook(p) 1102 } 1103 1104 // broadcast peer add 1105 srv.peerFeed.Send(&PeerEvent{ 1106 Type: PeerEventTypeAdd, 1107 Peer: p.ID(), 1108 RemoteAddress: p.RemoteAddr().String(), 1109 LocalAddress: p.LocalAddr().String(), 1110 }) 1111 1112 // run the protocol 1113 remoteRequested, err := p.run() 1114 1115 // broadcast peer drop 1116 srv.peerFeed.Send(&PeerEvent{ 1117 Type: PeerEventTypeDrop, 1118 Peer: p.ID(), 1119 Error: err.Error(), 1120 RemoteAddress: p.RemoteAddr().String(), 1121 LocalAddress: p.LocalAddr().String(), 1122 }) 1123 1124 // Note: run waits for existing peers to be sent on srv.delpeer 1125 // before returning, so this send should not select on srv.quit. 1126 srv.delpeer <- peerDrop{p, err, remoteRequested} 1127 } 1128 1129 // NodeInfo represents a short summary of the information known about the host. 1130 type NodeInfo struct { 1131 ID string `json:"id"` // Unique node identifier (also the encryption key) 1132 Name string `json:"name"` // Name of the node, including client type, version, OS, custom data 1133 Enode string `json:"enode"` // Enode URL for adding this peer from remote peers 1134 ENR string `json:"enr"` // Ethereum Node Record 1135 IP string `json:"ip"` // IP address of the node 1136 Ports struct { 1137 Discovery int `json:"discovery"` // UDP listening port for discovery protocol 1138 Listener int `json:"listener"` // TCP listening port for RLPx 1139 } `json:"ports"` 1140 ListenAddr string `json:"listenAddr"` 1141 Protocols map[string]interface{} `json:"protocols"` 1142 } 1143 1144 // NodeInfo gathers and returns a collection of metadata known about the host. 1145 func (srv *Server) NodeInfo() *NodeInfo { 1146 // Gather and assemble the generic node infos 1147 node := srv.Self() 1148 info := &NodeInfo{ 1149 Name: srv.Name, 1150 Enode: node.URLv4(), 1151 ID: node.ID().String(), 1152 IP: node.IP().String(), 1153 ListenAddr: srv.ListenAddr, 1154 Protocols: make(map[string]interface{}), 1155 } 1156 info.Ports.Discovery = node.UDP() 1157 info.Ports.Listener = node.TCP() 1158 info.ENR = node.String() 1159 1160 // Gather all the running protocol infos (only once per protocol type) 1161 for _, proto := range srv.Protocols { 1162 if _, ok := info.Protocols[proto.Name]; !ok { 1163 nodeInfo := interface{}("unknown") 1164 if query := proto.NodeInfo; query != nil { 1165 nodeInfo = proto.NodeInfo() 1166 } 1167 info.Protocols[proto.Name] = nodeInfo 1168 } 1169 } 1170 return info 1171 } 1172 1173 // PeersInfo returns an array of metadata objects describing connected peers. 1174 func (srv *Server) PeersInfo() []*PeerInfo { 1175 // Gather all the generic and sub-protocol specific infos 1176 infos := make([]*PeerInfo, 0, srv.PeerCount()) 1177 for _, peer := range srv.Peers() { 1178 if peer != nil { 1179 infos = append(infos, peer.Info()) 1180 } 1181 } 1182 // Sort the result array alphabetically by node identifier 1183 for i := 0; i < len(infos); i++ { 1184 for j := i + 1; j < len(infos); j++ { 1185 if infos[i].ID > infos[j].ID { 1186 infos[i], infos[j] = infos[j], infos[i] 1187 } 1188 } 1189 } 1190 return infos 1191 } 1192 1193 func (srv *Server) SetCheckPeerInRaft(f func(*enode.Node) bool) { 1194 srv.checkPeerInRaft = f 1195 } 1196 1197 func (srv *Server) SetIsNodePermissioned(f func(*enode.Node, string, string, string, string) bool) { 1198 if srv.isNodePermissionedFunc == nil { 1199 srv.isNodePermissionedFunc = f 1200 } 1201 }