github.com/cheng762/platon-go@v1.8.17-0.20190529111256-7deff2d7be26/p2p/protocols/protocol.go (about)

     1  // Copyright 2017 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  /*
    18  Package protocols is an extension to p2p. It offers a user friendly simple way to define
    19  devp2p subprotocols by abstracting away code standardly shared by protocols.
    20  
    21  * automate assigments of code indexes to messages
    22  * automate RLP decoding/encoding based on reflecting
    23  * provide the forever loop to read incoming messages
    24  * standardise error handling related to communication
    25  * standardised	handshake negotiation
    26  * TODO: automatic generation of wire protocol specification for peers
    27  
    28  */
    29  package protocols
    30  
    31  import (
    32  	"bufio"
    33  	"bytes"
    34  	"context"
    35  	"fmt"
    36  	"io"
    37  	"reflect"
    38  	"sync"
    39  	"time"
    40  
    41  	"github.com/PlatONnetwork/PlatON-Go/log"
    42  	"github.com/PlatONnetwork/PlatON-Go/metrics"
    43  	"github.com/PlatONnetwork/PlatON-Go/p2p"
    44  	"github.com/PlatONnetwork/PlatON-Go/rlp"
    45  	"github.com/PlatONnetwork/PlatON-Go/swarm/spancontext"
    46  	"github.com/PlatONnetwork/PlatON-Go/swarm/tracing"
    47  	opentracing "github.com/opentracing/opentracing-go"
    48  )
    49  
    50  // error codes used by this  protocol scheme
    51  const (
    52  	ErrMsgTooLong = iota
    53  	ErrDecode
    54  	ErrWrite
    55  	ErrInvalidMsgCode
    56  	ErrInvalidMsgType
    57  	ErrHandshake
    58  	ErrNoHandler
    59  	ErrHandler
    60  )
    61  
    62  // error description strings associated with the codes
    63  var errorToString = map[int]string{
    64  	ErrMsgTooLong:     "Message too long",
    65  	ErrDecode:         "Invalid message (RLP error)",
    66  	ErrWrite:          "Error sending message",
    67  	ErrInvalidMsgCode: "Invalid message code",
    68  	ErrInvalidMsgType: "Invalid message type",
    69  	ErrHandshake:      "Handshake error",
    70  	ErrNoHandler:      "No handler registered error",
    71  	ErrHandler:        "Message handler error",
    72  }
    73  
    74  /*
    75  Error implements the standard go error interface.
    76  Use:
    77  
    78    errorf(code, format, params ...interface{})
    79  
    80  Prints as:
    81  
    82   <description>: <details>
    83  
    84  where description is given by code in errorToString
    85  and details is fmt.Sprintf(format, params...)
    86  
    87  exported field Code can be checked
    88  */
    89  type Error struct {
    90  	Code    int
    91  	message string
    92  	format  string
    93  	params  []interface{}
    94  }
    95  
    96  func (e Error) Error() (message string) {
    97  	if len(e.message) == 0 {
    98  		name, ok := errorToString[e.Code]
    99  		if !ok {
   100  			panic("invalid message code")
   101  		}
   102  		e.message = name
   103  		if e.format != "" {
   104  			e.message += ": " + fmt.Sprintf(e.format, e.params...)
   105  		}
   106  	}
   107  	return e.message
   108  }
   109  
   110  func errorf(code int, format string, params ...interface{}) *Error {
   111  	return &Error{
   112  		Code:   code,
   113  		format: format,
   114  		params: params,
   115  	}
   116  }
   117  
   118  // WrappedMsg is used to propagate marshalled context alongside message payloads
   119  type WrappedMsg struct {
   120  	Context []byte
   121  	Size    uint32
   122  	Payload []byte
   123  }
   124  
   125  // Spec is a protocol specification including its name and version as well as
   126  // the types of messages which are exchanged
   127  type Spec struct {
   128  	// Name is the name of the protocol, often a three-letter word
   129  	Name string
   130  
   131  	// Version is the version number of the protocol
   132  	Version uint
   133  
   134  	// MaxMsgSize is the maximum accepted length of the message payload
   135  	MaxMsgSize uint32
   136  
   137  	// Messages is a list of message data types which this protocol uses, with
   138  	// each message type being sent with its array index as the code (so
   139  	// [&foo{}, &bar{}, &baz{}] would send foo, bar and baz with codes
   140  	// 0, 1 and 2 respectively)
   141  	// each message must have a single unique data type
   142  	Messages []interface{}
   143  
   144  	initOnce sync.Once
   145  	codes    map[reflect.Type]uint64
   146  	types    map[uint64]reflect.Type
   147  }
   148  
   149  func (s *Spec) init() {
   150  	s.initOnce.Do(func() {
   151  		s.codes = make(map[reflect.Type]uint64, len(s.Messages))
   152  		s.types = make(map[uint64]reflect.Type, len(s.Messages))
   153  		for i, msg := range s.Messages {
   154  			code := uint64(i)
   155  			typ := reflect.TypeOf(msg)
   156  			if typ.Kind() == reflect.Ptr {
   157  				typ = typ.Elem()
   158  			}
   159  			s.codes[typ] = code
   160  			s.types[code] = typ
   161  		}
   162  	})
   163  }
   164  
   165  // Length returns the number of message types in the protocol
   166  func (s *Spec) Length() uint64 {
   167  	return uint64(len(s.Messages))
   168  }
   169  
   170  // GetCode returns the message code of a type, and boolean second argument is
   171  // false if the message type is not found
   172  func (s *Spec) GetCode(msg interface{}) (uint64, bool) {
   173  	s.init()
   174  	typ := reflect.TypeOf(msg)
   175  	if typ.Kind() == reflect.Ptr {
   176  		typ = typ.Elem()
   177  	}
   178  	code, ok := s.codes[typ]
   179  	return code, ok
   180  }
   181  
   182  // NewMsg construct a new message type given the code
   183  func (s *Spec) NewMsg(code uint64) (interface{}, bool) {
   184  	s.init()
   185  	typ, ok := s.types[code]
   186  	if !ok {
   187  		return nil, false
   188  	}
   189  	return reflect.New(typ).Interface(), true
   190  }
   191  
   192  // Peer represents a remote peer or protocol instance that is running on a peer connection with
   193  // a remote peer
   194  type Peer struct {
   195  	*p2p.Peer                   // the p2p.Peer object representing the remote
   196  	rw        p2p.MsgReadWriter // p2p.MsgReadWriter to send messages to and read messages from
   197  	spec      *Spec
   198  }
   199  
   200  // NewPeer constructs a new peer
   201  // this constructor is called by the p2p.Protocol#Run function
   202  // the first two arguments are the arguments passed to p2p.Protocol.Run function
   203  // the third argument is the Spec describing the protocol
   204  func NewPeer(p *p2p.Peer, rw p2p.MsgReadWriter, spec *Spec) *Peer {
   205  	return &Peer{
   206  		Peer: p,
   207  		rw:   rw,
   208  		spec: spec,
   209  	}
   210  }
   211  
   212  // Run starts the forever loop that handles incoming messages
   213  // called within the p2p.Protocol#Run function
   214  // the handler argument is a function which is called for each message received
   215  // from the remote peer, a returned error causes the loop to exit
   216  // resulting in disconnection
   217  func (p *Peer) Run(handler func(ctx context.Context, msg interface{}) error) error {
   218  	for {
   219  		if err := p.handleIncoming(handler); err != nil {
   220  			if err != io.EOF {
   221  				metrics.GetOrRegisterCounter("peer.handleincoming.error", nil).Inc(1)
   222  				log.Error("peer.handleIncoming", "err", err)
   223  			}
   224  
   225  			return err
   226  		}
   227  	}
   228  }
   229  
   230  // Drop disconnects a peer.
   231  // TODO: may need to implement protocol drop only? don't want to kick off the peer
   232  // if they are useful for other protocols
   233  func (p *Peer) Drop(err error) {
   234  	p.Disconnect(p2p.DiscSubprotocolError)
   235  }
   236  
   237  // Send takes a message, encodes it in RLP, finds the right message code and sends the
   238  // message off to the peer
   239  // this low level call will be wrapped by libraries providing routed or broadcast sends
   240  // but often just used to forward and push messages to directly connected peers
   241  func (p *Peer) Send(ctx context.Context, msg interface{}) error {
   242  	defer metrics.GetOrRegisterResettingTimer("peer.send_t", nil).UpdateSince(time.Now())
   243  	metrics.GetOrRegisterCounter("peer.send", nil).Inc(1)
   244  
   245  	var b bytes.Buffer
   246  	if tracing.Enabled {
   247  		writer := bufio.NewWriter(&b)
   248  
   249  		tracer := opentracing.GlobalTracer()
   250  
   251  		sctx := spancontext.FromContext(ctx)
   252  
   253  		if sctx != nil {
   254  			err := tracer.Inject(
   255  				sctx,
   256  				opentracing.Binary,
   257  				writer)
   258  			if err != nil {
   259  				return err
   260  			}
   261  		}
   262  
   263  		writer.Flush()
   264  	}
   265  
   266  	r, err := rlp.EncodeToBytes(msg)
   267  	if err != nil {
   268  		return err
   269  	}
   270  
   271  	wmsg := WrappedMsg{
   272  		Context: b.Bytes(),
   273  		Size:    uint32(len(r)),
   274  		Payload: r,
   275  	}
   276  
   277  	code, found := p.spec.GetCode(msg)
   278  	if !found {
   279  		return errorf(ErrInvalidMsgType, "%v", code)
   280  	}
   281  	return p2p.Send(p.rw, code, wmsg)
   282  }
   283  
   284  // handleIncoming(code)
   285  // is called each cycle of the main forever loop that dispatches incoming messages
   286  // if this returns an error the loop returns and the peer is disconnected with the error
   287  // this generic handler
   288  // * checks message size,
   289  // * checks for out-of-range message codes,
   290  // * handles decoding with reflection,
   291  // * call handlers as callbacks
   292  func (p *Peer) handleIncoming(handle func(ctx context.Context, msg interface{}) error) error {
   293  	msg, err := p.rw.ReadMsg()
   294  	if err != nil {
   295  		return err
   296  	}
   297  	// make sure that the payload has been fully consumed
   298  	defer msg.Discard()
   299  
   300  	if msg.Size > p.spec.MaxMsgSize {
   301  		return errorf(ErrMsgTooLong, "%v > %v", msg.Size, p.spec.MaxMsgSize)
   302  	}
   303  
   304  	// unmarshal wrapped msg, which might contain context
   305  	var wmsg WrappedMsg
   306  	err = msg.Decode(&wmsg)
   307  	if err != nil {
   308  		log.Error(err.Error())
   309  		return err
   310  	}
   311  
   312  	ctx := context.Background()
   313  
   314  	// if tracing is enabled and the context coming within the request is
   315  	// not empty, try to unmarshal it
   316  	if tracing.Enabled && len(wmsg.Context) > 0 {
   317  		var sctx opentracing.SpanContext
   318  
   319  		tracer := opentracing.GlobalTracer()
   320  		sctx, err = tracer.Extract(
   321  			opentracing.Binary,
   322  			bytes.NewReader(wmsg.Context))
   323  		if err != nil {
   324  			log.Error(err.Error())
   325  			return err
   326  		}
   327  
   328  		ctx = spancontext.WithContext(ctx, sctx)
   329  	}
   330  
   331  	val, ok := p.spec.NewMsg(msg.Code)
   332  	if !ok {
   333  		return errorf(ErrInvalidMsgCode, "%v", msg.Code)
   334  	}
   335  	if err := rlp.DecodeBytes(wmsg.Payload, val); err != nil {
   336  		return errorf(ErrDecode, "<= %v: %v", msg, err)
   337  	}
   338  
   339  	// call the registered handler callbacks
   340  	// a registered callback take the decoded message as argument as an interface
   341  	// which the handler is supposed to cast to the appropriate type
   342  	// it is entirely safe not to check the cast in the handler since the handler is
   343  	// chosen based on the proper type in the first place
   344  	if err := handle(ctx, val); err != nil {
   345  		return errorf(ErrHandler, "(msg code %v): %v", msg.Code, err)
   346  	}
   347  	return nil
   348  }
   349  
   350  // Handshake negotiates a handshake on the peer connection
   351  // * arguments
   352  //   * context
   353  //   * the local handshake to be sent to the remote peer
   354  //   * funcion to be called on the remote handshake (can be nil)
   355  // * expects a remote handshake back of the same type
   356  // * the dialing peer needs to send the handshake first and then waits for remote
   357  // * the listening peer waits for the remote handshake and then sends it
   358  // returns the remote handshake and an error
   359  func (p *Peer) Handshake(ctx context.Context, hs interface{}, verify func(interface{}) error) (rhs interface{}, err error) {
   360  	if _, ok := p.spec.GetCode(hs); !ok {
   361  		return nil, errorf(ErrHandshake, "unknown handshake message type: %T", hs)
   362  	}
   363  	errc := make(chan error, 2)
   364  	handle := func(ctx context.Context, msg interface{}) error {
   365  		rhs = msg
   366  		if verify != nil {
   367  			return verify(rhs)
   368  		}
   369  		return nil
   370  	}
   371  	send := func() { errc <- p.Send(ctx, hs) }
   372  	receive := func() { errc <- p.handleIncoming(handle) }
   373  
   374  	go func() {
   375  		if p.Inbound() {
   376  			receive()
   377  			send()
   378  		} else {
   379  			send()
   380  			receive()
   381  		}
   382  	}()
   383  
   384  	for i := 0; i < 2; i++ {
   385  		select {
   386  		case err = <-errc:
   387  		case <-ctx.Done():
   388  			err = ctx.Err()
   389  		}
   390  		if err != nil {
   391  			return nil, errorf(ErrHandshake, err.Error())
   392  		}
   393  	}
   394  	return rhs, nil
   395  }