server.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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. "crypto/ecdsa"
  20. "errors"
  21. "fmt"
  22. "net"
  23. "sync"
  24. "time"
  25. "github.com/ethereum/go-ethereum/logger"
  26. "github.com/ethereum/go-ethereum/logger/glog"
  27. "github.com/ethereum/go-ethereum/p2p/discover"
  28. "github.com/ethereum/go-ethereum/p2p/nat"
  29. )
  30. const (
  31. defaultDialTimeout = 15 * time.Second
  32. refreshPeersInterval = 30 * time.Second
  33. staticPeerCheckInterval = 15 * time.Second
  34. // Maximum number of concurrently handshaking inbound connections.
  35. maxAcceptConns = 50
  36. // Maximum number of concurrently dialing outbound connections.
  37. maxActiveDialTasks = 16
  38. // Maximum time allowed for reading a complete message.
  39. // This is effectively the amount of time a connection can be idle.
  40. frameReadTimeout = 30 * time.Second
  41. // Maximum amount of time allowed for writing a complete message.
  42. frameWriteTimeout = 20 * time.Second
  43. )
  44. var errServerStopped = errors.New("server stopped")
  45. var srvjslog = logger.NewJsonLogger()
  46. // Server manages all peer connections.
  47. //
  48. // The fields of Server are used as configuration parameters.
  49. // You should set them before starting the Server. Fields may not be
  50. // modified while the server is running.
  51. type Server struct {
  52. // This field must be set to a valid secp256k1 private key.
  53. PrivateKey *ecdsa.PrivateKey
  54. // MaxPeers is the maximum number of peers that can be
  55. // connected. It must be greater than zero.
  56. MaxPeers int
  57. // MaxPendingPeers is the maximum number of peers that can be pending in the
  58. // handshake phase, counted separately for inbound and outbound connections.
  59. // Zero defaults to preset values.
  60. MaxPendingPeers int
  61. // Discovery specifies whether the peer discovery mechanism should be started
  62. // or not. Disabling is usually useful for protocol debugging (manual topology).
  63. Discovery bool
  64. // Name sets the node name of this server.
  65. // Use common.MakeName to create a name that follows existing conventions.
  66. Name string
  67. // Bootstrap nodes are used to establish connectivity
  68. // with the rest of the network.
  69. BootstrapNodes []*discover.Node
  70. // Static nodes are used as pre-configured connections which are always
  71. // maintained and re-connected on disconnects.
  72. StaticNodes []*discover.Node
  73. // Trusted nodes are used as pre-configured connections which are always
  74. // allowed to connect, even above the peer limit.
  75. TrustedNodes []*discover.Node
  76. // NodeDatabase is the path to the database containing the previously seen
  77. // live nodes in the network.
  78. NodeDatabase string
  79. // Protocols should contain the protocols supported
  80. // by the server. Matching protocols are launched for
  81. // each peer.
  82. Protocols []Protocol
  83. // If ListenAddr is set to a non-nil address, the server
  84. // will listen for incoming connections.
  85. //
  86. // If the port is zero, the operating system will pick a port. The
  87. // ListenAddr field will be updated with the actual address when
  88. // the server is started.
  89. ListenAddr string
  90. // If set to a non-nil value, the given NAT port mapper
  91. // is used to make the listening port available to the
  92. // Internet.
  93. NAT nat.Interface
  94. // If Dialer is set to a non-nil value, the given Dialer
  95. // is used to dial outbound peer connections.
  96. Dialer *net.Dialer
  97. // If NoDial is true, the server will not dial any peers.
  98. NoDial bool
  99. // Hooks for testing. These are useful because we can inhibit
  100. // the whole protocol stack.
  101. newTransport func(net.Conn) transport
  102. newPeerHook func(*Peer)
  103. lock sync.Mutex // protects running
  104. running bool
  105. ntab discoverTable
  106. listener net.Listener
  107. ourHandshake *protoHandshake
  108. lastLookup time.Time
  109. // These are for Peers, PeerCount (and nothing else).
  110. peerOp chan peerOpFunc
  111. peerOpDone chan struct{}
  112. quit chan struct{}
  113. addstatic chan *discover.Node
  114. posthandshake chan *conn
  115. addpeer chan *conn
  116. delpeer chan *Peer
  117. loopWG sync.WaitGroup // loop, listenLoop
  118. }
  119. type peerOpFunc func(map[discover.NodeID]*Peer)
  120. type connFlag int
  121. const (
  122. dynDialedConn connFlag = 1 << iota
  123. staticDialedConn
  124. inboundConn
  125. trustedConn
  126. )
  127. // conn wraps a network connection with information gathered
  128. // during the two handshakes.
  129. type conn struct {
  130. fd net.Conn
  131. transport
  132. flags connFlag
  133. cont chan error // The run loop uses cont to signal errors to setupConn.
  134. id discover.NodeID // valid after the encryption handshake
  135. caps []Cap // valid after the protocol handshake
  136. name string // valid after the protocol handshake
  137. }
  138. type transport interface {
  139. // The two handshakes.
  140. doEncHandshake(prv *ecdsa.PrivateKey, dialDest *discover.Node) (discover.NodeID, error)
  141. doProtoHandshake(our *protoHandshake) (*protoHandshake, error)
  142. // The MsgReadWriter can only be used after the encryption
  143. // handshake has completed. The code uses conn.id to track this
  144. // by setting it to a non-nil value after the encryption handshake.
  145. MsgReadWriter
  146. // transports must provide Close because we use MsgPipe in some of
  147. // the tests. Closing the actual network connection doesn't do
  148. // anything in those tests because NsgPipe doesn't use it.
  149. close(err error)
  150. }
  151. func (c *conn) String() string {
  152. s := c.flags.String() + " conn"
  153. if (c.id != discover.NodeID{}) {
  154. s += fmt.Sprintf(" %x", c.id[:8])
  155. }
  156. s += " " + c.fd.RemoteAddr().String()
  157. return s
  158. }
  159. func (f connFlag) String() string {
  160. s := ""
  161. if f&trustedConn != 0 {
  162. s += " trusted"
  163. }
  164. if f&dynDialedConn != 0 {
  165. s += " dyn dial"
  166. }
  167. if f&staticDialedConn != 0 {
  168. s += " static dial"
  169. }
  170. if f&inboundConn != 0 {
  171. s += " inbound"
  172. }
  173. if s != "" {
  174. s = s[1:]
  175. }
  176. return s
  177. }
  178. func (c *conn) is(f connFlag) bool {
  179. return c.flags&f != 0
  180. }
  181. // Peers returns all connected peers.
  182. func (srv *Server) Peers() []*Peer {
  183. var ps []*Peer
  184. select {
  185. // Note: We'd love to put this function into a variable but
  186. // that seems to cause a weird compiler error in some
  187. // environments.
  188. case srv.peerOp <- func(peers map[discover.NodeID]*Peer) {
  189. for _, p := range peers {
  190. ps = append(ps, p)
  191. }
  192. }:
  193. <-srv.peerOpDone
  194. case <-srv.quit:
  195. }
  196. return ps
  197. }
  198. // PeerCount returns the number of connected peers.
  199. func (srv *Server) PeerCount() int {
  200. var count int
  201. select {
  202. case srv.peerOp <- func(ps map[discover.NodeID]*Peer) { count = len(ps) }:
  203. <-srv.peerOpDone
  204. case <-srv.quit:
  205. }
  206. return count
  207. }
  208. // AddPeer connects to the given node and maintains the connection until the
  209. // server is shut down. If the connection fails for any reason, the server will
  210. // attempt to reconnect the peer.
  211. func (srv *Server) AddPeer(node *discover.Node) {
  212. select {
  213. case srv.addstatic <- node:
  214. case <-srv.quit:
  215. }
  216. }
  217. // Self returns the local node's endpoint information.
  218. func (srv *Server) Self() *discover.Node {
  219. srv.lock.Lock()
  220. defer srv.lock.Unlock()
  221. // If the server's not running, return an empty node
  222. if !srv.running {
  223. return &discover.Node{IP: net.ParseIP("0.0.0.0")}
  224. }
  225. // If the node is running but discovery is off, manually assemble the node infos
  226. if srv.ntab == nil {
  227. // Inbound connections disabled, use zero address
  228. if srv.listener == nil {
  229. return &discover.Node{IP: net.ParseIP("0.0.0.0"), ID: discover.PubkeyID(&srv.PrivateKey.PublicKey)}
  230. }
  231. // Otherwise inject the listener address too
  232. addr := srv.listener.Addr().(*net.TCPAddr)
  233. return &discover.Node{
  234. ID: discover.PubkeyID(&srv.PrivateKey.PublicKey),
  235. IP: addr.IP,
  236. TCP: uint16(addr.Port),
  237. }
  238. }
  239. // Otherwise return the live node infos
  240. return srv.ntab.Self()
  241. }
  242. // Stop terminates the server and all active peer connections.
  243. // It blocks until all active connections have been closed.
  244. func (srv *Server) Stop() {
  245. srv.lock.Lock()
  246. defer srv.lock.Unlock()
  247. if !srv.running {
  248. return
  249. }
  250. srv.running = false
  251. if srv.listener != nil {
  252. // this unblocks listener Accept
  253. srv.listener.Close()
  254. }
  255. close(srv.quit)
  256. srv.loopWG.Wait()
  257. }
  258. // Start starts running the server.
  259. // Servers can not be re-used after stopping.
  260. func (srv *Server) Start() (err error) {
  261. srv.lock.Lock()
  262. defer srv.lock.Unlock()
  263. if srv.running {
  264. return errors.New("server already running")
  265. }
  266. srv.running = true
  267. glog.V(logger.Info).Infoln("Starting Server")
  268. // static fields
  269. if srv.PrivateKey == nil {
  270. return fmt.Errorf("Server.PrivateKey must be set to a non-nil key")
  271. }
  272. if srv.newTransport == nil {
  273. srv.newTransport = newRLPX
  274. }
  275. if srv.Dialer == nil {
  276. srv.Dialer = &net.Dialer{Timeout: defaultDialTimeout}
  277. }
  278. srv.quit = make(chan struct{})
  279. srv.addpeer = make(chan *conn)
  280. srv.delpeer = make(chan *Peer)
  281. srv.posthandshake = make(chan *conn)
  282. srv.addstatic = make(chan *discover.Node)
  283. srv.peerOp = make(chan peerOpFunc)
  284. srv.peerOpDone = make(chan struct{})
  285. // node table
  286. if srv.Discovery {
  287. ntab, err := discover.ListenUDP(srv.PrivateKey, srv.ListenAddr, srv.NAT, srv.NodeDatabase)
  288. if err != nil {
  289. return err
  290. }
  291. if err := ntab.SetFallbackNodes(srv.BootstrapNodes); err != nil {
  292. return err
  293. }
  294. srv.ntab = ntab
  295. }
  296. dynPeers := (srv.MaxPeers + 1) / 2
  297. if !srv.Discovery {
  298. dynPeers = 0
  299. }
  300. dialer := newDialState(srv.StaticNodes, srv.ntab, dynPeers)
  301. // handshake
  302. srv.ourHandshake = &protoHandshake{Version: baseProtocolVersion, Name: srv.Name, ID: discover.PubkeyID(&srv.PrivateKey.PublicKey)}
  303. for _, p := range srv.Protocols {
  304. srv.ourHandshake.Caps = append(srv.ourHandshake.Caps, p.cap())
  305. }
  306. // listen/dial
  307. if srv.ListenAddr != "" {
  308. if err := srv.startListening(); err != nil {
  309. return err
  310. }
  311. }
  312. if srv.NoDial && srv.ListenAddr == "" {
  313. glog.V(logger.Warn).Infoln("I will be kind-of useless, neither dialing nor listening.")
  314. }
  315. srv.loopWG.Add(1)
  316. go srv.run(dialer)
  317. srv.running = true
  318. return nil
  319. }
  320. func (srv *Server) startListening() error {
  321. // Launch the TCP listener.
  322. listener, err := net.Listen("tcp", srv.ListenAddr)
  323. if err != nil {
  324. return err
  325. }
  326. laddr := listener.Addr().(*net.TCPAddr)
  327. srv.ListenAddr = laddr.String()
  328. srv.listener = listener
  329. srv.loopWG.Add(1)
  330. go srv.listenLoop()
  331. // Map the TCP listening port if NAT is configured.
  332. if !laddr.IP.IsLoopback() && srv.NAT != nil {
  333. srv.loopWG.Add(1)
  334. go func() {
  335. nat.Map(srv.NAT, srv.quit, "tcp", laddr.Port, laddr.Port, "ethereum p2p")
  336. srv.loopWG.Done()
  337. }()
  338. }
  339. return nil
  340. }
  341. type dialer interface {
  342. newTasks(running int, peers map[discover.NodeID]*Peer, now time.Time) []task
  343. taskDone(task, time.Time)
  344. addStatic(*discover.Node)
  345. }
  346. func (srv *Server) run(dialstate dialer) {
  347. defer srv.loopWG.Done()
  348. var (
  349. peers = make(map[discover.NodeID]*Peer)
  350. trusted = make(map[discover.NodeID]bool, len(srv.TrustedNodes))
  351. tasks []task
  352. pendingTasks []task
  353. taskdone = make(chan task, maxActiveDialTasks)
  354. )
  355. // Put trusted nodes into a map to speed up checks.
  356. // Trusted peers are loaded on startup and cannot be
  357. // modified while the server is running.
  358. for _, n := range srv.TrustedNodes {
  359. trusted[n.ID] = true
  360. }
  361. // Some task list helpers.
  362. delTask := func(t task) {
  363. for i := range tasks {
  364. if tasks[i] == t {
  365. tasks = append(tasks[:i], tasks[i+1:]...)
  366. break
  367. }
  368. }
  369. }
  370. scheduleTasks := func(new []task) {
  371. pt := append(pendingTasks, new...)
  372. start := maxActiveDialTasks - len(tasks)
  373. if len(pt) < start {
  374. start = len(pt)
  375. }
  376. if start > 0 {
  377. tasks = append(tasks, pt[:start]...)
  378. for _, t := range pt[:start] {
  379. t := t
  380. glog.V(logger.Detail).Infoln("new task:", t)
  381. go func() { t.Do(srv); taskdone <- t }()
  382. }
  383. copy(pt, pt[start:])
  384. pendingTasks = pt[:len(pt)-start]
  385. }
  386. }
  387. running:
  388. for {
  389. // Query the dialer for new tasks and launch them.
  390. now := time.Now()
  391. nt := dialstate.newTasks(len(pendingTasks)+len(tasks), peers, now)
  392. scheduleTasks(nt)
  393. select {
  394. case <-srv.quit:
  395. // The server was stopped. Run the cleanup logic.
  396. glog.V(logger.Detail).Infoln("<-quit: spinning down")
  397. break running
  398. case n := <-srv.addstatic:
  399. // This channel is used by AddPeer to add to the
  400. // ephemeral static peer list. Add it to the dialer,
  401. // it will keep the node connected.
  402. glog.V(logger.Detail).Infoln("<-addstatic:", n)
  403. dialstate.addStatic(n)
  404. case op := <-srv.peerOp:
  405. // This channel is used by Peers and PeerCount.
  406. op(peers)
  407. srv.peerOpDone <- struct{}{}
  408. case t := <-taskdone:
  409. // A task got done. Tell dialstate about it so it
  410. // can update its state and remove it from the active
  411. // tasks list.
  412. glog.V(logger.Detail).Infoln("<-taskdone:", t)
  413. dialstate.taskDone(t, now)
  414. delTask(t)
  415. case c := <-srv.posthandshake:
  416. // A connection has passed the encryption handshake so
  417. // the remote identity is known (but hasn't been verified yet).
  418. if trusted[c.id] {
  419. // Ensure that the trusted flag is set before checking against MaxPeers.
  420. c.flags |= trustedConn
  421. }
  422. glog.V(logger.Detail).Infoln("<-posthandshake:", c)
  423. // TODO: track in-progress inbound node IDs (pre-Peer) to avoid dialing them.
  424. c.cont <- srv.encHandshakeChecks(peers, c)
  425. case c := <-srv.addpeer:
  426. // At this point the connection is past the protocol handshake.
  427. // Its capabilities are known and the remote identity is verified.
  428. glog.V(logger.Detail).Infoln("<-addpeer:", c)
  429. err := srv.protoHandshakeChecks(peers, c)
  430. if err != nil {
  431. glog.V(logger.Detail).Infof("Not adding %v as peer: %v", c, err)
  432. } else {
  433. // The handshakes are done and it passed all checks.
  434. p := newPeer(c, srv.Protocols)
  435. peers[c.id] = p
  436. go srv.runPeer(p)
  437. }
  438. // The dialer logic relies on the assumption that
  439. // dial tasks complete after the peer has been added or
  440. // discarded. Unblock the task last.
  441. c.cont <- err
  442. case p := <-srv.delpeer:
  443. // A peer disconnected.
  444. glog.V(logger.Detail).Infoln("<-delpeer:", p)
  445. delete(peers, p.ID())
  446. }
  447. }
  448. // Terminate discovery. If there is a running lookup it will terminate soon.
  449. if srv.ntab != nil {
  450. srv.ntab.Close()
  451. }
  452. // Disconnect all peers.
  453. for _, p := range peers {
  454. p.Disconnect(DiscQuitting)
  455. }
  456. // Wait for peers to shut down. Pending connections and tasks are
  457. // not handled here and will terminate soon-ish because srv.quit
  458. // is closed.
  459. glog.V(logger.Detail).Infof("ignoring %d pending tasks at spindown", len(tasks))
  460. for len(peers) > 0 {
  461. p := <-srv.delpeer
  462. glog.V(logger.Detail).Infoln("<-delpeer (spindown):", p)
  463. delete(peers, p.ID())
  464. }
  465. }
  466. func (srv *Server) protoHandshakeChecks(peers map[discover.NodeID]*Peer, c *conn) error {
  467. // Drop connections with no matching protocols.
  468. if len(srv.Protocols) > 0 && countMatchingProtocols(srv.Protocols, c.caps) == 0 {
  469. return DiscUselessPeer
  470. }
  471. // Repeat the encryption handshake checks because the
  472. // peer set might have changed between the handshakes.
  473. return srv.encHandshakeChecks(peers, c)
  474. }
  475. func (srv *Server) encHandshakeChecks(peers map[discover.NodeID]*Peer, c *conn) error {
  476. switch {
  477. case !c.is(trustedConn|staticDialedConn) && len(peers) >= srv.MaxPeers:
  478. return DiscTooManyPeers
  479. case peers[c.id] != nil:
  480. return DiscAlreadyConnected
  481. case c.id == srv.Self().ID:
  482. return DiscSelf
  483. default:
  484. return nil
  485. }
  486. }
  487. type tempError interface {
  488. Temporary() bool
  489. }
  490. // listenLoop runs in its own goroutine and accepts
  491. // inbound connections.
  492. func (srv *Server) listenLoop() {
  493. defer srv.loopWG.Done()
  494. glog.V(logger.Info).Infoln("Listening on", srv.listener.Addr())
  495. // This channel acts as a semaphore limiting
  496. // active inbound connections that are lingering pre-handshake.
  497. // If all slots are taken, no further connections are accepted.
  498. tokens := maxAcceptConns
  499. if srv.MaxPendingPeers > 0 {
  500. tokens = srv.MaxPendingPeers
  501. }
  502. slots := make(chan struct{}, tokens)
  503. for i := 0; i < tokens; i++ {
  504. slots <- struct{}{}
  505. }
  506. for {
  507. // Wait for a handshake slot before accepting.
  508. <-slots
  509. var (
  510. fd net.Conn
  511. err error
  512. )
  513. for {
  514. fd, err = srv.listener.Accept()
  515. if tempErr, ok := err.(tempError); ok && tempErr.Temporary() {
  516. glog.V(logger.Debug).Infof("Temporary read error: %v", err)
  517. continue
  518. } else if err != nil {
  519. glog.V(logger.Debug).Infof("Read error: %v", err)
  520. return
  521. }
  522. break
  523. }
  524. fd = newMeteredConn(fd, true)
  525. glog.V(logger.Debug).Infof("Accepted conn %v\n", fd.RemoteAddr())
  526. // Spawn the handler. It will give the slot back when the connection
  527. // has been established.
  528. go func() {
  529. srv.setupConn(fd, inboundConn, nil)
  530. slots <- struct{}{}
  531. }()
  532. }
  533. }
  534. // setupConn runs the handshakes and attempts to add the connection
  535. // as a peer. It returns when the connection has been added as a peer
  536. // or the handshakes have failed.
  537. func (srv *Server) setupConn(fd net.Conn, flags connFlag, dialDest *discover.Node) {
  538. // Prevent leftover pending conns from entering the handshake.
  539. srv.lock.Lock()
  540. running := srv.running
  541. srv.lock.Unlock()
  542. c := &conn{fd: fd, transport: srv.newTransport(fd), flags: flags, cont: make(chan error)}
  543. if !running {
  544. c.close(errServerStopped)
  545. return
  546. }
  547. // Run the encryption handshake.
  548. var err error
  549. if c.id, err = c.doEncHandshake(srv.PrivateKey, dialDest); err != nil {
  550. glog.V(logger.Debug).Infof("%v faild enc handshake: %v", c, err)
  551. c.close(err)
  552. return
  553. }
  554. // For dialed connections, check that the remote public key matches.
  555. if dialDest != nil && c.id != dialDest.ID {
  556. c.close(DiscUnexpectedIdentity)
  557. glog.V(logger.Debug).Infof("%v dialed identity mismatch, want %x", c, dialDest.ID[:8])
  558. return
  559. }
  560. if err := srv.checkpoint(c, srv.posthandshake); err != nil {
  561. glog.V(logger.Debug).Infof("%v failed checkpoint posthandshake: %v", c, err)
  562. c.close(err)
  563. return
  564. }
  565. // Run the protocol handshake
  566. phs, err := c.doProtoHandshake(srv.ourHandshake)
  567. if err != nil {
  568. glog.V(logger.Debug).Infof("%v failed proto handshake: %v", c, err)
  569. c.close(err)
  570. return
  571. }
  572. if phs.ID != c.id {
  573. glog.V(logger.Debug).Infof("%v wrong proto handshake identity: %x", c, phs.ID[:8])
  574. c.close(DiscUnexpectedIdentity)
  575. return
  576. }
  577. c.caps, c.name = phs.Caps, phs.Name
  578. if err := srv.checkpoint(c, srv.addpeer); err != nil {
  579. glog.V(logger.Debug).Infof("%v failed checkpoint addpeer: %v", c, err)
  580. c.close(err)
  581. return
  582. }
  583. // If the checks completed successfully, runPeer has now been
  584. // launched by run.
  585. }
  586. // checkpoint sends the conn to run, which performs the
  587. // post-handshake checks for the stage (posthandshake, addpeer).
  588. func (srv *Server) checkpoint(c *conn, stage chan<- *conn) error {
  589. select {
  590. case stage <- c:
  591. case <-srv.quit:
  592. return errServerStopped
  593. }
  594. select {
  595. case err := <-c.cont:
  596. return err
  597. case <-srv.quit:
  598. return errServerStopped
  599. }
  600. }
  601. // runPeer runs in its own goroutine for each peer.
  602. // it waits until the Peer logic returns and removes
  603. // the peer.
  604. func (srv *Server) runPeer(p *Peer) {
  605. glog.V(logger.Debug).Infof("Added %v\n", p)
  606. srvjslog.LogJson(&logger.P2PConnected{
  607. RemoteId: p.ID().String(),
  608. RemoteAddress: p.RemoteAddr().String(),
  609. RemoteVersionString: p.Name(),
  610. NumConnections: srv.PeerCount(),
  611. })
  612. if srv.newPeerHook != nil {
  613. srv.newPeerHook(p)
  614. }
  615. discreason := p.run()
  616. // Note: run waits for existing peers to be sent on srv.delpeer
  617. // before returning, so this send should not select on srv.quit.
  618. srv.delpeer <- p
  619. glog.V(logger.Debug).Infof("Removed %v (%v)\n", p, discreason)
  620. srvjslog.LogJson(&logger.P2PDisconnected{
  621. RemoteId: p.ID().String(),
  622. NumConnections: srv.PeerCount(),
  623. })
  624. }
  625. // NodeInfo represents a short summary of the information known about the host.
  626. type NodeInfo struct {
  627. ID string `json:"id"` // Unique node identifier (also the encryption key)
  628. Name string `json:"name"` // Name of the node, including client type, version, OS, custom data
  629. Enode string `json:"enode"` // Enode URL for adding this peer from remote peers
  630. IP string `json:"ip"` // IP address of the node
  631. Ports struct {
  632. Discovery int `json:"discovery"` // UDP listening port for discovery protocol
  633. Listener int `json:"listener"` // TCP listening port for RLPx
  634. } `json:"ports"`
  635. ListenAddr string `json:"listenAddr"`
  636. Protocols map[string]interface{} `json:"protocols"`
  637. }
  638. // Info gathers and returns a collection of metadata known about the host.
  639. func (srv *Server) NodeInfo() *NodeInfo {
  640. node := srv.Self()
  641. // Gather and assemble the generic node infos
  642. info := &NodeInfo{
  643. Name: srv.Name,
  644. Enode: node.String(),
  645. ID: node.ID.String(),
  646. IP: node.IP.String(),
  647. ListenAddr: srv.ListenAddr,
  648. Protocols: make(map[string]interface{}),
  649. }
  650. info.Ports.Discovery = int(node.UDP)
  651. info.Ports.Listener = int(node.TCP)
  652. // Gather all the running protocol infos (only once per protocol type)
  653. for _, proto := range srv.Protocols {
  654. if _, ok := info.Protocols[proto.Name]; !ok {
  655. nodeInfo := interface{}("unknown")
  656. if query := proto.NodeInfo; query != nil {
  657. nodeInfo = proto.NodeInfo()
  658. }
  659. info.Protocols[proto.Name] = nodeInfo
  660. }
  661. }
  662. return info
  663. }
  664. // PeersInfo returns an array of metadata objects describing connected peers.
  665. func (srv *Server) PeersInfo() []*PeerInfo {
  666. // Gather all the generic and sub-protocol specific infos
  667. infos := make([]*PeerInfo, 0, srv.PeerCount())
  668. for _, peer := range srv.Peers() {
  669. if peer != nil {
  670. infos = append(infos, peer.Info())
  671. }
  672. }
  673. // Sort the result array alphabetically by node identifier
  674. for i := 0; i < len(infos); i++ {
  675. for j := i + 1; j < len(infos); j++ {
  676. if infos[i].ID > infos[j].ID {
  677. infos[i], infos[j] = infos[j], infos[i]
  678. }
  679. }
  680. }
  681. return infos
  682. }