server.go 31 KB

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