downloader_test.go 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package downloader
  17. import (
  18. "errors"
  19. "fmt"
  20. "math/big"
  21. "sync"
  22. "sync/atomic"
  23. "testing"
  24. "time"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/core"
  27. "github.com/ethereum/go-ethereum/core/state"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/crypto"
  30. "github.com/ethereum/go-ethereum/ethdb"
  31. "github.com/ethereum/go-ethereum/event"
  32. "github.com/ethereum/go-ethereum/params"
  33. "github.com/ethereum/go-ethereum/trie"
  34. )
  35. var (
  36. testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  37. testAddress = crypto.PubkeyToAddress(testKey.PublicKey)
  38. )
  39. // Reduce some of the parameters to make the tester faster.
  40. func init() {
  41. MaxForkAncestry = uint64(10000)
  42. blockCacheLimit = 1024
  43. fsCriticalTrials = 10
  44. }
  45. // downloadTester is a test simulator for mocking out local block chain.
  46. type downloadTester struct {
  47. downloader *Downloader
  48. genesis *types.Block // Genesis blocks used by the tester and peers
  49. stateDb ethdb.Database // Database used by the tester for syncing from peers
  50. peerDb ethdb.Database // Database of the peers containing all data
  51. ownHashes []common.Hash // Hash chain belonging to the tester
  52. ownHeaders map[common.Hash]*types.Header // Headers belonging to the tester
  53. ownBlocks map[common.Hash]*types.Block // Blocks belonging to the tester
  54. ownReceipts map[common.Hash]types.Receipts // Receipts belonging to the tester
  55. ownChainTd map[common.Hash]*big.Int // Total difficulties of the blocks in the local chain
  56. peerHashes map[string][]common.Hash // Hash chain belonging to different test peers
  57. peerHeaders map[string]map[common.Hash]*types.Header // Headers belonging to different test peers
  58. peerBlocks map[string]map[common.Hash]*types.Block // Blocks belonging to different test peers
  59. peerReceipts map[string]map[common.Hash]types.Receipts // Receipts belonging to different test peers
  60. peerChainTds map[string]map[common.Hash]*big.Int // Total difficulties of the blocks in the peer chains
  61. peerMissingStates map[string]map[common.Hash]bool // State entries that fast sync should not return
  62. lock sync.RWMutex
  63. }
  64. // newTester creates a new downloader test mocker.
  65. func newTester() *downloadTester {
  66. testdb, _ := ethdb.NewMemDatabase()
  67. genesis := core.GenesisBlockForTesting(testdb, testAddress, big.NewInt(1000000000))
  68. tester := &downloadTester{
  69. genesis: genesis,
  70. peerDb: testdb,
  71. ownHashes: []common.Hash{genesis.Hash()},
  72. ownHeaders: map[common.Hash]*types.Header{genesis.Hash(): genesis.Header()},
  73. ownBlocks: map[common.Hash]*types.Block{genesis.Hash(): genesis},
  74. ownReceipts: map[common.Hash]types.Receipts{genesis.Hash(): nil},
  75. ownChainTd: map[common.Hash]*big.Int{genesis.Hash(): genesis.Difficulty()},
  76. peerHashes: make(map[string][]common.Hash),
  77. peerHeaders: make(map[string]map[common.Hash]*types.Header),
  78. peerBlocks: make(map[string]map[common.Hash]*types.Block),
  79. peerReceipts: make(map[string]map[common.Hash]types.Receipts),
  80. peerChainTds: make(map[string]map[common.Hash]*big.Int),
  81. peerMissingStates: make(map[string]map[common.Hash]bool),
  82. }
  83. tester.stateDb, _ = ethdb.NewMemDatabase()
  84. tester.stateDb.Put(genesis.Root().Bytes(), []byte{0x00})
  85. tester.downloader = New(tester.stateDb, new(event.TypeMux), tester.hasHeader, tester.hasBlock, tester.getHeader,
  86. tester.getBlock, tester.headHeader, tester.headBlock, tester.headFastBlock, tester.commitHeadBlock, tester.getTd,
  87. tester.insertHeaders, tester.insertBlocks, tester.insertReceipts, tester.rollback, tester.dropPeer)
  88. return tester
  89. }
  90. // makeChain creates a chain of n blocks starting at and including parent.
  91. // the returned hash chain is ordered head->parent. In addition, every 3rd block
  92. // contains a transaction and every 5th an uncle to allow testing correct block
  93. // reassembly.
  94. 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) {
  95. // Generate the block chain
  96. blocks, receipts := core.GenerateChain(nil, parent, dl.peerDb, n, func(i int, block *core.BlockGen) {
  97. block.SetCoinbase(common.Address{seed})
  98. // If a heavy chain is requested, delay blocks to raise difficulty
  99. if heavy {
  100. block.OffsetTime(-1)
  101. }
  102. // If the block number is multiple of 3, send a bonus transaction to the miner
  103. if parent == dl.genesis && i%3 == 0 {
  104. tx, err := types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(testKey)
  105. if err != nil {
  106. panic(err)
  107. }
  108. block.AddTx(tx)
  109. }
  110. // If the block number is a multiple of 5, add a bonus uncle to the block
  111. if i > 0 && i%5 == 0 {
  112. block.AddUncle(&types.Header{
  113. ParentHash: block.PrevBlock(i - 1).Hash(),
  114. Number: big.NewInt(block.Number().Int64() - 1),
  115. })
  116. }
  117. })
  118. // Convert the block-chain into a hash-chain and header/block maps
  119. hashes := make([]common.Hash, n+1)
  120. hashes[len(hashes)-1] = parent.Hash()
  121. headerm := make(map[common.Hash]*types.Header, n+1)
  122. headerm[parent.Hash()] = parent.Header()
  123. blockm := make(map[common.Hash]*types.Block, n+1)
  124. blockm[parent.Hash()] = parent
  125. receiptm := make(map[common.Hash]types.Receipts, n+1)
  126. receiptm[parent.Hash()] = parentReceipts
  127. for i, b := range blocks {
  128. hashes[len(hashes)-i-2] = b.Hash()
  129. headerm[b.Hash()] = b.Header()
  130. blockm[b.Hash()] = b
  131. receiptm[b.Hash()] = receipts[i]
  132. }
  133. return hashes, headerm, blockm, receiptm
  134. }
  135. // makeChainFork creates two chains of length n, such that h1[:f] and
  136. // h2[:f] are different but have a common suffix of length n-f.
  137. 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) {
  138. // Create the common suffix
  139. hashes, headers, blocks, receipts := dl.makeChain(n-f, 0, parent, parentReceipts, false)
  140. // Create the forks, making the second heavyer if non balanced forks were requested
  141. hashes1, headers1, blocks1, receipts1 := dl.makeChain(f, 1, blocks[hashes[0]], receipts[hashes[0]], false)
  142. hashes1 = append(hashes1, hashes[1:]...)
  143. heavy := false
  144. if !balanced {
  145. heavy = true
  146. }
  147. hashes2, headers2, blocks2, receipts2 := dl.makeChain(f, 2, blocks[hashes[0]], receipts[hashes[0]], heavy)
  148. hashes2 = append(hashes2, hashes[1:]...)
  149. for hash, header := range headers {
  150. headers1[hash] = header
  151. headers2[hash] = header
  152. }
  153. for hash, block := range blocks {
  154. blocks1[hash] = block
  155. blocks2[hash] = block
  156. }
  157. for hash, receipt := range receipts {
  158. receipts1[hash] = receipt
  159. receipts2[hash] = receipt
  160. }
  161. return hashes1, hashes2, headers1, headers2, blocks1, blocks2, receipts1, receipts2
  162. }
  163. // terminate aborts any operations on the embedded downloader and releases all
  164. // held resources.
  165. func (dl *downloadTester) terminate() {
  166. dl.downloader.Terminate()
  167. }
  168. // sync starts synchronizing with a remote peer, blocking until it completes.
  169. func (dl *downloadTester) sync(id string, td *big.Int, mode SyncMode) error {
  170. dl.lock.RLock()
  171. hash := dl.peerHashes[id][0]
  172. // If no particular TD was requested, load from the peer's blockchain
  173. if td == nil {
  174. td = big.NewInt(1)
  175. if diff, ok := dl.peerChainTds[id][hash]; ok {
  176. td = diff
  177. }
  178. }
  179. dl.lock.RUnlock()
  180. // Synchronise with the chosen peer and ensure proper cleanup afterwards
  181. err := dl.downloader.synchronise(id, hash, td, mode)
  182. select {
  183. case <-dl.downloader.cancelCh:
  184. // Ok, downloader fully cancelled after sync cycle
  185. default:
  186. // Downloader is still accepting packets, can block a peer up
  187. panic("downloader active post sync cycle") // panic will be caught by tester
  188. }
  189. return err
  190. }
  191. // hasHeader checks if a header is present in the testers canonical chain.
  192. func (dl *downloadTester) hasHeader(hash common.Hash) bool {
  193. return dl.getHeader(hash) != nil
  194. }
  195. // hasBlock checks if a block and associated state is present in the testers canonical chain.
  196. func (dl *downloadTester) hasBlock(hash common.Hash) bool {
  197. block := dl.getBlock(hash)
  198. if block == nil {
  199. return false
  200. }
  201. _, err := dl.stateDb.Get(block.Root().Bytes())
  202. return err == nil
  203. }
  204. // getHeader retrieves a header from the testers canonical chain.
  205. func (dl *downloadTester) getHeader(hash common.Hash) *types.Header {
  206. dl.lock.RLock()
  207. defer dl.lock.RUnlock()
  208. return dl.ownHeaders[hash]
  209. }
  210. // getBlock retrieves a block from the testers canonical chain.
  211. func (dl *downloadTester) getBlock(hash common.Hash) *types.Block {
  212. dl.lock.RLock()
  213. defer dl.lock.RUnlock()
  214. return dl.ownBlocks[hash]
  215. }
  216. // headHeader retrieves the current head header from the canonical chain.
  217. func (dl *downloadTester) headHeader() *types.Header {
  218. dl.lock.RLock()
  219. defer dl.lock.RUnlock()
  220. for i := len(dl.ownHashes) - 1; i >= 0; i-- {
  221. if header := dl.ownHeaders[dl.ownHashes[i]]; header != nil {
  222. return header
  223. }
  224. }
  225. return dl.genesis.Header()
  226. }
  227. // headBlock retrieves the current head block from the canonical chain.
  228. func (dl *downloadTester) headBlock() *types.Block {
  229. dl.lock.RLock()
  230. defer dl.lock.RUnlock()
  231. for i := len(dl.ownHashes) - 1; i >= 0; i-- {
  232. if block := dl.ownBlocks[dl.ownHashes[i]]; block != nil {
  233. if _, err := dl.stateDb.Get(block.Root().Bytes()); err == nil {
  234. return block
  235. }
  236. }
  237. }
  238. return dl.genesis
  239. }
  240. // headFastBlock retrieves the current head fast-sync block from the canonical chain.
  241. func (dl *downloadTester) headFastBlock() *types.Block {
  242. dl.lock.RLock()
  243. defer dl.lock.RUnlock()
  244. for i := len(dl.ownHashes) - 1; i >= 0; i-- {
  245. if block := dl.ownBlocks[dl.ownHashes[i]]; block != nil {
  246. return block
  247. }
  248. }
  249. return dl.genesis
  250. }
  251. // commitHeadBlock manually sets the head block to a given hash.
  252. func (dl *downloadTester) commitHeadBlock(hash common.Hash) error {
  253. // For now only check that the state trie is correct
  254. if block := dl.getBlock(hash); block != nil {
  255. _, err := trie.NewSecure(block.Root(), dl.stateDb, 0)
  256. return err
  257. }
  258. return fmt.Errorf("non existent block: %x", hash[:4])
  259. }
  260. // getTd retrieves the block's total difficulty from the canonical chain.
  261. func (dl *downloadTester) getTd(hash common.Hash) *big.Int {
  262. dl.lock.RLock()
  263. defer dl.lock.RUnlock()
  264. return dl.ownChainTd[hash]
  265. }
  266. // insertHeaders injects a new batch of headers into the simulated chain.
  267. func (dl *downloadTester) insertHeaders(headers []*types.Header, checkFreq int) (int, error) {
  268. dl.lock.Lock()
  269. defer dl.lock.Unlock()
  270. // Do a quick check, as the blockchain.InsertHeaderChain doesn't insert anything in case of errors
  271. if _, ok := dl.ownHeaders[headers[0].ParentHash]; !ok {
  272. return 0, errors.New("unknown parent")
  273. }
  274. for i := 1; i < len(headers); i++ {
  275. if headers[i].ParentHash != headers[i-1].Hash() {
  276. return i, errors.New("unknown parent")
  277. }
  278. }
  279. // Do a full insert if pre-checks passed
  280. for i, header := range headers {
  281. if _, ok := dl.ownHeaders[header.Hash()]; ok {
  282. continue
  283. }
  284. if _, ok := dl.ownHeaders[header.ParentHash]; !ok {
  285. return i, errors.New("unknown parent")
  286. }
  287. dl.ownHashes = append(dl.ownHashes, header.Hash())
  288. dl.ownHeaders[header.Hash()] = header
  289. dl.ownChainTd[header.Hash()] = new(big.Int).Add(dl.ownChainTd[header.ParentHash], header.Difficulty)
  290. }
  291. return len(headers), nil
  292. }
  293. // insertBlocks injects a new batch of blocks into the simulated chain.
  294. func (dl *downloadTester) insertBlocks(blocks types.Blocks) (int, error) {
  295. dl.lock.Lock()
  296. defer dl.lock.Unlock()
  297. for i, block := range blocks {
  298. if parent, ok := dl.ownBlocks[block.ParentHash()]; !ok {
  299. return i, errors.New("unknown parent")
  300. } else if _, err := dl.stateDb.Get(parent.Root().Bytes()); err != nil {
  301. return i, fmt.Errorf("unknown parent state %x: %v", parent.Root(), err)
  302. }
  303. if _, ok := dl.ownHeaders[block.Hash()]; !ok {
  304. dl.ownHashes = append(dl.ownHashes, block.Hash())
  305. dl.ownHeaders[block.Hash()] = block.Header()
  306. }
  307. dl.ownBlocks[block.Hash()] = block
  308. dl.stateDb.Put(block.Root().Bytes(), []byte{0x00})
  309. dl.ownChainTd[block.Hash()] = new(big.Int).Add(dl.ownChainTd[block.ParentHash()], block.Difficulty())
  310. }
  311. return len(blocks), nil
  312. }
  313. // insertReceipts injects a new batch of blocks into the simulated chain.
  314. func (dl *downloadTester) insertReceipts(blocks types.Blocks, receipts []types.Receipts) (int, error) {
  315. dl.lock.Lock()
  316. defer dl.lock.Unlock()
  317. for i := 0; i < len(blocks) && i < len(receipts); i++ {
  318. if _, ok := dl.ownHeaders[blocks[i].Hash()]; !ok {
  319. return i, errors.New("unknown owner")
  320. }
  321. if _, ok := dl.ownBlocks[blocks[i].ParentHash()]; !ok {
  322. return i, errors.New("unknown parent")
  323. }
  324. dl.ownBlocks[blocks[i].Hash()] = blocks[i]
  325. dl.ownReceipts[blocks[i].Hash()] = receipts[i]
  326. }
  327. return len(blocks), nil
  328. }
  329. // rollback removes some recently added elements from the chain.
  330. func (dl *downloadTester) rollback(hashes []common.Hash) {
  331. dl.lock.Lock()
  332. defer dl.lock.Unlock()
  333. for i := len(hashes) - 1; i >= 0; i-- {
  334. if dl.ownHashes[len(dl.ownHashes)-1] == hashes[i] {
  335. dl.ownHashes = dl.ownHashes[:len(dl.ownHashes)-1]
  336. }
  337. delete(dl.ownChainTd, hashes[i])
  338. delete(dl.ownHeaders, hashes[i])
  339. delete(dl.ownReceipts, hashes[i])
  340. delete(dl.ownBlocks, hashes[i])
  341. }
  342. }
  343. // newPeer registers a new block download source into the downloader.
  344. 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 {
  345. return dl.newSlowPeer(id, version, hashes, headers, blocks, receipts, 0)
  346. }
  347. // newSlowPeer registers a new block download source into the downloader, with a
  348. // specific delay time on processing the network packets sent to it, simulating
  349. // potentially slow network IO.
  350. 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 {
  351. dl.lock.Lock()
  352. defer dl.lock.Unlock()
  353. var err error
  354. switch version {
  355. case 62:
  356. err = dl.downloader.RegisterPeer(id, version, dl.peerCurrentHeadFn(id), dl.peerGetRelHeadersFn(id, delay), dl.peerGetAbsHeadersFn(id, delay), dl.peerGetBodiesFn(id, delay), nil, nil)
  357. case 63:
  358. err = dl.downloader.RegisterPeer(id, version, dl.peerCurrentHeadFn(id), dl.peerGetRelHeadersFn(id, delay), dl.peerGetAbsHeadersFn(id, delay), dl.peerGetBodiesFn(id, delay), dl.peerGetReceiptsFn(id, delay), dl.peerGetNodeDataFn(id, delay))
  359. case 64:
  360. err = dl.downloader.RegisterPeer(id, version, dl.peerCurrentHeadFn(id), dl.peerGetRelHeadersFn(id, delay), dl.peerGetAbsHeadersFn(id, delay), dl.peerGetBodiesFn(id, delay), dl.peerGetReceiptsFn(id, delay), dl.peerGetNodeDataFn(id, delay))
  361. }
  362. if err == nil {
  363. // Assign the owned hashes, headers and blocks to the peer (deep copy)
  364. dl.peerHashes[id] = make([]common.Hash, len(hashes))
  365. copy(dl.peerHashes[id], hashes)
  366. dl.peerHeaders[id] = make(map[common.Hash]*types.Header)
  367. dl.peerBlocks[id] = make(map[common.Hash]*types.Block)
  368. dl.peerReceipts[id] = make(map[common.Hash]types.Receipts)
  369. dl.peerChainTds[id] = make(map[common.Hash]*big.Int)
  370. dl.peerMissingStates[id] = make(map[common.Hash]bool)
  371. genesis := hashes[len(hashes)-1]
  372. if header := headers[genesis]; header != nil {
  373. dl.peerHeaders[id][genesis] = header
  374. dl.peerChainTds[id][genesis] = header.Difficulty
  375. }
  376. if block := blocks[genesis]; block != nil {
  377. dl.peerBlocks[id][genesis] = block
  378. dl.peerChainTds[id][genesis] = block.Difficulty()
  379. }
  380. for i := len(hashes) - 2; i >= 0; i-- {
  381. hash := hashes[i]
  382. if header, ok := headers[hash]; ok {
  383. dl.peerHeaders[id][hash] = header
  384. if _, ok := dl.peerHeaders[id][header.ParentHash]; ok {
  385. dl.peerChainTds[id][hash] = new(big.Int).Add(header.Difficulty, dl.peerChainTds[id][header.ParentHash])
  386. }
  387. }
  388. if block, ok := blocks[hash]; ok {
  389. dl.peerBlocks[id][hash] = block
  390. if _, ok := dl.peerBlocks[id][block.ParentHash()]; ok {
  391. dl.peerChainTds[id][hash] = new(big.Int).Add(block.Difficulty(), dl.peerChainTds[id][block.ParentHash()])
  392. }
  393. }
  394. if receipt, ok := receipts[hash]; ok {
  395. dl.peerReceipts[id][hash] = receipt
  396. }
  397. }
  398. }
  399. return err
  400. }
  401. // dropPeer simulates a hard peer removal from the connection pool.
  402. func (dl *downloadTester) dropPeer(id string) {
  403. dl.lock.Lock()
  404. defer dl.lock.Unlock()
  405. delete(dl.peerHashes, id)
  406. delete(dl.peerHeaders, id)
  407. delete(dl.peerBlocks, id)
  408. delete(dl.peerChainTds, id)
  409. dl.downloader.UnregisterPeer(id)
  410. }
  411. // peerCurrentHeadFn constructs a function to retrieve a peer's current head hash
  412. // and total difficulty.
  413. func (dl *downloadTester) peerCurrentHeadFn(id string) func() (common.Hash, *big.Int) {
  414. return func() (common.Hash, *big.Int) {
  415. dl.lock.RLock()
  416. defer dl.lock.RUnlock()
  417. return dl.peerHashes[id][0], nil
  418. }
  419. }
  420. // peerGetRelHeadersFn constructs a GetBlockHeaders function based on a hashed
  421. // origin; associated with a particular peer in the download tester. The returned
  422. // function can be used to retrieve batches of headers from the particular peer.
  423. func (dl *downloadTester) peerGetRelHeadersFn(id string, delay time.Duration) func(common.Hash, int, int, bool) error {
  424. return func(origin common.Hash, amount int, skip int, reverse bool) error {
  425. // Find the canonical number of the hash
  426. dl.lock.RLock()
  427. number := uint64(0)
  428. for num, hash := range dl.peerHashes[id] {
  429. if hash == origin {
  430. number = uint64(len(dl.peerHashes[id]) - num - 1)
  431. break
  432. }
  433. }
  434. dl.lock.RUnlock()
  435. // Use the absolute header fetcher to satisfy the query
  436. return dl.peerGetAbsHeadersFn(id, delay)(number, amount, skip, reverse)
  437. }
  438. }
  439. // peerGetAbsHeadersFn constructs a GetBlockHeaders function based on a numbered
  440. // origin; associated with a particular peer in the download tester. The returned
  441. // function can be used to retrieve batches of headers from the particular peer.
  442. func (dl *downloadTester) peerGetAbsHeadersFn(id string, delay time.Duration) func(uint64, int, int, bool) error {
  443. return func(origin uint64, amount int, skip int, reverse bool) error {
  444. time.Sleep(delay)
  445. dl.lock.RLock()
  446. defer dl.lock.RUnlock()
  447. // Gather the next batch of headers
  448. hashes := dl.peerHashes[id]
  449. headers := dl.peerHeaders[id]
  450. result := make([]*types.Header, 0, amount)
  451. for i := 0; i < amount && len(hashes)-int(origin)-1-i*(skip+1) >= 0; i++ {
  452. if header, ok := headers[hashes[len(hashes)-int(origin)-1-i*(skip+1)]]; ok {
  453. result = append(result, header)
  454. }
  455. }
  456. // Delay delivery a bit to allow attacks to unfold
  457. go func() {
  458. time.Sleep(time.Millisecond)
  459. dl.downloader.DeliverHeaders(id, result)
  460. }()
  461. return nil
  462. }
  463. }
  464. // peerGetBodiesFn constructs a getBlockBodies method associated with a particular
  465. // peer in the download tester. The returned function can be used to retrieve
  466. // batches of block bodies from the particularly requested peer.
  467. func (dl *downloadTester) peerGetBodiesFn(id string, delay time.Duration) func([]common.Hash) error {
  468. return func(hashes []common.Hash) error {
  469. time.Sleep(delay)
  470. dl.lock.RLock()
  471. defer dl.lock.RUnlock()
  472. blocks := dl.peerBlocks[id]
  473. transactions := make([][]*types.Transaction, 0, len(hashes))
  474. uncles := make([][]*types.Header, 0, len(hashes))
  475. for _, hash := range hashes {
  476. if block, ok := blocks[hash]; ok {
  477. transactions = append(transactions, block.Transactions())
  478. uncles = append(uncles, block.Uncles())
  479. }
  480. }
  481. go dl.downloader.DeliverBodies(id, transactions, uncles)
  482. return nil
  483. }
  484. }
  485. // peerGetReceiptsFn constructs a getReceipts method associated with a particular
  486. // peer in the download tester. The returned function can be used to retrieve
  487. // batches of block receipts from the particularly requested peer.
  488. func (dl *downloadTester) peerGetReceiptsFn(id string, delay time.Duration) func([]common.Hash) error {
  489. return func(hashes []common.Hash) error {
  490. time.Sleep(delay)
  491. dl.lock.RLock()
  492. defer dl.lock.RUnlock()
  493. receipts := dl.peerReceipts[id]
  494. results := make([][]*types.Receipt, 0, len(hashes))
  495. for _, hash := range hashes {
  496. if receipt, ok := receipts[hash]; ok {
  497. results = append(results, receipt)
  498. }
  499. }
  500. go dl.downloader.DeliverReceipts(id, results)
  501. return nil
  502. }
  503. }
  504. // peerGetNodeDataFn constructs a getNodeData method associated with a particular
  505. // peer in the download tester. The returned function can be used to retrieve
  506. // batches of node state data from the particularly requested peer.
  507. func (dl *downloadTester) peerGetNodeDataFn(id string, delay time.Duration) func([]common.Hash) error {
  508. return func(hashes []common.Hash) error {
  509. time.Sleep(delay)
  510. dl.lock.RLock()
  511. defer dl.lock.RUnlock()
  512. results := make([][]byte, 0, len(hashes))
  513. for _, hash := range hashes {
  514. if data, err := dl.peerDb.Get(hash.Bytes()); err == nil {
  515. if !dl.peerMissingStates[id][hash] {
  516. results = append(results, data)
  517. }
  518. }
  519. }
  520. go dl.downloader.DeliverNodeData(id, results)
  521. return nil
  522. }
  523. }
  524. // assertOwnChain checks if the local chain contains the correct number of items
  525. // of the various chain components.
  526. func assertOwnChain(t *testing.T, tester *downloadTester, length int) {
  527. assertOwnForkedChain(t, tester, 1, []int{length})
  528. }
  529. // assertOwnForkedChain checks if the local forked chain contains the correct
  530. // number of items of the various chain components.
  531. func assertOwnForkedChain(t *testing.T, tester *downloadTester, common int, lengths []int) {
  532. // Initialize the counters for the first fork
  533. headers, blocks := lengths[0], lengths[0]
  534. minReceipts, maxReceipts := lengths[0]-fsMinFullBlocks-fsPivotInterval, lengths[0]-fsMinFullBlocks
  535. if minReceipts < 0 {
  536. minReceipts = 1
  537. }
  538. if maxReceipts < 0 {
  539. maxReceipts = 1
  540. }
  541. // Update the counters for each subsequent fork
  542. for _, length := range lengths[1:] {
  543. headers += length - common
  544. blocks += length - common
  545. minReceipts += length - common - fsMinFullBlocks - fsPivotInterval
  546. maxReceipts += length - common - fsMinFullBlocks
  547. }
  548. switch tester.downloader.mode {
  549. case FullSync:
  550. minReceipts, maxReceipts = 1, 1
  551. case LightSync:
  552. blocks, minReceipts, maxReceipts = 1, 1, 1
  553. }
  554. if hs := len(tester.ownHeaders); hs != headers {
  555. t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, headers)
  556. }
  557. if bs := len(tester.ownBlocks); bs != blocks {
  558. t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, blocks)
  559. }
  560. if rs := len(tester.ownReceipts); rs < minReceipts || rs > maxReceipts {
  561. t.Fatalf("synchronised receipts mismatch: have %v, want between [%v, %v]", rs, minReceipts, maxReceipts)
  562. }
  563. // Verify the state trie too for fast syncs
  564. if tester.downloader.mode == FastSync {
  565. index := 0
  566. if pivot := int(tester.downloader.queue.fastSyncPivot); pivot < common {
  567. index = pivot
  568. } else {
  569. index = len(tester.ownHashes) - lengths[len(lengths)-1] + int(tester.downloader.queue.fastSyncPivot)
  570. }
  571. if index > 0 {
  572. if statedb, err := state.New(tester.ownHeaders[tester.ownHashes[index]].Root, tester.stateDb); statedb == nil || err != nil {
  573. t.Fatalf("state reconstruction failed: %v", err)
  574. }
  575. }
  576. }
  577. }
  578. // Tests that simple synchronization against a canonical chain works correctly.
  579. // In this test common ancestor lookup should be short circuited and not require
  580. // binary searching.
  581. func TestCanonicalSynchronisation62(t *testing.T) { testCanonicalSynchronisation(t, 62, FullSync) }
  582. func TestCanonicalSynchronisation63Full(t *testing.T) { testCanonicalSynchronisation(t, 63, FullSync) }
  583. func TestCanonicalSynchronisation63Fast(t *testing.T) { testCanonicalSynchronisation(t, 63, FastSync) }
  584. func TestCanonicalSynchronisation64Full(t *testing.T) { testCanonicalSynchronisation(t, 64, FullSync) }
  585. func TestCanonicalSynchronisation64Fast(t *testing.T) { testCanonicalSynchronisation(t, 64, FastSync) }
  586. func TestCanonicalSynchronisation64Light(t *testing.T) { testCanonicalSynchronisation(t, 64, LightSync) }
  587. func testCanonicalSynchronisation(t *testing.T, protocol int, mode SyncMode) {
  588. t.Parallel()
  589. tester := newTester()
  590. defer tester.terminate()
  591. // Create a small enough block chain to download
  592. targetBlocks := blockCacheLimit - 15
  593. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  594. tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
  595. // Synchronise with the peer and make sure all relevant data was retrieved
  596. if err := tester.sync("peer", nil, mode); err != nil {
  597. t.Fatalf("failed to synchronise blocks: %v", err)
  598. }
  599. assertOwnChain(t, tester, targetBlocks+1)
  600. }
  601. // Tests that if a large batch of blocks are being downloaded, it is throttled
  602. // until the cached blocks are retrieved.
  603. func TestThrottling62(t *testing.T) { testThrottling(t, 62, FullSync) }
  604. func TestThrottling63Full(t *testing.T) { testThrottling(t, 63, FullSync) }
  605. func TestThrottling63Fast(t *testing.T) { testThrottling(t, 63, FastSync) }
  606. func TestThrottling64Full(t *testing.T) { testThrottling(t, 64, FullSync) }
  607. func TestThrottling64Fast(t *testing.T) { testThrottling(t, 64, FastSync) }
  608. func testThrottling(t *testing.T, protocol int, mode SyncMode) {
  609. tester := newTester()
  610. defer tester.terminate()
  611. // Create a long block chain to download and the tester
  612. targetBlocks := 8 * blockCacheLimit
  613. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  614. tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
  615. // Wrap the importer to allow stepping
  616. blocked, proceed := uint32(0), make(chan struct{})
  617. tester.downloader.chainInsertHook = func(results []*fetchResult) {
  618. atomic.StoreUint32(&blocked, uint32(len(results)))
  619. <-proceed
  620. }
  621. // Start a synchronisation concurrently
  622. errc := make(chan error)
  623. go func() {
  624. errc <- tester.sync("peer", nil, mode)
  625. }()
  626. // Iteratively take some blocks, always checking the retrieval count
  627. for {
  628. // Check the retrieval count synchronously (! reason for this ugly block)
  629. tester.lock.RLock()
  630. retrieved := len(tester.ownBlocks)
  631. tester.lock.RUnlock()
  632. if retrieved >= targetBlocks+1 {
  633. break
  634. }
  635. // Wait a bit for sync to throttle itself
  636. var cached, frozen int
  637. for start := time.Now(); time.Since(start) < 3*time.Second; {
  638. time.Sleep(25 * time.Millisecond)
  639. tester.lock.Lock()
  640. tester.downloader.queue.lock.Lock()
  641. cached = len(tester.downloader.queue.blockDonePool)
  642. if mode == FastSync {
  643. if receipts := len(tester.downloader.queue.receiptDonePool); receipts < cached {
  644. if tester.downloader.queue.resultCache[receipts].Header.Number.Uint64() < tester.downloader.queue.fastSyncPivot {
  645. cached = receipts
  646. }
  647. }
  648. }
  649. frozen = int(atomic.LoadUint32(&blocked))
  650. retrieved = len(tester.ownBlocks)
  651. tester.downloader.queue.lock.Unlock()
  652. tester.lock.Unlock()
  653. if cached == blockCacheLimit || retrieved+cached+frozen == targetBlocks+1 {
  654. break
  655. }
  656. }
  657. // Make sure we filled up the cache, then exhaust it
  658. time.Sleep(25 * time.Millisecond) // give it a chance to screw up
  659. tester.lock.RLock()
  660. retrieved = len(tester.ownBlocks)
  661. tester.lock.RUnlock()
  662. if cached != blockCacheLimit && retrieved+cached+frozen != targetBlocks+1 {
  663. t.Fatalf("block count mismatch: have %v, want %v (owned %v, blocked %v, target %v)", cached, blockCacheLimit, retrieved, frozen, targetBlocks+1)
  664. }
  665. // Permit the blocked blocks to import
  666. if atomic.LoadUint32(&blocked) > 0 {
  667. atomic.StoreUint32(&blocked, uint32(0))
  668. proceed <- struct{}{}
  669. }
  670. }
  671. // Check that we haven't pulled more blocks than available
  672. assertOwnChain(t, tester, targetBlocks+1)
  673. if err := <-errc; err != nil {
  674. t.Fatalf("block synchronization failed: %v", err)
  675. }
  676. }
  677. // Tests that simple synchronization against a forked chain works correctly. In
  678. // this test common ancestor lookup should *not* be short circuited, and a full
  679. // binary search should be executed.
  680. func TestForkedSync62(t *testing.T) { testForkedSync(t, 62, FullSync) }
  681. func TestForkedSync63Full(t *testing.T) { testForkedSync(t, 63, FullSync) }
  682. func TestForkedSync63Fast(t *testing.T) { testForkedSync(t, 63, FastSync) }
  683. func TestForkedSync64Full(t *testing.T) { testForkedSync(t, 64, FullSync) }
  684. func TestForkedSync64Fast(t *testing.T) { testForkedSync(t, 64, FastSync) }
  685. func TestForkedSync64Light(t *testing.T) { testForkedSync(t, 64, LightSync) }
  686. func testForkedSync(t *testing.T, protocol int, mode SyncMode) {
  687. t.Parallel()
  688. tester := newTester()
  689. defer tester.terminate()
  690. // Create a long enough forked chain
  691. common, fork := MaxHashFetch, 2*MaxHashFetch
  692. hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, true)
  693. tester.newPeer("fork A", protocol, hashesA, headersA, blocksA, receiptsA)
  694. tester.newPeer("fork B", protocol, hashesB, headersB, blocksB, receiptsB)
  695. // Synchronise with the peer and make sure all blocks were retrieved
  696. if err := tester.sync("fork A", nil, mode); err != nil {
  697. t.Fatalf("failed to synchronise blocks: %v", err)
  698. }
  699. assertOwnChain(t, tester, common+fork+1)
  700. // Synchronise with the second peer and make sure that fork is pulled too
  701. if err := tester.sync("fork B", nil, mode); err != nil {
  702. t.Fatalf("failed to synchronise blocks: %v", err)
  703. }
  704. assertOwnForkedChain(t, tester, common+1, []int{common + fork + 1, common + fork + 1})
  705. }
  706. // Tests that synchronising against a much shorter but much heavyer fork works
  707. // corrently and is not dropped.
  708. func TestHeavyForkedSync62(t *testing.T) { testHeavyForkedSync(t, 62, FullSync) }
  709. func TestHeavyForkedSync63Full(t *testing.T) { testHeavyForkedSync(t, 63, FullSync) }
  710. func TestHeavyForkedSync63Fast(t *testing.T) { testHeavyForkedSync(t, 63, FastSync) }
  711. func TestHeavyForkedSync64Full(t *testing.T) { testHeavyForkedSync(t, 64, FullSync) }
  712. func TestHeavyForkedSync64Fast(t *testing.T) { testHeavyForkedSync(t, 64, FastSync) }
  713. func TestHeavyForkedSync64Light(t *testing.T) { testHeavyForkedSync(t, 64, LightSync) }
  714. func testHeavyForkedSync(t *testing.T, protocol int, mode SyncMode) {
  715. t.Parallel()
  716. tester := newTester()
  717. defer tester.terminate()
  718. // Create a long enough forked chain
  719. common, fork := MaxHashFetch, 4*MaxHashFetch
  720. hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, false)
  721. tester.newPeer("light", protocol, hashesA, headersA, blocksA, receiptsA)
  722. tester.newPeer("heavy", protocol, hashesB[fork/2:], headersB, blocksB, receiptsB)
  723. // Synchronise with the peer and make sure all blocks were retrieved
  724. if err := tester.sync("light", nil, mode); err != nil {
  725. t.Fatalf("failed to synchronise blocks: %v", err)
  726. }
  727. assertOwnChain(t, tester, common+fork+1)
  728. // Synchronise with the second peer and make sure that fork is pulled too
  729. if err := tester.sync("heavy", nil, mode); err != nil {
  730. t.Fatalf("failed to synchronise blocks: %v", err)
  731. }
  732. assertOwnForkedChain(t, tester, common+1, []int{common + fork + 1, common + fork/2 + 1})
  733. }
  734. // Tests that chain forks are contained within a certain interval of the current
  735. // chain head, ensuring that malicious peers cannot waste resources by feeding
  736. // long dead chains.
  737. func TestBoundedForkedSync62(t *testing.T) { testBoundedForkedSync(t, 62, FullSync) }
  738. func TestBoundedForkedSync63Full(t *testing.T) { testBoundedForkedSync(t, 63, FullSync) }
  739. func TestBoundedForkedSync63Fast(t *testing.T) { testBoundedForkedSync(t, 63, FastSync) }
  740. func TestBoundedForkedSync64Full(t *testing.T) { testBoundedForkedSync(t, 64, FullSync) }
  741. func TestBoundedForkedSync64Fast(t *testing.T) { testBoundedForkedSync(t, 64, FastSync) }
  742. func TestBoundedForkedSync64Light(t *testing.T) { testBoundedForkedSync(t, 64, LightSync) }
  743. func testBoundedForkedSync(t *testing.T, protocol int, mode SyncMode) {
  744. t.Parallel()
  745. tester := newTester()
  746. defer tester.terminate()
  747. // Create a long enough forked chain
  748. common, fork := 13, int(MaxForkAncestry+17)
  749. hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, true)
  750. tester.newPeer("original", protocol, hashesA, headersA, blocksA, receiptsA)
  751. tester.newPeer("rewriter", protocol, hashesB, headersB, blocksB, receiptsB)
  752. // Synchronise with the peer and make sure all blocks were retrieved
  753. if err := tester.sync("original", nil, mode); err != nil {
  754. t.Fatalf("failed to synchronise blocks: %v", err)
  755. }
  756. assertOwnChain(t, tester, common+fork+1)
  757. // Synchronise with the second peer and ensure that the fork is rejected to being too old
  758. if err := tester.sync("rewriter", nil, mode); err != errInvalidAncestor {
  759. t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor)
  760. }
  761. }
  762. // Tests that chain forks are contained within a certain interval of the current
  763. // chain head for short but heavy forks too. These are a bit special because they
  764. // take different ancestor lookup paths.
  765. func TestBoundedHeavyForkedSync62(t *testing.T) { testBoundedHeavyForkedSync(t, 62, FullSync) }
  766. func TestBoundedHeavyForkedSync63Full(t *testing.T) { testBoundedHeavyForkedSync(t, 63, FullSync) }
  767. func TestBoundedHeavyForkedSync63Fast(t *testing.T) { testBoundedHeavyForkedSync(t, 63, FastSync) }
  768. func TestBoundedHeavyForkedSync64Full(t *testing.T) { testBoundedHeavyForkedSync(t, 64, FullSync) }
  769. func TestBoundedHeavyForkedSync64Fast(t *testing.T) { testBoundedHeavyForkedSync(t, 64, FastSync) }
  770. func TestBoundedHeavyForkedSync64Light(t *testing.T) { testBoundedHeavyForkedSync(t, 64, LightSync) }
  771. func testBoundedHeavyForkedSync(t *testing.T, protocol int, mode SyncMode) {
  772. t.Parallel()
  773. tester := newTester()
  774. defer tester.terminate()
  775. // Create a long enough forked chain
  776. common, fork := 13, int(MaxForkAncestry+17)
  777. hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, false)
  778. tester.newPeer("original", protocol, hashesA, headersA, blocksA, receiptsA)
  779. tester.newPeer("heavy-rewriter", protocol, hashesB[MaxForkAncestry-17:], headersB, blocksB, receiptsB) // Root the fork below the ancestor limit
  780. // Synchronise with the peer and make sure all blocks were retrieved
  781. if err := tester.sync("original", nil, mode); err != nil {
  782. t.Fatalf("failed to synchronise blocks: %v", err)
  783. }
  784. assertOwnChain(t, tester, common+fork+1)
  785. // Synchronise with the second peer and ensure that the fork is rejected to being too old
  786. if err := tester.sync("heavy-rewriter", nil, mode); err != errInvalidAncestor {
  787. t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor)
  788. }
  789. }
  790. // Tests that an inactive downloader will not accept incoming block headers and
  791. // bodies.
  792. func TestInactiveDownloader62(t *testing.T) {
  793. t.Parallel()
  794. tester := newTester()
  795. defer tester.terminate()
  796. // Check that neither block headers nor bodies are accepted
  797. if err := tester.downloader.DeliverHeaders("bad peer", []*types.Header{}); err != errNoSyncActive {
  798. t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
  799. }
  800. if err := tester.downloader.DeliverBodies("bad peer", [][]*types.Transaction{}, [][]*types.Header{}); err != errNoSyncActive {
  801. t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
  802. }
  803. }
  804. // Tests that an inactive downloader will not accept incoming block headers,
  805. // bodies and receipts.
  806. func TestInactiveDownloader63(t *testing.T) {
  807. t.Parallel()
  808. tester := newTester()
  809. defer tester.terminate()
  810. // Check that neither block headers nor bodies are accepted
  811. if err := tester.downloader.DeliverHeaders("bad peer", []*types.Header{}); err != errNoSyncActive {
  812. t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
  813. }
  814. if err := tester.downloader.DeliverBodies("bad peer", [][]*types.Transaction{}, [][]*types.Header{}); err != errNoSyncActive {
  815. t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
  816. }
  817. if err := tester.downloader.DeliverReceipts("bad peer", [][]*types.Receipt{}); err != errNoSyncActive {
  818. t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
  819. }
  820. }
  821. // Tests that a canceled download wipes all previously accumulated state.
  822. func TestCancel62(t *testing.T) { testCancel(t, 62, FullSync) }
  823. func TestCancel63Full(t *testing.T) { testCancel(t, 63, FullSync) }
  824. func TestCancel63Fast(t *testing.T) { testCancel(t, 63, FastSync) }
  825. func TestCancel64Full(t *testing.T) { testCancel(t, 64, FullSync) }
  826. func TestCancel64Fast(t *testing.T) { testCancel(t, 64, FastSync) }
  827. func TestCancel64Light(t *testing.T) { testCancel(t, 64, LightSync) }
  828. func testCancel(t *testing.T, protocol int, mode SyncMode) {
  829. t.Parallel()
  830. tester := newTester()
  831. defer tester.terminate()
  832. // Create a small enough block chain to download and the tester
  833. targetBlocks := blockCacheLimit - 15
  834. if targetBlocks >= MaxHashFetch {
  835. targetBlocks = MaxHashFetch - 15
  836. }
  837. if targetBlocks >= MaxHeaderFetch {
  838. targetBlocks = MaxHeaderFetch - 15
  839. }
  840. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  841. tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
  842. // Make sure canceling works with a pristine downloader
  843. tester.downloader.cancel()
  844. if !tester.downloader.queue.Idle() {
  845. t.Errorf("download queue not idle")
  846. }
  847. // Synchronise with the peer, but cancel afterwards
  848. if err := tester.sync("peer", nil, mode); err != nil {
  849. t.Fatalf("failed to synchronise blocks: %v", err)
  850. }
  851. tester.downloader.cancel()
  852. if !tester.downloader.queue.Idle() {
  853. t.Errorf("download queue not idle")
  854. }
  855. }
  856. // Tests that synchronisation from multiple peers works as intended (multi thread sanity test).
  857. func TestMultiSynchronisation62(t *testing.T) { testMultiSynchronisation(t, 62, FullSync) }
  858. func TestMultiSynchronisation63Full(t *testing.T) { testMultiSynchronisation(t, 63, FullSync) }
  859. func TestMultiSynchronisation63Fast(t *testing.T) { testMultiSynchronisation(t, 63, FastSync) }
  860. func TestMultiSynchronisation64Full(t *testing.T) { testMultiSynchronisation(t, 64, FullSync) }
  861. func TestMultiSynchronisation64Fast(t *testing.T) { testMultiSynchronisation(t, 64, FastSync) }
  862. func TestMultiSynchronisation64Light(t *testing.T) { testMultiSynchronisation(t, 64, LightSync) }
  863. func testMultiSynchronisation(t *testing.T, protocol int, mode SyncMode) {
  864. t.Parallel()
  865. tester := newTester()
  866. defer tester.terminate()
  867. // Create various peers with various parts of the chain
  868. targetPeers := 8
  869. targetBlocks := targetPeers*blockCacheLimit - 15
  870. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  871. for i := 0; i < targetPeers; i++ {
  872. id := fmt.Sprintf("peer #%d", i)
  873. tester.newPeer(id, protocol, hashes[i*blockCacheLimit:], headers, blocks, receipts)
  874. }
  875. if err := tester.sync("peer #0", nil, mode); err != nil {
  876. t.Fatalf("failed to synchronise blocks: %v", err)
  877. }
  878. assertOwnChain(t, tester, targetBlocks+1)
  879. }
  880. // Tests that synchronisations behave well in multi-version protocol environments
  881. // and not wreak havoc on other nodes in the network.
  882. func TestMultiProtoSynchronisation62(t *testing.T) { testMultiProtoSync(t, 62, FullSync) }
  883. func TestMultiProtoSynchronisation63Full(t *testing.T) { testMultiProtoSync(t, 63, FullSync) }
  884. func TestMultiProtoSynchronisation63Fast(t *testing.T) { testMultiProtoSync(t, 63, FastSync) }
  885. func TestMultiProtoSynchronisation64Full(t *testing.T) { testMultiProtoSync(t, 64, FullSync) }
  886. func TestMultiProtoSynchronisation64Fast(t *testing.T) { testMultiProtoSync(t, 64, FastSync) }
  887. func TestMultiProtoSynchronisation64Light(t *testing.T) { testMultiProtoSync(t, 64, LightSync) }
  888. func testMultiProtoSync(t *testing.T, protocol int, mode SyncMode) {
  889. t.Parallel()
  890. tester := newTester()
  891. defer tester.terminate()
  892. // Create a small enough block chain to download
  893. targetBlocks := blockCacheLimit - 15
  894. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  895. // Create peers of every type
  896. tester.newPeer("peer 62", 62, hashes, headers, blocks, nil)
  897. tester.newPeer("peer 63", 63, hashes, headers, blocks, receipts)
  898. tester.newPeer("peer 64", 64, hashes, headers, blocks, receipts)
  899. // Synchronise with the requested peer and make sure all blocks were retrieved
  900. if err := tester.sync(fmt.Sprintf("peer %d", protocol), nil, mode); err != nil {
  901. t.Fatalf("failed to synchronise blocks: %v", err)
  902. }
  903. assertOwnChain(t, tester, targetBlocks+1)
  904. // Check that no peers have been dropped off
  905. for _, version := range []int{62, 63, 64} {
  906. peer := fmt.Sprintf("peer %d", version)
  907. if _, ok := tester.peerHashes[peer]; !ok {
  908. t.Errorf("%s dropped", peer)
  909. }
  910. }
  911. }
  912. // Tests that if a block is empty (e.g. header only), no body request should be
  913. // made, and instead the header should be assembled into a whole block in itself.
  914. func TestEmptyShortCircuit62(t *testing.T) { testEmptyShortCircuit(t, 62, FullSync) }
  915. func TestEmptyShortCircuit63Full(t *testing.T) { testEmptyShortCircuit(t, 63, FullSync) }
  916. func TestEmptyShortCircuit63Fast(t *testing.T) { testEmptyShortCircuit(t, 63, FastSync) }
  917. func TestEmptyShortCircuit64Full(t *testing.T) { testEmptyShortCircuit(t, 64, FullSync) }
  918. func TestEmptyShortCircuit64Fast(t *testing.T) { testEmptyShortCircuit(t, 64, FastSync) }
  919. func TestEmptyShortCircuit64Light(t *testing.T) { testEmptyShortCircuit(t, 64, LightSync) }
  920. func testEmptyShortCircuit(t *testing.T, protocol int, mode SyncMode) {
  921. t.Parallel()
  922. tester := newTester()
  923. defer tester.terminate()
  924. // Create a block chain to download
  925. targetBlocks := 2*blockCacheLimit - 15
  926. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  927. tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
  928. // Instrument the downloader to signal body requests
  929. bodiesHave, receiptsHave := int32(0), int32(0)
  930. tester.downloader.bodyFetchHook = func(headers []*types.Header) {
  931. atomic.AddInt32(&bodiesHave, int32(len(headers)))
  932. }
  933. tester.downloader.receiptFetchHook = func(headers []*types.Header) {
  934. atomic.AddInt32(&receiptsHave, int32(len(headers)))
  935. }
  936. // Synchronise with the peer and make sure all blocks were retrieved
  937. if err := tester.sync("peer", nil, mode); err != nil {
  938. t.Fatalf("failed to synchronise blocks: %v", err)
  939. }
  940. assertOwnChain(t, tester, targetBlocks+1)
  941. // Validate the number of block bodies that should have been requested
  942. bodiesNeeded, receiptsNeeded := 0, 0
  943. for _, block := range blocks {
  944. if mode != LightSync && block != tester.genesis && (len(block.Transactions()) > 0 || len(block.Uncles()) > 0) {
  945. bodiesNeeded++
  946. }
  947. }
  948. for hash, receipt := range receipts {
  949. if mode == FastSync && len(receipt) > 0 && headers[hash].Number.Uint64() <= tester.downloader.queue.fastSyncPivot {
  950. receiptsNeeded++
  951. }
  952. }
  953. if int(bodiesHave) != bodiesNeeded {
  954. t.Errorf("body retrieval count mismatch: have %v, want %v", bodiesHave, bodiesNeeded)
  955. }
  956. if int(receiptsHave) != receiptsNeeded {
  957. t.Errorf("receipt retrieval count mismatch: have %v, want %v", receiptsHave, receiptsNeeded)
  958. }
  959. }
  960. // Tests that headers are enqueued continuously, preventing malicious nodes from
  961. // stalling the downloader by feeding gapped header chains.
  962. func TestMissingHeaderAttack62(t *testing.T) { testMissingHeaderAttack(t, 62, FullSync) }
  963. func TestMissingHeaderAttack63Full(t *testing.T) { testMissingHeaderAttack(t, 63, FullSync) }
  964. func TestMissingHeaderAttack63Fast(t *testing.T) { testMissingHeaderAttack(t, 63, FastSync) }
  965. func TestMissingHeaderAttack64Full(t *testing.T) { testMissingHeaderAttack(t, 64, FullSync) }
  966. func TestMissingHeaderAttack64Fast(t *testing.T) { testMissingHeaderAttack(t, 64, FastSync) }
  967. func TestMissingHeaderAttack64Light(t *testing.T) { testMissingHeaderAttack(t, 64, LightSync) }
  968. func testMissingHeaderAttack(t *testing.T, protocol int, mode SyncMode) {
  969. t.Parallel()
  970. tester := newTester()
  971. defer tester.terminate()
  972. // Create a small enough block chain to download
  973. targetBlocks := blockCacheLimit - 15
  974. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  975. // Attempt a full sync with an attacker feeding gapped headers
  976. tester.newPeer("attack", protocol, hashes, headers, blocks, receipts)
  977. missing := targetBlocks / 2
  978. delete(tester.peerHeaders["attack"], hashes[missing])
  979. if err := tester.sync("attack", nil, mode); err == nil {
  980. t.Fatalf("succeeded attacker synchronisation")
  981. }
  982. // Synchronise with the valid peer and make sure sync succeeds
  983. tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
  984. if err := tester.sync("valid", nil, mode); err != nil {
  985. t.Fatalf("failed to synchronise blocks: %v", err)
  986. }
  987. assertOwnChain(t, tester, targetBlocks+1)
  988. }
  989. // Tests that if requested headers are shifted (i.e. first is missing), the queue
  990. // detects the invalid numbering.
  991. func TestShiftedHeaderAttack62(t *testing.T) { testShiftedHeaderAttack(t, 62, FullSync) }
  992. func TestShiftedHeaderAttack63Full(t *testing.T) { testShiftedHeaderAttack(t, 63, FullSync) }
  993. func TestShiftedHeaderAttack63Fast(t *testing.T) { testShiftedHeaderAttack(t, 63, FastSync) }
  994. func TestShiftedHeaderAttack64Full(t *testing.T) { testShiftedHeaderAttack(t, 64, FullSync) }
  995. func TestShiftedHeaderAttack64Fast(t *testing.T) { testShiftedHeaderAttack(t, 64, FastSync) }
  996. func TestShiftedHeaderAttack64Light(t *testing.T) { testShiftedHeaderAttack(t, 64, LightSync) }
  997. func testShiftedHeaderAttack(t *testing.T, protocol int, mode SyncMode) {
  998. tester := newTester()
  999. defer tester.terminate()
  1000. // Create a small enough block chain to download
  1001. targetBlocks := blockCacheLimit - 15
  1002. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1003. // Attempt a full sync with an attacker feeding shifted headers
  1004. tester.newPeer("attack", protocol, hashes, headers, blocks, receipts)
  1005. delete(tester.peerHeaders["attack"], hashes[len(hashes)-2])
  1006. delete(tester.peerBlocks["attack"], hashes[len(hashes)-2])
  1007. delete(tester.peerReceipts["attack"], hashes[len(hashes)-2])
  1008. if err := tester.sync("attack", nil, mode); err == nil {
  1009. t.Fatalf("succeeded attacker synchronisation")
  1010. }
  1011. // Synchronise with the valid peer and make sure sync succeeds
  1012. tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
  1013. if err := tester.sync("valid", nil, mode); err != nil {
  1014. t.Fatalf("failed to synchronise blocks: %v", err)
  1015. }
  1016. assertOwnChain(t, tester, targetBlocks+1)
  1017. }
  1018. // Tests that upon detecting an invalid header, the recent ones are rolled back
  1019. // for various failure scenarios. Afterwards a full sync is attempted to make
  1020. // sure no state was corrupted.
  1021. func TestInvalidHeaderRollback63Fast(t *testing.T) { testInvalidHeaderRollback(t, 63, FastSync) }
  1022. func TestInvalidHeaderRollback64Fast(t *testing.T) { testInvalidHeaderRollback(t, 64, FastSync) }
  1023. func TestInvalidHeaderRollback64Light(t *testing.T) { testInvalidHeaderRollback(t, 64, LightSync) }
  1024. func testInvalidHeaderRollback(t *testing.T, protocol int, mode SyncMode) {
  1025. tester := newTester()
  1026. defer tester.terminate()
  1027. // Create a small enough block chain to download
  1028. targetBlocks := 3*fsHeaderSafetyNet + fsMinFullBlocks
  1029. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1030. // Attempt to sync with an attacker that feeds junk during the fast sync phase.
  1031. // This should result in the last fsHeaderSafetyNet headers being rolled back.
  1032. tester.newPeer("fast-attack", protocol, hashes, headers, blocks, receipts)
  1033. missing := fsHeaderSafetyNet + MaxHeaderFetch + 1
  1034. delete(tester.peerHeaders["fast-attack"], hashes[len(hashes)-missing])
  1035. if err := tester.sync("fast-attack", nil, mode); err == nil {
  1036. t.Fatalf("succeeded fast attacker synchronisation")
  1037. }
  1038. if head := tester.headHeader().Number.Int64(); int(head) > MaxHeaderFetch {
  1039. t.Errorf("rollback head mismatch: have %v, want at most %v", head, MaxHeaderFetch)
  1040. }
  1041. // Attempt to sync with an attacker that feeds junk during the block import phase.
  1042. // This should result in both the last fsHeaderSafetyNet number of headers being
  1043. // rolled back, and also the pivot point being reverted to a non-block status.
  1044. tester.newPeer("block-attack", protocol, hashes, headers, blocks, receipts)
  1045. missing = 3*fsHeaderSafetyNet + MaxHeaderFetch + 1
  1046. delete(tester.peerHeaders["fast-attack"], hashes[len(hashes)-missing]) // Make sure the fast-attacker doesn't fill in
  1047. delete(tester.peerHeaders["block-attack"], hashes[len(hashes)-missing])
  1048. if err := tester.sync("block-attack", nil, mode); err == nil {
  1049. t.Fatalf("succeeded block attacker synchronisation")
  1050. }
  1051. if head := tester.headHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
  1052. t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
  1053. }
  1054. if mode == FastSync {
  1055. if head := tester.headBlock().NumberU64(); head != 0 {
  1056. t.Errorf("fast sync pivot block #%d not rolled back", head)
  1057. }
  1058. }
  1059. // Attempt to sync with an attacker that withholds promised blocks after the
  1060. // fast sync pivot point. This could be a trial to leave the node with a bad
  1061. // but already imported pivot block.
  1062. tester.newPeer("withhold-attack", protocol, hashes, headers, blocks, receipts)
  1063. missing = 3*fsHeaderSafetyNet + MaxHeaderFetch + 1
  1064. tester.downloader.fsPivotFails = 0
  1065. tester.downloader.syncInitHook = func(uint64, uint64) {
  1066. for i := missing; i <= len(hashes); i++ {
  1067. delete(tester.peerHeaders["withhold-attack"], hashes[len(hashes)-i])
  1068. }
  1069. tester.downloader.syncInitHook = nil
  1070. }
  1071. if err := tester.sync("withhold-attack", nil, mode); err == nil {
  1072. t.Fatalf("succeeded withholding attacker synchronisation")
  1073. }
  1074. if head := tester.headHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
  1075. t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
  1076. }
  1077. if mode == FastSync {
  1078. if head := tester.headBlock().NumberU64(); head != 0 {
  1079. t.Errorf("fast sync pivot block #%d not rolled back", head)
  1080. }
  1081. }
  1082. tester.downloader.fsPivotFails = fsCriticalTrials
  1083. // Synchronise with the valid peer and make sure sync succeeds. Since the last
  1084. // rollback should also disable fast syncing for this process, verify that we
  1085. // did a fresh full sync. Note, we can't assert anything about the receipts
  1086. // since we won't purge the database of them, hence we can't use assertOwnChain.
  1087. tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
  1088. if err := tester.sync("valid", nil, mode); err != nil {
  1089. t.Fatalf("failed to synchronise blocks: %v", err)
  1090. }
  1091. if hs := len(tester.ownHeaders); hs != len(headers) {
  1092. t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, len(headers))
  1093. }
  1094. if mode != LightSync {
  1095. if bs := len(tester.ownBlocks); bs != len(blocks) {
  1096. t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, len(blocks))
  1097. }
  1098. }
  1099. }
  1100. // Tests that a peer advertising an high TD doesn't get to stall the downloader
  1101. // afterwards by not sending any useful hashes.
  1102. func TestHighTDStarvationAttack62(t *testing.T) { testHighTDStarvationAttack(t, 62, FullSync) }
  1103. func TestHighTDStarvationAttack63Full(t *testing.T) { testHighTDStarvationAttack(t, 63, FullSync) }
  1104. func TestHighTDStarvationAttack63Fast(t *testing.T) { testHighTDStarvationAttack(t, 63, FastSync) }
  1105. func TestHighTDStarvationAttack64Full(t *testing.T) { testHighTDStarvationAttack(t, 64, FullSync) }
  1106. func TestHighTDStarvationAttack64Fast(t *testing.T) { testHighTDStarvationAttack(t, 64, FastSync) }
  1107. func TestHighTDStarvationAttack64Light(t *testing.T) { testHighTDStarvationAttack(t, 64, LightSync) }
  1108. func testHighTDStarvationAttack(t *testing.T, protocol int, mode SyncMode) {
  1109. t.Parallel()
  1110. tester := newTester()
  1111. defer tester.terminate()
  1112. hashes, headers, blocks, receipts := tester.makeChain(0, 0, tester.genesis, nil, false)
  1113. tester.newPeer("attack", protocol, []common.Hash{hashes[0]}, headers, blocks, receipts)
  1114. if err := tester.sync("attack", big.NewInt(1000000), mode); err != errStallingPeer {
  1115. t.Fatalf("synchronisation error mismatch: have %v, want %v", err, errStallingPeer)
  1116. }
  1117. }
  1118. // Tests that misbehaving peers are disconnected, whilst behaving ones are not.
  1119. func TestBlockHeaderAttackerDropping62(t *testing.T) { testBlockHeaderAttackerDropping(t, 62) }
  1120. func TestBlockHeaderAttackerDropping63(t *testing.T) { testBlockHeaderAttackerDropping(t, 63) }
  1121. func TestBlockHeaderAttackerDropping64(t *testing.T) { testBlockHeaderAttackerDropping(t, 64) }
  1122. func testBlockHeaderAttackerDropping(t *testing.T, protocol int) {
  1123. // Define the disconnection requirement for individual hash fetch errors
  1124. tests := []struct {
  1125. result error
  1126. drop bool
  1127. }{
  1128. {nil, false}, // Sync succeeded, all is well
  1129. {errBusy, false}, // Sync is already in progress, no problem
  1130. {errUnknownPeer, false}, // Peer is unknown, was already dropped, don't double drop
  1131. {errBadPeer, true}, // Peer was deemed bad for some reason, drop it
  1132. {errStallingPeer, true}, // Peer was detected to be stalling, drop it
  1133. {errNoPeers, false}, // No peers to download from, soft race, no issue
  1134. {errTimeout, true}, // No hashes received in due time, drop the peer
  1135. {errEmptyHeaderSet, true}, // No headers were returned as a response, drop as it's a dead end
  1136. {errPeersUnavailable, true}, // Nobody had the advertised blocks, drop the advertiser
  1137. {errInvalidAncestor, true}, // Agreed upon ancestor is not acceptable, drop the chain rewriter
  1138. {errInvalidChain, true}, // Hash chain was detected as invalid, definitely drop
  1139. {errInvalidBlock, false}, // A bad peer was detected, but not the sync origin
  1140. {errInvalidBody, false}, // A bad peer was detected, but not the sync origin
  1141. {errInvalidReceipt, false}, // A bad peer was detected, but not the sync origin
  1142. {errCancelBlockFetch, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1143. {errCancelHeaderFetch, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1144. {errCancelBodyFetch, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1145. {errCancelReceiptFetch, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1146. {errCancelHeaderProcessing, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1147. {errCancelContentProcessing, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1148. }
  1149. // Run the tests and check disconnection status
  1150. tester := newTester()
  1151. defer tester.terminate()
  1152. for i, tt := range tests {
  1153. // Register a new peer and ensure it's presence
  1154. id := fmt.Sprintf("test %d", i)
  1155. if err := tester.newPeer(id, protocol, []common.Hash{tester.genesis.Hash()}, nil, nil, nil); err != nil {
  1156. t.Fatalf("test %d: failed to register new peer: %v", i, err)
  1157. }
  1158. if _, ok := tester.peerHashes[id]; !ok {
  1159. t.Fatalf("test %d: registered peer not found", i)
  1160. }
  1161. // Simulate a synchronisation and check the required result
  1162. tester.downloader.synchroniseMock = func(string, common.Hash) error { return tt.result }
  1163. tester.downloader.Synchronise(id, tester.genesis.Hash(), big.NewInt(1000), FullSync)
  1164. if _, ok := tester.peerHashes[id]; !ok != tt.drop {
  1165. t.Errorf("test %d: peer drop mismatch for %v: have %v, want %v", i, tt.result, !ok, tt.drop)
  1166. }
  1167. }
  1168. }
  1169. // Tests that synchronisation progress (origin block number, current block number
  1170. // and highest block number) is tracked and updated correctly.
  1171. func TestSyncProgress62(t *testing.T) { testSyncProgress(t, 62, FullSync) }
  1172. func TestSyncProgress63Full(t *testing.T) { testSyncProgress(t, 63, FullSync) }
  1173. func TestSyncProgress63Fast(t *testing.T) { testSyncProgress(t, 63, FastSync) }
  1174. func TestSyncProgress64Full(t *testing.T) { testSyncProgress(t, 64, FullSync) }
  1175. func TestSyncProgress64Fast(t *testing.T) { testSyncProgress(t, 64, FastSync) }
  1176. func TestSyncProgress64Light(t *testing.T) { testSyncProgress(t, 64, LightSync) }
  1177. func testSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1178. t.Parallel()
  1179. tester := newTester()
  1180. defer tester.terminate()
  1181. // Create a small enough block chain to download
  1182. targetBlocks := blockCacheLimit - 15
  1183. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1184. // Set a sync init hook to catch progress changes
  1185. starting := make(chan struct{})
  1186. progress := make(chan struct{})
  1187. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1188. starting <- struct{}{}
  1189. <-progress
  1190. }
  1191. // Retrieve the sync progress and ensure they are zero (pristine sync)
  1192. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
  1193. t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
  1194. }
  1195. // Synchronise half the blocks and check initial progress
  1196. tester.newPeer("peer-half", protocol, hashes[targetBlocks/2:], headers, blocks, receipts)
  1197. pending := new(sync.WaitGroup)
  1198. pending.Add(1)
  1199. go func() {
  1200. defer pending.Done()
  1201. if err := tester.sync("peer-half", nil, mode); err != nil {
  1202. t.Fatalf("failed to synchronise blocks: %v", err)
  1203. }
  1204. }()
  1205. <-starting
  1206. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(targetBlocks/2+1) {
  1207. t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, targetBlocks/2+1)
  1208. }
  1209. progress <- struct{}{}
  1210. pending.Wait()
  1211. // Synchronise all the blocks and check continuation progress
  1212. tester.newPeer("peer-full", protocol, hashes, headers, blocks, receipts)
  1213. pending.Add(1)
  1214. go func() {
  1215. defer pending.Done()
  1216. if err := tester.sync("peer-full", nil, mode); err != nil {
  1217. t.Fatalf("failed to synchronise blocks: %v", err)
  1218. }
  1219. }()
  1220. <-starting
  1221. if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(targetBlocks/2+1) || progress.CurrentBlock != uint64(targetBlocks/2+1) || progress.HighestBlock != uint64(targetBlocks) {
  1222. 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)
  1223. }
  1224. progress <- struct{}{}
  1225. pending.Wait()
  1226. // Check final progress after successful sync
  1227. if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(targetBlocks/2+1) || progress.CurrentBlock != uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
  1228. t.Fatalf("Final progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, targetBlocks/2+1, targetBlocks, targetBlocks)
  1229. }
  1230. }
  1231. // Tests that synchronisation progress (origin block number and highest block
  1232. // number) is tracked and updated correctly in case of a fork (or manual head
  1233. // revertal).
  1234. func TestForkedSyncProgress62(t *testing.T) { testForkedSyncProgress(t, 62, FullSync) }
  1235. func TestForkedSyncProgress63Full(t *testing.T) { testForkedSyncProgress(t, 63, FullSync) }
  1236. func TestForkedSyncProgress63Fast(t *testing.T) { testForkedSyncProgress(t, 63, FastSync) }
  1237. func TestForkedSyncProgress64Full(t *testing.T) { testForkedSyncProgress(t, 64, FullSync) }
  1238. func TestForkedSyncProgress64Fast(t *testing.T) { testForkedSyncProgress(t, 64, FastSync) }
  1239. func TestForkedSyncProgress64Light(t *testing.T) { testForkedSyncProgress(t, 64, LightSync) }
  1240. func testForkedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1241. t.Parallel()
  1242. tester := newTester()
  1243. defer tester.terminate()
  1244. // Create a forked chain to simulate origin revertal
  1245. common, fork := MaxHashFetch, 2*MaxHashFetch
  1246. hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, true)
  1247. // Set a sync init hook to catch progress changes
  1248. starting := make(chan struct{})
  1249. progress := make(chan struct{})
  1250. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1251. starting <- struct{}{}
  1252. <-progress
  1253. }
  1254. // Retrieve the sync progress and ensure they are zero (pristine sync)
  1255. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
  1256. t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
  1257. }
  1258. // Synchronise with one of the forks and check progress
  1259. tester.newPeer("fork A", protocol, hashesA, headersA, blocksA, receiptsA)
  1260. pending := new(sync.WaitGroup)
  1261. pending.Add(1)
  1262. go func() {
  1263. defer pending.Done()
  1264. if err := tester.sync("fork A", nil, mode); err != nil {
  1265. t.Fatalf("failed to synchronise blocks: %v", err)
  1266. }
  1267. }()
  1268. <-starting
  1269. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(len(hashesA)-1) {
  1270. t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, len(hashesA)-1)
  1271. }
  1272. progress <- struct{}{}
  1273. pending.Wait()
  1274. // Simulate a successful sync above the fork
  1275. tester.downloader.syncStatsChainOrigin = tester.downloader.syncStatsChainHeight
  1276. // Synchronise with the second fork and check progress resets
  1277. tester.newPeer("fork B", protocol, hashesB, headersB, blocksB, receiptsB)
  1278. pending.Add(1)
  1279. go func() {
  1280. defer pending.Done()
  1281. if err := tester.sync("fork B", nil, mode); err != nil {
  1282. t.Fatalf("failed to synchronise blocks: %v", err)
  1283. }
  1284. }()
  1285. <-starting
  1286. if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(common) || progress.CurrentBlock != uint64(len(hashesA)-1) || progress.HighestBlock != uint64(len(hashesB)-1) {
  1287. 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)
  1288. }
  1289. progress <- struct{}{}
  1290. pending.Wait()
  1291. // Check final progress after successful sync
  1292. if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(common) || progress.CurrentBlock != uint64(len(hashesB)-1) || progress.HighestBlock != uint64(len(hashesB)-1) {
  1293. 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)
  1294. }
  1295. }
  1296. // Tests that if synchronisation is aborted due to some failure, then the progress
  1297. // origin is not updated in the next sync cycle, as it should be considered the
  1298. // continuation of the previous sync and not a new instance.
  1299. func TestFailedSyncProgress62(t *testing.T) { testFailedSyncProgress(t, 62, FullSync) }
  1300. func TestFailedSyncProgress63Full(t *testing.T) { testFailedSyncProgress(t, 63, FullSync) }
  1301. func TestFailedSyncProgress63Fast(t *testing.T) { testFailedSyncProgress(t, 63, FastSync) }
  1302. func TestFailedSyncProgress64Full(t *testing.T) { testFailedSyncProgress(t, 64, FullSync) }
  1303. func TestFailedSyncProgress64Fast(t *testing.T) { testFailedSyncProgress(t, 64, FastSync) }
  1304. func TestFailedSyncProgress64Light(t *testing.T) { testFailedSyncProgress(t, 64, LightSync) }
  1305. func testFailedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1306. t.Parallel()
  1307. tester := newTester()
  1308. defer tester.terminate()
  1309. // Create a small enough block chain to download
  1310. targetBlocks := blockCacheLimit - 15
  1311. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1312. // Set a sync init hook to catch progress changes
  1313. starting := make(chan struct{})
  1314. progress := make(chan struct{})
  1315. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1316. starting <- struct{}{}
  1317. <-progress
  1318. }
  1319. // Retrieve the sync progress and ensure they are zero (pristine sync)
  1320. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
  1321. t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
  1322. }
  1323. // Attempt a full sync with a faulty peer
  1324. tester.newPeer("faulty", protocol, hashes, headers, blocks, receipts)
  1325. missing := targetBlocks / 2
  1326. delete(tester.peerHeaders["faulty"], hashes[missing])
  1327. delete(tester.peerBlocks["faulty"], hashes[missing])
  1328. delete(tester.peerReceipts["faulty"], hashes[missing])
  1329. pending := new(sync.WaitGroup)
  1330. pending.Add(1)
  1331. go func() {
  1332. defer pending.Done()
  1333. if err := tester.sync("faulty", nil, mode); err == nil {
  1334. t.Fatalf("succeeded faulty synchronisation")
  1335. }
  1336. }()
  1337. <-starting
  1338. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(targetBlocks) {
  1339. t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, targetBlocks)
  1340. }
  1341. progress <- struct{}{}
  1342. pending.Wait()
  1343. // Synchronise with a good peer and check that the progress origin remind the same after a failure
  1344. tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
  1345. pending.Add(1)
  1346. go func() {
  1347. defer pending.Done()
  1348. if err := tester.sync("valid", nil, mode); err != nil {
  1349. t.Fatalf("failed to synchronise blocks: %v", err)
  1350. }
  1351. }()
  1352. <-starting
  1353. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock > uint64(targetBlocks/2) || progress.HighestBlock != uint64(targetBlocks) {
  1354. t.Fatalf("Completing progress mismatch: have %v/%v/%v, want %v/0-%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, targetBlocks/2, targetBlocks)
  1355. }
  1356. progress <- struct{}{}
  1357. pending.Wait()
  1358. // Check final progress after successful sync
  1359. if progress := tester.downloader.Progress(); progress.StartingBlock > uint64(targetBlocks/2) || progress.CurrentBlock != uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
  1360. t.Fatalf("Final progress mismatch: have %v/%v/%v, want 0-%v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, targetBlocks/2, targetBlocks, targetBlocks)
  1361. }
  1362. }
  1363. // Tests that if an attacker fakes a chain height, after the attack is detected,
  1364. // the progress height is successfully reduced at the next sync invocation.
  1365. func TestFakedSyncProgress62(t *testing.T) { testFakedSyncProgress(t, 62, FullSync) }
  1366. func TestFakedSyncProgress63Full(t *testing.T) { testFakedSyncProgress(t, 63, FullSync) }
  1367. func TestFakedSyncProgress63Fast(t *testing.T) { testFakedSyncProgress(t, 63, FastSync) }
  1368. func TestFakedSyncProgress64Full(t *testing.T) { testFakedSyncProgress(t, 64, FullSync) }
  1369. func TestFakedSyncProgress64Fast(t *testing.T) { testFakedSyncProgress(t, 64, FastSync) }
  1370. func TestFakedSyncProgress64Light(t *testing.T) { testFakedSyncProgress(t, 64, LightSync) }
  1371. func testFakedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1372. t.Parallel()
  1373. tester := newTester()
  1374. defer tester.terminate()
  1375. // Create a small block chain
  1376. targetBlocks := blockCacheLimit - 15
  1377. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks+3, 0, tester.genesis, nil, false)
  1378. // Set a sync init hook to catch progress changes
  1379. starting := make(chan struct{})
  1380. progress := make(chan struct{})
  1381. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1382. starting <- struct{}{}
  1383. <-progress
  1384. }
  1385. // Retrieve the sync progress and ensure they are zero (pristine sync)
  1386. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
  1387. t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
  1388. }
  1389. // Create and sync with an attacker that promises a higher chain than available
  1390. tester.newPeer("attack", protocol, hashes, headers, blocks, receipts)
  1391. for i := 1; i < 3; i++ {
  1392. delete(tester.peerHeaders["attack"], hashes[i])
  1393. delete(tester.peerBlocks["attack"], hashes[i])
  1394. delete(tester.peerReceipts["attack"], hashes[i])
  1395. }
  1396. pending := new(sync.WaitGroup)
  1397. pending.Add(1)
  1398. go func() {
  1399. defer pending.Done()
  1400. if err := tester.sync("attack", nil, mode); err == nil {
  1401. t.Fatalf("succeeded attacker synchronisation")
  1402. }
  1403. }()
  1404. <-starting
  1405. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(targetBlocks+3) {
  1406. t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, targetBlocks+3)
  1407. }
  1408. progress <- struct{}{}
  1409. pending.Wait()
  1410. // Synchronise with a good peer and check that the progress height has been reduced to the true value
  1411. tester.newPeer("valid", protocol, hashes[3:], headers, blocks, receipts)
  1412. pending.Add(1)
  1413. go func() {
  1414. defer pending.Done()
  1415. if err := tester.sync("valid", nil, mode); err != nil {
  1416. t.Fatalf("failed to synchronise blocks: %v", err)
  1417. }
  1418. }()
  1419. <-starting
  1420. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock > uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
  1421. t.Fatalf("Completing progress mismatch: have %v/%v/%v, want %v/0-%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, targetBlocks, targetBlocks)
  1422. }
  1423. progress <- struct{}{}
  1424. pending.Wait()
  1425. // Check final progress after successful sync
  1426. if progress := tester.downloader.Progress(); progress.StartingBlock > uint64(targetBlocks) || progress.CurrentBlock != uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
  1427. t.Fatalf("Final progress mismatch: have %v/%v/%v, want 0-%v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, targetBlocks, targetBlocks, targetBlocks)
  1428. }
  1429. }
  1430. // This test reproduces an issue where unexpected deliveries would
  1431. // block indefinitely if they arrived at the right time.
  1432. func TestDeliverHeadersHang62(t *testing.T) { testDeliverHeadersHang(t, 62, FullSync) }
  1433. func TestDeliverHeadersHang63Full(t *testing.T) { testDeliverHeadersHang(t, 63, FullSync) }
  1434. func TestDeliverHeadersHang63Fast(t *testing.T) { testDeliverHeadersHang(t, 63, FastSync) }
  1435. func TestDeliverHeadersHang64Full(t *testing.T) { testDeliverHeadersHang(t, 64, FullSync) }
  1436. func TestDeliverHeadersHang64Fast(t *testing.T) { testDeliverHeadersHang(t, 64, FastSync) }
  1437. func TestDeliverHeadersHang64Light(t *testing.T) { testDeliverHeadersHang(t, 64, LightSync) }
  1438. func testDeliverHeadersHang(t *testing.T, protocol int, mode SyncMode) {
  1439. t.Parallel()
  1440. master := newTester()
  1441. defer master.terminate()
  1442. hashes, headers, blocks, receipts := master.makeChain(5, 0, master.genesis, nil, false)
  1443. fakeHeads := []*types.Header{{}, {}, {}, {}}
  1444. for i := 0; i < 200; i++ {
  1445. tester := newTester()
  1446. tester.peerDb = master.peerDb
  1447. tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
  1448. // Whenever the downloader requests headers, flood it with
  1449. // a lot of unrequested header deliveries.
  1450. tester.downloader.peers.peers["peer"].getAbsHeaders = func(from uint64, count, skip int, reverse bool) error {
  1451. deliveriesDone := make(chan struct{}, 500)
  1452. for i := 0; i < cap(deliveriesDone); i++ {
  1453. peer := fmt.Sprintf("fake-peer%d", i)
  1454. go func() {
  1455. tester.downloader.DeliverHeaders(peer, fakeHeads)
  1456. deliveriesDone <- struct{}{}
  1457. }()
  1458. }
  1459. // Deliver the actual requested headers.
  1460. impl := tester.peerGetAbsHeadersFn("peer", 0)
  1461. go impl(from, count, skip, reverse)
  1462. // None of the extra deliveries should block.
  1463. timeout := time.After(15 * time.Second)
  1464. for i := 0; i < cap(deliveriesDone); i++ {
  1465. select {
  1466. case <-deliveriesDone:
  1467. case <-timeout:
  1468. panic("blocked")
  1469. }
  1470. }
  1471. return nil
  1472. }
  1473. if err := tester.sync("peer", nil, mode); err != nil {
  1474. t.Errorf("sync failed: %v", err)
  1475. }
  1476. tester.terminate()
  1477. }
  1478. }
  1479. // Tests that if fast sync aborts in the critical section, it can restart a few
  1480. // times before giving up.
  1481. func TestFastCriticalRestartsFail63(t *testing.T) { testFastCriticalRestarts(t, 63, false) }
  1482. func TestFastCriticalRestartsFail64(t *testing.T) { testFastCriticalRestarts(t, 64, false) }
  1483. func TestFastCriticalRestartsCont63(t *testing.T) { testFastCriticalRestarts(t, 63, true) }
  1484. func TestFastCriticalRestartsCont64(t *testing.T) { testFastCriticalRestarts(t, 64, true) }
  1485. func testFastCriticalRestarts(t *testing.T, protocol int, progress bool) {
  1486. t.Parallel()
  1487. tester := newTester()
  1488. defer tester.terminate()
  1489. // Create a large enough blockchin to actually fast sync on
  1490. targetBlocks := fsMinFullBlocks + 2*fsPivotInterval - 15
  1491. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1492. // Create a tester peer with the critical section state roots missing (force failures)
  1493. tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
  1494. for i := 0; i < fsPivotInterval; i++ {
  1495. tester.peerMissingStates["peer"][headers[hashes[fsMinFullBlocks+i]].Root] = true
  1496. }
  1497. tester.downloader.dropPeer = func(id string) {} // We reuse the same "faulty" peer throughout the test
  1498. // Synchronise with the peer a few times and make sure they fail until the retry limit
  1499. for i := 0; i < int(fsCriticalTrials)-1; i++ {
  1500. // Attempt a sync and ensure it fails properly
  1501. if err := tester.sync("peer", nil, FastSync); err == nil {
  1502. t.Fatalf("failing fast sync succeeded: %v", err)
  1503. }
  1504. time.Sleep(100 * time.Millisecond) // Make sure no in-flight requests remain
  1505. // If it's the first failure, pivot should be locked => reenable all others to detect pivot changes
  1506. if i == 0 {
  1507. tester.lock.Lock()
  1508. tester.peerMissingStates["peer"] = map[common.Hash]bool{tester.downloader.fsPivotLock.Root: true}
  1509. tester.lock.Unlock()
  1510. }
  1511. }
  1512. // Return all nodes if we're testing fast sync progression
  1513. if progress {
  1514. tester.lock.Lock()
  1515. tester.peerMissingStates["peer"] = map[common.Hash]bool{}
  1516. tester.lock.Unlock()
  1517. if err := tester.sync("peer", nil, FastSync); err != nil {
  1518. t.Fatalf("failed to synchronise blocks in progressed fast sync: %v", err)
  1519. }
  1520. time.Sleep(100 * time.Millisecond) // Make sure no in-flight requests remain
  1521. if fails := atomic.LoadUint32(&tester.downloader.fsPivotFails); fails != 1 {
  1522. t.Fatalf("progressed pivot trial count mismatch: have %v, want %v", fails, 1)
  1523. }
  1524. } else {
  1525. if err := tester.sync("peer", nil, FastSync); err == nil {
  1526. t.Fatalf("succeeded to synchronise blocks in failed fast sync")
  1527. }
  1528. time.Sleep(100 * time.Millisecond) // Make sure no in-flight requests remain
  1529. if fails := atomic.LoadUint32(&tester.downloader.fsPivotFails); fails != fsCriticalTrials {
  1530. t.Fatalf("failed pivot trial count mismatch: have %v, want %v", fails, fsCriticalTrials)
  1531. }
  1532. }
  1533. // Retry limit exhausted, downloader will switch to full sync, should succeed
  1534. if err := tester.sync("peer", nil, FastSync); err != nil {
  1535. t.Fatalf("failed to synchronise blocks in slow sync: %v", err)
  1536. }
  1537. assertOwnChain(t, tester, targetBlocks+1)
  1538. }