server.go 31 KB

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