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