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