server.go 31 KB

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