2015-07-07 00:54:22 +00:00
|
|
|
// Copyright 2015 The go-ethereum Authors
|
2015-07-22 16:48:40 +00:00
|
|
|
// This file is part of the go-ethereum library.
|
2015-07-07 00:54:22 +00:00
|
|
|
//
|
2015-07-23 16:35:11 +00:00
|
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
2015-07-07 00:54:22 +00:00
|
|
|
// it under the terms of the GNU Lesser General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
2015-07-22 16:48:40 +00:00
|
|
|
// The go-ethereum library is distributed in the hope that it will be useful,
|
2015-07-07 00:54:22 +00:00
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
2015-07-22 16:48:40 +00:00
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
2015-07-07 00:54:22 +00:00
|
|
|
// GNU Lesser General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Lesser General Public License
|
2015-07-22 16:48:40 +00:00
|
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
2015-07-07 00:54:22 +00:00
|
|
|
|
2015-04-17 23:11:09 +00:00
|
|
|
package eth
|
|
|
|
|
|
|
|
import (
|
2016-10-05 13:31:48 +00:00
|
|
|
"encoding/json"
|
2015-09-01 14:35:14 +00:00
|
|
|
"errors"
|
2015-04-17 23:11:09 +00:00
|
|
|
"fmt"
|
2015-06-04 15:46:07 +00:00
|
|
|
"math"
|
2015-07-09 10:55:06 +00:00
|
|
|
"math/big"
|
2015-04-17 23:11:09 +00:00
|
|
|
"sync"
|
2016-05-17 11:17:20 +00:00
|
|
|
"sync/atomic"
|
2015-04-24 12:40:32 +00:00
|
|
|
"time"
|
2015-04-17 23:11:09 +00:00
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/common"
|
2015-04-18 00:21:07 +00:00
|
|
|
"github.com/ethereum/go-ethereum/core"
|
2015-04-17 23:11:09 +00:00
|
|
|
"github.com/ethereum/go-ethereum/core/types"
|
|
|
|
"github.com/ethereum/go-ethereum/eth/downloader"
|
2015-06-17 13:53:28 +00:00
|
|
|
"github.com/ethereum/go-ethereum/eth/fetcher"
|
2015-09-14 07:35:57 +00:00
|
|
|
"github.com/ethereum/go-ethereum/ethdb"
|
2015-04-22 15:56:06 +00:00
|
|
|
"github.com/ethereum/go-ethereum/event"
|
2015-04-17 23:11:09 +00:00
|
|
|
"github.com/ethereum/go-ethereum/logger"
|
|
|
|
"github.com/ethereum/go-ethereum/logger/glog"
|
|
|
|
"github.com/ethereum/go-ethereum/p2p"
|
2015-10-27 13:10:30 +00:00
|
|
|
"github.com/ethereum/go-ethereum/p2p/discover"
|
2015-06-19 07:07:37 +00:00
|
|
|
"github.com/ethereum/go-ethereum/pow"
|
2015-04-17 23:11:09 +00:00
|
|
|
"github.com/ethereum/go-ethereum/rlp"
|
|
|
|
)
|
|
|
|
|
2015-09-07 17:43:01 +00:00
|
|
|
const (
|
|
|
|
softResponseLimit = 2 * 1024 * 1024 // Target maximum size of returned blocks, headers or node data.
|
|
|
|
estHeaderRlpSize = 500 // Approximate size of an RLP encoded block header
|
|
|
|
)
|
2015-06-09 10:00:41 +00:00
|
|
|
|
2016-07-08 17:59:11 +00:00
|
|
|
var (
|
|
|
|
daoChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the DAO handshake challenge
|
|
|
|
)
|
|
|
|
|
2015-09-01 14:35:14 +00:00
|
|
|
// errIncompatibleConfig is returned if the requested protocols and configs are
|
|
|
|
// not compatible (low protocol version restrictions and high requirements).
|
|
|
|
var errIncompatibleConfig = errors.New("incompatible configuration")
|
|
|
|
|
2015-04-17 23:11:09 +00:00
|
|
|
func errResp(code errCode, format string, v ...interface{}) error {
|
|
|
|
return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...))
|
|
|
|
}
|
|
|
|
|
2015-04-18 00:21:07 +00:00
|
|
|
type ProtocolManager struct {
|
2015-10-27 13:10:30 +00:00
|
|
|
networkId int
|
|
|
|
|
2016-06-02 12:54:07 +00:00
|
|
|
fastSync uint32 // Flag whether fast sync is enabled (gets disabled if we already have blocks)
|
|
|
|
synced uint32 // Flag whether we're considered synchronised (enables transaction processing)
|
|
|
|
|
2016-07-08 17:59:11 +00:00
|
|
|
txpool txPool
|
|
|
|
blockchain *core.BlockChain
|
|
|
|
chaindb ethdb.Database
|
|
|
|
chainconfig *core.ChainConfig
|
2015-07-02 16:55:18 +00:00
|
|
|
|
|
|
|
downloader *downloader.Downloader
|
|
|
|
fetcher *fetcher.Fetcher
|
|
|
|
peers *peerSet
|
2015-04-18 00:21:07 +00:00
|
|
|
|
2015-06-26 13:54:27 +00:00
|
|
|
SubProtocols []p2p.Protocol
|
2015-04-22 15:56:06 +00:00
|
|
|
|
|
|
|
eventMux *event.TypeMux
|
|
|
|
txSub event.Subscription
|
|
|
|
minedBlockSub event.Subscription
|
2015-04-24 12:40:32 +00:00
|
|
|
|
2015-06-09 10:03:14 +00:00
|
|
|
// channels for fetcher, syncer, txsyncLoop
|
2016-03-29 01:08:16 +00:00
|
|
|
newPeerCh chan *peer
|
|
|
|
txsyncCh chan *txsync
|
|
|
|
quitSync chan struct{}
|
|
|
|
noMorePeers chan struct{}
|
2015-06-08 17:38:39 +00:00
|
|
|
|
2015-04-30 22:23:51 +00:00
|
|
|
// wait group is used for graceful shutdowns during downloading
|
|
|
|
// and processing
|
2016-03-29 01:08:16 +00:00
|
|
|
wg sync.WaitGroup
|
2016-05-24 16:49:54 +00:00
|
|
|
|
|
|
|
badBlockReportingEnabled bool
|
2015-04-17 23:11:09 +00:00
|
|
|
}
|
|
|
|
|
2015-04-18 00:21:07 +00:00
|
|
|
// NewProtocolManager returns a new ethereum sub protocol manager. The Ethereum sub protocol manages peers capable
|
|
|
|
// with the ethereum network.
|
2016-03-01 22:32:43 +00:00
|
|
|
func NewProtocolManager(config *core.ChainConfig, fastSync bool, networkId int, mux *event.TypeMux, txpool txPool, pow pow.PoW, blockchain *core.BlockChain, chaindb ethdb.Database) (*ProtocolManager, error) {
|
2015-06-26 13:54:27 +00:00
|
|
|
// Create the protocol manager with the base fields
|
2015-04-18 00:21:07 +00:00
|
|
|
manager := &ProtocolManager{
|
2016-03-29 01:08:16 +00:00
|
|
|
networkId: networkId,
|
|
|
|
eventMux: mux,
|
|
|
|
txpool: txpool,
|
|
|
|
blockchain: blockchain,
|
|
|
|
chaindb: chaindb,
|
2016-07-08 17:59:11 +00:00
|
|
|
chainconfig: config,
|
2016-03-29 01:08:16 +00:00
|
|
|
peers: newPeerSet(),
|
|
|
|
newPeerCh: make(chan *peer),
|
|
|
|
noMorePeers: make(chan struct{}),
|
|
|
|
txsyncCh: make(chan *txsync),
|
|
|
|
quitSync: make(chan struct{}),
|
2015-04-17 23:11:09 +00:00
|
|
|
}
|
2016-05-17 11:17:20 +00:00
|
|
|
// Figure out whether to allow fast sync or not
|
|
|
|
if fastSync && blockchain.CurrentBlock().NumberU64() > 0 {
|
|
|
|
glog.V(logger.Info).Infof("blockchain not empty, fast sync disabled")
|
|
|
|
fastSync = false
|
|
|
|
}
|
|
|
|
if fastSync {
|
|
|
|
manager.fastSync = uint32(1)
|
|
|
|
}
|
2015-06-26 13:54:27 +00:00
|
|
|
// Initiate a sub-protocol for every implemented version we can handle
|
2015-09-01 14:35:14 +00:00
|
|
|
manager.SubProtocols = make([]p2p.Protocol, 0, len(ProtocolVersions))
|
|
|
|
for i, version := range ProtocolVersions {
|
|
|
|
// Skip protocol version if incompatible with the mode of operation
|
2015-10-09 15:36:31 +00:00
|
|
|
if fastSync && version < eth63 {
|
2015-09-01 14:35:14 +00:00
|
|
|
continue
|
|
|
|
}
|
2015-10-13 09:04:25 +00:00
|
|
|
// Compatible; initialise the sub-protocol
|
2015-09-01 14:35:14 +00:00
|
|
|
version := version // Closure for the run
|
|
|
|
manager.SubProtocols = append(manager.SubProtocols, p2p.Protocol{
|
2015-10-27 13:10:30 +00:00
|
|
|
Name: ProtocolName,
|
2015-06-26 13:54:27 +00:00
|
|
|
Version: version,
|
|
|
|
Length: ProtocolLengths[i],
|
|
|
|
Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
|
2015-10-27 13:10:30 +00:00
|
|
|
peer := manager.newPeer(int(version), p, rw)
|
2016-03-29 01:08:16 +00:00
|
|
|
select {
|
|
|
|
case manager.newPeerCh <- peer:
|
|
|
|
manager.wg.Add(1)
|
|
|
|
defer manager.wg.Done()
|
|
|
|
return manager.handle(peer)
|
|
|
|
case <-manager.quitSync:
|
|
|
|
return p2p.DiscQuitting
|
|
|
|
}
|
2015-06-26 13:54:27 +00:00
|
|
|
},
|
2015-10-27 13:10:30 +00:00
|
|
|
NodeInfo: func() interface{} {
|
|
|
|
return manager.NodeInfo()
|
|
|
|
},
|
|
|
|
PeerInfo: func(id discover.NodeID) interface{} {
|
|
|
|
if p := manager.peers.Peer(fmt.Sprintf("%x", id[:8])); p != nil {
|
|
|
|
return p.Info()
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
},
|
2015-09-01 14:35:14 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
if len(manager.SubProtocols) == 0 {
|
|
|
|
return nil, errIncompatibleConfig
|
2015-04-18 00:21:07 +00:00
|
|
|
}
|
2015-06-16 08:58:32 +00:00
|
|
|
// Construct the different synchronisation mechanisms
|
2016-04-05 13:22:04 +00:00
|
|
|
manager.downloader = downloader.New(chaindb, manager.eventMux, blockchain.HasHeader, blockchain.HasBlockAndState, blockchain.GetHeaderByHash,
|
|
|
|
blockchain.GetBlockByHash, blockchain.CurrentHeader, blockchain.CurrentBlock, blockchain.CurrentFastBlock, blockchain.FastSyncCommitHead,
|
|
|
|
blockchain.GetTdByHash, blockchain.InsertHeaderChain, manager.insertChain, blockchain.InsertReceiptChain, blockchain.Rollback,
|
2015-12-29 12:01:08 +00:00
|
|
|
manager.removePeer)
|
2015-06-16 08:58:32 +00:00
|
|
|
|
2015-06-18 15:00:19 +00:00
|
|
|
validator := func(block *types.Block, parent *types.Block) error {
|
2016-03-01 22:32:43 +00:00
|
|
|
return core.ValidateHeader(config, pow, block.Header(), parent.Header(), true, false)
|
2015-06-18 15:00:19 +00:00
|
|
|
}
|
2015-06-16 14:39:04 +00:00
|
|
|
heighter := func() uint64 {
|
2015-09-28 16:27:31 +00:00
|
|
|
return blockchain.CurrentBlock().NumberU64()
|
2015-06-16 14:39:04 +00:00
|
|
|
}
|
2016-06-02 12:54:07 +00:00
|
|
|
inserter := func(blocks types.Blocks) (int, error) {
|
|
|
|
atomic.StoreUint32(&manager.synced, 1) // Mark initial sync done on any fetcher import
|
|
|
|
return manager.insertChain(blocks)
|
|
|
|
}
|
2016-04-05 13:22:04 +00:00
|
|
|
manager.fetcher = fetcher.New(blockchain.GetBlockByHash, validator, manager.BroadcastBlock, heighter, inserter, manager.removePeer)
|
2016-05-24 16:49:54 +00:00
|
|
|
|
|
|
|
if blockchain.Genesis().Hash().Hex() == defaultGenesisHash && networkId == 1 {
|
|
|
|
glog.V(logger.Debug).Infoln("Bad Block Reporting is enabled")
|
|
|
|
manager.badBlockReportingEnabled = true
|
|
|
|
}
|
2015-04-18 00:21:07 +00:00
|
|
|
|
2015-09-01 14:35:14 +00:00
|
|
|
return manager, nil
|
2015-04-17 23:11:09 +00:00
|
|
|
}
|
|
|
|
|
2016-05-24 16:49:54 +00:00
|
|
|
func (pm *ProtocolManager) insertChain(blocks types.Blocks) (i int, err error) {
|
|
|
|
i, err = pm.blockchain.InsertChain(blocks)
|
|
|
|
if pm.badBlockReportingEnabled && core.IsValidationErr(err) && i < len(blocks) {
|
|
|
|
go sendBadBlockReport(blocks[i], err)
|
|
|
|
}
|
|
|
|
return i, err
|
|
|
|
}
|
|
|
|
|
2015-05-26 11:00:21 +00:00
|
|
|
func (pm *ProtocolManager) removePeer(id string) {
|
2015-05-27 15:58:51 +00:00
|
|
|
// Short circuit if the peer was already removed
|
|
|
|
peer := pm.peers.Peer(id)
|
|
|
|
if peer == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
glog.V(logger.Debug).Infoln("Removing peer", id)
|
2015-05-18 18:33:37 +00:00
|
|
|
|
2015-05-27 15:58:51 +00:00
|
|
|
// Unregister the peer from the downloader and Ethereum peer set
|
|
|
|
pm.downloader.UnregisterPeer(id)
|
2015-05-26 11:00:21 +00:00
|
|
|
if err := pm.peers.Unregister(id); err != nil {
|
2015-05-18 18:33:37 +00:00
|
|
|
glog.V(logger.Error).Infoln("Removal failed:", err)
|
|
|
|
}
|
2015-05-27 15:58:51 +00:00
|
|
|
// Hard disconnect at the networking layer
|
|
|
|
if peer != nil {
|
|
|
|
peer.Peer.Disconnect(p2p.DiscUselessPeer)
|
|
|
|
}
|
2015-04-30 10:38:16 +00:00
|
|
|
}
|
|
|
|
|
2015-04-22 15:56:06 +00:00
|
|
|
func (pm *ProtocolManager) Start() {
|
|
|
|
// broadcast transactions
|
|
|
|
pm.txSub = pm.eventMux.Subscribe(core.TxPreEvent{})
|
|
|
|
go pm.txBroadcastLoop()
|
|
|
|
// broadcast mined blocks
|
|
|
|
pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{})
|
|
|
|
go pm.minedBroadcastLoop()
|
2015-04-24 13:37:32 +00:00
|
|
|
|
2015-06-09 10:03:14 +00:00
|
|
|
// start sync handlers
|
2015-06-08 16:24:56 +00:00
|
|
|
go pm.syncer()
|
2015-06-09 10:03:14 +00:00
|
|
|
go pm.txsyncLoop()
|
2015-04-22 15:56:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (pm *ProtocolManager) Stop() {
|
2015-04-30 22:23:51 +00:00
|
|
|
glog.V(logger.Info).Infoln("Stopping ethereum protocol handler...")
|
|
|
|
|
2015-04-22 15:56:06 +00:00
|
|
|
pm.txSub.Unsubscribe() // quits txBroadcastLoop
|
|
|
|
pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
|
2015-04-30 22:23:51 +00:00
|
|
|
|
2016-03-29 01:08:16 +00:00
|
|
|
// Quit the sync loop.
|
|
|
|
// After this send has completed, no new peers will be accepted.
|
|
|
|
pm.noMorePeers <- struct{}{}
|
|
|
|
|
|
|
|
// Quit fetcher, txsyncLoop.
|
|
|
|
close(pm.quitSync)
|
|
|
|
|
|
|
|
// Disconnect existing sessions.
|
|
|
|
// This also closes the gate for any new registrations on the peer set.
|
|
|
|
// sessions which are already established but not added to pm.peers yet
|
|
|
|
// will exit when they try to register.
|
|
|
|
pm.peers.Close()
|
|
|
|
|
|
|
|
// Wait for all peer handler goroutines and the loops to come down.
|
2015-04-30 22:23:51 +00:00
|
|
|
pm.wg.Wait()
|
|
|
|
|
|
|
|
glog.V(logger.Info).Infoln("Ethereum protocol handler stopped")
|
2015-04-22 15:56:06 +00:00
|
|
|
}
|
|
|
|
|
2015-10-27 13:10:30 +00:00
|
|
|
func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
|
|
|
|
return newPeer(pv, p, newMeteredMsgWriter(rw))
|
2015-04-17 23:11:09 +00:00
|
|
|
}
|
|
|
|
|
2015-06-26 17:42:27 +00:00
|
|
|
// handle is the callback invoked to manage the life cycle of an eth peer. When
|
|
|
|
// this function terminates, the peer is disconnected.
|
2015-04-18 00:21:07 +00:00
|
|
|
func (pm *ProtocolManager) handle(p *peer) error {
|
2015-07-01 12:19:11 +00:00
|
|
|
glog.V(logger.Debug).Infof("%v: peer connected [%s]", p, p.Name())
|
2015-06-26 17:42:27 +00:00
|
|
|
|
|
|
|
// Execute the Ethereum handshake
|
2015-08-31 15:09:50 +00:00
|
|
|
td, head, genesis := pm.blockchain.Status()
|
2015-10-27 13:10:30 +00:00
|
|
|
if err := p.Handshake(pm.networkId, td, head, genesis); err != nil {
|
2015-06-26 17:42:27 +00:00
|
|
|
glog.V(logger.Debug).Infof("%v: handshake failed: %v", p, err)
|
2015-04-17 23:11:09 +00:00
|
|
|
return err
|
|
|
|
}
|
2015-07-02 16:55:18 +00:00
|
|
|
if rw, ok := p.rw.(*meteredMsgReadWriter); ok {
|
|
|
|
rw.Init(p.version)
|
|
|
|
}
|
2015-06-26 17:42:27 +00:00
|
|
|
// Register the peer locally
|
|
|
|
glog.V(logger.Detail).Infof("%v: adding peer", p)
|
2015-05-18 18:33:37 +00:00
|
|
|
if err := pm.peers.Register(p); err != nil {
|
2015-06-26 17:42:27 +00:00
|
|
|
glog.V(logger.Error).Infof("%v: addition failed: %v", p, err)
|
2015-05-18 18:33:37 +00:00
|
|
|
return err
|
|
|
|
}
|
2015-05-26 11:00:21 +00:00
|
|
|
defer pm.removePeer(p.id)
|
2015-04-17 23:11:09 +00:00
|
|
|
|
2015-06-26 17:42:27 +00:00
|
|
|
// Register the peer in the downloader. If the downloader considers it banned, we disconnect
|
2016-07-25 12:14:14 +00:00
|
|
|
if err := pm.downloader.RegisterPeer(p.id, p.version, p.Head, p.RequestHeadersByHash, p.RequestHeadersByNumber, p.RequestBodies, p.RequestReceipts, p.RequestNodeData); err != nil {
|
2015-05-18 18:33:37 +00:00
|
|
|
return err
|
|
|
|
}
|
2015-06-09 10:03:14 +00:00
|
|
|
// Propagate existing transactions. new transactions appearing
|
2015-04-17 23:11:09 +00:00
|
|
|
// after this will be sent via broadcasts.
|
2015-06-09 10:03:14 +00:00
|
|
|
pm.syncTransactions(p)
|
|
|
|
|
2016-07-08 17:59:11 +00:00
|
|
|
// If we're DAO hard-fork aware, validate any remote peer with regard to the hard-fork
|
|
|
|
if daoBlock := pm.chainconfig.DAOForkBlock; daoBlock != nil {
|
|
|
|
// Request the peer's DAO fork header for extra-data validation
|
|
|
|
if err := p.RequestHeadersByNumber(daoBlock.Uint64(), 1, 0, false); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// Start a timer to disconnect if the peer doesn't reply in time
|
|
|
|
p.forkDrop = time.AfterFunc(daoChallengeTimeout, func() {
|
2016-10-07 12:26:13 +00:00
|
|
|
glog.V(logger.Debug).Infof("%v: timed out DAO fork-check, dropping", p)
|
2016-07-08 17:59:11 +00:00
|
|
|
pm.removePeer(p.id)
|
|
|
|
})
|
2016-07-19 09:00:09 +00:00
|
|
|
// Make sure it's cleaned up if the peer dies off
|
|
|
|
defer func() {
|
|
|
|
if p.forkDrop != nil {
|
|
|
|
p.forkDrop.Stop()
|
|
|
|
p.forkDrop = nil
|
|
|
|
}
|
|
|
|
}()
|
2016-07-08 17:59:11 +00:00
|
|
|
}
|
2015-04-17 23:11:09 +00:00
|
|
|
// main loop. handle incoming messages.
|
|
|
|
for {
|
|
|
|
if err := pm.handleMsg(p); err != nil {
|
2015-06-26 17:42:27 +00:00
|
|
|
glog.V(logger.Debug).Infof("%v: message handling failed: %v", p, err)
|
2015-04-17 23:11:09 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-06-26 17:42:27 +00:00
|
|
|
// handleMsg is invoked whenever an inbound message is received from a remote
|
|
|
|
// peer. The remote connection is torn down upon returning any error.
|
2015-06-17 15:25:23 +00:00
|
|
|
func (pm *ProtocolManager) handleMsg(p *peer) error {
|
2015-06-26 17:42:27 +00:00
|
|
|
// Read the next message from the remote peer, and ensure it's fully consumed
|
2015-04-17 23:11:09 +00:00
|
|
|
msg, err := p.rw.ReadMsg()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if msg.Size > ProtocolMaxMsgSize {
|
|
|
|
return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
|
|
|
|
}
|
|
|
|
defer msg.Discard()
|
|
|
|
|
2015-06-26 17:42:27 +00:00
|
|
|
// Handle the message depending on its contents
|
2015-07-02 16:55:18 +00:00
|
|
|
switch {
|
|
|
|
case msg.Code == StatusMsg:
|
2015-06-30 16:05:06 +00:00
|
|
|
// Status messages should never arrive after the handshake
|
2015-04-17 23:11:09 +00:00
|
|
|
return errResp(ErrExtraStatusMsg, "uncontrolled status message")
|
|
|
|
|
2015-07-02 16:55:18 +00:00
|
|
|
// Block header query, collect the requested headers and reply
|
2016-07-21 09:36:38 +00:00
|
|
|
case msg.Code == GetBlockHeadersMsg:
|
2015-07-02 16:55:18 +00:00
|
|
|
// Decode the complex header query
|
|
|
|
var query getBlockHeadersData
|
|
|
|
if err := msg.Decode(&query); err != nil {
|
|
|
|
return errResp(ErrDecode, "%v: %v", msg, err)
|
|
|
|
}
|
2015-12-15 17:22:48 +00:00
|
|
|
hashMode := query.Origin.Hash != (common.Hash{})
|
|
|
|
|
2015-08-31 17:21:02 +00:00
|
|
|
// Gather headers until the fetch or network limits is reached
|
2015-07-02 16:55:18 +00:00
|
|
|
var (
|
|
|
|
bytes common.StorageSize
|
|
|
|
headers []*types.Header
|
|
|
|
unknown bool
|
|
|
|
)
|
|
|
|
for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch {
|
2015-08-31 17:21:02 +00:00
|
|
|
// Retrieve the next header satisfying the query
|
|
|
|
var origin *types.Header
|
2015-12-15 17:22:48 +00:00
|
|
|
if hashMode {
|
2016-04-05 13:22:04 +00:00
|
|
|
origin = pm.blockchain.GetHeaderByHash(query.Origin.Hash)
|
2015-07-02 16:55:18 +00:00
|
|
|
} else {
|
2015-08-31 15:09:50 +00:00
|
|
|
origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number)
|
2015-07-02 16:55:18 +00:00
|
|
|
}
|
|
|
|
if origin == nil {
|
|
|
|
break
|
|
|
|
}
|
2016-04-05 13:22:04 +00:00
|
|
|
number := origin.Number.Uint64()
|
2015-08-31 17:21:02 +00:00
|
|
|
headers = append(headers, origin)
|
2015-09-07 17:43:01 +00:00
|
|
|
bytes += estHeaderRlpSize
|
2015-07-02 16:55:18 +00:00
|
|
|
|
2015-08-31 17:21:02 +00:00
|
|
|
// Advance to the next header of the query
|
2015-07-02 16:55:18 +00:00
|
|
|
switch {
|
|
|
|
case query.Origin.Hash != (common.Hash{}) && query.Reverse:
|
|
|
|
// Hash based traversal towards the genesis block
|
|
|
|
for i := 0; i < int(query.Skip)+1; i++ {
|
2016-04-05 13:22:04 +00:00
|
|
|
if header := pm.blockchain.GetHeader(query.Origin.Hash, number); header != nil {
|
2015-08-31 17:21:02 +00:00
|
|
|
query.Origin.Hash = header.ParentHash
|
2016-04-05 13:22:04 +00:00
|
|
|
number--
|
2015-07-02 16:55:18 +00:00
|
|
|
} else {
|
|
|
|
unknown = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
case query.Origin.Hash != (common.Hash{}) && !query.Reverse:
|
|
|
|
// Hash based traversal towards the leaf block
|
2016-10-05 13:31:48 +00:00
|
|
|
var (
|
|
|
|
current = origin.Number.Uint64()
|
|
|
|
next = current + query.Skip + 1
|
|
|
|
)
|
|
|
|
if next <= current {
|
|
|
|
infos, _ := json.MarshalIndent(p.Peer.Info(), "", " ")
|
|
|
|
glog.V(logger.Warn).Infof("%v: GetBlockHeaders skip overflow attack (current %v, skip %v, next %v)\nMalicious peer infos: %s", p, current, query.Skip, next, infos)
|
|
|
|
unknown = true
|
|
|
|
} else {
|
|
|
|
if header := pm.blockchain.GetHeaderByNumber(next); header != nil {
|
|
|
|
if pm.blockchain.GetBlockHashesFromHash(header.Hash(), query.Skip+1)[query.Skip] == query.Origin.Hash {
|
|
|
|
query.Origin.Hash = header.Hash()
|
|
|
|
} else {
|
|
|
|
unknown = true
|
|
|
|
}
|
2015-07-02 16:55:18 +00:00
|
|
|
} else {
|
|
|
|
unknown = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
case query.Reverse:
|
|
|
|
// Number based traversal towards the genesis block
|
|
|
|
if query.Origin.Number >= query.Skip+1 {
|
|
|
|
query.Origin.Number -= (query.Skip + 1)
|
|
|
|
} else {
|
|
|
|
unknown = true
|
|
|
|
}
|
|
|
|
|
|
|
|
case !query.Reverse:
|
|
|
|
// Number based traversal towards the leaf block
|
|
|
|
query.Origin.Number += (query.Skip + 1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return p.SendBlockHeaders(headers)
|
|
|
|
|
2016-07-21 09:36:38 +00:00
|
|
|
case msg.Code == BlockHeadersMsg:
|
2015-08-14 18:25:41 +00:00
|
|
|
// A batch of headers arrived to one of our previous requests
|
|
|
|
var headers []*types.Header
|
|
|
|
if err := msg.Decode(&headers); err != nil {
|
|
|
|
return errResp(ErrDecode, "msg %v: %v", msg, err)
|
|
|
|
}
|
2016-07-08 17:59:11 +00:00
|
|
|
// If no headers were received, but we're expending a DAO fork check, maybe it's that
|
|
|
|
if len(headers) == 0 && p.forkDrop != nil {
|
|
|
|
// Possibly an empty reply to the fork header checks, sanity check TDs
|
|
|
|
verifyDAO := true
|
|
|
|
|
|
|
|
// If we already have a DAO header, we can check the peer's TD against it. If
|
|
|
|
// the peer's ahead of this, it too must have a reply to the DAO check
|
|
|
|
if daoHeader := pm.blockchain.GetHeaderByNumber(pm.chainconfig.DAOForkBlock.Uint64()); daoHeader != nil {
|
2016-07-25 12:14:14 +00:00
|
|
|
if _, td := p.Head(); td.Cmp(pm.blockchain.GetTd(daoHeader.Hash(), daoHeader.Number.Uint64())) >= 0 {
|
2016-07-08 17:59:11 +00:00
|
|
|
verifyDAO = false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// If we're seemingly on the same chain, disable the drop timer
|
|
|
|
if verifyDAO {
|
2016-07-14 08:22:58 +00:00
|
|
|
glog.V(logger.Debug).Infof("%v: seems to be on the same side of the DAO fork", p)
|
2016-07-08 17:59:11 +00:00
|
|
|
p.forkDrop.Stop()
|
|
|
|
p.forkDrop = nil
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
2015-08-14 18:25:41 +00:00
|
|
|
// Filter out any explicitly requested headers, deliver the rest to the downloader
|
|
|
|
filter := len(headers) == 1
|
|
|
|
if filter {
|
2016-07-08 17:59:11 +00:00
|
|
|
// If it's a potential DAO fork check, validate against the rules
|
|
|
|
if p.forkDrop != nil && pm.chainconfig.DAOForkBlock.Cmp(headers[0].Number) == 0 {
|
|
|
|
// Disable the fork drop timer
|
|
|
|
p.forkDrop.Stop()
|
|
|
|
p.forkDrop = nil
|
|
|
|
|
|
|
|
// Validate the header and either drop the peer or continue
|
2016-07-14 08:22:58 +00:00
|
|
|
if err := core.ValidateDAOHeaderExtraData(pm.chainconfig, headers[0]); err != nil {
|
|
|
|
glog.V(logger.Debug).Infof("%v: verified to be on the other side of the DAO fork, dropping", p)
|
2016-07-08 17:59:11 +00:00
|
|
|
return err
|
|
|
|
}
|
2016-07-14 08:22:58 +00:00
|
|
|
glog.V(logger.Debug).Infof("%v: verified to be on the same side of the DAO fork", p)
|
2016-07-26 09:26:41 +00:00
|
|
|
return nil
|
2016-07-08 17:59:11 +00:00
|
|
|
}
|
|
|
|
// Irrelevant of the fork checks, send the header to the fetcher just in case
|
2015-08-14 18:25:41 +00:00
|
|
|
headers = pm.fetcher.FilterHeaders(headers, time.Now())
|
|
|
|
}
|
|
|
|
if len(headers) > 0 || !filter {
|
|
|
|
err := pm.downloader.DeliverHeaders(p.id, headers)
|
|
|
|
if err != nil {
|
|
|
|
glog.V(logger.Debug).Infoln(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-07-21 09:36:38 +00:00
|
|
|
case msg.Code == GetBlockBodiesMsg:
|
2015-07-02 16:55:18 +00:00
|
|
|
// Decode the retrieval message
|
2015-06-04 15:46:07 +00:00
|
|
|
msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
|
2015-07-02 16:55:18 +00:00
|
|
|
if _, err := msgStream.List(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// Gather blocks until the fetch or network limits is reached
|
|
|
|
var (
|
|
|
|
hash common.Hash
|
2015-08-31 17:21:02 +00:00
|
|
|
bytes int
|
2015-09-07 17:43:01 +00:00
|
|
|
bodies []rlp.RawValue
|
2015-07-02 16:55:18 +00:00
|
|
|
)
|
|
|
|
for bytes < softResponseLimit && len(bodies) < downloader.MaxBlockFetch {
|
2015-08-31 17:21:02 +00:00
|
|
|
// Retrieve the hash of the next block
|
2015-07-02 16:55:18 +00:00
|
|
|
if err := msgStream.Decode(&hash); err == rlp.EOL {
|
|
|
|
break
|
|
|
|
} else if err != nil {
|
|
|
|
return errResp(ErrDecode, "msg %v: %v", msg, err)
|
|
|
|
}
|
2015-08-31 17:21:02 +00:00
|
|
|
// Retrieve the requested block body, stopping if enough was found
|
2015-08-31 15:09:50 +00:00
|
|
|
if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 {
|
2015-09-07 17:43:01 +00:00
|
|
|
bodies = append(bodies, data)
|
|
|
|
bytes += len(data)
|
2015-07-02 16:55:18 +00:00
|
|
|
}
|
|
|
|
}
|
2015-08-31 17:21:02 +00:00
|
|
|
return p.SendBlockBodiesRLP(bodies)
|
2015-06-04 15:46:07 +00:00
|
|
|
|
2016-07-21 09:36:38 +00:00
|
|
|
case msg.Code == BlockBodiesMsg:
|
2015-09-30 16:23:31 +00:00
|
|
|
// A batch of block bodies arrived to one of our previous requests
|
|
|
|
var request blockBodiesData
|
|
|
|
if err := msg.Decode(&request); err != nil {
|
|
|
|
return errResp(ErrDecode, "msg %v: %v", msg, err)
|
|
|
|
}
|
|
|
|
// Deliver them all to the downloader for queuing
|
|
|
|
trasactions := make([][]*types.Transaction, len(request))
|
|
|
|
uncles := make([][]*types.Header, len(request))
|
|
|
|
|
|
|
|
for i, body := range request {
|
|
|
|
trasactions[i] = body.Transactions
|
|
|
|
uncles[i] = body.Uncles
|
|
|
|
}
|
|
|
|
// Filter out any explicitly requested bodies, deliver the rest to the downloader
|
2016-03-03 11:06:23 +00:00
|
|
|
filter := len(trasactions) > 0 || len(uncles) > 0
|
|
|
|
if filter {
|
|
|
|
trasactions, uncles = pm.fetcher.FilterBodies(trasactions, uncles, time.Now())
|
|
|
|
}
|
|
|
|
if len(trasactions) > 0 || len(uncles) > 0 || !filter {
|
2015-09-30 16:23:31 +00:00
|
|
|
err := pm.downloader.DeliverBodies(p.id, trasactions, uncles)
|
|
|
|
if err != nil {
|
|
|
|
glog.V(logger.Debug).Infoln(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-07-02 16:55:18 +00:00
|
|
|
case p.version >= eth63 && msg.Code == GetNodeDataMsg:
|
|
|
|
// Decode the retrieval message
|
2015-06-04 15:46:07 +00:00
|
|
|
msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
|
2015-07-02 16:55:18 +00:00
|
|
|
if _, err := msgStream.List(); err != nil {
|
|
|
|
return err
|
2015-06-04 15:46:07 +00:00
|
|
|
}
|
2015-07-02 16:55:18 +00:00
|
|
|
// Gather state data until the fetch or network limits is reached
|
|
|
|
var (
|
|
|
|
hash common.Hash
|
|
|
|
bytes int
|
|
|
|
data [][]byte
|
|
|
|
)
|
|
|
|
for bytes < softResponseLimit && len(data) < downloader.MaxStateFetch {
|
|
|
|
// Retrieve the hash of the next state entry
|
|
|
|
if err := msgStream.Decode(&hash); err == rlp.EOL {
|
|
|
|
break
|
|
|
|
} else if err != nil {
|
|
|
|
return errResp(ErrDecode, "msg %v: %v", msg, err)
|
|
|
|
}
|
|
|
|
// Retrieve the requested state entry, stopping if enough was found
|
|
|
|
if entry, err := pm.chaindb.Get(hash.Bytes()); err == nil {
|
|
|
|
data = append(data, entry)
|
|
|
|
bytes += len(entry)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return p.SendNodeData(data)
|
2015-06-26 17:42:27 +00:00
|
|
|
|
2015-10-05 16:37:56 +00:00
|
|
|
case p.version >= eth63 && msg.Code == NodeDataMsg:
|
|
|
|
// A batch of node state data arrived to one of our previous requests
|
|
|
|
var data [][]byte
|
|
|
|
if err := msg.Decode(&data); err != nil {
|
|
|
|
return errResp(ErrDecode, "msg %v: %v", msg, err)
|
|
|
|
}
|
|
|
|
// Deliver all to the downloader
|
|
|
|
if err := pm.downloader.DeliverNodeData(p.id, data); err != nil {
|
|
|
|
glog.V(logger.Debug).Infof("failed to deliver node state data: %v", err)
|
|
|
|
}
|
|
|
|
|
2015-07-02 16:55:18 +00:00
|
|
|
case p.version >= eth63 && msg.Code == GetReceiptsMsg:
|
|
|
|
// Decode the retrieval message
|
|
|
|
msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
|
|
|
|
if _, err := msgStream.List(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// Gather state data until the fetch or network limits is reached
|
|
|
|
var (
|
|
|
|
hash common.Hash
|
|
|
|
bytes int
|
2015-09-28 16:27:31 +00:00
|
|
|
receipts []rlp.RawValue
|
2015-07-02 16:55:18 +00:00
|
|
|
)
|
2015-09-28 16:27:31 +00:00
|
|
|
for bytes < softResponseLimit && len(receipts) < downloader.MaxReceiptFetch {
|
|
|
|
// Retrieve the hash of the next block
|
2015-07-02 16:55:18 +00:00
|
|
|
if err := msgStream.Decode(&hash); err == rlp.EOL {
|
|
|
|
break
|
|
|
|
} else if err != nil {
|
|
|
|
return errResp(ErrDecode, "msg %v: %v", msg, err)
|
|
|
|
}
|
2015-09-28 16:27:31 +00:00
|
|
|
// Retrieve the requested block's receipts, skipping if unknown to us
|
2016-04-05 13:22:04 +00:00
|
|
|
results := core.GetBlockReceipts(pm.chaindb, hash, core.GetBlockNumber(pm.chaindb, hash))
|
2015-09-28 16:27:31 +00:00
|
|
|
if results == nil {
|
2016-04-05 13:22:04 +00:00
|
|
|
if header := pm.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
|
2015-09-28 16:27:31 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// If known, encode and queue for response packet
|
|
|
|
if encoded, err := rlp.EncodeToBytes(results); err != nil {
|
|
|
|
glog.V(logger.Error).Infof("failed to encode receipt: %v", err)
|
|
|
|
} else {
|
|
|
|
receipts = append(receipts, encoded)
|
|
|
|
bytes += len(encoded)
|
2015-07-02 16:55:18 +00:00
|
|
|
}
|
|
|
|
}
|
2015-09-28 16:27:31 +00:00
|
|
|
return p.SendReceiptsRLP(receipts)
|
2015-07-02 16:55:18 +00:00
|
|
|
|
2015-09-30 16:23:31 +00:00
|
|
|
case p.version >= eth63 && msg.Code == ReceiptsMsg:
|
|
|
|
// A batch of receipts arrived to one of our previous requests
|
|
|
|
var receipts [][]*types.Receipt
|
|
|
|
if err := msg.Decode(&receipts); err != nil {
|
|
|
|
return errResp(ErrDecode, "msg %v: %v", msg, err)
|
|
|
|
}
|
|
|
|
// Deliver all to the downloader
|
|
|
|
if err := pm.downloader.DeliverReceipts(p.id, receipts); err != nil {
|
|
|
|
glog.V(logger.Debug).Infof("failed to deliver receipts: %v", err)
|
|
|
|
}
|
|
|
|
|
2015-07-02 16:55:18 +00:00
|
|
|
case msg.Code == NewBlockHashesMsg:
|
2016-03-15 18:27:49 +00:00
|
|
|
// Retrieve and deserialize the remote new block hashes notification
|
2015-07-02 16:55:18 +00:00
|
|
|
type announce struct {
|
|
|
|
Hash common.Hash
|
|
|
|
Number uint64
|
|
|
|
}
|
|
|
|
var announces = []announce{}
|
|
|
|
|
|
|
|
if p.version < eth62 {
|
|
|
|
// We're running the old protocol, make block number unknown (0)
|
|
|
|
var hashes []common.Hash
|
|
|
|
if err := msg.Decode(&hashes); err != nil {
|
|
|
|
return errResp(ErrDecode, "%v: %v", msg, err)
|
|
|
|
}
|
|
|
|
for _, hash := range hashes {
|
|
|
|
announces = append(announces, announce{hash, 0})
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// Otherwise extract both block hash and number
|
|
|
|
var request newBlockHashesData
|
|
|
|
if err := msg.Decode(&request); err != nil {
|
|
|
|
return errResp(ErrDecode, "%v: %v", msg, err)
|
|
|
|
}
|
|
|
|
for _, block := range request {
|
|
|
|
announces = append(announces, announce{block.Hash, block.Number})
|
|
|
|
}
|
2015-06-04 15:46:07 +00:00
|
|
|
}
|
|
|
|
// Mark the hashes as present at the remote node
|
2015-07-02 16:55:18 +00:00
|
|
|
for _, block := range announces {
|
|
|
|
p.MarkBlock(block.Hash)
|
2015-06-04 15:46:07 +00:00
|
|
|
}
|
2015-06-08 16:24:56 +00:00
|
|
|
// Schedule all the unknown hashes for retrieval
|
2015-07-02 16:55:18 +00:00
|
|
|
unknown := make([]announce, 0, len(announces))
|
|
|
|
for _, block := range announces {
|
2015-08-31 15:09:50 +00:00
|
|
|
if !pm.blockchain.HasBlock(block.Hash) {
|
2015-07-02 16:55:18 +00:00
|
|
|
unknown = append(unknown, block)
|
2015-06-04 15:46:07 +00:00
|
|
|
}
|
2015-06-08 16:24:56 +00:00
|
|
|
}
|
2015-07-02 16:55:18 +00:00
|
|
|
for _, block := range unknown {
|
2016-07-21 09:36:38 +00:00
|
|
|
pm.fetcher.Notify(p.id, block.Hash, block.Number, time.Now(), p.RequestOneHeader, p.RequestBodies)
|
2015-06-08 16:24:56 +00:00
|
|
|
}
|
2015-04-17 23:11:09 +00:00
|
|
|
|
2015-07-02 16:55:18 +00:00
|
|
|
case msg.Code == NewBlockMsg:
|
2015-06-17 15:25:23 +00:00
|
|
|
// Retrieve and decode the propagated block
|
2015-06-29 14:32:14 +00:00
|
|
|
var request newBlockData
|
2015-04-17 23:11:09 +00:00
|
|
|
if err := msg.Decode(&request); err != nil {
|
|
|
|
return errResp(ErrDecode, "%v: %v", msg, err)
|
|
|
|
}
|
2015-04-29 20:50:58 +00:00
|
|
|
request.Block.ReceivedAt = msg.ReceivedAt
|
2016-05-24 16:49:54 +00:00
|
|
|
request.Block.ReceivedFrom = p
|
2015-04-29 17:55:30 +00:00
|
|
|
|
2015-06-17 15:25:23 +00:00
|
|
|
// Mark the peer as owning the block and schedule it for import
|
2015-06-29 09:44:00 +00:00
|
|
|
p.MarkBlock(request.Block.Hash())
|
2015-06-17 15:25:23 +00:00
|
|
|
pm.fetcher.Enqueue(p.id, request.Block)
|
|
|
|
|
2016-07-25 12:14:14 +00:00
|
|
|
// Assuming the block is importable by the peer, but possibly not yet done so,
|
|
|
|
// calculate the head hash and TD that the peer truly must have.
|
|
|
|
var (
|
|
|
|
trueHead = request.Block.ParentHash()
|
|
|
|
trueTD = new(big.Int).Sub(request.TD, request.Block.Difficulty())
|
|
|
|
)
|
|
|
|
// Update the peers total difficulty if better than the previous
|
|
|
|
if _, td := p.Head(); trueTD.Cmp(td) > 0 {
|
|
|
|
p.SetHead(trueHead, trueTD)
|
|
|
|
|
|
|
|
// Schedule a sync if above ours. Note, this will not fire a sync for a gap of
|
|
|
|
// a singe block (as the true TD is below the propagated block), however this
|
|
|
|
// scenario should easily be covered by the fetcher.
|
2016-04-05 13:22:04 +00:00
|
|
|
currentBlock := pm.blockchain.CurrentBlock()
|
2016-07-25 12:14:14 +00:00
|
|
|
if trueTD.Cmp(pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64())) > 0 {
|
2015-08-19 12:14:26 +00:00
|
|
|
go pm.synchronise(p)
|
|
|
|
}
|
2015-07-09 10:55:06 +00:00
|
|
|
}
|
2015-04-18 00:24:24 +00:00
|
|
|
|
2015-07-02 16:55:18 +00:00
|
|
|
case msg.Code == TxMsg:
|
2016-06-02 12:54:07 +00:00
|
|
|
// Transactions arrived, make sure we have a valid and fresh chain to handle them
|
|
|
|
if atomic.LoadUint32(&pm.synced) == 0 {
|
2016-05-17 11:17:20 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
// Transactions can be processed, parse all of them and deliver to the pool
|
2015-06-30 16:05:06 +00:00
|
|
|
var txs []*types.Transaction
|
|
|
|
if err := msg.Decode(&txs); err != nil {
|
|
|
|
return errResp(ErrDecode, "msg %v: %v", msg, err)
|
|
|
|
}
|
|
|
|
for i, tx := range txs {
|
|
|
|
// Validate and mark the remote transaction
|
|
|
|
if tx == nil {
|
|
|
|
return errResp(ErrDecode, "transaction %d is nil", i)
|
|
|
|
}
|
|
|
|
p.MarkTransaction(tx.Hash())
|
|
|
|
}
|
2016-07-01 15:59:55 +00:00
|
|
|
pm.txpool.AddBatch(txs)
|
2015-06-30 16:05:06 +00:00
|
|
|
|
2015-04-17 23:11:09 +00:00
|
|
|
default:
|
|
|
|
return errResp(ErrInvalidMsgCode, "%v", msg.Code)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2015-04-18 00:21:07 +00:00
|
|
|
|
2015-06-18 15:00:19 +00:00
|
|
|
// BroadcastBlock will either propagate a block to a subset of it's peers, or
|
|
|
|
// will only announce it's availability (depending what's requested).
|
|
|
|
func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
|
2015-06-18 13:09:34 +00:00
|
|
|
hash := block.Hash()
|
|
|
|
peers := pm.peers.PeersWithoutBlock(hash)
|
2015-06-04 15:46:07 +00:00
|
|
|
|
2015-06-18 15:00:19 +00:00
|
|
|
// If propagation is requested, send to a subset of the peer
|
|
|
|
if propagate {
|
2015-07-09 10:55:06 +00:00
|
|
|
// Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
|
|
|
|
var td *big.Int
|
2016-04-05 13:22:04 +00:00
|
|
|
if parent := pm.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
|
|
|
|
td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash(), block.NumberU64()-1))
|
2015-07-09 10:55:06 +00:00
|
|
|
} else {
|
|
|
|
glog.V(logger.Error).Infof("propagating dangling block #%d [%x]", block.NumberU64(), hash[:4])
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// Send the block to a subset of our peers
|
2015-06-18 15:00:19 +00:00
|
|
|
transfer := peers[:int(math.Sqrt(float64(len(peers))))]
|
|
|
|
for _, peer := range transfer {
|
2015-07-09 10:55:06 +00:00
|
|
|
peer.SendNewBlock(block, td)
|
2015-06-18 15:00:19 +00:00
|
|
|
}
|
|
|
|
glog.V(logger.Detail).Infof("propagated block %x to %d peers in %v", hash[:4], len(transfer), time.Since(block.ReceivedAt))
|
2015-06-04 15:46:07 +00:00
|
|
|
}
|
2015-06-18 15:00:19 +00:00
|
|
|
// Otherwise if the block is indeed in out own chain, announce it
|
2015-08-31 15:09:50 +00:00
|
|
|
if pm.blockchain.HasBlock(hash) {
|
2015-06-18 15:00:19 +00:00
|
|
|
for _, peer := range peers {
|
2016-07-21 09:36:38 +00:00
|
|
|
peer.SendNewBlockHashes([]common.Hash{hash}, []uint64{block.NumberU64()})
|
2015-06-18 15:00:19 +00:00
|
|
|
}
|
|
|
|
glog.V(logger.Detail).Infof("announced block %x to %d peers in %v", hash[:4], len(peers), time.Since(block.ReceivedAt))
|
2015-04-18 00:21:07 +00:00
|
|
|
}
|
|
|
|
}
|
2015-04-22 15:56:06 +00:00
|
|
|
|
2015-06-26 17:42:27 +00:00
|
|
|
// BroadcastTx will propagate a transaction to all peers which are not known to
|
|
|
|
// already have the given transaction.
|
2015-04-22 15:56:06 +00:00
|
|
|
func (pm *ProtocolManager) BroadcastTx(hash common.Hash, tx *types.Transaction) {
|
2015-05-18 18:33:37 +00:00
|
|
|
// Broadcast transaction to a batch of peers not knowing about it
|
2015-05-20 07:34:45 +00:00
|
|
|
peers := pm.peers.PeersWithoutTx(hash)
|
2015-05-12 14:27:17 +00:00
|
|
|
//FIXME include this again: peers = peers[:int(math.Sqrt(float64(len(peers))))]
|
2015-04-22 15:56:06 +00:00
|
|
|
for _, peer := range peers {
|
2015-06-29 09:44:00 +00:00
|
|
|
peer.SendTransactions(types.Transactions{tx})
|
2015-04-22 15:56:06 +00:00
|
|
|
}
|
|
|
|
glog.V(logger.Detail).Infoln("broadcast tx to", len(peers), "peers")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Mined broadcast loop
|
|
|
|
func (self *ProtocolManager) minedBroadcastLoop() {
|
|
|
|
// automatically stops if unsubscribe
|
|
|
|
for obj := range self.minedBlockSub.Chan() {
|
2015-10-12 12:04:38 +00:00
|
|
|
switch ev := obj.Data.(type) {
|
2015-04-22 15:56:06 +00:00
|
|
|
case core.NewMinedBlockEvent:
|
2015-06-19 07:07:37 +00:00
|
|
|
self.BroadcastBlock(ev.Block, true) // First propagate block to peers
|
|
|
|
self.BroadcastBlock(ev.Block, false) // Only then announce to the rest
|
2015-04-22 15:56:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (self *ProtocolManager) txBroadcastLoop() {
|
|
|
|
// automatically stops if unsubscribe
|
|
|
|
for obj := range self.txSub.Chan() {
|
2015-10-12 12:04:38 +00:00
|
|
|
event := obj.Data.(core.TxPreEvent)
|
2015-04-22 15:56:06 +00:00
|
|
|
self.BroadcastTx(event.Tx.Hash(), event.Tx)
|
|
|
|
}
|
|
|
|
}
|
2015-10-27 13:10:30 +00:00
|
|
|
|
|
|
|
// EthNodeInfo represents a short summary of the Ethereum sub-protocol metadata known
|
|
|
|
// about the host peer.
|
|
|
|
type EthNodeInfo struct {
|
2016-01-18 12:28:03 +00:00
|
|
|
Network int `json:"network"` // Ethereum network ID (0=Olympic, 1=Frontier, 2=Morden)
|
|
|
|
Difficulty *big.Int `json:"difficulty"` // Total difficulty of the host's blockchain
|
|
|
|
Genesis common.Hash `json:"genesis"` // SHA3 hash of the host's genesis block
|
|
|
|
Head common.Hash `json:"head"` // SHA3 hash of the host's best owned block
|
2015-10-27 13:10:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NodeInfo retrieves some protocol metadata about the running host node.
|
|
|
|
func (self *ProtocolManager) NodeInfo() *EthNodeInfo {
|
2016-04-05 13:22:04 +00:00
|
|
|
currentBlock := self.blockchain.CurrentBlock()
|
2015-10-27 13:10:30 +00:00
|
|
|
return &EthNodeInfo{
|
|
|
|
Network: self.networkId,
|
2016-04-05 13:22:04 +00:00
|
|
|
Difficulty: self.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64()),
|
2016-01-18 12:28:03 +00:00
|
|
|
Genesis: self.blockchain.Genesis().Hash(),
|
2016-04-05 13:22:04 +00:00
|
|
|
Head: currentBlock.Hash(),
|
2015-10-27 13:10:30 +00:00
|
|
|
}
|
|
|
|
}
|