github.com/insight-chain/inb-go@v1.1.3-0.20191221022159-da049980ae38/eth/handler.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 eth
    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/insight-chain/inb-go/common"
    30  	"github.com/insight-chain/inb-go/consensus"
    31  	"github.com/insight-chain/inb-go/core"
    32  	"github.com/insight-chain/inb-go/core/types"
    33  	"github.com/insight-chain/inb-go/eth/downloader"
    34  	"github.com/insight-chain/inb-go/eth/fetcher"
    35  	"github.com/insight-chain/inb-go/ethdb"
    36  	"github.com/insight-chain/inb-go/event"
    37  	"github.com/insight-chain/inb-go/log"
    38  	"github.com/insight-chain/inb-go/p2p"
    39  	"github.com/insight-chain/inb-go/p2p/enode"
    40  	"github.com/insight-chain/inb-go/params"
    41  	"github.com/insight-chain/inb-go/rlp"
    42  )
    43  
    44  const (
    45  	softResponseLimit = 2 * 1024 * 1024 // Target maximum size of returned blocks, headers or node data.
    46  	estHeaderRlpSize  = 500             // Approximate size of an RLP encoded block header
    47  
    48  	// txChanSize is the size of channel listening to NewTxsEvent.
    49  	// The number is referenced from the size of tx pool.
    50  	txChanSize = 4096
    51  
    52  	// minimim number of peers to broadcast new blocks to
    53  	minBroadcastPeers = 4
    54  )
    55  
    56  //var (
    57  //	daoChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the DAO handshake challenge
    58  //)
    59  
    60  // errIncompatibleConfig is returned if the requested protocols and configs are
    61  // not compatible (low protocol version restrictions and high requirements).
    62  var errIncompatibleConfig = errors.New("incompatible configuration")
    63  
    64  func errResp(code errCode, format string, v ...interface{}) error {
    65  	return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...))
    66  }
    67  
    68  type ProtocolManager struct {
    69  	networkID uint64
    70  
    71  	fastSync  uint32 // Flag whether fast sync is enabled (gets disabled if we already have blocks)
    72  	acceptTxs uint32 // Flag whether we're considered synchronised (enables transaction processing)
    73  
    74  	txpool      txPool
    75  	blockchain  *core.BlockChain
    76  	chainconfig *params.ChainConfig
    77  	maxPeers    int
    78  
    79  	downloader *downloader.Downloader
    80  	fetcher    *fetcher.Fetcher
    81  	peers      *peerSet
    82  
    83  	SubProtocols []p2p.Protocol
    84  
    85  	eventMux      *event.TypeMux
    86  	txsCh         chan core.NewTxsEvent
    87  	txsSub        event.Subscription
    88  	minedBlockSub *event.TypeMuxSubscription
    89  
    90  	whitelist map[uint64]common.Hash
    91  
    92  	// channels for fetcher, syncer, txsyncLoop
    93  	newPeerCh   chan *peer
    94  	txsyncCh    chan *txsync
    95  	quitSync    chan struct{}
    96  	noMorePeers chan struct{}
    97  
    98  	// wait group is used for graceful shutdowns during downloading
    99  	// and processing
   100  	wg sync.WaitGroup
   101  }
   102  
   103  // NewProtocolManager returns a new Ethereum sub protocol manager. The Ethereum sub protocol manages peers capable
   104  // with the Ethereum network.
   105  func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, networkID uint64, mux *event.TypeMux, txpool txPool, engine consensus.Engine, blockchain *core.BlockChain, chaindb ethdb.Database, whitelist map[uint64]common.Hash) (*ProtocolManager, error) {
   106  	// Create the protocol manager with the base fields
   107  	manager := &ProtocolManager{
   108  		networkID:   networkID,
   109  		eventMux:    mux,
   110  		txpool:      txpool,
   111  		blockchain:  blockchain,
   112  		chainconfig: config,
   113  		peers:       newPeerSet(),
   114  		whitelist:   whitelist,
   115  		newPeerCh:   make(chan *peer),
   116  		noMorePeers: make(chan struct{}),
   117  		txsyncCh:    make(chan *txsync),
   118  		quitSync:    make(chan struct{}),
   119  	}
   120  	// Figure out whether to allow fast sync or not
   121  	if mode == downloader.FastSync && blockchain.CurrentBlock().NumberU64() > 0 {
   122  		log.Warn("Blockchain not empty, fast sync disabled")
   123  		mode = downloader.FullSync
   124  	}
   125  	if mode == downloader.FastSync {
   126  		manager.fastSync = uint32(1)
   127  	}
   128  	// Initiate a sub-protocol for every implemented version we can handle
   129  	manager.SubProtocols = make([]p2p.Protocol, 0, len(ProtocolVersions))
   130  	for i, version := range ProtocolVersions {
   131  		// Skip protocol version if incompatible with the mode of operation
   132  		if mode == downloader.FastSync && version < eth63 {
   133  			continue
   134  		}
   135  		// Compatible; initialise the sub-protocol
   136  		version := version // Closure for the run
   137  		manager.SubProtocols = append(manager.SubProtocols, p2p.Protocol{
   138  			Name:    ProtocolName,
   139  			Version: version,
   140  			Length:  ProtocolLengths[i],
   141  			Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
   142  				peer := manager.newPeer(int(version), p, rw)
   143  				select {
   144  				case manager.newPeerCh <- peer:
   145  					manager.wg.Add(1)
   146  					defer manager.wg.Done()
   147  					return manager.handle(peer)
   148  				case <-manager.quitSync:
   149  					return p2p.DiscQuitting
   150  				}
   151  			},
   152  			NodeInfo: func() interface{} {
   153  				return manager.NodeInfo()
   154  			},
   155  			PeerInfo: func(id enode.ID) interface{} {
   156  				if p := manager.peers.Peer(fmt.Sprintf("%x", id[:8])); p != nil {
   157  					return p.Info()
   158  				}
   159  				return nil
   160  			},
   161  		})
   162  	}
   163  	if len(manager.SubProtocols) == 0 {
   164  		return nil, errIncompatibleConfig
   165  	}
   166  	// Construct the different synchronisation mechanisms
   167  	manager.downloader = downloader.New(mode, chaindb, manager.eventMux, blockchain, nil, manager.removePeer)
   168  
   169  	validator := func(header *types.Header) error {
   170  		return engine.VerifyHeader(blockchain, header, true)
   171  	}
   172  	heighter := func() uint64 {
   173  		return blockchain.CurrentBlock().NumberU64()
   174  	}
   175  	inserter := func(blocks types.Blocks) (int, error) {
   176  		// If fast sync is running, deny importing weird blocks
   177  		if atomic.LoadUint32(&manager.fastSync) == 1 {
   178  			log.Warn("Discarded bad propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
   179  			return 0, nil
   180  		}
   181  		atomic.StoreUint32(&manager.acceptTxs, 1) // Mark initial sync done on any fetcher import
   182  		return manager.blockchain.InsertChain(blocks)
   183  	}
   184  	manager.fetcher = fetcher.New(blockchain.GetBlockByHash, validator, manager.BroadcastBlock, heighter, inserter, manager.removePeer)
   185  
   186  	return manager, nil
   187  }
   188  
   189  func (pm *ProtocolManager) removePeer(id string) {
   190  	// Short circuit if the peer was already removed
   191  	peer := pm.peers.Peer(id)
   192  	if peer == nil {
   193  		return
   194  	}
   195  	log.Debug("Removing Ethereum peer", "peer", id)
   196  
   197  	// Unregister the peer from the downloader and Ethereum peer set
   198  	pm.downloader.UnregisterPeer(id)
   199  	if err := pm.peers.Unregister(id); err != nil {
   200  		log.Error("Peer removal failed", "peer", id, "err", err)
   201  	}
   202  	// Hard disconnect at the networking layer
   203  	if peer != nil {
   204  		peer.Peer.Disconnect(p2p.DiscUselessPeer)
   205  	}
   206  }
   207  
   208  func (pm *ProtocolManager) Start(maxPeers int) {
   209  	pm.maxPeers = maxPeers
   210  
   211  	// broadcast transactions
   212  	pm.txsCh = make(chan core.NewTxsEvent, txChanSize)
   213  	pm.txsSub = pm.txpool.SubscribeNewTxsEvent(pm.txsCh)
   214  	go pm.txBroadcastLoop()
   215  
   216  	// broadcast mined blocks
   217  	pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{})
   218  	go pm.minedBroadcastLoop()
   219  
   220  	// start sync handlers
   221  	go pm.syncer()
   222  	go pm.txsyncLoop()
   223  }
   224  
   225  func (pm *ProtocolManager) Stop() {
   226  	log.Info("Stopping Ethereum protocol")
   227  
   228  	pm.txsSub.Unsubscribe()        // quits txBroadcastLoop
   229  	pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
   230  
   231  	// Quit the sync loop.
   232  	// After this send has completed, no new peers will be accepted.
   233  	pm.noMorePeers <- struct{}{}
   234  
   235  	// Quit fetcher, txsyncLoop.
   236  	close(pm.quitSync)
   237  
   238  	// Disconnect existing sessions.
   239  	// This also closes the gate for any new registrations on the peer set.
   240  	// sessions which are already established but not added to pm.peers yet
   241  	// will exit when they try to register.
   242  	pm.peers.Close()
   243  
   244  	// Wait for all peer handler goroutines and the loops to come down.
   245  	pm.wg.Wait()
   246  
   247  	log.Info("Ethereum protocol stopped")
   248  }
   249  
   250  func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
   251  	return newPeer(pv, p, newMeteredMsgWriter(rw))
   252  }
   253  
   254  // handle is the callback invoked to manage the life cycle of an eth peer. When
   255  // this function terminates, the peer is disconnected.
   256  func (pm *ProtocolManager) handle(p *peer) error {
   257  	// Ignore maxPeers if this is a trusted peer
   258  	if pm.peers.Len() >= pm.maxPeers && !p.Peer.Info().Network.Trusted {
   259  		return p2p.DiscTooManyPeers
   260  	}
   261  	p.Log().Debug("Ethereum peer connected", "name", p.Name())
   262  
   263  	// Execute the Ethereum handshake
   264  	var (
   265  		genesis = pm.blockchain.Genesis()
   266  		head    = pm.blockchain.CurrentHeader()
   267  		hash    = head.Hash()
   268  		number  = head.Number.Uint64()
   269  		td      = pm.blockchain.GetTd(hash, number)
   270  	)
   271  	if err := p.Handshake(pm.networkID, td, hash, genesis.Hash()); err != nil {
   272  		p.Log().Debug("Ethereum handshake failed", "err", err)
   273  		return err
   274  	}
   275  	if rw, ok := p.rw.(*meteredMsgReadWriter); ok {
   276  		rw.Init(p.version)
   277  	}
   278  	// Register the peer locally
   279  	if err := pm.peers.Register(p); err != nil {
   280  		p.Log().Error("Ethereum peer registration failed", "err", err)
   281  		return err
   282  	}
   283  	defer pm.removePeer(p.id)
   284  
   285  	// Register the peer in the downloader. If the downloader considers it banned, we disconnect
   286  	if err := pm.downloader.RegisterPeer(p.id, p.version, p); err != nil {
   287  		return err
   288  	}
   289  	// Propagate existing transactions. new transactions appearing
   290  	// after this will be sent via broadcasts.
   291  	pm.syncTransactions(p)
   292  
   293  	// If we're DAO hard-fork aware, validate any remote peer with regard to the hard-fork
   294  	//if daoBlock := pm.chainconfig.DAOForkBlock; daoBlock != nil {
   295  	//	// Request the peer's DAO fork header for extra-data validation
   296  	//	if err := p.RequestHeadersByNumber(daoBlock.Uint64(), 1, 0, false); err != nil {
   297  	//		return err
   298  	//	}
   299  	//	// Start a timer to disconnect if the peer doesn't reply in time
   300  	//	p.forkDrop = time.AfterFunc(daoChallengeTimeout, func() {
   301  	//		p.Log().Debug("Timed out DAO fork-check, dropping")
   302  	//		pm.removePeer(p.id)
   303  	//	})
   304  	//	// Make sure it's cleaned up if the peer dies off
   305  	//	defer func() {
   306  	//		if p.forkDrop != nil {
   307  	//			p.forkDrop.Stop()
   308  	//			p.forkDrop = nil
   309  	//		}
   310  	//	}()
   311  	//}
   312  	// If we have any explicit whitelist block hashes, request them
   313  	for number := range pm.whitelist {
   314  		if err := p.RequestHeadersByNumber(number, 1, 0, false); err != nil {
   315  			return err
   316  		}
   317  	}
   318  	// Handle incoming messages until the connection is torn down
   319  	for {
   320  		if err := pm.handleMsg(p); err != nil {
   321  			p.Log().Debug("Ethereum message handling failed", "err", err)
   322  			return err
   323  		}
   324  	}
   325  }
   326  
   327  // handleMsg is invoked whenever an inbound message is received from a remote
   328  // peer. The remote connection is torn down upon returning any error.
   329  func (pm *ProtocolManager) handleMsg(p *peer) error {
   330  	// Read the next message from the remote peer, and ensure it's fully consumed
   331  	msg, err := p.rw.ReadMsg()
   332  	if err != nil {
   333  		return err
   334  	}
   335  	if msg.Size > ProtocolMaxMsgSize {
   336  		return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
   337  	}
   338  	defer msg.Discard()
   339  
   340  	// Handle the message depending on its contents
   341  	switch {
   342  	case msg.Code == StatusMsg:
   343  		// Status messages should never arrive after the handshake
   344  		return errResp(ErrExtraStatusMsg, "uncontrolled status message")
   345  
   346  	// Block header query, collect the requested headers and reply
   347  	case msg.Code == GetBlockHeadersMsg:
   348  		// Decode the complex header query
   349  		var query getBlockHeadersData
   350  		if err := msg.Decode(&query); err != nil {
   351  			return errResp(ErrDecode, "%v: %v", msg, err)
   352  		}
   353  		hashMode := query.Origin.Hash != (common.Hash{})
   354  		first := true
   355  		maxNonCanonical := uint64(100)
   356  
   357  		// Gather headers until the fetch or network limits is reached
   358  		var (
   359  			bytes   common.StorageSize
   360  			headers []*types.Header
   361  			unknown bool
   362  		)
   363  		for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch {
   364  			// Retrieve the next header satisfying the query
   365  			var origin *types.Header
   366  			if hashMode {
   367  				if first {
   368  					first = false
   369  					origin = pm.blockchain.GetHeaderByHash(query.Origin.Hash)
   370  					if origin != nil {
   371  						query.Origin.Number = origin.Number.Uint64()
   372  					}
   373  				} else {
   374  					origin = pm.blockchain.GetHeader(query.Origin.Hash, query.Origin.Number)
   375  				}
   376  			} else {
   377  				origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number)
   378  			}
   379  			if origin == nil {
   380  				break
   381  			}
   382  			headers = append(headers, origin)
   383  			bytes += estHeaderRlpSize
   384  
   385  			// Advance to the next header of the query
   386  			switch {
   387  			case hashMode && query.Reverse:
   388  				// Hash based traversal towards the genesis block
   389  				ancestor := query.Skip + 1
   390  				if ancestor == 0 {
   391  					unknown = true
   392  				} else {
   393  					query.Origin.Hash, query.Origin.Number = pm.blockchain.GetAncestor(query.Origin.Hash, query.Origin.Number, ancestor, &maxNonCanonical)
   394  					unknown = (query.Origin.Hash == common.Hash{})
   395  				}
   396  			case hashMode && !query.Reverse:
   397  				// Hash based traversal towards the leaf block
   398  				var (
   399  					current = origin.Number.Uint64()
   400  					next    = current + query.Skip + 1
   401  				)
   402  				if next <= current {
   403  					infos, _ := json.MarshalIndent(p.Peer.Info(), "", "  ")
   404  					p.Log().Warn("GetBlockHeaders skip overflow attack", "current", current, "skip", query.Skip, "next", next, "attacker", infos)
   405  					unknown = true
   406  				} else {
   407  					if header := pm.blockchain.GetHeaderByNumber(next); header != nil {
   408  						nextHash := header.Hash()
   409  						expOldHash, _ := pm.blockchain.GetAncestor(nextHash, next, query.Skip+1, &maxNonCanonical)
   410  						if expOldHash == query.Origin.Hash {
   411  							query.Origin.Hash, query.Origin.Number = nextHash, next
   412  						} else {
   413  							unknown = true
   414  						}
   415  					} else {
   416  						unknown = true
   417  					}
   418  				}
   419  			case query.Reverse:
   420  				// Number based traversal towards the genesis block
   421  				if query.Origin.Number >= query.Skip+1 {
   422  					query.Origin.Number -= query.Skip + 1
   423  				} else {
   424  					unknown = true
   425  				}
   426  
   427  			case !query.Reverse:
   428  				// Number based traversal towards the leaf block
   429  				query.Origin.Number += query.Skip + 1
   430  			}
   431  		}
   432  		return p.SendBlockHeaders(headers)
   433  
   434  	case msg.Code == BlockHeadersMsg:
   435  		// A batch of headers arrived to one of our previous requests
   436  		var headers []*types.Header
   437  		if err := msg.Decode(&headers); err != nil {
   438  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   439  		}
   440  		// If no headers were received, but we're expending a DAO fork check, maybe it's that
   441  		//if len(headers) == 0 && p.forkDrop != nil {
   442  		//	// Possibly an empty reply to the fork header checks, sanity check TDs
   443  		//	verifyDAO := true
   444  		//
   445  		//	// If we already have a DAO header, we can check the peer's TD against it. If
   446  		//	// the peer's ahead of this, it too must have a reply to the DAO check
   447  		//	if daoHeader := pm.blockchain.GetHeaderByNumber(pm.chainconfig.DAOForkBlock.Uint64()); daoHeader != nil {
   448  		//		if _, td := p.Head(); td.Cmp(pm.blockchain.GetTd(daoHeader.Hash(), daoHeader.Number.Uint64())) >= 0 {
   449  		//			verifyDAO = false
   450  		//		}
   451  		//	}
   452  		//	// If we're seemingly on the same chain, disable the drop timer
   453  		//	if verifyDAO {
   454  		//		p.Log().Debug("Seems to be on the same side of the DAO fork")
   455  		//		p.forkDrop.Stop()
   456  		//		p.forkDrop = nil
   457  		//		return nil
   458  		//	}
   459  		//}
   460  		// Filter out any explicitly requested headers, deliver the rest to the downloader
   461  		filter := len(headers) == 1
   462  		if filter {
   463  			// If it's a potential DAO fork check, validate against the rules
   464  			//if p.forkDrop != nil && pm.chainconfig.DAOForkBlock.Cmp(headers[0].Number) == 0 {
   465  			//	// Disable the fork drop timer
   466  			//	p.forkDrop.Stop()
   467  			//	p.forkDrop = nil
   468  			//
   469  			//	// Validate the header and either drop the peer or continue
   470  			//	//if err := misc.VerifyDAOHeaderExtraData(pm.chainconfig, headers[0]); err != nil {
   471  			//	//	p.Log().Debug("Verified to be on the other side of the DAO fork, dropping")
   472  			//	//	return err
   473  			//	//}
   474  			//	p.Log().Debug("Verified to be on the same side of the DAO fork")
   475  			//	return nil
   476  			//}
   477  			// Otherwise if it's a whitelisted block, validate against the set
   478  			if want, ok := pm.whitelist[headers[0].Number.Uint64()]; ok {
   479  				if hash := headers[0].Hash(); want != hash {
   480  					p.Log().Info("Whitelist mismatch, dropping peer", "number", headers[0].Number.Uint64(), "hash", hash, "want", want)
   481  					return errors.New("whitelist block mismatch")
   482  				}
   483  				p.Log().Debug("Whitelist block verified", "number", headers[0].Number.Uint64(), "hash", want)
   484  			}
   485  			// Irrelevant of the fork checks, send the header to the fetcher just in case
   486  			headers = pm.fetcher.FilterHeaders(p.id, headers, time.Now())
   487  		}
   488  		if len(headers) > 0 || !filter {
   489  			err := pm.downloader.DeliverHeaders(p.id, headers)
   490  			if err != nil {
   491  				log.Debug("Failed to deliver headers", "err", err)
   492  			}
   493  		}
   494  
   495  	case msg.Code == GetBlockBodiesMsg:
   496  		// Decode the retrieval message
   497  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   498  		if _, err := msgStream.List(); err != nil {
   499  			return err
   500  		}
   501  		// Gather blocks until the fetch or network limits is reached
   502  		var (
   503  			hash   common.Hash
   504  			bytes  int
   505  			bodies []rlp.RawValue
   506  		)
   507  		for bytes < softResponseLimit && len(bodies) < downloader.MaxBlockFetch {
   508  			// Retrieve the hash of the next block
   509  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   510  				break
   511  			} else if err != nil {
   512  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   513  			}
   514  			// Retrieve the requested block body, stopping if enough was found
   515  			if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 {
   516  				bodies = append(bodies, data)
   517  				bytes += len(data)
   518  			}
   519  		}
   520  		return p.SendBlockBodiesRLP(bodies)
   521  
   522  	case msg.Code == BlockBodiesMsg:
   523  		// A batch of block bodies arrived to one of our previous requests
   524  		var request blockBodiesData
   525  		if err := msg.Decode(&request); err != nil {
   526  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   527  		}
   528  		// Deliver them all to the downloader for queuing
   529  		transactions := make([][]*types.Transaction, len(request))
   530  		uncles := make([][]*types.Header, len(request))
   531  
   532  		for i, body := range request {
   533  			transactions[i] = body.Transactions
   534  			uncles[i] = body.Uncles
   535  		}
   536  		// Filter out any explicitly requested bodies, deliver the rest to the downloader
   537  		filter := len(transactions) > 0 || len(uncles) > 0
   538  		if filter {
   539  			transactions, uncles = pm.fetcher.FilterBodies(p.id, transactions, uncles, time.Now())
   540  		}
   541  		if len(transactions) > 0 || len(uncles) > 0 || !filter {
   542  			err := pm.downloader.DeliverBodies(p.id, transactions, uncles)
   543  			if err != nil {
   544  				log.Debug("Failed to deliver bodies", "err", err)
   545  			}
   546  		}
   547  
   548  	case p.version >= eth63 && msg.Code == GetNodeDataMsg:
   549  		// Decode the retrieval message
   550  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   551  		if _, err := msgStream.List(); err != nil {
   552  			return err
   553  		}
   554  		// Gather state data until the fetch or network limits is reached
   555  		var (
   556  			hash  common.Hash
   557  			bytes int
   558  			data  [][]byte
   559  		)
   560  		for bytes < softResponseLimit && len(data) < downloader.MaxStateFetch {
   561  			// Retrieve the hash of the next state entry
   562  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   563  				break
   564  			} else if err != nil {
   565  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   566  			}
   567  			// Retrieve the requested state entry, stopping if enough was found
   568  			if entry, err := pm.blockchain.TrieNode(hash); err == nil {
   569  				data = append(data, entry)
   570  				bytes += len(entry)
   571  			}
   572  		}
   573  		return p.SendNodeData(data)
   574  
   575  	case p.version >= eth63 && msg.Code == NodeDataMsg:
   576  		// A batch of node state data arrived to one of our previous requests
   577  		var data [][]byte
   578  		if err := msg.Decode(&data); err != nil {
   579  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   580  		}
   581  		// Deliver all to the downloader
   582  		if err := pm.downloader.DeliverNodeData(p.id, data); err != nil {
   583  			log.Debug("Failed to deliver node state data", "err", err)
   584  		}
   585  
   586  	case p.version >= eth63 && msg.Code == GetReceiptsMsg:
   587  		// Decode the retrieval message
   588  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   589  		if _, err := msgStream.List(); err != nil {
   590  			return err
   591  		}
   592  		// Gather state data until the fetch or network limits is reached
   593  		var (
   594  			hash     common.Hash
   595  			bytes    int
   596  			receipts []rlp.RawValue
   597  		)
   598  		for bytes < softResponseLimit && len(receipts) < downloader.MaxReceiptFetch {
   599  			// Retrieve the hash of the next block
   600  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   601  				break
   602  			} else if err != nil {
   603  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   604  			}
   605  			// Retrieve the requested block's receipts, skipping if unknown to us
   606  			results := pm.blockchain.GetReceiptsByHash(hash)
   607  			if results == nil {
   608  				if header := pm.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
   609  					continue
   610  				}
   611  			}
   612  			// If known, encode and queue for response packet
   613  			if encoded, err := rlp.EncodeToBytes(results); err != nil {
   614  				log.Error("Failed to encode receipt", "err", err)
   615  			} else {
   616  				receipts = append(receipts, encoded)
   617  				bytes += len(encoded)
   618  			}
   619  		}
   620  		return p.SendReceiptsRLP(receipts)
   621  
   622  	case p.version >= eth63 && msg.Code == ReceiptsMsg:
   623  		// A batch of receipts arrived to one of our previous requests
   624  		var receipts [][]*types.Receipt
   625  		if err := msg.Decode(&receipts); err != nil {
   626  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   627  		}
   628  		// Deliver all to the downloader
   629  		if err := pm.downloader.DeliverReceipts(p.id, receipts); err != nil {
   630  			log.Debug("Failed to deliver receipts", "err", err)
   631  		}
   632  
   633  	case msg.Code == NewBlockHashesMsg:
   634  		var announces newBlockHashesData
   635  		if err := msg.Decode(&announces); err != nil {
   636  			return errResp(ErrDecode, "%v: %v", msg, err)
   637  		}
   638  		// Mark the hashes as present at the remote node
   639  		for _, block := range announces {
   640  			p.MarkBlock(block.Hash)
   641  		}
   642  		// Schedule all the unknown hashes for retrieval
   643  		unknown := make(newBlockHashesData, 0, len(announces))
   644  		for _, block := range announces {
   645  			if !pm.blockchain.HasBlock(block.Hash, block.Number) {
   646  				unknown = append(unknown, block)
   647  			}
   648  		}
   649  		for _, block := range unknown {
   650  			pm.fetcher.Notify(p.id, block.Hash, block.Number, time.Now(), p.RequestOneHeader, p.RequestBodies)
   651  		}
   652  
   653  	case msg.Code == NewBlockMsg:
   654  		// Retrieve and decode the propagated block
   655  		var request newBlockData
   656  		if err := msg.Decode(&request); err != nil {
   657  			return errResp(ErrDecode, "%v: %v", msg, err)
   658  		}
   659  		request.Block.ReceivedAt = msg.ReceivedAt
   660  		request.Block.ReceivedFrom = p
   661  
   662  		// Mark the peer as owning the block and schedule it for import
   663  		p.MarkBlock(request.Block.Hash())
   664  		pm.fetcher.Enqueue(p.id, request.Block)
   665  
   666  		// Assuming the block is importable by the peer, but possibly not yet done so,
   667  		// calculate the head hash and TD that the peer truly must have.
   668  		var (
   669  			trueHead = request.Block.ParentHash()
   670  			trueTD   = new(big.Int).Sub(request.TD, request.Block.Difficulty())
   671  		)
   672  		// Update the peer's total difficulty if better than the previous
   673  		if _, td := p.Head(); trueTD.Cmp(td) > 0 {
   674  			p.SetHead(trueHead, trueTD)
   675  
   676  			// Schedule a sync if above ours. Note, this will not fire a sync for a gap of
   677  			// a single block (as the true TD is below the propagated block), however this
   678  			// scenario should easily be covered by the fetcher.
   679  			currentBlock := pm.blockchain.CurrentBlock()
   680  			if trueTD.Cmp(pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64())) > 0 {
   681  				go pm.synchronise(p)
   682  			}
   683  		}
   684  
   685  	case msg.Code == TxMsg:
   686  		// Transactions arrived, make sure we have a valid and fresh chain to handle them
   687  		if atomic.LoadUint32(&pm.acceptTxs) == 0 {
   688  			break
   689  		}
   690  		// Transactions can be processed, parse all of them and deliver to the pool
   691  		var txs []*types.Transaction
   692  		if err := msg.Decode(&txs); err != nil {
   693  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   694  		}
   695  		for i, tx := range txs {
   696  			// Validate and mark the remote transaction
   697  			if tx == nil {
   698  				return errResp(ErrDecode, "transaction %d is nil", i)
   699  			}
   700  			p.MarkTransaction(tx.Hash())
   701  		}
   702  		pm.txpool.AddRemotes(txs)
   703  
   704  	default:
   705  		return errResp(ErrInvalidMsgCode, "%v", msg.Code)
   706  	}
   707  	return nil
   708  }
   709  
   710  // BroadcastBlock will either propagate a block to a subset of it's peers, or
   711  // will only announce it's availability (depending what's requested).
   712  func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
   713  	hash := block.Hash()
   714  	peers := pm.peers.PeersWithoutBlock(hash)
   715  
   716  	// If propagation is requested, send to a subset of the peer
   717  	if propagate {
   718  		// Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
   719  		var td *big.Int
   720  		if parent := pm.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
   721  			td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash(), block.NumberU64()-1))
   722  		} else {
   723  			log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
   724  			return
   725  		}
   726  		// Send the block to a subset of our peers
   727  		transferLen := int(math.Sqrt(float64(len(peers))))
   728  		if transferLen < minBroadcastPeers {
   729  			transferLen = minBroadcastPeers
   730  		}
   731  		if transferLen > len(peers) {
   732  			transferLen = len(peers)
   733  		}
   734  		transfer := peers[:transferLen]
   735  		for _, peer := range transfer {
   736  			peer.AsyncSendNewBlock(block, td)
   737  		}
   738  		log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
   739  		return
   740  	}
   741  	// Otherwise if the block is indeed in out own chain, announce it
   742  	if pm.blockchain.HasBlock(hash, block.NumberU64()) {
   743  		for _, peer := range peers {
   744  			peer.AsyncSendNewBlockHash(block)
   745  		}
   746  		log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
   747  	}
   748  }
   749  
   750  // BroadcastTxs will propagate a batch of transactions to all peers which are not known to
   751  // already have the given transaction.
   752  func (pm *ProtocolManager) BroadcastTxs(txs types.Transactions) {
   753  	var txset = make(map[*peer]types.Transactions)
   754  
   755  	// Broadcast transactions to a batch of peers not knowing about it
   756  	for _, tx := range txs {
   757  		peers := pm.peers.PeersWithoutTx(tx.Hash())
   758  		for _, peer := range peers {
   759  			txset[peer] = append(txset[peer], tx)
   760  		}
   761  		log.Trace("Broadcast transaction", "hash", tx.Hash(), "recipients", len(peers))
   762  	}
   763  	// FIXME include this again: peers = peers[:int(math.Sqrt(float64(len(peers))))]
   764  	for peer, txs := range txset {
   765  		peer.AsyncSendTransactions(txs)
   766  	}
   767  }
   768  
   769  // Mined broadcast loop
   770  func (pm *ProtocolManager) minedBroadcastLoop() {
   771  	// automatically stops if unsubscribe
   772  	for obj := range pm.minedBlockSub.Chan() {
   773  		if ev, ok := obj.Data.(core.NewMinedBlockEvent); ok {
   774  			pm.BroadcastBlock(ev.Block, true)  // First propagate block to peers
   775  			pm.BroadcastBlock(ev.Block, false) // Only then announce to the rest
   776  		}
   777  	}
   778  }
   779  
   780  func (pm *ProtocolManager) txBroadcastLoop() {
   781  	for {
   782  		select {
   783  		case event := <-pm.txsCh:
   784  			pm.BroadcastTxs(event.Txs)
   785  
   786  		// Err() channel will be closed when unsubscribing.
   787  		case <-pm.txsSub.Err():
   788  			return
   789  		}
   790  	}
   791  }
   792  
   793  // NodeInfo represents a short summary of the Ethereum sub-protocol metadata
   794  // known about the host peer.
   795  type NodeInfo struct {
   796  	Network    uint64              `json:"network"`    // Ethereum network ID (1=Frontier, 2=Morden, Ropsten=3, Rinkeby=4)
   797  	Difficulty *big.Int            `json:"difficulty"` // Total difficulty of the host's blockchain
   798  	Genesis    common.Hash         `json:"genesis"`    // SHA3 hash of the host's genesis block
   799  	Config     *params.ChainConfig `json:"config"`     // Chain configuration for the fork rules
   800  	Head       common.Hash         `json:"head"`       // SHA3 hash of the host's best owned block
   801  }
   802  
   803  // NodeInfo retrieves some protocol metadata about the running host node.
   804  func (pm *ProtocolManager) NodeInfo() *NodeInfo {
   805  	currentBlock := pm.blockchain.CurrentBlock()
   806  	return &NodeInfo{
   807  		Network:    pm.networkID,
   808  		Difficulty: pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64()),
   809  		Genesis:    pm.blockchain.Genesis().Hash(),
   810  		Config:     pm.blockchain.Config(),
   811  		Head:       currentBlock.Hash(),
   812  	}
   813  }