peer.go 12 KB

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