server.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  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/gopool"
  31. "github.com/ethereum/go-ethereum/common/mclock"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/event"
  34. "github.com/ethereum/go-ethereum/log"
  35. "github.com/ethereum/go-ethereum/p2p/discover"
  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 []*enode.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, *ecdsa.PublicKey) 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 *discover.UDPv5
  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) (*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 discover.UDPConn
  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 discover.UDPConn
  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. srv.loopWG.Add(1)
  494. gopool.Submit(func() {
  495. nat.Map(srv.NAT, srv.quit, "udp", realaddr.Port, realaddr.Port, "ethereum discovery")
  496. srv.loopWG.Done()
  497. })
  498. }
  499. }
  500. srv.localnode.SetFallbackUDP(realaddr.Port)
  501. // Discovery V4
  502. var unhandled chan discover.ReadPacket
  503. var sconn *sharedUDPConn
  504. if !srv.NoDiscovery {
  505. if srv.DiscoveryV5 {
  506. unhandled = make(chan discover.ReadPacket, 100)
  507. sconn = &sharedUDPConn{conn, unhandled}
  508. }
  509. cfg := discover.Config{
  510. PrivateKey: srv.PrivateKey,
  511. NetRestrict: srv.NetRestrict,
  512. Bootnodes: srv.BootstrapNodes,
  513. Unhandled: unhandled,
  514. Log: srv.log,
  515. }
  516. ntab, err := discover.ListenV4(conn, srv.localnode, cfg)
  517. if err != nil {
  518. return err
  519. }
  520. srv.ntab = ntab
  521. srv.discmix.AddSource(ntab.RandomNodes())
  522. }
  523. // Discovery V5
  524. if srv.DiscoveryV5 {
  525. cfg := discover.Config{
  526. PrivateKey: srv.PrivateKey,
  527. NetRestrict: srv.NetRestrict,
  528. Bootnodes: srv.BootstrapNodesV5,
  529. Log: srv.log,
  530. }
  531. var err error
  532. if sconn != nil {
  533. srv.DiscV5, err = discover.ListenV5(sconn, srv.localnode, cfg)
  534. } else {
  535. srv.DiscV5, err = discover.ListenV5(conn, srv.localnode, cfg)
  536. }
  537. if err != nil {
  538. return err
  539. }
  540. }
  541. return nil
  542. }
  543. func (srv *Server) setupDialScheduler() {
  544. config := dialConfig{
  545. self: srv.localnode.ID(),
  546. maxDialPeers: srv.maxDialedConns(),
  547. maxActiveDials: srv.MaxPendingPeers,
  548. log: srv.Logger,
  549. netRestrict: srv.NetRestrict,
  550. dialer: srv.Dialer,
  551. clock: srv.clock,
  552. }
  553. if srv.ntab != nil {
  554. config.resolver = srv.ntab
  555. }
  556. if config.dialer == nil {
  557. config.dialer = tcpDialer{&net.Dialer{Timeout: defaultDialTimeout}}
  558. }
  559. srv.dialsched = newDialScheduler(config, srv.discmix, srv.SetupConn)
  560. for _, n := range srv.StaticNodes {
  561. srv.dialsched.addStatic(n)
  562. }
  563. }
  564. func (srv *Server) maxInboundConns() int {
  565. return srv.MaxPeers - srv.maxDialedConns()
  566. }
  567. func (srv *Server) maxDialedConns() (limit int) {
  568. if srv.NoDial || srv.MaxPeers == 0 {
  569. return 0
  570. }
  571. if srv.DialRatio == 0 {
  572. limit = srv.MaxPeers / defaultDialRatio
  573. } else {
  574. limit = srv.MaxPeers / srv.DialRatio
  575. }
  576. if limit == 0 {
  577. limit = 1
  578. }
  579. return limit
  580. }
  581. func (srv *Server) setupListening() error {
  582. // Launch the listener.
  583. listener, err := srv.listenFunc("tcp", srv.ListenAddr)
  584. if err != nil {
  585. return err
  586. }
  587. srv.listener = listener
  588. srv.ListenAddr = listener.Addr().String()
  589. // Update the local node record and map the TCP listening port if NAT is configured.
  590. if tcp, ok := listener.Addr().(*net.TCPAddr); ok {
  591. srv.localnode.Set(enr.TCP(tcp.Port))
  592. if !tcp.IP.IsLoopback() && srv.NAT != nil {
  593. srv.loopWG.Add(1)
  594. gopool.Submit(func() {
  595. nat.Map(srv.NAT, srv.quit, "tcp", tcp.Port, tcp.Port, "ethereum p2p")
  596. srv.loopWG.Done()
  597. })
  598. }
  599. }
  600. srv.loopWG.Add(1)
  601. go srv.listenLoop()
  602. return nil
  603. }
  604. // doPeerOp runs fn on the main loop.
  605. func (srv *Server) doPeerOp(fn peerOpFunc) {
  606. select {
  607. case srv.peerOp <- fn:
  608. <-srv.peerOpDone
  609. case <-srv.quit:
  610. }
  611. }
  612. // run is the main loop of the server.
  613. func (srv *Server) run() {
  614. srv.log.Info("Started P2P networking", "self", srv.localnode.Node().URLv4())
  615. defer srv.loopWG.Done()
  616. defer srv.nodedb.Close()
  617. defer srv.discmix.Close()
  618. defer srv.dialsched.stop()
  619. var (
  620. peers = make(map[enode.ID]*Peer)
  621. inboundCount = 0
  622. trusted = make(map[enode.ID]bool, len(srv.TrustedNodes))
  623. )
  624. // Put trusted nodes into a map to speed up checks.
  625. // Trusted peers are loaded on startup or added via AddTrustedPeer RPC.
  626. for _, n := range srv.TrustedNodes {
  627. trusted[n.ID()] = true
  628. }
  629. running:
  630. for {
  631. select {
  632. case <-srv.quit:
  633. // The server was stopped. Run the cleanup logic.
  634. break running
  635. case n := <-srv.addtrusted:
  636. // This channel is used by AddTrustedPeer to add a node
  637. // to the trusted node set.
  638. srv.log.Trace("Adding trusted node", "node", n)
  639. trusted[n.ID()] = true
  640. if p, ok := peers[n.ID()]; ok {
  641. p.rw.set(trustedConn, true)
  642. }
  643. case n := <-srv.removetrusted:
  644. // This channel is used by RemoveTrustedPeer to remove a node
  645. // from the trusted node set.
  646. srv.log.Trace("Removing trusted node", "node", n)
  647. delete(trusted, n.ID())
  648. if p, ok := peers[n.ID()]; ok {
  649. p.rw.set(trustedConn, false)
  650. }
  651. case op := <-srv.peerOp:
  652. // This channel is used by Peers and PeerCount.
  653. op(peers)
  654. srv.peerOpDone <- struct{}{}
  655. case c := <-srv.checkpointPostHandshake:
  656. // A connection has passed the encryption handshake so
  657. // the remote identity is known (but hasn't been verified yet).
  658. if trusted[c.node.ID()] {
  659. // Ensure that the trusted flag is set before checking against MaxPeers.
  660. c.flags |= trustedConn
  661. }
  662. // TODO: track in-progress inbound node IDs (pre-Peer) to avoid dialing them.
  663. c.cont <- srv.postHandshakeChecks(peers, inboundCount, c)
  664. case c := <-srv.checkpointAddPeer:
  665. // At this point the connection is past the protocol handshake.
  666. // Its capabilities are known and the remote identity is verified.
  667. err := srv.addPeerChecks(peers, inboundCount, c)
  668. if err == nil {
  669. // The handshakes are done and it passed all checks.
  670. p := srv.launchPeer(c)
  671. peers[c.node.ID()] = p
  672. srv.log.Debug("Adding p2p peer", "peercount", len(peers), "id", p.ID(), "conn", c.flags, "addr", p.RemoteAddr(), "name", p.Name())
  673. srv.dialsched.peerAdded(c)
  674. if p.Inbound() {
  675. inboundCount++
  676. }
  677. }
  678. c.cont <- err
  679. case pd := <-srv.delpeer:
  680. // A peer disconnected.
  681. d := common.PrettyDuration(mclock.Now() - pd.created)
  682. delete(peers, pd.ID())
  683. srv.log.Debug("Removing p2p peer", "peercount", len(peers), "id", pd.ID(), "duration", d, "req", pd.requested, "err", pd.err)
  684. srv.dialsched.peerRemoved(pd.rw)
  685. if pd.Inbound() {
  686. inboundCount--
  687. }
  688. }
  689. }
  690. srv.log.Trace("P2P networking is spinning down")
  691. // Terminate discovery. If there is a running lookup it will terminate soon.
  692. if srv.ntab != nil {
  693. srv.ntab.Close()
  694. }
  695. if srv.DiscV5 != nil {
  696. srv.DiscV5.Close()
  697. }
  698. // Disconnect all peers.
  699. for _, p := range peers {
  700. p.Disconnect(DiscQuitting)
  701. }
  702. // Wait for peers to shut down. Pending connections and tasks are
  703. // not handled here and will terminate soon-ish because srv.quit
  704. // is closed.
  705. for len(peers) > 0 {
  706. p := <-srv.delpeer
  707. p.log.Trace("<-delpeer (spindown)")
  708. delete(peers, p.ID())
  709. }
  710. }
  711. func (srv *Server) postHandshakeChecks(peers map[enode.ID]*Peer, inboundCount int, c *conn) error {
  712. switch {
  713. case !c.is(trustedConn) && len(peers) >= srv.MaxPeers:
  714. return DiscTooManyPeers
  715. case !c.is(trustedConn) && c.is(inboundConn) && inboundCount >= srv.maxInboundConns():
  716. return DiscTooManyPeers
  717. case peers[c.node.ID()] != nil:
  718. return DiscAlreadyConnected
  719. case c.node.ID() == srv.localnode.ID():
  720. return DiscSelf
  721. default:
  722. return nil
  723. }
  724. }
  725. func (srv *Server) addPeerChecks(peers map[enode.ID]*Peer, inboundCount int, c *conn) error {
  726. // Drop connections with no matching protocols.
  727. if len(srv.Protocols) > 0 && countMatchingProtocols(srv.Protocols, c.caps) == 0 {
  728. return DiscUselessPeer
  729. }
  730. // Repeat the post-handshake checks because the
  731. // peer set might have changed since those checks were performed.
  732. return srv.postHandshakeChecks(peers, inboundCount, c)
  733. }
  734. // listenLoop runs in its own goroutine and accepts
  735. // inbound connections.
  736. func (srv *Server) listenLoop() {
  737. srv.log.Debug("TCP listener up", "addr", srv.listener.Addr())
  738. // The slots channel limits accepts of new connections.
  739. tokens := defaultMaxPendingPeers
  740. if srv.MaxPendingPeers > 0 {
  741. tokens = srv.MaxPendingPeers
  742. }
  743. slots := make(chan struct{}, tokens)
  744. for i := 0; i < tokens; i++ {
  745. slots <- struct{}{}
  746. }
  747. // Wait for slots to be returned on exit. This ensures all connection goroutines
  748. // are down before listenLoop returns.
  749. defer srv.loopWG.Done()
  750. defer func() {
  751. for i := 0; i < cap(slots); i++ {
  752. <-slots
  753. }
  754. }()
  755. for {
  756. // Wait for a free slot before accepting.
  757. <-slots
  758. var (
  759. fd net.Conn
  760. err error
  761. lastLog time.Time
  762. )
  763. for {
  764. fd, err = srv.listener.Accept()
  765. if netutil.IsTemporaryError(err) {
  766. if time.Since(lastLog) > 1*time.Second {
  767. srv.log.Debug("Temporary read error", "err", err)
  768. lastLog = time.Now()
  769. }
  770. time.Sleep(time.Millisecond * 200)
  771. continue
  772. } else if err != nil {
  773. srv.log.Debug("Read error", "err", err)
  774. slots <- struct{}{}
  775. return
  776. }
  777. break
  778. }
  779. remoteIP := netutil.AddrIP(fd.RemoteAddr())
  780. if err := srv.checkInboundConn(remoteIP); err != nil {
  781. srv.log.Debug("Rejected inbound connection", "addr", fd.RemoteAddr(), "err", err)
  782. fd.Close()
  783. slots <- struct{}{}
  784. continue
  785. }
  786. if remoteIP != nil {
  787. var addr *net.TCPAddr
  788. if tcp, ok := fd.RemoteAddr().(*net.TCPAddr); ok {
  789. addr = tcp
  790. }
  791. fd = newMeteredConn(fd, true, addr)
  792. srv.log.Trace("Accepted connection", "addr", fd.RemoteAddr())
  793. }
  794. gopool.Submit(func() {
  795. srv.SetupConn(fd, inboundConn, nil)
  796. slots <- struct{}{}
  797. })
  798. }
  799. }
  800. func (srv *Server) checkInboundConn(remoteIP net.IP) error {
  801. if remoteIP == nil {
  802. return nil
  803. }
  804. // Reject connections that do not match NetRestrict.
  805. if srv.NetRestrict != nil && !srv.NetRestrict.Contains(remoteIP) {
  806. return fmt.Errorf("not whitelisted in NetRestrict")
  807. }
  808. // Reject Internet peers that try too often.
  809. now := srv.clock.Now()
  810. srv.inboundHistory.expire(now, nil)
  811. if !netutil.IsLAN(remoteIP) && srv.inboundHistory.contains(remoteIP.String()) {
  812. return fmt.Errorf("too many attempts")
  813. }
  814. srv.inboundHistory.add(remoteIP.String(), now.Add(inboundThrottleTime))
  815. return nil
  816. }
  817. // SetupConn runs the handshakes and attempts to add the connection
  818. // as a peer. It returns when the connection has been added as a peer
  819. // or the handshakes have failed.
  820. func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *enode.Node) error {
  821. c := &conn{fd: fd, flags: flags, cont: make(chan error)}
  822. if dialDest == nil {
  823. c.transport = srv.newTransport(fd, nil)
  824. } else {
  825. c.transport = srv.newTransport(fd, dialDest.Pubkey())
  826. }
  827. err := srv.setupConn(c, flags, dialDest)
  828. if err != nil {
  829. c.close(err)
  830. }
  831. return err
  832. }
  833. func (srv *Server) setupConn(c *conn, flags connFlag, dialDest *enode.Node) error {
  834. // Prevent leftover pending conns from entering the handshake.
  835. srv.lock.Lock()
  836. running := srv.running
  837. srv.lock.Unlock()
  838. if !running {
  839. return errServerStopped
  840. }
  841. // If dialing, figure out the remote public key.
  842. var dialPubkey *ecdsa.PublicKey
  843. if dialDest != nil {
  844. dialPubkey = new(ecdsa.PublicKey)
  845. if err := dialDest.Load((*enode.Secp256k1)(dialPubkey)); err != nil {
  846. err = errors.New("dial destination doesn't have a secp256k1 public key")
  847. srv.log.Trace("Setting up connection failed", "addr", c.fd.RemoteAddr(), "conn", c.flags, "err", err)
  848. return err
  849. }
  850. }
  851. // Run the RLPx handshake.
  852. remotePubkey, err := c.doEncHandshake(srv.PrivateKey)
  853. if err != nil {
  854. srv.log.Trace("Failed RLPx handshake", "addr", c.fd.RemoteAddr(), "conn", c.flags, "err", err)
  855. return err
  856. }
  857. if dialDest != nil {
  858. c.node = dialDest
  859. } else {
  860. c.node = nodeFromConn(remotePubkey, c.fd)
  861. }
  862. clog := srv.log.New("id", c.node.ID(), "addr", c.fd.RemoteAddr(), "conn", c.flags)
  863. err = srv.checkpoint(c, srv.checkpointPostHandshake)
  864. if err != nil {
  865. clog.Trace("Rejected peer", "err", err)
  866. return err
  867. }
  868. // Run the capability negotiation handshake.
  869. phs, err := c.doProtoHandshake(srv.ourHandshake)
  870. if err != nil {
  871. clog.Trace("Failed p2p handshake", "err", err)
  872. return err
  873. }
  874. if id := c.node.ID(); !bytes.Equal(crypto.Keccak256(phs.ID), id[:]) {
  875. clog.Trace("Wrong devp2p handshake identity", "phsid", hex.EncodeToString(phs.ID))
  876. return DiscUnexpectedIdentity
  877. }
  878. c.caps, c.name = phs.Caps, phs.Name
  879. err = srv.checkpoint(c, srv.checkpointAddPeer)
  880. if err != nil {
  881. clog.Trace("Rejected peer", "err", err)
  882. return err
  883. }
  884. return nil
  885. }
  886. func nodeFromConn(pubkey *ecdsa.PublicKey, conn net.Conn) *enode.Node {
  887. var ip net.IP
  888. var port int
  889. if tcp, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
  890. ip = tcp.IP
  891. port = tcp.Port
  892. }
  893. return enode.NewV4(pubkey, ip, port, port)
  894. }
  895. // checkpoint sends the conn to run, which performs the
  896. // post-handshake checks for the stage (posthandshake, addpeer).
  897. func (srv *Server) checkpoint(c *conn, stage chan<- *conn) error {
  898. select {
  899. case stage <- c:
  900. case <-srv.quit:
  901. return errServerStopped
  902. }
  903. return <-c.cont
  904. }
  905. func (srv *Server) launchPeer(c *conn) *Peer {
  906. p := newPeer(srv.log, c, srv.Protocols)
  907. if srv.EnableMsgEvents {
  908. // If message events are enabled, pass the peerFeed
  909. // to the peer.
  910. p.events = &srv.peerFeed
  911. }
  912. gopool.Submit(func() {
  913. srv.runPeer(p)
  914. })
  915. return p
  916. }
  917. // runPeer runs in its own goroutine for each peer.
  918. func (srv *Server) runPeer(p *Peer) {
  919. if srv.newPeerHook != nil {
  920. srv.newPeerHook(p)
  921. }
  922. srv.peerFeed.Send(&PeerEvent{
  923. Type: PeerEventTypeAdd,
  924. Peer: p.ID(),
  925. RemoteAddress: p.RemoteAddr().String(),
  926. LocalAddress: p.LocalAddr().String(),
  927. })
  928. // Run the per-peer main loop.
  929. remoteRequested, err := p.run()
  930. // Announce disconnect on the main loop to update the peer set.
  931. // The main loop waits for existing peers to be sent on srv.delpeer
  932. // before returning, so this send should not select on srv.quit.
  933. srv.delpeer <- peerDrop{p, err, remoteRequested}
  934. // Broadcast peer drop to external subscribers. This needs to be
  935. // after the send to delpeer so subscribers have a consistent view of
  936. // the peer set (i.e. Server.Peers() doesn't include the peer when the
  937. // event is received.
  938. srv.peerFeed.Send(&PeerEvent{
  939. Type: PeerEventTypeDrop,
  940. Peer: p.ID(),
  941. Error: err.Error(),
  942. RemoteAddress: p.RemoteAddr().String(),
  943. LocalAddress: p.LocalAddr().String(),
  944. })
  945. }
  946. // NodeInfo represents a short summary of the information known about the host.
  947. type NodeInfo struct {
  948. ID string `json:"id"` // Unique node identifier (also the encryption key)
  949. Name string `json:"name"` // Name of the node, including client type, version, OS, custom data
  950. Enode string `json:"enode"` // Enode URL for adding this peer from remote peers
  951. ENR string `json:"enr"` // Ethereum Node Record
  952. IP string `json:"ip"` // IP address of the node
  953. Ports struct {
  954. Discovery int `json:"discovery"` // UDP listening port for discovery protocol
  955. Listener int `json:"listener"` // TCP listening port for RLPx
  956. } `json:"ports"`
  957. ListenAddr string `json:"listenAddr"`
  958. Protocols map[string]interface{} `json:"protocols"`
  959. }
  960. // NodeInfo gathers and returns a collection of metadata known about the host.
  961. func (srv *Server) NodeInfo() *NodeInfo {
  962. // Gather and assemble the generic node infos
  963. node := srv.Self()
  964. info := &NodeInfo{
  965. Name: srv.Name,
  966. Enode: node.URLv4(),
  967. ID: node.ID().String(),
  968. IP: node.IP().String(),
  969. ListenAddr: srv.ListenAddr,
  970. Protocols: make(map[string]interface{}),
  971. }
  972. info.Ports.Discovery = node.UDP()
  973. info.Ports.Listener = node.TCP()
  974. info.ENR = node.String()
  975. // Gather all the running protocol infos (only once per protocol type)
  976. for _, proto := range srv.Protocols {
  977. if _, ok := info.Protocols[proto.Name]; !ok {
  978. nodeInfo := interface{}("unknown")
  979. if query := proto.NodeInfo; query != nil {
  980. nodeInfo = proto.NodeInfo()
  981. }
  982. info.Protocols[proto.Name] = nodeInfo
  983. }
  984. }
  985. return info
  986. }
  987. // PeersInfo returns an array of metadata objects describing connected peers.
  988. func (srv *Server) PeersInfo() []*PeerInfo {
  989. // Gather all the generic and sub-protocol specific infos
  990. infos := make([]*PeerInfo, 0, srv.PeerCount())
  991. for _, peer := range srv.Peers() {
  992. if peer != nil {
  993. infos = append(infos, peer.Info())
  994. }
  995. }
  996. // Sort the result array alphabetically by node identifier
  997. for i := 0; i < len(infos); i++ {
  998. for j := i + 1; j < len(infos); j++ {
  999. if infos[i].ID > infos[j].ID {
  1000. infos[i], infos[j] = infos[j], infos[i]
  1001. }
  1002. }
  1003. }
  1004. return infos
  1005. }