github.com/core-coin/go-core/v2@v2.1.9/xcb/handler.go (about)

     1  // Copyright 2015 by the Authors
     2  // This file is part of the go-core library.
     3  //
     4  // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package xcb
    18  
    19  import (
    20  	"encoding/json"
    21  	"errors"
    22  	"fmt"
    23  	"math"
    24  	"math/big"
    25  	"sync"
    26  	"sync/atomic"
    27  	"time"
    28  
    29  	"github.com/core-coin/go-core/v2/xcbdb"
    30  
    31  	"github.com/core-coin/go-core/v2/common"
    32  	"github.com/core-coin/go-core/v2/consensus"
    33  	"github.com/core-coin/go-core/v2/core"
    34  	"github.com/core-coin/go-core/v2/core/forkid"
    35  	"github.com/core-coin/go-core/v2/core/types"
    36  	"github.com/core-coin/go-core/v2/event"
    37  	"github.com/core-coin/go-core/v2/log"
    38  	"github.com/core-coin/go-core/v2/p2p"
    39  	"github.com/core-coin/go-core/v2/p2p/enode"
    40  	"github.com/core-coin/go-core/v2/params"
    41  	"github.com/core-coin/go-core/v2/rlp"
    42  	"github.com/core-coin/go-core/v2/trie"
    43  	"github.com/core-coin/go-core/v2/xcb/downloader"
    44  	"github.com/core-coin/go-core/v2/xcb/fetcher"
    45  )
    46  
    47  const (
    48  	softResponseLimit = 2 * 1024 * 1024 // Target maximum size of returned blocks, headers or node data.
    49  	estHeaderRlpSize  = 500             // Approximate size of an RLP encoded block header
    50  
    51  	// txChanSize is the size of channel listening to NewTxsEvent.
    52  	// The number is referenced from the size of tx pool.
    53  	txChanSize = 4096
    54  )
    55  
    56  var (
    57  	syncChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the sync progress challenge
    58  )
    59  
    60  func errResp(code errCode, format string, v ...interface{}) error {
    61  	return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...))
    62  }
    63  
    64  type ProtocolManager struct {
    65  	networkID  uint64
    66  	forkFilter forkid.Filter // Fork ID filter, constant across the lifetime of the node
    67  
    68  	fastSync  uint32 // Flag whether fast sync is enabled (gets disabled if we already have blocks)
    69  	acceptTxs uint32 // Flag whether we're considered synchronised (enables transaction processing)
    70  
    71  	checkpointNumber uint64      // Block number for the sync progress validator to cross reference
    72  	checkpointHash   common.Hash // Block hash for the sync progress validator to cross reference
    73  
    74  	txpool     txPool
    75  	blockchain *core.BlockChain
    76  	chaindb    xcbdb.Database
    77  	maxPeers   int
    78  
    79  	downloader   *downloader.Downloader
    80  	blockFetcher *fetcher.BlockFetcher
    81  	txFetcher    *fetcher.TxFetcher
    82  	peers        *peerSet
    83  
    84  	eventMux      *event.TypeMux
    85  	txsCh         chan core.NewTxsEvent
    86  	txsSub        event.Subscription
    87  	minedBlockSub *event.TypeMuxSubscription
    88  
    89  	whitelist map[uint64]common.Hash
    90  
    91  	bttp bool
    92  
    93  	// channels for fetcher, syncer, txsyncLoop
    94  	txsyncCh chan *txsync
    95  	quitSync chan struct{}
    96  
    97  	chainSync *chainSyncer
    98  	wg        sync.WaitGroup
    99  	peerWG    sync.WaitGroup
   100  
   101  	// Test fields or hooks
   102  	broadcastTxAnnouncesOnly bool // Testing field, disable transaction propagation
   103  }
   104  
   105  // NewProtocolManager returns a new Core sub protocol manager. The Core sub protocol manages peers capable
   106  // with the Core network.
   107  func NewProtocolManager(config *params.ChainConfig, checkpoint *params.TrustedCheckpoint, mode downloader.SyncMode, networkID uint64, mux *event.TypeMux, txpool txPool, engine consensus.Engine, blockchain *core.BlockChain, chaindb xcbdb.Database, cacheLimit int, whitelist map[uint64]common.Hash, bttp bool) (*ProtocolManager, error) {
   108  	// Create the protocol manager with the base fields
   109  	manager := &ProtocolManager{
   110  		networkID:  networkID,
   111  		forkFilter: forkid.NewFilter(blockchain),
   112  		eventMux:   mux,
   113  		txpool:     txpool,
   114  		blockchain: blockchain,
   115  		chaindb:    chaindb,
   116  		peers:      newPeerSet(),
   117  		whitelist:  whitelist,
   118  		txsyncCh:   make(chan *txsync),
   119  		quitSync:   make(chan struct{}),
   120  		bttp:       bttp,
   121  	}
   122  
   123  	if mode == downloader.FullSync {
   124  		// The database seems empty as the current block is the genesis. Yet the fast
   125  		// block is ahead, so fast sync was enabled for this node at a certain point.
   126  		// The scenarios where this can happen is
   127  		// * if the user manually (or via a bad block) rolled back a fast sync node
   128  		//   below the sync point.
   129  		// * the last fast sync is not finished while user specifies a full sync this
   130  		//   time. But we don't have any recent state for full sync.
   131  		// In these cases however it's safe to reenable fast sync.
   132  		fullBlock, fastBlock := blockchain.CurrentBlock(), blockchain.CurrentFastBlock()
   133  		if fullBlock.NumberU64() == 0 && fastBlock.NumberU64() > 0 {
   134  			manager.fastSync = uint32(1)
   135  			log.Warn("Switch sync mode from full sync to fast sync")
   136  		}
   137  	} else {
   138  		if blockchain.CurrentBlock().NumberU64() > 0 {
   139  			// Print warning log if database is not empty to run fast sync.
   140  			log.Warn("Switch sync mode from fast sync to full sync")
   141  		} else {
   142  			// If fast sync was requested and our database is empty, grant it
   143  			manager.fastSync = uint32(1)
   144  		}
   145  	}
   146  
   147  	// If we have trusted checkpoints, enforce them on the chain
   148  	if checkpoint != nil {
   149  		manager.checkpointNumber = (checkpoint.SectionIndex+1)*params.CHTFrequency - 1
   150  		manager.checkpointHash = checkpoint.SectionHead
   151  	}
   152  
   153  	// Construct the downloader (long sync) and its backing state bloom if fast
   154  	// sync is requested. The downloader is responsible for deallocating the state
   155  	// bloom when it's done.
   156  	var stateBloom *trie.SyncBloom
   157  	if atomic.LoadUint32(&manager.fastSync) == 1 {
   158  		stateBloom = trie.NewSyncBloom(uint64(cacheLimit), chaindb)
   159  	}
   160  	manager.downloader = downloader.New(manager.checkpointNumber, chaindb, stateBloom, manager.eventMux, blockchain, nil, manager.removePeer)
   161  
   162  	// Construct the fetcher (short sync)
   163  	validator := func(header *types.Header) error {
   164  		return engine.VerifyHeader(blockchain, header, true)
   165  	}
   166  	heighter := func() uint64 {
   167  		return blockchain.CurrentBlock().NumberU64()
   168  	}
   169  	inserter := func(blocks types.Blocks) (int, error) {
   170  		// If sync hasn't reached the checkpoint yet, deny importing weird blocks.
   171  		//
   172  		// Ideally we would also compare the head block's timestamp and similarly reject
   173  		// the propagated block if the head is too old. Unfortunately there is a corner
   174  		// case when starting new networks, where the genesis might be ancient (0 unix)
   175  		// which would prevent full nodes from accepting it.
   176  		if manager.blockchain.CurrentBlock().NumberU64() < manager.checkpointNumber && manager.checkpointHash != (common.Hash{}) {
   177  			log.Warn("Unsynced yet, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
   178  			return 0, nil
   179  		}
   180  		// If fast sync is running, deny importing weird blocks. This is a problematic
   181  		// clause when starting up a new network, because fast-syncing miners might not
   182  		// accept each others' blocks until a restart. Unfortunately we haven't figured
   183  		// out a way yet where nodes can decide unilaterally whether the network is new
   184  		// or not. This should be fixed if we figure out a solution.
   185  		if atomic.LoadUint32(&manager.fastSync) == 1 {
   186  			log.Warn("Fast syncing, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
   187  			return 0, nil
   188  		}
   189  		n, err := manager.blockchain.InsertChain(blocks)
   190  		if err == nil {
   191  			atomic.StoreUint32(&manager.acceptTxs, 1) // Mark initial sync done on any fetcher import
   192  		}
   193  		return n, err
   194  	}
   195  	manager.blockFetcher = fetcher.NewBlockFetcher(false, nil, blockchain.GetBlockByHash, validator, manager.BroadcastBlock, heighter, nil, inserter, manager.removePeer)
   196  
   197  	fetchTx := func(peer string, hashes []common.Hash) error {
   198  		p := manager.peers.Peer(peer)
   199  		if p == nil {
   200  			return errors.New("unknown peer")
   201  		}
   202  		return p.RequestTxs(hashes)
   203  	}
   204  	manager.txFetcher = fetcher.NewTxFetcher(txpool.Has, txpool.AddRemotes, fetchTx)
   205  
   206  	manager.chainSync = newChainSyncer(manager)
   207  
   208  	return manager, nil
   209  }
   210  
   211  func (pm *ProtocolManager) makeProtocol(version uint) p2p.Protocol {
   212  	length, ok := protocolLengths[version]
   213  	if !ok {
   214  		panic("makeProtocol for unknown version")
   215  	}
   216  
   217  	return p2p.Protocol{
   218  		Name:    protocolName,
   219  		Version: version,
   220  		Length:  length,
   221  		Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
   222  			return pm.runPeer(pm.newPeer(int(version), p, rw, pm.txpool.Get))
   223  		},
   224  		NodeInfo: func() interface{} {
   225  			return pm.NodeInfo()
   226  		},
   227  		PeerInfo: func(id enode.ID) interface{} {
   228  			if p := pm.peers.Peer(fmt.Sprintf("%x", id[:8])); p != nil {
   229  				return p.Info()
   230  			}
   231  			return nil
   232  		},
   233  	}
   234  }
   235  
   236  func (pm *ProtocolManager) removePeer(id string) {
   237  	// Short circuit if the peer was already removed
   238  	peer := pm.peers.Peer(id)
   239  	if peer == nil {
   240  		return
   241  	}
   242  	log.Debug("Removing Core peer", "peer", id)
   243  
   244  	// Unregister the peer from the downloader and Core peer set
   245  	pm.downloader.UnregisterPeer(id)
   246  	pm.txFetcher.Drop(id)
   247  
   248  	if err := pm.peers.Unregister(id); err != nil {
   249  		log.Error("Peer removal failed", "peer", id, "err", err)
   250  	}
   251  	// Hard disconnect at the networking layer
   252  	if peer != nil {
   253  		peer.Peer.Disconnect(p2p.DiscUselessPeer)
   254  	}
   255  }
   256  
   257  func (pm *ProtocolManager) Start(maxPeers int) {
   258  	pm.maxPeers = maxPeers
   259  
   260  	// broadcast transactions
   261  	pm.wg.Add(1)
   262  	pm.txsCh = make(chan core.NewTxsEvent, txChanSize)
   263  	pm.txsSub = pm.txpool.SubscribeNewTxsEvent(pm.txsCh)
   264  	go pm.txBroadcastLoop()
   265  
   266  	// broadcast mined blocks
   267  	pm.wg.Add(1)
   268  	pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{})
   269  	go pm.minedBroadcastLoop()
   270  
   271  	// start sync handlers
   272  	pm.wg.Add(2)
   273  	go pm.chainSync.loop()
   274  	go pm.txsyncLoop64() // TODO(raisty): Legacy initial tx echange, drop with xcb/64.
   275  }
   276  
   277  func (pm *ProtocolManager) Stop() {
   278  	pm.txsSub.Unsubscribe()        // quits txBroadcastLoop
   279  	pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
   280  
   281  	// Quit chainSync and txsync64.
   282  	// After this is done, no new peers will be accepted.
   283  	close(pm.quitSync)
   284  	pm.wg.Wait()
   285  
   286  	// Disconnect existing sessions.
   287  	// This also closes the gate for any new registrations on the peer set.
   288  	// sessions which are already established but not added to pm.peers yet
   289  	// will exit when they try to register.
   290  	pm.peers.Close()
   291  	pm.peerWG.Wait()
   292  
   293  	log.Info("Core protocol stopped")
   294  }
   295  
   296  func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter, getPooledTx func(hash common.Hash) *types.Transaction) *peer {
   297  	return newPeer(pv, p, rw, getPooledTx)
   298  }
   299  
   300  func (pm *ProtocolManager) runPeer(p *peer) error {
   301  	if !pm.chainSync.handlePeerEvent(p) {
   302  		return p2p.DiscQuitting
   303  	}
   304  	pm.peerWG.Add(1)
   305  	defer pm.peerWG.Done()
   306  	return pm.handle(p)
   307  }
   308  
   309  // handle is the callback invoked to manage the life cycle of an xcb peer. When
   310  // this function terminates, the peer is disconnected.
   311  func (pm *ProtocolManager) handle(p *peer) error {
   312  	// Ignore maxPeers if this is a trusted peer
   313  	if pm.peers.Len() >= pm.maxPeers && !p.Peer.Info().Network.Trusted {
   314  		return p2p.DiscTooManyPeers
   315  	}
   316  	p.Log().Debug("Core peer connected", "name", p.Name())
   317  
   318  	// Execute the Core handshake
   319  	var (
   320  		genesis = pm.blockchain.Genesis()
   321  		head    = pm.blockchain.CurrentHeader()
   322  		hash    = head.Hash()
   323  		number  = head.Number.Uint64()
   324  		td      = pm.blockchain.GetTd(hash, number)
   325  	)
   326  	forkID := forkid.NewID(pm.blockchain.Config(), pm.blockchain.Genesis().Hash(), pm.blockchain.CurrentHeader().Number.Uint64())
   327  	if err := p.Handshake(pm.networkID, td, hash, genesis.Hash(), forkID, pm.forkFilter); err != nil {
   328  		p.Log().Debug("Core handshake failed", "err", err)
   329  		return err
   330  	}
   331  
   332  	// Register the peer locally
   333  	if err := pm.peers.Register(p, pm.removePeer); err != nil {
   334  		p.Log().Error("Core peer registration failed", "err", err)
   335  		return err
   336  	}
   337  	defer pm.removePeer(p.id)
   338  
   339  	// Register the peer in the downloader. If the downloader considers it banned, we disconnect
   340  	if err := pm.downloader.RegisterPeer(p.id, p.version, p); err != nil {
   341  		return err
   342  	}
   343  	pm.chainSync.handlePeerEvent(p)
   344  
   345  	// Propagate existing transactions. new transactions appearing
   346  	// after this will be sent via broadcasts.
   347  	pm.syncTransactions(p)
   348  
   349  	// If we have a trusted CHT, reject all peers below that (avoid fast sync eclipse)
   350  	if pm.checkpointHash != (common.Hash{}) {
   351  		// Request the peer's checkpoint header for chain height/weight validation
   352  		if err := p.RequestHeadersByNumber(pm.checkpointNumber, 1, 0, false); err != nil {
   353  			return err
   354  		}
   355  		// Start a timer to disconnect if the peer doesn't reply in time
   356  		p.syncDrop = time.AfterFunc(syncChallengeTimeout, func() {
   357  			p.Log().Warn("Checkpoint challenge timed out, dropping", "addr", p.RemoteAddr(), "type", p.Name())
   358  			pm.removePeer(p.id)
   359  		})
   360  		// Make sure it's cleaned up if the peer dies off
   361  		defer func() {
   362  			if p.syncDrop != nil {
   363  				p.syncDrop.Stop()
   364  				p.syncDrop = nil
   365  			}
   366  		}()
   367  	}
   368  	// If we have any explicit whitelist block hashes, request them
   369  	for number := range pm.whitelist {
   370  		if err := p.RequestHeadersByNumber(number, 1, 0, false); err != nil {
   371  			return err
   372  		}
   373  	}
   374  	// Handle incoming messages until the connection is torn down
   375  	for {
   376  		if err := pm.handleMsg(p); err != nil {
   377  			p.Log().Debug("Core message handling failed", "err", err)
   378  			return err
   379  		}
   380  	}
   381  }
   382  
   383  // handleMsg is invoked whenever an inbound message is received from a remote
   384  // peer. The remote connection is torn down upon returning any error.
   385  func (pm *ProtocolManager) handleMsg(p *peer) error {
   386  	// Read the next message from the remote peer, and ensure it's fully consumed
   387  	msg, err := p.rw.ReadMsg()
   388  	if err != nil {
   389  		return err
   390  	}
   391  	if msg.Size > protocolMaxMsgSize {
   392  		return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, protocolMaxMsgSize)
   393  	}
   394  	defer msg.Discard()
   395  
   396  	// Handle the message depending on its contents
   397  	switch {
   398  	case msg.Code == StatusMsg:
   399  		// Status messages should never arrive after the handshake
   400  		return errResp(ErrExtraStatusMsg, "uncontrolled status message")
   401  
   402  	// Block header query, collect the requested headers and reply
   403  	case msg.Code == GetBlockHeadersMsg:
   404  		// Decode the complex header query
   405  		var query getBlockHeadersData
   406  		if err := msg.Decode(&query); err != nil {
   407  			return errResp(ErrDecode, "%v: %v", msg, err)
   408  		}
   409  		hashMode := query.Origin.Hash != (common.Hash{})
   410  		first := true
   411  		maxNonCanonical := uint64(100)
   412  
   413  		// Gather headers until the fetch or network limits is reached
   414  		var (
   415  			bytes   common.StorageSize
   416  			headers []*types.Header
   417  			unknown bool
   418  		)
   419  		for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch {
   420  			// Retrieve the next header satisfying the query
   421  			var origin *types.Header
   422  			if hashMode {
   423  				if first {
   424  					first = false
   425  					origin = pm.blockchain.GetHeaderByHash(query.Origin.Hash)
   426  					if origin != nil {
   427  						query.Origin.Number = origin.Number.Uint64()
   428  					}
   429  				} else {
   430  					origin = pm.blockchain.GetHeader(query.Origin.Hash, query.Origin.Number)
   431  				}
   432  			} else {
   433  				origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number)
   434  			}
   435  			if origin == nil {
   436  				break
   437  			}
   438  			headers = append(headers, origin)
   439  			bytes += estHeaderRlpSize
   440  
   441  			// Advance to the next header of the query
   442  			switch {
   443  			case hashMode && query.Reverse:
   444  				// Hash based traversal towards the genesis block
   445  				ancestor := query.Skip + 1
   446  				if ancestor == 0 {
   447  					unknown = true
   448  				} else {
   449  					query.Origin.Hash, query.Origin.Number = pm.blockchain.GetAncestor(query.Origin.Hash, query.Origin.Number, ancestor, &maxNonCanonical)
   450  					unknown = (query.Origin.Hash == common.Hash{})
   451  				}
   452  			case hashMode && !query.Reverse:
   453  				// Hash based traversal towards the leaf block
   454  				var (
   455  					current = origin.Number.Uint64()
   456  					next    = current + query.Skip + 1
   457  				)
   458  				if next <= current {
   459  					infos, _ := json.MarshalIndent(p.Peer.Info(), "", "  ")
   460  					p.Log().Warn("GetBlockHeaders skip overflow attack", "current", current, "skip", query.Skip, "next", next, "attacker", infos)
   461  					unknown = true
   462  				} else {
   463  					if header := pm.blockchain.GetHeaderByNumber(next); header != nil {
   464  						nextHash := header.Hash()
   465  						expOldHash, _ := pm.blockchain.GetAncestor(nextHash, next, query.Skip+1, &maxNonCanonical)
   466  						if expOldHash == query.Origin.Hash {
   467  							query.Origin.Hash, query.Origin.Number = nextHash, next
   468  						} else {
   469  							unknown = true
   470  						}
   471  					} else {
   472  						unknown = true
   473  					}
   474  				}
   475  			case query.Reverse:
   476  				// Number based traversal towards the genesis block
   477  				if query.Origin.Number >= query.Skip+1 {
   478  					query.Origin.Number -= query.Skip + 1
   479  				} else {
   480  					unknown = true
   481  				}
   482  
   483  			case !query.Reverse:
   484  				// Number based traversal towards the leaf block
   485  				query.Origin.Number += query.Skip + 1
   486  			}
   487  		}
   488  		return p.SendBlockHeaders(headers)
   489  
   490  	case msg.Code == BlockHeadersMsg:
   491  		// A batch of headers arrived to one of our previous requests
   492  		var headers []*types.Header
   493  		if err := msg.Decode(&headers); err != nil {
   494  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   495  		}
   496  		// If no headers were received, but we're expencting a checkpoint header, consider it that
   497  		if len(headers) == 0 && p.syncDrop != nil {
   498  			// Stop the timer either way, decide later to drop or not
   499  			p.syncDrop.Stop()
   500  			p.syncDrop = nil
   501  
   502  			// If we're doing a fast sync, we must enforce the checkpoint block to avoid
   503  			// eclipse attacks. Unsynced nodes are welcome to connect after we're done
   504  			// joining the network
   505  			if atomic.LoadUint32(&pm.fastSync) == 1 {
   506  				p.Log().Warn("Dropping unsynced node during fast sync", "addr", p.RemoteAddr(), "type", p.Name())
   507  				return errors.New("unsynced node cannot serve fast sync")
   508  			}
   509  		}
   510  		// Filter out any explicitly requested headers, deliver the rest to the downloader
   511  		filter := len(headers) == 1
   512  		if filter {
   513  			// If it's a potential sync progress check, validate the content and advertised chain weight
   514  			if p.syncDrop != nil && headers[0].Number.Uint64() == pm.checkpointNumber {
   515  				// Disable the sync drop timer
   516  				p.syncDrop.Stop()
   517  				p.syncDrop = nil
   518  
   519  				// Validate the header and either drop the peer or continue
   520  				if headers[0].Hash() != pm.checkpointHash {
   521  					return errors.New("checkpoint hash mismatch")
   522  				}
   523  				return nil
   524  			}
   525  			// Otherwise if it's a whitelisted block, validate against the set
   526  			if want, ok := pm.whitelist[headers[0].Number.Uint64()]; ok {
   527  				if hash := headers[0].Hash(); want != hash {
   528  					p.Log().Info("Whitelist mismatch, dropping peer", "number", headers[0].Number.Uint64(), "hash", hash, "want", want)
   529  					return errors.New("whitelist block mismatch")
   530  				}
   531  				p.Log().Debug("Whitelist block verified", "number", headers[0].Number.Uint64(), "hash", want)
   532  			}
   533  			// Irrelevant of the fork checks, send the header to the fetcher just in case
   534  			headers = pm.blockFetcher.FilterHeaders(p.id, headers, time.Now())
   535  		}
   536  		if len(headers) > 0 || !filter {
   537  			err := pm.downloader.DeliverHeaders(p.id, headers)
   538  			if err != nil {
   539  				log.Debug("Failed to deliver headers", "err", err)
   540  			}
   541  		}
   542  
   543  	case msg.Code == GetBlockBodiesMsg:
   544  		// Decode the retrieval message
   545  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   546  		if _, err := msgStream.List(); err != nil {
   547  			return err
   548  		}
   549  		// Gather blocks until the fetch or network limits is reached
   550  		var (
   551  			hash   common.Hash
   552  			bytes  int
   553  			bodies []rlp.RawValue
   554  		)
   555  		for bytes < softResponseLimit && len(bodies) < downloader.MaxBlockFetch {
   556  			// Retrieve the hash of the next block
   557  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   558  				break
   559  			} else if err != nil {
   560  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   561  			}
   562  			// Retrieve the requested block body, stopping if enough was found
   563  			if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 {
   564  				bodies = append(bodies, data)
   565  				bytes += len(data)
   566  			}
   567  		}
   568  		return p.SendBlockBodiesRLP(bodies)
   569  
   570  	case msg.Code == BlockBodiesMsg:
   571  		// A batch of block bodies arrived to one of our previous requests
   572  		var request blockBodiesData
   573  		if err := msg.Decode(&request); err != nil {
   574  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   575  		}
   576  		// Deliver them all to the downloader for queuing
   577  		transactions := make([][]*types.Transaction, len(request))
   578  		uncles := make([][]*types.Header, len(request))
   579  
   580  		for i, body := range request {
   581  			transactions[i] = body.Transactions
   582  			uncles[i] = body.Uncles
   583  		}
   584  		// Filter out any explicitly requested bodies, deliver the rest to the downloader
   585  		filter := len(transactions) > 0 || len(uncles) > 0
   586  		if filter {
   587  			transactions, uncles = pm.blockFetcher.FilterBodies(p.id, transactions, uncles, time.Now())
   588  		}
   589  		if len(transactions) > 0 || len(uncles) > 0 || !filter {
   590  			err := pm.downloader.DeliverBodies(p.id, transactions, uncles)
   591  			if err != nil {
   592  				log.Debug("Failed to deliver bodies", "err", err)
   593  			}
   594  		}
   595  
   596  	case p.version >= xcb63 && msg.Code == GetNodeDataMsg:
   597  		// Decode the retrieval message
   598  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   599  		if _, err := msgStream.List(); err != nil {
   600  			return err
   601  		}
   602  		// Gather state data until the fetch or network limits is reached
   603  		var (
   604  			hash  common.Hash
   605  			bytes int
   606  			data  [][]byte
   607  		)
   608  		for bytes < softResponseLimit && len(data) < downloader.MaxStateFetch {
   609  			// Retrieve the hash of the next state entry
   610  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   611  				break
   612  			} else if err != nil {
   613  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   614  			}
   615  			// Retrieve the requested state entry, stopping if enough was found
   616  			// todo now the code and trienode is mixed in the protocol level,
   617  			// separate these two types.
   618  			if !pm.downloader.SyncBloomContains(hash[:]) {
   619  				// Only lookup the trie node if there's chance that we actually have it
   620  				continue
   621  			}
   622  			entry, err := pm.blockchain.TrieNode(hash)
   623  			if len(entry) == 0 || err != nil {
   624  				// Read the contract code with prefix only to save unnecessary lookups.
   625  				entry, err = pm.blockchain.ContractCodeWithPrefix(hash)
   626  			}
   627  			if err == nil && len(entry) > 0 {
   628  				data = append(data, entry)
   629  				bytes += len(entry)
   630  			}
   631  		}
   632  		return p.SendNodeData(data)
   633  
   634  	case p.version >= xcb63 && msg.Code == NodeDataMsg:
   635  		// A batch of node state data arrived to one of our previous requests
   636  		var data [][]byte
   637  		if err := msg.Decode(&data); err != nil {
   638  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   639  		}
   640  		// Deliver all to the downloader
   641  		if err := pm.downloader.DeliverNodeData(p.id, data); err != nil {
   642  			log.Debug("Failed to deliver node state data", "err", err)
   643  		}
   644  
   645  	case p.version >= xcb63 && msg.Code == GetReceiptsMsg:
   646  		// Decode the retrieval message
   647  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   648  		if _, err := msgStream.List(); err != nil {
   649  			return err
   650  		}
   651  		// Gather state data until the fetch or network limits is reached
   652  		var (
   653  			hash     common.Hash
   654  			bytes    int
   655  			receipts []rlp.RawValue
   656  		)
   657  		for bytes < softResponseLimit && len(receipts) < downloader.MaxReceiptFetch {
   658  			// Retrieve the hash of the next block
   659  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   660  				break
   661  			} else if err != nil {
   662  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   663  			}
   664  			// Retrieve the requested block's receipts, skipping if unknown to us
   665  			results := pm.blockchain.GetReceiptsByHash(hash)
   666  			if results == nil {
   667  				if header := pm.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
   668  					continue
   669  				}
   670  			}
   671  			// If known, encode and queue for response packet
   672  			if encoded, err := rlp.EncodeToBytes(results); err != nil {
   673  				log.Error("Failed to encode receipt", "err", err)
   674  			} else {
   675  				receipts = append(receipts, encoded)
   676  				bytes += len(encoded)
   677  			}
   678  		}
   679  		return p.SendReceiptsRLP(receipts)
   680  
   681  	case p.version >= xcb63 && msg.Code == ReceiptsMsg:
   682  		// A batch of receipts arrived to one of our previous requests
   683  		var receipts [][]*types.Receipt
   684  		if err := msg.Decode(&receipts); err != nil {
   685  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   686  		}
   687  		// Deliver all to the downloader
   688  		if err := pm.downloader.DeliverReceipts(p.id, receipts); err != nil {
   689  			log.Debug("Failed to deliver receipts", "err", err)
   690  		}
   691  
   692  	case msg.Code == NewBlockHashesMsg:
   693  		var announces newBlockHashesData
   694  		if err := msg.Decode(&announces); err != nil {
   695  			return errResp(ErrDecode, "%v: %v", msg, err)
   696  		}
   697  		// Mark the hashes as present at the remote node
   698  		for _, block := range announces {
   699  			p.MarkBlock(block.Hash)
   700  		}
   701  		// Schedule all the unknown hashes for retrieval
   702  		unknown := make(newBlockHashesData, 0, len(announces))
   703  		for _, block := range announces {
   704  			if !pm.blockchain.HasBlock(block.Hash, block.Number) {
   705  				unknown = append(unknown, block)
   706  			}
   707  		}
   708  		for _, block := range unknown {
   709  			pm.blockFetcher.Notify(p.id, block.Hash, block.Number, time.Now(), p.RequestOneHeader, p.RequestBodies)
   710  		}
   711  
   712  	case msg.Code == NewBlockMsg:
   713  		// Retrieve and decode the propagated block
   714  		var request newBlockData
   715  		if err := msg.Decode(&request); err != nil {
   716  			return errResp(ErrDecode, "%v: %v", msg, err)
   717  		}
   718  		if hash := types.CalcUncleHash(request.Block.Uncles()); hash != request.Block.UncleHash() {
   719  			log.Warn("Propagated block has invalid uncles", "have", hash, "exp", request.Block.UncleHash())
   720  			break // TODO(raisty): return error eventually, but wait a few releases
   721  		}
   722  		if hash := types.DeriveSha(request.Block.Transactions(), trie.NewStackTrie(nil)); hash != request.Block.TxHash() {
   723  			log.Warn("Propagated block has invalid body", "have", hash, "exp", request.Block.TxHash())
   724  			break // TODO(raisty): return error eventually, but wait a few releases
   725  		}
   726  		if err := request.sanityCheck(); err != nil {
   727  			return err
   728  		}
   729  		request.Block.ReceivedAt = msg.ReceivedAt
   730  		request.Block.ReceivedFrom = p
   731  
   732  		// Mark the peer as owning the block and schedule it for import
   733  		p.MarkBlock(request.Block.Hash())
   734  		pm.blockFetcher.Enqueue(p.id, request.Block)
   735  
   736  		// Assuming the block is importable by the peer, but possibly not yet done so,
   737  		// calculate the head hash and TD that the peer truly must have.
   738  		var (
   739  			trueHead = request.Block.ParentHash()
   740  			trueTD   = new(big.Int).Sub(request.TD, request.Block.Difficulty())
   741  		)
   742  		// Update the peer's total difficulty if better than the previous
   743  		if _, td := p.Head(); trueTD.Cmp(td) > 0 {
   744  			p.SetHead(trueHead, trueTD)
   745  			pm.chainSync.handlePeerEvent(p)
   746  		}
   747  
   748  	case msg.Code == NewPooledTransactionHashesMsg && p.version >= xcb65:
   749  		// New transaction announcement arrived, make sure we have
   750  		// a valid and fresh chain to handle them
   751  		if atomic.LoadUint32(&pm.acceptTxs) == 0 {
   752  			break
   753  		}
   754  		var hashes []common.Hash
   755  		if err := msg.Decode(&hashes); err != nil {
   756  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   757  		}
   758  		// Schedule all the unknown hashes for retrieval
   759  		for _, hash := range hashes {
   760  			p.MarkTransaction(hash)
   761  		}
   762  		pm.txFetcher.Notify(p.id, hashes)
   763  
   764  	case msg.Code == GetPooledTransactionsMsg && p.version >= xcb65:
   765  		// Decode the retrieval message
   766  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   767  		if _, err := msgStream.List(); err != nil {
   768  			return err
   769  		}
   770  		// Gather transactions until the fetch or network limits is reached
   771  		var (
   772  			hash   common.Hash
   773  			bytes  int
   774  			hashes []common.Hash
   775  			txs    []rlp.RawValue
   776  		)
   777  		for bytes < softResponseLimit {
   778  			// Retrieve the hash of the next block
   779  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   780  				break
   781  			} else if err != nil {
   782  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   783  			}
   784  			// Retrieve the requested transaction, skipping if unknown to us
   785  			tx := pm.txpool.Get(hash)
   786  			if tx == nil {
   787  				continue
   788  			}
   789  			// If known, encode and queue for response packet
   790  			if encoded, err := rlp.EncodeToBytes(tx); err != nil {
   791  				log.Error("Failed to encode transaction", "err", err)
   792  			} else {
   793  				hashes = append(hashes, hash)
   794  				txs = append(txs, encoded)
   795  				bytes += len(encoded)
   796  			}
   797  		}
   798  		return p.SendPooledTransactionsRLP(hashes, txs)
   799  
   800  	case msg.Code == TransactionMsg || (msg.Code == PooledTransactionsMsg && p.version >= xcb65):
   801  		// Transactions arrived, make sure we have a valid and fresh chain to handle them
   802  		if atomic.LoadUint32(&pm.acceptTxs) == 0 {
   803  			break
   804  		}
   805  		// Transactions can be processed, parse all of them and deliver to the pool
   806  		var txs []*types.Transaction
   807  		if err := msg.Decode(&txs); err != nil {
   808  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   809  		}
   810  		for i, tx := range txs {
   811  			// Validate and mark the remote transaction
   812  			if tx == nil {
   813  				return errResp(ErrDecode, "transaction %d is nil", i)
   814  			}
   815  			p.MarkTransaction(tx.Hash())
   816  		}
   817  		pm.txFetcher.Enqueue(p.id, txs, msg.Code == PooledTransactionsMsg)
   818  
   819  	default:
   820  		return errResp(ErrInvalidMsgCode, "%v", msg.Code)
   821  	}
   822  	return nil
   823  }
   824  
   825  // BroadcastBlock will either propagate a block to a subset of its peers, or
   826  // will only announce its availability (depending what's requested).
   827  func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
   828  	hash := block.Hash()
   829  	peers := pm.peers.PeersWithoutBlock(hash)
   830  
   831  	// If propagation is requested, send to a subset of the peer
   832  	if propagate {
   833  		// Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
   834  		var td *big.Int
   835  		if parent := pm.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
   836  			td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash(), block.NumberU64()-1))
   837  		} else {
   838  			log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
   839  			return
   840  		}
   841  		if pm.bttp {
   842  			// Prioritize sending to trusted peers
   843  			log.Debug("Broadcasting block to trusted peers", "number", block.Number(), "hash", hash)
   844  			for _, peer := range peers {
   845  				if peer.Peer.Info().Network.Trusted {
   846  					peer.AsyncSendNewBlock(block, td)
   847  				}
   848  			}
   849  			// Send to all remaining peers as well
   850  			for _, peer := range peers {
   851  				if !peer.Peer.Info().Network.Trusted {
   852  					peer.AsyncSendNewBlock(block, td)
   853  				}
   854  			}
   855  			log.Trace("Propagated block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
   856  			return
   857  		}
   858  
   859  		// Send the block to a subset of our peers
   860  		transfer := peers[:int(math.Sqrt(float64(len(peers))))]
   861  		for _, peer := range transfer {
   862  			peer.AsyncSendNewBlock(block, td)
   863  		}
   864  		log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
   865  		return
   866  	}
   867  	// Otherwise if the block is indeed in out own chain, announce it
   868  	if pm.blockchain.HasBlock(hash, block.NumberU64()) {
   869  		for _, peer := range peers {
   870  			peer.AsyncSendNewBlockHash(block)
   871  		}
   872  		log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
   873  	}
   874  }
   875  
   876  // BroadcastTransactions will propagate a batch of transactions to all peers which are not known to
   877  // already have the given transaction.
   878  func (pm *ProtocolManager) BroadcastTransactions(txs types.Transactions, propagate bool) {
   879  	var (
   880  		txset = make(map[*peer][]common.Hash)
   881  		annos = make(map[*peer][]common.Hash)
   882  	)
   883  	// Broadcast transactions to a batch of peers not knowing about it
   884  	if propagate {
   885  		for _, tx := range txs {
   886  			peers := pm.peers.PeersWithoutTx(tx.Hash())
   887  
   888  			// Send the block to a subset of our peers
   889  			transfer := peers[:int(math.Sqrt(float64(len(peers))))]
   890  			for _, peer := range transfer {
   891  				txset[peer] = append(txset[peer], tx.Hash())
   892  			}
   893  			log.Trace("Broadcast transaction", "hash", tx.Hash(), "recipients", len(peers))
   894  		}
   895  		for peer, hashes := range txset {
   896  			peer.AsyncSendTransactions(hashes)
   897  		}
   898  		return
   899  	}
   900  	// Otherwise only broadcast the announcement to peers
   901  	for _, tx := range txs {
   902  		peers := pm.peers.PeersWithoutTx(tx.Hash())
   903  		for _, peer := range peers {
   904  			annos[peer] = append(annos[peer], tx.Hash())
   905  		}
   906  	}
   907  	for peer, hashes := range annos {
   908  		if peer.version >= xcb65 {
   909  			peer.AsyncSendPooledTransactionHashes(hashes)
   910  		} else {
   911  			peer.AsyncSendTransactions(hashes)
   912  		}
   913  	}
   914  }
   915  
   916  // minedBroadcastLoop sends mined blocks to connected peers.
   917  func (pm *ProtocolManager) minedBroadcastLoop() {
   918  	defer pm.wg.Done()
   919  
   920  	for obj := range pm.minedBlockSub.Chan() {
   921  		if ev, ok := obj.Data.(core.NewMinedBlockEvent); ok {
   922  			pm.BroadcastBlock(ev.Block, true)  // First propagate block to peers
   923  			pm.BroadcastBlock(ev.Block, false) // Only then announce to the rest
   924  		}
   925  	}
   926  }
   927  
   928  // txBroadcastLoop announces new transactions to connected peers.
   929  func (pm *ProtocolManager) txBroadcastLoop() {
   930  	defer pm.wg.Done()
   931  
   932  	for {
   933  		select {
   934  		case event := <-pm.txsCh:
   935  			// For testing purpose only, disable propagation
   936  			if pm.broadcastTxAnnouncesOnly {
   937  				pm.BroadcastTransactions(event.Txs, false)
   938  				continue
   939  			}
   940  			pm.BroadcastTransactions(event.Txs, true)  // First propagate transactions to peers
   941  			pm.BroadcastTransactions(event.Txs, false) // Only then announce to the rest
   942  
   943  		case <-pm.txsSub.Err():
   944  			return
   945  		}
   946  	}
   947  }
   948  
   949  // NodeInfo represents a short summary of the Core sub-protocol metadata
   950  // known about the host peer.
   951  type NodeInfo struct {
   952  	Network    uint64              `json:"network"`    // Core network ID (Mainnet=1, Devin=3, Enterprise=4)
   953  	Difficulty *big.Int            `json:"difficulty"` // Total difficulty of the host's blockchain
   954  	Genesis    common.Hash         `json:"genesis"`    // SHA3 hash of the host's genesis block
   955  	Config     *params.ChainConfig `json:"config"`     // Chain configuration for the fork rules
   956  	Head       common.Hash         `json:"head"`       // SHA3 hash of the host's best owned block
   957  }
   958  
   959  // NodeInfo retrieves some protocol metadata about the running host node.
   960  func (pm *ProtocolManager) NodeInfo() *NodeInfo {
   961  	currentBlock := pm.blockchain.CurrentBlock()
   962  	return &NodeInfo{
   963  		Network:    pm.networkID,
   964  		Difficulty: pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64()),
   965  		Genesis:    pm.blockchain.Genesis().Hash(),
   966  		Config:     pm.blockchain.Config(),
   967  		Head:       currentBlock.Hash(),
   968  	}
   969  }