2015-07-06 17:54:22 -07:00
|
|
|
// Copyright 2015 The go-ethereum Authors
|
2015-07-22 09:48:40 -07:00
|
|
|
// This file is part of the go-ethereum library.
|
2015-07-06 17:54:22 -07:00
|
|
|
//
|
2015-07-23 09:35:11 -07:00
|
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
2015-07-06 17:54:22 -07: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 09:48:40 -07:00
|
|
|
// The go-ethereum library is distributed in the hope that it will be useful,
|
2015-07-06 17:54:22 -07:00
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
2015-07-22 09:48:40 -07:00
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
2015-07-06 17:54:22 -07: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 09:48:40 -07:00
|
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
2015-07-06 17:54:22 -07:00
|
|
|
|
2015-04-17 16:11:09 -07:00
|
|
|
package eth
|
|
|
|
|
|
|
|
import (
|
2015-09-01 07:35:14 -07:00
|
|
|
"errors"
|
2015-04-17 16:11:09 -07:00
|
|
|
"fmt"
|
2015-06-04 08:46:07 -07:00
|
|
|
"math"
|
2015-07-09 03:55:06 -07:00
|
|
|
"math/big"
|
2015-04-17 16:11:09 -07:00
|
|
|
"sync"
|
2016-05-17 04:17:20 -07:00
|
|
|
"sync/atomic"
|
2015-04-24 05:40:32 -07:00
|
|
|
"time"
|
2015-04-17 16:11:09 -07:00
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/common"
|
2015-04-17 17:21:07 -07:00
|
|
|
"github.com/ethereum/go-ethereum/core"
|
2015-04-17 16:11:09 -07:00
|
|
|
"github.com/ethereum/go-ethereum/core/types"
|
|
|
|
"github.com/ethereum/go-ethereum/eth/downloader"
|
2015-06-17 06:53:28 -07:00
|
|
|
"github.com/ethereum/go-ethereum/eth/fetcher"
|
2015-09-14 00:35:57 -07:00
|
|
|
"github.com/ethereum/go-ethereum/ethdb"
|
2015-04-22 08:56:06 -07:00
|
|
|
"github.com/ethereum/go-ethereum/event"
|
2015-04-17 16:11:09 -07:00
|
|
|
"github.com/ethereum/go-ethereum/logger"
|
|
|
|
"github.com/ethereum/go-ethereum/logger/glog"
|
|
|
|
"github.com/ethereum/go-ethereum/p2p"
|
2015-10-27 06:10:30 -07:00
|
|
|
"github.com/ethereum/go-ethereum/p2p/discover"
|
2015-06-19 00:07:37 -07:00
|
|
|
"github.com/ethereum/go-ethereum/pow"
|
2015-04-17 16:11:09 -07:00
|
|
|
"github.com/ethereum/go-ethereum/rlp"
|
|
|
|
)
|
|
|
|
|
2015-09-07 10:43:01 -07: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 03:00:41 -07:00
|
|
|
|
2016-07-08 10:59:11 -07:00
|
|
|
var (
|
|
|
|
daoChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the DAO handshake challenge
|
|
|
|
)
|
|
|
|
|
2015-09-01 07:35:14 -07: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 16:11:09 -07:00
|
|
|
func errResp(code errCode, format string, v ...interface{}) error {
|
|
|
|
return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...))
|
|
|
|
}
|
|
|
|
|
2015-04-17 17:21:07 -07:00
|
|
|
type ProtocolManager struct {
|
2015-10-27 06:10:30 -07:00
|
|
|
networkId int
|
|
|
|
|
2016-06-02 05:54:07 -07: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 10:59:11 -07:00
|
|
|
txpool txPool
|
|
|
|
blockchain *core.BlockChain
|
|
|
|
chaindb ethdb.Database
|
|
|
|
chainconfig *core.ChainConfig
|
2015-07-02 09:55:18 -07:00
|
|
|
|
|
|
|
downloader *downloader.Downloader
|
|
|
|
fetcher *fetcher.Fetcher
|
|
|
|
peers *peerSet
|
2015-04-17 17:21:07 -07:00
|
|
|
|
2015-06-26 06:54:27 -07:00
|
|
|
SubProtocols []p2p.Protocol
|
2015-04-22 08:56:06 -07:00
|
|
|
|
|
|
|
eventMux *event.TypeMux
|
|
|
|
txSub event.Subscription
|
|
|
|
minedBlockSub event.Subscription
|
2015-04-24 05:40:32 -07:00
|
|
|
|
2015-06-09 03:03:14 -07:00
|
|
|
// channels for fetcher, syncer, txsyncLoop
|
2016-03-28 18:08:16 -07:00
|
|
|
newPeerCh chan *peer
|
|
|
|
txsyncCh chan *txsync
|
|
|
|
quitSync chan struct{}
|
|
|
|
noMorePeers chan struct{}
|
2015-06-08 10:38:39 -07:00
|
|
|
|
2015-04-30 15:23:51 -07:00
|
|
|
// wait group is used for graceful shutdowns during downloading
|
|
|
|
// and processing
|
2016-03-28 18:08:16 -07:00
|
|
|
wg sync.WaitGroup
|
2016-05-24 09:49:54 -07:00
|
|
|
|
|
|
|
badBlockReportingEnabled bool
|
2015-04-17 16:11:09 -07:00
|
|
|
}
|
|
|
|
|
2015-04-17 17:21:07 -07:00
|
|
|
// NewProtocolManager returns a new ethereum sub protocol manager. The Ethereum sub protocol manages peers capable
|
|
|
|
// with the ethereum network.
|
2016-03-01 14:32:43 -08: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 06:54:27 -07:00
|
|
|
// Create the protocol manager with the base fields
|
2015-04-17 17:21:07 -07:00
|
|
|
manager := &ProtocolManager{
|
2016-03-28 18:08:16 -07:00
|
|
|
networkId: networkId,
|
|
|
|
eventMux: mux,
|
|
|
|
txpool: txpool,
|
|
|
|
blockchain: blockchain,
|
|
|
|
chaindb: chaindb,
|
2016-07-08 10:59:11 -07:00
|
|
|
chainconfig: config,
|
2016-03-28 18:08:16 -07:00
|
|
|
peers: newPeerSet(),
|
|
|
|
newPeerCh: make(chan *peer),
|
|
|
|
noMorePeers: make(chan struct{}),
|
|
|
|
txsyncCh: make(chan *txsync),
|
|
|
|
quitSync: make(chan struct{}),
|
2015-04-17 16:11:09 -07:00
|
|
|
}
|
2016-05-17 04:17:20 -07: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 06:54:27 -07:00
|
|
|
// Initiate a sub-protocol for every implemented version we can handle
|
2015-09-01 07:35:14 -07: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 08:36:31 -07:00
|
|
|
if fastSync && version < eth63 {
|
2015-09-01 07:35:14 -07:00
|
|
|
continue
|
|
|
|
}
|
2015-10-13 02:04:25 -07:00
|
|
|
// Compatible; initialise the sub-protocol
|
2015-09-01 07:35:14 -07:00
|
|
|
version := version // Closure for the run
|
|
|
|
manager.SubProtocols = append(manager.SubProtocols, p2p.Protocol{
|
2015-10-27 06:10:30 -07:00
|
|
|
Name: ProtocolName,
|
2015-06-26 06:54:27 -07:00
|
|
|
Version: version,
|
|
|
|
Length: ProtocolLengths[i],
|
|
|
|
Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
|
2015-10-27 06:10:30 -07:00
|
|
|
peer := manager.newPeer(int(version), p, rw)
|
2016-03-28 18:08:16 -07: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 06:54:27 -07:00
|
|
|
},
|
2015-10-27 06:10:30 -07: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 07:35:14 -07:00
|
|
|
})
|
|
|
|
}
|
|
|
|
if len(manager.SubProtocols) == 0 {
|
|
|
|
return nil, errIncompatibleConfig
|
2015-04-17 17:21:07 -07:00
|
|
|
}
|
2015-06-16 01:58:32 -07:00
|
|
|
// Construct the different synchronisation mechanisms
|
2016-04-05 06:22:04 -07: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 04:01:08 -08:00
|
|
|
manager.removePeer)
|
2015-06-16 01:58:32 -07:00
|
|
|
|
2015-06-18 08:00:19 -07:00
|
|
|
validator := func(block *types.Block, parent *types.Block) error {
|
2016-03-01 14:32:43 -08:00
|
|
|
return core.ValidateHeader(config, pow, block.Header(), parent.Header(), true, false)
|
2015-06-18 08:00:19 -07:00
|
|
|
}
|
2015-06-16 07:39:04 -07:00
|
|
|
heighter := func() uint64 {
|
2015-09-28 09:27:31 -07:00
|
|
|
return blockchain.CurrentBlock().NumberU64()
|
2015-06-16 07:39:04 -07:00
|
|
|
}
|
2016-06-02 05:54:07 -07: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 06:22:04 -07:00
|
|
|
manager.fetcher = fetcher.New(blockchain.GetBlockByHash, validator, manager.BroadcastBlock, heighter, inserter, manager.removePeer)
|
2016-05-24 09:49:54 -07:00
|
|
|
|
|
|
|
if blockchain.Genesis().Hash().Hex() == defaultGenesisHash && networkId == 1 {
|
|
|
|
glog.V(logger.Debug).Infoln("Bad Block Reporting is enabled")
|
|
|
|
manager.badBlockReportingEnabled = true
|
|
|
|
}
|
2015-04-17 17:21:07 -07:00
|
|
|
|
2015-09-01 07:35:14 -07:00
|
|
|
return manager, nil
|
2015-04-17 16:11:09 -07:00
|
|
|
}
|
|
|
|
|
2016-05-24 09:49:54 -07: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 04:00:21 -07:00
|
|
|
func (pm *ProtocolManager) removePeer(id string) {
|
2015-05-27 08:58:51 -07: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 11:33:37 -07:00
|
|
|
|
2015-05-27 08:58:51 -07:00
|
|
|
// Unregister the peer from the downloader and Ethereum peer set
|
|
|
|
pm.downloader.UnregisterPeer(id)
|
2015-05-26 04:00:21 -07:00
|
|
|
if err := pm.peers.Unregister(id); err != nil {
|
2015-05-18 11:33:37 -07:00
|
|
|
glog.V(logger.Error).Infoln("Removal failed:", err)
|
|
|
|
}
|
2015-05-27 08:58:51 -07:00
|
|
|
// Hard disconnect at the networking layer
|
|
|
|
if peer != nil {
|
|
|
|
peer.Peer.Disconnect(p2p.DiscUselessPeer)
|
|
|
|
}
|
2015-04-30 03:38:16 -07:00
|
|
|
}
|
|
|
|
|
2015-04-22 08:56:06 -07: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 06:37:32 -07:00
|
|
|
|
2015-06-09 03:03:14 -07:00
|
|
|
// start sync handlers
|
2015-06-08 09:24:56 -07:00
|
|
|
go pm.syncer()
|
2015-06-09 03:03:14 -07:00
|
|
|
go pm.txsyncLoop()
|
2015-04-22 08:56:06 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func (pm *ProtocolManager) Stop() {
|
2015-04-30 15:23:51 -07:00
|
|
|
glog.V(logger.Info).Infoln("Stopping ethereum protocol handler...")
|
|
|
|
|
2015-04-22 08:56:06 -07:00
|
|
|
pm.txSub.Unsubscribe() // quits txBroadcastLoop
|
|
|
|
pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
|
2015-04-30 15:23:51 -07:00
|
|
|
|
2016-03-28 18:08:16 -07: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 15:23:51 -07:00
|
|
|
pm.wg.Wait()
|
|
|
|
|
|
|
|
glog.V(logger.Info).Infoln("Ethereum protocol handler stopped")
|
2015-04-22 08:56:06 -07:00
|
|
|
}
|
|
|
|
|
2015-10-27 06:10:30 -07:00
|
|
|
func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
|
|
|
|
return newPeer(pv, p, newMeteredMsgWriter(rw))
|
2015-04-17 16:11:09 -07:00
|
|
|
}
|
|
|
|
|
2015-06-26 10:42:27 -07: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-17 17:21:07 -07:00
|
|
|
func (pm *ProtocolManager) handle(p *peer) error {
|
2015-07-01 05:19:11 -07:00
|
|
|
glog.V(logger.Debug).Infof("%v: peer connected [%s]", p, p.Name())
|
2015-06-26 10:42:27 -07:00
|
|
|
|
|
|
|
// Execute the Ethereum handshake
|
2015-08-31 08:09:50 -07:00
|
|
|
td, head, genesis := pm.blockchain.Status()
|
2015-10-27 06:10:30 -07:00
|
|
|
if err := p.Handshake(pm.networkId, td, head, genesis); err != nil {
|
2015-06-26 10:42:27 -07:00
|
|
|
glog.V(logger.Debug).Infof("%v: handshake failed: %v", p, err)
|
2015-04-17 16:11:09 -07:00
|
|
|
return err
|
|
|
|
}
|
2015-07-02 09:55:18 -07:00
|
|
|
if rw, ok := p.rw.(*meteredMsgReadWriter); ok {
|
|
|
|
rw.Init(p.version)
|
|
|
|
}
|
2015-06-26 10:42:27 -07:00
|
|
|
// Register the peer locally
|
|
|
|
glog.V(logger.Detail).Infof("%v: adding peer", p)
|
2015-05-18 11:33:37 -07:00
|
|
|
if err := pm.peers.Register(p); err != nil {
|
2015-06-26 10:42:27 -07:00
|
|
|
glog.V(logger.Error).Infof("%v: addition failed: %v", p, err)
|
2015-05-18 11:33:37 -07:00
|
|
|
return err
|
|
|
|
}
|
2015-05-26 04:00:21 -07:00
|
|
|
defer pm.removePeer(p.id)
|
2015-04-17 16:11:09 -07:00
|
|
|
|
2015-06-26 10:42:27 -07:00
|
|
|
// Register the peer in the downloader. If the downloader considers it banned, we disconnect
|
2016-07-21 02:36:38 -07:00
|
|
|
err := pm.downloader.RegisterPeer(p.id, p.version, p.Head(),
|
|
|
|
p.RequestHeadersByHash, p.RequestHeadersByNumber,
|
|
|
|
p.RequestBodies, p.RequestReceipts, p.RequestNodeData,
|
|
|
|
)
|
|
|
|
if err != nil {
|
2015-05-18 11:33:37 -07:00
|
|
|
return err
|
|
|
|
}
|
2015-06-09 03:03:14 -07:00
|
|
|
// Propagate existing transactions. new transactions appearing
|
2015-04-17 16:11:09 -07:00
|
|
|
// after this will be sent via broadcasts.
|
2015-06-09 03:03:14 -07:00
|
|
|
pm.syncTransactions(p)
|
|
|
|
|
2016-07-08 10:59:11 -07: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() {
|
|
|
|
glog.V(logger.Warn).Infof("%v: timed out DAO fork-check, dropping", p)
|
|
|
|
pm.removePeer(p.id)
|
|
|
|
})
|
2016-07-19 02:00:09 -07: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 10:59:11 -07:00
|
|
|
}
|
2015-04-17 16:11:09 -07:00
|
|
|
// main loop. handle incoming messages.
|
|
|
|
for {
|
|
|
|
if err := pm.handleMsg(p); err != nil {
|
2015-06-26 10:42:27 -07:00
|
|
|
glog.V(logger.Debug).Infof("%v: message handling failed: %v", p, err)
|
2015-04-17 16:11:09 -07:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-06-26 10:42:27 -07: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 08:25:23 -07:00
|
|
|
func (pm *ProtocolManager) handleMsg(p *peer) error {
|
2015-06-26 10:42:27 -07:00
|
|
|
// Read the next message from the remote peer, and ensure it's fully consumed
|
2015-04-17 16:11:09 -07: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 10:42:27 -07:00
|
|
|
// Handle the message depending on its contents
|
2015-07-02 09:55:18 -07:00
|
|
|
switch {
|
|
|
|
case msg.Code == StatusMsg:
|
2015-06-30 09:05:06 -07:00
|
|
|
// Status messages should never arrive after the handshake
|
2015-04-17 16:11:09 -07:00
|
|
|
return errResp(ErrExtraStatusMsg, "uncontrolled status message")
|
|
|
|
|
2015-07-02 09:55:18 -07:00
|
|
|
// Block header query, collect the requested headers and reply
|
2016-07-21 02:36:38 -07:00
|
|
|
case msg.Code == GetBlockHeadersMsg:
|
2015-07-02 09:55:18 -07: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 09:22:48 -08:00
|
|
|
hashMode := query.Origin.Hash != (common.Hash{})
|
|
|
|
|
2015-08-31 10:21:02 -07:00
|
|
|
// Gather headers until the fetch or network limits is reached
|
2015-07-02 09:55:18 -07: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 10:21:02 -07:00
|
|
|
// Retrieve the next header satisfying the query
|
|
|
|
var origin *types.Header
|
2015-12-15 09:22:48 -08:00
|
|
|
if hashMode {
|
2016-04-05 06:22:04 -07:00
|
|
|
origin = pm.blockchain.GetHeaderByHash(query.Origin.Hash)
|
2015-07-02 09:55:18 -07:00
|
|
|
} else {
|
2015-08-31 08:09:50 -07:00
|
|
|
origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number)
|
2015-07-02 09:55:18 -07:00
|
|
|
}
|
|
|
|
if origin == nil {
|
|
|
|
break
|
|
|
|
}
|
2016-04-05 06:22:04 -07:00
|
|
|
number := origin.Number.Uint64()
|
2015-08-31 10:21:02 -07:00
|
|
|
headers = append(headers, origin)
|
2015-09-07 10:43:01 -07:00
|
|
|
bytes += estHeaderRlpSize
|
2015-07-02 09:55:18 -07:00
|
|
|
|
2015-08-31 10:21:02 -07:00
|
|
|
// Advance to the next header of the query
|
2015-07-02 09:55:18 -07: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 06:22:04 -07:00
|
|
|
if header := pm.blockchain.GetHeader(query.Origin.Hash, number); header != nil {
|
2015-08-31 10:21:02 -07:00
|
|
|
query.Origin.Hash = header.ParentHash
|
2016-04-05 06:22:04 -07:00
|
|
|
number--
|
2015-07-02 09:55:18 -07:00
|
|
|
} else {
|
|
|
|
unknown = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
case query.Origin.Hash != (common.Hash{}) && !query.Reverse:
|
|
|
|
// Hash based traversal towards the leaf block
|
2015-08-31 08:09:50 -07:00
|
|
|
if header := pm.blockchain.GetHeaderByNumber(origin.Number.Uint64() + query.Skip + 1); header != nil {
|
|
|
|
if pm.blockchain.GetBlockHashesFromHash(header.Hash(), query.Skip+1)[query.Skip] == query.Origin.Hash {
|
2015-08-31 10:21:02 -07:00
|
|
|
query.Origin.Hash = header.Hash()
|
2015-07-02 09:55:18 -07:00
|
|
|
} else {
|
|
|
|
unknown = true
|
|
|
|
}
|
|
|
|
} 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 02:36:38 -07:00
|
|
|
case msg.Code == BlockHeadersMsg:
|
2015-08-14 11:25:41 -07: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 10:59:11 -07: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 {
|
|
|
|
if p.Td().Cmp(pm.blockchain.GetTd(daoHeader.Hash(), daoHeader.Number.Uint64())) >= 0 {
|
|
|
|
verifyDAO = false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// If we're seemingly on the same chain, disable the drop timer
|
|
|
|
if verifyDAO {
|
2016-07-14 01:22:58 -07:00
|
|
|
glog.V(logger.Debug).Infof("%v: seems to be on the same side of the DAO fork", p)
|
2016-07-08 10:59:11 -07:00
|
|
|
p.forkDrop.Stop()
|
|
|
|
p.forkDrop = nil
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
2015-08-14 11:25:41 -07:00
|
|
|
// Filter out any explicitly requested headers, deliver the rest to the downloader
|
|
|
|
filter := len(headers) == 1
|
|
|
|
if filter {
|
2016-07-08 10:59:11 -07: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 01:22:58 -07: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 10:59:11 -07:00
|
|
|
return err
|
|
|
|
}
|
2016-07-14 01:22:58 -07:00
|
|
|
glog.V(logger.Debug).Infof("%v: verified to be on the same side of the DAO fork", p)
|
2016-07-08 10:59:11 -07:00
|
|
|
}
|
|
|
|
// Irrelevant of the fork checks, send the header to the fetcher just in case
|
2015-08-14 11:25:41 -07: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 02:36:38 -07:00
|
|
|
case msg.Code == GetBlockBodiesMsg:
|
2015-07-02 09:55:18 -07:00
|
|
|
// Decode the retrieval message
|
2015-06-04 08:46:07 -07:00
|
|
|
msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
|
2015-07-02 09:55:18 -07: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 10:21:02 -07:00
|
|
|
bytes int
|
2015-09-07 10:43:01 -07:00
|
|
|
bodies []rlp.RawValue
|
2015-07-02 09:55:18 -07:00
|
|
|
)
|
|
|
|
for bytes < softResponseLimit && len(bodies) < downloader.MaxBlockFetch {
|
2015-08-31 10:21:02 -07:00
|
|
|
// Retrieve the hash of the next block
|
2015-07-02 09:55:18 -07: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 10:21:02 -07:00
|
|
|
// Retrieve the requested block body, stopping if enough was found
|
2015-08-31 08:09:50 -07:00
|
|
|
if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 {
|
2015-09-07 10:43:01 -07:00
|
|
|
bodies = append(bodies, data)
|
|
|
|
bytes += len(data)
|
2015-07-02 09:55:18 -07:00
|
|
|
}
|
|
|
|
}
|
2015-08-31 10:21:02 -07:00
|
|
|
return p.SendBlockBodiesRLP(bodies)
|
2015-06-04 08:46:07 -07:00
|
|
|
|
2016-07-21 02:36:38 -07:00
|
|
|
case msg.Code == BlockBodiesMsg:
|
2015-09-30 09:23:31 -07: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 03:06:23 -08: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 09:23:31 -07:00
|
|
|
err := pm.downloader.DeliverBodies(p.id, trasactions, uncles)
|
|
|
|
if err != nil {
|
|
|
|
glog.V(logger.Debug).Infoln(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-07-02 09:55:18 -07:00
|
|
|
case p.version >= eth63 && msg.Code == GetNodeDataMsg:
|
|
|
|
// Decode the retrieval message
|
2015-06-04 08:46:07 -07:00
|
|
|
msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
|
2015-07-02 09:55:18 -07:00
|
|
|
if _, err := msgStream.List(); err != nil {
|
|
|
|
return err
|
2015-06-04 08:46:07 -07:00
|
|
|
}
|
2015-07-02 09:55:18 -07: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 10:42:27 -07:00
|
|
|
|
2015-10-05 09:37:56 -07: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 09:55:18 -07: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 09:27:31 -07:00
|
|
|
receipts []rlp.RawValue
|
2015-07-02 09:55:18 -07:00
|
|
|
)
|
2015-09-28 09:27:31 -07:00
|
|
|
for bytes < softResponseLimit && len(receipts) < downloader.MaxReceiptFetch {
|
|
|
|
// Retrieve the hash of the next block
|
2015-07-02 09:55:18 -07: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 09:27:31 -07:00
|
|
|
// Retrieve the requested block's receipts, skipping if unknown to us
|
2016-04-05 06:22:04 -07:00
|
|
|
results := core.GetBlockReceipts(pm.chaindb, hash, core.GetBlockNumber(pm.chaindb, hash))
|
2015-09-28 09:27:31 -07:00
|
|
|
if results == nil {
|
2016-04-05 06:22:04 -07:00
|
|
|
if header := pm.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
|
2015-09-28 09:27:31 -07: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 09:55:18 -07:00
|
|
|
}
|
|
|
|
}
|
2015-09-28 09:27:31 -07:00
|
|
|
return p.SendReceiptsRLP(receipts)
|
2015-07-02 09:55:18 -07:00
|
|
|
|
2015-09-30 09:23:31 -07: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 09:55:18 -07:00
|
|
|
case msg.Code == NewBlockHashesMsg:
|
2016-03-15 11:27:49 -07:00
|
|
|
// Retrieve and deserialize the remote new block hashes notification
|
2015-07-02 09:55:18 -07: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 08:46:07 -07:00
|
|
|
}
|
|
|
|
// Mark the hashes as present at the remote node
|
2015-07-02 09:55:18 -07:00
|
|
|
for _, block := range announces {
|
|
|
|
p.MarkBlock(block.Hash)
|
|
|
|
p.SetHead(block.Hash)
|
2015-06-04 08:46:07 -07:00
|
|
|
}
|
2015-06-08 09:24:56 -07:00
|
|
|
// Schedule all the unknown hashes for retrieval
|
2015-07-02 09:55:18 -07:00
|
|
|
unknown := make([]announce, 0, len(announces))
|
|
|
|
for _, block := range announces {
|
2015-08-31 08:09:50 -07:00
|
|
|
if !pm.blockchain.HasBlock(block.Hash) {
|
2015-07-02 09:55:18 -07:00
|
|
|
unknown = append(unknown, block)
|
2015-06-04 08:46:07 -07:00
|
|
|
}
|
2015-06-08 09:24:56 -07:00
|
|
|
}
|
2015-07-02 09:55:18 -07:00
|
|
|
for _, block := range unknown {
|
2016-07-21 02:36:38 -07:00
|
|
|
pm.fetcher.Notify(p.id, block.Hash, block.Number, time.Now(), p.RequestOneHeader, p.RequestBodies)
|
2015-06-08 09:24:56 -07:00
|
|
|
}
|
2015-04-17 16:11:09 -07:00
|
|
|
|
2015-07-02 09:55:18 -07:00
|
|
|
case msg.Code == NewBlockMsg:
|
2015-06-17 08:25:23 -07:00
|
|
|
// Retrieve and decode the propagated block
|
2015-06-29 07:32:14 -07:00
|
|
|
var request newBlockData
|
2015-04-17 16:11:09 -07:00
|
|
|
if err := msg.Decode(&request); err != nil {
|
|
|
|
return errResp(ErrDecode, "%v: %v", msg, err)
|
|
|
|
}
|
|
|
|
if err := request.Block.ValidateFields(); err != nil {
|
|
|
|
return errResp(ErrDecode, "block validation %v: %v", msg, err)
|
|
|
|
}
|
2015-04-29 13:50:58 -07:00
|
|
|
request.Block.ReceivedAt = msg.ReceivedAt
|
2016-05-24 09:49:54 -07:00
|
|
|
request.Block.ReceivedFrom = p
|
2015-04-29 10:55:30 -07:00
|
|
|
|
2015-06-17 08:25:23 -07:00
|
|
|
// Mark the peer as owning the block and schedule it for import
|
2015-06-29 02:44:00 -07:00
|
|
|
p.MarkBlock(request.Block.Hash())
|
2015-06-17 08:25:23 -07:00
|
|
|
p.SetHead(request.Block.Hash())
|
|
|
|
|
|
|
|
pm.fetcher.Enqueue(p.id, request.Block)
|
|
|
|
|
2015-08-19 05:14:26 -07:00
|
|
|
// Update the peers total difficulty if needed, schedule a download if gapped
|
2015-07-09 03:55:06 -07:00
|
|
|
if request.TD.Cmp(p.Td()) > 0 {
|
|
|
|
p.SetTd(request.TD)
|
2016-04-05 06:22:04 -07:00
|
|
|
currentBlock := pm.blockchain.CurrentBlock()
|
|
|
|
td := pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
|
2015-09-21 05:36:29 -07:00
|
|
|
if request.TD.Cmp(new(big.Int).Add(td, request.Block.Difficulty())) > 0 {
|
2015-08-19 05:14:26 -07:00
|
|
|
go pm.synchronise(p)
|
|
|
|
}
|
2015-07-09 03:55:06 -07:00
|
|
|
}
|
2015-04-17 17:24:24 -07:00
|
|
|
|
2015-07-02 09:55:18 -07:00
|
|
|
case msg.Code == TxMsg:
|
2016-06-02 05:54:07 -07:00
|
|
|
// Transactions arrived, make sure we have a valid and fresh chain to handle them
|
|
|
|
if atomic.LoadUint32(&pm.synced) == 0 {
|
2016-05-17 04:17:20 -07:00
|
|
|
break
|
|
|
|
}
|
|
|
|
// Transactions can be processed, parse all of them and deliver to the pool
|
2015-06-30 09:05:06 -07: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())
|
|
|
|
}
|
|
|
|
pm.txpool.AddTransactions(txs)
|
|
|
|
|
2015-04-17 16:11:09 -07:00
|
|
|
default:
|
|
|
|
return errResp(ErrInvalidMsgCode, "%v", msg.Code)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2015-04-17 17:21:07 -07:00
|
|
|
|
2015-06-18 08:00:19 -07: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 06:09:34 -07:00
|
|
|
hash := block.Hash()
|
|
|
|
peers := pm.peers.PeersWithoutBlock(hash)
|
2015-06-04 08:46:07 -07:00
|
|
|
|
2015-06-18 08:00:19 -07:00
|
|
|
// If propagation is requested, send to a subset of the peer
|
|
|
|
if propagate {
|
2015-07-09 03:55:06 -07: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 06:22:04 -07: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 03:55:06 -07: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 08:00:19 -07:00
|
|
|
transfer := peers[:int(math.Sqrt(float64(len(peers))))]
|
|
|
|
for _, peer := range transfer {
|
2015-07-09 03:55:06 -07:00
|
|
|
peer.SendNewBlock(block, td)
|
2015-06-18 08:00:19 -07: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 08:46:07 -07:00
|
|
|
}
|
2015-06-18 08:00:19 -07:00
|
|
|
// Otherwise if the block is indeed in out own chain, announce it
|
2015-08-31 08:09:50 -07:00
|
|
|
if pm.blockchain.HasBlock(hash) {
|
2015-06-18 08:00:19 -07:00
|
|
|
for _, peer := range peers {
|
2016-07-21 02:36:38 -07:00
|
|
|
peer.SendNewBlockHashes([]common.Hash{hash}, []uint64{block.NumberU64()})
|
2015-06-18 08:00:19 -07:00
|
|
|
}
|
|
|
|
glog.V(logger.Detail).Infof("announced block %x to %d peers in %v", hash[:4], len(peers), time.Since(block.ReceivedAt))
|
2015-04-17 17:21:07 -07:00
|
|
|
}
|
|
|
|
}
|
2015-04-22 08:56:06 -07:00
|
|
|
|
2015-06-26 10:42:27 -07:00
|
|
|
// BroadcastTx will propagate a transaction to all peers which are not known to
|
|
|
|
// already have the given transaction.
|
2015-04-22 08:56:06 -07:00
|
|
|
func (pm *ProtocolManager) BroadcastTx(hash common.Hash, tx *types.Transaction) {
|
2015-05-18 11:33:37 -07:00
|
|
|
// Broadcast transaction to a batch of peers not knowing about it
|
2015-05-20 00:34:45 -07:00
|
|
|
peers := pm.peers.PeersWithoutTx(hash)
|
2015-05-12 07:27:17 -07:00
|
|
|
//FIXME include this again: peers = peers[:int(math.Sqrt(float64(len(peers))))]
|
2015-04-22 08:56:06 -07:00
|
|
|
for _, peer := range peers {
|
2015-06-29 02:44:00 -07:00
|
|
|
peer.SendTransactions(types.Transactions{tx})
|
2015-04-22 08:56:06 -07: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 05:04:38 -07:00
|
|
|
switch ev := obj.Data.(type) {
|
2015-04-22 08:56:06 -07:00
|
|
|
case core.NewMinedBlockEvent:
|
2015-06-19 00:07:37 -07: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 08:56:06 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (self *ProtocolManager) txBroadcastLoop() {
|
|
|
|
// automatically stops if unsubscribe
|
|
|
|
for obj := range self.txSub.Chan() {
|
2015-10-12 05:04:38 -07:00
|
|
|
event := obj.Data.(core.TxPreEvent)
|
2015-04-22 08:56:06 -07:00
|
|
|
self.BroadcastTx(event.Tx.Hash(), event.Tx)
|
|
|
|
}
|
|
|
|
}
|
2015-10-27 06:10:30 -07:00
|
|
|
|
|
|
|
// EthNodeInfo represents a short summary of the Ethereum sub-protocol metadata known
|
|
|
|
// about the host peer.
|
|
|
|
type EthNodeInfo struct {
|
2016-01-18 04:28:03 -08: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 06:10:30 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// NodeInfo retrieves some protocol metadata about the running host node.
|
|
|
|
func (self *ProtocolManager) NodeInfo() *EthNodeInfo {
|
2016-04-05 06:22:04 -07:00
|
|
|
currentBlock := self.blockchain.CurrentBlock()
|
2015-10-27 06:10:30 -07:00
|
|
|
return &EthNodeInfo{
|
|
|
|
Network: self.networkId,
|
2016-04-05 06:22:04 -07:00
|
|
|
Difficulty: self.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64()),
|
2016-01-18 04:28:03 -08:00
|
|
|
Genesis: self.blockchain.Genesis().Hash(),
|
2016-04-05 06:22:04 -07:00
|
|
|
Head: currentBlock.Hash(),
|
2015-10-27 06:10:30 -07:00
|
|
|
}
|
|
|
|
}
|