github.com/n1ghtfa1l/go-vnt@v0.6.4-alpha.6/vnt/peer.go (about)

     1  // Copyright 2015 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 vnt
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  	"math/big"
    23  	"sync"
    24  	"time"
    25  
    26  	libp2p "github.com/libp2p/go-libp2p-peer"
    27  	"github.com/vntchain/go-vnt/common"
    28  	"github.com/vntchain/go-vnt/core/types"
    29  	"github.com/vntchain/go-vnt/log"
    30  	"github.com/vntchain/go-vnt/rlp"
    31  	"github.com/vntchain/go-vnt/vntp2p"
    32  	set "gopkg.in/fatih/set.v0"
    33  )
    34  
    35  var (
    36  	errClosed            = errors.New("peer set is closed")
    37  	errAlreadyRegistered = errors.New("peer is already registered")
    38  	errNotRegistered     = errors.New("peer is not registered")
    39  )
    40  
    41  const (
    42  	maxKnownTxs    = 32768 // Maximum transactions hashes to keep in the known list (prevent DOS)
    43  	maxKnownBlocks = 1024  // Maximum block hashes to keep in the known list (prevent DOS)
    44  
    45  	// maxQueuedTxs is the maximum number of transaction lists to queue up before
    46  	// dropping broadcasts. This is a sensitive number as a transaction list might
    47  	// contain a single transaction, or thousands.
    48  	maxQueuedTxs = 128
    49  
    50  	// maxQueuedProps is the maximum number of block propagations to queue up before
    51  	// dropping broadcasts. There's not much point in queueing stale blocks, so a few
    52  	// that might cover uncles should be enough.
    53  	maxQueuedProps = 4
    54  
    55  	// maxQueuedAnns is the maximum number of block announcements to queue up before
    56  	// dropping broadcasts. Similarly to block propagations, there's no point to queue
    57  	// above some healthy uncle limit, so use that.
    58  	maxQueuedAnns = 4
    59  
    60  	handshakeTimeout = 5 * time.Second
    61  )
    62  
    63  // PeerInfo represents a short summary of the VNT sub-protocol metadata known
    64  // about a connected peer.
    65  type PeerInfo struct {
    66  	Version    int      `json:"version"`    // VNT protocol version negotiated
    67  	Difficulty *big.Int `json:"difficulty"` // Total difficulty of the peer's blockchain
    68  	Head       string   `json:"head"`       // SHA3 hash of the peer's best owned block
    69  }
    70  
    71  // propEvent is a block propagation, waiting for its turn in the broadcast queue.
    72  type propEvent struct {
    73  	block *types.Block
    74  	td    *big.Int
    75  }
    76  
    77  type annoEvent struct {
    78  	block    *types.Block
    79  	parentTd *big.Int
    80  }
    81  
    82  type peer struct {
    83  	id libp2p.ID
    84  
    85  	*vntp2p.Peer
    86  	rw vntp2p.MsgReadWriter
    87  
    88  	version int // Protocol version negotiated
    89  
    90  	head common.Hash
    91  	td   *big.Int
    92  	lock sync.RWMutex
    93  
    94  	knownTxs    *set.Set                  // Set of transaction hashes known to be known by this peer
    95  	knownBlocks *set.Set                  // Set of block hashes known to be known by this peer
    96  	queuedTxs   chan []*types.Transaction // Queue of transactions to broadcast to the peer
    97  	queuedAnns  chan *annoEvent           // Queue of blocks to announce to the peer
    98  	term        chan struct{}             // Termination channel to stop the broadcaster
    99  }
   100  
   101  func newPeer(version int, p *vntp2p.Peer, rw vntp2p.MsgReadWriter) *peer {
   102  	return &peer{
   103  		Peer:        p,
   104  		rw:          rw,
   105  		version:     version,
   106  		id:          p.RemoteID(), //fmt.Sprintf("%x", p.ID().Bytes()[:8]),
   107  		knownTxs:    set.New(),
   108  		knownBlocks: set.New(),
   109  		queuedTxs:   make(chan []*types.Transaction, maxQueuedTxs),
   110  		queuedAnns:  make(chan *annoEvent, maxQueuedAnns),
   111  		term:        make(chan struct{}),
   112  	}
   113  }
   114  
   115  // broadcast is a write loop that multiplexes block propagations, announcements
   116  // and transaction broadcasts into the remote peer. The goal is to have an async
   117  // writer that does not lock up node internals.
   118  func (p *peer) broadcast() {
   119  	for {
   120  		select {
   121  		case txs := <-p.queuedTxs:
   122  			if err := p.SendTransactions(txs); err != nil {
   123  				return
   124  			}
   125  			p.Log().Trace("Broadcast transactions", "count", len(txs))
   126  
   127  		case anno := <-p.queuedAnns:
   128  			data := newBlockHashData{
   129  				Hash:       anno.block.Hash(),
   130  				Number:     anno.block.NumberU64(),
   131  				ParentHash: anno.block.ParentHash(),
   132  				ParentTD:   anno.parentTd,
   133  			}
   134  			if err := p.SendNewBlockHashes(newBlockHashesData{data}); err != nil {
   135  				return
   136  			}
   137  			p.Log().Trace("Announced block", "number", anno.block.Number(), "hash", anno.block.Hash().String(), "peer", p.id)
   138  
   139  		case <-p.term:
   140  			return
   141  		}
   142  	}
   143  }
   144  
   145  // close signals the broadcast goroutine to terminate.
   146  func (p *peer) close() {
   147  	close(p.term)
   148  }
   149  
   150  // Info gathers and returns a collection of metadata known about a peer.
   151  func (p *peer) Info() *PeerInfo {
   152  	hash, td := p.Head()
   153  
   154  	return &PeerInfo{
   155  		Version:    p.version,
   156  		Difficulty: td,
   157  		Head:       hash.Hex(),
   158  	}
   159  }
   160  
   161  // Head retrieves a copy of the current head hash and total difficulty of the
   162  // peer.
   163  func (p *peer) Head() (hash common.Hash, td *big.Int) {
   164  	p.lock.RLock()
   165  	defer p.lock.RUnlock()
   166  
   167  	copy(hash[:], p.head[:])
   168  	return hash, new(big.Int).Set(p.td)
   169  }
   170  
   171  // SetHead updates the head hash and total difficulty of the peer.
   172  func (p *peer) SetHead(hash common.Hash, td *big.Int) {
   173  	p.lock.Lock()
   174  	defer p.lock.Unlock()
   175  
   176  	copy(p.head[:], hash[:])
   177  	p.td.Set(td)
   178  }
   179  
   180  // MarkBlock marks a block as known for the peer, ensuring that the block will
   181  // never be propagated to this particular peer.
   182  func (p *peer) MarkBlock(hash common.Hash) {
   183  	// If we reached the memory allowance, drop a previously known block hash
   184  	for p.knownBlocks.Size() >= maxKnownBlocks {
   185  		p.knownBlocks.Pop()
   186  	}
   187  	p.knownBlocks.Add(hash)
   188  }
   189  
   190  // MarkTransaction marks a transaction as known for the peer, ensuring that it
   191  // will never be propagated to this particular peer.
   192  func (p *peer) MarkTransaction(hash common.Hash) {
   193  	// If we reached the memory allowance, drop a previously known transaction hash
   194  	for p.knownTxs.Size() >= maxKnownTxs {
   195  		p.knownTxs.Pop()
   196  	}
   197  	p.knownTxs.Add(hash)
   198  }
   199  
   200  // SendTransactions sends transactions to the peer and includes the hashes
   201  // in its transaction hash set for future reference.
   202  func (p *peer) SendTransactions(txs types.Transactions) error {
   203  	for _, tx := range txs {
   204  		p.knownTxs.Add(tx.Hash())
   205  	}
   206  	return vntp2p.Send(p.rw, ProtocolName, TxMsg, txs)
   207  }
   208  
   209  // AsyncSendTransactions queues list of transactions propagation to a remote
   210  // peer. If the peer's broadcast queue is full, the event is silently dropped.
   211  func (p *peer) AsyncSendTransactions(txs []*types.Transaction) {
   212  	select {
   213  	case p.queuedTxs <- txs:
   214  		for _, tx := range txs {
   215  			p.knownTxs.Add(tx.Hash())
   216  		}
   217  	default:
   218  		p.Log().Debug("Dropping transaction propagation", "count", len(txs))
   219  	}
   220  }
   221  
   222  // SendNewBlockHashes announces the availability of a number of blocks through
   223  // a hash notification.
   224  func (p *peer) SendNewBlockHashes(hashesData newBlockHashesData) error {
   225  	for _, item := range hashesData {
   226  		p.knownBlocks.Add(item.Hash)
   227  	}
   228  	return vntp2p.Send(p.rw, ProtocolName, NewBlockHashesMsg, hashesData)
   229  }
   230  
   231  // AsyncSendNewBlockHash queues the availability of a block for propagation to a
   232  // remote peer. If the peer's broadcast queue is full, the event is silently
   233  // dropped.
   234  func (p *peer) AsyncSendNewBlockHash(block *types.Block, parentTD *big.Int) {
   235  	select {
   236  	case p.queuedAnns <- &annoEvent{block: block, parentTd: parentTD}:
   237  		p.knownBlocks.Add(block.Hash())
   238  	default:
   239  		p.Log().Debug("Dropping block announcement", "number", block.NumberU64(), "hash", block.Hash())
   240  	}
   241  }
   242  
   243  // SendBlockHeaders sends a batch of block headers to the remote peer.
   244  func (p *peer) SendBlockHeaders(headers []*types.Header) error {
   245  	return vntp2p.Send(p.rw, ProtocolName, BlockHeadersMsg, headers)
   246  }
   247  
   248  // SendBlockBodies sends a batch of block contents to the remote peer.
   249  func (p *peer) SendBlockBodies(bodies []*blockBody) error {
   250  	return vntp2p.Send(p.rw, ProtocolName, BlockBodiesMsg, blockBodiesData(bodies))
   251  }
   252  
   253  // SendBlockBodiesRLP sends a batch of block contents to the remote peer from
   254  // an already RLP encoded format.
   255  func (p *peer) SendBlockBodiesRLP(bodies []rlp.RawValue) error {
   256  	return vntp2p.Send(p.rw, ProtocolName, BlockBodiesMsg, bodies)
   257  }
   258  
   259  // SendNodeDataRLP sends a batch of arbitrary internal data, corresponding to the
   260  // hashes requested.
   261  func (p *peer) SendNodeData(data [][]byte) error {
   262  	return vntp2p.Send(p.rw, ProtocolName, NodeDataMsg, data)
   263  }
   264  
   265  // SendReceiptsRLP sends a batch of transaction receipts, corresponding to the
   266  // ones requested from an already RLP encoded format.
   267  func (p *peer) SendReceiptsRLP(receipts []rlp.RawValue) error {
   268  	return vntp2p.Send(p.rw, ProtocolName, ReceiptsMsg, receipts)
   269  }
   270  
   271  // SendBftMsg
   272  func (p *peer) SendBftMsg(bftMsg types.BftMsg) error {
   273  	var msgType vntp2p.MessageType
   274  	switch bftMsg.BftType {
   275  	case types.BftPreprepareMessage:
   276  		msgType = BftPreprepareMsg
   277  	case types.BftPrepareMessage:
   278  		msgType = BftPrepareMsg
   279  	case types.BftCommitMessage:
   280  		msgType = BftCommitMsg
   281  	}
   282  	return vntp2p.Send(p.rw, ProtocolName, msgType, bftMsg.Msg)
   283  }
   284  
   285  // RequestOneHeader is a wrapper around the header query functions to fetch a
   286  // single header. It is used solely by the fetcher.
   287  func (p *peer) RequestOneHeader(hash common.Hash) error {
   288  	p.Log().Debug("Fetching single header", "hash", hash)
   289  	return vntp2p.Send(p.rw, ProtocolName, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Hash: hash}, Amount: uint64(1), Skip: uint64(0), Reverse: false})
   290  }
   291  
   292  // RequestHeadersByHash fetches a batch of blocks' headers corresponding to the
   293  // specified header query, based on the hash of an origin block.
   294  func (p *peer) RequestHeadersByHash(origin common.Hash, amount int, skip int, reverse bool) error {
   295  	p.Log().Debug("Fetching batch of headers", "count", amount, "fromhash", origin, "skip", skip, "reverse", reverse)
   296  	return vntp2p.Send(p.rw, ProtocolName, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Hash: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse})
   297  }
   298  
   299  // RequestHeadersByNumber fetches a batch of blocks' headers corresponding to the
   300  // specified header query, based on the number of an origin block.
   301  func (p *peer) RequestHeadersByNumber(origin uint64, amount int, skip int, reverse bool) error {
   302  	p.Log().Debug("Fetching batch of headers", "count", amount, "fromnum", origin, "skip", skip, "reverse", reverse)
   303  	return vntp2p.Send(p.rw, ProtocolName, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Number: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse})
   304  }
   305  
   306  // RequestBodies fetches a batch of blocks' bodies corresponding to the hashes
   307  // specified.
   308  func (p *peer) RequestBodies(hashes []common.Hash) error {
   309  	p.Log().Debug("Fetching batch of block bodies", "count", len(hashes))
   310  	return vntp2p.Send(p.rw, ProtocolName, GetBlockBodiesMsg, hashes)
   311  }
   312  
   313  // RequestNodeData fetches a batch of arbitrary data from a node's known state
   314  // data, corresponding to the specified hashes.
   315  func (p *peer) RequestNodeData(hashes []common.Hash) error {
   316  	p.Log().Debug("Fetching batch of state data", "count", len(hashes))
   317  	return vntp2p.Send(p.rw, ProtocolName, GetNodeDataMsg, hashes)
   318  }
   319  
   320  // RequestReceipts fetches a batch of transaction receipts from a remote node.
   321  func (p *peer) RequestReceipts(hashes []common.Hash) error {
   322  	p.Log().Debug("Fetching batch of receipts", "count", len(hashes))
   323  	return vntp2p.Send(p.rw, ProtocolName, GetReceiptsMsg, hashes)
   324  }
   325  
   326  // Handshake executes the vnt protocol handshake, negotiating version number,
   327  // network IDs, difficulties, head and genesis blocks.
   328  func (p *peer) Handshake(network uint64, td *big.Int, head common.Hash, genesis common.Hash) error {
   329  	// Send out own handshake in a new thread
   330  	errc := make(chan error, 2)
   331  	var status statusData // safe to read after two values have been received from errc
   332  
   333  	go func() {
   334  		log.Info("vnt protocol handshake", "going to send handshake msg to", p.id, "ProtocolVersion", uint32(p.version))
   335  		errc <- vntp2p.Send(p.rw, ProtocolName, StatusMsg, &statusData{
   336  			ProtocolVersion: uint32(p.version),
   337  			NetworkId:       network,
   338  			TD:              td,
   339  			CurrentBlock:    head,
   340  			GenesisBlock:    genesis,
   341  		})
   342  	}()
   343  
   344  	go func() {
   345  		errc <- p.readStatus(network, &status, genesis)
   346  	}()
   347  
   348  	timeout := time.NewTimer(handshakeTimeout)
   349  	defer timeout.Stop()
   350  	for i := 0; i < 2; i++ {
   351  		select {
   352  		case err := <-errc:
   353  			if err != nil {
   354  				return err
   355  			}
   356  		case <-timeout.C:
   357  			return vntp2p.DiscReadTimeout
   358  		}
   359  	}
   360  	p.td, p.head = status.TD, status.CurrentBlock
   361  	return nil
   362  }
   363  
   364  func (p *peer) readStatus(network uint64, status *statusData, genesis common.Hash) (err error) {
   365  	msg, err := p.rw.ReadMsg()
   366  	if err != nil {
   367  		return err
   368  	}
   369  	if msg.Body.Type != StatusMsg {
   370  		return errResp(ErrNoStatusMsg, "first msg has code %x (!= %x)", msg.Body.Type, StatusMsg)
   371  	}
   372  	size := msg.GetBodySize()
   373  	if size > ProtocolMaxMsgSize {
   374  		return errResp(ErrMsgTooLarge, "%v > %v", size, ProtocolMaxMsgSize)
   375  	}
   376  	// Decode the handshake and make sure everything matches
   377  	if err := msg.Decode(&status); err != nil {
   378  		return errResp(ErrDecode, "msg %v: %v", msg, err)
   379  	}
   380  
   381  	if status.GenesisBlock != genesis {
   382  		// this peer is mismatch with local node, drop it
   383  		p.Peer.Drop()
   384  		return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", status.GenesisBlock[:8], genesis[:8])
   385  	}
   386  	if status.NetworkId != network {
   387  		p.Peer.Drop()
   388  		return errResp(ErrNetworkIdMismatch, "%d (!= %d)", status.NetworkId, network)
   389  	}
   390  	if int(status.ProtocolVersion) != p.version {
   391  		p.Peer.Drop()
   392  		return errResp(ErrProtocolVersionMismatch, "%d (!= %d)", status.ProtocolVersion, p.version)
   393  	}
   394  	return nil
   395  }
   396  
   397  // String implements fmt.Stringer.
   398  func (p *peer) String() string {
   399  	return fmt.Sprintf("Peer %s [%s]", p.id,
   400  		fmt.Sprintf("vnt/%2d", p.version),
   401  	)
   402  }
   403  
   404  // peerSet represents the collection of active peers currently participating in
   405  // the VNT sub-protocol.
   406  type peerSet struct {
   407  	peers    map[libp2p.ID]*peer
   408  	bftPeers map[libp2p.ID]struct{}
   409  	lock     sync.RWMutex
   410  	closed   bool
   411  }
   412  
   413  // newPeerSet creates a new peer set to track the active participants.
   414  func newPeerSet() *peerSet {
   415  	return &peerSet{
   416  		peers:    make(map[libp2p.ID]*peer),
   417  		bftPeers: make(map[libp2p.ID]struct{}),
   418  	}
   419  }
   420  
   421  // Register injects a new peer into the working set, or returns an error if the
   422  // peer is already known. If a new peer it registered, its broadcast loop is also
   423  // started.
   424  func (ps *peerSet) Register(p *peer) error {
   425  	ps.lock.Lock()
   426  	defer ps.lock.Unlock()
   427  
   428  	if ps.closed {
   429  		return errClosed
   430  	}
   431  	if _, ok := ps.peers[p.id]; ok {
   432  		return errAlreadyRegistered
   433  	}
   434  	ps.peers[p.id] = p
   435  	go p.broadcast()
   436  
   437  	return nil
   438  }
   439  
   440  // Unregister removes a remote peer from the active set, disabling any further
   441  // actions to/from that particular entity.
   442  func (ps *peerSet) Unregister(id libp2p.ID) error {
   443  	ps.lock.Lock()
   444  	defer ps.lock.Unlock()
   445  
   446  	p, ok := ps.peers[id]
   447  	if !ok {
   448  		return errNotRegistered
   449  	}
   450  	delete(ps.peers, id)
   451  	p.close()
   452  
   453  	return nil
   454  }
   455  
   456  // Peer retrieves the registered peer with the given id.
   457  func (ps *peerSet) Peer(id libp2p.ID) *peer {
   458  	ps.lock.RLock()
   459  	defer ps.lock.RUnlock()
   460  
   461  	return ps.peers[id]
   462  }
   463  
   464  // Len returns if the current number of peers in the set.
   465  func (ps *peerSet) Len() int {
   466  	ps.lock.RLock()
   467  	defer ps.lock.RUnlock()
   468  
   469  	return len(ps.peers)
   470  }
   471  
   472  // PeersWithoutBlock retrieves a list of peers that do not have a given block in
   473  // their set of known hashes.
   474  func (ps *peerSet) PeersWithoutBlock(hash common.Hash) []*peer {
   475  	ps.lock.RLock()
   476  	defer ps.lock.RUnlock()
   477  
   478  	list := make([]*peer, 0, len(ps.peers))
   479  	for _, p := range ps.peers {
   480  		if !p.knownBlocks.Has(hash) {
   481  			list = append(list, p)
   482  		}
   483  	}
   484  	return list
   485  }
   486  
   487  // PeersWithoutTx retrieves a list of peers that do not have a given transaction
   488  // in their set of known hashes.
   489  func (ps *peerSet) PeersWithoutTx(hash common.Hash) []*peer {
   490  	ps.lock.RLock()
   491  	defer ps.lock.RUnlock()
   492  
   493  	list := make([]*peer, 0, len(ps.peers))
   494  	for _, p := range ps.peers {
   495  		if !p.knownTxs.Has(hash) {
   496  			list = append(list, p)
   497  		}
   498  	}
   499  	return list
   500  }
   501  
   502  func (ps *peerSet) PeersForBft() []*peer {
   503  	ps.lock.RLock()
   504  	defer ps.lock.RUnlock()
   505  
   506  	list := make([]*peer, 0, len(ps.bftPeers))
   507  	for p, _ := range ps.bftPeers {
   508  		// 该处需要判断是不是bft节点
   509  		if peer, exists := ps.peers[p]; exists {
   510  			list = append(list, peer)
   511  		}
   512  	}
   513  	return list
   514  }
   515  
   516  // BestPeer retrieves the known peer with the currently highest total difficulty.
   517  func (ps *peerSet) BestPeer() *peer {
   518  	ps.lock.RLock()
   519  	defer ps.lock.RUnlock()
   520  
   521  	var (
   522  		bestPeer *peer
   523  		bestTd   *big.Int
   524  	)
   525  	for _, p := range ps.peers {
   526  		if _, td := p.Head(); bestPeer == nil || td.Cmp(bestTd) > 0 {
   527  			bestPeer, bestTd = p, td
   528  		}
   529  	}
   530  	return bestPeer
   531  }
   532  
   533  // Close disconnects all peers.
   534  // No new peers can be registered after Close has returned.
   535  func (ps *peerSet) Close() {
   536  	ps.lock.Lock()
   537  	defer ps.lock.Unlock()
   538  
   539  	for _, p := range ps.peers {
   540  		p.Disconnect(vntp2p.DiscQuitting)
   541  	}
   542  	ps.closed = true
   543  }