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