downloader_test.go 75 KB

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