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