downloader.go 14.0 KB
Newer Older
1 2 3
package downloader

import (
4
	"errors"
5
	"fmt"
6 7 8 9 10 11 12 13 14 15
	"sync"
	"sync/atomic"
	"time"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
)

16
const (
17
	maxBlockFetch    = 128              // Amount of max blocks to be fetched per chunk
18 19
	peerCountTimeout = 12 * time.Second // Amount of time it takes for the peer handler to ignore minDesiredPeerCount
	hashTtl          = 20 * time.Second // The amount of time it takes for a hash request to time out
20
)
21

22
var (
O
obscuren 已提交
23 24
	minDesiredPeerCount = 5                // Amount of peers desired to start syncing
	blockTtl            = 20 * time.Second // The amount of time it takes for a block request to time out
25

26
	errLowTd               = errors.New("peer's TD is too low")
27
	ErrBusy                = errors.New("busy")
28
	errUnknownPeer         = errors.New("peer's unknown or unhealthy")
29
	errBadPeer             = errors.New("action from bad peer ignored")
30
	errNoPeers             = errors.New("no peers to keep download active")
31
	ErrPendingQueue        = errors.New("pending items in queue")
32
	ErrTimeout             = errors.New("timeout")
33 34 35 36
	errEmptyHashSet        = errors.New("empty hash set by peer")
	errPeersUnavailable    = errors.New("no peers available or all peers tried for block download process")
	errAlreadyInPool       = errors.New("hash already in pool")
	errBlockNumberOverflow = errors.New("received block which overflows")
37 38 39
	errCancelHashFetch     = errors.New("hash fetching cancelled (requested)")
	errCancelBlockFetch    = errors.New("block downloading cancelled (requested)")
	errNoSyncActive        = errors.New("no sync active")
40 41
)

42
type hashCheckFn func(common.Hash) bool
43
type getBlockFn func(common.Hash) *types.Block
44
type chainInsertFn func(types.Blocks) (int, error)
45 46
type hashIterFn func() (common.Hash, error)

O
obscuren 已提交
47 48 49 50 51
type blockPack struct {
	peerId string
	blocks []*types.Block
}

O
obscuren 已提交
52 53 54 55 56
type hashPack struct {
	peerId string
	hashes []common.Hash
}

57
type Downloader struct {
58 59 60
	mu    sync.RWMutex
	queue *queue
	peers *peerSet
61

62
	// Callbacks
63 64
	hasBlock hashCheckFn
	getBlock getBlockFn
65

66
	// Status
67
	synchronising int32
68
	notified      int32
69 70 71

	// Channels
	newPeerCh chan *peer
O
obscuren 已提交
72
	hashCh    chan hashPack
73
	blockCh   chan blockPack
74 75 76

	cancelCh   chan struct{} // Channel to cancel mid-flight syncs
	cancelLock sync.RWMutex  // Lock to protect the cancel channel in delivers
77 78
}

79
func New(hasBlock hashCheckFn, getBlock getBlockFn) *Downloader {
80
	downloader := &Downloader{
81
		queue:     newQueue(),
82
		peers:     newPeerSet(),
83 84 85
		hasBlock:  hasBlock,
		getBlock:  getBlock,
		newPeerCh: make(chan *peer, 1),
O
obscuren 已提交
86
		hashCh:    make(chan hashPack, 1),
87
		blockCh:   make(chan blockPack, 1),
88 89 90 91
	}
	return downloader
}

O
obscuren 已提交
92
func (d *Downloader) Stats() (current int, max int) {
93
	return d.queue.Size()
O
obscuren 已提交
94 95
}

96 97 98 99 100 101 102 103
// RegisterPeer injects a new download peer into the set of block source to be
// used for fetching hashes and blocks from.
func (d *Downloader) RegisterPeer(id string, head common.Hash, getHashes hashFetcherFn, getBlocks blockFetcherFn) error {
	glog.V(logger.Detail).Infoln("Registering peer", id)
	if err := d.peers.Register(newPeer(id, head, getHashes, getBlocks)); err != nil {
		glog.V(logger.Error).Infoln("Register failed:", err)
		return err
	}
104 105 106
	return nil
}

107 108 109 110 111 112 113 114 115
// UnregisterPeer remove a peer from the known list, preventing any action from
// the specified peer.
func (d *Downloader) UnregisterPeer(id string) error {
	glog.V(logger.Detail).Infoln("Unregistering peer", id)
	if err := d.peers.Unregister(id); err != nil {
		glog.V(logger.Error).Infoln("Unregister failed:", err)
		return err
	}
	return nil
116 117
}

118
// Synchronise will select the peer and use it for synchronising. If an empty string is given
119
// it will use the best peer possible and synchronize if it's TD is higher than our own. If any of the
120
// checks fail an error will be returned. This method is synchronous
121
func (d *Downloader) Synchronise(id string, hash common.Hash) error {
122
	// Make sure only one goroutine is ever allowed past this point at once
123 124
	if !atomic.CompareAndSwapInt32(&d.synchronising, 0, 1) {
		return ErrBusy
125
	}
126
	defer atomic.StoreInt32(&d.synchronising, 0)
127

128 129 130 131
	// Post a user notification of the sync (only once per session)
	if atomic.CompareAndSwapInt32(&d.notified, 0, 1) {
		glog.V(logger.Info).Infoln("Block synchronisation started")
	}
132 133
	// Create cancel channel for aborting mid-flight
	d.cancelLock.Lock()
134
	d.cancelCh = make(chan struct{})
135
	d.cancelLock.Unlock()
136

137
	// Abort if the queue still contains some leftover data
138
	if _, cached := d.queue.Size(); cached > 0 && d.queue.GetHeadBlock() != nil {
139
		return ErrPendingQueue
140
	}
141
	// Reset the queue and peer set to clean any internal leftover state
142
	d.queue.Reset()
143
	d.peers.Reset()
144

145
	// Retrieve the origin peer and initiate the downloading process
146
	p := d.peers.Peer(id)
147
	if p == nil {
148
		return errUnknownPeer
149
	}
150
	return d.syncWithPeer(p, hash)
151 152
}

153
// TakeBlocks takes blocks from the queue and yields them to the caller.
154
func (d *Downloader) TakeBlocks() types.Blocks {
155
	return d.queue.TakeBlocks()
156 157
}

158
func (d *Downloader) Has(hash common.Hash) bool {
159
	return d.queue.Has(hash)
160 161
}

162 163 164
// syncWithPeer starts a block synchronization based on the hash chain from the
// specified peer and head hash.
func (d *Downloader) syncWithPeer(p *peer, hash common.Hash) (err error) {
165 166 167
	defer func() {
		// reset on error
		if err != nil {
168
			d.queue.Reset()
169 170
		}
	}()
171

172
	glog.V(logger.Debug).Infoln("Synchronizing with the network using:", p.id)
173
	if err = d.fetchHashes(p, hash); err != nil {
174 175
		return err
	}
176
	if err = d.fetchBlocks(); err != nil {
177
		return err
178
	}
179
	glog.V(logger.Debug).Infoln("Synchronization completed")
180 181

	return nil
182 183
}

184 185 186 187
// Cancel cancels all of the operations and resets the queue. It returns true
// if the cancel operation was completed.
func (d *Downloader) Cancel() bool {
	// If we're not syncing just return.
188
	hs, bs := d.queue.Size()
189 190 191
	if atomic.LoadInt32(&d.synchronising) == 0 && hs == 0 && bs == 0 {
		return false
	}
192 193
	// Close the current cancel channel
	d.cancelLock.RLock()
194
	close(d.cancelCh)
195
	d.cancelLock.RUnlock()
196 197 198 199 200 201 202

	// reset the queue
	d.queue.Reset()

	return true
}

203
// XXX Make synchronous
204
func (d *Downloader) fetchHashes(p *peer, h common.Hash) error {
O
obscuren 已提交
205
	glog.V(logger.Debug).Infof("Downloading hashes (%x) from %s", h[:4], p.id)
206 207 208

	start := time.Now()

209 210 211
	// Add the hash to the queue first
	d.queue.Insert([]common.Hash{h})

212
	// Get the first batch of hashes
O
obscuren 已提交
213
	p.getHashes(h)
214

O
obscuren 已提交
215 216 217 218 219 220 221
	var (
		failureResponseTimer = time.NewTimer(hashTtl)
		attemptedPeers       = make(map[string]bool) // attempted peers will help with retries
		activePeer           = p                     // active peer will help determine the current active peer
		hash                 common.Hash             // common and last hash
	)
	attemptedPeers[p.id] = true
222

223 224 225
out:
	for {
		select {
226 227
		case <-d.cancelCh:
			return errCancelHashFetch
O
obscuren 已提交
228
		case hashPack := <-d.hashCh:
229
			// Make sure the active peer is giving us the hashes
O
obscuren 已提交
230 231 232 233 234
			if hashPack.peerId != activePeer.id {
				glog.V(logger.Debug).Infof("Received hashes from incorrect peer(%s)\n", hashPack.peerId)
				break
			}

235
			failureResponseTimer.Reset(hashTtl)
O
obscuren 已提交
236

237 238 239 240
			// Make sure the peer actually gave something valid
			if len(hashPack.hashes) == 0 {
				glog.V(logger.Debug).Infof("Peer (%s) responded with empty hash set\n", activePeer.id)
				d.queue.Reset()
241

242 243 244 245 246 247 248 249
				return errEmptyHashSet
			}
			// Determine if we're done fetching hashes (queue up all pending), and continue if not done
			done, index := false, 0
			for index, hash = range hashPack.hashes {
				if d.hasBlock(hash) || d.queue.GetBlock(hash) != nil {
					glog.V(logger.Debug).Infof("Found common hash %x\n", hash[:4])
					hashPack.hashes = hashPack.hashes[:index]
250 251 252 253
					done = true
					break
				}
			}
254
			d.queue.Insert(hashPack.hashes)
255

256
			if !done {
O
obscuren 已提交
257
				activePeer.getHashes(hash)
258
				continue
259
			}
260 261 262 263 264 265 266 267
			// We're done, allocate the download cache and proceed pulling the blocks
			offset := 0
			if block := d.getBlock(hash); block != nil {
				offset = int(block.NumberU64() + 1)
			}
			d.queue.Alloc(offset)
			break out

268
		case <-failureResponseTimer.C:
269 270
			glog.V(logger.Debug).Infof("Peer (%s) didn't respond in time for hash request\n", p.id)

O
obscuren 已提交
271 272 273 274
			var p *peer // p will be set if a peer can be found
			// Attempt to find a new peer by checking inclusion of peers best hash in our
			// already fetched hash list. This can't guarantee 100% correctness but does
			// a fair job. This is always either correct or false incorrect.
275
			for _, peer := range d.peers.AllPeers() {
276
				if d.queue.Has(peer.head) && !attemptedPeers[peer.id] {
O
obscuren 已提交
277 278 279 280 281 282 283
					p = peer
					break
				}
			}
			// if all peers have been tried, abort the process entirely or if the hash is
			// the zero hash.
			if p == nil || (hash == common.Hash{}) {
284
				d.queue.Reset()
285
				return ErrTimeout
O
obscuren 已提交
286 287 288 289 290 291
			}
			// set p to the active peer. this will invalidate any hashes that may be returned
			// by our previous (delayed) peer.
			activePeer = p
			p.getHashes(hash)
			glog.V(logger.Debug).Infof("Hash fetching switched to new peer(%s)\n", p.id)
292 293
		}
	}
294
	glog.V(logger.Debug).Infof("Downloaded hashes (%d) in %v\n", d.queue.Pending(), time.Since(start))
295 296 297 298

	return nil
}

299 300 301 302
// fetchBlocks iteratively downloads the entire schedules block-chain, taking
// any available peers, reserving a chunk of blocks for each, wait for delivery
// and periodically checking for timeouts.
func (d *Downloader) fetchBlocks() error {
303
	glog.V(logger.Debug).Infoln("Downloading", d.queue.Pending(), "block(s)")
304 305
	start := time.Now()

306
	// default ticker for re-fetching blocks every now and then
307 308 309 310
	ticker := time.NewTicker(20 * time.Millisecond)
out:
	for {
		select {
311 312
		case <-d.cancelCh:
			return errCancelBlockFetch
313
		case blockPack := <-d.blockCh:
314 315
			// If the peer was previously banned and failed to deliver it's pack
			// in a reasonable time frame, ignore it's message.
316 317 318 319
			if peer := d.peers.Peer(blockPack.peerId); peer != nil {
				// Deliver the received chunk of blocks, but drop the peer if invalid
				if err := d.queue.Deliver(blockPack.peerId, blockPack.blocks); err != nil {
					glog.V(logger.Debug).Infof("Failed delivery for peer %s: %v\n", blockPack.peerId, err)
320
					peer.Demote()
321 322 323
					break
				}
				if glog.V(logger.Debug) {
324
					glog.Infof("Added %d blocks from: %s\n", len(blockPack.blocks), blockPack.peerId)
325
				}
326 327 328
				// Promote the peer and update it's idle state
				peer.Promote()
				peer.SetIdle()
329
			}
330
		case <-ticker.C:
331 332 333 334 335 336 337 338 339 340 341 342
			// Check for bad peers. Bad peers may indicate a peer not responding
			// to a `getBlocks` message. A timeout of 5 seconds is set. Peers
			// that badly or poorly behave are removed from the peer set (not banned).
			// Bad peers are excluded from the available peer set and therefor won't be
			// reused. XXX We could re-introduce peers after X time.
			badPeers := d.queue.Expire(blockTtl)
			for _, pid := range badPeers {
				// XXX We could make use of a reputation system here ranking peers
				// in their performance
				// 1) Time for them to respond;
				// 2) Measure their speed;
				// 3) Amount and availability.
343 344 345
				if peer := d.peers.Peer(pid); peer != nil {
					peer.Demote()
				}
346 347
			}
			// After removing bad peers make sure we actually have sufficient peer left to keep downloading
348
			if d.peers.Len() == 0 {
349
				d.queue.Reset()
350 351
				return errNoPeers
			}
352 353
			// If there are unrequested hashes left start fetching
			// from the available peers.
354 355 356 357 358
			if d.queue.Pending() > 0 {
				// Throttle the download if block cache is full and waiting processing
				if d.queue.Throttle() {
					continue
				}
359
				// Send a download request to all idle peers, until throttled
360 361
				idlePeers := d.peers.IdlePeers()
				for _, peer := range idlePeers {
362 363 364 365
					// Short circuit if throttling activated since above
					if d.queue.Throttle() {
						break
					}
366 367
					// Get a possible chunk. If nil is returned no chunk
					// could be returned due to no hashes available.
368 369
					request := d.queue.Reserve(peer, maxBlockFetch)
					if request == nil {
370 371 372 373 374
						continue
					}
					// Fetch the chunk and check for error. If the peer was somehow
					// already fetching a chunk due to a bug, it will be returned to
					// the queue
375 376
					if err := peer.Fetch(request); err != nil {
						glog.V(logger.Error).Infof("Peer %s received double work\n", peer.id)
377
						d.queue.Cancel(request)
378 379
					}
				}
380
				// Make sure that we have peers available for fetching. If all peers have been tried
381
				// and all failed throw an error
382 383
				if d.queue.InFlight() == 0 {
					d.queue.Reset()
384

385
					return fmt.Errorf("%v peers available = %d. total peers = %d. hashes needed = %d", errPeersUnavailable, len(idlePeers), d.peers.Len(), d.queue.Pending())
386 387
				}

388 389
			} else if d.queue.InFlight() == 0 {
				// When there are no more queue and no more in flight, We can
390 391 392 393 394 395
				// safely assume we're done. Another part of the process will  check
				// for parent errors and will re-request anything that's missing
				break out
			}
		}
	}
396 397 398 399 400
	glog.V(logger.Detail).Infoln("Downloaded block(s) in", time.Since(start))

	return nil
}

401 402 403
// DeliverBlocks injects a new batch of blocks received from a remote node.
// This is usually invoked through the BlocksMsg by the protocol handler.
func (d *Downloader) DeliverBlocks(id string, blocks []*types.Block) error {
404 405 406 407
	// Make sure the downloader is active
	if atomic.LoadInt32(&d.synchronising) == 0 {
		return errNoSyncActive
	}
408 409 410 411
	// Deliver or abort if the sync is canceled while queuing
	d.cancelLock.RLock()
	cancel := d.cancelCh
	d.cancelLock.RUnlock()
412

413 414 415 416 417 418 419
	select {
	case d.blockCh <- blockPack{id, blocks}:
		return nil

	case <-cancel:
		return errNoSyncActive
	}
O
moved  
obscuren 已提交
420 421
}

422 423 424 425
// DeliverHashes injects a new batch of hashes received from a remote node into
// the download schedule. This is usually invoked through the BlockHashesMsg by
// the protocol handler.
func (d *Downloader) DeliverHashes(id string, hashes []common.Hash) error {
426 427 428 429
	// Make sure the downloader is active
	if atomic.LoadInt32(&d.synchronising) == 0 {
		return errNoSyncActive
	}
430 431 432 433
	// Deliver or abort if the sync is canceled while queuing
	d.cancelLock.RLock()
	cancel := d.cancelCh
	d.cancelLock.RUnlock()
434

435 436 437 438 439 440 441
	select {
	case d.hashCh <- hashPack{id, hashes}:
		return nil

	case <-cancel:
		return errNoSyncActive
	}
442
}