github.com/linapex/ethereum-dpos-chinese@v0.0.0-20190316121959-b78b3a4a1ece/eth/downloader/downloader_test.go (about)

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