downloader_test.go 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860
  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/consensus/ethash"
  27. "github.com/ethereum/go-ethereum/core"
  28. "github.com/ethereum/go-ethereum/core/state"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/crypto"
  31. "github.com/ethereum/go-ethereum/ethdb"
  32. "github.com/ethereum/go-ethereum/event"
  33. "github.com/ethereum/go-ethereum/params"
  34. "github.com/ethereum/go-ethereum/trie"
  35. )
  36. var (
  37. testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  38. testAddress = crypto.PubkeyToAddress(testKey.PublicKey)
  39. )
  40. // Reduce some of the parameters to make the tester faster.
  41. func init() {
  42. MaxForkAncestry = uint64(10000)
  43. blockCacheLimit = 1024
  44. fsCriticalTrials = 10
  45. }
  46. // downloadTester is a test simulator for mocking out local block chain.
  47. type downloadTester struct {
  48. downloader *Downloader
  49. genesis *types.Block // Genesis blocks used by the tester and peers
  50. stateDb ethdb.Database // Database used by the tester for syncing from peers
  51. peerDb ethdb.Database // Database of the peers containing all data
  52. ownHashes []common.Hash // Hash chain belonging to the tester
  53. ownHeaders map[common.Hash]*types.Header // Headers belonging to the tester
  54. ownBlocks map[common.Hash]*types.Block // Blocks belonging to the tester
  55. ownReceipts map[common.Hash]types.Receipts // Receipts belonging to the tester
  56. ownChainTd map[common.Hash]*big.Int // Total difficulties of the blocks in the local chain
  57. peerHashes map[string][]common.Hash // Hash chain belonging to different test peers
  58. peerHeaders map[string]map[common.Hash]*types.Header // Headers belonging to different test peers
  59. peerBlocks map[string]map[common.Hash]*types.Block // Blocks belonging to different test peers
  60. peerReceipts map[string]map[common.Hash]types.Receipts // Receipts belonging to different test peers
  61. peerChainTds map[string]map[common.Hash]*big.Int // Total difficulties of the blocks in the peer chains
  62. peerMissingStates map[string]map[common.Hash]bool // State entries that fast sync should not return
  63. lock sync.RWMutex
  64. }
  65. // newTester creates a new downloader test mocker.
  66. func newTester() *downloadTester {
  67. testdb, _ := ethdb.NewMemDatabase()
  68. genesis := core.GenesisBlockForTesting(testdb, testAddress, big.NewInt(1000000000))
  69. tester := &downloadTester{
  70. genesis: genesis,
  71. peerDb: testdb,
  72. ownHashes: []common.Hash{genesis.Hash()},
  73. ownHeaders: map[common.Hash]*types.Header{genesis.Hash(): genesis.Header()},
  74. ownBlocks: map[common.Hash]*types.Block{genesis.Hash(): genesis},
  75. ownReceipts: map[common.Hash]types.Receipts{genesis.Hash(): nil},
  76. ownChainTd: map[common.Hash]*big.Int{genesis.Hash(): genesis.Difficulty()},
  77. peerHashes: make(map[string][]common.Hash),
  78. peerHeaders: make(map[string]map[common.Hash]*types.Header),
  79. peerBlocks: make(map[string]map[common.Hash]*types.Block),
  80. peerReceipts: make(map[string]map[common.Hash]types.Receipts),
  81. peerChainTds: make(map[string]map[common.Hash]*big.Int),
  82. peerMissingStates: make(map[string]map[common.Hash]bool),
  83. }
  84. tester.stateDb, _ = ethdb.NewMemDatabase()
  85. tester.stateDb.Put(genesis.Root().Bytes(), []byte{0x00})
  86. tester.downloader = New(FullSync, tester.stateDb, new(event.TypeMux), tester, nil, tester.dropPeer)
  87. return tester
  88. }
  89. // makeChain creates a chain of n blocks starting at and including parent.
  90. // the returned hash chain is ordered head->parent. In addition, every 3rd block
  91. // contains a transaction and every 5th an uncle to allow testing correct block
  92. // reassembly.
  93. 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) {
  94. // Generate the block chain
  95. blocks, receipts := core.GenerateChain(params.TestChainConfig, parent, ethash.NewFaker(), dl.peerDb, n, func(i int, block *core.BlockGen) {
  96. block.SetCoinbase(common.Address{seed})
  97. // If a heavy chain is requested, delay blocks to raise difficulty
  98. if heavy {
  99. block.OffsetTime(-1)
  100. }
  101. // If the block number is multiple of 3, send a bonus transaction to the miner
  102. if parent == dl.genesis && i%3 == 0 {
  103. signer := types.MakeSigner(params.TestChainConfig, block.Number())
  104. tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, nil, nil), signer, 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, number uint64) bool {
  193. return dl.GetHeaderByHash(hash) != nil
  194. }
  195. // HasBlockAndState checks if a block and associated state is present in the testers canonical chain.
  196. func (dl *downloadTester) HasBlockAndState(hash common.Hash) bool {
  197. block := dl.GetBlockByHash(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) GetHeaderByHash(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) GetBlockByHash(hash common.Hash) *types.Block {
  212. dl.lock.RLock()
  213. defer dl.lock.RUnlock()
  214. return dl.ownBlocks[hash]
  215. }
  216. // CurrentHeader retrieves the current head header from the canonical chain.
  217. func (dl *downloadTester) CurrentHeader() *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. // CurrentBlock retrieves the current head block from the canonical chain.
  228. func (dl *downloadTester) CurrentBlock() *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. // CurrentFastBlock retrieves the current head fast-sync block from the canonical chain.
  241. func (dl *downloadTester) CurrentFastBlock() *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. // FastSyncCommitHead manually sets the head block to a given hash.
  252. func (dl *downloadTester) FastSyncCommitHead(hash common.Hash) error {
  253. // For now only check that the state trie is correct
  254. if block := dl.GetBlockByHash(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. // GetTdByHash retrieves the block's total difficulty from the canonical chain.
  261. func (dl *downloadTester) GetTdByHash(hash common.Hash) *big.Int {
  262. dl.lock.RLock()
  263. defer dl.lock.RUnlock()
  264. return dl.ownChainTd[hash]
  265. }
  266. // InsertHeaderChain injects a new batch of headers into the simulated chain.
  267. func (dl *downloadTester) InsertHeaderChain(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. // InsertChain injects a new batch of blocks into the simulated chain.
  294. func (dl *downloadTester) InsertChain(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. // InsertReceiptChain injects a new batch of receipts into the simulated chain.
  314. func (dl *downloadTester) InsertReceiptChain(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 = dl.downloader.RegisterPeer(id, version, &downloadTesterPeer{dl: dl, id: id, delay: delay})
  354. if err == nil {
  355. // Assign the owned hashes, headers and blocks to the peer (deep copy)
  356. dl.peerHashes[id] = make([]common.Hash, len(hashes))
  357. copy(dl.peerHashes[id], hashes)
  358. dl.peerHeaders[id] = make(map[common.Hash]*types.Header)
  359. dl.peerBlocks[id] = make(map[common.Hash]*types.Block)
  360. dl.peerReceipts[id] = make(map[common.Hash]types.Receipts)
  361. dl.peerChainTds[id] = make(map[common.Hash]*big.Int)
  362. dl.peerMissingStates[id] = make(map[common.Hash]bool)
  363. genesis := hashes[len(hashes)-1]
  364. if header := headers[genesis]; header != nil {
  365. dl.peerHeaders[id][genesis] = header
  366. dl.peerChainTds[id][genesis] = header.Difficulty
  367. }
  368. if block := blocks[genesis]; block != nil {
  369. dl.peerBlocks[id][genesis] = block
  370. dl.peerChainTds[id][genesis] = block.Difficulty()
  371. }
  372. for i := len(hashes) - 2; i >= 0; i-- {
  373. hash := hashes[i]
  374. if header, ok := headers[hash]; ok {
  375. dl.peerHeaders[id][hash] = header
  376. if _, ok := dl.peerHeaders[id][header.ParentHash]; ok {
  377. dl.peerChainTds[id][hash] = new(big.Int).Add(header.Difficulty, dl.peerChainTds[id][header.ParentHash])
  378. }
  379. }
  380. if block, ok := blocks[hash]; ok {
  381. dl.peerBlocks[id][hash] = block
  382. if _, ok := dl.peerBlocks[id][block.ParentHash()]; ok {
  383. dl.peerChainTds[id][hash] = new(big.Int).Add(block.Difficulty(), dl.peerChainTds[id][block.ParentHash()])
  384. }
  385. }
  386. if receipt, ok := receipts[hash]; ok {
  387. dl.peerReceipts[id][hash] = receipt
  388. }
  389. }
  390. }
  391. return err
  392. }
  393. // dropPeer simulates a hard peer removal from the connection pool.
  394. func (dl *downloadTester) dropPeer(id string) {
  395. dl.lock.Lock()
  396. defer dl.lock.Unlock()
  397. delete(dl.peerHashes, id)
  398. delete(dl.peerHeaders, id)
  399. delete(dl.peerBlocks, id)
  400. delete(dl.peerChainTds, id)
  401. dl.downloader.UnregisterPeer(id)
  402. }
  403. type downloadTesterPeer struct {
  404. dl *downloadTester
  405. id string
  406. delay time.Duration
  407. lock sync.RWMutex
  408. }
  409. // setDelay is a thread safe setter for the network delay value.
  410. func (dlp *downloadTesterPeer) setDelay(delay time.Duration) {
  411. dlp.lock.Lock()
  412. defer dlp.lock.Unlock()
  413. dlp.delay = delay
  414. }
  415. // waitDelay is a thread safe way to sleep for the configured time.
  416. func (dlp *downloadTesterPeer) waitDelay() {
  417. dlp.lock.RLock()
  418. delay := dlp.delay
  419. dlp.lock.RUnlock()
  420. time.Sleep(delay)
  421. }
  422. // Head constructs a function to retrieve a peer's current head hash
  423. // and total difficulty.
  424. func (dlp *downloadTesterPeer) Head() (common.Hash, *big.Int) {
  425. dlp.dl.lock.RLock()
  426. defer dlp.dl.lock.RUnlock()
  427. return dlp.dl.peerHashes[dlp.id][0], nil
  428. }
  429. // RequestHeadersByHash constructs a GetBlockHeaders function based on a hashed
  430. // origin; associated with a particular peer in the download tester. The returned
  431. // function can be used to retrieve batches of headers from the particular peer.
  432. func (dlp *downloadTesterPeer) RequestHeadersByHash(origin common.Hash, amount int, skip int, reverse bool) error {
  433. // Find the canonical number of the hash
  434. dlp.dl.lock.RLock()
  435. number := uint64(0)
  436. for num, hash := range dlp.dl.peerHashes[dlp.id] {
  437. if hash == origin {
  438. number = uint64(len(dlp.dl.peerHashes[dlp.id]) - num - 1)
  439. break
  440. }
  441. }
  442. dlp.dl.lock.RUnlock()
  443. // Use the absolute header fetcher to satisfy the query
  444. return dlp.RequestHeadersByNumber(number, amount, skip, reverse)
  445. }
  446. // RequestHeadersByNumber constructs a GetBlockHeaders function based on a numbered
  447. // origin; associated with a particular peer in the download tester. The returned
  448. // function can be used to retrieve batches of headers from the particular peer.
  449. func (dlp *downloadTesterPeer) RequestHeadersByNumber(origin uint64, amount int, skip int, reverse bool) error {
  450. dlp.waitDelay()
  451. dlp.dl.lock.RLock()
  452. defer dlp.dl.lock.RUnlock()
  453. // Gather the next batch of headers
  454. hashes := dlp.dl.peerHashes[dlp.id]
  455. headers := dlp.dl.peerHeaders[dlp.id]
  456. result := make([]*types.Header, 0, amount)
  457. for i := 0; i < amount && len(hashes)-int(origin)-1-i*(skip+1) >= 0; i++ {
  458. if header, ok := headers[hashes[len(hashes)-int(origin)-1-i*(skip+1)]]; ok {
  459. result = append(result, header)
  460. }
  461. }
  462. // Delay delivery a bit to allow attacks to unfold
  463. go func() {
  464. time.Sleep(time.Millisecond)
  465. dlp.dl.downloader.DeliverHeaders(dlp.id, result)
  466. }()
  467. return nil
  468. }
  469. // RequestBodies constructs a getBlockBodies method associated with a particular
  470. // peer in the download tester. The returned function can be used to retrieve
  471. // batches of block bodies from the particularly requested peer.
  472. func (dlp *downloadTesterPeer) RequestBodies(hashes []common.Hash) error {
  473. dlp.waitDelay()
  474. dlp.dl.lock.RLock()
  475. defer dlp.dl.lock.RUnlock()
  476. blocks := dlp.dl.peerBlocks[dlp.id]
  477. transactions := make([][]*types.Transaction, 0, len(hashes))
  478. uncles := make([][]*types.Header, 0, len(hashes))
  479. for _, hash := range hashes {
  480. if block, ok := blocks[hash]; ok {
  481. transactions = append(transactions, block.Transactions())
  482. uncles = append(uncles, block.Uncles())
  483. }
  484. }
  485. go dlp.dl.downloader.DeliverBodies(dlp.id, transactions, uncles)
  486. return nil
  487. }
  488. // RequestReceipts constructs a getReceipts method associated with a particular
  489. // peer in the download tester. The returned function can be used to retrieve
  490. // batches of block receipts from the particularly requested peer.
  491. func (dlp *downloadTesterPeer) RequestReceipts(hashes []common.Hash) error {
  492. dlp.waitDelay()
  493. dlp.dl.lock.RLock()
  494. defer dlp.dl.lock.RUnlock()
  495. receipts := dlp.dl.peerReceipts[dlp.id]
  496. results := make([][]*types.Receipt, 0, len(hashes))
  497. for _, hash := range hashes {
  498. if receipt, ok := receipts[hash]; ok {
  499. results = append(results, receipt)
  500. }
  501. }
  502. go dlp.dl.downloader.DeliverReceipts(dlp.id, results)
  503. return nil
  504. }
  505. // RequestNodeData constructs a getNodeData method associated with a particular
  506. // peer in the download tester. The returned function can be used to retrieve
  507. // batches of node state data from the particularly requested peer.
  508. func (dlp *downloadTesterPeer) RequestNodeData(hashes []common.Hash) error {
  509. dlp.waitDelay()
  510. dlp.dl.lock.RLock()
  511. defer dlp.dl.lock.RUnlock()
  512. results := make([][]byte, 0, len(hashes))
  513. for _, hash := range hashes {
  514. if data, err := dlp.dl.peerDb.Get(hash.Bytes()); err == nil {
  515. if !dlp.dl.peerMissingStates[dlp.id][hash] {
  516. results = append(results, data)
  517. }
  518. }
  519. }
  520. go dlp.dl.downloader.DeliverNodeData(dlp.id, results)
  521. return nil
  522. }
  523. // assertOwnChain checks if the local chain contains the correct number of items
  524. // of the various chain components.
  525. func assertOwnChain(t *testing.T, tester *downloadTester, length int) {
  526. assertOwnForkedChain(t, tester, 1, []int{length})
  527. }
  528. // assertOwnForkedChain checks if the local forked chain contains the correct
  529. // number of items of the various chain components.
  530. func assertOwnForkedChain(t *testing.T, tester *downloadTester, common int, lengths []int) {
  531. // Initialize the counters for the first fork
  532. headers, blocks := lengths[0], lengths[0]
  533. minReceipts, maxReceipts := lengths[0]-fsMinFullBlocks-fsPivotInterval, lengths[0]-fsMinFullBlocks
  534. if minReceipts < 0 {
  535. minReceipts = 1
  536. }
  537. if maxReceipts < 0 {
  538. maxReceipts = 1
  539. }
  540. // Update the counters for each subsequent fork
  541. for _, length := range lengths[1:] {
  542. headers += length - common
  543. blocks += length - common
  544. minReceipts += length - common - fsMinFullBlocks - fsPivotInterval
  545. maxReceipts += length - common - fsMinFullBlocks
  546. }
  547. switch tester.downloader.mode {
  548. case FullSync:
  549. minReceipts, maxReceipts = 1, 1
  550. case LightSync:
  551. blocks, minReceipts, maxReceipts = 1, 1, 1
  552. }
  553. if hs := len(tester.ownHeaders); hs != headers {
  554. t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, headers)
  555. }
  556. if bs := len(tester.ownBlocks); bs != blocks {
  557. t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, blocks)
  558. }
  559. if rs := len(tester.ownReceipts); rs < minReceipts || rs > maxReceipts {
  560. t.Fatalf("synchronised receipts mismatch: have %v, want between [%v, %v]", rs, minReceipts, maxReceipts)
  561. }
  562. // Verify the state trie too for fast syncs
  563. if tester.downloader.mode == FastSync {
  564. var index int
  565. if pivot := int(tester.downloader.queue.fastSyncPivot); pivot < common {
  566. index = pivot
  567. } else {
  568. index = len(tester.ownHashes) - lengths[len(lengths)-1] + int(tester.downloader.queue.fastSyncPivot)
  569. }
  570. if index > 0 {
  571. if statedb, err := state.New(tester.ownHeaders[tester.ownHashes[index]].Root, state.NewDatabase(tester.stateDb)); statedb == nil || err != nil {
  572. t.Fatalf("state reconstruction failed: %v", err)
  573. }
  574. }
  575. }
  576. }
  577. // Tests that simple synchronization against a canonical chain works correctly.
  578. // In this test common ancestor lookup should be short circuited and not require
  579. // binary searching.
  580. func TestCanonicalSynchronisation62(t *testing.T) { testCanonicalSynchronisation(t, 62, FullSync) }
  581. func TestCanonicalSynchronisation63Full(t *testing.T) { testCanonicalSynchronisation(t, 63, FullSync) }
  582. func TestCanonicalSynchronisation63Fast(t *testing.T) { testCanonicalSynchronisation(t, 63, FastSync) }
  583. func TestCanonicalSynchronisation64Full(t *testing.T) { testCanonicalSynchronisation(t, 64, FullSync) }
  584. func TestCanonicalSynchronisation64Fast(t *testing.T) { testCanonicalSynchronisation(t, 64, FastSync) }
  585. func TestCanonicalSynchronisation64Light(t *testing.T) { testCanonicalSynchronisation(t, 64, LightSync) }
  586. func testCanonicalSynchronisation(t *testing.T, protocol int, mode SyncMode) {
  587. t.Parallel()
  588. tester := newTester()
  589. defer tester.terminate()
  590. // Create a small enough block chain to download
  591. targetBlocks := blockCacheLimit - 15
  592. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  593. tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
  594. // Synchronise with the peer and make sure all relevant data was retrieved
  595. if err := tester.sync("peer", nil, mode); err != nil {
  596. t.Fatalf("failed to synchronise blocks: %v", err)
  597. }
  598. assertOwnChain(t, tester, targetBlocks+1)
  599. }
  600. // Tests that if a large batch of blocks are being downloaded, it is throttled
  601. // until the cached blocks are retrieved.
  602. func TestThrottling62(t *testing.T) { testThrottling(t, 62, FullSync) }
  603. func TestThrottling63Full(t *testing.T) { testThrottling(t, 63, FullSync) }
  604. func TestThrottling63Fast(t *testing.T) { testThrottling(t, 63, FastSync) }
  605. func TestThrottling64Full(t *testing.T) { testThrottling(t, 64, FullSync) }
  606. func TestThrottling64Fast(t *testing.T) { testThrottling(t, 64, FastSync) }
  607. func testThrottling(t *testing.T, protocol int, mode SyncMode) {
  608. t.Parallel()
  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. t.Parallel()
  999. tester := newTester()
  1000. defer tester.terminate()
  1001. // Create a small enough block chain to download
  1002. targetBlocks := blockCacheLimit - 15
  1003. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1004. // Attempt a full sync with an attacker feeding shifted headers
  1005. tester.newPeer("attack", protocol, hashes, headers, blocks, receipts)
  1006. delete(tester.peerHeaders["attack"], hashes[len(hashes)-2])
  1007. delete(tester.peerBlocks["attack"], hashes[len(hashes)-2])
  1008. delete(tester.peerReceipts["attack"], hashes[len(hashes)-2])
  1009. if err := tester.sync("attack", nil, mode); err == nil {
  1010. t.Fatalf("succeeded attacker synchronisation")
  1011. }
  1012. // Synchronise with the valid peer and make sure sync succeeds
  1013. tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
  1014. if err := tester.sync("valid", nil, mode); err != nil {
  1015. t.Fatalf("failed to synchronise blocks: %v", err)
  1016. }
  1017. assertOwnChain(t, tester, targetBlocks+1)
  1018. }
  1019. // Tests that upon detecting an invalid header, the recent ones are rolled back
  1020. // for various failure scenarios. Afterwards a full sync is attempted to make
  1021. // sure no state was corrupted.
  1022. func TestInvalidHeaderRollback63Fast(t *testing.T) { testInvalidHeaderRollback(t, 63, FastSync) }
  1023. func TestInvalidHeaderRollback64Fast(t *testing.T) { testInvalidHeaderRollback(t, 64, FastSync) }
  1024. func TestInvalidHeaderRollback64Light(t *testing.T) { testInvalidHeaderRollback(t, 64, LightSync) }
  1025. func testInvalidHeaderRollback(t *testing.T, protocol int, mode SyncMode) {
  1026. t.Parallel()
  1027. tester := newTester()
  1028. defer tester.terminate()
  1029. // Create a small enough block chain to download
  1030. targetBlocks := 3*fsHeaderSafetyNet + fsPivotInterval + fsMinFullBlocks
  1031. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1032. // Attempt to sync with an attacker that feeds junk during the fast sync phase.
  1033. // This should result in the last fsHeaderSafetyNet headers being rolled back.
  1034. tester.newPeer("fast-attack", protocol, hashes, headers, blocks, receipts)
  1035. missing := fsHeaderSafetyNet + MaxHeaderFetch + 1
  1036. delete(tester.peerHeaders["fast-attack"], hashes[len(hashes)-missing])
  1037. if err := tester.sync("fast-attack", nil, mode); err == nil {
  1038. t.Fatalf("succeeded fast attacker synchronisation")
  1039. }
  1040. if head := tester.CurrentHeader().Number.Int64(); int(head) > MaxHeaderFetch {
  1041. t.Errorf("rollback head mismatch: have %v, want at most %v", head, MaxHeaderFetch)
  1042. }
  1043. // Attempt to sync with an attacker that feeds junk during the block import phase.
  1044. // This should result in both the last fsHeaderSafetyNet number of headers being
  1045. // rolled back, and also the pivot point being reverted to a non-block status.
  1046. tester.newPeer("block-attack", protocol, hashes, headers, blocks, receipts)
  1047. missing = 3*fsHeaderSafetyNet + MaxHeaderFetch + 1
  1048. delete(tester.peerHeaders["fast-attack"], hashes[len(hashes)-missing]) // Make sure the fast-attacker doesn't fill in
  1049. delete(tester.peerHeaders["block-attack"], hashes[len(hashes)-missing])
  1050. if err := tester.sync("block-attack", nil, mode); err == nil {
  1051. t.Fatalf("succeeded block attacker synchronisation")
  1052. }
  1053. if head := tester.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
  1054. t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
  1055. }
  1056. if mode == FastSync {
  1057. if head := tester.CurrentBlock().NumberU64(); head != 0 {
  1058. t.Errorf("fast sync pivot block #%d not rolled back", head)
  1059. }
  1060. }
  1061. // Attempt to sync with an attacker that withholds promised blocks after the
  1062. // fast sync pivot point. This could be a trial to leave the node with a bad
  1063. // but already imported pivot block.
  1064. tester.newPeer("withhold-attack", protocol, hashes, headers, blocks, receipts)
  1065. missing = 3*fsHeaderSafetyNet + MaxHeaderFetch + 1
  1066. tester.downloader.fsPivotFails = 0
  1067. tester.downloader.syncInitHook = func(uint64, uint64) {
  1068. for i := missing; i <= len(hashes); i++ {
  1069. delete(tester.peerHeaders["withhold-attack"], hashes[len(hashes)-i])
  1070. }
  1071. tester.downloader.syncInitHook = nil
  1072. }
  1073. if err := tester.sync("withhold-attack", nil, mode); err == nil {
  1074. t.Fatalf("succeeded withholding attacker synchronisation")
  1075. }
  1076. if head := tester.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
  1077. t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
  1078. }
  1079. if mode == FastSync {
  1080. if head := tester.CurrentBlock().NumberU64(); head != 0 {
  1081. t.Errorf("fast sync pivot block #%d not rolled back", head)
  1082. }
  1083. }
  1084. tester.downloader.fsPivotFails = fsCriticalTrials
  1085. // Synchronise with the valid peer and make sure sync succeeds. Since the last
  1086. // rollback should also disable fast syncing for this process, verify that we
  1087. // did a fresh full sync. Note, we can't assert anything about the receipts
  1088. // since we won't purge the database of them, hence we can't use assertOwnChain.
  1089. tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
  1090. if err := tester.sync("valid", nil, mode); err != nil {
  1091. t.Fatalf("failed to synchronise blocks: %v", err)
  1092. }
  1093. if hs := len(tester.ownHeaders); hs != len(headers) {
  1094. t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, len(headers))
  1095. }
  1096. if mode != LightSync {
  1097. if bs := len(tester.ownBlocks); bs != len(blocks) {
  1098. t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, len(blocks))
  1099. }
  1100. }
  1101. }
  1102. // Tests that a peer advertising an high TD doesn't get to stall the downloader
  1103. // afterwards by not sending any useful hashes.
  1104. func TestHighTDStarvationAttack62(t *testing.T) { testHighTDStarvationAttack(t, 62, FullSync) }
  1105. func TestHighTDStarvationAttack63Full(t *testing.T) { testHighTDStarvationAttack(t, 63, FullSync) }
  1106. func TestHighTDStarvationAttack63Fast(t *testing.T) { testHighTDStarvationAttack(t, 63, FastSync) }
  1107. func TestHighTDStarvationAttack64Full(t *testing.T) { testHighTDStarvationAttack(t, 64, FullSync) }
  1108. func TestHighTDStarvationAttack64Fast(t *testing.T) { testHighTDStarvationAttack(t, 64, FastSync) }
  1109. func TestHighTDStarvationAttack64Light(t *testing.T) { testHighTDStarvationAttack(t, 64, LightSync) }
  1110. func testHighTDStarvationAttack(t *testing.T, protocol int, mode SyncMode) {
  1111. t.Parallel()
  1112. tester := newTester()
  1113. defer tester.terminate()
  1114. hashes, headers, blocks, receipts := tester.makeChain(0, 0, tester.genesis, nil, false)
  1115. tester.newPeer("attack", protocol, []common.Hash{hashes[0]}, headers, blocks, receipts)
  1116. if err := tester.sync("attack", big.NewInt(1000000), mode); err != errStallingPeer {
  1117. t.Fatalf("synchronisation error mismatch: have %v, want %v", err, errStallingPeer)
  1118. }
  1119. }
  1120. // Tests that misbehaving peers are disconnected, whilst behaving ones are not.
  1121. func TestBlockHeaderAttackerDropping62(t *testing.T) { testBlockHeaderAttackerDropping(t, 62) }
  1122. func TestBlockHeaderAttackerDropping63(t *testing.T) { testBlockHeaderAttackerDropping(t, 63) }
  1123. func TestBlockHeaderAttackerDropping64(t *testing.T) { testBlockHeaderAttackerDropping(t, 64) }
  1124. func testBlockHeaderAttackerDropping(t *testing.T, protocol int) {
  1125. t.Parallel()
  1126. // Define the disconnection requirement for individual hash fetch errors
  1127. tests := []struct {
  1128. result error
  1129. drop bool
  1130. }{
  1131. {nil, false}, // Sync succeeded, all is well
  1132. {errBusy, false}, // Sync is already in progress, no problem
  1133. {errUnknownPeer, false}, // Peer is unknown, was already dropped, don't double drop
  1134. {errBadPeer, true}, // Peer was deemed bad for some reason, drop it
  1135. {errStallingPeer, true}, // Peer was detected to be stalling, drop it
  1136. {errNoPeers, false}, // No peers to download from, soft race, no issue
  1137. {errTimeout, true}, // No hashes received in due time, drop the peer
  1138. {errEmptyHeaderSet, true}, // No headers were returned as a response, drop as it's a dead end
  1139. {errPeersUnavailable, true}, // Nobody had the advertised blocks, drop the advertiser
  1140. {errInvalidAncestor, true}, // Agreed upon ancestor is not acceptable, drop the chain rewriter
  1141. {errInvalidChain, true}, // Hash chain was detected as invalid, definitely drop
  1142. {errInvalidBlock, false}, // A bad peer was detected, but not the sync origin
  1143. {errInvalidBody, false}, // A bad peer was detected, but not the sync origin
  1144. {errInvalidReceipt, false}, // A bad peer was detected, but not the sync origin
  1145. {errCancelBlockFetch, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1146. {errCancelHeaderFetch, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1147. {errCancelBodyFetch, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1148. {errCancelReceiptFetch, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1149. {errCancelHeaderProcessing, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1150. {errCancelContentProcessing, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1151. }
  1152. // Run the tests and check disconnection status
  1153. tester := newTester()
  1154. defer tester.terminate()
  1155. for i, tt := range tests {
  1156. // Register a new peer and ensure it's presence
  1157. id := fmt.Sprintf("test %d", i)
  1158. if err := tester.newPeer(id, protocol, []common.Hash{tester.genesis.Hash()}, nil, nil, nil); err != nil {
  1159. t.Fatalf("test %d: failed to register new peer: %v", i, err)
  1160. }
  1161. if _, ok := tester.peerHashes[id]; !ok {
  1162. t.Fatalf("test %d: registered peer not found", i)
  1163. }
  1164. // Simulate a synchronisation and check the required result
  1165. tester.downloader.synchroniseMock = func(string, common.Hash) error { return tt.result }
  1166. tester.downloader.Synchronise(id, tester.genesis.Hash(), big.NewInt(1000), FullSync)
  1167. if _, ok := tester.peerHashes[id]; !ok != tt.drop {
  1168. t.Errorf("test %d: peer drop mismatch for %v: have %v, want %v", i, tt.result, !ok, tt.drop)
  1169. }
  1170. }
  1171. }
  1172. // Tests that synchronisation progress (origin block number, current block number
  1173. // and highest block number) is tracked and updated correctly.
  1174. func TestSyncProgress62(t *testing.T) { testSyncProgress(t, 62, FullSync) }
  1175. func TestSyncProgress63Full(t *testing.T) { testSyncProgress(t, 63, FullSync) }
  1176. func TestSyncProgress63Fast(t *testing.T) { testSyncProgress(t, 63, FastSync) }
  1177. func TestSyncProgress64Full(t *testing.T) { testSyncProgress(t, 64, FullSync) }
  1178. func TestSyncProgress64Fast(t *testing.T) { testSyncProgress(t, 64, FastSync) }
  1179. func TestSyncProgress64Light(t *testing.T) { testSyncProgress(t, 64, LightSync) }
  1180. func testSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1181. t.Parallel()
  1182. tester := newTester()
  1183. defer tester.terminate()
  1184. // Create a small enough block chain to download
  1185. targetBlocks := blockCacheLimit - 15
  1186. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1187. // Set a sync init hook to catch progress changes
  1188. starting := make(chan struct{})
  1189. progress := make(chan struct{})
  1190. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1191. starting <- struct{}{}
  1192. <-progress
  1193. }
  1194. // Retrieve the sync progress and ensure they are zero (pristine sync)
  1195. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
  1196. t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
  1197. }
  1198. // Synchronise half the blocks and check initial progress
  1199. tester.newPeer("peer-half", protocol, hashes[targetBlocks/2:], headers, blocks, receipts)
  1200. pending := new(sync.WaitGroup)
  1201. pending.Add(1)
  1202. go func() {
  1203. defer pending.Done()
  1204. if err := tester.sync("peer-half", nil, mode); err != nil {
  1205. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1206. }
  1207. }()
  1208. <-starting
  1209. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(targetBlocks/2+1) {
  1210. t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, targetBlocks/2+1)
  1211. }
  1212. progress <- struct{}{}
  1213. pending.Wait()
  1214. // Synchronise all the blocks and check continuation progress
  1215. tester.newPeer("peer-full", protocol, hashes, headers, blocks, receipts)
  1216. pending.Add(1)
  1217. go func() {
  1218. defer pending.Done()
  1219. if err := tester.sync("peer-full", nil, mode); err != nil {
  1220. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1221. }
  1222. }()
  1223. <-starting
  1224. if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(targetBlocks/2+1) || progress.CurrentBlock != uint64(targetBlocks/2+1) || progress.HighestBlock != uint64(targetBlocks) {
  1225. 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)
  1226. }
  1227. progress <- struct{}{}
  1228. pending.Wait()
  1229. // Check final progress after successful sync
  1230. if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(targetBlocks/2+1) || progress.CurrentBlock != uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
  1231. t.Fatalf("Final progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, targetBlocks/2+1, targetBlocks, targetBlocks)
  1232. }
  1233. }
  1234. // Tests that synchronisation progress (origin block number and highest block
  1235. // number) is tracked and updated correctly in case of a fork (or manual head
  1236. // revertal).
  1237. func TestForkedSyncProgress62(t *testing.T) { testForkedSyncProgress(t, 62, FullSync) }
  1238. func TestForkedSyncProgress63Full(t *testing.T) { testForkedSyncProgress(t, 63, FullSync) }
  1239. func TestForkedSyncProgress63Fast(t *testing.T) { testForkedSyncProgress(t, 63, FastSync) }
  1240. func TestForkedSyncProgress64Full(t *testing.T) { testForkedSyncProgress(t, 64, FullSync) }
  1241. func TestForkedSyncProgress64Fast(t *testing.T) { testForkedSyncProgress(t, 64, FastSync) }
  1242. func TestForkedSyncProgress64Light(t *testing.T) { testForkedSyncProgress(t, 64, LightSync) }
  1243. func testForkedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1244. t.Parallel()
  1245. tester := newTester()
  1246. defer tester.terminate()
  1247. // Create a forked chain to simulate origin revertal
  1248. common, fork := MaxHashFetch, 2*MaxHashFetch
  1249. hashesA, hashesB, headersA, headersB, blocksA, blocksB, receiptsA, receiptsB := tester.makeChainFork(common+fork, fork, tester.genesis, nil, true)
  1250. // Set a sync init hook to catch progress changes
  1251. starting := make(chan struct{})
  1252. progress := make(chan struct{})
  1253. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1254. starting <- struct{}{}
  1255. <-progress
  1256. }
  1257. // Retrieve the sync progress and ensure they are zero (pristine sync)
  1258. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
  1259. t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
  1260. }
  1261. // Synchronise with one of the forks and check progress
  1262. tester.newPeer("fork A", protocol, hashesA, headersA, blocksA, receiptsA)
  1263. pending := new(sync.WaitGroup)
  1264. pending.Add(1)
  1265. go func() {
  1266. defer pending.Done()
  1267. if err := tester.sync("fork A", nil, mode); err != nil {
  1268. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1269. }
  1270. }()
  1271. <-starting
  1272. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(len(hashesA)-1) {
  1273. t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, len(hashesA)-1)
  1274. }
  1275. progress <- struct{}{}
  1276. pending.Wait()
  1277. // Simulate a successful sync above the fork
  1278. tester.downloader.syncStatsChainOrigin = tester.downloader.syncStatsChainHeight
  1279. // Synchronise with the second fork and check progress resets
  1280. tester.newPeer("fork B", protocol, hashesB, headersB, blocksB, receiptsB)
  1281. pending.Add(1)
  1282. go func() {
  1283. defer pending.Done()
  1284. if err := tester.sync("fork B", nil, mode); err != nil {
  1285. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1286. }
  1287. }()
  1288. <-starting
  1289. if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(common) || progress.CurrentBlock != uint64(len(hashesA)-1) || progress.HighestBlock != uint64(len(hashesB)-1) {
  1290. 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)
  1291. }
  1292. progress <- struct{}{}
  1293. pending.Wait()
  1294. // Check final progress after successful sync
  1295. if progress := tester.downloader.Progress(); progress.StartingBlock != uint64(common) || progress.CurrentBlock != uint64(len(hashesB)-1) || progress.HighestBlock != uint64(len(hashesB)-1) {
  1296. 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)
  1297. }
  1298. }
  1299. // Tests that if synchronisation is aborted due to some failure, then the progress
  1300. // origin is not updated in the next sync cycle, as it should be considered the
  1301. // continuation of the previous sync and not a new instance.
  1302. func TestFailedSyncProgress62(t *testing.T) { testFailedSyncProgress(t, 62, FullSync) }
  1303. func TestFailedSyncProgress63Full(t *testing.T) { testFailedSyncProgress(t, 63, FullSync) }
  1304. func TestFailedSyncProgress63Fast(t *testing.T) { testFailedSyncProgress(t, 63, FastSync) }
  1305. func TestFailedSyncProgress64Full(t *testing.T) { testFailedSyncProgress(t, 64, FullSync) }
  1306. func TestFailedSyncProgress64Fast(t *testing.T) { testFailedSyncProgress(t, 64, FastSync) }
  1307. func TestFailedSyncProgress64Light(t *testing.T) { testFailedSyncProgress(t, 64, LightSync) }
  1308. func testFailedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1309. t.Parallel()
  1310. tester := newTester()
  1311. defer tester.terminate()
  1312. // Create a small enough block chain to download
  1313. targetBlocks := blockCacheLimit - 15
  1314. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1315. // Set a sync init hook to catch progress changes
  1316. starting := make(chan struct{})
  1317. progress := make(chan struct{})
  1318. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1319. starting <- struct{}{}
  1320. <-progress
  1321. }
  1322. // Retrieve the sync progress and ensure they are zero (pristine sync)
  1323. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
  1324. t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
  1325. }
  1326. // Attempt a full sync with a faulty peer
  1327. tester.newPeer("faulty", protocol, hashes, headers, blocks, receipts)
  1328. missing := targetBlocks / 2
  1329. delete(tester.peerHeaders["faulty"], hashes[missing])
  1330. delete(tester.peerBlocks["faulty"], hashes[missing])
  1331. delete(tester.peerReceipts["faulty"], hashes[missing])
  1332. pending := new(sync.WaitGroup)
  1333. pending.Add(1)
  1334. go func() {
  1335. defer pending.Done()
  1336. if err := tester.sync("faulty", nil, mode); err == nil {
  1337. panic("succeeded faulty synchronisation")
  1338. }
  1339. }()
  1340. <-starting
  1341. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(targetBlocks) {
  1342. t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, targetBlocks)
  1343. }
  1344. progress <- struct{}{}
  1345. pending.Wait()
  1346. // Synchronise with a good peer and check that the progress origin remind the same after a failure
  1347. tester.newPeer("valid", protocol, hashes, headers, blocks, receipts)
  1348. pending.Add(1)
  1349. go func() {
  1350. defer pending.Done()
  1351. if err := tester.sync("valid", nil, mode); err != nil {
  1352. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1353. }
  1354. }()
  1355. <-starting
  1356. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock > uint64(targetBlocks/2) || progress.HighestBlock != uint64(targetBlocks) {
  1357. t.Fatalf("Completing progress mismatch: have %v/%v/%v, want %v/0-%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, targetBlocks/2, targetBlocks)
  1358. }
  1359. progress <- struct{}{}
  1360. pending.Wait()
  1361. // Check final progress after successful sync
  1362. if progress := tester.downloader.Progress(); progress.StartingBlock > uint64(targetBlocks/2) || progress.CurrentBlock != uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
  1363. t.Fatalf("Final progress mismatch: have %v/%v/%v, want 0-%v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, targetBlocks/2, targetBlocks, targetBlocks)
  1364. }
  1365. }
  1366. // Tests that if an attacker fakes a chain height, after the attack is detected,
  1367. // the progress height is successfully reduced at the next sync invocation.
  1368. func TestFakedSyncProgress62(t *testing.T) { testFakedSyncProgress(t, 62, FullSync) }
  1369. func TestFakedSyncProgress63Full(t *testing.T) { testFakedSyncProgress(t, 63, FullSync) }
  1370. func TestFakedSyncProgress63Fast(t *testing.T) { testFakedSyncProgress(t, 63, FastSync) }
  1371. func TestFakedSyncProgress64Full(t *testing.T) { testFakedSyncProgress(t, 64, FullSync) }
  1372. func TestFakedSyncProgress64Fast(t *testing.T) { testFakedSyncProgress(t, 64, FastSync) }
  1373. func TestFakedSyncProgress64Light(t *testing.T) { testFakedSyncProgress(t, 64, LightSync) }
  1374. func testFakedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1375. t.Parallel()
  1376. tester := newTester()
  1377. defer tester.terminate()
  1378. // Create a small block chain
  1379. targetBlocks := blockCacheLimit - 15
  1380. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks+3, 0, tester.genesis, nil, false)
  1381. // Set a sync init hook to catch progress changes
  1382. starting := make(chan struct{})
  1383. progress := make(chan struct{})
  1384. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1385. starting <- struct{}{}
  1386. <-progress
  1387. }
  1388. // Retrieve the sync progress and ensure they are zero (pristine sync)
  1389. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != 0 {
  1390. t.Fatalf("Pristine progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, 0)
  1391. }
  1392. // Create and sync with an attacker that promises a higher chain than available
  1393. tester.newPeer("attack", protocol, hashes, headers, blocks, receipts)
  1394. for i := 1; i < 3; i++ {
  1395. delete(tester.peerHeaders["attack"], hashes[i])
  1396. delete(tester.peerBlocks["attack"], hashes[i])
  1397. delete(tester.peerReceipts["attack"], hashes[i])
  1398. }
  1399. pending := new(sync.WaitGroup)
  1400. pending.Add(1)
  1401. go func() {
  1402. defer pending.Done()
  1403. if err := tester.sync("attack", nil, mode); err == nil {
  1404. panic("succeeded attacker synchronisation")
  1405. }
  1406. }()
  1407. <-starting
  1408. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock != 0 || progress.HighestBlock != uint64(targetBlocks+3) {
  1409. t.Fatalf("Initial progress mismatch: have %v/%v/%v, want %v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, 0, targetBlocks+3)
  1410. }
  1411. progress <- struct{}{}
  1412. pending.Wait()
  1413. // Synchronise with a good peer and check that the progress height has been reduced to the true value
  1414. tester.newPeer("valid", protocol, hashes[3:], headers, blocks, receipts)
  1415. pending.Add(1)
  1416. go func() {
  1417. defer pending.Done()
  1418. if err := tester.sync("valid", nil, mode); err != nil {
  1419. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1420. }
  1421. }()
  1422. <-starting
  1423. if progress := tester.downloader.Progress(); progress.StartingBlock != 0 || progress.CurrentBlock > uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
  1424. t.Fatalf("Completing progress mismatch: have %v/%v/%v, want %v/0-%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, 0, targetBlocks, targetBlocks)
  1425. }
  1426. progress <- struct{}{}
  1427. pending.Wait()
  1428. // Check final progress after successful sync
  1429. if progress := tester.downloader.Progress(); progress.StartingBlock > uint64(targetBlocks) || progress.CurrentBlock != uint64(targetBlocks) || progress.HighestBlock != uint64(targetBlocks) {
  1430. t.Fatalf("Final progress mismatch: have %v/%v/%v, want 0-%v/%v/%v", progress.StartingBlock, progress.CurrentBlock, progress.HighestBlock, targetBlocks, targetBlocks, targetBlocks)
  1431. }
  1432. }
  1433. // This test reproduces an issue where unexpected deliveries would
  1434. // block indefinitely if they arrived at the right time.
  1435. // We use data driven subtests to manage this so that it will be parallel on its own
  1436. // and not with the other tests, avoiding intermittent failures.
  1437. func TestDeliverHeadersHang(t *testing.T) {
  1438. testCases := []struct {
  1439. protocol int
  1440. syncMode SyncMode
  1441. }{
  1442. {62, FullSync},
  1443. {63, FullSync},
  1444. {63, FastSync},
  1445. {64, FullSync},
  1446. {64, FastSync},
  1447. {64, LightSync},
  1448. }
  1449. for _, tc := range testCases {
  1450. t.Run(fmt.Sprintf("protocol %d mode %v", tc.protocol, tc.syncMode), func(t *testing.T) {
  1451. testDeliverHeadersHang(t, tc.protocol, tc.syncMode)
  1452. })
  1453. }
  1454. }
  1455. type floodingTestPeer struct {
  1456. peer Peer
  1457. tester *downloadTester
  1458. }
  1459. func (ftp *floodingTestPeer) Head() (common.Hash, *big.Int) { return ftp.peer.Head() }
  1460. func (ftp *floodingTestPeer) RequestHeadersByHash(hash common.Hash, count int, skip int, reverse bool) error {
  1461. return ftp.peer.RequestHeadersByHash(hash, count, skip, reverse)
  1462. }
  1463. func (ftp *floodingTestPeer) RequestBodies(hashes []common.Hash) error {
  1464. return ftp.peer.RequestBodies(hashes)
  1465. }
  1466. func (ftp *floodingTestPeer) RequestReceipts(hashes []common.Hash) error {
  1467. return ftp.peer.RequestReceipts(hashes)
  1468. }
  1469. func (ftp *floodingTestPeer) RequestNodeData(hashes []common.Hash) error {
  1470. return ftp.peer.RequestNodeData(hashes)
  1471. }
  1472. func (ftp *floodingTestPeer) RequestHeadersByNumber(from uint64, count, skip int, reverse bool) error {
  1473. deliveriesDone := make(chan struct{}, 500)
  1474. for i := 0; i < cap(deliveriesDone); i++ {
  1475. peer := fmt.Sprintf("fake-peer%d", i)
  1476. go func() {
  1477. ftp.tester.downloader.DeliverHeaders(peer, []*types.Header{{}, {}, {}, {}})
  1478. deliveriesDone <- struct{}{}
  1479. }()
  1480. }
  1481. // Deliver the actual requested headers.
  1482. go ftp.peer.RequestHeadersByNumber(from, count, skip, reverse)
  1483. // None of the extra deliveries should block.
  1484. timeout := time.After(60 * time.Second)
  1485. for i := 0; i < cap(deliveriesDone); i++ {
  1486. select {
  1487. case <-deliveriesDone:
  1488. case <-timeout:
  1489. panic("blocked")
  1490. }
  1491. }
  1492. return nil
  1493. }
  1494. func testDeliverHeadersHang(t *testing.T, protocol int, mode SyncMode) {
  1495. t.Parallel()
  1496. master := newTester()
  1497. defer master.terminate()
  1498. hashes, headers, blocks, receipts := master.makeChain(5, 0, master.genesis, nil, false)
  1499. for i := 0; i < 200; i++ {
  1500. tester := newTester()
  1501. tester.peerDb = master.peerDb
  1502. tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
  1503. // Whenever the downloader requests headers, flood it with
  1504. // a lot of unrequested header deliveries.
  1505. tester.downloader.peers.peers["peer"].peer = &floodingTestPeer{
  1506. tester.downloader.peers.peers["peer"].peer,
  1507. tester,
  1508. }
  1509. if err := tester.sync("peer", nil, mode); err != nil {
  1510. t.Errorf("sync failed: %v", err)
  1511. }
  1512. tester.terminate()
  1513. }
  1514. }
  1515. // Tests that if fast sync aborts in the critical section, it can restart a few
  1516. // times before giving up.
  1517. // We use data driven subtests to manage this so that it will be parallel on its own
  1518. // and not with the other tests, avoiding intermittent failures.
  1519. func TestFastCriticalRestarts(t *testing.T) {
  1520. testCases := []struct {
  1521. protocol int
  1522. progress bool
  1523. }{
  1524. {63, false},
  1525. {64, false},
  1526. {63, true},
  1527. {64, true},
  1528. }
  1529. for _, tc := range testCases {
  1530. t.Run(fmt.Sprintf("protocol %d progress %v", tc.protocol, tc.progress), func(t *testing.T) {
  1531. testFastCriticalRestarts(t, tc.protocol, tc.progress)
  1532. })
  1533. }
  1534. }
  1535. func testFastCriticalRestarts(t *testing.T, protocol int, progress bool) {
  1536. t.Parallel()
  1537. tester := newTester()
  1538. defer tester.terminate()
  1539. // Create a large enough blockchin to actually fast sync on
  1540. targetBlocks := fsMinFullBlocks + 2*fsPivotInterval - 15
  1541. hashes, headers, blocks, receipts := tester.makeChain(targetBlocks, 0, tester.genesis, nil, false)
  1542. // Create a tester peer with a critical section header missing (force failures)
  1543. tester.newPeer("peer", protocol, hashes, headers, blocks, receipts)
  1544. delete(tester.peerHeaders["peer"], hashes[fsMinFullBlocks-1])
  1545. tester.downloader.dropPeer = func(id string) {} // We reuse the same "faulty" peer throughout the test
  1546. // Remove all possible pivot state roots and slow down replies (test failure resets later)
  1547. for i := 0; i < fsPivotInterval; i++ {
  1548. tester.peerMissingStates["peer"][headers[hashes[fsMinFullBlocks+i]].Root] = true
  1549. }
  1550. (tester.downloader.peers.peers["peer"].peer).(*downloadTesterPeer).setDelay(500 * time.Millisecond) // Enough to reach the critical section
  1551. // Synchronise with the peer a few times and make sure they fail until the retry limit
  1552. for i := 0; i < int(fsCriticalTrials)-1; i++ {
  1553. // Attempt a sync and ensure it fails properly
  1554. if err := tester.sync("peer", nil, FastSync); err == nil {
  1555. t.Fatalf("failing fast sync succeeded: %v", err)
  1556. }
  1557. time.Sleep(150 * time.Millisecond) // Make sure no in-flight requests remain
  1558. // If it's the first failure, pivot should be locked => reenable all others to detect pivot changes
  1559. if i == 0 {
  1560. time.Sleep(150 * time.Millisecond) // Make sure no in-flight requests remain
  1561. if tester.downloader.fsPivotLock == nil {
  1562. time.Sleep(400 * time.Millisecond) // Make sure the first huge timeout expires too
  1563. t.Fatalf("pivot block not locked in after critical section failure")
  1564. }
  1565. tester.lock.Lock()
  1566. tester.peerHeaders["peer"][hashes[fsMinFullBlocks-1]] = headers[hashes[fsMinFullBlocks-1]]
  1567. tester.peerMissingStates["peer"] = map[common.Hash]bool{tester.downloader.fsPivotLock.Root: true}
  1568. (tester.downloader.peers.peers["peer"].peer).(*downloadTesterPeer).setDelay(0)
  1569. tester.lock.Unlock()
  1570. }
  1571. }
  1572. // Return all nodes if we're testing fast sync progression
  1573. if progress {
  1574. tester.lock.Lock()
  1575. tester.peerMissingStates["peer"] = map[common.Hash]bool{}
  1576. tester.lock.Unlock()
  1577. if err := tester.sync("peer", nil, FastSync); err != nil {
  1578. t.Fatalf("failed to synchronise blocks in progressed fast sync: %v", err)
  1579. }
  1580. time.Sleep(150 * time.Millisecond) // Make sure no in-flight requests remain
  1581. if fails := atomic.LoadUint32(&tester.downloader.fsPivotFails); fails != 1 {
  1582. t.Fatalf("progressed pivot trial count mismatch: have %v, want %v", fails, 1)
  1583. }
  1584. assertOwnChain(t, tester, targetBlocks+1)
  1585. } else {
  1586. if err := tester.sync("peer", nil, FastSync); err == nil {
  1587. t.Fatalf("succeeded to synchronise blocks in failed fast sync")
  1588. }
  1589. time.Sleep(150 * time.Millisecond) // Make sure no in-flight requests remain
  1590. if fails := atomic.LoadUint32(&tester.downloader.fsPivotFails); fails != fsCriticalTrials {
  1591. t.Fatalf("failed pivot trial count mismatch: have %v, want %v", fails, fsCriticalTrials)
  1592. }
  1593. }
  1594. // Retry limit exhausted, downloader will switch to full sync, should succeed
  1595. if err := tester.sync("peer", nil, FastSync); err != nil {
  1596. t.Fatalf("failed to synchronise blocks in slow sync: %v", err)
  1597. }
  1598. // Note, we can't assert the chain here because the test asserter assumes sync
  1599. // completed using a single mode of operation, whereas fast-then-slow can result
  1600. // in arbitrary intermediate state that's not cleanly verifiable.
  1601. }