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