github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/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/ethereumproject/go-ethereum/rlp"
    29  )
    30  
    31  // Msg defines the structure of a p2p message.
    32  //
    33  // Note that a Msg can only be sent once since the Payload reader is
    34  // consumed during sending. It is not possible to create a Msg and
    35  // send it any number of times. If you want to reuse an encoded
    36  // structure, encode the payload into a byte array and create a
    37  // separate Msg with a bytes.Reader as Payload for each send.
    38  type Msg struct {
    39  	Code       uint64
    40  	Size       uint32 // size of the paylod
    41  	Payload    io.Reader
    42  	ReceivedAt time.Time
    43  }
    44  
    45  // Decode parses the RLP content of a message into
    46  // the given value, which must be a pointer.
    47  //
    48  // For the decoding rules, please see package rlp.
    49  func (msg Msg) Decode(val interface{}) error {
    50  	s := rlp.NewStream(msg.Payload, uint64(msg.Size))
    51  	if err := s.Decode(val); err != nil {
    52  		return newPeerError(errInvalidMsg, "(code %x) (size %d) %v", msg.Code, msg.Size, err)
    53  	}
    54  	return nil
    55  }
    56  
    57  func (msg Msg) String() string {
    58  	return fmt.Sprintf("msg #%v (%v bytes)", msg.Code, msg.Size)
    59  }
    60  
    61  // Discard reads any remaining payload data into a black hole.
    62  func (msg Msg) Discard() error {
    63  	_, err := io.Copy(ioutil.Discard, msg.Payload)
    64  	return err
    65  }
    66  
    67  type MsgReader interface {
    68  	ReadMsg() (Msg, error)
    69  }
    70  
    71  type MsgWriter interface {
    72  	// WriteMsg sends a message. It will block until the message's
    73  	// Payload has been consumed by the other end.
    74  	//
    75  	// Note that messages can be sent only once because their
    76  	// payload reader is drained.
    77  	WriteMsg(Msg) error
    78  }
    79  
    80  // MsgReadWriter provides reading and writing of encoded messages.
    81  // Implementations should ensure that ReadMsg and WriteMsg can be
    82  // called simultaneously from multiple goroutines.
    83  type MsgReadWriter interface {
    84  	MsgReader
    85  	MsgWriter
    86  }
    87  
    88  // Send writes an RLP-encoded message with the given code.
    89  // data should encode as an RLP list. It returns the size of the encoded data for logging purposes.
    90  func Send(w MsgWriter, msgcode uint64, data interface{}) (int, error) {
    91  	size, r, err := rlp.EncodeToReader(data)
    92  	if err != nil {
    93  		return size, err
    94  	}
    95  	return size, w.WriteMsg(Msg{Code: msgcode, Size: uint32(size), Payload: r})
    96  }
    97  
    98  // SendItems writes an RLP with the given code and data elements.
    99  // For a call such as:
   100  //
   101  //    SendItems(w, code, e1, e2, e3)
   102  //
   103  // the message payload will be an RLP list containing the items:
   104  //
   105  //    [e1, e2, e3]
   106  //
   107  func SendItems(w MsgWriter, msgcode uint64, elems ...interface{}) (err error) {
   108  	_, err = Send(w, msgcode, elems)
   109  	return
   110  }
   111  
   112  // eofSignal wraps a reader with eof signaling. the eof channel is
   113  // closed when the wrapped reader returns an error or when count bytes
   114  // have been read.
   115  type eofSignal struct {
   116  	wrapped io.Reader
   117  	count   uint32 // number of bytes left
   118  	eof     chan<- struct{}
   119  }
   120  
   121  // note: when using eofSignal to detect whether a message payload
   122  // has been read, Read might not be called for zero sized messages.
   123  func (r *eofSignal) Read(buf []byte) (int, error) {
   124  	if r.count == 0 {
   125  		if r.eof != nil {
   126  			r.eof <- struct{}{}
   127  			r.eof = nil
   128  		}
   129  		return 0, io.EOF
   130  	}
   131  
   132  	max := len(buf)
   133  	if int(r.count) < len(buf) {
   134  		max = int(r.count)
   135  	}
   136  	n, err := r.wrapped.Read(buf[:max])
   137  	r.count -= uint32(n)
   138  	if (err != nil || r.count == 0) && r.eof != nil {
   139  		r.eof <- struct{}{} // tell Peer that msg has been consumed
   140  		r.eof = nil
   141  	}
   142  	return n, err
   143  }
   144  
   145  // MsgPipe creates a message pipe. Reads on one end are matched
   146  // with writes on the other. The pipe is full-duplex, both ends
   147  // implement MsgReadWriter.
   148  func MsgPipe() (*MsgPipeRW, *MsgPipeRW) {
   149  	var (
   150  		c1, c2  = make(chan Msg), make(chan Msg)
   151  		closing = make(chan struct{})
   152  		closed  = new(int32)
   153  		rw1     = &MsgPipeRW{c1, c2, closing, closed}
   154  		rw2     = &MsgPipeRW{c2, c1, closing, closed}
   155  	)
   156  	return rw1, rw2
   157  }
   158  
   159  // ErrPipeClosed is returned from pipe operations after the
   160  // pipe has been closed.
   161  var ErrPipeClosed = errors.New("p2p: read or write on closed message pipe")
   162  
   163  // MsgPipeRW is an endpoint of a MsgReadWriter pipe.
   164  type MsgPipeRW struct {
   165  	w       chan<- Msg
   166  	r       <-chan Msg
   167  	closing chan struct{}
   168  	closed  *int32
   169  }
   170  
   171  // WriteMsg sends a messsage on the pipe.
   172  // It blocks until the receiver has consumed the message payload.
   173  func (p *MsgPipeRW) WriteMsg(msg Msg) error {
   174  	if atomic.LoadInt32(p.closed) == 0 {
   175  		consumed := make(chan struct{}, 1)
   176  		msg.Payload = &eofSignal{msg.Payload, msg.Size, consumed}
   177  		select {
   178  		case p.w <- msg:
   179  			if msg.Size > 0 {
   180  				// wait for payload read or discard
   181  				select {
   182  				case <-consumed:
   183  				case <-p.closing:
   184  				}
   185  			}
   186  			return nil
   187  		case <-p.closing:
   188  		}
   189  	}
   190  	return ErrPipeClosed
   191  }
   192  
   193  // ReadMsg returns a message sent on the other end of the pipe.
   194  func (p *MsgPipeRW) ReadMsg() (Msg, error) {
   195  	if atomic.LoadInt32(p.closed) == 0 {
   196  		select {
   197  		case msg := <-p.r:
   198  			return msg, nil
   199  		case <-p.closing:
   200  		}
   201  	}
   202  	return Msg{}, ErrPipeClosed
   203  }
   204  
   205  // Close unblocks any pending ReadMsg and WriteMsg calls on both ends
   206  // of the pipe. They will return ErrPipeClosed. Close also
   207  // interrupts any reads from a message payload.
   208  func (p *MsgPipeRW) Close() error {
   209  	if atomic.AddInt32(p.closed, 1) != 1 {
   210  		// someone else is already closing
   211  		atomic.StoreInt32(p.closed, 1) // avoid overflow
   212  		return nil
   213  	}
   214  	close(p.closing)
   215  	return nil
   216  }
   217  
   218  // ExpectMsg reads a message from r and verifies that its
   219  // code and encoded RLP content match the provided values.
   220  // If content is nil, the payload is discarded and not verified.
   221  func ExpectMsg(r MsgReader, code uint64, content interface{}) error {
   222  	msg, err := r.ReadMsg()
   223  	if err != nil {
   224  		return err
   225  	}
   226  	if msg.Code != code {
   227  		return fmt.Errorf("message code mismatch: got %d, expected %d", msg.Code, code)
   228  	}
   229  	if content == nil {
   230  		return msg.Discard()
   231  	} else {
   232  		contentEnc, err := rlp.EncodeToBytes(content)
   233  		if err != nil {
   234  			panic("content encode error: " + err.Error())
   235  		}
   236  		if int(msg.Size) != len(contentEnc) {
   237  			return fmt.Errorf("message size mismatch: got %d, want %d", msg.Size, len(contentEnc))
   238  		}
   239  		actualContent, err := ioutil.ReadAll(msg.Payload)
   240  		if err != nil {
   241  			return err
   242  		}
   243  		if !bytes.Equal(actualContent, contentEnc) {
   244  			return fmt.Errorf("message payload mismatch:\ngot:  %x\nwant: %x", actualContent, contentEnc)
   245  		}
   246  	}
   247  	return nil
   248  }