downloader_test.go 72 KB

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