github.com/klaytn/klaytn@v1.12.1/networks/p2p/message.go (about)

     1  // Modifications Copyright 2018 The klaytn Authors
     2  // Copyright 2014 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  // This file is derived from p2p/message.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package p2p
    22  
    23  import (
    24  	"bytes"
    25  	"errors"
    26  	"fmt"
    27  	"io"
    28  	"sync/atomic"
    29  	"time"
    30  
    31  	"github.com/klaytn/klaytn/event"
    32  	"github.com/klaytn/klaytn/networks/p2p/discover"
    33  	"github.com/klaytn/klaytn/rlp"
    34  )
    35  
    36  // Msg defines the structure of a p2p message.
    37  //
    38  // Note that a Msg can only be sent once since the Payload reader is
    39  // consumed during sending. It is not possible to create a Msg and
    40  // send it any number of times. If you want to reuse an encoded
    41  // structure, encode the payload into a byte array and create a
    42  // separate Msg with a bytes.Reader as Payload for each send.
    43  type Msg struct {
    44  	Code       uint64
    45  	Size       uint32 // size of the paylod
    46  	Payload    io.Reader
    47  	ReceivedAt time.Time
    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  type MsgReader interface {
    73  	ReadMsg() (Msg, error)
    74  }
    75  
    76  type MsgWriter interface {
    77  	// WriteMsg sends a message. It will block until the message's
    78  	// Payload has been consumed by the other end.
    79  	//
    80  	// Note that messages can be sent only once because their
    81  	// payload reader is drained.
    82  	WriteMsg(Msg) error
    83  }
    84  
    85  // MsgReadWriter provides reading and writing of encoded messages.
    86  // Implementations should ensure that ReadMsg and WriteMsg can be
    87  // called simultaneously from multiple goroutines.
    88  type MsgReadWriter interface {
    89  	MsgReader
    90  	MsgWriter
    91  }
    92  
    93  // Send writes an RLP-encoded message with the given code.
    94  // data should encode as an RLP list.
    95  func Send(w MsgWriter, msgcode uint64, data interface{}) error {
    96  	size, r, err := rlp.EncodeToReader(data)
    97  	if err != nil {
    98  		return err
    99  	}
   100  	return w.WriteMsg(Msg{Code: msgcode, Size: uint32(size), Payload: r})
   101  }
   102  
   103  // SendItems writes an RLP with the given code and data elements.
   104  // For a call such as:
   105  //
   106  //	SendItems(w, code, e1, e2, e3)
   107  //
   108  // the message payload will be an RLP list containing the items:
   109  //
   110  //	[e1, e2, e3]
   111  func SendItems(w MsgWriter, msgcode uint64, elems ...interface{}) error {
   112  	return Send(w, msgcode, elems)
   113  }
   114  
   115  // eofSignal wraps a reader with eof signaling. the eof channel is
   116  // closed when the wrapped reader returns an error or when count bytes
   117  // have been read.
   118  type eofSignal struct {
   119  	wrapped io.Reader
   120  	count   uint32 // number of bytes left
   121  	eof     chan<- struct{}
   122  }
   123  
   124  // note: when using eofSignal to detect whether a message payload
   125  // has been read, Read might not be called for zero sized messages.
   126  func (r *eofSignal) Read(buf []byte) (int, error) {
   127  	if r.count == 0 {
   128  		if r.eof != nil {
   129  			r.eof <- struct{}{}
   130  			r.eof = nil
   131  		}
   132  		return 0, io.EOF
   133  	}
   134  
   135  	max := len(buf)
   136  	if int(r.count) < len(buf) {
   137  		max = int(r.count)
   138  	}
   139  	n, err := r.wrapped.Read(buf[:max])
   140  	r.count -= uint32(n)
   141  	if (err != nil || r.count == 0) && r.eof != nil {
   142  		r.eof <- struct{}{} // tell Peer that msg has been consumed
   143  		r.eof = nil
   144  	}
   145  	return n, err
   146  }
   147  
   148  // MsgPipe creates a message pipe. Reads on one end are matched
   149  // with writes on the other. The pipe is full-duplex, both ends
   150  // implement MsgReadWriter.
   151  func MsgPipe() (*MsgPipeRW, *MsgPipeRW) {
   152  	var (
   153  		c1, c2  = make(chan Msg), make(chan Msg)
   154  		closing = make(chan struct{})
   155  		closed  = new(int32)
   156  		rw1     = &MsgPipeRW{c1, c2, closing, closed}
   157  		rw2     = &MsgPipeRW{c2, c1, closing, closed}
   158  	)
   159  	return rw1, rw2
   160  }
   161  
   162  // ErrPipeClosed is returned from pipe operations after the
   163  // pipe has been closed.
   164  var ErrPipeClosed = errors.New("p2p: read or write on closed message pipe")
   165  
   166  // MsgPipeRW is an endpoint of a MsgReadWriter pipe.
   167  type MsgPipeRW struct {
   168  	w       chan<- Msg
   169  	r       <-chan Msg
   170  	closing chan struct{}
   171  	closed  *int32
   172  }
   173  
   174  // WriteMsg sends a message on the pipe.
   175  // It blocks until the receiver has consumed the message payload.
   176  func (p *MsgPipeRW) WriteMsg(msg Msg) error {
   177  	if atomic.LoadInt32(p.closed) == 0 {
   178  		consumed := make(chan struct{}, 1)
   179  		msg.Payload = &eofSignal{msg.Payload, msg.Size, consumed}
   180  		select {
   181  		case p.w <- msg:
   182  			if msg.Size > 0 {
   183  				// wait for payload read or discard
   184  				select {
   185  				case <-consumed:
   186  				case <-p.closing:
   187  				}
   188  			}
   189  			return nil
   190  		case <-p.closing:
   191  		}
   192  	}
   193  	return ErrPipeClosed
   194  }
   195  
   196  // ReadMsg returns a message sent on the other end of the pipe.
   197  func (p *MsgPipeRW) ReadMsg() (Msg, error) {
   198  	if atomic.LoadInt32(p.closed) == 0 {
   199  		select {
   200  		case msg := <-p.r:
   201  			return msg, nil
   202  		case <-p.closing:
   203  		}
   204  	}
   205  	return Msg{}, ErrPipeClosed
   206  }
   207  
   208  // Close unblocks any pending ReadMsg and WriteMsg calls on both ends
   209  // of the pipe. They will return ErrPipeClosed. Close also
   210  // interrupts any reads from a message payload.
   211  func (p *MsgPipeRW) Close() error {
   212  	if atomic.AddInt32(p.closed, 1) != 1 {
   213  		// someone else is already closing
   214  		atomic.StoreInt32(p.closed, 1) // avoid overflow
   215  		return nil
   216  	}
   217  	close(p.closing)
   218  	return nil
   219  }
   220  
   221  // ExpectMsg reads a message from r and verifies that its
   222  // code and encoded RLP content match the provided values.
   223  // If content is nil, the payload is discarded and not verified.
   224  func ExpectMsg(r MsgReader, code uint64, content interface{}) error {
   225  	msg, err := r.ReadMsg()
   226  	if err != nil {
   227  		return err
   228  	}
   229  	if msg.Code != code {
   230  		return fmt.Errorf("message code mismatch: got %d, expected %d", msg.Code, code)
   231  	}
   232  	if content == nil {
   233  		return msg.Discard()
   234  	}
   235  	contentEnc, err := rlp.EncodeToBytes(content)
   236  	if err != nil {
   237  		panic("content encode error: " + err.Error())
   238  	}
   239  	if int(msg.Size) != len(contentEnc) {
   240  		return fmt.Errorf("message size mismatch: got %d, want %d", msg.Size, len(contentEnc))
   241  	}
   242  	actualContent, err := io.ReadAll(msg.Payload)
   243  	if err != nil {
   244  		return err
   245  	}
   246  	if !bytes.Equal(actualContent, contentEnc) {
   247  		return fmt.Errorf("message payload mismatch:\ngot:  %x\nwant: %x", actualContent, contentEnc)
   248  	}
   249  	return nil
   250  }
   251  
   252  // msgEventer wraps a MsgReadWriter and sends events whenever a message is sent
   253  // or received
   254  type msgEventer struct {
   255  	MsgReadWriter
   256  
   257  	feed     *event.Feed
   258  	peerID   discover.NodeID
   259  	Protocol string
   260  }
   261  
   262  // newMsgEventer returns a msgEventer which sends message events to the given
   263  // feed
   264  func newMsgEventer(rw MsgReadWriter, feed *event.Feed, peerID discover.NodeID, proto string) *msgEventer {
   265  	return &msgEventer{
   266  		MsgReadWriter: rw,
   267  		feed:          feed,
   268  		peerID:        peerID,
   269  		Protocol:      proto,
   270  	}
   271  }
   272  
   273  // ReadMsg reads a message from the underlying MsgReadWriter and emits a
   274  // "message received" event
   275  func (ev *msgEventer) ReadMsg() (Msg, error) {
   276  	msg, err := ev.MsgReadWriter.ReadMsg()
   277  	if err != nil {
   278  		return msg, err
   279  	}
   280  	ev.feed.Send(&PeerEvent{
   281  		Type:     PeerEventTypeMsgRecv,
   282  		Peer:     ev.peerID,
   283  		Protocol: ev.Protocol,
   284  		MsgCode:  &msg.Code,
   285  		MsgSize:  &msg.Size,
   286  	})
   287  	return msg, nil
   288  }
   289  
   290  // WriteMsg writes a message to the underlying MsgReadWriter and emits a
   291  // "message sent" event
   292  func (ev *msgEventer) WriteMsg(msg Msg) error {
   293  	err := ev.MsgReadWriter.WriteMsg(msg)
   294  	if err != nil {
   295  		return err
   296  	}
   297  	ev.feed.Send(&PeerEvent{
   298  		Type:     PeerEventTypeMsgSend,
   299  		Peer:     ev.peerID,
   300  		Protocol: ev.Protocol,
   301  		MsgCode:  &msg.Code,
   302  		MsgSize:  &msg.Size,
   303  	})
   304  	return nil
   305  }
   306  
   307  // Close closes the underlying MsgReadWriter if it implements the io.Closer
   308  // interface
   309  func (ev *msgEventer) Close() error {
   310  	if v, ok := ev.MsgReadWriter.(io.Closer); ok {
   311  		return v.Close()
   312  	}
   313  	return nil
   314  }