server.go 31 KB

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