github.com/ebakus/go-ebakus@v1.0.5-0.20200520105415-dbccef9ec421/eth/handler.go (about)

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