github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/p2p/peer.go (about)

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