github.com/core-coin/go-core/v2@v2.1.9/p2p/message.go (about)

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