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