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