server.go 32 KB

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