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