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