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