peer.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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
  17. import (
  18. "errors"
  19. "fmt"
  20. "io"
  21. "net"
  22. "sort"
  23. "sync"
  24. "time"
  25. "github.com/ethereum/go-ethereum/common/mclock"
  26. "github.com/ethereum/go-ethereum/event"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/metrics"
  29. "github.com/ethereum/go-ethereum/p2p/enode"
  30. "github.com/ethereum/go-ethereum/p2p/enr"
  31. "github.com/ethereum/go-ethereum/rlp"
  32. )
  33. var (
  34. ErrShuttingDown = errors.New("shutting down")
  35. )
  36. const (
  37. baseProtocolVersion = 5
  38. baseProtocolLength = uint64(16)
  39. baseProtocolMaxMsgSize = 2 * 1024
  40. snappyProtocolVersion = 5
  41. pingInterval = 15 * time.Second
  42. )
  43. const (
  44. // devp2p message codes
  45. handshakeMsg = 0x00
  46. discMsg = 0x01
  47. pingMsg = 0x02
  48. pongMsg = 0x03
  49. )
  50. // protoHandshake is the RLP structure of the protocol handshake.
  51. type protoHandshake struct {
  52. Version uint64
  53. Name string
  54. Caps []Cap
  55. ListenPort uint64
  56. ID []byte // secp256k1 public key
  57. // Ignore additional fields (for forward compatibility).
  58. Rest []rlp.RawValue `rlp:"tail"`
  59. }
  60. // PeerEventType is the type of peer events emitted by a p2p.Server
  61. type PeerEventType string
  62. const (
  63. // PeerEventTypeAdd is the type of event emitted when a peer is added
  64. // to a p2p.Server
  65. PeerEventTypeAdd PeerEventType = "add"
  66. // PeerEventTypeDrop is the type of event emitted when a peer is
  67. // dropped from a p2p.Server
  68. PeerEventTypeDrop PeerEventType = "drop"
  69. // PeerEventTypeMsgSend is the type of event emitted when a
  70. // message is successfully sent to a peer
  71. PeerEventTypeMsgSend PeerEventType = "msgsend"
  72. // PeerEventTypeMsgRecv is the type of event emitted when a
  73. // message is received from a peer
  74. PeerEventTypeMsgRecv PeerEventType = "msgrecv"
  75. )
  76. // PeerEvent is an event emitted when peers are either added or dropped from
  77. // a p2p.Server or when a message is sent or received on a peer connection
  78. type PeerEvent struct {
  79. Type PeerEventType `json:"type"`
  80. Peer enode.ID `json:"peer"`
  81. Error string `json:"error,omitempty"`
  82. Protocol string `json:"protocol,omitempty"`
  83. MsgCode *uint64 `json:"msg_code,omitempty"`
  84. MsgSize *uint32 `json:"msg_size,omitempty"`
  85. LocalAddress string `json:"local,omitempty"`
  86. RemoteAddress string `json:"remote,omitempty"`
  87. }
  88. // Peer represents a connected remote node.
  89. type Peer struct {
  90. rw *conn
  91. running map[string]*protoRW
  92. log log.Logger
  93. created mclock.AbsTime
  94. wg sync.WaitGroup
  95. protoErr chan error
  96. closed chan struct{}
  97. disc chan DiscReason
  98. // events receives message send / receive events if set
  99. events *event.Feed
  100. }
  101. // NewPeer returns a peer for testing purposes.
  102. func NewPeer(id enode.ID, name string, caps []Cap) *Peer {
  103. pipe, _ := net.Pipe()
  104. node := enode.SignNull(new(enr.Record), id)
  105. conn := &conn{fd: pipe, transport: nil, node: node, caps: caps, name: name}
  106. peer := newPeer(log.Root(), conn, nil)
  107. close(peer.closed) // ensures Disconnect doesn't block
  108. return peer
  109. }
  110. // ID returns the node's public key.
  111. func (p *Peer) ID() enode.ID {
  112. return p.rw.node.ID()
  113. }
  114. // Node returns the peer's node descriptor.
  115. func (p *Peer) Node() *enode.Node {
  116. return p.rw.node
  117. }
  118. // Name returns an abbreviated form of the name
  119. func (p *Peer) Name() string {
  120. s := p.rw.name
  121. if len(s) > 20 {
  122. return s[:20] + "..."
  123. }
  124. return s
  125. }
  126. // Fullname returns the node name that the remote node advertised.
  127. func (p *Peer) Fullname() string {
  128. return p.rw.name
  129. }
  130. // Caps returns the capabilities (supported subprotocols) of the remote peer.
  131. func (p *Peer) Caps() []Cap {
  132. // TODO: maybe return copy
  133. return p.rw.caps
  134. }
  135. // SupportsCap returns true if the peer supports the given protocol/version
  136. func (p *Peer) SupportsCap(protocol string, version uint) bool {
  137. for _, cap := range p.rw.caps {
  138. if cap.Name == protocol {
  139. return version <= cap.Version
  140. }
  141. }
  142. return false
  143. }
  144. // RemoteAddr returns the remote address of the network connection.
  145. func (p *Peer) RemoteAddr() net.Addr {
  146. return p.rw.fd.RemoteAddr()
  147. }
  148. // LocalAddr returns the local address of the network connection.
  149. func (p *Peer) LocalAddr() net.Addr {
  150. return p.rw.fd.LocalAddr()
  151. }
  152. // Disconnect terminates the peer connection with the given reason.
  153. // It returns immediately and does not wait until the connection is closed.
  154. func (p *Peer) Disconnect(reason DiscReason) {
  155. select {
  156. case p.disc <- reason:
  157. case <-p.closed:
  158. }
  159. }
  160. // String implements fmt.Stringer.
  161. func (p *Peer) String() string {
  162. id := p.ID()
  163. return fmt.Sprintf("Peer %x %v", id[:8], p.RemoteAddr())
  164. }
  165. // Inbound returns true if the peer is an inbound connection
  166. func (p *Peer) Inbound() bool {
  167. return p.rw.is(inboundConn)
  168. }
  169. func newPeer(log log.Logger, conn *conn, protocols []Protocol) *Peer {
  170. protomap := matchProtocols(protocols, conn.caps, conn)
  171. p := &Peer{
  172. rw: conn,
  173. running: protomap,
  174. created: mclock.Now(),
  175. disc: make(chan DiscReason),
  176. protoErr: make(chan error, len(protomap)+1), // protocols + pingLoop
  177. closed: make(chan struct{}),
  178. log: log.New("id", conn.node.ID(), "conn", conn.flags),
  179. }
  180. return p
  181. }
  182. func (p *Peer) Log() log.Logger {
  183. return p.log
  184. }
  185. func (p *Peer) run() (remoteRequested bool, err error) {
  186. var (
  187. writeStart = make(chan struct{}, 1)
  188. writeErr = make(chan error, 1)
  189. readErr = make(chan error, 1)
  190. reason DiscReason // sent to the peer
  191. )
  192. p.wg.Add(2)
  193. go p.readLoop(readErr)
  194. go p.pingLoop()
  195. // Start all protocol handlers.
  196. writeStart <- struct{}{}
  197. p.startProtocols(writeStart, writeErr)
  198. // Wait for an error or disconnect.
  199. loop:
  200. for {
  201. select {
  202. case err = <-writeErr:
  203. // A write finished. Allow the next write to start if
  204. // there was no error.
  205. if err != nil {
  206. reason = DiscNetworkError
  207. break loop
  208. }
  209. writeStart <- struct{}{}
  210. case err = <-readErr:
  211. if r, ok := err.(DiscReason); ok {
  212. remoteRequested = true
  213. reason = r
  214. } else {
  215. reason = DiscNetworkError
  216. }
  217. break loop
  218. case err = <-p.protoErr:
  219. reason = discReasonForError(err)
  220. break loop
  221. case err = <-p.disc:
  222. reason = discReasonForError(err)
  223. break loop
  224. }
  225. }
  226. close(p.closed)
  227. p.rw.close(reason)
  228. p.wg.Wait()
  229. return remoteRequested, err
  230. }
  231. func (p *Peer) pingLoop() {
  232. ping := time.NewTimer(pingInterval)
  233. defer p.wg.Done()
  234. defer ping.Stop()
  235. for {
  236. select {
  237. case <-ping.C:
  238. if err := SendItems(p.rw, pingMsg); err != nil {
  239. p.protoErr <- err
  240. return
  241. }
  242. ping.Reset(pingInterval)
  243. case <-p.closed:
  244. return
  245. }
  246. }
  247. }
  248. func (p *Peer) readLoop(errc chan<- error) {
  249. defer p.wg.Done()
  250. for {
  251. msg, err := p.rw.ReadMsg()
  252. if err != nil {
  253. errc <- err
  254. return
  255. }
  256. msg.ReceivedAt = time.Now()
  257. if err = p.handle(msg); err != nil {
  258. errc <- err
  259. return
  260. }
  261. }
  262. }
  263. func (p *Peer) handle(msg Msg) error {
  264. switch {
  265. case msg.Code == pingMsg:
  266. msg.Discard()
  267. go SendItems(p.rw, pongMsg)
  268. case msg.Code == discMsg:
  269. var reason [1]DiscReason
  270. // This is the last message. We don't need to discard or
  271. // check errors because, the connection will be closed after it.
  272. rlp.Decode(msg.Payload, &reason)
  273. return reason[0]
  274. case msg.Code < baseProtocolLength:
  275. // ignore other base protocol messages
  276. return msg.Discard()
  277. default:
  278. // it's a subprotocol message
  279. proto, err := p.getProto(msg.Code)
  280. if err != nil {
  281. return fmt.Errorf("msg code out of range: %v", msg.Code)
  282. }
  283. if metrics.Enabled {
  284. m := fmt.Sprintf("%s/%s/%d/%#02x", ingressMeterName, proto.Name, proto.Version, msg.Code-proto.offset)
  285. metrics.GetOrRegisterMeter(m, nil).Mark(int64(msg.meterSize))
  286. metrics.GetOrRegisterMeter(m+"/packets", nil).Mark(1)
  287. }
  288. select {
  289. case proto.in <- msg:
  290. return nil
  291. case <-p.closed:
  292. return io.EOF
  293. }
  294. }
  295. return nil
  296. }
  297. func countMatchingProtocols(protocols []Protocol, caps []Cap) int {
  298. n := 0
  299. for _, cap := range caps {
  300. for _, proto := range protocols {
  301. if proto.Name == cap.Name && proto.Version == cap.Version {
  302. n++
  303. }
  304. }
  305. }
  306. return n
  307. }
  308. // matchProtocols creates structures for matching named subprotocols.
  309. func matchProtocols(protocols []Protocol, caps []Cap, rw MsgReadWriter) map[string]*protoRW {
  310. sort.Sort(capsByNameAndVersion(caps))
  311. offset := baseProtocolLength
  312. result := make(map[string]*protoRW)
  313. outer:
  314. for _, cap := range caps {
  315. for _, proto := range protocols {
  316. if proto.Name == cap.Name && proto.Version == cap.Version {
  317. // If an old protocol version matched, revert it
  318. if old := result[cap.Name]; old != nil {
  319. offset -= old.Length
  320. }
  321. // Assign the new match
  322. result[cap.Name] = &protoRW{Protocol: proto, offset: offset, in: make(chan Msg), w: rw}
  323. offset += proto.Length
  324. continue outer
  325. }
  326. }
  327. }
  328. return result
  329. }
  330. func (p *Peer) startProtocols(writeStart <-chan struct{}, writeErr chan<- error) {
  331. p.wg.Add(len(p.running))
  332. for _, proto := range p.running {
  333. proto := proto
  334. proto.closed = p.closed
  335. proto.wstart = writeStart
  336. proto.werr = writeErr
  337. var rw MsgReadWriter = proto
  338. if p.events != nil {
  339. rw = newMsgEventer(rw, p.events, p.ID(), proto.Name, p.Info().Network.RemoteAddress, p.Info().Network.LocalAddress)
  340. }
  341. p.log.Trace(fmt.Sprintf("Starting protocol %s/%d", proto.Name, proto.Version))
  342. go func() {
  343. defer p.wg.Done()
  344. err := proto.Run(p, rw)
  345. if err == nil {
  346. p.log.Trace(fmt.Sprintf("Protocol %s/%d returned", proto.Name, proto.Version))
  347. err = errProtocolReturned
  348. } else if err != io.EOF {
  349. p.log.Trace(fmt.Sprintf("Protocol %s/%d failed", proto.Name, proto.Version), "err", err)
  350. }
  351. p.protoErr <- err
  352. }()
  353. }
  354. }
  355. // getProto finds the protocol responsible for handling
  356. // the given message code.
  357. func (p *Peer) getProto(code uint64) (*protoRW, error) {
  358. for _, proto := range p.running {
  359. if code >= proto.offset && code < proto.offset+proto.Length {
  360. return proto, nil
  361. }
  362. }
  363. return nil, newPeerError(errInvalidMsgCode, "%d", code)
  364. }
  365. type protoRW struct {
  366. Protocol
  367. in chan Msg // receives read messages
  368. closed <-chan struct{} // receives when peer is shutting down
  369. wstart <-chan struct{} // receives when write may start
  370. werr chan<- error // for write results
  371. offset uint64
  372. w MsgWriter
  373. }
  374. func (rw *protoRW) WriteMsg(msg Msg) (err error) {
  375. if msg.Code >= rw.Length {
  376. return newPeerError(errInvalidMsgCode, "not handled")
  377. }
  378. msg.meterCap = rw.cap()
  379. msg.meterCode = msg.Code
  380. msg.Code += rw.offset
  381. select {
  382. case <-rw.wstart:
  383. err = rw.w.WriteMsg(msg)
  384. // Report write status back to Peer.run. It will initiate
  385. // shutdown if the error is non-nil and unblock the next write
  386. // otherwise. The calling protocol code should exit for errors
  387. // as well but we don't want to rely on that.
  388. rw.werr <- err
  389. case <-rw.closed:
  390. err = ErrShuttingDown
  391. }
  392. return err
  393. }
  394. func (rw *protoRW) ReadMsg() (Msg, error) {
  395. select {
  396. case msg := <-rw.in:
  397. msg.Code -= rw.offset
  398. return msg, nil
  399. case <-rw.closed:
  400. return Msg{}, io.EOF
  401. }
  402. }
  403. // PeerInfo represents a short summary of the information known about a connected
  404. // peer. Sub-protocol independent fields are contained and initialized here, with
  405. // protocol specifics delegated to all connected sub-protocols.
  406. type PeerInfo struct {
  407. ENR string `json:"enr,omitempty"` // Ethereum Node Record
  408. Enode string `json:"enode"` // Node URL
  409. ID string `json:"id"` // Unique node identifier
  410. Name string `json:"name"` // Name of the node, including client type, version, OS, custom data
  411. Caps []string `json:"caps"` // Protocols advertised by this peer
  412. Network struct {
  413. LocalAddress string `json:"localAddress"` // Local endpoint of the TCP data connection
  414. RemoteAddress string `json:"remoteAddress"` // Remote endpoint of the TCP data connection
  415. Inbound bool `json:"inbound"`
  416. Trusted bool `json:"trusted"`
  417. Static bool `json:"static"`
  418. } `json:"network"`
  419. Protocols map[string]interface{} `json:"protocols"` // Sub-protocol specific metadata fields
  420. }
  421. // Info gathers and returns a collection of metadata known about a peer.
  422. func (p *Peer) Info() *PeerInfo {
  423. // Gather the protocol capabilities
  424. var caps []string
  425. for _, cap := range p.Caps() {
  426. caps = append(caps, cap.String())
  427. }
  428. // Assemble the generic peer metadata
  429. info := &PeerInfo{
  430. Enode: p.Node().URLv4(),
  431. ID: p.ID().String(),
  432. Name: p.Fullname(),
  433. Caps: caps,
  434. Protocols: make(map[string]interface{}),
  435. }
  436. if p.Node().Seq() > 0 {
  437. info.ENR = p.Node().String()
  438. }
  439. info.Network.LocalAddress = p.LocalAddr().String()
  440. info.Network.RemoteAddress = p.RemoteAddr().String()
  441. info.Network.Inbound = p.rw.is(inboundConn)
  442. info.Network.Trusted = p.rw.is(trustedConn)
  443. info.Network.Static = p.rw.is(staticDialedConn)
  444. // Gather all the running protocol infos
  445. for _, proto := range p.running {
  446. protoInfo := interface{}("unknown")
  447. if query := proto.Protocol.PeerInfo; query != nil {
  448. if metadata := query(p.ID()); metadata != nil {
  449. protoInfo = metadata
  450. } else {
  451. protoInfo = "handshake"
  452. }
  453. }
  454. info.Protocols[proto.Name] = protoInfo
  455. }
  456. return info
  457. }