github.com/yinchengtsinghua/golang-Eos-dpos-Ethereum@v0.0.0-20190121132951-92cc4225ed8e/eth/downloader/downloader_test.go (about)

     1  
     2  //此源码被清华学神尹成大魔王专业翻译分析并修改
     3  //尹成QQ77025077
     4  //尹成微信18510341407
     5  //尹成所在QQ群721929980
     6  //尹成邮箱 yinc13@mails.tsinghua.edu.cn
     7  //尹成毕业于清华大学,微软区块链领域全球最有价值专家
     8  //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
     9  //版权所有2015 Go Ethereum作者
    10  //此文件是Go以太坊库的一部分。
    11  //
    12  //Go-Ethereum库是免费软件:您可以重新分发它和/或修改
    13  //根据GNU发布的较低通用公共许可证的条款
    14  //自由软件基金会,或者许可证的第3版,或者
    15  //(由您选择)任何更高版本。
    16  //
    17  //Go以太坊图书馆的发行目的是希望它会有用,
    18  //但没有任何保证;甚至没有
    19  //适销性或特定用途的适用性。见
    20  //GNU较低的通用公共许可证,了解更多详细信息。
    21  //
    22  //你应该收到一份GNU较低级别的公共许可证副本
    23  //以及Go以太坊图书馆。如果没有,请参见<http://www.gnu.org/licenses/>。
    24  
    25  package downloader
    26  
    27  import (
    28  	"errors"
    29  	"fmt"
    30  	"math/big"
    31  	"sync"
    32  	"sync/atomic"
    33  	"testing"
    34  	"time"
    35  
    36  	"github.com/ethereum/go-ethereum/common"
    37  	"github.com/ethereum/go-ethereum/consensus/ethash"
    38  	"github.com/ethereum/go-ethereum/core"
    39  	"github.com/ethereum/go-ethereum/core/types"
    40  	"github.com/ethereum/go-ethereum/crypto"
    41  	"github.com/ethereum/go-ethereum/ethdb"
    42  	"github.com/ethereum/go-ethereum/event"
    43  	"github.com/ethereum/go-ethereum/params"
    44  	"github.com/ethereum/go-ethereum/trie"
    45  )
    46  
    47  var (
    48  	testKey, _  = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
    49  	testAddress = crypto.PubkeyToAddress(testKey.PublicKey)
    50  )
    51  
    52  //减少一些参数以使测试仪更快。
    53  func init() {
    54  	MaxForkAncestry = uint64(10000)
    55  	blockCacheItems = 1024
    56  	fsHeaderContCheck = 500 * time.Millisecond
    57  }
    58  
    59  //下载测试仪是模拟本地区块链的测试模拟器。
    60  type downloadTester struct {
    61  	downloader *Downloader
    62  
    63  genesis *types.Block   //测试人员和同行使用的Genesis块
    64  stateDb ethdb.Database //测试人员用于从对等机同步的数据库
    65  peerDb  ethdb.Database //包含所有数据的对等数据库
    66  
    67  ownHashes   []common.Hash                  //属于测试人员的哈希链
    68  ownHeaders  map[common.Hash]*types.Header  //属于检测仪的收割台
    69  ownBlocks   map[common.Hash]*types.Block   //属于测试仪的块
    70  ownReceipts map[common.Hash]types.Receipts //属于测试人员的收据
    71  ownChainTd  map[common.Hash]*big.Int       //本地链中块的总困难
    72  
    73  peerHashes   map[string][]common.Hash                  //属于不同测试对等方的哈希链
    74  peerHeaders  map[string]map[common.Hash]*types.Header  //属于不同测试对等的头
    75  peerBlocks   map[string]map[common.Hash]*types.Block   //属于不同测试对等体的块
    76  peerReceipts map[string]map[common.Hash]types.Receipts //Receipts belonging to different test peers
    77  peerChainTds map[string]map[common.Hash]*big.Int       //对等链中块的总困难
    78  
    79  peerMissingStates map[string]map[common.Hash]bool //快速同步不应返回的状态项
    80  
    81  	lock sync.RWMutex
    82  }
    83  
    84  //NewTester创建了一个新的下载程序测试mocker。
    85  func newTester() *downloadTester {
    86  	testdb := ethdb.NewMemDatabase()
    87  	genesis := core.GenesisBlockForTesting(testdb, testAddress, big.NewInt(1000000000))
    88  
    89  	tester := &downloadTester{
    90  		genesis:           genesis,
    91  		peerDb:            testdb,
    92  		ownHashes:         []common.Hash{genesis.Hash()},
    93  		ownHeaders:        map[common.Hash]*types.Header{genesis.Hash(): genesis.Header()},
    94  		ownBlocks:         map[common.Hash]*types.Block{genesis.Hash(): genesis},
    95  		ownReceipts:       map[common.Hash]types.Receipts{genesis.Hash(): nil},
    96  		ownChainTd:        map[common.Hash]*big.Int{genesis.Hash(): genesis.Difficulty()},
    97  		peerHashes:        make(map[string][]common.Hash),
    98  		peerHeaders:       make(map[string]map[common.Hash]*types.Header),
    99  		peerBlocks:        make(map[string]map[common.Hash]*types.Block),
   100  		peerReceipts:      make(map[string]map[common.Hash]types.Receipts),
   101  		peerChainTds:      make(map[string]map[common.Hash]*big.Int),
   102  		peerMissingStates: make(map[string]map[common.Hash]bool),
   103  	}
   104  	tester.stateDb = ethdb.NewMemDatabase()
   105  	tester.stateDb.Put(genesis.Root().Bytes(), []byte{0x00})
   106  
   107  	tester.downloader = New(FullSync, tester.stateDb, new(event.TypeMux), tester, nil, tester.dropPeer)
   108  
   109  	return tester
   110  }
   111  
   112  //makechain创建一个由n个块组成的链,从父块开始并包含父块。
   113  //返回的哈希链是有序的head->parent。此外,每三个街区
   114  //包含一个事务,每隔5分钟一个叔叔以允许测试正确的块
   115  //重新组装。
   116  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) {
   117  //生成区块链
   118  	blocks, receipts := core.GenerateChain(params.TestChainConfig, parent, ethash.NewFaker(), dl.peerDb, n, func(i int, block *core.BlockGen) {
   119  		block.SetCoinbase(common.Address{seed})
   120  
   121  //如果要求重链,则延迟阻止以增加难度。
   122  		if heavy {
   123  			block.OffsetTime(-1)
   124  		}
   125  //If the block number is multiple of 3, send a bonus transaction to the miner
   126  		if parent == dl.genesis && i%3 == 0 {
   127  			signer := types.MakeSigner(params.TestChainConfig, block.Number())
   128  			tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, nil, nil), signer, testKey)
   129  			if err != nil {
   130  				panic(err)
   131  			}
   132  			block.AddTx(tx)
   133  		}
   134  //如果区块编号是5的倍数,请在区块中添加一个奖金叔叔。
   135  		if i > 0 && i%5 == 0 {
   136  			block.AddUncle(&types.Header{
   137  				ParentHash: block.PrevBlock(i - 1).Hash(),
   138  				Number:     big.NewInt(block.Number().Int64() - 1),
   139  			})
   140  		}
   141  	})
   142  //将块链转换为哈希链和头/块映射
   143  	hashes := make([]common.Hash, n+1)
   144  	hashes[len(hashes)-1] = parent.Hash()
   145  
   146  	headerm := make(map[common.Hash]*types.Header, n+1)
   147  	headerm[parent.Hash()] = parent.Header()
   148  
   149  	blockm := make(map[common.Hash]*types.Block, n+1)
   150  	blockm[parent.Hash()] = parent
   151  
   152  	receiptm := make(map[common.Hash]types.Receipts, n+1)
   153  	receiptm[parent.Hash()] = parentReceipts
   154  
   155  	for i, b := range blocks {
   156  		hashes[len(hashes)-i-2] = b.Hash()
   157  		headerm[b.Hash()] = b.Header()
   158  		blockm[b.Hash()] = b
   159  		receiptm[b.Hash()] = receipts[i]
   160  	}
   161  	return hashes, headerm, blockm, receiptm
   162  }
   163  
   164  //makechainfork创建两个长度为n的链,这样h1[:f]和
   165  //h2[:f]不同,但有一个长度为n-f的公共后缀。
   166  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) {
   167  //创建公共后缀
   168  	hashes, headers, blocks, receipts := dl.makeChain(n-f, 0, parent, parentReceipts, false)
   169  
   170  //创建叉,如果请求非平衡叉,则使第二个更重
   171  	hashes1, headers1, blocks1, receipts1 := dl.makeChain(f, 1, blocks[hashes[0]], receipts[hashes[0]], false)
   172  	hashes1 = append(hashes1, hashes[1:]...)
   173  
   174  	heavy := false
   175  	if !balanced {
   176  		heavy = true
   177  	}
   178  	hashes2, headers2, blocks2, receipts2 := dl.makeChain(f, 2, blocks[hashes[0]], receipts[hashes[0]], heavy)
   179  	hashes2 = append(hashes2, hashes[1:]...)
   180  
   181  	for hash, header := range headers {
   182  		headers1[hash] = header
   183  		headers2[hash] = header
   184  	}
   185  	for hash, block := range blocks {
   186  		blocks1[hash] = block
   187  		blocks2[hash] = block
   188  	}
   189  	for hash, receipt := range receipts {
   190  		receipts1[hash] = receipt
   191  		receipts2[hash] = receipt
   192  	}
   193  	return hashes1, hashes2, headers1, headers2, blocks1, blocks2, receipts1, receipts2
   194  }
   195  
   196  //终止中止嵌入式下载程序上的任何操作并释放所有
   197  //持有资源。
   198  func (dl *downloadTester) terminate() {
   199  	dl.downloader.Terminate()
   200  }
   201  
   202  //同步开始与远程对等机同步,直到同步完成。
   203  func (dl *downloadTester) sync(id string, td *big.Int, mode SyncMode) error {
   204  	dl.lock.RLock()
   205  	hash := dl.peerHashes[id][0]
   206  //如果没有请求特定的TD,则从对等区块链加载
   207  	if td == nil {
   208  		td = big.NewInt(1)
   209  		if diff, ok := dl.peerChainTds[id][hash]; ok {
   210  			td = diff
   211  		}
   212  	}
   213  	dl.lock.RUnlock()
   214  
   215  //与选定的对等机同步,并确保随后正确清理
   216  	err := dl.downloader.synchronise(id, hash, td, mode)
   217  	select {
   218  	case <-dl.downloader.cancelCh:
   219  //好的,下载程序在同步循环后完全取消
   220  	default:
   221  //下载程序仍在接受数据包,可能会阻止对等机
   222  panic("downloader active post sync cycle") //测试人员会发现恐慌
   223  	}
   224  	return err
   225  }
   226  
   227  //hasheader检查测试仪规范链中是否存在头。
   228  func (dl *downloadTester) HasHeader(hash common.Hash, number uint64) bool {
   229  	return dl.GetHeaderByHash(hash) != nil
   230  }
   231  
   232  //hasblock检查测试仪规范链中是否存在块。
   233  func (dl *downloadTester) HasBlock(hash common.Hash, number uint64) bool {
   234  	return dl.GetBlockByHash(hash) != nil
   235  }
   236  
   237  //getheader从测试人员规范链中检索一个头。
   238  func (dl *downloadTester) GetHeaderByHash(hash common.Hash) *types.Header {
   239  	dl.lock.RLock()
   240  	defer dl.lock.RUnlock()
   241  
   242  	return dl.ownHeaders[hash]
   243  }
   244  
   245  //GetBlock从测试程序规范链中检索一个块。
   246  func (dl *downloadTester) GetBlockByHash(hash common.Hash) *types.Block {
   247  	dl.lock.RLock()
   248  	defer dl.lock.RUnlock()
   249  
   250  	return dl.ownBlocks[hash]
   251  }
   252  
   253  //当前头从规范链中检索当前头。
   254  func (dl *downloadTester) CurrentHeader() *types.Header {
   255  	dl.lock.RLock()
   256  	defer dl.lock.RUnlock()
   257  
   258  	for i := len(dl.ownHashes) - 1; i >= 0; i-- {
   259  		if header := dl.ownHeaders[dl.ownHashes[i]]; header != nil {
   260  			return header
   261  		}
   262  	}
   263  	return dl.genesis.Header()
   264  }
   265  
   266  //currentBlock从规范链中检索当前头块。
   267  func (dl *downloadTester) CurrentBlock() *types.Block {
   268  	dl.lock.RLock()
   269  	defer dl.lock.RUnlock()
   270  
   271  	for i := len(dl.ownHashes) - 1; i >= 0; i-- {
   272  		if block := dl.ownBlocks[dl.ownHashes[i]]; block != nil {
   273  			if _, err := dl.stateDb.Get(block.Root().Bytes()); err == nil {
   274  				return block
   275  			}
   276  		}
   277  	}
   278  	return dl.genesis
   279  }
   280  
   281  //CurrentFastBlock从规范链中检索当前磁头快速同步块。
   282  func (dl *downloadTester) CurrentFastBlock() *types.Block {
   283  	dl.lock.RLock()
   284  	defer dl.lock.RUnlock()
   285  
   286  	for i := len(dl.ownHashes) - 1; i >= 0; i-- {
   287  		if block := dl.ownBlocks[dl.ownHashes[i]]; block != nil {
   288  			return block
   289  		}
   290  	}
   291  	return dl.genesis
   292  }
   293  
   294  //fastsynccommithead手动将头块设置为给定哈希。
   295  func (dl *downloadTester) FastSyncCommitHead(hash common.Hash) error {
   296  //现在只检查状态trie是否正确。
   297  	if block := dl.GetBlockByHash(hash); block != nil {
   298  		_, err := trie.NewSecure(block.Root(), trie.NewDatabase(dl.stateDb), 0)
   299  		return err
   300  	}
   301  	return fmt.Errorf("non existent block: %x", hash[:4])
   302  }
   303  
   304  //gettd从规范链中检索块的总难度。
   305  func (dl *downloadTester) GetTd(hash common.Hash, number uint64) *big.Int {
   306  	dl.lock.RLock()
   307  	defer dl.lock.RUnlock()
   308  
   309  	return dl.ownChainTd[hash]
   310  }
   311  
   312  //InsertHeaderChain将新的一批头注入到模拟链中。
   313  func (dl *downloadTester) InsertHeaderChain(headers []*types.Header, checkFreq int) (int, error) {
   314  	dl.lock.Lock()
   315  	defer dl.lock.Unlock()
   316  
   317  //快速检查,因为区块链。插入头链不会插入任何内容以防出错。
   318  	if _, ok := dl.ownHeaders[headers[0].ParentHash]; !ok {
   319  		return 0, errors.New("unknown parent")
   320  	}
   321  	for i := 1; i < len(headers); i++ {
   322  		if headers[i].ParentHash != headers[i-1].Hash() {
   323  			return i, errors.New("unknown parent")
   324  		}
   325  	}
   326  //如果预检查通过,则执行完全插入
   327  	for i, header := range headers {
   328  		if _, ok := dl.ownHeaders[header.Hash()]; ok {
   329  			continue
   330  		}
   331  		if _, ok := dl.ownHeaders[header.ParentHash]; !ok {
   332  			return i, errors.New("unknown parent")
   333  		}
   334  		dl.ownHashes = append(dl.ownHashes, header.Hash())
   335  		dl.ownHeaders[header.Hash()] = header
   336  		dl.ownChainTd[header.Hash()] = new(big.Int).Add(dl.ownChainTd[header.ParentHash], header.Difficulty)
   337  	}
   338  	return len(headers), nil
   339  }
   340  
   341  //insertchain向模拟链中注入一批新的块。
   342  func (dl *downloadTester) InsertChain(blocks types.Blocks) (int, error) {
   343  	dl.lock.Lock()
   344  	defer dl.lock.Unlock()
   345  
   346  	for i, block := range blocks {
   347  		if parent, ok := dl.ownBlocks[block.ParentHash()]; !ok {
   348  			return i, errors.New("unknown parent")
   349  		} else if _, err := dl.stateDb.Get(parent.Root().Bytes()); err != nil {
   350  			return i, fmt.Errorf("unknown parent state %x: %v", parent.Root(), err)
   351  		}
   352  		if _, ok := dl.ownHeaders[block.Hash()]; !ok {
   353  			dl.ownHashes = append(dl.ownHashes, block.Hash())
   354  			dl.ownHeaders[block.Hash()] = block.Header()
   355  		}
   356  		dl.ownBlocks[block.Hash()] = block
   357  		dl.stateDb.Put(block.Root().Bytes(), []byte{0x00})
   358  		dl.ownChainTd[block.Hash()] = new(big.Int).Add(dl.ownChainTd[block.ParentHash()], block.Difficulty())
   359  	}
   360  	return len(blocks), nil
   361  }
   362  
   363  //InsertReceiptChain将新的一批收据注入到模拟链中。
   364  func (dl *downloadTester) InsertReceiptChain(blocks types.Blocks, receipts []types.Receipts) (int, error) {
   365  	dl.lock.Lock()
   366  	defer dl.lock.Unlock()
   367  
   368  	for i := 0; i < len(blocks) && i < len(receipts); i++ {
   369  		if _, ok := dl.ownHeaders[blocks[i].Hash()]; !ok {
   370  			return i, errors.New("unknown owner")
   371  		}
   372  		if _, ok := dl.ownBlocks[blocks[i].ParentHash()]; !ok {
   373  			return i, errors.New("unknown parent")
   374  		}
   375  		dl.ownBlocks[blocks[i].Hash()] = blocks[i]
   376  		dl.ownReceipts[blocks[i].Hash()] = receipts[i]
   377  	}
   378  	return len(blocks), nil
   379  }
   380  
   381  //回滚从链中删除一些最近添加的元素。
   382  func (dl *downloadTester) Rollback(hashes []common.Hash) {
   383  	dl.lock.Lock()
   384  	defer dl.lock.Unlock()
   385  
   386  	for i := len(hashes) - 1; i >= 0; i-- {
   387  		if dl.ownHashes[len(dl.ownHashes)-1] == hashes[i] {
   388  			dl.ownHashes = dl.ownHashes[:len(dl.ownHashes)-1]
   389  		}
   390  		delete(dl.ownChainTd, hashes[i])
   391  		delete(dl.ownHeaders, hashes[i])
   392  		delete(dl.ownReceipts, hashes[i])
   393  		delete(dl.ownBlocks, hashes[i])
   394  	}
   395  }
   396  
   397  //newpeer向下载程序注册一个新的块下载源。
   398  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 {
   399  	return dl.newSlowPeer(id, version, hashes, headers, blocks, receipts, 0)
   400  }
   401  
   402  //NexStand将一个新的块下载源注册到下载器中
   403  //处理发送给它的网络包时的特定延迟时间,模拟
   404  //网络IO可能较慢。
   405  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 {
   406  	dl.lock.Lock()
   407  	defer dl.lock.Unlock()
   408  
   409  	var err = dl.downloader.RegisterPeer(id, version, &downloadTesterPeer{dl: dl, id: id, delay: delay})
   410  	if err == nil {
   411  //将拥有的哈希、头和块分配给对等端(深度复制)
   412  		dl.peerHashes[id] = make([]common.Hash, len(hashes))
   413  		copy(dl.peerHashes[id], hashes)
   414  
   415  		dl.peerHeaders[id] = make(map[common.Hash]*types.Header)
   416  		dl.peerBlocks[id] = make(map[common.Hash]*types.Block)
   417  		dl.peerReceipts[id] = make(map[common.Hash]types.Receipts)
   418  		dl.peerChainTds[id] = make(map[common.Hash]*big.Int)
   419  		dl.peerMissingStates[id] = make(map[common.Hash]bool)
   420  
   421  		genesis := hashes[len(hashes)-1]
   422  		if header := headers[genesis]; header != nil {
   423  			dl.peerHeaders[id][genesis] = header
   424  			dl.peerChainTds[id][genesis] = header.Difficulty
   425  		}
   426  		if block := blocks[genesis]; block != nil {
   427  			dl.peerBlocks[id][genesis] = block
   428  			dl.peerChainTds[id][genesis] = block.Difficulty()
   429  		}
   430  
   431  		for i := len(hashes) - 2; i >= 0; i-- {
   432  			hash := hashes[i]
   433  
   434  			if header, ok := headers[hash]; ok {
   435  				dl.peerHeaders[id][hash] = header
   436  				if _, ok := dl.peerHeaders[id][header.ParentHash]; ok {
   437  					dl.peerChainTds[id][hash] = new(big.Int).Add(header.Difficulty, dl.peerChainTds[id][header.ParentHash])
   438  				}
   439  			}
   440  			if block, ok := blocks[hash]; ok {
   441  				dl.peerBlocks[id][hash] = block
   442  				if _, ok := dl.peerBlocks[id][block.ParentHash()]; ok {
   443  					dl.peerChainTds[id][hash] = new(big.Int).Add(block.Difficulty(), dl.peerChainTds[id][block.ParentHash()])
   444  				}
   445  			}
   446  			if receipt, ok := receipts[hash]; ok {
   447  				dl.peerReceipts[id][hash] = receipt
   448  			}
   449  		}
   450  	}
   451  	return err
   452  }
   453  
   454  //DropPeer模拟从连接池中删除硬对等。
   455  func (dl *downloadTester) dropPeer(id string) {
   456  	dl.lock.Lock()
   457  	defer dl.lock.Unlock()
   458  
   459  	delete(dl.peerHashes, id)
   460  	delete(dl.peerHeaders, id)
   461  	delete(dl.peerBlocks, id)
   462  	delete(dl.peerChainTds, id)
   463  
   464  	dl.downloader.UnregisterPeer(id)
   465  }
   466  
   467  type downloadTesterPeer struct {
   468  	dl    *downloadTester
   469  	id    string
   470  	delay time.Duration
   471  	lock  sync.RWMutex
   472  }
   473  
   474  //setdelay是网络延迟值的线程安全设置器。
   475  func (dlp *downloadTesterPeer) setDelay(delay time.Duration) {
   476  	dlp.lock.Lock()
   477  	defer dlp.lock.Unlock()
   478  
   479  	dlp.delay = delay
   480  }
   481  
   482  //waitdelay是一种线程安全的方式,可以在配置的时间内睡眠。
   483  func (dlp *downloadTesterPeer) waitDelay() {
   484  	dlp.lock.RLock()
   485  	delay := dlp.delay
   486  	dlp.lock.RUnlock()
   487  
   488  	time.Sleep(delay)
   489  }
   490  
   491  //head构造一个函数来检索对等端的当前head哈希
   492  //以及全部的困难。
   493  func (dlp *downloadTesterPeer) Head() (common.Hash, *big.Int) {
   494  	dlp.dl.lock.RLock()
   495  	defer dlp.dl.lock.RUnlock()
   496  
   497  	return dlp.dl.peerHashes[dlp.id][0], nil
   498  }
   499  
   500  //RequestHeadersByHash基于哈希构造GetBlockHeaders函数
   501  //源站;与下载测试仪中的特定对等点关联。归还的人
   502  //函数可用于从特定的对等端检索成批的头。
   503  func (dlp *downloadTesterPeer) RequestHeadersByHash(origin common.Hash, amount int, skip int, reverse bool) error {
   504  //查找哈希的规范编号
   505  	dlp.dl.lock.RLock()
   506  	number := uint64(0)
   507  	for num, hash := range dlp.dl.peerHashes[dlp.id] {
   508  		if hash == origin {
   509  			number = uint64(len(dlp.dl.peerHashes[dlp.id]) - num - 1)
   510  			break
   511  		}
   512  	}
   513  	dlp.dl.lock.RUnlock()
   514  
   515  //使用绝对头获取器来满足查询
   516  	return dlp.RequestHeadersByNumber(number, amount, skip, reverse)
   517  }
   518  
   519  //RequestHeadersByNumber基于编号的
   520  //源站;与下载测试仪中的特定对等点关联。归还的人
   521  //函数可用于从特定的对等端检索成批的头。
   522  func (dlp *downloadTesterPeer) RequestHeadersByNumber(origin uint64, amount int, skip int, reverse bool) error {
   523  	dlp.waitDelay()
   524  
   525  	dlp.dl.lock.RLock()
   526  	defer dlp.dl.lock.RUnlock()
   527  
   528  //收集下一批报头
   529  	hashes := dlp.dl.peerHashes[dlp.id]
   530  	headers := dlp.dl.peerHeaders[dlp.id]
   531  	result := make([]*types.Header, 0, amount)
   532  	for i := 0; i < amount && len(hashes)-int(origin)-1-i*(skip+1) >= 0; i++ {
   533  		if header, ok := headers[hashes[len(hashes)-int(origin)-1-i*(skip+1)]]; ok {
   534  			result = append(result, header)
   535  		}
   536  	}
   537  //延迟交付一点以允许攻击展开
   538  	go func() {
   539  		time.Sleep(time.Millisecond)
   540  		dlp.dl.downloader.DeliverHeaders(dlp.id, result)
   541  	}()
   542  	return nil
   543  }
   544  
   545  //RequestBodies构造与特定
   546  //在下载测试仪中查找。返回的函数可用于检索
   547  //来自特定请求对等端的一批块体。
   548  func (dlp *downloadTesterPeer) RequestBodies(hashes []common.Hash) error {
   549  	dlp.waitDelay()
   550  
   551  	dlp.dl.lock.RLock()
   552  	defer dlp.dl.lock.RUnlock()
   553  
   554  	blocks := dlp.dl.peerBlocks[dlp.id]
   555  
   556  	transactions := make([][]*types.Transaction, 0, len(hashes))
   557  	uncles := make([][]*types.Header, 0, len(hashes))
   558  
   559  	for _, hash := range hashes {
   560  		if block, ok := blocks[hash]; ok {
   561  			transactions = append(transactions, block.Transactions())
   562  			uncles = append(uncles, block.Uncles())
   563  		}
   564  	}
   565  	go dlp.dl.downloader.DeliverBodies(dlp.id, transactions, uncles)
   566  
   567  	return nil
   568  }
   569  
   570  //RequestReceipts构造与特定
   571  //在下载测试仪中查找。返回的函数可用于检索
   572  //来自特定请求对等方的批量块接收。
   573  func (dlp *downloadTesterPeer) RequestReceipts(hashes []common.Hash) error {
   574  	dlp.waitDelay()
   575  
   576  	dlp.dl.lock.RLock()
   577  	defer dlp.dl.lock.RUnlock()
   578  
   579  	receipts := dlp.dl.peerReceipts[dlp.id]
   580  
   581  	results := make([][]*types.Receipt, 0, len(hashes))
   582  	for _, hash := range hashes {
   583  		if receipt, ok := receipts[hash]; ok {
   584  			results = append(results, receipt)
   585  		}
   586  	}
   587  	go dlp.dl.downloader.DeliverReceipts(dlp.id, results)
   588  
   589  	return nil
   590  }
   591  
   592  //RequestNodeData构造与特定
   593  //在下载测试仪中查找。返回的函数可用于检索
   594  //来自特定请求对等端的节点状态数据批。
   595  func (dlp *downloadTesterPeer) RequestNodeData(hashes []common.Hash) error {
   596  	dlp.waitDelay()
   597  
   598  	dlp.dl.lock.RLock()
   599  	defer dlp.dl.lock.RUnlock()
   600  
   601  	results := make([][]byte, 0, len(hashes))
   602  	for _, hash := range hashes {
   603  		if data, err := dlp.dl.peerDb.Get(hash.Bytes()); err == nil {
   604  			if !dlp.dl.peerMissingStates[dlp.id][hash] {
   605  				results = append(results, data)
   606  			}
   607  		}
   608  	}
   609  	go dlp.dl.downloader.DeliverNodeData(dlp.id, results)
   610  
   611  	return nil
   612  }
   613  
   614  //AssertownChain检查本地链是否包含正确数量的项
   615  //各种链条组件。
   616  func assertOwnChain(t *testing.T, tester *downloadTester, length int) {
   617  	assertOwnForkedChain(t, tester, 1, []int{length})
   618  }
   619  
   620  //AssertOwnMarkedChain检查本地分叉链是否包含正确的
   621  //各种链组件的项数。
   622  func assertOwnForkedChain(t *testing.T, tester *downloadTester, common int, lengths []int) {
   623  //初始化第一个分叉的计数器
   624  	headers, blocks, receipts := lengths[0], lengths[0], lengths[0]-fsMinFullBlocks
   625  
   626  	if receipts < 0 {
   627  		receipts = 1
   628  	}
   629  //更新每个后续分叉的计数器
   630  	for _, length := range lengths[1:] {
   631  		headers += length - common
   632  		blocks += length - common
   633  		receipts += length - common - fsMinFullBlocks
   634  	}
   635  	switch tester.downloader.mode {
   636  	case FullSync:
   637  		receipts = 1
   638  	case LightSync:
   639  		blocks, receipts = 1, 1
   640  	}
   641  	if hs := len(tester.ownHeaders); hs != headers {
   642  		t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, headers)
   643  	}
   644  	if bs := len(tester.ownBlocks); bs != blocks {
   645  		t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, blocks)
   646  	}
   647  	if rs := len(tester.ownReceipts); rs != receipts {
   648  		t.Fatalf("synchronised receipts mismatch: have %v, want %v", rs, receipts)
   649  	}
   650  //Verify the state trie too for fast syncs
   651   /*f tester.downloader.mode==fastsync_
   652    透视:=uint64(0)
   653    var索引int
   654    如果pivot:=int(tester.downloader.queue.fastsyncpivot);pivot<common_
   655     索引=枢轴
   656    }否则{
   657     index=len(tester.ownhahes)-长度[len(lengs)-1]+int(tester.downloader.queue.fastsyncpivot)
   658    }
   659    如果索引>0 {
   660     如果statedb,则错误:=state.new(tester.ownheaders[tester.ownhahes[index]].root,state.newdatabase(trie.newdatabase(tester.statedb)));statedb==nil err!= nIL{
   661      T.FATALF(“状态重建失败:%V”,Err)
   662     }
   663    }
   664   */
   665  
   666  }
   667  
   668  //测试针对规范链的简单同步是否正常工作。
   669  //在此测试中,公共祖先查找应该是短路的,不需要
   670  //二进制搜索。
   671  func TestCanonicalSynchronisation62(t *testing.T)      { testCanonicalSynchronisation(t, 62, FullSync) }
   672  func TestCanonicalSynchronisation63Full(t *testing.T)  { testCanonicalSynchronisation(t, 63, FullSync) }
   673  func TestCanonicalSynchronisation63Fast(t *testing.T)  { testCanonicalSynchronisation(t, 63, FastSync) }
   674  func TestCanonicalSynchronisation64Full(t *testing.T)  { testCanonicalSynchronisation(t, 64, FullSync) }
   675  func TestCanonicalSynchronisation64Fast(t *testing.T)  { testCanonicalSynchronisation(t, 64, FastSync) }
   676  func TestCanonicalSynchronisation64Light(t *testing.T) { testCanonicalSynchronisation(t, 64, LightSync) }
   677  
   678  func testCanonicalSynchronisation(t *testing.T, protocol int, mode SyncMode) {
   679  	t.Parallel()
   680  
   681  	tester := newTester()
   682  	defer tester.terminate()
   683  
   684  //创建一个足够小的区块链来下载
   685  	targetBlocks := blockCacheItems - 15
   686  	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
   687  
   688  	tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
   689  
   690  //与对等机同步并确保检索到所有相关数据
   691  	if err := tester.sync("peer", nil, mode); err != nil {
   692  		t.Fatalf("failed to synchronise blocks: %v", err)
   693  	}
   694  	assertOwnChain(t, tester, targetBlocks+1)
   695  }
   696  
   697  //测试如果下载了大量块,则会阻止
   698  //直到检索到缓存块。
   699  func TestThrottling62(t *testing.T)     { testThrottling(t, 62, FullSync) }
   700  func TestThrottling63Full(t *testing.T) { testThrottling(t, 63, FullSync) }
   701  func TestThrottling63Fast(t *testing.T) { testThrottling(t, 63, FastSync) }
   702  func TestThrottling64Full(t *testing.T) { testThrottling(t, 64, FullSync) }
   703  func TestThrottling64Fast(t *testing.T) { testThrottling(t, 64, FastSync) }
   704  
   705  func testThrottling(t *testing.T, protocol int, mode SyncMode) {
   706  	t.Parallel()
   707  	tester := newTester()
   708  	defer tester.terminate()
   709  
   710  //创建要下载的长区块链和测试仪
   711  	targetBlocks := 8 * blockCacheItems
   712  	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
   713  
   714  	tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
   715  
   716  //包裹导入器以允许步进
   717  	blocked, proceed := uint32(0), make(chan struct{})
   718  	tester.downloader.chainInsertHook = func(results []*fetchResult) {
   719  		atomic.StoreUint32(&blocked, uint32(len(results)))
   720  		<-proceed
   721  	}
   722  //同时启动同步
   723  	errc := make(chan error)
   724  	go func() {
   725  		errc <- tester.sync("peer", nil, mode)
   726  	}()
   727  //迭代获取一些块,始终检查检索计数
   728  	for {
   729  //同步检查检索计数(!这个丑陋街区的原因)
   730  		tester.lock.RLock()
   731  		retrieved := len(tester.ownBlocks)
   732  		tester.lock.RUnlock()
   733  		if retrieved >= targetBlocks+1 {
   734  			break
   735  		}
   736  //等一下,让同步自行调节。
   737  		var cached, frozen int
   738  		for start := time.Now(); time.Since(start) < 3*time.Second; {
   739  			time.Sleep(25 * time.Millisecond)
   740  
   741  			tester.lock.Lock()
   742  			tester.downloader.queue.lock.Lock()
   743  			cached = len(tester.downloader.queue.blockDonePool)
   744  			if mode == FastSync {
   745  				if receipts := len(tester.downloader.queue.receiptDonePool); receipts < cached {
   746  //if tester.downloader.queue.resultcache[receipts].header.number.uint64()<tester.downloader.queue.fastsyncpivot_
   747  					cached = receipts
   748  //}
   749  				}
   750  			}
   751  			frozen = int(atomic.LoadUint32(&blocked))
   752  			retrieved = len(tester.ownBlocks)
   753  			tester.downloader.queue.lock.Unlock()
   754  			tester.lock.Unlock()
   755  
   756  			if cached == blockCacheItems || retrieved+cached+frozen == targetBlocks+1 {
   757  				break
   758  			}
   759  		}
   760  //确保我们填满了缓存,然后耗尽它
   761  time.Sleep(25 * time.Millisecond) //给它一个搞砸的机会
   762  
   763  		tester.lock.RLock()
   764  		retrieved = len(tester.ownBlocks)
   765  		tester.lock.RUnlock()
   766  		if cached != blockCacheItems && retrieved+cached+frozen != targetBlocks+1 {
   767  			t.Fatalf("block count mismatch: have %v, want %v (owned %v, blocked %v, target %v)", cached, blockCacheItems, retrieved, frozen, targetBlocks+1)
   768  		}
   769  //允许导入被阻止的块
   770  		if atomic.LoadUint32(&blocked) > 0 {
   771  			atomic.StoreUint32(&blocked, uint32(0))
   772  			proceed <- struct{}{}
   773  		}
   774  	}
   775  //检查我们没有拖过多的街区
   776  	assertOwnChain(t, tester, targetBlocks+1)
   777  	if err := <-errc; err != nil {
   778  		t.Fatalf("block synchronization failed: %v", err)
   779  	}
   780  }
   781  
   782  //测试针对分叉链的简单同步是否正确工作。在
   783  //此测试公共祖先查找应*不*短路,并且
   784  //应执行二进制搜索。
   785  func TestForkedSync62(t *testing.T)      { testForkedSync(t, 62, FullSync) }
   786  func TestForkedSync63Full(t *testing.T)  { testForkedSync(t, 63, FullSync) }
   787  func TestForkedSync63Fast(t *testing.T)  { testForkedSync(t, 63, FastSync) }
   788  func TestForkedSync64Full(t *testing.T)  { testForkedSync(t, 64, FullSync) }
   789  func TestForkedSync64Fast(t *testing.T)  { testForkedSync(t, 64, FastSync) }
   790  func TestForkedSync64Light(t *testing.T) { testForkedSync(t, 64, LightSync) }
   791  
   792  func testForkedSync(t *testing.T, protocol int, mode SyncMode) {
   793  	t.Parallel()
   794  
   795  	tester := newTester()
   796  	defer tester.terminate()
   797  
   798  //创建足够长的分叉链
   799  	common, fork := MaxHashFetch, 2*MaxHashFetch
   800  	hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, true)
   801  
   802  	tester.newPeer("fork A", protocol, hashesA, headersA, blocksA, receiptsA)
   803  	tester.newPeer("fork B", protocol, hashesB, headersB, blocksB, receiptsB)
   804  
   805  //与对等机同步并确保检索到所有块
   806  	if err := tester.sync("fork A", nil, mode); err != nil {
   807  		t.Fatalf("failed to synchronise blocks: %v", err)
   808  	}
   809  	assertOwnChain(t, tester, common+fork+1)
   810  
   811  //与第二个对等机同步,并确保拨叉也被拉动
   812  	if err := tester.sync("fork B", nil, mode); err != nil {
   813  		t.Fatalf("failed to synchronise blocks: %v", err)
   814  	}
   815  	assertOwnForkedChain(t, tester, common+1, []int{common + fork + 1, common + fork + 1})
   816  }
   817  
   818  //与较短但较重的叉子同步的测试
   819  //正确无误,不会掉落。
   820  func TestHeavyForkedSync62(t *testing.T)      { testHeavyForkedSync(t, 62, FullSync) }
   821  func TestHeavyForkedSync63Full(t *testing.T)  { testHeavyForkedSync(t, 63, FullSync) }
   822  func TestHeavyForkedSync63Fast(t *testing.T)  { testHeavyForkedSync(t, 63, FastSync) }
   823  func TestHeavyForkedSync64Full(t *testing.T)  { testHeavyForkedSync(t, 64, FullSync) }
   824  func TestHeavyForkedSync64Fast(t *testing.T)  { testHeavyForkedSync(t, 64, FastSync) }
   825  func TestHeavyForkedSync64Light(t *testing.T) { testHeavyForkedSync(t, 64, LightSync) }
   826  
   827  func testHeavyForkedSync(t *testing.T, protocol int, mode SyncMode) {
   828  	t.Parallel()
   829  
   830  	tester := newTester()
   831  	defer tester.terminate()
   832  
   833  //创建足够长的分叉链
   834  	common, fork := MaxHashFetch, 4*MaxHashFetch
   835  	hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, false)
   836  
   837  	tester.newPeer("light", protocol, hashesA, headersA, blocksA, receiptsA)
   838  	tester.newPeer("heavy", protocol, hashesB[fork/2:], headersB, blocksB, receiptsB)
   839  
   840  //与对等机同步并确保检索到所有块
   841  	if err := tester.sync("light", nil, mode); err != nil {
   842  		t.Fatalf("failed to synchronise blocks: %v", err)
   843  	}
   844  	assertOwnChain(t, tester, common+fork+1)
   845  
   846  //与第二个对等机同步,并确保拨叉也被拉动
   847  	if err := tester.sync("heavy", nil, mode); err != nil {
   848  		t.Fatalf("failed to synchronise blocks: %v", err)
   849  	}
   850  	assertOwnForkedChain(t, tester, common+1, []int{common + fork + 1, common + fork/2 + 1})
   851  }
   852  
   853  //测试链叉是否包含在电流的某个间隔内
   854  //链头,确保恶意同行不会通过喂养浪费资源
   855  //死链长。
   856  func TestBoundedForkedSync62(t *testing.T)      { testBoundedForkedSync(t, 62, FullSync) }
   857  func TestBoundedForkedSync63Full(t *testing.T)  { testBoundedForkedSync(t, 63, FullSync) }
   858  func TestBoundedForkedSync63Fast(t *testing.T)  { testBoundedForkedSync(t, 63, FastSync) }
   859  func TestBoundedForkedSync64Full(t *testing.T)  { testBoundedForkedSync(t, 64, FullSync) }
   860  func TestBoundedForkedSync64Fast(t *testing.T)  { testBoundedForkedSync(t, 64, FastSync) }
   861  func TestBoundedForkedSync64Light(t *testing.T) { testBoundedForkedSync(t, 64, LightSync) }
   862  
   863  func testBoundedForkedSync(t *testing.T, protocol int, mode SyncMode) {
   864  	t.Parallel()
   865  
   866  	tester := newTester()
   867  	defer tester.terminate()
   868  
   869  //创建足够长的分叉链
   870  	common, fork := 13, int(MaxForkAncestry+17)
   871  	hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, true)
   872  
   873  	tester.newPeer("original", protocol, hashesA, headersA, blocksA, receiptsA)
   874  	tester.newPeer("rewriter", protocol, hashesB, headersB, blocksB, receiptsB)
   875  
   876  //与对等机同步并确保检索到所有块
   877  	if err := tester.sync("original", nil, mode); err != nil {
   878  		t.Fatalf("failed to synchronise blocks: %v", err)
   879  	}
   880  	assertOwnChain(t, tester, common+fork+1)
   881  
   882  //与第二个对等机同步,并确保叉被拒绝太旧
   883  	if err := tester.sync("rewriter", nil, mode); err != errInvalidAncestor {
   884  		t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor)
   885  	}
   886  }
   887  
   888  //测试链叉是否包含在电流的某个间隔内
   889  //链头也适用于短而重的叉子。这些有点特别,因为它们
   890  //采用不同的祖先查找路径。
   891  func TestBoundedHeavyForkedSync62(t *testing.T)      { testBoundedHeavyForkedSync(t, 62, FullSync) }
   892  func TestBoundedHeavyForkedSync63Full(t *testing.T)  { testBoundedHeavyForkedSync(t, 63, FullSync) }
   893  func TestBoundedHeavyForkedSync63Fast(t *testing.T)  { testBoundedHeavyForkedSync(t, 63, FastSync) }
   894  func TestBoundedHeavyForkedSync64Full(t *testing.T)  { testBoundedHeavyForkedSync(t, 64, FullSync) }
   895  func TestBoundedHeavyForkedSync64Fast(t *testing.T)  { testBoundedHeavyForkedSync(t, 64, FastSync) }
   896  func TestBoundedHeavyForkedSync64Light(t *testing.T) { testBoundedHeavyForkedSync(t, 64, LightSync) }
   897  
   898  func testBoundedHeavyForkedSync(t *testing.T, protocol int, mode SyncMode) {
   899  	t.Parallel()
   900  
   901  	tester := newTester()
   902  	defer tester.terminate()
   903  
   904  //创建足够长的分叉链
   905  	common, fork := 13, int(MaxForkAncestry+17)
   906  	hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, false)
   907  
   908  	tester.newPeer("original", protocol, hashesA, headersA, blocksA, receiptsA)
   909  tester.newPeer("heavy-rewriter", protocol, hashesB[MaxForkAncestry-17:], headersB, blocksB, receiptsB) //把叉子根在祖先限制以下
   910  
   911  //与对等机同步并确保检索到所有块
   912  	if err := tester.sync("original", nil, mode); err != nil {
   913  		t.Fatalf("failed to synchronise blocks: %v", err)
   914  	}
   915  	assertOwnChain(t, tester, common+fork+1)
   916  
   917  //与第二个对等机同步,并确保叉被拒绝太旧
   918  	if err := tester.sync("heavy-rewriter", nil, mode); err != errInvalidAncestor {
   919  		t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor)
   920  	}
   921  }
   922  
   923  //测试非活动下载程序是否不接受传入的块头,以及
   924  //身体。
   925  func TestInactiveDownloader62(t *testing.T) {
   926  	t.Parallel()
   927  
   928  	tester := newTester()
   929  	defer tester.terminate()
   930  
   931  //检查是否不接受块头和块体
   932  	if err := tester.downloader.DeliverHeaders("bad peer", []*types.Header{}); err != errNoSyncActive {
   933  		t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
   934  	}
   935  	if err := tester.downloader.DeliverBodies("bad peer", [][]*types.Transaction{}, [][]*types.Header{}); err != errNoSyncActive {
   936  		t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
   937  	}
   938  }
   939  
   940  //测试非活动下载程序是否不接受传入的块头,
   941  //机构和收据。
   942  func TestInactiveDownloader63(t *testing.T) {
   943  	t.Parallel()
   944  
   945  	tester := newTester()
   946  	defer tester.terminate()
   947  
   948  //检查是否不接受块头和块体
   949  	if err := tester.downloader.DeliverHeaders("bad peer", []*types.Header{}); err != errNoSyncActive {
   950  		t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
   951  	}
   952  	if err := tester.downloader.DeliverBodies("bad peer", [][]*types.Transaction{}, [][]*types.Header{}); err != errNoSyncActive {
   953  		t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
   954  	}
   955  	if err := tester.downloader.DeliverReceipts("bad peer", [][]*types.Receipt{}); err != errNoSyncActive {
   956  		t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
   957  	}
   958  }
   959  
   960  //测试取消的下载是否会清除所有以前累积的状态。
   961  func TestCancel62(t *testing.T)      { testCancel(t, 62, FullSync) }
   962  func TestCancel63Full(t *testing.T)  { testCancel(t, 63, FullSync) }
   963  func TestCancel63Fast(t *testing.T)  { testCancel(t, 63, FastSync) }
   964  func TestCancel64Full(t *testing.T)  { testCancel(t, 64, FullSync) }
   965  func TestCancel64Fast(t *testing.T)  { testCancel(t, 64, FastSync) }
   966  func TestCancel64Light(t *testing.T) { testCancel(t, 64, LightSync) }
   967  
   968  func testCancel(t *testing.T, protocol int, mode SyncMode) {
   969  	t.Parallel()
   970  
   971  	tester := newTester()
   972  	defer tester.terminate()
   973  
   974  //创建一个足够小的区块链来下载和测试
   975  	targetBlocks := blockCacheItems - 15
   976  	if targetBlocks >= MaxHashFetch {
   977  		targetBlocks = MaxHashFetch - 15
   978  	}
   979  	if targetBlocks >= MaxHeaderFetch {
   980  		targetBlocks = MaxHeaderFetch - 15
   981  	}
   982  	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
   983  
   984  	tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
   985  
   986  //确保取消与原始下载程序一起工作
   987  	tester.downloader.Cancel()
   988  	if !tester.downloader.queue.Idle() {
   989  		t.Errorf("download queue not idle")
   990  	}
   991  //与同级同步,但随后取消
   992  	if err := tester.sync("peer", nil, mode); err != nil {
   993  		t.Fatalf("failed to synchronise blocks: %v", err)
   994  	}
   995  	tester.downloader.Cancel()
   996  	if !tester.downloader.queue.Idle() {
   997  		t.Errorf("download queue not idle")
   998  	}
   999  }
  1000  
  1001  //多个对等机同步按预期工作的测试(多线程健全性测试)。
  1002  func TestMultiSynchronisation62(t *testing.T)      { testMultiSynchronisation(t, 62, FullSync) }
  1003  func TestMultiSynchronisation63Full(t *testing.T)  { testMultiSynchronisation(t, 63, FullSync) }
  1004  func TestMultiSynchronisation63Fast(t *testing.T)  { testMultiSynchronisation(t, 63, FastSync) }
  1005  func TestMultiSynchronisation64Full(t *testing.T)  { testMultiSynchronisation(t, 64, FullSync) }
  1006  func TestMultiSynchronisation64Fast(t *testing.T)  { testMultiSynchronisation(t, 64, FastSync) }
  1007  func TestMultiSynchronisation64Light(t *testing.T) { testMultiSynchronisation(t, 64, LightSync) }
  1008  
  1009  func testMultiSynchronisation(t *testing.T, protocol int, mode SyncMode) {
  1010  	t.Parallel()
  1011  
  1012  	tester := newTester()
  1013  	defer tester.terminate()
  1014  
  1015  //用链的不同部分创建不同的对等点
  1016  	targetPeers := 8
  1017  	targetBlocks := targetPeers*blockCacheItems - 15
  1018  	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1019  
  1020  	for i := 0; i < targetPeers; i++ {
  1021  		id := fmt.Sprintf("peer #%d", i)
  1022  		tester.newPeer(id, protocol, hashes[i*blockCacheItems:], headers, blocks, receipts)
  1023  	}
  1024  	if err := tester.sync("peer #0", nil, mode); err != nil {
  1025  		t.Fatalf("failed to synchronise blocks: %v", err)
  1026  	}
  1027  	assertOwnChain(t, tester, targetBlocks+1)
  1028  }
  1029  
  1030  //在多版本协议环境中同步运行良好的测试
  1031  //不会对网络中的其他节点造成破坏。
  1032  func TestMultiProtoSynchronisation62(t *testing.T)      { testMultiProtoSync(t, 62, FullSync) }
  1033  func TestMultiProtoSynchronisation63Full(t *testing.T)  { testMultiProtoSync(t, 63, FullSync) }
  1034  func TestMultiProtoSynchronisation63Fast(t *testing.T)  { testMultiProtoSync(t, 63, FastSync) }
  1035  func TestMultiProtoSynchronisation64Full(t *testing.T)  { testMultiProtoSync(t, 64, FullSync) }
  1036  func TestMultiProtoSynchronisation64Fast(t *testing.T)  { testMultiProtoSync(t, 64, FastSync) }
  1037  func TestMultiProtoSynchronisation64Light(t *testing.T) { testMultiProtoSync(t, 64, LightSync) }
  1038  
  1039  func testMultiProtoSync(t *testing.T, protocol int, mode SyncMode) {
  1040  	t.Parallel()
  1041  
  1042  	tester := newTester()
  1043  	defer tester.terminate()
  1044  
  1045  //创建一个足够小的区块链来下载
  1046  	targetBlocks := blockCacheItems - 15
  1047  	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1048  
  1049  //创建每种类型的对等点
  1050  	tester.newPeer("peer 62", 62, hashes, headers, blocks, nil)
  1051  	tester.newPeer("peer 63", 63, hashes, headers, blocks, receipts)
  1052  	tester.newPeer("peer 64", 64, hashes, headers, blocks, receipts)
  1053  
  1054  //与请求的对等机同步,并确保检索到所有块
  1055  	if err := tester.sync(fmt.Sprintf("peer %d", protocol), nil, mode); err != nil {
  1056  		t.Fatalf("failed to synchronise blocks: %v", err)
  1057  	}
  1058  	assertOwnChain(t, tester, targetBlocks+1)
  1059  
  1060  //检查是否没有同伴掉线
  1061  	for _, version := range []int{62, 63, 64} {
  1062  		peer := fmt.Sprintf("peer %d", version)
  1063  		if _, ok := tester.peerHashes[peer]; !ok {
  1064  			t.Errorf("%s dropped", peer)
  1065  		}
  1066  	}
  1067  }
  1068  
  1069  //测试如果一个块为空(例如,仅限头),则不应执行任何Body请求
  1070  //制作,而不是集管本身组装成一个整体。
  1071  func TestEmptyShortCircuit62(t *testing.T)      { testEmptyShortCircuit(t, 62, FullSync) }
  1072  func TestEmptyShortCircuit63Full(t *testing.T)  { testEmptyShortCircuit(t, 63, FullSync) }
  1073  func TestEmptyShortCircuit63Fast(t *testing.T)  { testEmptyShortCircuit(t, 63, FastSync) }
  1074  func TestEmptyShortCircuit64Full(t *testing.T)  { testEmptyShortCircuit(t, 64, FullSync) }
  1075  func TestEmptyShortCircuit64Fast(t *testing.T)  { testEmptyShortCircuit(t, 64, FastSync) }
  1076  func TestEmptyShortCircuit64Light(t *testing.T) { testEmptyShortCircuit(t, 64, LightSync) }
  1077  
  1078  func testEmptyShortCircuit(t *testing.T, protocol int, mode SyncMode) {
  1079  	t.Parallel()
  1080  
  1081  	tester := newTester()
  1082  	defer tester.terminate()
  1083  
  1084  //创建要下载的区块链
  1085  	targetBlocks := 2*blockCacheItems - 15
  1086  	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1087  
  1088  	tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
  1089  
  1090  //向下载器发送信号,以发出Body请求
  1091  	bodiesHave, receiptsHave := int32(0), int32(0)
  1092  	tester.downloader.bodyFetchHook = func(headers []*types.Header) {
  1093  		atomic.AddInt32(&bodiesHave, int32(len(headers)))
  1094  	}
  1095  	tester.downloader.receiptFetchHook = func(headers []*types.Header) {
  1096  		atomic.AddInt32(&receiptsHave, int32(len(headers)))
  1097  	}
  1098  //与对等机同步并确保检索到所有块
  1099  	if err := tester.sync("peer", nil, mode); err != nil {
  1100  		t.Fatalf("failed to synchronise blocks: %v", err)
  1101  	}
  1102  	assertOwnChain(t, tester, targetBlocks+1)
  1103  
  1104  //验证应请求的块体数
  1105  	bodiesNeeded, receiptsNeeded := 0, 0
  1106  	for _, block := range blocks {
  1107  		if mode != LightSync && block != tester.genesis && (len(block.Transactions()) > 0 || len(block.Uncles()) > 0) {
  1108  			bodiesNeeded++
  1109  		}
  1110  	}
  1111  	for _, receipt := range receipts {
  1112  		if mode == FastSync && len(receipt) > 0 {
  1113  			receiptsNeeded++
  1114  		}
  1115  	}
  1116  	if int(bodiesHave) != bodiesNeeded {
  1117  		t.Errorf("body retrieval count mismatch: have %v, want %v", bodiesHave, bodiesNeeded)
  1118  	}
  1119  	if int(receiptsHave) != receiptsNeeded {
  1120  		t.Errorf("receipt retrieval count mismatch: have %v, want %v", receiptsHave, receiptsNeeded)
  1121  	}
  1122  }
  1123  
  1124  //测试头是否连续排队,以防止恶意节点
  1125  //通过喂入有间隙的收割台链条来安装下载器。
  1126  func TestMissingHeaderAttack62(t *testing.T)      { testMissingHeaderAttack(t, 62, FullSync) }
  1127  func TestMissingHeaderAttack63Full(t *testing.T)  { testMissingHeaderAttack(t, 63, FullSync) }
  1128  func TestMissingHeaderAttack63Fast(t *testing.T)  { testMissingHeaderAttack(t, 63, FastSync) }
  1129  func TestMissingHeaderAttack64Full(t *testing.T)  { testMissingHeaderAttack(t, 64, FullSync) }
  1130  func TestMissingHeaderAttack64Fast(t *testing.T)  { testMissingHeaderAttack(t, 64, FastSync) }
  1131  func TestMissingHeaderAttack64Light(t *testing.T) { testMissingHeaderAttack(t, 64, LightSync) }
  1132  
  1133  func testMissingHeaderAttack(t *testing.T, protocol int, mode SyncMode) {
  1134  	t.Parallel()
  1135  
  1136  	tester := newTester()
  1137  	defer tester.terminate()
  1138  
  1139  //创建一个足够小的区块链来下载
  1140  	targetBlocks := blockCacheItems - 15
  1141  	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1142  
  1143  //尝试与攻击者进行完全同步,以提供有间隙的头文件
  1144  	tester.newPeer("attack", protocol, hashes, headers, blocks, receipts)
  1145  	missing := targetBlocks / 2
  1146  	delete(tester.peerHeaders["attack"], hashes[missing])
  1147  
  1148  	if err := tester.sync("attack", nil, mode); err == nil {
  1149  		t.Fatalf("succeeded attacker synchronisation")
  1150  	}
  1151  //与有效的对等机同步并确保同步成功
  1152  	tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
  1153  	if err := tester.sync("valid", nil, mode); err != nil {
  1154  		t.Fatalf("failed to synchronise blocks: %v", err)
  1155  	}
  1156  	assertOwnChain(t, tester, targetBlocks+1)
  1157  }
  1158  
  1159  //测试如果请求的头被移动(即第一个头丢失),队列
  1160  //检测无效编号。
  1161  func TestShiftedHeaderAttack62(t *testing.T)      { testShiftedHeaderAttack(t, 62, FullSync) }
  1162  func TestShiftedHeaderAttack63Full(t *testing.T)  { testShiftedHeaderAttack(t, 63, FullSync) }
  1163  func TestShiftedHeaderAttack63Fast(t *testing.T)  { testShiftedHeaderAttack(t, 63, FastSync) }
  1164  func TestShiftedHeaderAttack64Full(t *testing.T)  { testShiftedHeaderAttack(t, 64, FullSync) }
  1165  func TestShiftedHeaderAttack64Fast(t *testing.T)  { testShiftedHeaderAttack(t, 64, FastSync) }
  1166  func TestShiftedHeaderAttack64Light(t *testing.T) { testShiftedHeaderAttack(t, 64, LightSync) }
  1167  
  1168  func testShiftedHeaderAttack(t *testing.T, protocol int, mode SyncMode) {
  1169  	t.Parallel()
  1170  
  1171  	tester := newTester()
  1172  	defer tester.terminate()
  1173  
  1174  //创建一个足够小的区块链来下载
  1175  	targetBlocks := blockCacheItems - 15
  1176  	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1177  
  1178  //尝试与攻击者进行完全同步以输入移位的头文件
  1179  	tester.newPeer("attack", protocol, hashes, headers, blocks, receipts)
  1180  	delete(tester.peerHeaders["attack"], hashes[len(hashes)-2])
  1181  	delete(tester.peerBlocks["attack"], hashes[len(hashes)-2])
  1182  	delete(tester.peerReceipts["attack"], hashes[len(hashes)-2])
  1183  
  1184  	if err := tester.sync("attack", nil, mode); err == nil {
  1185  		t.Fatalf("succeeded attacker synchronisation")
  1186  	}
  1187  //与有效的对等机同步并确保同步成功
  1188  	tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
  1189  	if err := tester.sync("valid", nil, mode); err != nil {
  1190  		t.Fatalf("failed to synchronise blocks: %v", err)
  1191  	}
  1192  	assertOwnChain(t, tester, targetBlocks+1)
  1193  }
  1194  
  1195  //测试在检测到无效的头时,将回滚最近的头
  1196  //对于各种故障情况。之后,尝试进行完全同步
  1197  //确保没有状态损坏。
  1198  func TestInvalidHeaderRollback63Fast(t *testing.T)  { testInvalidHeaderRollback(t, 63, FastSync) }
  1199  func TestInvalidHeaderRollback64Fast(t *testing.T)  { testInvalidHeaderRollback(t, 64, FastSync) }
  1200  func TestInvalidHeaderRollback64Light(t *testing.T) { testInvalidHeaderRollback(t, 64, LightSync) }
  1201  
  1202  func testInvalidHeaderRollback(t *testing.T, protocol int, mode SyncMode) {
  1203  	t.Parallel()
  1204  
  1205  	tester := newTester()
  1206  	defer tester.terminate()
  1207  
  1208  //创建一个足够小的区块链来下载
  1209  	targetBlocks := 3*fsHeaderSafetyNet + 256 + fsMinFullBlocks
  1210  	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1211  
  1212  //尝试与在快速同步阶段提供垃圾的攻击者同步。
  1213  //这将导致最后一个fsheadersafetynet头回滚。
  1214  	tester.newPeer("fast-attack", protocol, hashes, headers, blocks, receipts)
  1215  	missing := fsHeaderSafetyNet + MaxHeaderFetch + 1
  1216  	delete(tester.peerHeaders["fast-attack"], hashes[len(hashes)-missing])
  1217  
  1218  	if err := tester.sync("fast-attack", nil, mode); err == nil {
  1219  		t.Fatalf("succeeded fast attacker synchronisation")
  1220  	}
  1221  	if head := tester.CurrentHeader().Number.Int64(); int(head) > MaxHeaderFetch {
  1222  		t.Errorf("rollback head mismatch: have %v, want at most %v", head, MaxHeaderFetch)
  1223  	}
  1224  //尝试与在块导入阶段提供垃圾的攻击者同步。
  1225  //这将导致最后一个fsheadersafetynet头的数量
  1226  //回滚,同时将轴点还原为非块状态。
  1227  	tester.newPeer("block-attack", protocol, hashes, headers, blocks, receipts)
  1228  	missing = 3*fsHeaderSafetyNet + MaxHeaderFetch + 1
  1229  delete(tester.peerHeaders["fast-attack"], hashes[len(hashes)-missing]) //确保快速攻击者没有填写
  1230  	delete(tester.peerHeaders["block-attack"], hashes[len(hashes)-missing])
  1231  
  1232  	if err := tester.sync("block-attack", nil, mode); err == nil {
  1233  		t.Fatalf("succeeded block attacker synchronisation")
  1234  	}
  1235  	if head := tester.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
  1236  		t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
  1237  	}
  1238  	if mode == FastSync {
  1239  		if head := tester.CurrentBlock().NumberU64(); head != 0 {
  1240  			t.Errorf("fast sync pivot block #%d not rolled back", head)
  1241  		}
  1242  	}
  1243  //尝试与在
  1244  //快速同步轴点。这可能是让节点
  1245  //但已经导入了透视图块。
  1246  	tester.newPeer("withhold-attack", protocol, hashes, headers, blocks, receipts)
  1247  	missing = 3*fsHeaderSafetyNet + MaxHeaderFetch + 1
  1248  
  1249  	tester.downloader.syncInitHook = func(uint64, uint64) {
  1250  		for i := missing; i <= len(hashes); i++ {
  1251  			delete(tester.peerHeaders["withhold-attack"], hashes[len(hashes)-i])
  1252  		}
  1253  		tester.downloader.syncInitHook = nil
  1254  	}
  1255  
  1256  	if err := tester.sync("withhold-attack", nil, mode); err == nil {
  1257  		t.Fatalf("succeeded withholding attacker synchronisation")
  1258  	}
  1259  	if head := tester.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
  1260  		t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
  1261  	}
  1262  	if mode == FastSync {
  1263  		if head := tester.CurrentBlock().NumberU64(); head != 0 {
  1264  			t.Errorf("fast sync pivot block #%d not rolled back", head)
  1265  		}
  1266  	}
  1267  //与有效的对等机同步,并确保同步成功。自上次以来
  1268  //回滚还应禁用此进程的快速同步,请验证
  1269  //进行了全新的完全同步。注意,我们不能断言任何有关收据的内容
  1270  //因为我们不会清除它们的数据库,所以我们不能使用assertownchain。
  1271  	tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
  1272  	if err := tester.sync("valid", nil, mode); err != nil {
  1273  		t.Fatalf("failed to synchronise blocks: %v", err)
  1274  	}
  1275  	if hs := len(tester.ownHeaders); hs != len(headers) {
  1276  		t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, len(headers))
  1277  	}
  1278  	if mode != LightSync {
  1279  		if bs := len(tester.ownBlocks); bs != len(blocks) {
  1280  			t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, len(blocks))
  1281  		}
  1282  	}
  1283  }
  1284  
  1285  //测试一个发布高TD的同龄人是否能够阻止下载者
  1286  //之后不发送任何有用的哈希。
  1287  func TestHighTDStarvationAttack62(t *testing.T)      { testHighTDStarvationAttack(t, 62, FullSync) }
  1288  func TestHighTDStarvationAttack63Full(t *testing.T)  { testHighTDStarvationAttack(t, 63, FullSync) }
  1289  func TestHighTDStarvationAttack63Fast(t *testing.T)  { testHighTDStarvationAttack(t, 63, FastSync) }
  1290  func TestHighTDStarvationAttack64Full(t *testing.T)  { testHighTDStarvationAttack(t, 64, FullSync) }
  1291  func TestHighTDStarvationAttack64Fast(t *testing.T)  { testHighTDStarvationAttack(t, 64, FastSync) }
  1292  func TestHighTDStarvationAttack64Light(t *testing.T) { testHighTDStarvationAttack(t, 64, LightSync) }
  1293  
  1294  func testHighTDStarvationAttack(t *testing.T, protocol int, mode SyncMode) {
  1295  	t.Parallel()
  1296  
  1297  	tester := newTester()
  1298  	defer tester.terminate()
  1299  
  1300  	hashes, headers, blocks, receipts := tester.makeChain(0, 0, tester.genesis, nil, false)
  1301  	tester.newPeer("attack", protocol, []common.Hash{hashes[0]}, headers, blocks, receipts)
  1302  
  1303  	if err := tester.sync("attack", big.NewInt(1000000), mode); err != errStallingPeer {
  1304  		t.Fatalf("synchronisation error mismatch: have %v, want %v", err, errStallingPeer)
  1305  	}
  1306  }
  1307  
  1308  //行为不端的测试是断开连接的,而行为不正确的测试则是断开连接的。
  1309  func TestBlockHeaderAttackerDropping62(t *testing.T) { testBlockHeaderAttackerDropping(t, 62) }
  1310  func TestBlockHeaderAttackerDropping63(t *testing.T) { testBlockHeaderAttackerDropping(t, 63) }
  1311  func TestBlockHeaderAttackerDropping64(t *testing.T) { testBlockHeaderAttackerDropping(t, 64) }
  1312  
  1313  func testBlockHeaderAttackerDropping(t *testing.T, protocol int) {
  1314  	t.Parallel()
  1315  
  1316  //定义单个哈希获取错误的断开连接要求
  1317  	tests := []struct {
  1318  		result error
  1319  		drop   bool
  1320  	}{
  1321  {nil, false},                        //同步成功,一切正常
  1322  {errBusy, false},                    //同步已在进行中,没问题
  1323  {errUnknownPeer, false},             //对等机未知,已被删除,不要重复删除
  1324  {errBadPeer, true},                  //因为某种原因,同伴被认为是坏的,放下它。
  1325  {errStallingPeer, true},             //检测到对等机正在停止,请删除它
  1326  {errNoPeers, false},                 //无需下载同龄人,软件竞赛,无问题
  1327  {errTimeout, true},                  //在适当的时间内没有收到哈希,请删除对等机
  1328  {errEmptyHeaderSet, true},           //没有返回任何头作为响应,因为它是死胡同而丢弃
  1329  {errPeersUnavailable, true},         //没有人有广告块,把广告丢了
  1330  {errInvalidAncestor, true},          //同意祖先是不可接受的,请删除链重写器
  1331  {errInvalidChain, true},             //哈希链被检测为无效,肯定会丢失
  1332  {errInvalidBlock, false},            //检测到一个错误的对等机,但不是同步源
  1333  {errInvalidBody, false},             //检测到一个错误的对等机,但不是同步源
  1334  {errInvalidReceipt, false},          //检测到一个错误的对等机,但不是同步源
  1335  {errCancelBlockFetch, false},        //同步被取消,原点可能是无辜的,不要掉下来
  1336  {errCancelHeaderFetch, false},       //同步被取消,原点可能是无辜的,不要掉下来
  1337  {errCancelBodyFetch, false},         //同步被取消,原点可能是无辜的,不要掉下来
  1338  {errCancelReceiptFetch, false},      //同步被取消,原点可能是无辜的,不要掉下来
  1339  {errCancelHeaderProcessing, false},  //同步被取消,原点可能是无辜的,不要掉下来
  1340  {errCancelContentProcessing, false}, //同步被取消,原点可能是无辜的,不要掉下来
  1341  	}
  1342  //运行测试并检查断开状态
  1343  	tester := newTester()
  1344  	defer tester.terminate()
  1345  
  1346  	for i, tt := range tests {
  1347  //注册新的对等点并确保其存在
  1348  		id := fmt.Sprintf("test %d", i)
  1349  		if err := tester.newPeer(id, protocol, []common.Hash{tester.genesis.Hash()}, nil, nil, nil); err != nil {
  1350  			t.Fatalf("test %d: failed to register new peer: %v", i, err)
  1351  		}
  1352  		if _, ok := tester.peerHashes[id]; !ok {
  1353  			t.Fatalf("test %d: registered peer not found", i)
  1354  		}
  1355  //模拟同步并检查所需结果
  1356  		tester.downloader.synchroniseMock = func(string, common.Hash) error { return tt.result }
  1357  
  1358  		tester.downloader.Synchronise(id, tester.genesis.Hash(), big.NewInt(1000), FullSync)
  1359  		if _, ok := tester.peerHashes[id]; !ok != tt.drop {
  1360  			t.Errorf("test %d: peer drop mismatch for %v: have %v, want %v", i, tt.result, !ok, tt.drop)
  1361  		}
  1362  	}
  1363  }
  1364  
  1365  //Tests that synchronisation progress (origin block number, current block number
  1366  //以及最高的块号)被正确地跟踪和更新。
  1367  func TestSyncProgress62(t *testing.T)      { testSyncProgress(t, 62, FullSync) }
  1368  func TestSyncProgress63Full(t *testing.T)  { testSyncProgress(t, 63, FullSync) }
  1369  func TestSyncProgress63Fast(t *testing.T)  { testSyncProgress(t, 63, FastSync) }
  1370  func TestSyncProgress64Full(t *testing.T)  { testSyncProgress(t, 64, FullSync) }
  1371  func TestSyncProgress64Fast(t *testing.T)  { testSyncProgress(t, 64, FastSync) }
  1372  func TestSyncProgress64Light(t *testing.T) { testSyncProgress(t, 64, LightSync) }
  1373  
  1374  func testSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1375  	t.Parallel()
  1376  
  1377  	tester := newTester()
  1378  	defer tester.terminate()
  1379  
  1380  //创建一个足够小的区块链来下载
  1381  	targetBlocks := blockCacheItems - 15
  1382  	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1383  
  1384  //设置同步初始化挂钩以捕获进度更改
  1385  	starting := make(chan struct{})
  1386  	progress := make(chan struct{})
  1387  
  1388  	tester.downloader.syncInitHook = func(origin, latest uint64) {
  1389  		starting <- struct{}{}
  1390  		<-progress
  1391  	}
  1392  //检索同步进度并确保它们为零(原始同步)
  1393  	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
  1394  		t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
  1395  	}
  1396  //同步一半块并检查初始进度
  1397  	tester.newPeer("peer-half", protocol, hashes[targetBlocks/2:], headers, blocks, receipts)
  1398  	pending := new(sync.WaitGroup)
  1399  	pending.Add(1)
  1400  
  1401  	go func() {
  1402  		defer pending.Done()
  1403  		if err := tester.sync("peer-half", nil, mode); err != nil {
  1404  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1405  		}
  1406  	}()
  1407  	<-starting
  1408  	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(targetBlocks/2+1) {
  1409  		t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, targetBlocks/2+1)
  1410  	}
  1411  	progress <- struct{}{}
  1412  	pending.Wait()
  1413  
  1414  //同步所有块并检查继续进度
  1415  	tester.newPeer("peer-full", protocol, hashes, headers, blocks, receipts)
  1416  	pending.Add(1)
  1417  
  1418  	go func() {
  1419  		defer pending.Done()
  1420  		if err := tester.sync("peer-full", nil, mode); err != nil {
  1421  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1422  		}
  1423  	}()
  1424  	<-starting
  1425  	if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(targetBlocks/2+1) || progress.CurrentBlock != uint64(targetBlocks/2+1) || progress.HighestBlock != uint64(targetBlocks) {
  1426  		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)
  1427  	}
  1428  	progress <- struct{}{}
  1429  	pending.Wait()
  1430  
  1431  //同步成功后检查最终进度
  1432  	if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(targetBlocks/2+1) || progress.CurrentBlock != uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
  1433  		t.Fatalf("Final progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, targetBlocks/2+1, targetBlocks, targetBlocks)
  1434  	}
  1435  }
  1436  
  1437  //测试同步进程(起始块编号和最高块
  1438  //如果是叉子(或手动头),则正确跟踪和更新数字。
  1439  //回复)
  1440  func TestForkedSyncProgress62(t *testing.T)      { testForkedSyncProgress(t, 62, FullSync) }
  1441  func TestForkedSyncProgress63Full(t *testing.T)  { testForkedSyncProgress(t, 63, FullSync) }
  1442  func TestForkedSyncProgress63Fast(t *testing.T)  { testForkedSyncProgress(t, 63, FastSync) }
  1443  func TestForkedSyncProgress64Full(t *testing.T)  { testForkedSyncProgress(t, 64, FullSync) }
  1444  func TestForkedSyncProgress64Fast(t *testing.T)  { testForkedSyncProgress(t, 64, FastSync) }
  1445  func TestForkedSyncProgress64Light(t *testing.T) { testForkedSyncProgress(t, 64, LightSync) }
  1446  
  1447  func testForkedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1448  	t.Parallel()
  1449  
  1450  	tester := newTester()
  1451  	defer tester.terminate()
  1452  
  1453  //创建分叉链以模拟原点还原
  1454  	common, fork := MaxHashFetch, 2*MaxHashFetch
  1455  	hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, true)
  1456  
  1457  //设置同步初始化挂钩以捕获进度更改
  1458  	starting := make(chan struct{})
  1459  	progress := make(chan struct{})
  1460  
  1461  	tester.downloader.syncInitHook = func(origin, latest uint64) {
  1462  		starting <- struct{}{}
  1463  		<-progress
  1464  	}
  1465  //检索同步进度并确保它们为零(原始同步)
  1466  	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
  1467  		t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
  1468  	}
  1469  //与其中一个拨叉同步并检查进度
  1470  	tester.newPeer("fork A", protocol, hashesA, headersA, blocksA, receiptsA)
  1471  	pending := new(sync.WaitGroup)
  1472  	pending.Add(1)
  1473  
  1474  	go func() {
  1475  		defer pending.Done()
  1476  		if err := tester.sync("fork A", nil, mode); err != nil {
  1477  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1478  		}
  1479  	}()
  1480  	<-starting
  1481  	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(len(hashesA)-1) {
  1482  		t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, len(hashesA)-1)
  1483  	}
  1484  	progress <- struct{}{}
  1485  	pending.Wait()
  1486  
  1487  //在分叉上方模拟成功的同步
  1488  	tester.downloader.syncStatsChainOrigin = tester.downloader.syncStatsChainHeight
  1489  
  1490  //与第二个拨叉同步并检查进度重置
  1491  	tester.newPeer("fork B", protocol, hashesB, headersB, blocksB, receiptsB)
  1492  	pending.Add(1)
  1493  
  1494  	go func() {
  1495  		defer pending.Done()
  1496  		if err := tester.sync("fork B", nil, mode); err != nil {
  1497  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1498  		}
  1499  	}()
  1500  	<-starting
  1501  	if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(common) || progress.CurrentBlock != uint64(len(hashesA)-1) || progress.HighestBlock != uint64(len(hashesB)-1) {
  1502  		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)
  1503  	}
  1504  	progress <- struct{}{}
  1505  	pending.Wait()
  1506  
  1507  //同步成功后检查最终进度
  1508  	if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(common) || progress.CurrentBlock != uint64(len(hashesB)-1) || progress.HighestBlock != uint64(len(hashesB)-1) {
  1509  		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)
  1510  	}
  1511  }
  1512  
  1513  //测试如果同步由于某些故障而中止,则进度
  1514  //原点不会在下一个同步周期中更新,因为它应该被视为
  1515  //继续上一次同步,而不是新实例。
  1516  func TestFailedSyncProgress62(t *testing.T)      { testFailedSyncProgress(t, 62, FullSync) }
  1517  func TestFailedSyncProgress63Full(t *testing.T)  { testFailedSyncProgress(t, 63, FullSync) }
  1518  func TestFailedSyncProgress63Fast(t *testing.T)  { testFailedSyncProgress(t, 63, FastSync) }
  1519  func TestFailedSyncProgress64Full(t *testing.T)  { testFailedSyncProgress(t, 64, FullSync) }
  1520  func TestFailedSyncProgress64Fast(t *testing.T)  { testFailedSyncProgress(t, 64, FastSync) }
  1521  func TestFailedSyncProgress64Light(t *testing.T) { testFailedSyncProgress(t, 64, LightSync) }
  1522  
  1523  func testFailedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1524  	t.Parallel()
  1525  
  1526  	tester := newTester()
  1527  	defer tester.terminate()
  1528  
  1529  //创建一个足够小的区块链来下载
  1530  	targetBlocks := blockCacheItems - 15
  1531  	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1532  
  1533  //设置同步初始化挂钩以捕获进度更改
  1534  	starting := make(chan struct{})
  1535  	progress := make(chan struct{})
  1536  
  1537  	tester.downloader.syncInitHook = func(origin, latest uint64) {
  1538  		starting <- struct{}{}
  1539  		<-progress
  1540  	}
  1541  //检索同步进度并确保它们为零(原始同步)
  1542  	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
  1543  		t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
  1544  	}
  1545  //尝试与有故障的对等机完全同步
  1546  	tester.newPeer("faulty", protocol, hashes, headers, blocks, receipts)
  1547  	missing := targetBlocks / 2
  1548  	delete(tester.peerHeaders["faulty"], hashes[missing])
  1549  	delete(tester.peerBlocks["faulty"], hashes[missing])
  1550  	delete(tester.peerReceipts["faulty"], hashes[missing])
  1551  
  1552  	pending := new(sync.WaitGroup)
  1553  	pending.Add(1)
  1554  
  1555  	go func() {
  1556  		defer pending.Done()
  1557  		if err := tester.sync("faulty", nil, mode); err == nil {
  1558  			panic("succeeded faulty synchronisation")
  1559  		}
  1560  	}()
  1561  	<-starting
  1562  	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(targetBlocks) {
  1563  		t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, targetBlocks)
  1564  	}
  1565  	progress <- struct{}{}
  1566  	pending.Wait()
  1567  
  1568  //与一位优秀的同行同步,并检查故障后进度来源是否提醒相同
  1569  	tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
  1570  	pending.Add(1)
  1571  
  1572  	go func() {
  1573  		defer pending.Done()
  1574  		if err := tester.sync("valid", nil, mode); err != nil {
  1575  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1576  		}
  1577  	}()
  1578  	<-starting
  1579  	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock > uint64(targetBlocks/2) || progress.HighestBlock != uint64(targetBlocks) {
  1580  		t.Fatalf("Completing progress mismatch: have %v/%v/%v, want %v/0-%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, targetBlocks/2, targetBlocks)
  1581  	}
  1582  	progress <- struct{}{}
  1583  	pending.Wait()
  1584  
  1585  //同步成功后检查最终进度
  1586  	if progress := tester.downloader.Progress(); progress.StartingBlock > uint64(targetBlocks/2) || progress.CurrentBlock != uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
  1587  		t.Fatalf("Final progress mismatch: have %v/%v/%v, want 0-%v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, targetBlocks/2, targetBlocks, targetBlocks)
  1588  	}
  1589  }
  1590  
  1591  //测试在检测到攻击后,如果攻击者伪造链高度,
  1592  //在下次同步调用时,进度高度已成功降低。
  1593  func TestFakedSyncProgress62(t *testing.T)      { testFakedSyncProgress(t, 62, FullSync) }
  1594  func TestFakedSyncProgress63Full(t *testing.T)  { testFakedSyncProgress(t, 63, FullSync) }
  1595  func TestFakedSyncProgress63Fast(t *testing.T)  { testFakedSyncProgress(t, 63, FastSync) }
  1596  func TestFakedSyncProgress64Full(t *testing.T)  { testFakedSyncProgress(t, 64, FullSync) }
  1597  func TestFakedSyncProgress64Fast(t *testing.T)  { testFakedSyncProgress(t, 64, FastSync) }
  1598  func TestFakedSyncProgress64Light(t *testing.T) { testFakedSyncProgress(t, 64, LightSync) }
  1599  
  1600  func testFakedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1601  	t.Parallel()
  1602  
  1603  	tester := newTester()
  1604  	defer tester.terminate()
  1605  
  1606  //创建一个小的区块链
  1607  	targetBlocks := blockCacheItems - 15
  1608  	hashes, headers, blocks, receipts := tester.makeChain(targetBlocks+3, 0, tester.genesis, nil, false)
  1609  
  1610  //设置同步初始化挂钩以捕获进度更改
  1611  	starting := make(chan struct{})
  1612  	progress := make(chan struct{})
  1613  
  1614  	tester.downloader.syncInitHook = func(origin, latest uint64) {
  1615  		starting <- struct{}{}
  1616  		<-progress
  1617  	}
  1618  //检索同步进度并确保它们为零(原始同步)
  1619  	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
  1620  		t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
  1621  	}
  1622  //创建并与攻击者同步,该攻击者承诺比可用的链更高
  1623  	tester.newPeer("attack", protocol, hashes, headers, blocks, receipts)
  1624  	for i := 1; i < 3; i++ {
  1625  		delete(tester.peerHeaders["attack"], hashes[i])
  1626  		delete(tester.peerBlocks["attack"], hashes[i])
  1627  		delete(tester.peerReceipts["attack"], hashes[i])
  1628  	}
  1629  
  1630  	pending := new(sync.WaitGroup)
  1631  	pending.Add(1)
  1632  
  1633  	go func() {
  1634  		defer pending.Done()
  1635  		if err := tester.sync("attack", nil, mode); err == nil {
  1636  			panic("succeeded attacker synchronisation")
  1637  		}
  1638  	}()
  1639  	<-starting
  1640  	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(targetBlocks+3) {
  1641  		t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, targetBlocks+3)
  1642  	}
  1643  	progress <- struct{}{}
  1644  	pending.Wait()
  1645  
  1646  //与良好的同行同步,并检查进度高度是否已降低到真实值。
  1647  	tester.newPeer("valid", protocol, hashes[3:], headers, blocks, receipts)
  1648  	pending.Add(1)
  1649  
  1650  	go func() {
  1651  		defer pending.Done()
  1652  		if err := tester.sync("valid", nil, mode); err != nil {
  1653  			panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1654  		}
  1655  	}()
  1656  	<-starting
  1657  	if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock > uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
  1658  		t.Fatalf("Completing progress mismatch: have %v/%v/%v, want %v/0-%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, targetBlocks, targetBlocks)
  1659  	}
  1660  	progress <- struct{}{}
  1661  	pending.Wait()
  1662  
  1663  //同步成功后检查最终进度
  1664  	if progress := tester.downloader.Progress(); progress.StartingBlock > uint64(targetBlocks) || progress.CurrentBlock != uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
  1665  		t.Fatalf("Final progress mismatch: have %v/%v/%v, want 0-%v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, targetBlocks, targetBlocks, targetBlocks)
  1666  	}
  1667  }
  1668  
  1669  //此测试复制了一个问题,即意外交付
  1670  //如果他们到达正确的时间,无限期地封锁。
  1671  //我们使用数据驱动的子测试来管理它,这样它就可以自己并行。
  1672  //而不是其他测试,避免间歇性故障。
  1673  func TestDeliverHeadersHang(t *testing.T) {
  1674  	testCases := []struct {
  1675  		protocol int
  1676  		syncMode SyncMode
  1677  	}{
  1678  		{62, FullSync},
  1679  		{63, FullSync},
  1680  		{63, FastSync},
  1681  		{64, FullSync},
  1682  		{64, FastSync},
  1683  		{64, LightSync},
  1684  	}
  1685  	for _, tc := range testCases {
  1686  		t.Run(fmt.Sprintf("protocol %d mode %v", tc.protocol, tc.syncMode), func(t *testing.T) {
  1687  			testDeliverHeadersHang(t, tc.protocol, tc.syncMode)
  1688  		})
  1689  	}
  1690  }
  1691  
  1692  type floodingTestPeer struct {
  1693  	peer   Peer
  1694  	tester *downloadTester
  1695  	pend   sync.WaitGroup
  1696  }
  1697  
  1698  func (ftp *floodingTestPeer) Head() (common.Hash, *big.Int) { return ftp.peer.Head() }
  1699  func (ftp *floodingTestPeer) RequestHeadersByHash(hash common.Hash, count int, skip int, reverse bool) error {
  1700  	return ftp.peer.RequestHeadersByHash(hash, count, skip, reverse)
  1701  }
  1702  func (ftp *floodingTestPeer) RequestBodies(hashes []common.Hash) error {
  1703  	return ftp.peer.RequestBodies(hashes)
  1704  }
  1705  func (ftp *floodingTestPeer) RequestReceipts(hashes []common.Hash) error {
  1706  	return ftp.peer.RequestReceipts(hashes)
  1707  }
  1708  func (ftp *floodingTestPeer) RequestNodeData(hashes []common.Hash) error {
  1709  	return ftp.peer.RequestNodeData(hashes)
  1710  }
  1711  
  1712  func (ftp *floodingTestPeer) RequestHeadersByNumber(from uint64, count, skip int, reverse bool) error {
  1713  	deliveriesDone := make(chan struct{}, 500)
  1714  	for i := 0; i < cap(deliveriesDone); i++ {
  1715  		peer := fmt.Sprintf("fake-peer%d", i)
  1716  		ftp.pend.Add(1)
  1717  
  1718  		go func() {
  1719  			ftp.tester.downloader.DeliverHeaders(peer, []*types.Header{{}, {}, {}, {}})
  1720  			deliveriesDone <- struct{}{}
  1721  			ftp.pend.Done()
  1722  		}()
  1723  	}
  1724  //传递实际请求的头。
  1725  	go ftp.peer.RequestHeadersByNumber(from, count, skip, reverse)
  1726  //额外交货不应受阻。
  1727  	timeout := time.After(60 * time.Second)
  1728  	for i := 0; i < cap(deliveriesDone); i++ {
  1729  		select {
  1730  		case <-deliveriesDone:
  1731  		case <-timeout:
  1732  			panic("blocked")
  1733  		}
  1734  	}
  1735  	return nil
  1736  }
  1737  
  1738  func testDeliverHeadersHang(t *testing.T, protocol int, mode SyncMode) {
  1739  	t.Parallel()
  1740  
  1741  	master := newTester()
  1742  	defer master.terminate()
  1743  
  1744  	hashes, headers, blocks, receipts := master.makeChain(5, 0, master.genesis, nil, false)
  1745  	for i := 0; i < 200; i++ {
  1746  		tester := newTester()
  1747  		tester.peerDb = master.peerDb
  1748  
  1749  		tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
  1750  //每当下载程序请求报头时,就用
  1751  //很多未请求的头部交付。
  1752  		tester.downloader.peers.peers["peer"].peer = &floodingTestPeer{
  1753  			peer:   tester.downloader.peers.peers["peer"].peer,
  1754  			tester: tester,
  1755  		}
  1756  		if err := tester.sync("peer", nil, mode); err != nil {
  1757  			t.Errorf("test %d: sync failed: %v", i, err)
  1758  		}
  1759  		tester.terminate()
  1760  
  1761  //冲洗所有Goroutine,以防干扰后续测试
  1762  		tester.downloader.peers.peers["peer"].peer.(*floodingTestPeer).pend.Wait()
  1763  	}
  1764  }