sync.go 5.3 KB
Newer Older
1 2 3 4
package eth

import (
	"math"
5
	"sync/atomic"
6 7
	"time"

8
	"github.com/ethereum/go-ethereum/common"
9
	"github.com/ethereum/go-ethereum/core/types"
10 11 12 13 14
	"github.com/ethereum/go-ethereum/eth/downloader"
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
)

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
// blockAnnounce is the hash notification of the availability of a new block in
// the network.
type blockAnnounce struct {
	hash common.Hash
	peer *peer
	time time.Time
}

// fetcher is responsible for collecting hash notifications, and periodically
// checking all unknown ones and individually fetching them.
func (pm *ProtocolManager) fetcher() {
	announces := make(map[common.Hash]*blockAnnounce)
	request := make(map[*peer][]common.Hash)
	cycle := time.Tick(notifyCheckCycle)

	// Iterate the block fetching until a quit is requested
	for {
		select {
		case notifications := <-pm.newHashCh:
			// A batch of hashes the notified, schedule them for retrieval
			glog.V(logger.Detail).Infof("Scheduling %d hash announces from %s", len(notifications), notifications[0].peer.id)
			for _, announce := range notifications {
				announces[announce.hash] = announce
			}

		case <-cycle:
			// Check if any notified blocks failed to arrive
			for hash, announce := range announces {
				if time.Since(announce.time) > notifyArriveTimeout {
					if !pm.chainman.HasBlock(hash) {
						request[announce.peer] = append(request[announce.peer], hash)
					}
					delete(announces, hash)
				}
			}
			if len(request) == 0 {
				break
			}
			// Send out all block requests
			for peer, hashes := range request {
				glog.V(logger.Detail).Infof("Fetching specific %d blocks from %s", len(hashes), peer.id)
				peer.requestBlocks(hashes)
			}
			request = make(map[*peer][]common.Hash)

		case <-pm.quitSync:
			return
		}
	}
}

// syncer is responsible for periodically synchronising with the network, both
// downloading hashes and blocks as well as retrieving cached ones.
func (pm *ProtocolManager) syncer() {
69 70
	forceSync := time.Tick(forceSyncCycle)
	blockProc := time.Tick(blockProcCycle)
71
	blockProcPend := int32(0)
O
obscuren 已提交
72

73 74 75
	for {
		select {
		case <-pm.newPeerCh:
76 77
			// Make sure we have peers to select from, then sync
			if pm.peers.Len() < minDesiredPeerCount {
78 79
				break
			}
80
			go pm.synchronise(pm.peers.BestPeer())
81

82 83
		case <-forceSync:
			// Force a sync even if not enough peers are present
84 85
			go pm.synchronise(pm.peers.BestPeer())

86 87
		case <-blockProc:
			// Try to pull some blocks from the downloaded
88 89
			if atomic.CompareAndSwapInt32(&blockProcPend, 0, 1) {
				go func() {
90
					pm.processBlocks()
91 92 93
					atomic.StoreInt32(&blockProcPend, 0)
				}()
			}
94

95
		case <-pm.quitSync:
O
obscuren 已提交
96
			return
97 98 99 100
		}
	}
}

101 102 103
// processBlocks retrieves downloaded blocks from the download cache and tries
// to construct the local block chain with it. Note, since the block retrieval
// order matters, access to this function *must* be synchronized/serialized.
104 105 106 107
func (pm *ProtocolManager) processBlocks() error {
	pm.wg.Add(1)
	defer pm.wg.Done()

108 109
	// Short circuit if no blocks are available for insertion
	blocks := pm.downloader.TakeBlocks()
110 111 112
	if len(blocks) == 0 {
		return nil
	}
113
	glog.V(logger.Debug).Infof("Inserting chain with %d blocks (#%v - #%v)\n", len(blocks), blocks[0].RawBlock.Number(), blocks[len(blocks)-1].RawBlock.Number())
114 115

	for len(blocks) != 0 && !pm.quit {
116
		// Retrieve the first batch of blocks to insert
117
		max := int(math.Min(float64(len(blocks)), float64(blockProcAmount)))
118 119 120 121 122 123
		raw := make(types.Blocks, 0, max)
		for _, block := range blocks[:max] {
			raw = append(raw, block.RawBlock)
		}
		// Try to inset the blocks, drop the originating peer if there's an error
		index, err := pm.chainman.InsertChain(raw)
124
		if err != nil {
125
			glog.V(logger.Debug).Infoln("Downloaded block import failed:", err)
126
			pm.removePeer(blocks[index].OriginPeer)
127
			pm.downloader.Cancel()
128 129 130 131 132 133 134
			return err
		}
		blocks = blocks[max:]
	}
	return nil
}

135 136
// synchronise tries to sync up our local block chain with a remote peer, both
// adding various sanity checks as well as wrapping it with various log entries.
137
func (pm *ProtocolManager) synchronise(peer *peer) {
138 139 140 141
	// Short circuit if no peers are available
	if peer == nil {
		return
	}
142 143 144 145
	// Make sure the peer's TD is higher than our own. If not drop.
	if peer.td.Cmp(pm.chainman.Td()) <= 0 {
		return
	}
146 147 148 149
	// FIXME if we have the hash in our chain and the TD of the peer is
	// much higher than ours, something is wrong with us or the peer.
	// Check if the hash is on our own chain
	if pm.chainman.HasBlock(peer.recentHash) {
150
		glog.V(logger.Debug).Infoln("Synchronisation canceled: head already known")
151 152
		return
	}
153
	// Get the hashes from the peer (synchronously)
154 155 156 157 158 159 160 161 162 163
	glog.V(logger.Debug).Infof("Attempting synchronisation: %v, 0x%x", peer.id, peer.recentHash)

	err := pm.downloader.Synchronise(peer.id, peer.recentHash)
	switch err {
	case nil:
		glog.V(logger.Debug).Infof("Synchronisation completed")

	case downloader.ErrBusy:
		glog.V(logger.Debug).Infof("Synchronisation already in progress")

164
	case downloader.ErrTimeout, downloader.ErrBadPeer, downloader.ErrEmptyHashSet, downloader.ErrInvalidChain, downloader.ErrCrossCheckFailed:
165
		glog.V(logger.Debug).Infof("Removing peer %v: %v", peer.id, err)
166
		pm.removePeer(peer.id)
167

168 169
	case downloader.ErrPendingQueue:
		glog.V(logger.Debug).Infoln("Synchronisation aborted:", err)
170

171 172
	default:
		glog.V(logger.Warn).Infof("Synchronisation failed: %v", err)
173 174
	}
}