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