peer.go 13 KB

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