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