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