downloader_test.go 73 KB

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