server.go 30 KB

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