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