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