github.com/gregpr07/bsc@v1.1.2/p2p/peer.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  	"errors"
    21  	"fmt"
    22  	"io"
    23  	"net"
    24  	"sort"
    25  	"sync"
    26  	"time"
    27  
    28  	"github.com/gregpr07/bsc/common/gopool"
    29  	"github.com/gregpr07/bsc/common/mclock"
    30  	"github.com/gregpr07/bsc/event"
    31  	"github.com/gregpr07/bsc/log"
    32  	"github.com/gregpr07/bsc/metrics"
    33  	"github.com/gregpr07/bsc/p2p/enode"
    34  	"github.com/gregpr07/bsc/p2p/enr"
    35  	"github.com/gregpr07/bsc/rlp"
    36  )
    37  
    38  var (
    39  	ErrShuttingDown = errors.New("shutting down")
    40  )
    41  
    42  const (
    43  	baseProtocolVersion    = 5
    44  	baseProtocolLength     = uint64(16)
    45  	baseProtocolMaxMsgSize = 2 * 1024
    46  
    47  	snappyProtocolVersion = 5
    48  
    49  	pingInterval = 15 * time.Second
    50  )
    51  
    52  const (
    53  	// devp2p message codes
    54  	handshakeMsg = 0x00
    55  	discMsg      = 0x01
    56  	pingMsg      = 0x02
    57  	pongMsg      = 0x03
    58  )
    59  
    60  // protoHandshake is the RLP structure of the protocol handshake.
    61  type protoHandshake struct {
    62  	Version    uint64
    63  	Name       string
    64  	Caps       []Cap
    65  	ListenPort uint64
    66  	ID         []byte // secp256k1 public key
    67  
    68  	// Ignore additional fields (for forward compatibility).
    69  	Rest []rlp.RawValue `rlp:"tail"`
    70  }
    71  
    72  // PeerEventType is the type of peer events emitted by a p2p.Server
    73  type PeerEventType string
    74  
    75  const (
    76  	// PeerEventTypeAdd is the type of event emitted when a peer is added
    77  	// to a p2p.Server
    78  	PeerEventTypeAdd PeerEventType = "add"
    79  
    80  	// PeerEventTypeDrop is the type of event emitted when a peer is
    81  	// dropped from a p2p.Server
    82  	PeerEventTypeDrop PeerEventType = "drop"
    83  
    84  	// PeerEventTypeMsgSend is the type of event emitted when a
    85  	// message is successfully sent to a peer
    86  	PeerEventTypeMsgSend PeerEventType = "msgsend"
    87  
    88  	// PeerEventTypeMsgRecv is the type of event emitted when a
    89  	// message is received from a peer
    90  	PeerEventTypeMsgRecv PeerEventType = "msgrecv"
    91  )
    92  
    93  // PeerEvent is an event emitted when peers are either added or dropped from
    94  // a p2p.Server or when a message is sent or received on a peer connection
    95  type PeerEvent struct {
    96  	Type          PeerEventType `json:"type"`
    97  	Peer          enode.ID      `json:"peer"`
    98  	Error         string        `json:"error,omitempty"`
    99  	Protocol      string        `json:"protocol,omitempty"`
   100  	MsgCode       *uint64       `json:"msg_code,omitempty"`
   101  	MsgSize       *uint32       `json:"msg_size,omitempty"`
   102  	LocalAddress  string        `json:"local,omitempty"`
   103  	RemoteAddress string        `json:"remote,omitempty"`
   104  }
   105  
   106  // Peer represents a connected remote node.
   107  type Peer struct {
   108  	rw      *conn
   109  	running map[string]*protoRW
   110  	log     log.Logger
   111  	created mclock.AbsTime
   112  
   113  	wg       sync.WaitGroup
   114  	protoErr chan error
   115  	closed   chan struct{}
   116  	disc     chan DiscReason
   117  
   118  	// events receives message send / receive events if set
   119  	events *event.Feed
   120  }
   121  
   122  // NewPeer returns a peer for testing purposes.
   123  func NewPeer(id enode.ID, name string, caps []Cap) *Peer {
   124  	pipe, _ := net.Pipe()
   125  	node := enode.SignNull(new(enr.Record), id)
   126  	conn := &conn{fd: pipe, transport: nil, node: node, caps: caps, name: name}
   127  	peer := newPeer(log.Root(), conn, nil)
   128  	close(peer.closed) // ensures Disconnect doesn't block
   129  	return peer
   130  }
   131  
   132  // ID returns the node's public key.
   133  func (p *Peer) ID() enode.ID {
   134  	return p.rw.node.ID()
   135  }
   136  
   137  // Node returns the peer's node descriptor.
   138  func (p *Peer) Node() *enode.Node {
   139  	return p.rw.node
   140  }
   141  
   142  // Name returns an abbreviated form of the name
   143  func (p *Peer) Name() string {
   144  	s := p.rw.name
   145  	if len(s) > 20 {
   146  		return s[:20] + "..."
   147  	}
   148  	return s
   149  }
   150  
   151  // Fullname returns the node name that the remote node advertised.
   152  func (p *Peer) Fullname() string {
   153  	return p.rw.name
   154  }
   155  
   156  // Caps returns the capabilities (supported subprotocols) of the remote peer.
   157  func (p *Peer) Caps() []Cap {
   158  	// TODO: maybe return copy
   159  	return p.rw.caps
   160  }
   161  
   162  // RunningCap returns true if the peer is actively connected using any of the
   163  // enumerated versions of a specific protocol, meaning that at least one of the
   164  // versions is supported by both this node and the peer p.
   165  func (p *Peer) RunningCap(protocol string, versions []uint) bool {
   166  	if proto, ok := p.running[protocol]; ok {
   167  		for _, ver := range versions {
   168  			if proto.Version == ver {
   169  				return true
   170  			}
   171  		}
   172  	}
   173  	return false
   174  }
   175  
   176  // RemoteAddr returns the remote address of the network connection.
   177  func (p *Peer) RemoteAddr() net.Addr {
   178  	return p.rw.fd.RemoteAddr()
   179  }
   180  
   181  // LocalAddr returns the local address of the network connection.
   182  func (p *Peer) LocalAddr() net.Addr {
   183  	return p.rw.fd.LocalAddr()
   184  }
   185  
   186  // Disconnect terminates the peer connection with the given reason.
   187  // It returns immediately and does not wait until the connection is closed.
   188  func (p *Peer) Disconnect(reason DiscReason) {
   189  	select {
   190  	case p.disc <- reason:
   191  	case <-p.closed:
   192  	}
   193  }
   194  
   195  // String implements fmt.Stringer.
   196  func (p *Peer) String() string {
   197  	id := p.ID()
   198  	return fmt.Sprintf("Peer %x %v", id[:8], p.RemoteAddr())
   199  }
   200  
   201  // Inbound returns true if the peer is an inbound connection
   202  func (p *Peer) Inbound() bool {
   203  	return p.rw.is(inboundConn)
   204  }
   205  
   206  func newPeer(log log.Logger, conn *conn, protocols []Protocol) *Peer {
   207  	protomap := matchProtocols(protocols, conn.caps, conn)
   208  	p := &Peer{
   209  		rw:       conn,
   210  		running:  protomap,
   211  		created:  mclock.Now(),
   212  		disc:     make(chan DiscReason),
   213  		protoErr: make(chan error, len(protomap)+1), // protocols + pingLoop
   214  		closed:   make(chan struct{}),
   215  		log:      log.New("id", conn.node.ID(), "conn", conn.flags),
   216  	}
   217  	return p
   218  }
   219  
   220  func (p *Peer) Log() log.Logger {
   221  	return p.log
   222  }
   223  
   224  func (p *Peer) run() (remoteRequested bool, err error) {
   225  	var (
   226  		writeStart = make(chan struct{}, 1)
   227  		writeErr   = make(chan error, 1)
   228  		readErr    = make(chan error, 1)
   229  		reason     DiscReason // sent to the peer
   230  	)
   231  	p.wg.Add(2)
   232  	go p.readLoop(readErr)
   233  	go p.pingLoop()
   234  
   235  	// Start all protocol handlers.
   236  	writeStart <- struct{}{}
   237  	p.startProtocols(writeStart, writeErr)
   238  
   239  	// Wait for an error or disconnect.
   240  loop:
   241  	for {
   242  		select {
   243  		case err = <-writeErr:
   244  			// A write finished. Allow the next write to start if
   245  			// there was no error.
   246  			if err != nil {
   247  				reason = DiscNetworkError
   248  				break loop
   249  			}
   250  			writeStart <- struct{}{}
   251  		case err = <-readErr:
   252  			if r, ok := err.(DiscReason); ok {
   253  				remoteRequested = true
   254  				reason = r
   255  			} else {
   256  				reason = DiscNetworkError
   257  			}
   258  			break loop
   259  		case err = <-p.protoErr:
   260  			reason = discReasonForError(err)
   261  			break loop
   262  		case err = <-p.disc:
   263  			reason = discReasonForError(err)
   264  			break loop
   265  		}
   266  	}
   267  
   268  	close(p.closed)
   269  	p.rw.close(reason)
   270  	p.wg.Wait()
   271  	return remoteRequested, err
   272  }
   273  
   274  func (p *Peer) pingLoop() {
   275  	ping := time.NewTimer(pingInterval)
   276  	defer p.wg.Done()
   277  	defer ping.Stop()
   278  	for {
   279  		select {
   280  		case <-ping.C:
   281  			if err := SendItems(p.rw, pingMsg); err != nil {
   282  				p.protoErr <- err
   283  				return
   284  			}
   285  			ping.Reset(pingInterval)
   286  		case <-p.closed:
   287  			return
   288  		}
   289  	}
   290  }
   291  
   292  func (p *Peer) readLoop(errc chan<- error) {
   293  	defer p.wg.Done()
   294  	for {
   295  		msg, err := p.rw.ReadMsg()
   296  		if err != nil {
   297  			errc <- err
   298  			return
   299  		}
   300  		msg.ReceivedAt = time.Now()
   301  		if err = p.handle(msg); err != nil {
   302  			errc <- err
   303  			return
   304  		}
   305  	}
   306  }
   307  
   308  func (p *Peer) handle(msg Msg) error {
   309  	switch {
   310  	case msg.Code == pingMsg:
   311  		msg.Discard()
   312  		gopool.Submit(func() {
   313  			SendItems(p.rw, pongMsg)
   314  		})
   315  	case msg.Code == discMsg:
   316  		var reason [1]DiscReason
   317  		// This is the last message. We don't need to discard or
   318  		// check errors because, the connection will be closed after it.
   319  		rlp.Decode(msg.Payload, &reason)
   320  		return reason[0]
   321  	case msg.Code < baseProtocolLength:
   322  		// ignore other base protocol messages
   323  		return msg.Discard()
   324  	default:
   325  		// it's a subprotocol message
   326  		proto, err := p.getProto(msg.Code)
   327  		if err != nil {
   328  			return fmt.Errorf("msg code out of range: %v", msg.Code)
   329  		}
   330  		if metrics.Enabled {
   331  			m := fmt.Sprintf("%s/%s/%d/%#02x", ingressMeterName, proto.Name, proto.Version, msg.Code-proto.offset)
   332  			metrics.GetOrRegisterMeter(m, nil).Mark(int64(msg.meterSize))
   333  			metrics.GetOrRegisterMeter(m+"/packets", nil).Mark(1)
   334  		}
   335  		select {
   336  		case proto.in <- msg:
   337  			return nil
   338  		case <-p.closed:
   339  			return io.EOF
   340  		}
   341  	}
   342  	return nil
   343  }
   344  
   345  func countMatchingProtocols(protocols []Protocol, caps []Cap) int {
   346  	n := 0
   347  	for _, cap := range caps {
   348  		for _, proto := range protocols {
   349  			if proto.Name == cap.Name && proto.Version == cap.Version {
   350  				n++
   351  			}
   352  		}
   353  	}
   354  	return n
   355  }
   356  
   357  // matchProtocols creates structures for matching named subprotocols.
   358  func matchProtocols(protocols []Protocol, caps []Cap, rw MsgReadWriter) map[string]*protoRW {
   359  	sort.Sort(capsByNameAndVersion(caps))
   360  	offset := baseProtocolLength
   361  	result := make(map[string]*protoRW)
   362  
   363  outer:
   364  	for _, cap := range caps {
   365  		for _, proto := range protocols {
   366  			if proto.Name == cap.Name && proto.Version == cap.Version {
   367  				// If an old protocol version matched, revert it
   368  				if old := result[cap.Name]; old != nil {
   369  					offset -= old.Length
   370  				}
   371  				// Assign the new match
   372  				result[cap.Name] = &protoRW{Protocol: proto, offset: offset, in: make(chan Msg), w: rw}
   373  				offset += proto.Length
   374  
   375  				continue outer
   376  			}
   377  		}
   378  	}
   379  	return result
   380  }
   381  
   382  func (p *Peer) startProtocols(writeStart <-chan struct{}, writeErr chan<- error) {
   383  	p.wg.Add(len(p.running))
   384  	for _, proto := range p.running {
   385  		proto := proto
   386  		proto.closed = p.closed
   387  		proto.wstart = writeStart
   388  		proto.werr = writeErr
   389  		var rw MsgReadWriter = proto
   390  		if p.events != nil {
   391  			rw = newMsgEventer(rw, p.events, p.ID(), proto.Name, p.Info().Network.RemoteAddress, p.Info().Network.LocalAddress)
   392  		}
   393  		p.log.Trace(fmt.Sprintf("Starting protocol %s/%d", proto.Name, proto.Version))
   394  		go func() {
   395  			defer p.wg.Done()
   396  			err := proto.Run(p, rw)
   397  			if err == nil {
   398  				p.log.Trace(fmt.Sprintf("Protocol %s/%d returned", proto.Name, proto.Version))
   399  				err = errProtocolReturned
   400  			} else if err != io.EOF {
   401  				p.log.Trace(fmt.Sprintf("Protocol %s/%d failed", proto.Name, proto.Version), "err", err)
   402  			}
   403  			p.protoErr <- err
   404  		}()
   405  	}
   406  }
   407  
   408  // getProto finds the protocol responsible for handling
   409  // the given message code.
   410  func (p *Peer) getProto(code uint64) (*protoRW, error) {
   411  	for _, proto := range p.running {
   412  		if code >= proto.offset && code < proto.offset+proto.Length {
   413  			return proto, nil
   414  		}
   415  	}
   416  	return nil, newPeerError(errInvalidMsgCode, "%d", code)
   417  }
   418  
   419  type protoRW struct {
   420  	Protocol
   421  	in     chan Msg        // receives read messages
   422  	closed <-chan struct{} // receives when peer is shutting down
   423  	wstart <-chan struct{} // receives when write may start
   424  	werr   chan<- error    // for write results
   425  	offset uint64
   426  	w      MsgWriter
   427  }
   428  
   429  func (rw *protoRW) WriteMsg(msg Msg) (err error) {
   430  	if msg.Code >= rw.Length {
   431  		return newPeerError(errInvalidMsgCode, "not handled")
   432  	}
   433  	msg.meterCap = rw.cap()
   434  	msg.meterCode = msg.Code
   435  
   436  	msg.Code += rw.offset
   437  
   438  	select {
   439  	case <-rw.wstart:
   440  		err = rw.w.WriteMsg(msg)
   441  		// Report write status back to Peer.run. It will initiate
   442  		// shutdown if the error is non-nil and unblock the next write
   443  		// otherwise. The calling protocol code should exit for errors
   444  		// as well but we don't want to rely on that.
   445  		rw.werr <- err
   446  	case <-rw.closed:
   447  		err = ErrShuttingDown
   448  	}
   449  	return err
   450  }
   451  
   452  func (rw *protoRW) ReadMsg() (Msg, error) {
   453  	select {
   454  	case msg := <-rw.in:
   455  		msg.Code -= rw.offset
   456  		return msg, nil
   457  	case <-rw.closed:
   458  		return Msg{}, io.EOF
   459  	}
   460  }
   461  
   462  // PeerInfo represents a short summary of the information known about a connected
   463  // peer. Sub-protocol independent fields are contained and initialized here, with
   464  // protocol specifics delegated to all connected sub-protocols.
   465  type PeerInfo struct {
   466  	ENR     string   `json:"enr,omitempty"` // Ethereum Node Record
   467  	Enode   string   `json:"enode"`         // Node URL
   468  	ID      string   `json:"id"`            // Unique node identifier
   469  	Name    string   `json:"name"`          // Name of the node, including client type, version, OS, custom data
   470  	Caps    []string `json:"caps"`          // Protocols advertised by this peer
   471  	Network struct {
   472  		LocalAddress  string `json:"localAddress"`  // Local endpoint of the TCP data connection
   473  		RemoteAddress string `json:"remoteAddress"` // Remote endpoint of the TCP data connection
   474  		Inbound       bool   `json:"inbound"`
   475  		Trusted       bool   `json:"trusted"`
   476  		Static        bool   `json:"static"`
   477  	} `json:"network"`
   478  	Protocols map[string]interface{} `json:"protocols"` // Sub-protocol specific metadata fields
   479  }
   480  
   481  // Info gathers and returns a collection of metadata known about a peer.
   482  func (p *Peer) Info() *PeerInfo {
   483  	// Gather the protocol capabilities
   484  	var caps []string
   485  	for _, cap := range p.Caps() {
   486  		caps = append(caps, cap.String())
   487  	}
   488  	// Assemble the generic peer metadata
   489  	info := &PeerInfo{
   490  		Enode:     p.Node().URLv4(),
   491  		ID:        p.ID().String(),
   492  		Name:      p.Fullname(),
   493  		Caps:      caps,
   494  		Protocols: make(map[string]interface{}),
   495  	}
   496  	if p.Node().Seq() > 0 {
   497  		info.ENR = p.Node().String()
   498  	}
   499  	info.Network.LocalAddress = p.LocalAddr().String()
   500  	info.Network.RemoteAddress = p.RemoteAddr().String()
   501  	info.Network.Inbound = p.rw.is(inboundConn)
   502  	info.Network.Trusted = p.rw.is(trustedConn)
   503  	info.Network.Static = p.rw.is(staticDialedConn)
   504  
   505  	// Gather all the running protocol infos
   506  	for _, proto := range p.running {
   507  		protoInfo := interface{}("unknown")
   508  		if query := proto.Protocol.PeerInfo; query != nil {
   509  			if metadata := query(p.ID()); metadata != nil {
   510  				protoInfo = metadata
   511  			} else {
   512  				protoInfo = "handshake"
   513  			}
   514  		}
   515  		info.Protocols[proto.Name] = protoInfo
   516  	}
   517  	return info
   518  }