downloader_test.go 76 KB

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