message.go 8.9 KB

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