server.go 31 KB

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