downloader_test.go 64 KB

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