downloader_test.go 71.7 KB
Newer Older
F
Felix Lange 已提交
1
// Copyright 2015 The go-ethereum Authors
2
// This file is part of the go-ethereum library.
F
Felix Lange 已提交
3
//
4
// The go-ethereum library is free software: you can redistribute it and/or modify
F
Felix Lange 已提交
5 6 7 8
// 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.
//
9
// The go-ethereum library is distributed in the hope that it will be useful,
F
Felix Lange 已提交
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
F
Felix Lange 已提交
12 13 14
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
15
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
F
Felix Lange 已提交
16

17 18 19
package downloader

import (
20
	"errors"
21
	"fmt"
22
	"math/big"
23
	"sync"
24
	"sync/atomic"
25 26 27 28
	"testing"
	"time"

	"github.com/ethereum/go-ethereum/common"
29
	"github.com/ethereum/go-ethereum/consensus/ethash"
30
	"github.com/ethereum/go-ethereum/core"
31
	"github.com/ethereum/go-ethereum/core/types"
32
	"github.com/ethereum/go-ethereum/crypto"
33
	"github.com/ethereum/go-ethereum/ethdb"
O
obscuren 已提交
34
	"github.com/ethereum/go-ethereum/event"
35
	"github.com/ethereum/go-ethereum/params"
36
	"github.com/ethereum/go-ethereum/trie"
37 38
)

39
var (
40 41
	testKey, _  = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
	testAddress = crypto.PubkeyToAddress(testKey.PublicKey)
42
)
43

44
// Reduce some of the parameters to make the tester faster.
45
func init() {
46
	MaxForkAncestry = uint64(10000)
47 48
	blockCacheItems = 1024
	fsHeaderContCheck = 500 * time.Millisecond
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
}

// downloadTester is a test simulator for mocking out local block chain.
type downloadTester struct {
	downloader *Downloader

	genesis *types.Block   // Genesis blocks used by the tester and peers
	stateDb ethdb.Database // Database used by the tester for syncing from peers
	peerDb  ethdb.Database // Database of the peers containing all data

	ownHashes   []common.Hash                  // Hash chain belonging to the tester
	ownHeaders  map[common.Hash]*types.Header  // Headers belonging to the tester
	ownBlocks   map[common.Hash]*types.Block   // Blocks belonging to the tester
	ownReceipts map[common.Hash]types.Receipts // Receipts belonging to the tester
	ownChainTd  map[common.Hash]*big.Int       // Total difficulties of the blocks in the local chain

	peerHashes   map[string][]common.Hash                  // Hash chain belonging to different test peers
	peerHeaders  map[string]map[common.Hash]*types.Header  // Headers belonging to different test peers
	peerBlocks   map[string]map[common.Hash]*types.Block   // Blocks belonging to different test peers
	peerReceipts map[string]map[common.Hash]types.Receipts // Receipts belonging to different test peers
	peerChainTds map[string]map[common.Hash]*big.Int       // Total difficulties of the blocks in the peer chains

	peerMissingStates map[string]map[common.Hash]bool // State entries that fast sync should not return

	lock sync.RWMutex
}

// newTester creates a new downloader test mocker.
func newTester() *downloadTester {
	testdb, _ := ethdb.NewMemDatabase()
	genesis := core.GenesisBlockForTesting(testdb, testAddress, big.NewInt(1000000000))

	tester := &downloadTester{
		genesis:           genesis,
		peerDb:            testdb,
		ownHashes:         []common.Hash{genesis.Hash()},
		ownHeaders:        map[common.Hash]*types.Header{genesis.Hash(): genesis.Header()},
		ownBlocks:         map[common.Hash]*types.Block{genesis.Hash(): genesis},
		ownReceipts:       map[common.Hash]types.Receipts{genesis.Hash(): nil},
		ownChainTd:        map[common.Hash]*big.Int{genesis.Hash(): genesis.Difficulty()},
		peerHashes:        make(map[string][]common.Hash),
		peerHeaders:       make(map[string]map[common.Hash]*types.Header),
		peerBlocks:        make(map[string]map[common.Hash]*types.Block),
		peerReceipts:      make(map[string]map[common.Hash]types.Receipts),
		peerChainTds:      make(map[string]map[common.Hash]*big.Int),
		peerMissingStates: make(map[string]map[common.Hash]bool),
	}
	tester.stateDb, _ = ethdb.NewMemDatabase()
	tester.stateDb.Put(genesis.Root().Bytes(), []byte{0x00})

99
	tester.downloader = New(FullSync, tester.stateDb, new(event.TypeMux), tester, nil, tester.dropPeer)
100 101

	return tester
102 103
}

104 105 106 107
// makeChain creates a chain of n blocks starting at and including parent.
// the returned hash chain is ordered head->parent. In addition, every 3rd block
// contains a transaction and every 5th an uncle to allow testing correct block
// reassembly.
108
func (dl *downloadTester) makeChain(n int, seed byte, parent *types.Block, parentReceipts types.Receipts, heavy bool) ([]common.Hash, map[common.Hash]*types.Header, map[common.Hash]*types.Block, map[common.Hash]types.Receipts) {
109
	// Generate the block chain
110
	blocks, receipts := core.GenerateChain(params.TestChainConfig, parent, ethash.NewFaker(), dl.peerDb, n, func(i int, block *core.BlockGen) {
111 112
		block.SetCoinbase(common.Address{seed})

113 114 115 116
		// If a heavy chain is requested, delay blocks to raise difficulty
		if heavy {
			block.OffsetTime(-1)
		}
117
		// If the block number is multiple of 3, send a bonus transaction to the miner
118
		if parent == dl.genesis && i%3 == 0 {
J
Jeffrey Wilcke 已提交
119
			signer := types.MakeSigner(params.TestChainConfig, block.Number())
120
			tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, nil, nil), signer, testKey)
121 122 123 124 125 126
			if err != nil {
				panic(err)
			}
			block.AddTx(tx)
		}
		// If the block number is a multiple of 5, add a bonus uncle to the block
127 128 129 130 131
		if i > 0 && i%5 == 0 {
			block.AddUncle(&types.Header{
				ParentHash: block.PrevBlock(i - 1).Hash(),
				Number:     big.NewInt(block.Number().Int64() - 1),
			})
132
		}
133
	})
134
	// Convert the block-chain into a hash-chain and header/block maps
135 136
	hashes := make([]common.Hash, n+1)
	hashes[len(hashes)-1] = parent.Hash()
137 138 139 140

	headerm := make(map[common.Hash]*types.Header, n+1)
	headerm[parent.Hash()] = parent.Header()

141 142
	blockm := make(map[common.Hash]*types.Block, n+1)
	blockm[parent.Hash()] = parent
143

144 145 146
	receiptm := make(map[common.Hash]types.Receipts, n+1)
	receiptm[parent.Hash()] = parentReceipts

147 148
	for i, b := range blocks {
		hashes[len(hashes)-i-2] = b.Hash()
149
		headerm[b.Hash()] = b.Header()
150
		blockm[b.Hash()] = b
151
		receiptm[b.Hash()] = receipts[i]
152
	}
153
	return hashes, headerm, blockm, receiptm
154 155 156 157
}

// makeChainFork creates two chains of length n, such that h1[:f] and
// h2[:f] are different but have a common suffix of length n-f.
158
func (dl *downloadTester) makeChainFork(n, f int, parent *types.Block, parentReceipts types.Receipts, balanced bool) ([]common.Hash, []common.Hash, map[common.Hash]*types.Header, map[common.Hash]*types.Header, map[common.Hash]*types.Block, map[common.Hash]*types.Block, map[common.Hash]types.Receipts, map[common.Hash]types.Receipts) {
159
	// Create the common suffix
160
	hashes, headers, blocks, receipts := dl.makeChain(n-f, 0, parent, parentReceipts, false)
161

Y
Yusup 已提交
162
	// Create the forks, making the second heavier if non balanced forks were requested
163
	hashes1, headers1, blocks1, receipts1 := dl.makeChain(f, 1, blocks[hashes[0]], receipts[hashes[0]], false)
164 165
	hashes1 = append(hashes1, hashes[1:]...)

166 167 168 169
	heavy := false
	if !balanced {
		heavy = true
	}
170
	hashes2, headers2, blocks2, receipts2 := dl.makeChain(f, 2, blocks[hashes[0]], receipts[hashes[0]], heavy)
171 172 173 174 175 176 177 178 179 180
	hashes2 = append(hashes2, hashes[1:]...)

	for hash, header := range headers {
		headers1[hash] = header
		headers2[hash] = header
	}
	for hash, block := range blocks {
		blocks1[hash] = block
		blocks2[hash] = block
	}
181 182 183 184 185
	for hash, receipt := range receipts {
		receipts1[hash] = receipt
		receipts2[hash] = receipt
	}
	return hashes1, hashes2, headers1, headers2, blocks1, blocks2, receipts1, receipts2
186 187
}

188 189 190 191 192 193
// terminate aborts any operations on the embedded downloader and releases all
// held resources.
func (dl *downloadTester) terminate() {
	dl.downloader.Terminate()
}

194
// sync starts synchronizing with a remote peer, blocking until it completes.
195
func (dl *downloadTester) sync(id string, td *big.Int, mode SyncMode) error {
196
	dl.lock.RLock()
197 198 199 200
	hash := dl.peerHashes[id][0]
	// If no particular TD was requested, load from the peer's blockchain
	if td == nil {
		td = big.NewInt(1)
201 202
		if diff, ok := dl.peerChainTds[id][hash]; ok {
			td = diff
203 204
		}
	}
205
	dl.lock.RUnlock()
206 207 208 209 210 211 212 213 214 215 216

	// Synchronise with the chosen peer and ensure proper cleanup afterwards
	err := dl.downloader.synchronise(id, hash, td, mode)
	select {
	case <-dl.downloader.cancelCh:
		// Ok, downloader fully cancelled after sync cycle
	default:
		// Downloader is still accepting packets, can block a peer up
		panic("downloader active post sync cycle") // panic will be caught by tester
	}
	return err
O
obscuren 已提交
217 218
}

219
// HasHeader checks if a header is present in the testers canonical chain.
220
func (dl *downloadTester) HasHeader(hash common.Hash, number uint64) bool {
221
	return dl.GetHeaderByHash(hash) != nil
222 223
}

224 225 226
// HasBlock checks if a block is present in the testers canonical chain.
func (dl *downloadTester) HasBlock(hash common.Hash, number uint64) bool {
	return dl.GetBlockByHash(hash) != nil
227 228
}

229 230
// GetHeader retrieves a header from the testers canonical chain.
func (dl *downloadTester) GetHeaderByHash(hash common.Hash) *types.Header {
231 232 233
	dl.lock.RLock()
	defer dl.lock.RUnlock()

234
	return dl.ownHeaders[hash]
235 236
}

237 238
// GetBlock retrieves a block from the testers canonical chain.
func (dl *downloadTester) GetBlockByHash(hash common.Hash) *types.Block {
239 240 241
	dl.lock.RLock()
	defer dl.lock.RUnlock()

242 243 244
	return dl.ownBlocks[hash]
}

245 246
// CurrentHeader retrieves the current head header from the canonical chain.
func (dl *downloadTester) CurrentHeader() *types.Header {
247 248 249
	dl.lock.RLock()
	defer dl.lock.RUnlock()

250
	for i := len(dl.ownHashes) - 1; i >= 0; i-- {
251
		if header := dl.ownHeaders[dl.ownHashes[i]]; header != nil {
252 253 254
			return header
		}
	}
255
	return dl.genesis.Header()
256 257
}

258 259
// CurrentBlock retrieves the current head block from the canonical chain.
func (dl *downloadTester) CurrentBlock() *types.Block {
260 261 262
	dl.lock.RLock()
	defer dl.lock.RUnlock()

263
	for i := len(dl.ownHashes) - 1; i >= 0; i-- {
264
		if block := dl.ownBlocks[dl.ownHashes[i]]; block != nil {
265 266 267
			if _, err := dl.stateDb.Get(block.Root().Bytes()); err == nil {
				return block
			}
268 269
		}
	}
270
	return dl.genesis
271 272
}

273 274
// CurrentFastBlock retrieves the current head fast-sync block from the canonical chain.
func (dl *downloadTester) CurrentFastBlock() *types.Block {
275 276 277 278
	dl.lock.RLock()
	defer dl.lock.RUnlock()

	for i := len(dl.ownHashes) - 1; i >= 0; i-- {
279
		if block := dl.ownBlocks[dl.ownHashes[i]]; block != nil {
280
			return block
281 282
		}
	}
283
	return dl.genesis
284 285
}

286
// FastSyncCommitHead manually sets the head block to a given hash.
287
func (dl *downloadTester) FastSyncCommitHead(hash common.Hash) error {
288
	// For now only check that the state trie is correct
289
	if block := dl.GetBlockByHash(hash); block != nil {
290
		_, err := trie.NewSecure(block.Root(), trie.NewDatabase(dl.stateDb), 0)
291 292 293
		return err
	}
	return fmt.Errorf("non existent block: %x", hash[:4])
294 295
}

296 297
// GetTd retrieves the block's total difficulty from the canonical chain.
func (dl *downloadTester) GetTd(hash common.Hash, number uint64) *big.Int {
298 299 300
	dl.lock.RLock()
	defer dl.lock.RUnlock()

301 302 303
	return dl.ownChainTd[hash]
}

304 305
// InsertHeaderChain injects a new batch of headers into the simulated chain.
func (dl *downloadTester) InsertHeaderChain(headers []*types.Header, checkFreq int) (int, error) {
306 307 308
	dl.lock.Lock()
	defer dl.lock.Unlock()

L
Leif Jurvetson 已提交
309
	// Do a quick check, as the blockchain.InsertHeaderChain doesn't insert anything in case of errors
310 311 312 313 314 315 316 317 318
	if _, ok := dl.ownHeaders[headers[0].ParentHash]; !ok {
		return 0, errors.New("unknown parent")
	}
	for i := 1; i < len(headers); i++ {
		if headers[i].ParentHash != headers[i-1].Hash() {
			return i, errors.New("unknown parent")
		}
	}
	// Do a full insert if pre-checks passed
319
	for i, header := range headers {
320 321 322
		if _, ok := dl.ownHeaders[header.Hash()]; ok {
			continue
		}
323 324 325 326 327
		if _, ok := dl.ownHeaders[header.ParentHash]; !ok {
			return i, errors.New("unknown parent")
		}
		dl.ownHashes = append(dl.ownHashes, header.Hash())
		dl.ownHeaders[header.Hash()] = header
328
		dl.ownChainTd[header.Hash()] = new(big.Int).Add(dl.ownChainTd[header.ParentHash], header.Difficulty)
329 330 331 332
	}
	return len(headers), nil
}

333 334
// InsertChain injects a new batch of blocks into the simulated chain.
func (dl *downloadTester) InsertChain(blocks types.Blocks) (int, error) {
335 336 337
	dl.lock.Lock()
	defer dl.lock.Unlock()

338
	for i, block := range blocks {
339
		if parent, ok := dl.ownBlocks[block.ParentHash()]; !ok {
340
			return i, errors.New("unknown parent")
341 342
		} else if _, err := dl.stateDb.Get(parent.Root().Bytes()); err != nil {
			return i, fmt.Errorf("unknown parent state %x: %v", parent.Root(), err)
343
		}
344 345 346 347
		if _, ok := dl.ownHeaders[block.Hash()]; !ok {
			dl.ownHashes = append(dl.ownHashes, block.Hash())
			dl.ownHeaders[block.Hash()] = block.Header()
		}
348
		dl.ownBlocks[block.Hash()] = block
349 350
		dl.stateDb.Put(block.Root().Bytes(), []byte{0x00})
		dl.ownChainTd[block.Hash()] = new(big.Int).Add(dl.ownChainTd[block.ParentHash()], block.Difficulty())
351 352 353 354
	}
	return len(blocks), nil
}

355 356
// InsertReceiptChain injects a new batch of receipts into the simulated chain.
func (dl *downloadTester) InsertReceiptChain(blocks types.Blocks, receipts []types.Receipts) (int, error) {
357 358 359 360
	dl.lock.Lock()
	defer dl.lock.Unlock()

	for i := 0; i < len(blocks) && i < len(receipts); i++ {
361 362 363
		if _, ok := dl.ownHeaders[blocks[i].Hash()]; !ok {
			return i, errors.New("unknown owner")
		}
364 365 366 367
		if _, ok := dl.ownBlocks[blocks[i].ParentHash()]; !ok {
			return i, errors.New("unknown parent")
		}
		dl.ownBlocks[blocks[i].Hash()] = blocks[i]
368
		dl.ownReceipts[blocks[i].Hash()] = receipts[i]
369 370 371 372
	}
	return len(blocks), nil
}

373 374
// Rollback removes some recently added elements from the chain.
func (dl *downloadTester) Rollback(hashes []common.Hash) {
375 376 377 378 379 380 381 382 383 384 385 386 387 388
	dl.lock.Lock()
	defer dl.lock.Unlock()

	for i := len(hashes) - 1; i >= 0; i-- {
		if dl.ownHashes[len(dl.ownHashes)-1] == hashes[i] {
			dl.ownHashes = dl.ownHashes[:len(dl.ownHashes)-1]
		}
		delete(dl.ownChainTd, hashes[i])
		delete(dl.ownHeaders, hashes[i])
		delete(dl.ownReceipts, hashes[i])
		delete(dl.ownBlocks, hashes[i])
	}
}

389
// newPeer registers a new block download source into the downloader.
390 391
func (dl *downloadTester) newPeer(id string, version int, hashes []common.Hash, headers map[common.Hash]*types.Header, blocks map[common.Hash]*types.Block, receipts map[common.Hash]types.Receipts) error {
	return dl.newSlowPeer(id, version, hashes, headers, blocks, receipts, 0)
392 393 394 395 396
}

// newSlowPeer registers a new block download source into the downloader, with a
// specific delay time on processing the network packets sent to it, simulating
// potentially slow network IO.
397
func (dl *downloadTester) newSlowPeer(id string, version int, hashes []common.Hash, headers map[common.Hash]*types.Header, blocks map[common.Hash]*types.Block, receipts map[common.Hash]types.Receipts, delay time.Duration) error {
398 399 400
	dl.lock.Lock()
	defer dl.lock.Unlock()

401
	var err = dl.downloader.RegisterPeer(id, version, &downloadTesterPeer{dl: dl, id: id, delay: delay})
402
	if err == nil {
403
		// Assign the owned hashes, headers and blocks to the peer (deep copy)
404 405
		dl.peerHashes[id] = make([]common.Hash, len(hashes))
		copy(dl.peerHashes[id], hashes)
406

407
		dl.peerHeaders[id] = make(map[common.Hash]*types.Header)
408
		dl.peerBlocks[id] = make(map[common.Hash]*types.Block)
409
		dl.peerReceipts[id] = make(map[common.Hash]types.Receipts)
410
		dl.peerChainTds[id] = make(map[common.Hash]*big.Int)
411
		dl.peerMissingStates[id] = make(map[common.Hash]bool)
412

413 414 415 416 417 418 419 420 421 422 423 424 425
		genesis := hashes[len(hashes)-1]
		if header := headers[genesis]; header != nil {
			dl.peerHeaders[id][genesis] = header
			dl.peerChainTds[id][genesis] = header.Difficulty
		}
		if block := blocks[genesis]; block != nil {
			dl.peerBlocks[id][genesis] = block
			dl.peerChainTds[id][genesis] = block.Difficulty()
		}

		for i := len(hashes) - 2; i >= 0; i-- {
			hash := hashes[i]

426 427 428 429 430 431
			if header, ok := headers[hash]; ok {
				dl.peerHeaders[id][hash] = header
				if _, ok := dl.peerHeaders[id][header.ParentHash]; ok {
					dl.peerChainTds[id][hash] = new(big.Int).Add(header.Difficulty, dl.peerChainTds[id][header.ParentHash])
				}
			}
432 433
			if block, ok := blocks[hash]; ok {
				dl.peerBlocks[id][hash] = block
434 435
				if _, ok := dl.peerBlocks[id][block.ParentHash()]; ok {
					dl.peerChainTds[id][hash] = new(big.Int).Add(block.Difficulty(), dl.peerChainTds[id][block.ParentHash()])
436 437
				}
			}
438 439 440
			if receipt, ok := receipts[hash]; ok {
				dl.peerReceipts[id][hash] = receipt
			}
441
		}
442 443
	}
	return err
444 445
}

446 447
// dropPeer simulates a hard peer removal from the connection pool.
func (dl *downloadTester) dropPeer(id string) {
448 449 450
	dl.lock.Lock()
	defer dl.lock.Unlock()

451
	delete(dl.peerHashes, id)
452
	delete(dl.peerHeaders, id)
453
	delete(dl.peerBlocks, id)
454
	delete(dl.peerChainTds, id)
455 456 457 458

	dl.downloader.UnregisterPeer(id)
}

459 460 461 462
type downloadTesterPeer struct {
	dl    *downloadTester
	id    string
	delay time.Duration
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
	lock  sync.RWMutex
}

// setDelay is a thread safe setter for the network delay value.
func (dlp *downloadTesterPeer) setDelay(delay time.Duration) {
	dlp.lock.Lock()
	defer dlp.lock.Unlock()

	dlp.delay = delay
}

// waitDelay is a thread safe way to sleep for the configured time.
func (dlp *downloadTesterPeer) waitDelay() {
	dlp.lock.RLock()
	delay := dlp.delay
	dlp.lock.RUnlock()

	time.Sleep(delay)
481 482 483
}

// Head constructs a function to retrieve a peer's current head hash
484
// and total difficulty.
485 486 487
func (dlp *downloadTesterPeer) Head() (common.Hash, *big.Int) {
	dlp.dl.lock.RLock()
	defer dlp.dl.lock.RUnlock()
488

489
	return dlp.dl.peerHashes[dlp.id][0], nil
490 491
}

492
// RequestHeadersByHash constructs a GetBlockHeaders function based on a hashed
493 494
// origin; associated with a particular peer in the download tester. The returned
// function can be used to retrieve batches of headers from the particular peer.
495 496 497 498 499 500 501 502
func (dlp *downloadTesterPeer) RequestHeadersByHash(origin common.Hash, amount int, skip int, reverse bool) error {
	// Find the canonical number of the hash
	dlp.dl.lock.RLock()
	number := uint64(0)
	for num, hash := range dlp.dl.peerHashes[dlp.id] {
		if hash == origin {
			number = uint64(len(dlp.dl.peerHashes[dlp.id]) - num - 1)
			break
503 504
		}
	}
505 506 507 508
	dlp.dl.lock.RUnlock()

	// Use the absolute header fetcher to satisfy the query
	return dlp.RequestHeadersByNumber(number, amount, skip, reverse)
509 510
}

511
// RequestHeadersByNumber constructs a GetBlockHeaders function based on a numbered
512 513
// origin; associated with a particular peer in the download tester. The returned
// function can be used to retrieve batches of headers from the particular peer.
514
func (dlp *downloadTesterPeer) RequestHeadersByNumber(origin uint64, amount int, skip int, reverse bool) error {
515
	dlp.waitDelay()
516 517 518 519 520 521 522 523 524 525 526

	dlp.dl.lock.RLock()
	defer dlp.dl.lock.RUnlock()

	// Gather the next batch of headers
	hashes := dlp.dl.peerHashes[dlp.id]
	headers := dlp.dl.peerHeaders[dlp.id]
	result := make([]*types.Header, 0, amount)
	for i := 0; i < amount && len(hashes)-int(origin)-1-i*(skip+1) >= 0; i++ {
		if header, ok := headers[hashes[len(hashes)-int(origin)-1-i*(skip+1)]]; ok {
			result = append(result, header)
527 528
		}
	}
529 530 531 532 533 534
	// Delay delivery a bit to allow attacks to unfold
	go func() {
		time.Sleep(time.Millisecond)
		dlp.dl.downloader.DeliverHeaders(dlp.id, result)
	}()
	return nil
535 536
}

537
// RequestBodies constructs a getBlockBodies method associated with a particular
538 539
// peer in the download tester. The returned function can be used to retrieve
// batches of block bodies from the particularly requested peer.
540
func (dlp *downloadTesterPeer) RequestBodies(hashes []common.Hash) error {
541
	dlp.waitDelay()
542

543 544
	dlp.dl.lock.RLock()
	defer dlp.dl.lock.RUnlock()
545

546
	blocks := dlp.dl.peerBlocks[dlp.id]
547

548 549
	transactions := make([][]*types.Transaction, 0, len(hashes))
	uncles := make([][]*types.Header, 0, len(hashes))
550

551 552 553 554
	for _, hash := range hashes {
		if block, ok := blocks[hash]; ok {
			transactions = append(transactions, block.Transactions())
			uncles = append(uncles, block.Uncles())
555
		}
556
	}
557 558 559
	go dlp.dl.downloader.DeliverBodies(dlp.id, transactions, uncles)

	return nil
560 561
}

562
// RequestReceipts constructs a getReceipts method associated with a particular
563 564
// peer in the download tester. The returned function can be used to retrieve
// batches of block receipts from the particularly requested peer.
565
func (dlp *downloadTesterPeer) RequestReceipts(hashes []common.Hash) error {
566
	dlp.waitDelay()
567

568 569
	dlp.dl.lock.RLock()
	defer dlp.dl.lock.RUnlock()
570

571
	receipts := dlp.dl.peerReceipts[dlp.id]
572

573 574 575 576
	results := make([][]*types.Receipt, 0, len(hashes))
	for _, hash := range hashes {
		if receipt, ok := receipts[hash]; ok {
			results = append(results, receipt)
577 578
		}
	}
579 580 581
	go dlp.dl.downloader.DeliverReceipts(dlp.id, results)

	return nil
582 583
}

584
// RequestNodeData constructs a getNodeData method associated with a particular
585 586
// peer in the download tester. The returned function can be used to retrieve
// batches of node state data from the particularly requested peer.
587
func (dlp *downloadTesterPeer) RequestNodeData(hashes []common.Hash) error {
588
	dlp.waitDelay()
589 590 591 592 593 594 595 596 597

	dlp.dl.lock.RLock()
	defer dlp.dl.lock.RUnlock()

	results := make([][]byte, 0, len(hashes))
	for _, hash := range hashes {
		if data, err := dlp.dl.peerDb.Get(hash.Bytes()); err == nil {
			if !dlp.dl.peerMissingStates[dlp.id][hash] {
				results = append(results, data)
598 599 600
			}
		}
	}
601 602 603
	go dlp.dl.downloader.DeliverNodeData(dlp.id, results)

	return nil
604 605
}

606 607 608
// assertOwnChain checks if the local chain contains the correct number of items
// of the various chain components.
func assertOwnChain(t *testing.T, tester *downloadTester, length int) {
609 610 611 612 613 614 615
	assertOwnForkedChain(t, tester, 1, []int{length})
}

// assertOwnForkedChain checks if the local forked chain contains the correct
// number of items of the various chain components.
func assertOwnForkedChain(t *testing.T, tester *downloadTester, common int, lengths []int) {
	// Initialize the counters for the first fork
616
	headers, blocks, receipts := lengths[0], lengths[0], lengths[0]-fsMinFullBlocks
617

618 619
	if receipts < 0 {
		receipts = 1
620 621 622 623 624
	}
	// Update the counters for each subsequent fork
	for _, length := range lengths[1:] {
		headers += length - common
		blocks += length - common
625
		receipts += length - common - fsMinFullBlocks
626
	}
627 628
	switch tester.downloader.mode {
	case FullSync:
629
		receipts = 1
630
	case LightSync:
631
		blocks, receipts = 1, 1
632 633 634 635 636 637 638
	}
	if hs := len(tester.ownHeaders); hs != headers {
		t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, headers)
	}
	if bs := len(tester.ownBlocks); bs != blocks {
		t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, blocks)
	}
639 640
	if rs := len(tester.ownReceipts); rs != receipts {
		t.Fatalf("synchronised receipts mismatch: have %v, want %v", rs, receipts)
641
	}
642
	// Verify the state trie too for fast syncs
643 644
	/*if tester.downloader.mode == FastSync {
		pivot := uint64(0)
645
		var index int
646 647 648 649 650 651
		if pivot := int(tester.downloader.queue.fastSyncPivot); pivot < common {
			index = pivot
		} else {
			index = len(tester.ownHashes) - lengths[len(lengths)-1] + int(tester.downloader.queue.fastSyncPivot)
		}
		if index > 0 {
652
			if statedb, err := state.New(tester.ownHeaders[tester.ownHashes[index]].Root, state.NewDatabase(trie.NewDatabase(tester.stateDb))); statedb == nil || err != nil {
653
				t.Fatalf("state reconstruction failed: %v", err)
654 655
			}
		}
656
	}*/
657 658
}

659 660 661
// Tests that simple synchronization against a canonical chain works correctly.
// In this test common ancestor lookup should be short circuited and not require
// binary searching.
662 663 664 665 666 667 668 669
func TestCanonicalSynchronisation62(t *testing.T)      { testCanonicalSynchronisation(t, 62, FullSync) }
func TestCanonicalSynchronisation63Full(t *testing.T)  { testCanonicalSynchronisation(t, 63, FullSync) }
func TestCanonicalSynchronisation63Fast(t *testing.T)  { testCanonicalSynchronisation(t, 63, FastSync) }
func TestCanonicalSynchronisation64Full(t *testing.T)  { testCanonicalSynchronisation(t, 64, FullSync) }
func TestCanonicalSynchronisation64Fast(t *testing.T)  { testCanonicalSynchronisation(t, 64, FastSync) }
func TestCanonicalSynchronisation64Light(t *testing.T) { testCanonicalSynchronisation(t, 64, LightSync) }

func testCanonicalSynchronisation(t *testing.T, protocol int, mode SyncMode) {
670 671
	t.Parallel()

672
	tester := newTester()
673 674
	defer tester.terminate()

675
	// Create a small enough block chain to download
676
	targetBlocks := blockCacheItems - 15
677 678
	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)

679
	tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
680

681
	// Synchronise with the peer and make sure all relevant data was retrieved
682
	if err := tester.sync("peer", nil, mode); err != nil {
683
		t.Fatalf("failed to synchronise blocks: %v", err)
684
	}
685
	assertOwnChain(t, tester, targetBlocks+1)
686 687
}

688 689
// Tests that if a large batch of blocks are being downloaded, it is throttled
// until the cached blocks are retrieved.
690 691 692 693 694 695 696
func TestThrottling62(t *testing.T)     { testThrottling(t, 62, FullSync) }
func TestThrottling63Full(t *testing.T) { testThrottling(t, 63, FullSync) }
func TestThrottling63Fast(t *testing.T) { testThrottling(t, 63, FastSync) }
func TestThrottling64Full(t *testing.T) { testThrottling(t, 64, FullSync) }
func TestThrottling64Fast(t *testing.T) { testThrottling(t, 64, FastSync) }

func testThrottling(t *testing.T, protocol int, mode SyncMode) {
697
	t.Parallel()
698
	tester := newTester()
699 700
	defer tester.terminate()

701
	// Create a long block chain to download and the tester
702
	targetBlocks := 8 * blockCacheItems
703 704
	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)

705
	tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
706

707
	// Wrap the importer to allow stepping
708
	blocked, proceed := uint32(0), make(chan struct{})
709 710
	tester.downloader.chainInsertHook = func(results []*fetchResult) {
		atomic.StoreUint32(&blocked, uint32(len(results)))
711
		<-proceed
712
	}
713 714 715
	// Start a synchronisation concurrently
	errc := make(chan error)
	go func() {
716
		errc <- tester.sync("peer", nil, mode)
717 718
	}()
	// Iteratively take some blocks, always checking the retrieval count
719 720 721 722 723 724 725 726
	for {
		// Check the retrieval count synchronously (! reason for this ugly block)
		tester.lock.RLock()
		retrieved := len(tester.ownBlocks)
		tester.lock.RUnlock()
		if retrieved >= targetBlocks+1 {
			break
		}
727
		// Wait a bit for sync to throttle itself
728
		var cached, frozen int
729
		for start := time.Now(); time.Since(start) < 3*time.Second; {
730
			time.Sleep(25 * time.Millisecond)
731

732 733
			tester.lock.Lock()
			tester.downloader.queue.lock.Lock()
734 735 736
			cached = len(tester.downloader.queue.blockDonePool)
			if mode == FastSync {
				if receipts := len(tester.downloader.queue.receiptDonePool); receipts < cached {
737 738 739
					//if tester.downloader.queue.resultCache[receipts].Header.Number.Uint64() < tester.downloader.queue.fastSyncPivot {
					cached = receipts
					//}
740 741
				}
			}
742 743
			frozen = int(atomic.LoadUint32(&blocked))
			retrieved = len(tester.ownBlocks)
744 745
			tester.downloader.queue.lock.Unlock()
			tester.lock.Unlock()
746

747
			if cached == blockCacheItems || retrieved+cached+frozen == targetBlocks+1 {
748 749 750
				break
			}
		}
751 752
		// Make sure we filled up the cache, then exhaust it
		time.Sleep(25 * time.Millisecond) // give it a chance to screw up
753 754 755 756

		tester.lock.RLock()
		retrieved = len(tester.ownBlocks)
		tester.lock.RUnlock()
757 758
		if cached != blockCacheItems && retrieved+cached+frozen != targetBlocks+1 {
			t.Fatalf("block count mismatch: have %v, want %v (owned %v, blocked %v, target %v)", cached, blockCacheItems, retrieved, frozen, targetBlocks+1)
759
		}
760 761 762 763
		// Permit the blocked blocks to import
		if atomic.LoadUint32(&blocked) > 0 {
			atomic.StoreUint32(&blocked, uint32(0))
			proceed <- struct{}{}
764
		}
765 766
	}
	// Check that we haven't pulled more blocks than available
767
	assertOwnChain(t, tester, targetBlocks+1)
768 769
	if err := <-errc; err != nil {
		t.Fatalf("block synchronization failed: %v", err)
770 771
	}
}
772

773 774 775
// Tests that simple synchronization against a forked chain works correctly. In
// this test common ancestor lookup should *not* be short circuited, and a full
// binary search should be executed.
776 777 778 779 780 781 782 783
func TestForkedSync62(t *testing.T)      { testForkedSync(t, 62, FullSync) }
func TestForkedSync63Full(t *testing.T)  { testForkedSync(t, 63, FullSync) }
func TestForkedSync63Fast(t *testing.T)  { testForkedSync(t, 63, FastSync) }
func TestForkedSync64Full(t *testing.T)  { testForkedSync(t, 64, FullSync) }
func TestForkedSync64Fast(t *testing.T)  { testForkedSync(t, 64, FastSync) }
func TestForkedSync64Light(t *testing.T) { testForkedSync(t, 64, LightSync) }

func testForkedSync(t *testing.T, protocol int, mode SyncMode) {
784 785
	t.Parallel()

786
	tester := newTester()
787 788
	defer tester.terminate()

789 790 791 792
	// Create a long enough forked chain
	common, fork := MaxHashFetch, 2*MaxHashFetch
	hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, true)

793 794
	tester.newPeer("fork A", protocol, hashesA, headersA, blocksA, receiptsA)
	tester.newPeer("fork B", protocol, hashesB, headersB, blocksB, receiptsB)
795 796

	// Synchronise with the peer and make sure all blocks were retrieved
797
	if err := tester.sync("fork A", nil, mode); err != nil {
798 799
		t.Fatalf("failed to synchronise blocks: %v", err)
	}
800 801
	assertOwnChain(t, tester, common+fork+1)

802
	// Synchronise with the second peer and make sure that fork is pulled too
803
	if err := tester.sync("fork B", nil, mode); err != nil {
804 805
		t.Fatalf("failed to synchronise blocks: %v", err)
	}
806
	assertOwnForkedChain(t, tester, common+1, []int{common + fork + 1, common + fork + 1})
807 808
}

809 810 811 812 813 814 815 816 817 818 819 820 821
// Tests that synchronising against a much shorter but much heavyer fork works
// corrently and is not dropped.
func TestHeavyForkedSync62(t *testing.T)      { testHeavyForkedSync(t, 62, FullSync) }
func TestHeavyForkedSync63Full(t *testing.T)  { testHeavyForkedSync(t, 63, FullSync) }
func TestHeavyForkedSync63Fast(t *testing.T)  { testHeavyForkedSync(t, 63, FastSync) }
func TestHeavyForkedSync64Full(t *testing.T)  { testHeavyForkedSync(t, 64, FullSync) }
func TestHeavyForkedSync64Fast(t *testing.T)  { testHeavyForkedSync(t, 64, FastSync) }
func TestHeavyForkedSync64Light(t *testing.T) { testHeavyForkedSync(t, 64, LightSync) }

func testHeavyForkedSync(t *testing.T, protocol int, mode SyncMode) {
	t.Parallel()

	tester := newTester()
822 823
	defer tester.terminate()

824 825 826 827
	// Create a long enough forked chain
	common, fork := MaxHashFetch, 4*MaxHashFetch
	hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, false)

828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
	tester.newPeer("light", protocol, hashesA, headersA, blocksA, receiptsA)
	tester.newPeer("heavy", protocol, hashesB[fork/2:], headersB, blocksB, receiptsB)

	// Synchronise with the peer and make sure all blocks were retrieved
	if err := tester.sync("light", nil, mode); err != nil {
		t.Fatalf("failed to synchronise blocks: %v", err)
	}
	assertOwnChain(t, tester, common+fork+1)

	// Synchronise with the second peer and make sure that fork is pulled too
	if err := tester.sync("heavy", nil, mode); err != nil {
		t.Fatalf("failed to synchronise blocks: %v", err)
	}
	assertOwnForkedChain(t, tester, common+1, []int{common + fork + 1, common + fork/2 + 1})
}

// Tests that chain forks are contained within a certain interval of the current
// chain head, ensuring that malicious peers cannot waste resources by feeding
// long dead chains.
func TestBoundedForkedSync62(t *testing.T)      { testBoundedForkedSync(t, 62, FullSync) }
func TestBoundedForkedSync63Full(t *testing.T)  { testBoundedForkedSync(t, 63, FullSync) }
func TestBoundedForkedSync63Fast(t *testing.T)  { testBoundedForkedSync(t, 63, FastSync) }
func TestBoundedForkedSync64Full(t *testing.T)  { testBoundedForkedSync(t, 64, FullSync) }
func TestBoundedForkedSync64Fast(t *testing.T)  { testBoundedForkedSync(t, 64, FastSync) }
func TestBoundedForkedSync64Light(t *testing.T) { testBoundedForkedSync(t, 64, LightSync) }

func testBoundedForkedSync(t *testing.T, protocol int, mode SyncMode) {
	t.Parallel()

	tester := newTester()
858 859
	defer tester.terminate()

860 861 862 863
	// Create a long enough forked chain
	common, fork := 13, int(MaxForkAncestry+17)
	hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, true)

864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
	tester.newPeer("original", protocol, hashesA, headersA, blocksA, receiptsA)
	tester.newPeer("rewriter", protocol, hashesB, headersB, blocksB, receiptsB)

	// Synchronise with the peer and make sure all blocks were retrieved
	if err := tester.sync("original", nil, mode); err != nil {
		t.Fatalf("failed to synchronise blocks: %v", err)
	}
	assertOwnChain(t, tester, common+fork+1)

	// Synchronise with the second peer and ensure that the fork is rejected to being too old
	if err := tester.sync("rewriter", nil, mode); err != errInvalidAncestor {
		t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor)
	}
}

// Tests that chain forks are contained within a certain interval of the current
// chain head for short but heavy forks too. These are a bit special because they
// take different ancestor lookup paths.
func TestBoundedHeavyForkedSync62(t *testing.T)      { testBoundedHeavyForkedSync(t, 62, FullSync) }
func TestBoundedHeavyForkedSync63Full(t *testing.T)  { testBoundedHeavyForkedSync(t, 63, FullSync) }
func TestBoundedHeavyForkedSync63Fast(t *testing.T)  { testBoundedHeavyForkedSync(t, 63, FastSync) }
func TestBoundedHeavyForkedSync64Full(t *testing.T)  { testBoundedHeavyForkedSync(t, 64, FullSync) }
func TestBoundedHeavyForkedSync64Fast(t *testing.T)  { testBoundedHeavyForkedSync(t, 64, FastSync) }
func TestBoundedHeavyForkedSync64Light(t *testing.T) { testBoundedHeavyForkedSync(t, 64, LightSync) }

func testBoundedHeavyForkedSync(t *testing.T, protocol int, mode SyncMode) {
	t.Parallel()

	tester := newTester()
893 894
	defer tester.terminate()

895 896 897 898
	// Create a long enough forked chain
	common, fork := 13, int(MaxForkAncestry+17)
	hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, false)

899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
	tester.newPeer("original", protocol, hashesA, headersA, blocksA, receiptsA)
	tester.newPeer("heavy-rewriter", protocol, hashesB[MaxForkAncestry-17:], headersB, blocksB, receiptsB) // Root the fork below the ancestor limit

	// Synchronise with the peer and make sure all blocks were retrieved
	if err := tester.sync("original", nil, mode); err != nil {
		t.Fatalf("failed to synchronise blocks: %v", err)
	}
	assertOwnChain(t, tester, common+fork+1)

	// Synchronise with the second peer and ensure that the fork is rejected to being too old
	if err := tester.sync("heavy-rewriter", nil, mode); err != errInvalidAncestor {
		t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor)
	}
}

914 915
// Tests that an inactive downloader will not accept incoming block headers and
// bodies.
916
func TestInactiveDownloader62(t *testing.T) {
917
	t.Parallel()
918

919
	tester := newTester()
920
	defer tester.terminate()
921 922 923

	// Check that neither block headers nor bodies are accepted
	if err := tester.downloader.DeliverHeaders("bad peer", []*types.Header{}); err != errNoSyncActive {
924 925
		t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
	}
926
	if err := tester.downloader.DeliverBodies("bad peer", [][]*types.Transaction{}, [][]*types.Header{}); err != errNoSyncActive {
927 928 929 930
		t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
	}
}

931 932 933
// Tests that an inactive downloader will not accept incoming block headers,
// bodies and receipts.
func TestInactiveDownloader63(t *testing.T) {
934
	t.Parallel()
935

936
	tester := newTester()
937
	defer tester.terminate()
938 939 940 941 942 943 944 945 946 947 948 949

	// Check that neither block headers nor bodies are accepted
	if err := tester.downloader.DeliverHeaders("bad peer", []*types.Header{}); err != errNoSyncActive {
		t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
	}
	if err := tester.downloader.DeliverBodies("bad peer", [][]*types.Transaction{}, [][]*types.Header{}); err != errNoSyncActive {
		t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
	}
	if err := tester.downloader.DeliverReceipts("bad peer", [][]*types.Receipt{}); err != errNoSyncActive {
		t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
	}
}
950

951 952 953 954 955 956 957 958 959
// Tests that a canceled download wipes all previously accumulated state.
func TestCancel62(t *testing.T)      { testCancel(t, 62, FullSync) }
func TestCancel63Full(t *testing.T)  { testCancel(t, 63, FullSync) }
func TestCancel63Fast(t *testing.T)  { testCancel(t, 63, FastSync) }
func TestCancel64Full(t *testing.T)  { testCancel(t, 64, FullSync) }
func TestCancel64Fast(t *testing.T)  { testCancel(t, 64, FastSync) }
func TestCancel64Light(t *testing.T) { testCancel(t, 64, LightSync) }

func testCancel(t *testing.T, protocol int, mode SyncMode) {
960 961
	t.Parallel()

962 963 964
	tester := newTester()
	defer tester.terminate()

965
	// Create a small enough block chain to download and the tester
966
	targetBlocks := blockCacheItems - 15
967 968 969
	if targetBlocks >= MaxHashFetch {
		targetBlocks = MaxHashFetch - 15
	}
970 971 972
	if targetBlocks >= MaxHeaderFetch {
		targetBlocks = MaxHeaderFetch - 15
	}
973
	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
974

975
	tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
976 977

	// Make sure canceling works with a pristine downloader
978
	tester.downloader.Cancel()
979 980
	if !tester.downloader.queue.Idle() {
		t.Errorf("download queue not idle")
981 982
	}
	// Synchronise with the peer, but cancel afterwards
983
	if err := tester.sync("peer", nil, mode); err != nil {
984 985
		t.Fatalf("failed to synchronise blocks: %v", err)
	}
986
	tester.downloader.Cancel()
987 988
	if !tester.downloader.queue.Idle() {
		t.Errorf("download queue not idle")
989 990 991
	}
}

992
// Tests that synchronisation from multiple peers works as intended (multi thread sanity test).
993 994 995 996 997 998 999 1000
func TestMultiSynchronisation62(t *testing.T)      { testMultiSynchronisation(t, 62, FullSync) }
func TestMultiSynchronisation63Full(t *testing.T)  { testMultiSynchronisation(t, 63, FullSync) }
func TestMultiSynchronisation63Fast(t *testing.T)  { testMultiSynchronisation(t, 63, FastSync) }
func TestMultiSynchronisation64Full(t *testing.T)  { testMultiSynchronisation(t, 64, FullSync) }
func TestMultiSynchronisation64Fast(t *testing.T)  { testMultiSynchronisation(t, 64, FastSync) }
func TestMultiSynchronisation64Light(t *testing.T) { testMultiSynchronisation(t, 64, LightSync) }

func testMultiSynchronisation(t *testing.T, protocol int, mode SyncMode) {
1001 1002
	t.Parallel()

1003 1004 1005
	tester := newTester()
	defer tester.terminate()

1006
	// Create various peers with various parts of the chain
1007
	targetPeers := 8
1008
	targetBlocks := targetPeers*blockCacheItems - 15
1009
	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
1010

1011 1012
	for i := 0; i < targetPeers; i++ {
		id := fmt.Sprintf("peer #%d", i)
1013
		tester.newPeer(id, protocol, hashes[i*blockCacheItems:], headers, blocks, receipts)
1014
	}
1015
	if err := tester.sync("peer #0", nil, mode); err != nil {
1016 1017
		t.Fatalf("failed to synchronise blocks: %v", err)
	}
1018
	assertOwnChain(t, tester, targetBlocks+1)
1019 1020
}

1021
// Tests that synchronisations behave well in multi-version protocol environments
L
Leif Jurvetson 已提交
1022
// and not wreak havoc on other nodes in the network.
1023 1024 1025 1026 1027 1028 1029 1030
func TestMultiProtoSynchronisation62(t *testing.T)      { testMultiProtoSync(t, 62, FullSync) }
func TestMultiProtoSynchronisation63Full(t *testing.T)  { testMultiProtoSync(t, 63, FullSync) }
func TestMultiProtoSynchronisation63Fast(t *testing.T)  { testMultiProtoSync(t, 63, FastSync) }
func TestMultiProtoSynchronisation64Full(t *testing.T)  { testMultiProtoSync(t, 64, FullSync) }
func TestMultiProtoSynchronisation64Fast(t *testing.T)  { testMultiProtoSync(t, 64, FastSync) }
func TestMultiProtoSynchronisation64Light(t *testing.T) { testMultiProtoSync(t, 64, LightSync) }

func testMultiProtoSync(t *testing.T, protocol int, mode SyncMode) {
1031 1032
	t.Parallel()

1033 1034 1035
	tester := newTester()
	defer tester.terminate()

1036
	// Create a small enough block chain to download
1037
	targetBlocks := blockCacheItems - 15
1038
	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
1039 1040

	// Create peers of every type
1041
	tester.newPeer("peer 62", 62, hashes, headers, blocks, nil)
1042 1043
	tester.newPeer("peer 63", 63, hashes, headers, blocks, receipts)
	tester.newPeer("peer 64", 64, hashes, headers, blocks, receipts)
1044

1045 1046
	// Synchronise with the requested peer and make sure all blocks were retrieved
	if err := tester.sync(fmt.Sprintf("peer %d", protocol), nil, mode); err != nil {
1047 1048
		t.Fatalf("failed to synchronise blocks: %v", err)
	}
1049 1050
	assertOwnChain(t, tester, targetBlocks+1)

1051
	// Check that no peers have been dropped off
1052
	for _, version := range []int{62, 63, 64} {
1053 1054 1055 1056 1057 1058 1059
		peer := fmt.Sprintf("peer %d", version)
		if _, ok := tester.peerHashes[peer]; !ok {
			t.Errorf("%s dropped", peer)
		}
	}
}

1060
// Tests that if a block is empty (e.g. header only), no body request should be
1061
// made, and instead the header should be assembled into a whole block in itself.
1062 1063 1064 1065 1066 1067 1068 1069
func TestEmptyShortCircuit62(t *testing.T)      { testEmptyShortCircuit(t, 62, FullSync) }
func TestEmptyShortCircuit63Full(t *testing.T)  { testEmptyShortCircuit(t, 63, FullSync) }
func TestEmptyShortCircuit63Fast(t *testing.T)  { testEmptyShortCircuit(t, 63, FastSync) }
func TestEmptyShortCircuit64Full(t *testing.T)  { testEmptyShortCircuit(t, 64, FullSync) }
func TestEmptyShortCircuit64Fast(t *testing.T)  { testEmptyShortCircuit(t, 64, FastSync) }
func TestEmptyShortCircuit64Light(t *testing.T) { testEmptyShortCircuit(t, 64, LightSync) }

func testEmptyShortCircuit(t *testing.T, protocol int, mode SyncMode) {
1070 1071
	t.Parallel()

1072
	tester := newTester()
1073 1074
	defer tester.terminate()

1075
	// Create a block chain to download
1076
	targetBlocks := 2*blockCacheItems - 15
1077 1078
	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)

1079
	tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
1080 1081

	// Instrument the downloader to signal body requests
1082
	bodiesHave, receiptsHave := int32(0), int32(0)
1083
	tester.downloader.bodyFetchHook = func(headers []*types.Header) {
1084
		atomic.AddInt32(&bodiesHave, int32(len(headers)))
1085 1086
	}
	tester.downloader.receiptFetchHook = func(headers []*types.Header) {
1087
		atomic.AddInt32(&receiptsHave, int32(len(headers)))
1088 1089
	}
	// Synchronise with the peer and make sure all blocks were retrieved
1090
	if err := tester.sync("peer", nil, mode); err != nil {
1091 1092
		t.Fatalf("failed to synchronise blocks: %v", err)
	}
1093 1094
	assertOwnChain(t, tester, targetBlocks+1)

1095
	// Validate the number of block bodies that should have been requested
1096
	bodiesNeeded, receiptsNeeded := 0, 0
1097
	for _, block := range blocks {
1098
		if mode != LightSync && block != tester.genesis && (len(block.Transactions()) > 0 || len(block.Uncles()) > 0) {
1099
			bodiesNeeded++
1100
		}
1101
	}
1102 1103
	for _, receipt := range receipts {
		if mode == FastSync && len(receipt) > 0 {
1104 1105 1106
			receiptsNeeded++
		}
	}
1107 1108
	if int(bodiesHave) != bodiesNeeded {
		t.Errorf("body retrieval count mismatch: have %v, want %v", bodiesHave, bodiesNeeded)
1109
	}
1110 1111
	if int(receiptsHave) != receiptsNeeded {
		t.Errorf("receipt retrieval count mismatch: have %v, want %v", receiptsHave, receiptsNeeded)
1112 1113 1114
	}
}

1115 1116
// Tests that headers are enqueued continuously, preventing malicious nodes from
// stalling the downloader by feeding gapped header chains.
1117 1118 1119 1120 1121 1122 1123 1124
func TestMissingHeaderAttack62(t *testing.T)      { testMissingHeaderAttack(t, 62, FullSync) }
func TestMissingHeaderAttack63Full(t *testing.T)  { testMissingHeaderAttack(t, 63, FullSync) }
func TestMissingHeaderAttack63Fast(t *testing.T)  { testMissingHeaderAttack(t, 63, FastSync) }
func TestMissingHeaderAttack64Full(t *testing.T)  { testMissingHeaderAttack(t, 64, FullSync) }
func TestMissingHeaderAttack64Fast(t *testing.T)  { testMissingHeaderAttack(t, 64, FastSync) }
func TestMissingHeaderAttack64Light(t *testing.T) { testMissingHeaderAttack(t, 64, LightSync) }

func testMissingHeaderAttack(t *testing.T, protocol int, mode SyncMode) {
1125 1126
	t.Parallel()

1127
	tester := newTester()
1128
	defer tester.terminate()
1129

1130
	// Create a small enough block chain to download
1131
	targetBlocks := blockCacheItems - 15
1132 1133
	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)

1134
	// Attempt a full sync with an attacker feeding gapped headers
1135
	tester.newPeer("attack", protocol, hashes, headers, blocks, receipts)
1136
	missing := targetBlocks / 2
1137
	delete(tester.peerHeaders["attack"], hashes[missing])
1138

1139
	if err := tester.sync("attack", nil, mode); err == nil {
1140 1141 1142
		t.Fatalf("succeeded attacker synchronisation")
	}
	// Synchronise with the valid peer and make sure sync succeeds
1143
	tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
1144
	if err := tester.sync("valid", nil, mode); err != nil {
1145 1146
		t.Fatalf("failed to synchronise blocks: %v", err)
	}
1147
	assertOwnChain(t, tester, targetBlocks+1)
1148 1149 1150 1151
}

// Tests that if requested headers are shifted (i.e. first is missing), the queue
// detects the invalid numbering.
1152 1153 1154 1155 1156 1157 1158 1159
func TestShiftedHeaderAttack62(t *testing.T)      { testShiftedHeaderAttack(t, 62, FullSync) }
func TestShiftedHeaderAttack63Full(t *testing.T)  { testShiftedHeaderAttack(t, 63, FullSync) }
func TestShiftedHeaderAttack63Fast(t *testing.T)  { testShiftedHeaderAttack(t, 63, FastSync) }
func TestShiftedHeaderAttack64Full(t *testing.T)  { testShiftedHeaderAttack(t, 64, FullSync) }
func TestShiftedHeaderAttack64Fast(t *testing.T)  { testShiftedHeaderAttack(t, 64, FastSync) }
func TestShiftedHeaderAttack64Light(t *testing.T) { testShiftedHeaderAttack(t, 64, LightSync) }

func testShiftedHeaderAttack(t *testing.T, protocol int, mode SyncMode) {
1160 1161
	t.Parallel()

1162
	tester := newTester()
1163
	defer tester.terminate()
1164

1165
	// Create a small enough block chain to download
1166
	targetBlocks := blockCacheItems - 15
1167 1168
	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)

1169
	// Attempt a full sync with an attacker feeding shifted headers
1170
	tester.newPeer("attack", protocol, hashes, headers, blocks, receipts)
1171
	delete(tester.peerHeaders["attack"], hashes[len(hashes)-2])
1172
	delete(tester.peerBlocks["attack"], hashes[len(hashes)-2])
1173
	delete(tester.peerReceipts["attack"], hashes[len(hashes)-2])
1174

1175
	if err := tester.sync("attack", nil, mode); err == nil {
1176 1177 1178
		t.Fatalf("succeeded attacker synchronisation")
	}
	// Synchronise with the valid peer and make sure sync succeeds
1179
	tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
1180
	if err := tester.sync("valid", nil, mode); err != nil {
1181 1182 1183 1184 1185 1186
		t.Fatalf("failed to synchronise blocks: %v", err)
	}
	assertOwnChain(t, tester, targetBlocks+1)
}

// Tests that upon detecting an invalid header, the recent ones are rolled back
1187 1188
// for various failure scenarios. Afterwards a full sync is attempted to make
// sure no state was corrupted.
1189 1190 1191 1192 1193
func TestInvalidHeaderRollback63Fast(t *testing.T)  { testInvalidHeaderRollback(t, 63, FastSync) }
func TestInvalidHeaderRollback64Fast(t *testing.T)  { testInvalidHeaderRollback(t, 64, FastSync) }
func TestInvalidHeaderRollback64Light(t *testing.T) { testInvalidHeaderRollback(t, 64, LightSync) }

func testInvalidHeaderRollback(t *testing.T, protocol int, mode SyncMode) {
1194 1195
	t.Parallel()

1196
	tester := newTester()
1197
	defer tester.terminate()
1198

1199
	// Create a small enough block chain to download
1200
	targetBlocks := 3*fsHeaderSafetyNet + 256 + fsMinFullBlocks
1201 1202
	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)

1203 1204
	// Attempt to sync with an attacker that feeds junk during the fast sync phase.
	// This should result in the last fsHeaderSafetyNet headers being rolled back.
1205
	tester.newPeer("fast-attack", protocol, hashes, headers, blocks, receipts)
1206
	missing := fsHeaderSafetyNet + MaxHeaderFetch + 1
1207 1208
	delete(tester.peerHeaders["fast-attack"], hashes[len(hashes)-missing])

1209
	if err := tester.sync("fast-attack", nil, mode); err == nil {
1210 1211
		t.Fatalf("succeeded fast attacker synchronisation")
	}
1212
	if head := tester.CurrentHeader().Number.Int64(); int(head) > MaxHeaderFetch {
1213
		t.Errorf("rollback head mismatch: have %v, want at most %v", head, MaxHeaderFetch)
1214
	}
1215 1216 1217
	// Attempt to sync with an attacker that feeds junk during the block import phase.
	// This should result in both the last fsHeaderSafetyNet number of headers being
	// rolled back, and also the pivot point being reverted to a non-block status.
1218
	tester.newPeer("block-attack", protocol, hashes, headers, blocks, receipts)
1219
	missing = 3*fsHeaderSafetyNet + MaxHeaderFetch + 1
1220
	delete(tester.peerHeaders["fast-attack"], hashes[len(hashes)-missing]) // Make sure the fast-attacker doesn't fill in
1221 1222
	delete(tester.peerHeaders["block-attack"], hashes[len(hashes)-missing])

1223
	if err := tester.sync("block-attack", nil, mode); err == nil {
1224 1225
		t.Fatalf("succeeded block attacker synchronisation")
	}
1226
	if head := tester.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
1227 1228
		t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
	}
1229
	if mode == FastSync {
1230
		if head := tester.CurrentBlock().NumberU64(); head != 0 {
1231
			t.Errorf("fast sync pivot block #%d not rolled back", head)
1232
		}
1233
	}
1234 1235 1236 1237 1238
	// Attempt to sync with an attacker that withholds promised blocks after the
	// fast sync pivot point. This could be a trial to leave the node with a bad
	// but already imported pivot block.
	tester.newPeer("withhold-attack", protocol, hashes, headers, blocks, receipts)
	missing = 3*fsHeaderSafetyNet + MaxHeaderFetch + 1
1239

1240 1241 1242 1243 1244
	tester.downloader.syncInitHook = func(uint64, uint64) {
		for i := missing; i <= len(hashes); i++ {
			delete(tester.peerHeaders["withhold-attack"], hashes[len(hashes)-i])
		}
		tester.downloader.syncInitHook = nil
1245
	}
1246

1247 1248 1249
	if err := tester.sync("withhold-attack", nil, mode); err == nil {
		t.Fatalf("succeeded withholding attacker synchronisation")
	}
1250
	if head := tester.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
1251
		t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
1252 1253
	}
	if mode == FastSync {
1254
		if head := tester.CurrentBlock().NumberU64(); head != 0 {
1255 1256
			t.Errorf("fast sync pivot block #%d not rolled back", head)
		}
1257
	}
1258 1259 1260
	// Synchronise with the valid peer and make sure sync succeeds. Since the last
	// rollback should also disable fast syncing for this process, verify that we
	// did a fresh full sync. Note, we can't assert anything about the receipts
L
Leif Jurvetson 已提交
1261
	// since we won't purge the database of them, hence we can't use assertOwnChain.
1262 1263
	tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
	if err := tester.sync("valid", nil, mode); err != nil {
1264 1265
		t.Fatalf("failed to synchronise blocks: %v", err)
	}
1266 1267
	if hs := len(tester.ownHeaders); hs != len(headers) {
		t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, len(headers))
1268
	}
1269 1270 1271 1272
	if mode != LightSync {
		if bs := len(tester.ownBlocks); bs != len(blocks) {
			t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, len(blocks))
		}
1273
	}
1274 1275
}

1276 1277
// Tests that a peer advertising an high TD doesn't get to stall the downloader
// afterwards by not sending any useful hashes.
1278 1279 1280 1281 1282 1283 1284 1285
func TestHighTDStarvationAttack62(t *testing.T)      { testHighTDStarvationAttack(t, 62, FullSync) }
func TestHighTDStarvationAttack63Full(t *testing.T)  { testHighTDStarvationAttack(t, 63, FullSync) }
func TestHighTDStarvationAttack63Fast(t *testing.T)  { testHighTDStarvationAttack(t, 63, FastSync) }
func TestHighTDStarvationAttack64Full(t *testing.T)  { testHighTDStarvationAttack(t, 64, FullSync) }
func TestHighTDStarvationAttack64Fast(t *testing.T)  { testHighTDStarvationAttack(t, 64, FastSync) }
func TestHighTDStarvationAttack64Light(t *testing.T) { testHighTDStarvationAttack(t, 64, LightSync) }

func testHighTDStarvationAttack(t *testing.T, protocol int, mode SyncMode) {
1286 1287
	t.Parallel()

1288
	tester := newTester()
1289
	defer tester.terminate()
1290

1291
	hashes, headers, blocks, receipts := tester.makeChain(0, 0, tester.genesis, nil, false)
1292
	tester.newPeer("attack", protocol, []common.Hash{hashes[0]}, headers, blocks, receipts)
1293

1294
	if err := tester.sync("attack", big.NewInt(1000000), mode); err != errStallingPeer {
1295 1296 1297 1298
		t.Fatalf("synchronisation error mismatch: have %v, want %v", err, errStallingPeer)
	}
}

1299
// Tests that misbehaving peers are disconnected, whilst behaving ones are not.
1300 1301 1302 1303 1304
func TestBlockHeaderAttackerDropping62(t *testing.T) { testBlockHeaderAttackerDropping(t, 62) }
func TestBlockHeaderAttackerDropping63(t *testing.T) { testBlockHeaderAttackerDropping(t, 63) }
func TestBlockHeaderAttackerDropping64(t *testing.T) { testBlockHeaderAttackerDropping(t, 64) }

func testBlockHeaderAttackerDropping(t *testing.T, protocol int) {
1305 1306
	t.Parallel()

1307
	// Define the disconnection requirement for individual hash fetch errors
1308 1309 1310 1311
	tests := []struct {
		result error
		drop   bool
	}{
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
		{nil, false},                        // Sync succeeded, all is well
		{errBusy, false},                    // Sync is already in progress, no problem
		{errUnknownPeer, false},             // Peer is unknown, was already dropped, don't double drop
		{errBadPeer, true},                  // Peer was deemed bad for some reason, drop it
		{errStallingPeer, true},             // Peer was detected to be stalling, drop it
		{errNoPeers, false},                 // No peers to download from, soft race, no issue
		{errTimeout, true},                  // No hashes received in due time, drop the peer
		{errEmptyHeaderSet, true},           // No headers were returned as a response, drop as it's a dead end
		{errPeersUnavailable, true},         // Nobody had the advertised blocks, drop the advertiser
		{errInvalidAncestor, true},          // Agreed upon ancestor is not acceptable, drop the chain rewriter
		{errInvalidChain, true},             // Hash chain was detected as invalid, definitely drop
		{errInvalidBlock, false},            // A bad peer was detected, but not the sync origin
		{errInvalidBody, false},             // A bad peer was detected, but not the sync origin
		{errInvalidReceipt, false},          // A bad peer was detected, but not the sync origin
		{errCancelBlockFetch, false},        // Synchronisation was canceled, origin may be innocent, don't drop
		{errCancelHeaderFetch, false},       // Synchronisation was canceled, origin may be innocent, don't drop
		{errCancelBodyFetch, false},         // Synchronisation was canceled, origin may be innocent, don't drop
		{errCancelReceiptFetch, false},      // Synchronisation was canceled, origin may be innocent, don't drop
		{errCancelHeaderProcessing, false},  // Synchronisation was canceled, origin may be innocent, don't drop
		{errCancelContentProcessing, false}, // Synchronisation was canceled, origin may be innocent, don't drop
1332 1333
	}
	// Run the tests and check disconnection status
1334
	tester := newTester()
1335 1336
	defer tester.terminate()

1337 1338 1339
	for i, tt := range tests {
		// Register a new peer and ensure it's presence
		id := fmt.Sprintf("test %d", i)
1340
		if err := tester.newPeer(id, protocol, []common.Hash{tester.genesis.Hash()}, nil, nil, nil); err != nil {
1341 1342 1343 1344 1345 1346 1347 1348
			t.Fatalf("test %d: failed to register new peer: %v", i, err)
		}
		if _, ok := tester.peerHashes[id]; !ok {
			t.Fatalf("test %d: registered peer not found", i)
		}
		// Simulate a synchronisation and check the required result
		tester.downloader.synchroniseMock = func(string, common.Hash) error { return tt.result }

1349
		tester.downloader.Synchronise(id, tester.genesis.Hash(), big.NewInt(1000), FullSync)
1350 1351 1352 1353 1354
		if _, ok := tester.peerHashes[id]; !ok != tt.drop {
			t.Errorf("test %d: peer drop mismatch for %v: have %v, want %v", i, tt.result, !ok, tt.drop)
		}
	}
}
1355

1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
// Tests that synchronisation progress (origin block number, current block number
// and highest block number) is tracked and updated correctly.
func TestSyncProgress62(t *testing.T)      { testSyncProgress(t, 62, FullSync) }
func TestSyncProgress63Full(t *testing.T)  { testSyncProgress(t, 63, FullSync) }
func TestSyncProgress63Fast(t *testing.T)  { testSyncProgress(t, 63, FastSync) }
func TestSyncProgress64Full(t *testing.T)  { testSyncProgress(t, 64, FullSync) }
func TestSyncProgress64Fast(t *testing.T)  { testSyncProgress(t, 64, FastSync) }
func TestSyncProgress64Light(t *testing.T) { testSyncProgress(t, 64, LightSync) }

func testSyncProgress(t *testing.T, protocol int, mode SyncMode) {
1366 1367
	t.Parallel()

1368 1369 1370
	tester := newTester()
	defer tester.terminate()

1371
	// Create a small enough block chain to download
1372
	targetBlocks := blockCacheItems - 15
1373
	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
1374

1375
	// Set a sync init hook to catch progress changes
1376 1377 1378 1379 1380 1381 1382
	starting := make(chan struct{})
	progress := make(chan struct{})

	tester.downloader.syncInitHook = func(origin, latest uint64) {
		starting <- struct{}{}
		<-progress
	}
1383
	// Retrieve the sync progress and ensure they are zero (pristine sync)
1384 1385
	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
		t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
1386
	}
1387
	// Synchronise half the blocks and check initial progress
1388
	tester.newPeer("peer-half", protocol, hashes[targetBlocks/2:], headers, blocks, receipts)
1389 1390 1391 1392 1393
	pending := new(sync.WaitGroup)
	pending.Add(1)

	go func() {
		defer pending.Done()
1394
		if err := tester.sync("peer-half", nil, mode); err != nil {
E
Egon Elbre 已提交
1395
			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
1396 1397 1398
		}
	}()
	<-starting
1399 1400
	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(targetBlocks/2+1) {
		t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, targetBlocks/2+1)
1401 1402 1403 1404
	}
	progress <- struct{}{}
	pending.Wait()

1405
	// Synchronise all the blocks and check continuation progress
1406
	tester.newPeer("peer-full", protocol, hashes, headers, blocks, receipts)
1407 1408 1409 1410
	pending.Add(1)

	go func() {
		defer pending.Done()
1411
		if err := tester.sync("peer-full", nil, mode); err != nil {
E
Egon Elbre 已提交
1412
			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
1413 1414 1415
		}
	}()
	<-starting
1416 1417
	if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(targetBlocks/2+1) || progress.CurrentBlock != uint64(targetBlocks/2+1) || progress.HighestBlock != uint64(targetBlocks) {
		t.Fatalf("Completing progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, targetBlocks/2+1, targetBlocks/2+1, targetBlocks)
1418 1419 1420
	}
	progress <- struct{}{}
	pending.Wait()
1421 1422

	// Check final progress after successful sync
1423 1424
	if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(targetBlocks/2+1) || progress.CurrentBlock != uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
		t.Fatalf("Final progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, targetBlocks/2+1, targetBlocks, targetBlocks)
1425
	}
1426 1427
}

1428
// Tests that synchronisation progress (origin block number and highest block
1429 1430
// number) is tracked and updated correctly in case of a fork (or manual head
// revertal).
1431 1432 1433 1434 1435 1436 1437 1438
func TestForkedSyncProgress62(t *testing.T)      { testForkedSyncProgress(t, 62, FullSync) }
func TestForkedSyncProgress63Full(t *testing.T)  { testForkedSyncProgress(t, 63, FullSync) }
func TestForkedSyncProgress63Fast(t *testing.T)  { testForkedSyncProgress(t, 63, FastSync) }
func TestForkedSyncProgress64Full(t *testing.T)  { testForkedSyncProgress(t, 64, FullSync) }
func TestForkedSyncProgress64Fast(t *testing.T)  { testForkedSyncProgress(t, 64, FastSync) }
func TestForkedSyncProgress64Light(t *testing.T) { testForkedSyncProgress(t, 64, LightSync) }

func testForkedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
1439 1440
	t.Parallel()

1441 1442 1443
	tester := newTester()
	defer tester.terminate()

1444 1445
	// Create a forked chain to simulate origin revertal
	common, fork := MaxHashFetch, 2*MaxHashFetch
1446
	hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, true)
1447

1448
	// Set a sync init hook to catch progress changes
1449 1450 1451 1452 1453 1454 1455
	starting := make(chan struct{})
	progress := make(chan struct{})

	tester.downloader.syncInitHook = func(origin, latest uint64) {
		starting <- struct{}{}
		<-progress
	}
1456
	// Retrieve the sync progress and ensure they are zero (pristine sync)
1457 1458
	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
		t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
1459
	}
1460
	// Synchronise with one of the forks and check progress
1461
	tester.newPeer("fork A", protocol, hashesA, headersA, blocksA, receiptsA)
1462 1463 1464 1465 1466
	pending := new(sync.WaitGroup)
	pending.Add(1)

	go func() {
		defer pending.Done()
1467
		if err := tester.sync("fork A", nil, mode); err != nil {
E
Egon Elbre 已提交
1468
			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
1469 1470 1471
		}
	}()
	<-starting
1472 1473
	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(len(hashesA)-1) {
		t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, len(hashesA)-1)
1474 1475 1476 1477 1478
	}
	progress <- struct{}{}
	pending.Wait()

	// Simulate a successful sync above the fork
1479
	tester.downloader.syncStatsChainOrigin = tester.downloader.syncStatsChainHeight
1480

1481
	// Synchronise with the second fork and check progress resets
1482
	tester.newPeer("fork B", protocol, hashesB, headersB, blocksB, receiptsB)
1483 1484 1485 1486
	pending.Add(1)

	go func() {
		defer pending.Done()
1487
		if err := tester.sync("fork B", nil, mode); err != nil {
E
Egon Elbre 已提交
1488
			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
1489 1490 1491
		}
	}()
	<-starting
1492 1493
	if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(common) || progress.CurrentBlock != uint64(len(hashesA)-1) || progress.HighestBlock != uint64(len(hashesB)-1) {
		t.Fatalf("Forking progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, common, len(hashesA)-1, len(hashesB)-1)
1494 1495 1496
	}
	progress <- struct{}{}
	pending.Wait()
1497 1498

	// Check final progress after successful sync
1499 1500
	if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(common) || progress.CurrentBlock != uint64(len(hashesB)-1) || progress.HighestBlock != uint64(len(hashesB)-1) {
		t.Fatalf("Final progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, common, len(hashesB)-1, len(hashesB)-1)
1501
	}
1502 1503
}

1504
// Tests that if synchronisation is aborted due to some failure, then the progress
1505 1506
// origin is not updated in the next sync cycle, as it should be considered the
// continuation of the previous sync and not a new instance.
1507 1508 1509 1510 1511 1512 1513 1514
func TestFailedSyncProgress62(t *testing.T)      { testFailedSyncProgress(t, 62, FullSync) }
func TestFailedSyncProgress63Full(t *testing.T)  { testFailedSyncProgress(t, 63, FullSync) }
func TestFailedSyncProgress63Fast(t *testing.T)  { testFailedSyncProgress(t, 63, FastSync) }
func TestFailedSyncProgress64Full(t *testing.T)  { testFailedSyncProgress(t, 64, FullSync) }
func TestFailedSyncProgress64Fast(t *testing.T)  { testFailedSyncProgress(t, 64, FastSync) }
func TestFailedSyncProgress64Light(t *testing.T) { testFailedSyncProgress(t, 64, LightSync) }

func testFailedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
1515 1516
	t.Parallel()

1517 1518 1519
	tester := newTester()
	defer tester.terminate()

1520
	// Create a small enough block chain to download
1521
	targetBlocks := blockCacheItems - 15
1522
	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
1523

1524
	// Set a sync init hook to catch progress changes
1525 1526 1527 1528 1529 1530 1531
	starting := make(chan struct{})
	progress := make(chan struct{})

	tester.downloader.syncInitHook = func(origin, latest uint64) {
		starting <- struct{}{}
		<-progress
	}
1532
	// Retrieve the sync progress and ensure they are zero (pristine sync)
1533 1534
	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
		t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
1535 1536
	}
	// Attempt a full sync with a faulty peer
1537
	tester.newPeer("faulty", protocol, hashes, headers, blocks, receipts)
1538
	missing := targetBlocks / 2
1539
	delete(tester.peerHeaders["faulty"], hashes[missing])
1540
	delete(tester.peerBlocks["faulty"], hashes[missing])
1541
	delete(tester.peerReceipts["faulty"], hashes[missing])
1542 1543 1544 1545 1546 1547

	pending := new(sync.WaitGroup)
	pending.Add(1)

	go func() {
		defer pending.Done()
1548
		if err := tester.sync("faulty", nil, mode); err == nil {
E
Egon Elbre 已提交
1549
			panic("succeeded faulty synchronisation")
1550 1551 1552
		}
	}()
	<-starting
1553 1554
	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(targetBlocks) {
		t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, targetBlocks)
1555 1556 1557 1558
	}
	progress <- struct{}{}
	pending.Wait()

1559
	// Synchronise with a good peer and check that the progress origin remind the same after a failure
1560
	tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
1561 1562 1563 1564
	pending.Add(1)

	go func() {
		defer pending.Done()
1565
		if err := tester.sync("valid", nil, mode); err != nil {
E
Egon Elbre 已提交
1566
			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
1567 1568 1569
		}
	}()
	<-starting
1570 1571
	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock > uint64(targetBlocks/2) || progress.HighestBlock != uint64(targetBlocks) {
		t.Fatalf("Completing progress mismatch: have %v/%v/%v, want %v/0-%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, targetBlocks/2, targetBlocks)
1572 1573 1574
	}
	progress <- struct{}{}
	pending.Wait()
1575 1576

	// Check final progress after successful sync
1577 1578
	if progress := tester.downloader.Progress(); progress.StartingBlock > uint64(targetBlocks/2) || progress.CurrentBlock != uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
		t.Fatalf("Final progress mismatch: have %v/%v/%v, want 0-%v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, targetBlocks/2, targetBlocks, targetBlocks)
1579
	}
1580 1581 1582
}

// Tests that if an attacker fakes a chain height, after the attack is detected,
1583 1584 1585 1586 1587 1588 1589 1590 1591
// the progress height is successfully reduced at the next sync invocation.
func TestFakedSyncProgress62(t *testing.T)      { testFakedSyncProgress(t, 62, FullSync) }
func TestFakedSyncProgress63Full(t *testing.T)  { testFakedSyncProgress(t, 63, FullSync) }
func TestFakedSyncProgress63Fast(t *testing.T)  { testFakedSyncProgress(t, 63, FastSync) }
func TestFakedSyncProgress64Full(t *testing.T)  { testFakedSyncProgress(t, 64, FullSync) }
func TestFakedSyncProgress64Fast(t *testing.T)  { testFakedSyncProgress(t, 64, FastSync) }
func TestFakedSyncProgress64Light(t *testing.T) { testFakedSyncProgress(t, 64, LightSync) }

func testFakedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
1592 1593
	t.Parallel()

1594 1595 1596
	tester := newTester()
	defer tester.terminate()

1597
	// Create a small block chain
1598
	targetBlocks := blockCacheItems - 15
1599
	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks+3, 0, tester.genesis, nil, false)
1600

1601
	// Set a sync init hook to catch progress changes
1602 1603 1604 1605 1606 1607 1608
	starting := make(chan struct{})
	progress := make(chan struct{})

	tester.downloader.syncInitHook = func(origin, latest uint64) {
		starting <- struct{}{}
		<-progress
	}
1609
	// Retrieve the sync progress and ensure they are zero (pristine sync)
1610 1611
	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
		t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
1612 1613
	}
	//  Create and sync with an attacker that promises a higher chain than available
1614
	tester.newPeer("attack", protocol, hashes, headers, blocks, receipts)
1615
	for i := 1; i < 3; i++ {
1616
		delete(tester.peerHeaders["attack"], hashes[i])
1617
		delete(tester.peerBlocks["attack"], hashes[i])
1618
		delete(tester.peerReceipts["attack"], hashes[i])
1619 1620 1621 1622 1623 1624 1625
	}

	pending := new(sync.WaitGroup)
	pending.Add(1)

	go func() {
		defer pending.Done()
1626
		if err := tester.sync("attack", nil, mode); err == nil {
E
Egon Elbre 已提交
1627
			panic("succeeded attacker synchronisation")
1628 1629 1630
		}
	}()
	<-starting
1631 1632
	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(targetBlocks+3) {
		t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, targetBlocks+3)
1633 1634 1635 1636
	}
	progress <- struct{}{}
	pending.Wait()

1637
	// Synchronise with a good peer and check that the progress height has been reduced to the true value
1638
	tester.newPeer("valid", protocol, hashes[3:], headers, blocks, receipts)
1639 1640 1641 1642
	pending.Add(1)

	go func() {
		defer pending.Done()
1643
		if err := tester.sync("valid", nil, mode); err != nil {
E
Egon Elbre 已提交
1644
			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
1645 1646 1647
		}
	}()
	<-starting
1648 1649
	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock > uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
		t.Fatalf("Completing progress mismatch: have %v/%v/%v, want %v/0-%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, targetBlocks, targetBlocks)
1650 1651 1652
	}
	progress <- struct{}{}
	pending.Wait()
1653 1654

	// Check final progress after successful sync
1655 1656
	if progress := tester.downloader.Progress(); progress.StartingBlock > uint64(targetBlocks) || progress.CurrentBlock != uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
		t.Fatalf("Final progress mismatch: have %v/%v/%v, want 0-%v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, targetBlocks, targetBlocks, targetBlocks)
1657
	}
1658
}
1659 1660 1661

// This test reproduces an issue where unexpected deliveries would
// block indefinitely if they arrived at the right time.
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
// We use data driven subtests to manage this so that it will be parallel on its own
// and not with the other tests, avoiding intermittent failures.
func TestDeliverHeadersHang(t *testing.T) {
	testCases := []struct {
		protocol int
		syncMode SyncMode
	}{
		{62, FullSync},
		{63, FullSync},
		{63, FastSync},
		{64, FullSync},
		{64, FastSync},
		{64, LightSync},
	}
	for _, tc := range testCases {
		t.Run(fmt.Sprintf("protocol %d mode %v", tc.protocol, tc.syncMode), func(t *testing.T) {
			testDeliverHeadersHang(t, tc.protocol, tc.syncMode)
		})
	}
}
1682

1683 1684 1685
type floodingTestPeer struct {
	peer   Peer
	tester *downloadTester
1686
	pend   sync.WaitGroup
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
}

func (ftp *floodingTestPeer) Head() (common.Hash, *big.Int) { return ftp.peer.Head() }
func (ftp *floodingTestPeer) RequestHeadersByHash(hash common.Hash, count int, skip int, reverse bool) error {
	return ftp.peer.RequestHeadersByHash(hash, count, skip, reverse)
}
func (ftp *floodingTestPeer) RequestBodies(hashes []common.Hash) error {
	return ftp.peer.RequestBodies(hashes)
}
func (ftp *floodingTestPeer) RequestReceipts(hashes []common.Hash) error {
	return ftp.peer.RequestReceipts(hashes)
}
func (ftp *floodingTestPeer) RequestNodeData(hashes []common.Hash) error {
	return ftp.peer.RequestNodeData(hashes)
}

func (ftp *floodingTestPeer) RequestHeadersByNumber(from uint64, count, skip int, reverse bool) error {
	deliveriesDone := make(chan struct{}, 500)
	for i := 0; i < cap(deliveriesDone); i++ {
		peer := fmt.Sprintf("fake-peer%d", i)
1707 1708
		ftp.pend.Add(1)

1709 1710 1711
		go func() {
			ftp.tester.downloader.DeliverHeaders(peer, []*types.Header{{}, {}, {}, {}})
			deliveriesDone <- struct{}{}
1712
			ftp.pend.Done()
1713 1714 1715 1716 1717
		}()
	}
	// Deliver the actual requested headers.
	go ftp.peer.RequestHeadersByNumber(from, count, skip, reverse)
	// None of the extra deliveries should block.
1718
	timeout := time.After(60 * time.Second)
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
	for i := 0; i < cap(deliveriesDone); i++ {
		select {
		case <-deliveriesDone:
		case <-timeout:
			panic("blocked")
		}
	}
	return nil
}

1729 1730
func testDeliverHeadersHang(t *testing.T, protocol int, mode SyncMode) {
	t.Parallel()
1731 1732 1733 1734 1735

	master := newTester()
	defer master.terminate()

	hashes, headers, blocks, receipts := master.makeChain(5, 0, master.genesis, nil, false)
1736 1737
	for i := 0; i < 200; i++ {
		tester := newTester()
1738 1739
		tester.peerDb = master.peerDb

1740 1741 1742
		tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
		// Whenever the downloader requests headers, flood it with
		// a lot of unrequested header deliveries.
1743
		tester.downloader.peers.peers["peer"].peer = &floodingTestPeer{
1744 1745
			peer:   tester.downloader.peers.peers["peer"].peer,
			tester: tester,
1746 1747
		}
		if err := tester.sync("peer", nil, mode); err != nil {
1748
			t.Errorf("test %d: sync failed: %v", i, err)
1749
		}
1750
		tester.terminate()
1751

1752 1753
		// Flush all goroutines to prevent messing with subsequent tests
		tester.downloader.peers.peers["peer"].peer.(*floodingTestPeer).pend.Wait()
1754 1755
	}
}