message.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. "bytes"
  19. "errors"
  20. "fmt"
  21. "io"
  22. "sync/atomic"
  23. "time"
  24. "github.com/ethereum/go-ethereum/event"
  25. "github.com/ethereum/go-ethereum/p2p/enode"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. )
  28. // Msg defines the structure of a p2p message.
  29. //
  30. // Note that a Msg can only be sent once since the Payload reader is
  31. // consumed during sending. It is not possible to create a Msg and
  32. // send it any number of times. If you want to reuse an encoded
  33. // structure, encode the payload into a byte array and create a
  34. // separate Msg with a bytes.Reader as Payload for each send.
  35. type Msg struct {
  36. Code uint64
  37. Size uint32 // Size of the raw payload
  38. Payload io.Reader
  39. ReceivedAt time.Time
  40. meterCap Cap // Protocol name and version for egress metering
  41. meterCode uint64 // Message within protocol for egress metering
  42. meterSize uint32 // Compressed message size for ingress metering
  43. }
  44. // Decode parses the RLP content of a message into
  45. // the given value, which must be a pointer.
  46. //
  47. // For the decoding rules, please see package rlp.
  48. func (msg Msg) Decode(val interface{}) error {
  49. s := rlp.NewStream(msg.Payload, uint64(msg.Size))
  50. if err := s.Decode(val); err != nil {
  51. return newPeerError(errInvalidMsg, "(code %x) (size %d) %v", msg.Code, msg.Size, err)
  52. }
  53. return nil
  54. }
  55. func (msg Msg) String() string {
  56. return fmt.Sprintf("msg #%v (%v bytes)", msg.Code, msg.Size)
  57. }
  58. // Discard reads any remaining payload data into a black hole.
  59. func (msg Msg) Discard() error {
  60. _, err := io.Copy(io.Discard, msg.Payload)
  61. return err
  62. }
  63. func (msg Msg) Time() time.Time {
  64. return msg.ReceivedAt
  65. }
  66. type MsgReader interface {
  67. ReadMsg() (Msg, error)
  68. }
  69. type MsgWriter interface {
  70. // WriteMsg sends a message. It will block until the message's
  71. // Payload has been consumed by the other end.
  72. //
  73. // Note that messages can be sent only once because their
  74. // payload reader is drained.
  75. WriteMsg(Msg) error
  76. }
  77. // MsgReadWriter provides reading and writing of encoded messages.
  78. // Implementations should ensure that ReadMsg and WriteMsg can be
  79. // called simultaneously from multiple goroutines.
  80. type MsgReadWriter interface {
  81. MsgReader
  82. MsgWriter
  83. }
  84. // Send writes an RLP-encoded message with the given code.
  85. // data should encode as an RLP list.
  86. func Send(w MsgWriter, msgcode uint64, data interface{}) error {
  87. size, r, err := rlp.EncodeToReader(data)
  88. if err != nil {
  89. return err
  90. }
  91. return w.WriteMsg(Msg{Code: msgcode, Size: uint32(size), Payload: r})
  92. }
  93. // SendItems writes an RLP with the given code and data elements.
  94. // For a call such as:
  95. //
  96. // SendItems(w, code, e1, e2, e3)
  97. //
  98. // the message payload will be an RLP list containing the items:
  99. //
  100. // [e1, e2, e3]
  101. //
  102. func SendItems(w MsgWriter, msgcode uint64, elems ...interface{}) error {
  103. return Send(w, msgcode, elems)
  104. }
  105. // eofSignal wraps a reader with eof signaling. the eof channel is
  106. // closed when the wrapped reader returns an error or when count bytes
  107. // have been read.
  108. type eofSignal struct {
  109. wrapped io.Reader
  110. count uint32 // number of bytes left
  111. eof chan<- struct{}
  112. }
  113. // note: when using eofSignal to detect whether a message payload
  114. // has been read, Read might not be called for zero sized messages.
  115. func (r *eofSignal) Read(buf []byte) (int, error) {
  116. if r.count == 0 {
  117. if r.eof != nil {
  118. r.eof <- struct{}{}
  119. r.eof = nil
  120. }
  121. return 0, io.EOF
  122. }
  123. max := len(buf)
  124. if int(r.count) < len(buf) {
  125. max = int(r.count)
  126. }
  127. n, err := r.wrapped.Read(buf[:max])
  128. r.count -= uint32(n)
  129. if (err != nil || r.count == 0) && r.eof != nil {
  130. r.eof <- struct{}{} // tell Peer that msg has been consumed
  131. r.eof = nil
  132. }
  133. return n, err
  134. }
  135. // MsgPipe creates a message pipe. Reads on one end are matched
  136. // with writes on the other. The pipe is full-duplex, both ends
  137. // implement MsgReadWriter.
  138. func MsgPipe() (*MsgPipeRW, *MsgPipeRW) {
  139. var (
  140. c1, c2 = make(chan Msg), make(chan Msg)
  141. closing = make(chan struct{})
  142. closed = new(int32)
  143. rw1 = &MsgPipeRW{c1, c2, closing, closed}
  144. rw2 = &MsgPipeRW{c2, c1, closing, closed}
  145. )
  146. return rw1, rw2
  147. }
  148. // ErrPipeClosed is returned from pipe operations after the
  149. // pipe has been closed.
  150. var ErrPipeClosed = errors.New("p2p: read or write on closed message pipe")
  151. // MsgPipeRW is an endpoint of a MsgReadWriter pipe.
  152. type MsgPipeRW struct {
  153. w chan<- Msg
  154. r <-chan Msg
  155. closing chan struct{}
  156. closed *int32
  157. }
  158. // WriteMsg sends a message on the pipe.
  159. // It blocks until the receiver has consumed the message payload.
  160. func (p *MsgPipeRW) WriteMsg(msg Msg) error {
  161. if atomic.LoadInt32(p.closed) == 0 {
  162. consumed := make(chan struct{}, 1)
  163. msg.Payload = &eofSignal{msg.Payload, msg.Size, consumed}
  164. select {
  165. case p.w <- msg:
  166. if msg.Size > 0 {
  167. // wait for payload read or discard
  168. select {
  169. case <-consumed:
  170. case <-p.closing:
  171. }
  172. }
  173. return nil
  174. case <-p.closing:
  175. }
  176. }
  177. return ErrPipeClosed
  178. }
  179. // ReadMsg returns a message sent on the other end of the pipe.
  180. func (p *MsgPipeRW) ReadMsg() (Msg, error) {
  181. if atomic.LoadInt32(p.closed) == 0 {
  182. select {
  183. case msg := <-p.r:
  184. return msg, nil
  185. case <-p.closing:
  186. }
  187. }
  188. return Msg{}, ErrPipeClosed
  189. }
  190. // Close unblocks any pending ReadMsg and WriteMsg calls on both ends
  191. // of the pipe. They will return ErrPipeClosed. Close also
  192. // interrupts any reads from a message payload.
  193. func (p *MsgPipeRW) Close() error {
  194. if atomic.AddInt32(p.closed, 1) != 1 {
  195. // someone else is already closing
  196. atomic.StoreInt32(p.closed, 1) // avoid overflow
  197. return nil
  198. }
  199. close(p.closing)
  200. return nil
  201. }
  202. // ExpectMsg reads a message from r and verifies that its
  203. // code and encoded RLP content match the provided values.
  204. // If content is nil, the payload is discarded and not verified.
  205. func ExpectMsg(r MsgReader, code uint64, content interface{}) error {
  206. msg, err := r.ReadMsg()
  207. if err != nil {
  208. return err
  209. }
  210. if msg.Code != code {
  211. return fmt.Errorf("message code mismatch: got %d, expected %d", msg.Code, code)
  212. }
  213. if content == nil {
  214. return msg.Discard()
  215. }
  216. contentEnc, err := rlp.EncodeToBytes(content)
  217. if err != nil {
  218. panic("content encode error: " + err.Error())
  219. }
  220. if int(msg.Size) != len(contentEnc) {
  221. return fmt.Errorf("message size mismatch: got %d, want %d", msg.Size, len(contentEnc))
  222. }
  223. actualContent, err := io.ReadAll(msg.Payload)
  224. if err != nil {
  225. return err
  226. }
  227. if !bytes.Equal(actualContent, contentEnc) {
  228. return fmt.Errorf("message payload mismatch:\ngot: %x\nwant: %x", actualContent, contentEnc)
  229. }
  230. return nil
  231. }
  232. // msgEventer wraps a MsgReadWriter and sends events whenever a message is sent
  233. // or received
  234. type msgEventer struct {
  235. MsgReadWriter
  236. feed *event.Feed
  237. peerID enode.ID
  238. Protocol string
  239. localAddress string
  240. remoteAddress string
  241. }
  242. // newMsgEventer returns a msgEventer which sends message events to the given
  243. // feed
  244. func newMsgEventer(rw MsgReadWriter, feed *event.Feed, peerID enode.ID, proto, remote, local string) *msgEventer {
  245. return &msgEventer{
  246. MsgReadWriter: rw,
  247. feed: feed,
  248. peerID: peerID,
  249. Protocol: proto,
  250. remoteAddress: remote,
  251. localAddress: local,
  252. }
  253. }
  254. // ReadMsg reads a message from the underlying MsgReadWriter and emits a
  255. // "message received" event
  256. func (ev *msgEventer) ReadMsg() (Msg, error) {
  257. msg, err := ev.MsgReadWriter.ReadMsg()
  258. if err != nil {
  259. return msg, err
  260. }
  261. ev.feed.Send(&PeerEvent{
  262. Type: PeerEventTypeMsgRecv,
  263. Peer: ev.peerID,
  264. Protocol: ev.Protocol,
  265. MsgCode: &msg.Code,
  266. MsgSize: &msg.Size,
  267. LocalAddress: ev.localAddress,
  268. RemoteAddress: ev.remoteAddress,
  269. })
  270. return msg, nil
  271. }
  272. // WriteMsg writes a message to the underlying MsgReadWriter and emits a
  273. // "message sent" event
  274. func (ev *msgEventer) WriteMsg(msg Msg) error {
  275. err := ev.MsgReadWriter.WriteMsg(msg)
  276. if err != nil {
  277. return err
  278. }
  279. ev.feed.Send(&PeerEvent{
  280. Type: PeerEventTypeMsgSend,
  281. Peer: ev.peerID,
  282. Protocol: ev.Protocol,
  283. MsgCode: &msg.Code,
  284. MsgSize: &msg.Size,
  285. LocalAddress: ev.localAddress,
  286. RemoteAddress: ev.remoteAddress,
  287. })
  288. return nil
  289. }
  290. // Close closes the underlying MsgReadWriter if it implements the io.Closer
  291. // interface
  292. func (ev *msgEventer) Close() error {
  293. if v, ok := ev.MsgReadWriter.(io.Closer); ok {
  294. return v.Close()
  295. }
  296. return nil
  297. }