downloader_test.go 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738
  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. "strings"
  22. "sync"
  23. "sync/atomic"
  24. "testing"
  25. "time"
  26. "github.com/ethereum/go-ethereum"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/core/rawdb"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/ethdb"
  31. "github.com/ethereum/go-ethereum/event"
  32. "github.com/ethereum/go-ethereum/trie"
  33. )
  34. // Reduce some of the parameters to make the tester faster.
  35. func init() {
  36. fullMaxForkAncestry = 10000
  37. lightMaxForkAncestry = 10000
  38. blockCacheMaxItems = 1024
  39. fsHeaderContCheck = 500 * time.Millisecond
  40. }
  41. // downloadTester is a test simulator for mocking out local block chain.
  42. type downloadTester struct {
  43. downloader *Downloader
  44. genesis *types.Block // Genesis blocks used by the tester and peers
  45. stateDb ethdb.Database // Database used by the tester for syncing from peers
  46. peerDb ethdb.Database // Database of the peers containing all data
  47. peers map[string]*downloadTesterPeer
  48. ownHashes []common.Hash // Hash chain belonging to the tester
  49. ownHeaders map[common.Hash]*types.Header // Headers belonging to the tester
  50. ownBlocks map[common.Hash]*types.Block // Blocks belonging to the tester
  51. ownReceipts map[common.Hash]types.Receipts // Receipts belonging to the tester
  52. ownChainTd map[common.Hash]*big.Int // Total difficulties of the blocks in the local chain
  53. ancientHeaders map[common.Hash]*types.Header // Ancient headers belonging to the tester
  54. ancientBlocks map[common.Hash]*types.Block // Ancient blocks belonging to the tester
  55. ancientReceipts map[common.Hash]types.Receipts // Ancient receipts belonging to the tester
  56. ancientChainTd map[common.Hash]*big.Int // Ancient total difficulties of the blocks in the local chain
  57. lock sync.RWMutex
  58. }
  59. // newTester creates a new downloader test mocker.
  60. func newTester() *downloadTester {
  61. tester := &downloadTester{
  62. genesis: testGenesis,
  63. peerDb: testDB,
  64. peers: make(map[string]*downloadTesterPeer),
  65. ownHashes: []common.Hash{testGenesis.Hash()},
  66. ownHeaders: map[common.Hash]*types.Header{testGenesis.Hash(): testGenesis.Header()},
  67. ownBlocks: map[common.Hash]*types.Block{testGenesis.Hash(): testGenesis},
  68. ownReceipts: map[common.Hash]types.Receipts{testGenesis.Hash(): nil},
  69. ownChainTd: map[common.Hash]*big.Int{testGenesis.Hash(): testGenesis.Difficulty()},
  70. // Initialize ancient store with test genesis block
  71. ancientHeaders: map[common.Hash]*types.Header{testGenesis.Hash(): testGenesis.Header()},
  72. ancientBlocks: map[common.Hash]*types.Block{testGenesis.Hash(): testGenesis},
  73. ancientReceipts: map[common.Hash]types.Receipts{testGenesis.Hash(): nil},
  74. ancientChainTd: map[common.Hash]*big.Int{testGenesis.Hash(): testGenesis.Difficulty()},
  75. }
  76. tester.stateDb = rawdb.NewMemoryDatabase()
  77. tester.stateDb.Put(testGenesis.Root().Bytes(), []byte{0x00})
  78. tester.downloader = New(0, tester.stateDb, trie.NewSyncBloom(1, tester.stateDb), new(event.TypeMux), tester, nil, tester.dropPeer)
  79. return tester
  80. }
  81. // terminate aborts any operations on the embedded downloader and releases all
  82. // held resources.
  83. func (dl *downloadTester) terminate() {
  84. dl.downloader.Terminate()
  85. }
  86. // sync starts synchronizing with a remote peer, blocking until it completes.
  87. func (dl *downloadTester) sync(id string, td *big.Int, mode SyncMode) error {
  88. dl.lock.RLock()
  89. hash := dl.peers[id].chain.headBlock().Hash()
  90. // If no particular TD was requested, load from the peer's blockchain
  91. if td == nil {
  92. td = dl.peers[id].chain.td(hash)
  93. }
  94. dl.lock.RUnlock()
  95. // Synchronise with the chosen peer and ensure proper cleanup afterwards
  96. err := dl.downloader.synchronise(id, hash, td, mode)
  97. select {
  98. case <-dl.downloader.cancelCh:
  99. // Ok, downloader fully cancelled after sync cycle
  100. default:
  101. // Downloader is still accepting packets, can block a peer up
  102. panic("downloader active post sync cycle") // panic will be caught by tester
  103. }
  104. return err
  105. }
  106. // HasHeader checks if a header is present in the testers canonical chain.
  107. func (dl *downloadTester) HasHeader(hash common.Hash, number uint64) bool {
  108. return dl.GetHeaderByHash(hash) != nil
  109. }
  110. // HasBlock checks if a block is present in the testers canonical chain.
  111. func (dl *downloadTester) HasBlock(hash common.Hash, number uint64) bool {
  112. return dl.GetBlockByHash(hash) != nil
  113. }
  114. // HasFastBlock checks if a block is present in the testers canonical chain.
  115. func (dl *downloadTester) HasFastBlock(hash common.Hash, number uint64) bool {
  116. dl.lock.RLock()
  117. defer dl.lock.RUnlock()
  118. if _, ok := dl.ancientReceipts[hash]; ok {
  119. return true
  120. }
  121. _, ok := dl.ownReceipts[hash]
  122. return ok
  123. }
  124. // GetHeader retrieves a header from the testers canonical chain.
  125. func (dl *downloadTester) GetHeaderByHash(hash common.Hash) *types.Header {
  126. dl.lock.RLock()
  127. defer dl.lock.RUnlock()
  128. return dl.getHeaderByHash(hash)
  129. }
  130. // getHeaderByHash returns the header if found either within ancients or own blocks)
  131. // This method assumes that the caller holds at least the read-lock (dl.lock)
  132. func (dl *downloadTester) getHeaderByHash(hash common.Hash) *types.Header {
  133. header := dl.ancientHeaders[hash]
  134. if header != nil {
  135. return header
  136. }
  137. return dl.ownHeaders[hash]
  138. }
  139. // GetBlock retrieves a block from the testers canonical chain.
  140. func (dl *downloadTester) GetBlockByHash(hash common.Hash) *types.Block {
  141. dl.lock.RLock()
  142. defer dl.lock.RUnlock()
  143. block := dl.ancientBlocks[hash]
  144. if block != nil {
  145. return block
  146. }
  147. return dl.ownBlocks[hash]
  148. }
  149. // CurrentHeader retrieves the current head header from the canonical chain.
  150. func (dl *downloadTester) CurrentHeader() *types.Header {
  151. dl.lock.RLock()
  152. defer dl.lock.RUnlock()
  153. for i := len(dl.ownHashes) - 1; i >= 0; i-- {
  154. if header := dl.ancientHeaders[dl.ownHashes[i]]; header != nil {
  155. return header
  156. }
  157. if header := dl.ownHeaders[dl.ownHashes[i]]; header != nil {
  158. return header
  159. }
  160. }
  161. return dl.genesis.Header()
  162. }
  163. // CurrentBlock retrieves the current head block from the canonical chain.
  164. func (dl *downloadTester) CurrentBlock() *types.Block {
  165. dl.lock.RLock()
  166. defer dl.lock.RUnlock()
  167. for i := len(dl.ownHashes) - 1; i >= 0; i-- {
  168. if block := dl.ancientBlocks[dl.ownHashes[i]]; block != nil {
  169. if _, err := dl.stateDb.Get(block.Root().Bytes()); err == nil {
  170. return block
  171. }
  172. return block
  173. }
  174. if block := dl.ownBlocks[dl.ownHashes[i]]; block != nil {
  175. if _, err := dl.stateDb.Get(block.Root().Bytes()); err == nil {
  176. return block
  177. }
  178. }
  179. }
  180. return dl.genesis
  181. }
  182. // CurrentFastBlock retrieves the current head fast-sync block from the canonical chain.
  183. func (dl *downloadTester) CurrentFastBlock() *types.Block {
  184. dl.lock.RLock()
  185. defer dl.lock.RUnlock()
  186. for i := len(dl.ownHashes) - 1; i >= 0; i-- {
  187. if block := dl.ancientBlocks[dl.ownHashes[i]]; block != nil {
  188. return block
  189. }
  190. if block := dl.ownBlocks[dl.ownHashes[i]]; block != nil {
  191. return block
  192. }
  193. }
  194. return dl.genesis
  195. }
  196. // FastSyncCommitHead manually sets the head block to a given hash.
  197. func (dl *downloadTester) FastSyncCommitHead(hash common.Hash) error {
  198. // For now only check that the state trie is correct
  199. if block := dl.GetBlockByHash(hash); block != nil {
  200. _, err := trie.NewSecure(block.Root(), trie.NewDatabase(dl.stateDb))
  201. return err
  202. }
  203. return fmt.Errorf("non existent block: %x", hash[:4])
  204. }
  205. // GetTd retrieves the block's total difficulty from the canonical chain.
  206. func (dl *downloadTester) GetTd(hash common.Hash, number uint64) *big.Int {
  207. dl.lock.RLock()
  208. defer dl.lock.RUnlock()
  209. return dl.getTd(hash)
  210. }
  211. // getTd retrieves the block's total difficulty if found either within
  212. // ancients or own blocks).
  213. // This method assumes that the caller holds at least the read-lock (dl.lock)
  214. func (dl *downloadTester) getTd(hash common.Hash) *big.Int {
  215. if td := dl.ancientChainTd[hash]; td != nil {
  216. return td
  217. }
  218. return dl.ownChainTd[hash]
  219. }
  220. // InsertHeaderChain injects a new batch of headers into the simulated chain.
  221. func (dl *downloadTester) InsertHeaderChain(headers []*types.Header, checkFreq int) (i int, err error) {
  222. dl.lock.Lock()
  223. defer dl.lock.Unlock()
  224. // Do a quick check, as the blockchain.InsertHeaderChain doesn't insert anything in case of errors
  225. if dl.getHeaderByHash(headers[0].ParentHash) == nil {
  226. return 0, fmt.Errorf("InsertHeaderChain: unknown parent at first position, parent of number %d", headers[0].Number)
  227. }
  228. var hashes []common.Hash
  229. for i := 1; i < len(headers); i++ {
  230. hash := headers[i-1].Hash()
  231. if headers[i].ParentHash != headers[i-1].Hash() {
  232. return i, fmt.Errorf("non-contiguous import at position %d", i)
  233. }
  234. hashes = append(hashes, hash)
  235. }
  236. hashes = append(hashes, headers[len(headers)-1].Hash())
  237. // Do a full insert if pre-checks passed
  238. for i, header := range headers {
  239. hash := hashes[i]
  240. if dl.getHeaderByHash(hash) != nil {
  241. continue
  242. }
  243. if dl.getHeaderByHash(header.ParentHash) == nil {
  244. // This _should_ be impossible, due to precheck and induction
  245. return i, fmt.Errorf("InsertHeaderChain: unknown parent at position %d", i)
  246. }
  247. dl.ownHashes = append(dl.ownHashes, hash)
  248. dl.ownHeaders[hash] = header
  249. td := dl.getTd(header.ParentHash)
  250. dl.ownChainTd[hash] = new(big.Int).Add(td, header.Difficulty)
  251. }
  252. return len(headers), nil
  253. }
  254. // InsertChain injects a new batch of blocks into the simulated chain.
  255. func (dl *downloadTester) InsertChain(blocks types.Blocks) (i int, err error) {
  256. dl.lock.Lock()
  257. defer dl.lock.Unlock()
  258. for i, block := range blocks {
  259. if parent, ok := dl.ownBlocks[block.ParentHash()]; !ok {
  260. return i, fmt.Errorf("InsertChain: unknown parent at position %d / %d", i, len(blocks))
  261. } else if _, err := dl.stateDb.Get(parent.Root().Bytes()); err != nil {
  262. return i, fmt.Errorf("InsertChain: unknown parent state %x: %v", parent.Root(), err)
  263. }
  264. if hdr := dl.getHeaderByHash(block.Hash()); hdr == nil {
  265. dl.ownHashes = append(dl.ownHashes, block.Hash())
  266. dl.ownHeaders[block.Hash()] = block.Header()
  267. }
  268. dl.ownBlocks[block.Hash()] = block
  269. dl.ownReceipts[block.Hash()] = make(types.Receipts, 0)
  270. dl.stateDb.Put(block.Root().Bytes(), []byte{0x00})
  271. td := dl.getTd(block.ParentHash())
  272. dl.ownChainTd[block.Hash()] = new(big.Int).Add(td, block.Difficulty())
  273. }
  274. return len(blocks), nil
  275. }
  276. // InsertReceiptChain injects a new batch of receipts into the simulated chain.
  277. func (dl *downloadTester) InsertReceiptChain(blocks types.Blocks, receipts []types.Receipts, ancientLimit uint64) (i int, err error) {
  278. dl.lock.Lock()
  279. defer dl.lock.Unlock()
  280. for i := 0; i < len(blocks) && i < len(receipts); i++ {
  281. if _, ok := dl.ownHeaders[blocks[i].Hash()]; !ok {
  282. return i, errors.New("unknown owner")
  283. }
  284. if _, ok := dl.ancientBlocks[blocks[i].ParentHash()]; !ok {
  285. if _, ok := dl.ownBlocks[blocks[i].ParentHash()]; !ok {
  286. return i, errors.New("InsertReceiptChain: unknown parent")
  287. }
  288. }
  289. if blocks[i].NumberU64() <= ancientLimit {
  290. dl.ancientBlocks[blocks[i].Hash()] = blocks[i]
  291. dl.ancientReceipts[blocks[i].Hash()] = receipts[i]
  292. // Migrate from active db to ancient db
  293. dl.ancientHeaders[blocks[i].Hash()] = blocks[i].Header()
  294. dl.ancientChainTd[blocks[i].Hash()] = new(big.Int).Add(dl.ancientChainTd[blocks[i].ParentHash()], blocks[i].Difficulty())
  295. delete(dl.ownHeaders, blocks[i].Hash())
  296. delete(dl.ownChainTd, blocks[i].Hash())
  297. } else {
  298. dl.ownBlocks[blocks[i].Hash()] = blocks[i]
  299. dl.ownReceipts[blocks[i].Hash()] = receipts[i]
  300. }
  301. }
  302. return len(blocks), nil
  303. }
  304. // SetHead rewinds the local chain to a new head.
  305. func (dl *downloadTester) SetHead(head uint64) error {
  306. dl.lock.Lock()
  307. defer dl.lock.Unlock()
  308. // Find the hash of the head to reset to
  309. var hash common.Hash
  310. for h, header := range dl.ownHeaders {
  311. if header.Number.Uint64() == head {
  312. hash = h
  313. }
  314. }
  315. for h, header := range dl.ancientHeaders {
  316. if header.Number.Uint64() == head {
  317. hash = h
  318. }
  319. }
  320. if hash == (common.Hash{}) {
  321. return fmt.Errorf("unknown head to set: %d", head)
  322. }
  323. // Find the offset in the header chain
  324. var offset int
  325. for o, h := range dl.ownHashes {
  326. if h == hash {
  327. offset = o
  328. break
  329. }
  330. }
  331. // Remove all the hashes and associated data afterwards
  332. for i := offset + 1; i < len(dl.ownHashes); i++ {
  333. delete(dl.ownChainTd, dl.ownHashes[i])
  334. delete(dl.ownHeaders, dl.ownHashes[i])
  335. delete(dl.ownReceipts, dl.ownHashes[i])
  336. delete(dl.ownBlocks, dl.ownHashes[i])
  337. delete(dl.ancientChainTd, dl.ownHashes[i])
  338. delete(dl.ancientHeaders, dl.ownHashes[i])
  339. delete(dl.ancientReceipts, dl.ownHashes[i])
  340. delete(dl.ancientBlocks, dl.ownHashes[i])
  341. }
  342. dl.ownHashes = dl.ownHashes[:offset+1]
  343. return nil
  344. }
  345. // Rollback removes some recently added elements from the chain.
  346. func (dl *downloadTester) Rollback(hashes []common.Hash) {
  347. }
  348. // newPeer registers a new block download source into the downloader.
  349. func (dl *downloadTester) newPeer(id string, version uint, chain *testChain) error {
  350. dl.lock.Lock()
  351. defer dl.lock.Unlock()
  352. peer := &downloadTesterPeer{dl: dl, id: id, chain: chain}
  353. dl.peers[id] = peer
  354. return dl.downloader.RegisterPeer(id, version, peer)
  355. }
  356. // dropPeer simulates a hard peer removal from the connection pool.
  357. func (dl *downloadTester) dropPeer(id string) {
  358. dl.lock.Lock()
  359. defer dl.lock.Unlock()
  360. delete(dl.peers, id)
  361. dl.downloader.UnregisterPeer(id)
  362. }
  363. type downloadTesterPeer struct {
  364. dl *downloadTester
  365. id string
  366. chain *testChain
  367. missingStates map[common.Hash]bool // State entries that fast sync should not return
  368. }
  369. // Head constructs a function to retrieve a peer's current head hash
  370. // and total difficulty.
  371. func (dlp *downloadTesterPeer) Head() (common.Hash, *big.Int) {
  372. b := dlp.chain.headBlock()
  373. return b.Hash(), dlp.chain.td(b.Hash())
  374. }
  375. // RequestHeadersByHash constructs a GetBlockHeaders function based on a hashed
  376. // origin; associated with a particular peer in the download tester. The returned
  377. // function can be used to retrieve batches of headers from the particular peer.
  378. func (dlp *downloadTesterPeer) RequestHeadersByHash(origin common.Hash, amount int, skip int, reverse bool) error {
  379. result := dlp.chain.headersByHash(origin, amount, skip, reverse)
  380. go dlp.dl.downloader.DeliverHeaders(dlp.id, result)
  381. return nil
  382. }
  383. // RequestHeadersByNumber constructs a GetBlockHeaders function based on a numbered
  384. // origin; associated with a particular peer in the download tester. The returned
  385. // function can be used to retrieve batches of headers from the particular peer.
  386. func (dlp *downloadTesterPeer) RequestHeadersByNumber(origin uint64, amount int, skip int, reverse bool) error {
  387. result := dlp.chain.headersByNumber(origin, amount, skip, reverse)
  388. go dlp.dl.downloader.DeliverHeaders(dlp.id, result)
  389. return nil
  390. }
  391. // RequestBodies constructs a getBlockBodies method associated with a particular
  392. // peer in the download tester. The returned function can be used to retrieve
  393. // batches of block bodies from the particularly requested peer.
  394. func (dlp *downloadTesterPeer) RequestBodies(hashes []common.Hash) error {
  395. txs, uncles := dlp.chain.bodies(hashes)
  396. go dlp.dl.downloader.DeliverBodies(dlp.id, txs, uncles)
  397. return nil
  398. }
  399. // RequestReceipts constructs a getReceipts method associated with a particular
  400. // peer in the download tester. The returned function can be used to retrieve
  401. // batches of block receipts from the particularly requested peer.
  402. func (dlp *downloadTesterPeer) RequestReceipts(hashes []common.Hash) error {
  403. receipts := dlp.chain.receipts(hashes)
  404. go dlp.dl.downloader.DeliverReceipts(dlp.id, receipts)
  405. return nil
  406. }
  407. // RequestNodeData constructs a getNodeData method associated with a particular
  408. // peer in the download tester. The returned function can be used to retrieve
  409. // batches of node state data from the particularly requested peer.
  410. func (dlp *downloadTesterPeer) RequestNodeData(hashes []common.Hash) error {
  411. dlp.dl.lock.RLock()
  412. defer dlp.dl.lock.RUnlock()
  413. results := make([][]byte, 0, len(hashes))
  414. for _, hash := range hashes {
  415. if data, err := dlp.dl.peerDb.Get(hash.Bytes()); err == nil {
  416. if !dlp.missingStates[hash] {
  417. results = append(results, data)
  418. }
  419. }
  420. }
  421. go dlp.dl.downloader.DeliverNodeData(dlp.id, results)
  422. return nil
  423. }
  424. // assertOwnChain checks if the local chain contains the correct number of items
  425. // of the various chain components.
  426. func assertOwnChain(t *testing.T, tester *downloadTester, length int) {
  427. // Mark this method as a helper to report errors at callsite, not in here
  428. t.Helper()
  429. assertOwnForkedChain(t, tester, 1, []int{length})
  430. }
  431. // assertOwnForkedChain checks if the local forked chain contains the correct
  432. // number of items of the various chain components.
  433. func assertOwnForkedChain(t *testing.T, tester *downloadTester, common int, lengths []int) {
  434. // Mark this method as a helper to report errors at callsite, not in here
  435. t.Helper()
  436. // Initialize the counters for the first fork
  437. headers, blocks, receipts := lengths[0], lengths[0], lengths[0]
  438. // Update the counters for each subsequent fork
  439. for _, length := range lengths[1:] {
  440. headers += length - common
  441. blocks += length - common
  442. receipts += length - common
  443. }
  444. if tester.downloader.getMode() == LightSync {
  445. blocks, receipts = 1, 1
  446. }
  447. if hs := len(tester.ownHeaders) + len(tester.ancientHeaders) - 1; hs != headers {
  448. t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, headers)
  449. }
  450. if bs := len(tester.ownBlocks) + len(tester.ancientBlocks) - 1; bs != blocks {
  451. t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, blocks)
  452. }
  453. if rs := len(tester.ownReceipts) + len(tester.ancientReceipts) - 1; rs != receipts {
  454. t.Fatalf("synchronised receipts mismatch: have %v, want %v", rs, receipts)
  455. }
  456. }
  457. func TestCanonicalSynchronisation64Full(t *testing.T) { testCanonSync(t, 64, FullSync) }
  458. func TestCanonicalSynchronisation64Fast(t *testing.T) { testCanonSync(t, 64, FastSync) }
  459. func TestCanonicalSynchronisation65Full(t *testing.T) { testCanonSync(t, 65, FullSync) }
  460. func TestCanonicalSynchronisation65Fast(t *testing.T) { testCanonSync(t, 65, FastSync) }
  461. func TestCanonicalSynchronisation65Light(t *testing.T) { testCanonSync(t, 65, LightSync) }
  462. func TestCanonicalSynchronisation66Full(t *testing.T) { testCanonSync(t, 66, FullSync) }
  463. func TestCanonicalSynchronisation66Fast(t *testing.T) { testCanonSync(t, 66, FastSync) }
  464. func TestCanonicalSynchronisation66Light(t *testing.T) { testCanonSync(t, 66, LightSync) }
  465. func testCanonSync(t *testing.T, protocol uint, mode SyncMode) {
  466. t.Parallel()
  467. tester := newTester()
  468. defer tester.terminate()
  469. // Create a small enough block chain to download
  470. chain := testChainBase.shorten(blockCacheMaxItems - 15)
  471. tester.newPeer("peer", protocol, chain)
  472. // Synchronise with the peer and make sure all relevant data was retrieved
  473. if err := tester.sync("peer", nil, mode); err != nil {
  474. t.Fatalf("failed to synchronise blocks: %v", err)
  475. }
  476. assertOwnChain(t, tester, chain.len())
  477. }
  478. // Tests that if a large batch of blocks are being downloaded, it is throttled
  479. // until the cached blocks are retrieved.
  480. func TestThrottling64Full(t *testing.T) { testThrottling(t, 64, FullSync) }
  481. func TestThrottling64Fast(t *testing.T) { testThrottling(t, 64, FastSync) }
  482. func TestThrottling65Full(t *testing.T) { testThrottling(t, 65, FullSync) }
  483. func TestThrottling65Fast(t *testing.T) { testThrottling(t, 65, FastSync) }
  484. func TestThrottling66Full(t *testing.T) { testThrottling(t, 66, FullSync) }
  485. func TestThrottling66Fast(t *testing.T) { testThrottling(t, 66, FastSync) }
  486. func testThrottling(t *testing.T, protocol uint, mode SyncMode) {
  487. t.Parallel()
  488. tester := newTester()
  489. // Create a long block chain to download and the tester
  490. targetBlocks := testChainBase.len() - 1
  491. tester.newPeer("peer", protocol, testChainBase)
  492. // Wrap the importer to allow stepping
  493. blocked, proceed := uint32(0), make(chan struct{})
  494. tester.downloader.chainInsertHook = func(results []*fetchResult) {
  495. atomic.StoreUint32(&blocked, uint32(len(results)))
  496. <-proceed
  497. }
  498. // Start a synchronisation concurrently
  499. errc := make(chan error, 1)
  500. go func() {
  501. errc <- tester.sync("peer", nil, mode)
  502. }()
  503. // Iteratively take some blocks, always checking the retrieval count
  504. for {
  505. // Check the retrieval count synchronously (! reason for this ugly block)
  506. tester.lock.RLock()
  507. retrieved := len(tester.ownBlocks)
  508. tester.lock.RUnlock()
  509. if retrieved >= targetBlocks+1 {
  510. break
  511. }
  512. // Wait a bit for sync to throttle itself
  513. var cached, frozen int
  514. for start := time.Now(); time.Since(start) < 3*time.Second; {
  515. time.Sleep(25 * time.Millisecond)
  516. tester.lock.Lock()
  517. tester.downloader.queue.lock.Lock()
  518. tester.downloader.queue.resultCache.lock.Lock()
  519. {
  520. cached = tester.downloader.queue.resultCache.countCompleted()
  521. frozen = int(atomic.LoadUint32(&blocked))
  522. retrieved = len(tester.ownBlocks)
  523. }
  524. tester.downloader.queue.resultCache.lock.Unlock()
  525. tester.downloader.queue.lock.Unlock()
  526. tester.lock.Unlock()
  527. if cached == blockCacheMaxItems ||
  528. cached == blockCacheMaxItems-reorgProtHeaderDelay ||
  529. retrieved+cached+frozen == targetBlocks+1 ||
  530. retrieved+cached+frozen == targetBlocks+1-reorgProtHeaderDelay {
  531. break
  532. }
  533. }
  534. // Make sure we filled up the cache, then exhaust it
  535. time.Sleep(25 * time.Millisecond) // give it a chance to screw up
  536. tester.lock.RLock()
  537. retrieved = len(tester.ownBlocks)
  538. tester.lock.RUnlock()
  539. if cached != blockCacheMaxItems && cached != blockCacheMaxItems-reorgProtHeaderDelay && retrieved+cached+frozen != targetBlocks+1 && retrieved+cached+frozen != targetBlocks+1-reorgProtHeaderDelay {
  540. t.Fatalf("block count mismatch: have %v, want %v (owned %v, blocked %v, target %v)", cached, blockCacheMaxItems, retrieved, frozen, targetBlocks+1)
  541. }
  542. // Permit the blocked blocks to import
  543. if atomic.LoadUint32(&blocked) > 0 {
  544. atomic.StoreUint32(&blocked, uint32(0))
  545. proceed <- struct{}{}
  546. }
  547. }
  548. // Check that we haven't pulled more blocks than available
  549. assertOwnChain(t, tester, targetBlocks+1)
  550. if err := <-errc; err != nil {
  551. t.Fatalf("block synchronization failed: %v", err)
  552. }
  553. tester.terminate()
  554. }
  555. // Tests that simple synchronization against a forked chain works correctly. In
  556. // this test common ancestor lookup should *not* be short circuited, and a full
  557. // binary search should be executed.
  558. func TestForkedSync64Full(t *testing.T) { testForkedSync(t, 64, FullSync) }
  559. func TestForkedSync64Fast(t *testing.T) { testForkedSync(t, 64, FastSync) }
  560. func TestForkedSync65Full(t *testing.T) { testForkedSync(t, 65, FullSync) }
  561. func TestForkedSync65Fast(t *testing.T) { testForkedSync(t, 65, FastSync) }
  562. func TestForkedSync65Light(t *testing.T) { testForkedSync(t, 65, LightSync) }
  563. func TestForkedSync66Full(t *testing.T) { testForkedSync(t, 66, FullSync) }
  564. func TestForkedSync66Fast(t *testing.T) { testForkedSync(t, 66, FastSync) }
  565. func TestForkedSync66Light(t *testing.T) { testForkedSync(t, 66, LightSync) }
  566. func testForkedSync(t *testing.T, protocol uint, mode SyncMode) {
  567. t.Parallel()
  568. tester := newTester()
  569. defer tester.terminate()
  570. chainA := testChainForkLightA.shorten(testChainBase.len() + 80)
  571. chainB := testChainForkLightB.shorten(testChainBase.len() + 80)
  572. tester.newPeer("fork A", protocol, chainA)
  573. tester.newPeer("fork B", protocol, chainB)
  574. // Synchronise with the peer and make sure all blocks were retrieved
  575. if err := tester.sync("fork A", nil, mode); err != nil {
  576. t.Fatalf("failed to synchronise blocks: %v", err)
  577. }
  578. assertOwnChain(t, tester, chainA.len())
  579. // Synchronise with the second peer and make sure that fork is pulled too
  580. if err := tester.sync("fork B", nil, mode); err != nil {
  581. t.Fatalf("failed to synchronise blocks: %v", err)
  582. }
  583. assertOwnForkedChain(t, tester, testChainBase.len(), []int{chainA.len(), chainB.len()})
  584. }
  585. // Tests that synchronising against a much shorter but much heavyer fork works
  586. // corrently and is not dropped.
  587. func TestHeavyForkedSync64Full(t *testing.T) { testHeavyForkedSync(t, 64, FullSync) }
  588. func TestHeavyForkedSync64Fast(t *testing.T) { testHeavyForkedSync(t, 64, FastSync) }
  589. func TestHeavyForkedSync65Full(t *testing.T) { testHeavyForkedSync(t, 65, FullSync) }
  590. func TestHeavyForkedSync65Fast(t *testing.T) { testHeavyForkedSync(t, 65, FastSync) }
  591. func TestHeavyForkedSync65Light(t *testing.T) { testHeavyForkedSync(t, 65, LightSync) }
  592. func TestHeavyForkedSync66Full(t *testing.T) { testHeavyForkedSync(t, 66, FullSync) }
  593. func TestHeavyForkedSync66Fast(t *testing.T) { testHeavyForkedSync(t, 66, FastSync) }
  594. func TestHeavyForkedSync66Light(t *testing.T) { testHeavyForkedSync(t, 66, LightSync) }
  595. func testHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) {
  596. t.Parallel()
  597. tester := newTester()
  598. defer tester.terminate()
  599. chainA := testChainForkLightA.shorten(testChainBase.len() + 80)
  600. chainB := testChainForkHeavy.shorten(testChainBase.len() + 80)
  601. tester.newPeer("light", protocol, chainA)
  602. tester.newPeer("heavy", protocol, chainB)
  603. // Synchronise with the peer and make sure all blocks were retrieved
  604. if err := tester.sync("light", nil, mode); err != nil {
  605. t.Fatalf("failed to synchronise blocks: %v", err)
  606. }
  607. assertOwnChain(t, tester, chainA.len())
  608. // Synchronise with the second peer and make sure that fork is pulled too
  609. if err := tester.sync("heavy", nil, mode); err != nil {
  610. t.Fatalf("failed to synchronise blocks: %v", err)
  611. }
  612. assertOwnForkedChain(t, tester, testChainBase.len(), []int{chainA.len(), chainB.len()})
  613. }
  614. // Tests that chain forks are contained within a certain interval of the current
  615. // chain head, ensuring that malicious peers cannot waste resources by feeding
  616. // long dead chains.
  617. func TestBoundedForkedSync64Full(t *testing.T) { testBoundedForkedSync(t, 64, FullSync) }
  618. func TestBoundedForkedSync64Fast(t *testing.T) { testBoundedForkedSync(t, 64, FastSync) }
  619. func TestBoundedForkedSync65Full(t *testing.T) { testBoundedForkedSync(t, 65, FullSync) }
  620. func TestBoundedForkedSync65Fast(t *testing.T) { testBoundedForkedSync(t, 65, FastSync) }
  621. func TestBoundedForkedSync65Light(t *testing.T) { testBoundedForkedSync(t, 65, LightSync) }
  622. func TestBoundedForkedSync66Full(t *testing.T) { testBoundedForkedSync(t, 66, FullSync) }
  623. func TestBoundedForkedSync66Fast(t *testing.T) { testBoundedForkedSync(t, 66, FastSync) }
  624. func TestBoundedForkedSync66Light(t *testing.T) { testBoundedForkedSync(t, 66, LightSync) }
  625. func testBoundedForkedSync(t *testing.T, protocol uint, mode SyncMode) {
  626. t.Parallel()
  627. tester := newTester()
  628. defer tester.terminate()
  629. chainA := testChainForkLightA
  630. chainB := testChainForkLightB
  631. tester.newPeer("original", protocol, chainA)
  632. tester.newPeer("rewriter", protocol, chainB)
  633. // Synchronise with the peer and make sure all blocks were retrieved
  634. if err := tester.sync("original", nil, mode); err != nil {
  635. t.Fatalf("failed to synchronise blocks: %v", err)
  636. }
  637. assertOwnChain(t, tester, chainA.len())
  638. // Synchronise with the second peer and ensure that the fork is rejected to being too old
  639. if err := tester.sync("rewriter", nil, mode); err != errInvalidAncestor {
  640. t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor)
  641. }
  642. }
  643. // Tests that chain forks are contained within a certain interval of the current
  644. // chain head for short but heavy forks too. These are a bit special because they
  645. // take different ancestor lookup paths.
  646. func TestBoundedHeavyForkedSync64Full(t *testing.T) { testBoundedHeavyForkedSync(t, 64, FullSync) }
  647. func TestBoundedHeavyForkedSync64Fast(t *testing.T) { testBoundedHeavyForkedSync(t, 64, FastSync) }
  648. func TestBoundedHeavyForkedSync65Full(t *testing.T) { testBoundedHeavyForkedSync(t, 65, FullSync) }
  649. func TestBoundedHeavyForkedSync65Fast(t *testing.T) { testBoundedHeavyForkedSync(t, 65, FastSync) }
  650. func TestBoundedHeavyForkedSync65Light(t *testing.T) { testBoundedHeavyForkedSync(t, 65, LightSync) }
  651. func TestBoundedHeavyForkedSync66Full(t *testing.T) { testBoundedHeavyForkedSync(t, 66, FullSync) }
  652. func TestBoundedHeavyForkedSync66Fast(t *testing.T) { testBoundedHeavyForkedSync(t, 66, FastSync) }
  653. func TestBoundedHeavyForkedSync66Light(t *testing.T) { testBoundedHeavyForkedSync(t, 66, LightSync) }
  654. func testBoundedHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) {
  655. t.Parallel()
  656. tester := newTester()
  657. // Create a long enough forked chain
  658. chainA := testChainForkLightA
  659. chainB := testChainForkHeavy
  660. tester.newPeer("original", protocol, chainA)
  661. // Synchronise with the peer and make sure all blocks were retrieved
  662. if err := tester.sync("original", nil, mode); err != nil {
  663. t.Fatalf("failed to synchronise blocks: %v", err)
  664. }
  665. assertOwnChain(t, tester, chainA.len())
  666. tester.newPeer("heavy-rewriter", protocol, chainB)
  667. // Synchronise with the second peer and ensure that the fork is rejected to being too old
  668. if err := tester.sync("heavy-rewriter", nil, mode); err != errInvalidAncestor {
  669. t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor)
  670. }
  671. tester.terminate()
  672. }
  673. // Tests that an inactive downloader will not accept incoming block headers,
  674. // bodies and receipts.
  675. func TestInactiveDownloader63(t *testing.T) {
  676. t.Parallel()
  677. tester := newTester()
  678. defer tester.terminate()
  679. // Check that neither block headers nor bodies are accepted
  680. if err := tester.downloader.DeliverHeaders("bad peer", []*types.Header{}); err != errNoSyncActive {
  681. t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
  682. }
  683. if err := tester.downloader.DeliverBodies("bad peer", [][]*types.Transaction{}, [][]*types.Header{}); err != errNoSyncActive {
  684. t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
  685. }
  686. if err := tester.downloader.DeliverReceipts("bad peer", [][]*types.Receipt{}); err != errNoSyncActive {
  687. t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
  688. }
  689. }
  690. // Tests that a canceled download wipes all previously accumulated state.
  691. func TestCancel64Full(t *testing.T) { testCancel(t, 64, FullSync) }
  692. func TestCancel64Fast(t *testing.T) { testCancel(t, 64, FastSync) }
  693. func TestCancel65Full(t *testing.T) { testCancel(t, 65, FullSync) }
  694. func TestCancel65Fast(t *testing.T) { testCancel(t, 65, FastSync) }
  695. func TestCancel65Light(t *testing.T) { testCancel(t, 65, LightSync) }
  696. func TestCancel66Full(t *testing.T) { testCancel(t, 66, FullSync) }
  697. func TestCancel66Fast(t *testing.T) { testCancel(t, 66, FastSync) }
  698. func TestCancel66Light(t *testing.T) { testCancel(t, 66, LightSync) }
  699. func testCancel(t *testing.T, protocol uint, mode SyncMode) {
  700. t.Parallel()
  701. tester := newTester()
  702. defer tester.terminate()
  703. chain := testChainBase.shorten(MaxHeaderFetch)
  704. tester.newPeer("peer", protocol, chain)
  705. // Make sure canceling works with a pristine downloader
  706. tester.downloader.Cancel()
  707. if !tester.downloader.queue.Idle() {
  708. t.Errorf("download queue not idle")
  709. }
  710. // Synchronise with the peer, but cancel afterwards
  711. if err := tester.sync("peer", nil, mode); err != nil {
  712. t.Fatalf("failed to synchronise blocks: %v", err)
  713. }
  714. tester.downloader.Cancel()
  715. if !tester.downloader.queue.Idle() {
  716. t.Errorf("download queue not idle")
  717. }
  718. }
  719. // Tests that synchronisation from multiple peers works as intended (multi thread sanity test).
  720. func TestMultiSynchronisation64Full(t *testing.T) { testMultiSynchronisation(t, 64, FullSync) }
  721. func TestMultiSynchronisation64Fast(t *testing.T) { testMultiSynchronisation(t, 64, FastSync) }
  722. func TestMultiSynchronisation65Full(t *testing.T) { testMultiSynchronisation(t, 65, FullSync) }
  723. func TestMultiSynchronisation65Fast(t *testing.T) { testMultiSynchronisation(t, 65, FastSync) }
  724. func TestMultiSynchronisation65Light(t *testing.T) { testMultiSynchronisation(t, 65, LightSync) }
  725. func TestMultiSynchronisation66Full(t *testing.T) { testMultiSynchronisation(t, 66, FullSync) }
  726. func TestMultiSynchronisation66Fast(t *testing.T) { testMultiSynchronisation(t, 66, FastSync) }
  727. func TestMultiSynchronisation66Light(t *testing.T) { testMultiSynchronisation(t, 66, LightSync) }
  728. func testMultiSynchronisation(t *testing.T, protocol uint, mode SyncMode) {
  729. t.Parallel()
  730. tester := newTester()
  731. defer tester.terminate()
  732. // Create various peers with various parts of the chain
  733. targetPeers := 8
  734. chain := testChainBase.shorten(targetPeers * 100)
  735. for i := 0; i < targetPeers; i++ {
  736. id := fmt.Sprintf("peer #%d", i)
  737. tester.newPeer(id, protocol, chain.shorten(chain.len()/(i+1)))
  738. }
  739. if err := tester.sync("peer #0", nil, mode); err != nil {
  740. t.Fatalf("failed to synchronise blocks: %v", err)
  741. }
  742. assertOwnChain(t, tester, chain.len())
  743. }
  744. // Tests that synchronisations behave well in multi-version protocol environments
  745. // and not wreak havoc on other nodes in the network.
  746. func TestMultiProtoSynchronisation64Full(t *testing.T) { testMultiProtoSync(t, 64, FullSync) }
  747. func TestMultiProtoSynchronisation64Fast(t *testing.T) { testMultiProtoSync(t, 64, FastSync) }
  748. func TestMultiProtoSynchronisation65Full(t *testing.T) { testMultiProtoSync(t, 65, FullSync) }
  749. func TestMultiProtoSynchronisation65Fast(t *testing.T) { testMultiProtoSync(t, 65, FastSync) }
  750. func TestMultiProtoSynchronisation65Light(t *testing.T) { testMultiProtoSync(t, 65, LightSync) }
  751. func TestMultiProtoSynchronisation66Full(t *testing.T) { testMultiProtoSync(t, 66, FullSync) }
  752. func TestMultiProtoSynchronisation66Fast(t *testing.T) { testMultiProtoSync(t, 66, FastSync) }
  753. func TestMultiProtoSynchronisation66Light(t *testing.T) { testMultiProtoSync(t, 66, LightSync) }
  754. func testMultiProtoSync(t *testing.T, protocol uint, mode SyncMode) {
  755. t.Parallel()
  756. tester := newTester()
  757. defer tester.terminate()
  758. // Create a small enough block chain to download
  759. chain := testChainBase.shorten(blockCacheMaxItems - 15)
  760. // Create peers of every type
  761. tester.newPeer("peer 64", 64, chain)
  762. tester.newPeer("peer 65", 65, chain)
  763. tester.newPeer("peer 66", 66, chain)
  764. // Synchronise with the requested peer and make sure all blocks were retrieved
  765. if err := tester.sync(fmt.Sprintf("peer %d", protocol), nil, mode); err != nil {
  766. t.Fatalf("failed to synchronise blocks: %v", err)
  767. }
  768. assertOwnChain(t, tester, chain.len())
  769. // Check that no peers have been dropped off
  770. for _, version := range []int{64, 65, 66} {
  771. peer := fmt.Sprintf("peer %d", version)
  772. if _, ok := tester.peers[peer]; !ok {
  773. t.Errorf("%s dropped", peer)
  774. }
  775. }
  776. }
  777. // Tests that if a block is empty (e.g. header only), no body request should be
  778. // made, and instead the header should be assembled into a whole block in itself.
  779. func TestEmptyShortCircuit64Full(t *testing.T) { testEmptyShortCircuit(t, 64, FullSync) }
  780. func TestEmptyShortCircuit64Fast(t *testing.T) { testEmptyShortCircuit(t, 64, FastSync) }
  781. func TestEmptyShortCircuit65Full(t *testing.T) { testEmptyShortCircuit(t, 65, FullSync) }
  782. func TestEmptyShortCircuit65Fast(t *testing.T) { testEmptyShortCircuit(t, 65, FastSync) }
  783. func TestEmptyShortCircuit65Light(t *testing.T) { testEmptyShortCircuit(t, 65, LightSync) }
  784. func TestEmptyShortCircuit66Full(t *testing.T) { testEmptyShortCircuit(t, 66, FullSync) }
  785. func TestEmptyShortCircuit66Fast(t *testing.T) { testEmptyShortCircuit(t, 66, FastSync) }
  786. func TestEmptyShortCircuit66Light(t *testing.T) { testEmptyShortCircuit(t, 66, LightSync) }
  787. func testEmptyShortCircuit(t *testing.T, protocol uint, mode SyncMode) {
  788. t.Parallel()
  789. tester := newTester()
  790. defer tester.terminate()
  791. // Create a block chain to download
  792. chain := testChainBase
  793. tester.newPeer("peer", protocol, chain)
  794. // Instrument the downloader to signal body requests
  795. bodiesHave, receiptsHave := int32(0), int32(0)
  796. tester.downloader.bodyFetchHook = func(headers []*types.Header) {
  797. atomic.AddInt32(&bodiesHave, int32(len(headers)))
  798. }
  799. tester.downloader.receiptFetchHook = func(headers []*types.Header) {
  800. atomic.AddInt32(&receiptsHave, int32(len(headers)))
  801. }
  802. // Synchronise with the peer and make sure all blocks were retrieved
  803. if err := tester.sync("peer", nil, mode); err != nil {
  804. t.Fatalf("failed to synchronise blocks: %v", err)
  805. }
  806. assertOwnChain(t, tester, chain.len())
  807. // Validate the number of block bodies that should have been requested
  808. bodiesNeeded, receiptsNeeded := 0, 0
  809. for _, block := range chain.blockm {
  810. if mode != LightSync && block != tester.genesis && (len(block.Transactions()) > 0 || len(block.Uncles()) > 0) {
  811. bodiesNeeded++
  812. }
  813. }
  814. for _, receipt := range chain.receiptm {
  815. if mode == FastSync && len(receipt) > 0 {
  816. receiptsNeeded++
  817. }
  818. }
  819. if int(bodiesHave) != bodiesNeeded {
  820. t.Errorf("body retrieval count mismatch: have %v, want %v", bodiesHave, bodiesNeeded)
  821. }
  822. if int(receiptsHave) != receiptsNeeded {
  823. t.Errorf("receipt retrieval count mismatch: have %v, want %v", receiptsHave, receiptsNeeded)
  824. }
  825. }
  826. // Tests that headers are enqueued continuously, preventing malicious nodes from
  827. // stalling the downloader by feeding gapped header chains.
  828. func TestMissingHeaderAttack64Full(t *testing.T) { testMissingHeaderAttack(t, 64, FullSync) }
  829. func TestMissingHeaderAttack64Fast(t *testing.T) { testMissingHeaderAttack(t, 64, FastSync) }
  830. func TestMissingHeaderAttack65Full(t *testing.T) { testMissingHeaderAttack(t, 65, FullSync) }
  831. func TestMissingHeaderAttack65Fast(t *testing.T) { testMissingHeaderAttack(t, 65, FastSync) }
  832. func TestMissingHeaderAttack65Light(t *testing.T) { testMissingHeaderAttack(t, 65, LightSync) }
  833. func TestMissingHeaderAttack66Full(t *testing.T) { testMissingHeaderAttack(t, 66, FullSync) }
  834. func TestMissingHeaderAttack66Fast(t *testing.T) { testMissingHeaderAttack(t, 66, FastSync) }
  835. func TestMissingHeaderAttack66Light(t *testing.T) { testMissingHeaderAttack(t, 66, LightSync) }
  836. func testMissingHeaderAttack(t *testing.T, protocol uint, mode SyncMode) {
  837. t.Parallel()
  838. tester := newTester()
  839. defer tester.terminate()
  840. chain := testChainBase.shorten(blockCacheMaxItems - 15)
  841. brokenChain := chain.shorten(chain.len())
  842. delete(brokenChain.headerm, brokenChain.chain[brokenChain.len()/2])
  843. tester.newPeer("attack", protocol, brokenChain)
  844. if err := tester.sync("attack", nil, mode); err == nil {
  845. t.Fatalf("succeeded attacker synchronisation")
  846. }
  847. // Synchronise with the valid peer and make sure sync succeeds
  848. tester.newPeer("valid", protocol, chain)
  849. if err := tester.sync("valid", nil, mode); err != nil {
  850. t.Fatalf("failed to synchronise blocks: %v", err)
  851. }
  852. assertOwnChain(t, tester, chain.len())
  853. }
  854. // Tests that if requested headers are shifted (i.e. first is missing), the queue
  855. // detects the invalid numbering.
  856. func TestShiftedHeaderAttack64Full(t *testing.T) { testShiftedHeaderAttack(t, 64, FullSync) }
  857. func TestShiftedHeaderAttack64Fast(t *testing.T) { testShiftedHeaderAttack(t, 64, FastSync) }
  858. func TestShiftedHeaderAttack65Full(t *testing.T) { testShiftedHeaderAttack(t, 65, FullSync) }
  859. func TestShiftedHeaderAttack65Fast(t *testing.T) { testShiftedHeaderAttack(t, 65, FastSync) }
  860. func TestShiftedHeaderAttack65Light(t *testing.T) { testShiftedHeaderAttack(t, 65, LightSync) }
  861. func TestShiftedHeaderAttack66Full(t *testing.T) { testShiftedHeaderAttack(t, 66, FullSync) }
  862. func TestShiftedHeaderAttack66Fast(t *testing.T) { testShiftedHeaderAttack(t, 66, FastSync) }
  863. func TestShiftedHeaderAttack66Light(t *testing.T) { testShiftedHeaderAttack(t, 66, LightSync) }
  864. func testShiftedHeaderAttack(t *testing.T, protocol uint, mode SyncMode) {
  865. t.Parallel()
  866. tester := newTester()
  867. defer tester.terminate()
  868. chain := testChainBase.shorten(blockCacheMaxItems - 15)
  869. // Attempt a full sync with an attacker feeding shifted headers
  870. brokenChain := chain.shorten(chain.len())
  871. delete(brokenChain.headerm, brokenChain.chain[1])
  872. delete(brokenChain.blockm, brokenChain.chain[1])
  873. delete(brokenChain.receiptm, brokenChain.chain[1])
  874. tester.newPeer("attack", protocol, brokenChain)
  875. if err := tester.sync("attack", nil, mode); err == nil {
  876. t.Fatalf("succeeded attacker synchronisation")
  877. }
  878. // Synchronise with the valid peer and make sure sync succeeds
  879. tester.newPeer("valid", protocol, chain)
  880. if err := tester.sync("valid", nil, mode); err != nil {
  881. t.Fatalf("failed to synchronise blocks: %v", err)
  882. }
  883. assertOwnChain(t, tester, chain.len())
  884. }
  885. // Tests that upon detecting an invalid header, the recent ones are rolled back
  886. // for various failure scenarios. Afterwards a full sync is attempted to make
  887. // sure no state was corrupted.
  888. func TestInvalidHeaderRollback64Fast(t *testing.T) { testInvalidHeaderRollback(t, 64, FastSync) }
  889. func TestInvalidHeaderRollback65Fast(t *testing.T) { testInvalidHeaderRollback(t, 65, FastSync) }
  890. func TestInvalidHeaderRollback66Fast(t *testing.T) { testInvalidHeaderRollback(t, 66, FastSync) }
  891. func testInvalidHeaderRollback(t *testing.T, protocol uint, mode SyncMode) {
  892. t.Parallel()
  893. tester := newTester()
  894. // Create a small enough block chain to download
  895. targetBlocks := 3*fsHeaderSafetyNet + 256 + fsMinFullBlocks
  896. chain := testChainBase.shorten(targetBlocks)
  897. // Attempt to sync with an attacker that feeds junk during the fast sync phase.
  898. // This should result in the last fsHeaderSafetyNet headers being rolled back.
  899. missing := fsHeaderSafetyNet + MaxHeaderFetch + 1
  900. fastAttackChain := chain.shorten(chain.len())
  901. delete(fastAttackChain.headerm, fastAttackChain.chain[missing])
  902. tester.newPeer("fast-attack", protocol, fastAttackChain)
  903. if err := tester.sync("fast-attack", nil, mode); err == nil {
  904. t.Fatalf("succeeded fast attacker synchronisation")
  905. }
  906. if head := tester.CurrentHeader().Number.Int64(); int(head) > MaxHeaderFetch {
  907. t.Errorf("rollback head mismatch: have %v, want at most %v", head, MaxHeaderFetch)
  908. }
  909. // Attempt to sync with an attacker that feeds junk during the block import phase.
  910. // This should result in both the last fsHeaderSafetyNet number of headers being
  911. // rolled back, and also the pivot point being reverted to a non-block status.
  912. missing = 3*fsHeaderSafetyNet + MaxHeaderFetch + 1
  913. blockAttackChain := chain.shorten(chain.len())
  914. delete(fastAttackChain.headerm, fastAttackChain.chain[missing]) // Make sure the fast-attacker doesn't fill in
  915. delete(blockAttackChain.headerm, blockAttackChain.chain[missing])
  916. tester.newPeer("block-attack", protocol, blockAttackChain)
  917. if err := tester.sync("block-attack", nil, mode); err == nil {
  918. t.Fatalf("succeeded block attacker synchronisation")
  919. }
  920. if head := tester.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
  921. t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
  922. }
  923. if mode == FastSync {
  924. if head := tester.CurrentBlock().NumberU64(); head != 0 {
  925. t.Errorf("fast sync pivot block #%d not rolled back", head)
  926. }
  927. }
  928. // Attempt to sync with an attacker that withholds promised blocks after the
  929. // fast sync pivot point. This could be a trial to leave the node with a bad
  930. // but already imported pivot block.
  931. withholdAttackChain := chain.shorten(chain.len())
  932. tester.newPeer("withhold-attack", protocol, withholdAttackChain)
  933. tester.downloader.syncInitHook = func(uint64, uint64) {
  934. for i := missing; i < withholdAttackChain.len(); i++ {
  935. delete(withholdAttackChain.headerm, withholdAttackChain.chain[i])
  936. }
  937. tester.downloader.syncInitHook = nil
  938. }
  939. if err := tester.sync("withhold-attack", nil, mode); err == nil {
  940. t.Fatalf("succeeded withholding attacker synchronisation")
  941. }
  942. if head := tester.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
  943. t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
  944. }
  945. if mode == FastSync {
  946. if head := tester.CurrentBlock().NumberU64(); head != 0 {
  947. t.Errorf("fast sync pivot block #%d not rolled back", head)
  948. }
  949. }
  950. // synchronise with the valid peer and make sure sync succeeds. Since the last rollback
  951. // should also disable fast syncing for this process, verify that we did a fresh full
  952. // sync. Note, we can't assert anything about the receipts since we won't purge the
  953. // database of them, hence we can't use assertOwnChain.
  954. tester.newPeer("valid", protocol, chain)
  955. if err := tester.sync("valid", nil, mode); err != nil {
  956. t.Fatalf("failed to synchronise blocks: %v", err)
  957. }
  958. if hs := len(tester.ownHeaders); hs != chain.len() {
  959. t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, chain.len())
  960. }
  961. if mode != LightSync {
  962. if bs := len(tester.ownBlocks); bs != chain.len() {
  963. t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, chain.len())
  964. }
  965. }
  966. tester.terminate()
  967. }
  968. // Tests that a peer advertising a high TD doesn't get to stall the downloader
  969. // afterwards by not sending any useful hashes.
  970. func TestHighTDStarvationAttack64Full(t *testing.T) { testHighTDStarvationAttack(t, 64, FullSync) }
  971. func TestHighTDStarvationAttack64Fast(t *testing.T) { testHighTDStarvationAttack(t, 64, FastSync) }
  972. func TestHighTDStarvationAttack65Full(t *testing.T) { testHighTDStarvationAttack(t, 65, FullSync) }
  973. func TestHighTDStarvationAttack65Fast(t *testing.T) { testHighTDStarvationAttack(t, 65, FastSync) }
  974. func TestHighTDStarvationAttack65Light(t *testing.T) { testHighTDStarvationAttack(t, 65, LightSync) }
  975. func TestHighTDStarvationAttack66Full(t *testing.T) { testHighTDStarvationAttack(t, 66, FullSync) }
  976. func TestHighTDStarvationAttack66Fast(t *testing.T) { testHighTDStarvationAttack(t, 66, FastSync) }
  977. func TestHighTDStarvationAttack66Light(t *testing.T) { testHighTDStarvationAttack(t, 66, LightSync) }
  978. func testHighTDStarvationAttack(t *testing.T, protocol uint, mode SyncMode) {
  979. t.Parallel()
  980. tester := newTester()
  981. chain := testChainBase.shorten(1)
  982. tester.newPeer("attack", protocol, chain)
  983. if err := tester.sync("attack", big.NewInt(1000000), mode); err != errStallingPeer {
  984. t.Fatalf("synchronisation error mismatch: have %v, want %v", err, errStallingPeer)
  985. }
  986. tester.terminate()
  987. }
  988. // Tests that misbehaving peers are disconnected, whilst behaving ones are not.
  989. func TestBlockHeaderAttackerDropping64(t *testing.T) { testBlockHeaderAttackerDropping(t, 64) }
  990. func TestBlockHeaderAttackerDropping65(t *testing.T) { testBlockHeaderAttackerDropping(t, 65) }
  991. func TestBlockHeaderAttackerDropping66(t *testing.T) { testBlockHeaderAttackerDropping(t, 66) }
  992. func testBlockHeaderAttackerDropping(t *testing.T, protocol uint) {
  993. t.Parallel()
  994. // Define the disconnection requirement for individual hash fetch errors
  995. tests := []struct {
  996. result error
  997. drop bool
  998. }{
  999. {nil, false}, // Sync succeeded, all is well
  1000. {errBusy, false}, // Sync is already in progress, no problem
  1001. {errUnknownPeer, false}, // Peer is unknown, was already dropped, don't double drop
  1002. {errBadPeer, true}, // Peer was deemed bad for some reason, drop it
  1003. {errStallingPeer, true}, // Peer was detected to be stalling, drop it
  1004. {errUnsyncedPeer, true}, // Peer was detected to be unsynced, drop it
  1005. {errNoPeers, false}, // No peers to download from, soft race, no issue
  1006. {errTimeout, true}, // No hashes received in due time, drop the peer
  1007. {errEmptyHeaderSet, true}, // No headers were returned as a response, drop as it's a dead end
  1008. {errPeersUnavailable, true}, // Nobody had the advertised blocks, drop the advertiser
  1009. {errInvalidAncestor, true}, // Agreed upon ancestor is not acceptable, drop the chain rewriter
  1010. {errInvalidChain, true}, // Hash chain was detected as invalid, definitely drop
  1011. {errInvalidBody, false}, // A bad peer was detected, but not the sync origin
  1012. {errInvalidReceipt, false}, // A bad peer was detected, but not the sync origin
  1013. {errCancelContentProcessing, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  1014. }
  1015. // Run the tests and check disconnection status
  1016. tester := newTester()
  1017. defer tester.terminate()
  1018. chain := testChainBase.shorten(1)
  1019. for i, tt := range tests {
  1020. // Register a new peer and ensure its presence
  1021. id := fmt.Sprintf("test %d", i)
  1022. if err := tester.newPeer(id, protocol, chain); err != nil {
  1023. t.Fatalf("test %d: failed to register new peer: %v", i, err)
  1024. }
  1025. if _, ok := tester.peers[id]; !ok {
  1026. t.Fatalf("test %d: registered peer not found", i)
  1027. }
  1028. // Simulate a synchronisation and check the required result
  1029. tester.downloader.synchroniseMock = func(string, common.Hash) error { return tt.result }
  1030. tester.downloader.Synchronise(id, tester.genesis.Hash(), big.NewInt(1000), FullSync)
  1031. if _, ok := tester.peers[id]; !ok != tt.drop {
  1032. t.Errorf("test %d: peer drop mismatch for %v: have %v, want %v", i, tt.result, !ok, tt.drop)
  1033. }
  1034. }
  1035. }
  1036. // Tests that synchronisation progress (origin block number, current block number
  1037. // and highest block number) is tracked and updated correctly.
  1038. func TestSyncProgress64Full(t *testing.T) { testSyncProgress(t, 64, FullSync) }
  1039. func TestSyncProgress64Fast(t *testing.T) { testSyncProgress(t, 64, FastSync) }
  1040. func TestSyncProgress65Full(t *testing.T) { testSyncProgress(t, 65, FullSync) }
  1041. func TestSyncProgress65Fast(t *testing.T) { testSyncProgress(t, 65, FastSync) }
  1042. func TestSyncProgress65Light(t *testing.T) { testSyncProgress(t, 65, LightSync) }
  1043. func TestSyncProgress66Full(t *testing.T) { testSyncProgress(t, 66, FullSync) }
  1044. func TestSyncProgress66Fast(t *testing.T) { testSyncProgress(t, 66, FastSync) }
  1045. func TestSyncProgress66Light(t *testing.T) { testSyncProgress(t, 66, LightSync) }
  1046. func testSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
  1047. t.Parallel()
  1048. tester := newTester()
  1049. defer tester.terminate()
  1050. chain := testChainBase.shorten(blockCacheMaxItems - 15)
  1051. // Set a sync init hook to catch progress changes
  1052. starting := make(chan struct{})
  1053. progress := make(chan struct{})
  1054. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1055. starting <- struct{}{}
  1056. <-progress
  1057. }
  1058. checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1059. // Synchronise half the blocks and check initial progress
  1060. tester.newPeer("peer-half", protocol, chain.shorten(chain.len()/2))
  1061. pending := new(sync.WaitGroup)
  1062. pending.Add(1)
  1063. go func() {
  1064. defer pending.Done()
  1065. if err := tester.sync("peer-half", nil, mode); err != nil {
  1066. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1067. }
  1068. }()
  1069. <-starting
  1070. checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1071. HighestBlock: uint64(chain.len()/2 - 1),
  1072. })
  1073. progress <- struct{}{}
  1074. pending.Wait()
  1075. // Synchronise all the blocks and check continuation progress
  1076. tester.newPeer("peer-full", protocol, chain)
  1077. pending.Add(1)
  1078. go func() {
  1079. defer pending.Done()
  1080. if err := tester.sync("peer-full", nil, mode); err != nil {
  1081. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1082. }
  1083. }()
  1084. <-starting
  1085. checkProgress(t, tester.downloader, "completing", ethereum.SyncProgress{
  1086. StartingBlock: uint64(chain.len()/2 - 1),
  1087. CurrentBlock: uint64(chain.len()/2 - 1),
  1088. HighestBlock: uint64(chain.len() - 1),
  1089. })
  1090. // Check final progress after successful sync
  1091. progress <- struct{}{}
  1092. pending.Wait()
  1093. checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1094. StartingBlock: uint64(chain.len()/2 - 1),
  1095. CurrentBlock: uint64(chain.len() - 1),
  1096. HighestBlock: uint64(chain.len() - 1),
  1097. })
  1098. }
  1099. func checkProgress(t *testing.T, d *Downloader, stage string, want ethereum.SyncProgress) {
  1100. // Mark this method as a helper to report errors at callsite, not in here
  1101. t.Helper()
  1102. p := d.Progress()
  1103. p.KnownStates, p.PulledStates = 0, 0
  1104. want.KnownStates, want.PulledStates = 0, 0
  1105. if p != want {
  1106. t.Fatalf("%s progress mismatch:\nhave %+v\nwant %+v", stage, p, want)
  1107. }
  1108. }
  1109. // Tests that synchronisation progress (origin block number and highest block
  1110. // number) is tracked and updated correctly in case of a fork (or manual head
  1111. // revertal).
  1112. func TestForkedSyncProgress64Full(t *testing.T) { testForkedSyncProgress(t, 64, FullSync) }
  1113. func TestForkedSyncProgress64Fast(t *testing.T) { testForkedSyncProgress(t, 64, FastSync) }
  1114. func TestForkedSyncProgress65Full(t *testing.T) { testForkedSyncProgress(t, 65, FullSync) }
  1115. func TestForkedSyncProgress65Fast(t *testing.T) { testForkedSyncProgress(t, 65, FastSync) }
  1116. func TestForkedSyncProgress65Light(t *testing.T) { testForkedSyncProgress(t, 65, LightSync) }
  1117. func TestForkedSyncProgress66Full(t *testing.T) { testForkedSyncProgress(t, 66, FullSync) }
  1118. func TestForkedSyncProgress66Fast(t *testing.T) { testForkedSyncProgress(t, 66, FastSync) }
  1119. func TestForkedSyncProgress66Light(t *testing.T) { testForkedSyncProgress(t, 66, LightSync) }
  1120. func testForkedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
  1121. t.Parallel()
  1122. tester := newTester()
  1123. defer tester.terminate()
  1124. chainA := testChainForkLightA.shorten(testChainBase.len() + MaxHeaderFetch)
  1125. chainB := testChainForkLightB.shorten(testChainBase.len() + MaxHeaderFetch)
  1126. // Set a sync init hook to catch progress changes
  1127. starting := make(chan struct{})
  1128. progress := make(chan struct{})
  1129. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1130. starting <- struct{}{}
  1131. <-progress
  1132. }
  1133. checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1134. // Synchronise with one of the forks and check progress
  1135. tester.newPeer("fork A", protocol, chainA)
  1136. pending := new(sync.WaitGroup)
  1137. pending.Add(1)
  1138. go func() {
  1139. defer pending.Done()
  1140. if err := tester.sync("fork A", nil, mode); err != nil {
  1141. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1142. }
  1143. }()
  1144. <-starting
  1145. checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1146. HighestBlock: uint64(chainA.len() - 1),
  1147. })
  1148. progress <- struct{}{}
  1149. pending.Wait()
  1150. // Simulate a successful sync above the fork
  1151. tester.downloader.syncStatsChainOrigin = tester.downloader.syncStatsChainHeight
  1152. // Synchronise with the second fork and check progress resets
  1153. tester.newPeer("fork B", protocol, chainB)
  1154. pending.Add(1)
  1155. go func() {
  1156. defer pending.Done()
  1157. if err := tester.sync("fork B", nil, mode); err != nil {
  1158. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1159. }
  1160. }()
  1161. <-starting
  1162. checkProgress(t, tester.downloader, "forking", ethereum.SyncProgress{
  1163. StartingBlock: uint64(testChainBase.len()) - 1,
  1164. CurrentBlock: uint64(chainA.len() - 1),
  1165. HighestBlock: uint64(chainB.len() - 1),
  1166. })
  1167. // Check final progress after successful sync
  1168. progress <- struct{}{}
  1169. pending.Wait()
  1170. checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1171. StartingBlock: uint64(testChainBase.len()) - 1,
  1172. CurrentBlock: uint64(chainB.len() - 1),
  1173. HighestBlock: uint64(chainB.len() - 1),
  1174. })
  1175. }
  1176. // Tests that if synchronisation is aborted due to some failure, then the progress
  1177. // origin is not updated in the next sync cycle, as it should be considered the
  1178. // continuation of the previous sync and not a new instance.
  1179. func TestFailedSyncProgress64Full(t *testing.T) { testFailedSyncProgress(t, 64, FullSync) }
  1180. func TestFailedSyncProgress64Fast(t *testing.T) { testFailedSyncProgress(t, 64, FastSync) }
  1181. func TestFailedSyncProgress65Full(t *testing.T) { testFailedSyncProgress(t, 65, FullSync) }
  1182. func TestFailedSyncProgress65Fast(t *testing.T) { testFailedSyncProgress(t, 65, FastSync) }
  1183. func TestFailedSyncProgress65Light(t *testing.T) { testFailedSyncProgress(t, 65, LightSync) }
  1184. func TestFailedSyncProgress66Full(t *testing.T) { testFailedSyncProgress(t, 66, FullSync) }
  1185. func TestFailedSyncProgress66Fast(t *testing.T) { testFailedSyncProgress(t, 66, FastSync) }
  1186. func TestFailedSyncProgress66Light(t *testing.T) { testFailedSyncProgress(t, 66, LightSync) }
  1187. func testFailedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
  1188. t.Parallel()
  1189. tester := newTester()
  1190. defer tester.terminate()
  1191. chain := testChainBase.shorten(blockCacheMaxItems - 15)
  1192. // Set a sync init hook to catch progress changes
  1193. starting := make(chan struct{})
  1194. progress := make(chan struct{})
  1195. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1196. starting <- struct{}{}
  1197. <-progress
  1198. }
  1199. checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1200. // Attempt a full sync with a faulty peer
  1201. brokenChain := chain.shorten(chain.len())
  1202. missing := brokenChain.len() / 2
  1203. delete(brokenChain.headerm, brokenChain.chain[missing])
  1204. delete(brokenChain.blockm, brokenChain.chain[missing])
  1205. delete(brokenChain.receiptm, brokenChain.chain[missing])
  1206. tester.newPeer("faulty", protocol, brokenChain)
  1207. pending := new(sync.WaitGroup)
  1208. pending.Add(1)
  1209. go func() {
  1210. defer pending.Done()
  1211. if err := tester.sync("faulty", nil, mode); err == nil {
  1212. panic("succeeded faulty synchronisation")
  1213. }
  1214. }()
  1215. <-starting
  1216. checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1217. HighestBlock: uint64(brokenChain.len() - 1),
  1218. })
  1219. progress <- struct{}{}
  1220. pending.Wait()
  1221. afterFailedSync := tester.downloader.Progress()
  1222. // Synchronise with a good peer and check that the progress origin remind the same
  1223. // after a failure
  1224. tester.newPeer("valid", protocol, chain)
  1225. pending.Add(1)
  1226. go func() {
  1227. defer pending.Done()
  1228. if err := tester.sync("valid", nil, mode); err != nil {
  1229. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1230. }
  1231. }()
  1232. <-starting
  1233. checkProgress(t, tester.downloader, "completing", afterFailedSync)
  1234. // Check final progress after successful sync
  1235. progress <- struct{}{}
  1236. pending.Wait()
  1237. checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1238. CurrentBlock: uint64(chain.len() - 1),
  1239. HighestBlock: uint64(chain.len() - 1),
  1240. })
  1241. }
  1242. // Tests that if an attacker fakes a chain height, after the attack is detected,
  1243. // the progress height is successfully reduced at the next sync invocation.
  1244. func TestFakedSyncProgress64Full(t *testing.T) { testFakedSyncProgress(t, 64, FullSync) }
  1245. func TestFakedSyncProgress64Fast(t *testing.T) { testFakedSyncProgress(t, 64, FastSync) }
  1246. func TestFakedSyncProgress65Full(t *testing.T) { testFakedSyncProgress(t, 65, FullSync) }
  1247. func TestFakedSyncProgress65Fast(t *testing.T) { testFakedSyncProgress(t, 65, FastSync) }
  1248. func TestFakedSyncProgress65Light(t *testing.T) { testFakedSyncProgress(t, 65, LightSync) }
  1249. func TestFakedSyncProgress66Full(t *testing.T) { testFakedSyncProgress(t, 66, FullSync) }
  1250. func TestFakedSyncProgress66Fast(t *testing.T) { testFakedSyncProgress(t, 66, FastSync) }
  1251. func TestFakedSyncProgress66Light(t *testing.T) { testFakedSyncProgress(t, 66, LightSync) }
  1252. func testFakedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
  1253. t.Parallel()
  1254. tester := newTester()
  1255. defer tester.terminate()
  1256. chain := testChainBase.shorten(blockCacheMaxItems - 15)
  1257. // Set a sync init hook to catch progress changes
  1258. starting := make(chan struct{})
  1259. progress := make(chan struct{})
  1260. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1261. starting <- struct{}{}
  1262. <-progress
  1263. }
  1264. checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1265. // Create and sync with an attacker that promises a higher chain than available.
  1266. brokenChain := chain.shorten(chain.len())
  1267. numMissing := 5
  1268. for i := brokenChain.len() - 2; i > brokenChain.len()-numMissing; i-- {
  1269. delete(brokenChain.headerm, brokenChain.chain[i])
  1270. }
  1271. tester.newPeer("attack", protocol, brokenChain)
  1272. pending := new(sync.WaitGroup)
  1273. pending.Add(1)
  1274. go func() {
  1275. defer pending.Done()
  1276. if err := tester.sync("attack", nil, mode); err == nil {
  1277. panic("succeeded attacker synchronisation")
  1278. }
  1279. }()
  1280. <-starting
  1281. checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1282. HighestBlock: uint64(brokenChain.len() - 1),
  1283. })
  1284. progress <- struct{}{}
  1285. pending.Wait()
  1286. afterFailedSync := tester.downloader.Progress()
  1287. // Synchronise with a good peer and check that the progress height has been reduced to
  1288. // the true value.
  1289. validChain := chain.shorten(chain.len() - numMissing)
  1290. tester.newPeer("valid", protocol, validChain)
  1291. pending.Add(1)
  1292. go func() {
  1293. defer pending.Done()
  1294. if err := tester.sync("valid", nil, mode); err != nil {
  1295. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1296. }
  1297. }()
  1298. <-starting
  1299. checkProgress(t, tester.downloader, "completing", ethereum.SyncProgress{
  1300. CurrentBlock: afterFailedSync.CurrentBlock,
  1301. HighestBlock: uint64(validChain.len() - 1),
  1302. })
  1303. // Check final progress after successful sync.
  1304. progress <- struct{}{}
  1305. pending.Wait()
  1306. checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1307. CurrentBlock: uint64(validChain.len() - 1),
  1308. HighestBlock: uint64(validChain.len() - 1),
  1309. })
  1310. }
  1311. // This test reproduces an issue where unexpected deliveries would
  1312. // block indefinitely if they arrived at the right time.
  1313. func TestDeliverHeadersHang64Full(t *testing.T) { testDeliverHeadersHang(t, 64, FullSync) }
  1314. func TestDeliverHeadersHang64Fast(t *testing.T) { testDeliverHeadersHang(t, 64, FastSync) }
  1315. func TestDeliverHeadersHang65Full(t *testing.T) { testDeliverHeadersHang(t, 65, FullSync) }
  1316. func TestDeliverHeadersHang65Fast(t *testing.T) { testDeliverHeadersHang(t, 65, FastSync) }
  1317. func TestDeliverHeadersHang65Light(t *testing.T) { testDeliverHeadersHang(t, 65, LightSync) }
  1318. func TestDeliverHeadersHang66Full(t *testing.T) { testDeliverHeadersHang(t, 66, FullSync) }
  1319. func TestDeliverHeadersHang66Fast(t *testing.T) { testDeliverHeadersHang(t, 66, FastSync) }
  1320. func TestDeliverHeadersHang66Light(t *testing.T) { testDeliverHeadersHang(t, 66, LightSync) }
  1321. func testDeliverHeadersHang(t *testing.T, protocol uint, mode SyncMode) {
  1322. t.Parallel()
  1323. master := newTester()
  1324. defer master.terminate()
  1325. chain := testChainBase.shorten(15)
  1326. for i := 0; i < 200; i++ {
  1327. tester := newTester()
  1328. tester.peerDb = master.peerDb
  1329. tester.newPeer("peer", protocol, chain)
  1330. // Whenever the downloader requests headers, flood it with
  1331. // a lot of unrequested header deliveries.
  1332. tester.downloader.peers.peers["peer"].peer = &floodingTestPeer{
  1333. peer: tester.downloader.peers.peers["peer"].peer,
  1334. tester: tester,
  1335. }
  1336. if err := tester.sync("peer", nil, mode); err != nil {
  1337. t.Errorf("test %d: sync failed: %v", i, err)
  1338. }
  1339. tester.terminate()
  1340. }
  1341. }
  1342. type floodingTestPeer struct {
  1343. peer Peer
  1344. tester *downloadTester
  1345. }
  1346. func (ftp *floodingTestPeer) Head() (common.Hash, *big.Int) { return ftp.peer.Head() }
  1347. func (ftp *floodingTestPeer) RequestHeadersByHash(hash common.Hash, count int, skip int, reverse bool) error {
  1348. return ftp.peer.RequestHeadersByHash(hash, count, skip, reverse)
  1349. }
  1350. func (ftp *floodingTestPeer) RequestBodies(hashes []common.Hash) error {
  1351. return ftp.peer.RequestBodies(hashes)
  1352. }
  1353. func (ftp *floodingTestPeer) RequestReceipts(hashes []common.Hash) error {
  1354. return ftp.peer.RequestReceipts(hashes)
  1355. }
  1356. func (ftp *floodingTestPeer) RequestNodeData(hashes []common.Hash) error {
  1357. return ftp.peer.RequestNodeData(hashes)
  1358. }
  1359. func (ftp *floodingTestPeer) RequestHeadersByNumber(from uint64, count, skip int, reverse bool) error {
  1360. deliveriesDone := make(chan struct{}, 500)
  1361. for i := 0; i < cap(deliveriesDone)-1; i++ {
  1362. peer := fmt.Sprintf("fake-peer%d", i)
  1363. go func() {
  1364. ftp.tester.downloader.DeliverHeaders(peer, []*types.Header{{}, {}, {}, {}})
  1365. deliveriesDone <- struct{}{}
  1366. }()
  1367. }
  1368. // None of the extra deliveries should block.
  1369. timeout := time.After(60 * time.Second)
  1370. launched := false
  1371. for i := 0; i < cap(deliveriesDone); i++ {
  1372. select {
  1373. case <-deliveriesDone:
  1374. if !launched {
  1375. // Start delivering the requested headers
  1376. // after one of the flooding responses has arrived.
  1377. go func() {
  1378. ftp.peer.RequestHeadersByNumber(from, count, skip, reverse)
  1379. deliveriesDone <- struct{}{}
  1380. }()
  1381. launched = true
  1382. }
  1383. case <-timeout:
  1384. panic("blocked")
  1385. }
  1386. }
  1387. return nil
  1388. }
  1389. func TestRemoteHeaderRequestSpan(t *testing.T) {
  1390. testCases := []struct {
  1391. remoteHeight uint64
  1392. localHeight uint64
  1393. expected []int
  1394. }{
  1395. // Remote is way higher. We should ask for the remote head and go backwards
  1396. {1500, 1000,
  1397. []int{1323, 1339, 1355, 1371, 1387, 1403, 1419, 1435, 1451, 1467, 1483, 1499},
  1398. },
  1399. {15000, 13006,
  1400. []int{14823, 14839, 14855, 14871, 14887, 14903, 14919, 14935, 14951, 14967, 14983, 14999},
  1401. },
  1402. // Remote is pretty close to us. We don't have to fetch as many
  1403. {1200, 1150,
  1404. []int{1149, 1154, 1159, 1164, 1169, 1174, 1179, 1184, 1189, 1194, 1199},
  1405. },
  1406. // Remote is equal to us (so on a fork with higher td)
  1407. // We should get the closest couple of ancestors
  1408. {1500, 1500,
  1409. []int{1497, 1499},
  1410. },
  1411. // We're higher than the remote! Odd
  1412. {1000, 1500,
  1413. []int{997, 999},
  1414. },
  1415. // Check some weird edgecases that it behaves somewhat rationally
  1416. {0, 1500,
  1417. []int{0, 2},
  1418. },
  1419. {6000000, 0,
  1420. []int{5999823, 5999839, 5999855, 5999871, 5999887, 5999903, 5999919, 5999935, 5999951, 5999967, 5999983, 5999999},
  1421. },
  1422. {0, 0,
  1423. []int{0, 2},
  1424. },
  1425. }
  1426. reqs := func(from, count, span int) []int {
  1427. var r []int
  1428. num := from
  1429. for len(r) < count {
  1430. r = append(r, num)
  1431. num += span + 1
  1432. }
  1433. return r
  1434. }
  1435. for i, tt := range testCases {
  1436. from, count, span, max := calculateRequestSpan(tt.remoteHeight, tt.localHeight)
  1437. data := reqs(int(from), count, span)
  1438. if max != uint64(data[len(data)-1]) {
  1439. t.Errorf("test %d: wrong last value %d != %d", i, data[len(data)-1], max)
  1440. }
  1441. failed := false
  1442. if len(data) != len(tt.expected) {
  1443. failed = true
  1444. t.Errorf("test %d: length wrong, expected %d got %d", i, len(tt.expected), len(data))
  1445. } else {
  1446. for j, n := range data {
  1447. if n != tt.expected[j] {
  1448. failed = true
  1449. break
  1450. }
  1451. }
  1452. }
  1453. if failed {
  1454. res := strings.Replace(fmt.Sprint(data), " ", ",", -1)
  1455. exp := strings.Replace(fmt.Sprint(tt.expected), " ", ",", -1)
  1456. t.Logf("got: %v\n", res)
  1457. t.Logf("exp: %v\n", exp)
  1458. t.Errorf("test %d: wrong values", i)
  1459. }
  1460. }
  1461. }
  1462. // Tests that peers below a pre-configured checkpoint block are prevented from
  1463. // being fast-synced from, avoiding potential cheap eclipse attacks.
  1464. func TestCheckpointEnforcement64Full(t *testing.T) { testCheckpointEnforcement(t, 64, FullSync) }
  1465. func TestCheckpointEnforcement64Fast(t *testing.T) { testCheckpointEnforcement(t, 64, FastSync) }
  1466. func TestCheckpointEnforcement65Full(t *testing.T) { testCheckpointEnforcement(t, 65, FullSync) }
  1467. func TestCheckpointEnforcement65Fast(t *testing.T) { testCheckpointEnforcement(t, 65, FastSync) }
  1468. func TestCheckpointEnforcement65Light(t *testing.T) { testCheckpointEnforcement(t, 65, LightSync) }
  1469. func TestCheckpointEnforcement66Full(t *testing.T) { testCheckpointEnforcement(t, 66, FullSync) }
  1470. func TestCheckpointEnforcement66Fast(t *testing.T) { testCheckpointEnforcement(t, 66, FastSync) }
  1471. func TestCheckpointEnforcement66Light(t *testing.T) { testCheckpointEnforcement(t, 66, LightSync) }
  1472. func testCheckpointEnforcement(t *testing.T, protocol uint, mode SyncMode) {
  1473. t.Parallel()
  1474. // Create a new tester with a particular hard coded checkpoint block
  1475. tester := newTester()
  1476. defer tester.terminate()
  1477. tester.downloader.checkpoint = uint64(fsMinFullBlocks) + 256
  1478. chain := testChainBase.shorten(int(tester.downloader.checkpoint) - 1)
  1479. // Attempt to sync with the peer and validate the result
  1480. tester.newPeer("peer", protocol, chain)
  1481. var expect error
  1482. if mode == FastSync || mode == LightSync {
  1483. expect = errUnsyncedPeer
  1484. }
  1485. if err := tester.sync("peer", nil, mode); !errors.Is(err, expect) {
  1486. t.Fatalf("block sync error mismatch: have %v, want %v", err, expect)
  1487. }
  1488. if mode == FastSync || mode == LightSync {
  1489. assertOwnChain(t, tester, 1)
  1490. } else {
  1491. assertOwnChain(t, tester, chain.len())
  1492. }
  1493. }