sync.go 7.8 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
const (
	forceSyncCycle      = 10 * time.Second       // Time interval to force syncs, even if few peers are available
	blockProcCycle      = 500 * time.Millisecond // Time interval to check for new blocks to process
	notifyCheckCycle    = 100 * time.Millisecond // Time interval to allow hash notifies to fulfill before hard fetching
	notifyArriveTimeout = 500 * time.Millisecond // Time allowance before an announced block is explicitly requested
	notifyFetchTimeout  = 5 * time.Second        // Maximum alloted time to return an explicitly requested block
	minDesiredPeerCount = 5                      // Amount of peers desired to start syncing
	blockProcAmount     = 256
)

25 26 27 28 29 30 31 32 33 34 35 36 37
// 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)
38
	pending := make(map[common.Hash]*blockAnnounce)
39 40 41 42 43 44 45
	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
46
			glog.V(logger.Debug).Infof("Scheduling %d hash announcements from %s", len(notifications), notifications[0].peer.id)
47 48 49 50 51
			for _, announce := range notifications {
				announces[announce.hash] = announce
			}

		case <-cycle:
52 53 54 55 56 57
			// Clean up any expired block fetches
			for hash, announce := range pending {
				if time.Since(announce.time) > notifyFetchTimeout {
					delete(pending, hash)
				}
			}
58 59 60 61 62
			// 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)
63
						pending[hash] = announce
64 65 66 67 68 69 70 71 72
					}
					delete(announces, hash)
				}
			}
			if len(request) == 0 {
				break
			}
			// Send out all block requests
			for peer, hashes := range request {
73
				glog.V(logger.Debug).Infof("Explicitly fetching %d blocks from %s", len(hashes), peer.id)
74 75 76 77
				peer.requestBlocks(hashes)
			}
			request = make(map[*peer][]common.Hash)

78
		case filter := <-pm.newBlockCh:
79
			// Blocks arrived, extract any explicit fetches, return all else
80 81 82 83 84 85 86
			var blocks types.Blocks
			select {
			case blocks = <-filter:
			case <-pm.quitSync:
				return
			}

87
			explicit, download := []*types.Block{}, []*types.Block{}
88 89
			for _, block := range blocks {
				hash := block.Hash()
90 91

				// Filter explicitly requested blocks from hash announcements
92
				if _, ok := pending[hash]; ok {
93 94 95 96 97 98
					// Discard if already imported by other means
					if !pm.chainman.HasBlock(hash) {
						explicit = append(explicit, block)
					} else {
						delete(pending, hash)
					}
99
				} else {
100
					download = append(download, block)
101 102 103 104
				}
			}

			select {
105
			case filter <- download:
106 107 108 109
			case <-pm.quitSync:
				return
			}
			// If any explicit fetches were replied to, import them
110 111
			if count := len(explicit); count > 0 {
				glog.V(logger.Debug).Infof("Importing %d explicitly fetched blocks", count)
112 113 114 115 116 117 118 119 120 121 122 123 124 125

				// Create a closure with the retrieved blocks and origin peers
				peers := make([]*peer, 0, count)
				blocks := make([]*types.Block, 0, count)
				for _, block := range explicit {
					hash := block.Hash()
					if announce := pending[hash]; announce != nil {
						peers = append(peers, announce.peer)
						blocks = append(blocks, block)

						delete(pending, hash)
					}
				}
				// Run the importer on a new thread
126
				go func() {
127 128 129 130
					for i := 0; i < len(blocks); i++ {
						if err := pm.importBlock(peers[i], blocks[i], nil); err != nil {
							glog.V(logger.Detail).Infof("Failed to import explicitly fetched block: %v", err)
							return
131 132 133 134 135
						}
					}
				}()
			}

136 137 138 139 140 141 142 143 144
		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() {
145 146
	forceSync := time.Tick(forceSyncCycle)
	blockProc := time.Tick(blockProcCycle)
147
	blockProcPend := int32(0)
O
obscuren 已提交
148

149 150 151
	for {
		select {
		case <-pm.newPeerCh:
152 153
			// Make sure we have peers to select from, then sync
			if pm.peers.Len() < minDesiredPeerCount {
154 155
				break
			}
156
			go pm.synchronise(pm.peers.BestPeer())
157

158 159
		case <-forceSync:
			// Force a sync even if not enough peers are present
160 161
			go pm.synchronise(pm.peers.BestPeer())

162 163
		case <-blockProc:
			// Try to pull some blocks from the downloaded
164 165
			if atomic.CompareAndSwapInt32(&blockProcPend, 0, 1) {
				go func() {
166
					pm.processBlocks()
167 168 169
					atomic.StoreInt32(&blockProcPend, 0)
				}()
			}
170

171
		case <-pm.quitSync:
O
obscuren 已提交
172
			return
173 174 175 176
		}
	}
}

177 178 179
// 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.
180 181 182 183
func (pm *ProtocolManager) processBlocks() error {
	pm.wg.Add(1)
	defer pm.wg.Done()

184 185
	// Short circuit if no blocks are available for insertion
	blocks := pm.downloader.TakeBlocks()
186 187 188
	if len(blocks) == 0 {
		return nil
	}
189
	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())
190 191

	for len(blocks) != 0 && !pm.quit {
192
		// Retrieve the first batch of blocks to insert
193
		max := int(math.Min(float64(len(blocks)), float64(blockProcAmount)))
194 195 196 197 198 199
		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)
200
		if err != nil {
201
			glog.V(logger.Debug).Infoln("Downloaded block import failed:", err)
202
			pm.removePeer(blocks[index].OriginPeer)
203
			pm.downloader.Cancel()
204 205 206 207 208 209 210
			return err
		}
		blocks = blocks[max:]
	}
	return nil
}

211 212
// 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.
213
func (pm *ProtocolManager) synchronise(peer *peer) {
214 215 216 217
	// Short circuit if no peers are available
	if peer == nil {
		return
	}
218
	// Make sure the peer's TD is higher than our own. If not drop.
219
	if peer.Td().Cmp(pm.chainman.Td()) <= 0 {
220 221
		return
	}
222 223 224
	// 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
225 226
	head := peer.Head()
	if pm.chainman.HasBlock(head) {
227
		glog.V(logger.Debug).Infoln("Synchronisation canceled: head already known")
228 229
		return
	}
230
	// Get the hashes from the peer (synchronously)
231
	glog.V(logger.Detail).Infof("Attempting synchronisation: %v, 0x%x", peer.id, head)
232

233
	err := pm.downloader.Synchronise(peer.id, head)
234 235
	switch err {
	case nil:
236
		glog.V(logger.Detail).Infof("Synchronisation completed")
237 238

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

241
	case downloader.ErrTimeout, downloader.ErrBadPeer, downloader.ErrEmptyHashSet, downloader.ErrInvalidChain, downloader.ErrCrossCheckFailed:
242
		glog.V(logger.Debug).Infof("Removing peer %v: %v", peer.id, err)
243
		pm.removePeer(peer.id)
244

245 246
	case downloader.ErrPendingQueue:
		glog.V(logger.Debug).Infoln("Synchronisation aborted:", err)
247

248 249
	default:
		glog.V(logger.Warn).Infof("Synchronisation failed: %v", err)
250 251
	}
}