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