downloader_test.go 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646
  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. // Tests that simple synchronization against a canonical chain works correctly.
  458. // In this test common ancestor lookup should be short circuited and not require
  459. // binary searching.
  460. func TestCanonicalSynchronisation64Full(t *testing.T) { testCanonicalSynchronisation(t, 64, FullSync) }
  461. func TestCanonicalSynchronisation64Fast(t *testing.T) { testCanonicalSynchronisation(t, 64, FastSync) }
  462. func TestCanonicalSynchronisation65Full(t *testing.T) { testCanonicalSynchronisation(t, 65, FullSync) }
  463. func TestCanonicalSynchronisation65Fast(t *testing.T) { testCanonicalSynchronisation(t, 65, FastSync) }
  464. func TestCanonicalSynchronisation65Light(t *testing.T) {
  465. testCanonicalSynchronisation(t, 65, LightSync)
  466. }
  467. func testCanonicalSynchronisation(t *testing.T, protocol uint, mode SyncMode) {
  468. t.Parallel()
  469. tester := newTester()
  470. defer tester.terminate()
  471. // Create a small enough block chain to download
  472. chain := testChainBase.shorten(blockCacheMaxItems - 15)
  473. tester.newPeer("peer", protocol, chain)
  474. // Synchronise with the peer and make sure all relevant data was retrieved
  475. if err := tester.sync("peer", nil, mode); err != nil {
  476. t.Fatalf("failed to synchronise blocks: %v", err)
  477. }
  478. assertOwnChain(t, tester, chain.len())
  479. }
  480. // Tests that if a large batch of blocks are being downloaded, it is throttled
  481. // until the cached blocks are retrieved.
  482. func TestThrottling64Full(t *testing.T) { testThrottling(t, 64, FullSync) }
  483. func TestThrottling64Fast(t *testing.T) { testThrottling(t, 64, FastSync) }
  484. func TestThrottling65Full(t *testing.T) { testThrottling(t, 65, FullSync) }
  485. func TestThrottling65Fast(t *testing.T) { testThrottling(t, 65, 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. {
  518. tester.downloader.queue.resultCache.lock.Lock()
  519. cached = tester.downloader.queue.resultCache.countCompleted()
  520. tester.downloader.queue.resultCache.lock.Unlock()
  521. frozen = int(atomic.LoadUint32(&blocked))
  522. retrieved = len(tester.ownBlocks)
  523. }
  524. tester.lock.Unlock()
  525. if cached == blockCacheMaxItems ||
  526. cached == blockCacheMaxItems-reorgProtHeaderDelay ||
  527. retrieved+cached+frozen == targetBlocks+1 ||
  528. retrieved+cached+frozen == targetBlocks+1-reorgProtHeaderDelay {
  529. break
  530. }
  531. }
  532. // Make sure we filled up the cache, then exhaust it
  533. time.Sleep(25 * time.Millisecond) // give it a chance to screw up
  534. tester.lock.RLock()
  535. retrieved = len(tester.ownBlocks)
  536. tester.lock.RUnlock()
  537. if cached != blockCacheMaxItems && cached != blockCacheMaxItems-reorgProtHeaderDelay && retrieved+cached+frozen != targetBlocks+1 && retrieved+cached+frozen != targetBlocks+1-reorgProtHeaderDelay {
  538. t.Fatalf("block count mismatch: have %v, want %v (owned %v, blocked %v, target %v)", cached, blockCacheMaxItems, retrieved, frozen, targetBlocks+1)
  539. }
  540. // Permit the blocked blocks to import
  541. if atomic.LoadUint32(&blocked) > 0 {
  542. atomic.StoreUint32(&blocked, uint32(0))
  543. proceed <- struct{}{}
  544. }
  545. }
  546. // Check that we haven't pulled more blocks than available
  547. assertOwnChain(t, tester, targetBlocks+1)
  548. if err := <-errc; err != nil {
  549. t.Fatalf("block synchronization failed: %v", err)
  550. }
  551. tester.terminate()
  552. }
  553. // Tests that simple synchronization against a forked chain works correctly. In
  554. // this test common ancestor lookup should *not* be short circuited, and a full
  555. // binary search should be executed.
  556. func TestForkedSync64Full(t *testing.T) { testForkedSync(t, 64, FullSync) }
  557. func TestForkedSync64Fast(t *testing.T) { testForkedSync(t, 64, FastSync) }
  558. func TestForkedSync65Full(t *testing.T) { testForkedSync(t, 65, FullSync) }
  559. func TestForkedSync65Fast(t *testing.T) { testForkedSync(t, 65, FastSync) }
  560. func TestForkedSync65Light(t *testing.T) { testForkedSync(t, 65, LightSync) }
  561. func testForkedSync(t *testing.T, protocol uint, mode SyncMode) {
  562. t.Parallel()
  563. tester := newTester()
  564. defer tester.terminate()
  565. chainA := testChainForkLightA.shorten(testChainBase.len() + 80)
  566. chainB := testChainForkLightB.shorten(testChainBase.len() + 80)
  567. tester.newPeer("fork A", protocol, chainA)
  568. tester.newPeer("fork B", protocol, chainB)
  569. // Synchronise with the peer and make sure all blocks were retrieved
  570. if err := tester.sync("fork A", nil, mode); err != nil {
  571. t.Fatalf("failed to synchronise blocks: %v", err)
  572. }
  573. assertOwnChain(t, tester, chainA.len())
  574. // Synchronise with the second peer and make sure that fork is pulled too
  575. if err := tester.sync("fork B", nil, mode); err != nil {
  576. t.Fatalf("failed to synchronise blocks: %v", err)
  577. }
  578. assertOwnForkedChain(t, tester, testChainBase.len(), []int{chainA.len(), chainB.len()})
  579. }
  580. // Tests that synchronising against a much shorter but much heavyer fork works
  581. // corrently and is not dropped.
  582. func TestHeavyForkedSync64Full(t *testing.T) { testHeavyForkedSync(t, 64, FullSync) }
  583. func TestHeavyForkedSync64Fast(t *testing.T) { testHeavyForkedSync(t, 64, FastSync) }
  584. func TestHeavyForkedSync65Full(t *testing.T) { testHeavyForkedSync(t, 65, FullSync) }
  585. func TestHeavyForkedSync65Fast(t *testing.T) { testHeavyForkedSync(t, 65, FastSync) }
  586. func TestHeavyForkedSync65Light(t *testing.T) { testHeavyForkedSync(t, 65, LightSync) }
  587. func testHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) {
  588. t.Parallel()
  589. tester := newTester()
  590. defer tester.terminate()
  591. chainA := testChainForkLightA.shorten(testChainBase.len() + 80)
  592. chainB := testChainForkHeavy.shorten(testChainBase.len() + 80)
  593. tester.newPeer("light", protocol, chainA)
  594. tester.newPeer("heavy", protocol, chainB)
  595. // Synchronise with the peer and make sure all blocks were retrieved
  596. if err := tester.sync("light", nil, mode); err != nil {
  597. t.Fatalf("failed to synchronise blocks: %v", err)
  598. }
  599. assertOwnChain(t, tester, chainA.len())
  600. // Synchronise with the second peer and make sure that fork is pulled too
  601. if err := tester.sync("heavy", nil, mode); err != nil {
  602. t.Fatalf("failed to synchronise blocks: %v", err)
  603. }
  604. assertOwnForkedChain(t, tester, testChainBase.len(), []int{chainA.len(), chainB.len()})
  605. }
  606. // Tests that chain forks are contained within a certain interval of the current
  607. // chain head, ensuring that malicious peers cannot waste resources by feeding
  608. // long dead chains.
  609. func TestBoundedForkedSync64Full(t *testing.T) { testBoundedForkedSync(t, 64, FullSync) }
  610. func TestBoundedForkedSync64Fast(t *testing.T) { testBoundedForkedSync(t, 64, FastSync) }
  611. func TestBoundedForkedSync65Full(t *testing.T) { testBoundedForkedSync(t, 65, FullSync) }
  612. func TestBoundedForkedSync65Fast(t *testing.T) { testBoundedForkedSync(t, 65, FastSync) }
  613. func TestBoundedForkedSync65Light(t *testing.T) { testBoundedForkedSync(t, 65, LightSync) }
  614. func testBoundedForkedSync(t *testing.T, protocol uint, mode SyncMode) {
  615. t.Parallel()
  616. tester := newTester()
  617. defer tester.terminate()
  618. chainA := testChainForkLightA
  619. chainB := testChainForkLightB
  620. tester.newPeer("original", protocol, chainA)
  621. tester.newPeer("rewriter", protocol, chainB)
  622. // Synchronise with the peer and make sure all blocks were retrieved
  623. if err := tester.sync("original", nil, mode); err != nil {
  624. t.Fatalf("failed to synchronise blocks: %v", err)
  625. }
  626. assertOwnChain(t, tester, chainA.len())
  627. // Synchronise with the second peer and ensure that the fork is rejected to being too old
  628. if err := tester.sync("rewriter", nil, mode); err != errInvalidAncestor {
  629. t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor)
  630. }
  631. }
  632. // Tests that chain forks are contained within a certain interval of the current
  633. // chain head for short but heavy forks too. These are a bit special because they
  634. // take different ancestor lookup paths.
  635. func TestBoundedHeavyForkedSync64Full(t *testing.T) { testBoundedHeavyForkedSync(t, 64, FullSync) }
  636. func TestBoundedHeavyForkedSync64Fast(t *testing.T) { testBoundedHeavyForkedSync(t, 64, FastSync) }
  637. func TestBoundedHeavyForkedSync65Full(t *testing.T) { testBoundedHeavyForkedSync(t, 65, FullSync) }
  638. func TestBoundedHeavyForkedSync65Fast(t *testing.T) { testBoundedHeavyForkedSync(t, 65, FastSync) }
  639. func TestBoundedHeavyForkedSync65Light(t *testing.T) { testBoundedHeavyForkedSync(t, 65, LightSync) }
  640. func testBoundedHeavyForkedSync(t *testing.T, protocol uint, mode SyncMode) {
  641. t.Parallel()
  642. tester := newTester()
  643. // Create a long enough forked chain
  644. chainA := testChainForkLightA
  645. chainB := testChainForkHeavy
  646. tester.newPeer("original", protocol, chainA)
  647. // Synchronise with the peer and make sure all blocks were retrieved
  648. if err := tester.sync("original", nil, mode); err != nil {
  649. t.Fatalf("failed to synchronise blocks: %v", err)
  650. }
  651. assertOwnChain(t, tester, chainA.len())
  652. tester.newPeer("heavy-rewriter", protocol, chainB)
  653. // Synchronise with the second peer and ensure that the fork is rejected to being too old
  654. if err := tester.sync("heavy-rewriter", nil, mode); err != errInvalidAncestor {
  655. t.Fatalf("sync failure mismatch: have %v, want %v", err, errInvalidAncestor)
  656. }
  657. tester.terminate()
  658. }
  659. // Tests that an inactive downloader will not accept incoming block headers,
  660. // bodies and receipts.
  661. func TestInactiveDownloader63(t *testing.T) {
  662. t.Parallel()
  663. tester := newTester()
  664. defer tester.terminate()
  665. // Check that neither block headers nor bodies are accepted
  666. if err := tester.downloader.DeliverHeaders("bad peer", []*types.Header{}); err != errNoSyncActive {
  667. t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
  668. }
  669. if err := tester.downloader.DeliverBodies("bad peer", [][]*types.Transaction{}, [][]*types.Header{}); err != errNoSyncActive {
  670. t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
  671. }
  672. if err := tester.downloader.DeliverReceipts("bad peer", [][]*types.Receipt{}); err != errNoSyncActive {
  673. t.Errorf("error mismatch: have %v, want %v", err, errNoSyncActive)
  674. }
  675. }
  676. // Tests that a canceled download wipes all previously accumulated state.
  677. func TestCancel64Full(t *testing.T) { testCancel(t, 64, FullSync) }
  678. func TestCancel64Fast(t *testing.T) { testCancel(t, 64, FastSync) }
  679. func TestCancel65Full(t *testing.T) { testCancel(t, 65, FullSync) }
  680. func TestCancel65Fast(t *testing.T) { testCancel(t, 65, FastSync) }
  681. func TestCancel65Light(t *testing.T) { testCancel(t, 65, LightSync) }
  682. func testCancel(t *testing.T, protocol uint, mode SyncMode) {
  683. t.Parallel()
  684. tester := newTester()
  685. defer tester.terminate()
  686. chain := testChainBase.shorten(MaxHeaderFetch)
  687. tester.newPeer("peer", protocol, chain)
  688. // Make sure canceling works with a pristine downloader
  689. tester.downloader.Cancel()
  690. if !tester.downloader.queue.Idle() {
  691. t.Errorf("download queue not idle")
  692. }
  693. // Synchronise with the peer, but cancel afterwards
  694. if err := tester.sync("peer", nil, mode); err != nil {
  695. t.Fatalf("failed to synchronise blocks: %v", err)
  696. }
  697. tester.downloader.Cancel()
  698. if !tester.downloader.queue.Idle() {
  699. t.Errorf("download queue not idle")
  700. }
  701. }
  702. // Tests that synchronisation from multiple peers works as intended (multi thread sanity test).
  703. func TestMultiSynchronisation64Full(t *testing.T) { testMultiSynchronisation(t, 64, FullSync) }
  704. func TestMultiSynchronisation64Fast(t *testing.T) { testMultiSynchronisation(t, 64, FastSync) }
  705. func TestMultiSynchronisation65Full(t *testing.T) { testMultiSynchronisation(t, 65, FullSync) }
  706. func TestMultiSynchronisation65Fast(t *testing.T) { testMultiSynchronisation(t, 65, FastSync) }
  707. func TestMultiSynchronisation65Light(t *testing.T) { testMultiSynchronisation(t, 65, LightSync) }
  708. func testMultiSynchronisation(t *testing.T, protocol uint, mode SyncMode) {
  709. t.Parallel()
  710. tester := newTester()
  711. defer tester.terminate()
  712. // Create various peers with various parts of the chain
  713. targetPeers := 8
  714. chain := testChainBase.shorten(targetPeers * 100)
  715. for i := 0; i < targetPeers; i++ {
  716. id := fmt.Sprintf("peer #%d", i)
  717. tester.newPeer(id, protocol, chain.shorten(chain.len()/(i+1)))
  718. }
  719. if err := tester.sync("peer #0", nil, mode); err != nil {
  720. t.Fatalf("failed to synchronise blocks: %v", err)
  721. }
  722. assertOwnChain(t, tester, chain.len())
  723. }
  724. // Tests that synchronisations behave well in multi-version protocol environments
  725. // and not wreak havoc on other nodes in the network.
  726. func TestMultiProtoSynchronisation64Full(t *testing.T) { testMultiProtoSync(t, 64, FullSync) }
  727. func TestMultiProtoSynchronisation64Fast(t *testing.T) { testMultiProtoSync(t, 64, FastSync) }
  728. func TestMultiProtoSynchronisation65Full(t *testing.T) { testMultiProtoSync(t, 65, FullSync) }
  729. func TestMultiProtoSynchronisation65Fast(t *testing.T) { testMultiProtoSync(t, 65, FastSync) }
  730. func TestMultiProtoSynchronisation65Light(t *testing.T) { testMultiProtoSync(t, 65, LightSync) }
  731. func testMultiProtoSync(t *testing.T, protocol uint, mode SyncMode) {
  732. t.Parallel()
  733. tester := newTester()
  734. defer tester.terminate()
  735. // Create a small enough block chain to download
  736. chain := testChainBase.shorten(blockCacheMaxItems - 15)
  737. // Create peers of every type
  738. tester.newPeer("peer 63", 63, chain)
  739. tester.newPeer("peer 64", 64, chain)
  740. tester.newPeer("peer 65", 65, chain)
  741. // Synchronise with the requested peer and make sure all blocks were retrieved
  742. if err := tester.sync(fmt.Sprintf("peer %d", protocol), nil, mode); err != nil {
  743. t.Fatalf("failed to synchronise blocks: %v", err)
  744. }
  745. assertOwnChain(t, tester, chain.len())
  746. // Check that no peers have been dropped off
  747. for _, version := range []int{63, 64, 65} {
  748. peer := fmt.Sprintf("peer %d", version)
  749. if _, ok := tester.peers[peer]; !ok {
  750. t.Errorf("%s dropped", peer)
  751. }
  752. }
  753. }
  754. // Tests that if a block is empty (e.g. header only), no body request should be
  755. // made, and instead the header should be assembled into a whole block in itself.
  756. func TestEmptyShortCircuit64Full(t *testing.T) { testEmptyShortCircuit(t, 64, FullSync) }
  757. func TestEmptyShortCircuit64Fast(t *testing.T) { testEmptyShortCircuit(t, 64, FastSync) }
  758. func TestEmptyShortCircuit65Full(t *testing.T) { testEmptyShortCircuit(t, 65, FullSync) }
  759. func TestEmptyShortCircuit65Fast(t *testing.T) { testEmptyShortCircuit(t, 65, FastSync) }
  760. func TestEmptyShortCircuit65Light(t *testing.T) { testEmptyShortCircuit(t, 65, LightSync) }
  761. func testEmptyShortCircuit(t *testing.T, protocol uint, mode SyncMode) {
  762. t.Parallel()
  763. tester := newTester()
  764. defer tester.terminate()
  765. // Create a block chain to download
  766. chain := testChainBase
  767. tester.newPeer("peer", protocol, chain)
  768. // Instrument the downloader to signal body requests
  769. bodiesHave, receiptsHave := int32(0), int32(0)
  770. tester.downloader.bodyFetchHook = func(headers []*types.Header) {
  771. atomic.AddInt32(&bodiesHave, int32(len(headers)))
  772. }
  773. tester.downloader.receiptFetchHook = func(headers []*types.Header) {
  774. atomic.AddInt32(&receiptsHave, int32(len(headers)))
  775. }
  776. // Synchronise with the peer and make sure all blocks were retrieved
  777. if err := tester.sync("peer", nil, mode); err != nil {
  778. t.Fatalf("failed to synchronise blocks: %v", err)
  779. }
  780. assertOwnChain(t, tester, chain.len())
  781. // Validate the number of block bodies that should have been requested
  782. bodiesNeeded, receiptsNeeded := 0, 0
  783. for _, block := range chain.blockm {
  784. if mode != LightSync && block != tester.genesis && (len(block.Transactions()) > 0 || len(block.Uncles()) > 0) {
  785. bodiesNeeded++
  786. }
  787. }
  788. for _, receipt := range chain.receiptm {
  789. if mode == FastSync && len(receipt) > 0 {
  790. receiptsNeeded++
  791. }
  792. }
  793. if int(bodiesHave) != bodiesNeeded {
  794. t.Errorf("body retrieval count mismatch: have %v, want %v", bodiesHave, bodiesNeeded)
  795. }
  796. if int(receiptsHave) != receiptsNeeded {
  797. t.Errorf("receipt retrieval count mismatch: have %v, want %v", receiptsHave, receiptsNeeded)
  798. }
  799. }
  800. // Tests that headers are enqueued continuously, preventing malicious nodes from
  801. // stalling the downloader by feeding gapped header chains.
  802. func TestMissingHeaderAttack64Full(t *testing.T) { testMissingHeaderAttack(t, 64, FullSync) }
  803. func TestMissingHeaderAttack64Fast(t *testing.T) { testMissingHeaderAttack(t, 64, FastSync) }
  804. func TestMissingHeaderAttack65Full(t *testing.T) { testMissingHeaderAttack(t, 65, FullSync) }
  805. func TestMissingHeaderAttack65Fast(t *testing.T) { testMissingHeaderAttack(t, 65, FastSync) }
  806. func TestMissingHeaderAttack65Light(t *testing.T) { testMissingHeaderAttack(t, 65, LightSync) }
  807. func testMissingHeaderAttack(t *testing.T, protocol uint, mode SyncMode) {
  808. t.Parallel()
  809. tester := newTester()
  810. defer tester.terminate()
  811. chain := testChainBase.shorten(blockCacheMaxItems - 15)
  812. brokenChain := chain.shorten(chain.len())
  813. delete(brokenChain.headerm, brokenChain.chain[brokenChain.len()/2])
  814. tester.newPeer("attack", protocol, brokenChain)
  815. if err := tester.sync("attack", nil, mode); err == nil {
  816. t.Fatalf("succeeded attacker synchronisation")
  817. }
  818. // Synchronise with the valid peer and make sure sync succeeds
  819. tester.newPeer("valid", protocol, chain)
  820. if err := tester.sync("valid", nil, mode); err != nil {
  821. t.Fatalf("failed to synchronise blocks: %v", err)
  822. }
  823. assertOwnChain(t, tester, chain.len())
  824. }
  825. // Tests that if requested headers are shifted (i.e. first is missing), the queue
  826. // detects the invalid numbering.
  827. func TestShiftedHeaderAttack64Full(t *testing.T) { testShiftedHeaderAttack(t, 64, FullSync) }
  828. func TestShiftedHeaderAttack64Fast(t *testing.T) { testShiftedHeaderAttack(t, 64, FastSync) }
  829. func TestShiftedHeaderAttack65Full(t *testing.T) { testShiftedHeaderAttack(t, 65, FullSync) }
  830. func TestShiftedHeaderAttack65Fast(t *testing.T) { testShiftedHeaderAttack(t, 65, FastSync) }
  831. func TestShiftedHeaderAttack65Light(t *testing.T) { testShiftedHeaderAttack(t, 65, LightSync) }
  832. func testShiftedHeaderAttack(t *testing.T, protocol uint, mode SyncMode) {
  833. t.Parallel()
  834. tester := newTester()
  835. defer tester.terminate()
  836. chain := testChainBase.shorten(blockCacheMaxItems - 15)
  837. // Attempt a full sync with an attacker feeding shifted headers
  838. brokenChain := chain.shorten(chain.len())
  839. delete(brokenChain.headerm, brokenChain.chain[1])
  840. delete(brokenChain.blockm, brokenChain.chain[1])
  841. delete(brokenChain.receiptm, brokenChain.chain[1])
  842. tester.newPeer("attack", protocol, brokenChain)
  843. if err := tester.sync("attack", nil, mode); err == nil {
  844. t.Fatalf("succeeded attacker synchronisation")
  845. }
  846. // Synchronise with the valid peer and make sure sync succeeds
  847. tester.newPeer("valid", protocol, chain)
  848. if err := tester.sync("valid", nil, mode); err != nil {
  849. t.Fatalf("failed to synchronise blocks: %v", err)
  850. }
  851. assertOwnChain(t, tester, chain.len())
  852. }
  853. // Tests that upon detecting an invalid header, the recent ones are rolled back
  854. // for various failure scenarios. Afterwards a full sync is attempted to make
  855. // sure no state was corrupted.
  856. func TestInvalidHeaderRollback64Fast(t *testing.T) { testInvalidHeaderRollback(t, 64, FastSync) }
  857. func TestInvalidHeaderRollback65Fast(t *testing.T) { testInvalidHeaderRollback(t, 65, FastSync) }
  858. func testInvalidHeaderRollback(t *testing.T, protocol uint, mode SyncMode) {
  859. t.Parallel()
  860. tester := newTester()
  861. // Create a small enough block chain to download
  862. targetBlocks := 3*fsHeaderSafetyNet + 256 + fsMinFullBlocks
  863. chain := testChainBase.shorten(targetBlocks)
  864. // Attempt to sync with an attacker that feeds junk during the fast sync phase.
  865. // This should result in the last fsHeaderSafetyNet headers being rolled back.
  866. missing := fsHeaderSafetyNet + MaxHeaderFetch + 1
  867. fastAttackChain := chain.shorten(chain.len())
  868. delete(fastAttackChain.headerm, fastAttackChain.chain[missing])
  869. tester.newPeer("fast-attack", protocol, fastAttackChain)
  870. if err := tester.sync("fast-attack", nil, mode); err == nil {
  871. t.Fatalf("succeeded fast attacker synchronisation")
  872. }
  873. if head := tester.CurrentHeader().Number.Int64(); int(head) > MaxHeaderFetch {
  874. t.Errorf("rollback head mismatch: have %v, want at most %v", head, MaxHeaderFetch)
  875. }
  876. // Attempt to sync with an attacker that feeds junk during the block import phase.
  877. // This should result in both the last fsHeaderSafetyNet number of headers being
  878. // rolled back, and also the pivot point being reverted to a non-block status.
  879. missing = 3*fsHeaderSafetyNet + MaxHeaderFetch + 1
  880. blockAttackChain := chain.shorten(chain.len())
  881. delete(fastAttackChain.headerm, fastAttackChain.chain[missing]) // Make sure the fast-attacker doesn't fill in
  882. delete(blockAttackChain.headerm, blockAttackChain.chain[missing])
  883. tester.newPeer("block-attack", protocol, blockAttackChain)
  884. if err := tester.sync("block-attack", nil, mode); err == nil {
  885. t.Fatalf("succeeded block attacker synchronisation")
  886. }
  887. if head := tester.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
  888. t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
  889. }
  890. if mode == FastSync {
  891. if head := tester.CurrentBlock().NumberU64(); head != 0 {
  892. t.Errorf("fast sync pivot block #%d not rolled back", head)
  893. }
  894. }
  895. // Attempt to sync with an attacker that withholds promised blocks after the
  896. // fast sync pivot point. This could be a trial to leave the node with a bad
  897. // but already imported pivot block.
  898. withholdAttackChain := chain.shorten(chain.len())
  899. tester.newPeer("withhold-attack", protocol, withholdAttackChain)
  900. tester.downloader.syncInitHook = func(uint64, uint64) {
  901. for i := missing; i < withholdAttackChain.len(); i++ {
  902. delete(withholdAttackChain.headerm, withholdAttackChain.chain[i])
  903. }
  904. tester.downloader.syncInitHook = nil
  905. }
  906. if err := tester.sync("withhold-attack", nil, mode); err == nil {
  907. t.Fatalf("succeeded withholding attacker synchronisation")
  908. }
  909. if head := tester.CurrentHeader().Number.Int64(); int(head) > 2*fsHeaderSafetyNet+MaxHeaderFetch {
  910. t.Errorf("rollback head mismatch: have %v, want at most %v", head, 2*fsHeaderSafetyNet+MaxHeaderFetch)
  911. }
  912. if mode == FastSync {
  913. if head := tester.CurrentBlock().NumberU64(); head != 0 {
  914. t.Errorf("fast sync pivot block #%d not rolled back", head)
  915. }
  916. }
  917. // synchronise with the valid peer and make sure sync succeeds. Since the last rollback
  918. // should also disable fast syncing for this process, verify that we did a fresh full
  919. // sync. Note, we can't assert anything about the receipts since we won't purge the
  920. // database of them, hence we can't use assertOwnChain.
  921. tester.newPeer("valid", protocol, chain)
  922. if err := tester.sync("valid", nil, mode); err != nil {
  923. t.Fatalf("failed to synchronise blocks: %v", err)
  924. }
  925. if hs := len(tester.ownHeaders); hs != chain.len() {
  926. t.Fatalf("synchronised headers mismatch: have %v, want %v", hs, chain.len())
  927. }
  928. if mode != LightSync {
  929. if bs := len(tester.ownBlocks); bs != chain.len() {
  930. t.Fatalf("synchronised blocks mismatch: have %v, want %v", bs, chain.len())
  931. }
  932. }
  933. tester.terminate()
  934. }
  935. // Tests that a peer advertising a high TD doesn't get to stall the downloader
  936. // afterwards by not sending any useful hashes.
  937. func TestHighTDStarvationAttack64Full(t *testing.T) { testHighTDStarvationAttack(t, 64, FullSync) }
  938. func TestHighTDStarvationAttack64Fast(t *testing.T) { testHighTDStarvationAttack(t, 64, FastSync) }
  939. func TestHighTDStarvationAttack65Full(t *testing.T) { testHighTDStarvationAttack(t, 65, FullSync) }
  940. func TestHighTDStarvationAttack65Fast(t *testing.T) { testHighTDStarvationAttack(t, 65, FastSync) }
  941. func TestHighTDStarvationAttack65Light(t *testing.T) { testHighTDStarvationAttack(t, 65, LightSync) }
  942. func testHighTDStarvationAttack(t *testing.T, protocol uint, mode SyncMode) {
  943. t.Parallel()
  944. tester := newTester()
  945. chain := testChainBase.shorten(1)
  946. tester.newPeer("attack", protocol, chain)
  947. if err := tester.sync("attack", big.NewInt(1000000), mode); err != errStallingPeer {
  948. t.Fatalf("synchronisation error mismatch: have %v, want %v", err, errStallingPeer)
  949. }
  950. tester.terminate()
  951. }
  952. // Tests that misbehaving peers are disconnected, whilst behaving ones are not.
  953. func TestBlockHeaderAttackerDropping64(t *testing.T) { testBlockHeaderAttackerDropping(t, 64) }
  954. func TestBlockHeaderAttackerDropping65(t *testing.T) { testBlockHeaderAttackerDropping(t, 65) }
  955. func testBlockHeaderAttackerDropping(t *testing.T, protocol uint) {
  956. t.Parallel()
  957. // Define the disconnection requirement for individual hash fetch errors
  958. tests := []struct {
  959. result error
  960. drop bool
  961. }{
  962. {nil, false}, // Sync succeeded, all is well
  963. {errBusy, false}, // Sync is already in progress, no problem
  964. {errUnknownPeer, false}, // Peer is unknown, was already dropped, don't double drop
  965. {errBadPeer, true}, // Peer was deemed bad for some reason, drop it
  966. {errStallingPeer, true}, // Peer was detected to be stalling, drop it
  967. {errUnsyncedPeer, true}, // Peer was detected to be unsynced, drop it
  968. {errNoPeers, false}, // No peers to download from, soft race, no issue
  969. {errTimeout, true}, // No hashes received in due time, drop the peer
  970. {errEmptyHeaderSet, true}, // No headers were returned as a response, drop as it's a dead end
  971. {errPeersUnavailable, true}, // Nobody had the advertised blocks, drop the advertiser
  972. {errInvalidAncestor, true}, // Agreed upon ancestor is not acceptable, drop the chain rewriter
  973. {errInvalidChain, true}, // Hash chain was detected as invalid, definitely drop
  974. {errInvalidBody, false}, // A bad peer was detected, but not the sync origin
  975. {errInvalidReceipt, false}, // A bad peer was detected, but not the sync origin
  976. {errCancelContentProcessing, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  977. }
  978. // Run the tests and check disconnection status
  979. tester := newTester()
  980. defer tester.terminate()
  981. chain := testChainBase.shorten(1)
  982. for i, tt := range tests {
  983. // Register a new peer and ensure its presence
  984. id := fmt.Sprintf("test %d", i)
  985. if err := tester.newPeer(id, protocol, chain); err != nil {
  986. t.Fatalf("test %d: failed to register new peer: %v", i, err)
  987. }
  988. if _, ok := tester.peers[id]; !ok {
  989. t.Fatalf("test %d: registered peer not found", i)
  990. }
  991. // Simulate a synchronisation and check the required result
  992. tester.downloader.synchroniseMock = func(string, common.Hash) error { return tt.result }
  993. tester.downloader.Synchronise(id, tester.genesis.Hash(), big.NewInt(1000), FullSync)
  994. if _, ok := tester.peers[id]; !ok != tt.drop {
  995. t.Errorf("test %d: peer drop mismatch for %v: have %v, want %v", i, tt.result, !ok, tt.drop)
  996. }
  997. }
  998. }
  999. // Tests that synchronisation progress (origin block number, current block number
  1000. // and highest block number) is tracked and updated correctly.
  1001. func TestSyncProgress64Full(t *testing.T) { testSyncProgress(t, 64, FullSync) }
  1002. func TestSyncProgress64Fast(t *testing.T) { testSyncProgress(t, 64, FastSync) }
  1003. func TestSyncProgress65Full(t *testing.T) { testSyncProgress(t, 65, FullSync) }
  1004. func TestSyncProgress65Fast(t *testing.T) { testSyncProgress(t, 65, FastSync) }
  1005. func TestSyncProgress65Light(t *testing.T) { testSyncProgress(t, 65, LightSync) }
  1006. func testSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
  1007. t.Parallel()
  1008. tester := newTester()
  1009. defer tester.terminate()
  1010. chain := testChainBase.shorten(blockCacheMaxItems - 15)
  1011. // Set a sync init hook to catch progress changes
  1012. starting := make(chan struct{})
  1013. progress := make(chan struct{})
  1014. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1015. starting <- struct{}{}
  1016. <-progress
  1017. }
  1018. checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1019. // Synchronise half the blocks and check initial progress
  1020. tester.newPeer("peer-half", protocol, chain.shorten(chain.len()/2))
  1021. pending := new(sync.WaitGroup)
  1022. pending.Add(1)
  1023. go func() {
  1024. defer pending.Done()
  1025. if err := tester.sync("peer-half", nil, mode); err != nil {
  1026. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1027. }
  1028. }()
  1029. <-starting
  1030. checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1031. HighestBlock: uint64(chain.len()/2 - 1),
  1032. })
  1033. progress <- struct{}{}
  1034. pending.Wait()
  1035. // Synchronise all the blocks and check continuation progress
  1036. tester.newPeer("peer-full", protocol, chain)
  1037. pending.Add(1)
  1038. go func() {
  1039. defer pending.Done()
  1040. if err := tester.sync("peer-full", nil, mode); err != nil {
  1041. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1042. }
  1043. }()
  1044. <-starting
  1045. checkProgress(t, tester.downloader, "completing", ethereum.SyncProgress{
  1046. StartingBlock: uint64(chain.len()/2 - 1),
  1047. CurrentBlock: uint64(chain.len()/2 - 1),
  1048. HighestBlock: uint64(chain.len() - 1),
  1049. })
  1050. // Check final progress after successful sync
  1051. progress <- struct{}{}
  1052. pending.Wait()
  1053. checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1054. StartingBlock: uint64(chain.len()/2 - 1),
  1055. CurrentBlock: uint64(chain.len() - 1),
  1056. HighestBlock: uint64(chain.len() - 1),
  1057. })
  1058. }
  1059. func checkProgress(t *testing.T, d *Downloader, stage string, want ethereum.SyncProgress) {
  1060. // Mark this method as a helper to report errors at callsite, not in here
  1061. t.Helper()
  1062. p := d.Progress()
  1063. p.KnownStates, p.PulledStates = 0, 0
  1064. want.KnownStates, want.PulledStates = 0, 0
  1065. if p != want {
  1066. t.Fatalf("%s progress mismatch:\nhave %+v\nwant %+v", stage, p, want)
  1067. }
  1068. }
  1069. // Tests that synchronisation progress (origin block number and highest block
  1070. // number) is tracked and updated correctly in case of a fork (or manual head
  1071. // revertal).
  1072. func TestForkedSyncProgress64Full(t *testing.T) { testForkedSyncProgress(t, 64, FullSync) }
  1073. func TestForkedSyncProgress64Fast(t *testing.T) { testForkedSyncProgress(t, 64, FastSync) }
  1074. func TestForkedSyncProgress65Full(t *testing.T) { testForkedSyncProgress(t, 65, FullSync) }
  1075. func TestForkedSyncProgress65Fast(t *testing.T) { testForkedSyncProgress(t, 65, FastSync) }
  1076. func TestForkedSyncProgress65Light(t *testing.T) { testForkedSyncProgress(t, 65, LightSync) }
  1077. func testForkedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
  1078. t.Parallel()
  1079. tester := newTester()
  1080. defer tester.terminate()
  1081. chainA := testChainForkLightA.shorten(testChainBase.len() + MaxHeaderFetch)
  1082. chainB := testChainForkLightB.shorten(testChainBase.len() + MaxHeaderFetch)
  1083. // Set a sync init hook to catch progress changes
  1084. starting := make(chan struct{})
  1085. progress := make(chan struct{})
  1086. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1087. starting <- struct{}{}
  1088. <-progress
  1089. }
  1090. checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1091. // Synchronise with one of the forks and check progress
  1092. tester.newPeer("fork A", protocol, chainA)
  1093. pending := new(sync.WaitGroup)
  1094. pending.Add(1)
  1095. go func() {
  1096. defer pending.Done()
  1097. if err := tester.sync("fork A", nil, mode); err != nil {
  1098. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1099. }
  1100. }()
  1101. <-starting
  1102. checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1103. HighestBlock: uint64(chainA.len() - 1),
  1104. })
  1105. progress <- struct{}{}
  1106. pending.Wait()
  1107. // Simulate a successful sync above the fork
  1108. tester.downloader.syncStatsChainOrigin = tester.downloader.syncStatsChainHeight
  1109. // Synchronise with the second fork and check progress resets
  1110. tester.newPeer("fork B", protocol, chainB)
  1111. pending.Add(1)
  1112. go func() {
  1113. defer pending.Done()
  1114. if err := tester.sync("fork B", nil, mode); err != nil {
  1115. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1116. }
  1117. }()
  1118. <-starting
  1119. checkProgress(t, tester.downloader, "forking", ethereum.SyncProgress{
  1120. StartingBlock: uint64(testChainBase.len()) - 1,
  1121. CurrentBlock: uint64(chainA.len() - 1),
  1122. HighestBlock: uint64(chainB.len() - 1),
  1123. })
  1124. // Check final progress after successful sync
  1125. progress <- struct{}{}
  1126. pending.Wait()
  1127. checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1128. StartingBlock: uint64(testChainBase.len()) - 1,
  1129. CurrentBlock: uint64(chainB.len() - 1),
  1130. HighestBlock: uint64(chainB.len() - 1),
  1131. })
  1132. }
  1133. // Tests that if synchronisation is aborted due to some failure, then the progress
  1134. // origin is not updated in the next sync cycle, as it should be considered the
  1135. // continuation of the previous sync and not a new instance.
  1136. func TestFailedSyncProgress64Full(t *testing.T) { testFailedSyncProgress(t, 64, FullSync) }
  1137. func TestFailedSyncProgress64Fast(t *testing.T) { testFailedSyncProgress(t, 64, FastSync) }
  1138. func TestFailedSyncProgress65Full(t *testing.T) { testFailedSyncProgress(t, 65, FullSync) }
  1139. func TestFailedSyncProgress65Fast(t *testing.T) { testFailedSyncProgress(t, 65, FastSync) }
  1140. func TestFailedSyncProgress65Light(t *testing.T) { testFailedSyncProgress(t, 65, LightSync) }
  1141. func testFailedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
  1142. t.Parallel()
  1143. tester := newTester()
  1144. defer tester.terminate()
  1145. chain := testChainBase.shorten(blockCacheMaxItems - 15)
  1146. // Set a sync init hook to catch progress changes
  1147. starting := make(chan struct{})
  1148. progress := make(chan struct{})
  1149. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1150. starting <- struct{}{}
  1151. <-progress
  1152. }
  1153. checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1154. // Attempt a full sync with a faulty peer
  1155. brokenChain := chain.shorten(chain.len())
  1156. missing := brokenChain.len() / 2
  1157. delete(brokenChain.headerm, brokenChain.chain[missing])
  1158. delete(brokenChain.blockm, brokenChain.chain[missing])
  1159. delete(brokenChain.receiptm, brokenChain.chain[missing])
  1160. tester.newPeer("faulty", protocol, brokenChain)
  1161. pending := new(sync.WaitGroup)
  1162. pending.Add(1)
  1163. go func() {
  1164. defer pending.Done()
  1165. if err := tester.sync("faulty", nil, mode); err == nil {
  1166. panic("succeeded faulty synchronisation")
  1167. }
  1168. }()
  1169. <-starting
  1170. checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1171. HighestBlock: uint64(brokenChain.len() - 1),
  1172. })
  1173. progress <- struct{}{}
  1174. pending.Wait()
  1175. afterFailedSync := tester.downloader.Progress()
  1176. // Synchronise with a good peer and check that the progress origin remind the same
  1177. // after a failure
  1178. tester.newPeer("valid", protocol, chain)
  1179. pending.Add(1)
  1180. go func() {
  1181. defer pending.Done()
  1182. if err := tester.sync("valid", nil, mode); err != nil {
  1183. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1184. }
  1185. }()
  1186. <-starting
  1187. checkProgress(t, tester.downloader, "completing", afterFailedSync)
  1188. // Check final progress after successful sync
  1189. progress <- struct{}{}
  1190. pending.Wait()
  1191. checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1192. CurrentBlock: uint64(chain.len() - 1),
  1193. HighestBlock: uint64(chain.len() - 1),
  1194. })
  1195. }
  1196. // Tests that if an attacker fakes a chain height, after the attack is detected,
  1197. // the progress height is successfully reduced at the next sync invocation.
  1198. func TestFakedSyncProgress64Full(t *testing.T) { testFakedSyncProgress(t, 64, FullSync) }
  1199. func TestFakedSyncProgress64Fast(t *testing.T) { testFakedSyncProgress(t, 64, FastSync) }
  1200. func TestFakedSyncProgress65Full(t *testing.T) { testFakedSyncProgress(t, 65, FullSync) }
  1201. func TestFakedSyncProgress65Fast(t *testing.T) { testFakedSyncProgress(t, 65, FastSync) }
  1202. func TestFakedSyncProgress65Light(t *testing.T) { testFakedSyncProgress(t, 65, LightSync) }
  1203. func testFakedSyncProgress(t *testing.T, protocol uint, mode SyncMode) {
  1204. t.Parallel()
  1205. tester := newTester()
  1206. defer tester.terminate()
  1207. chain := testChainBase.shorten(blockCacheMaxItems - 15)
  1208. // Set a sync init hook to catch progress changes
  1209. starting := make(chan struct{})
  1210. progress := make(chan struct{})
  1211. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1212. starting <- struct{}{}
  1213. <-progress
  1214. }
  1215. checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1216. // Create and sync with an attacker that promises a higher chain than available.
  1217. brokenChain := chain.shorten(chain.len())
  1218. numMissing := 5
  1219. for i := brokenChain.len() - 2; i > brokenChain.len()-numMissing; i-- {
  1220. delete(brokenChain.headerm, brokenChain.chain[i])
  1221. }
  1222. tester.newPeer("attack", protocol, brokenChain)
  1223. pending := new(sync.WaitGroup)
  1224. pending.Add(1)
  1225. go func() {
  1226. defer pending.Done()
  1227. if err := tester.sync("attack", nil, mode); err == nil {
  1228. panic("succeeded attacker synchronisation")
  1229. }
  1230. }()
  1231. <-starting
  1232. checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1233. HighestBlock: uint64(brokenChain.len() - 1),
  1234. })
  1235. progress <- struct{}{}
  1236. pending.Wait()
  1237. afterFailedSync := tester.downloader.Progress()
  1238. // Synchronise with a good peer and check that the progress height has been reduced to
  1239. // the true value.
  1240. validChain := chain.shorten(chain.len() - numMissing)
  1241. tester.newPeer("valid", protocol, validChain)
  1242. pending.Add(1)
  1243. go func() {
  1244. defer pending.Done()
  1245. if err := tester.sync("valid", nil, mode); err != nil {
  1246. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1247. }
  1248. }()
  1249. <-starting
  1250. checkProgress(t, tester.downloader, "completing", ethereum.SyncProgress{
  1251. CurrentBlock: afterFailedSync.CurrentBlock,
  1252. HighestBlock: uint64(validChain.len() - 1),
  1253. })
  1254. // Check final progress after successful sync.
  1255. progress <- struct{}{}
  1256. pending.Wait()
  1257. checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1258. CurrentBlock: uint64(validChain.len() - 1),
  1259. HighestBlock: uint64(validChain.len() - 1),
  1260. })
  1261. }
  1262. // This test reproduces an issue where unexpected deliveries would
  1263. // block indefinitely if they arrived at the right time.
  1264. func TestDeliverHeadersHang64Full(t *testing.T) { testDeliverHeadersHang(t, 64, FullSync) }
  1265. func TestDeliverHeadersHang64Fast(t *testing.T) { testDeliverHeadersHang(t, 64, FastSync) }
  1266. func TestDeliverHeadersHang65Full(t *testing.T) { testDeliverHeadersHang(t, 65, FullSync) }
  1267. func TestDeliverHeadersHang65Fast(t *testing.T) { testDeliverHeadersHang(t, 65, FastSync) }
  1268. func TestDeliverHeadersHang65Light(t *testing.T) { testDeliverHeadersHang(t, 65, LightSync) }
  1269. func testDeliverHeadersHang(t *testing.T, protocol uint, mode SyncMode) {
  1270. t.Parallel()
  1271. master := newTester()
  1272. defer master.terminate()
  1273. chain := testChainBase.shorten(15)
  1274. for i := 0; i < 200; i++ {
  1275. tester := newTester()
  1276. tester.peerDb = master.peerDb
  1277. tester.newPeer("peer", protocol, chain)
  1278. // Whenever the downloader requests headers, flood it with
  1279. // a lot of unrequested header deliveries.
  1280. tester.downloader.peers.peers["peer"].peer = &floodingTestPeer{
  1281. peer: tester.downloader.peers.peers["peer"].peer,
  1282. tester: tester,
  1283. }
  1284. if err := tester.sync("peer", nil, mode); err != nil {
  1285. t.Errorf("test %d: sync failed: %v", i, err)
  1286. }
  1287. tester.terminate()
  1288. }
  1289. }
  1290. type floodingTestPeer struct {
  1291. peer Peer
  1292. tester *downloadTester
  1293. }
  1294. func (ftp *floodingTestPeer) Head() (common.Hash, *big.Int) { return ftp.peer.Head() }
  1295. func (ftp *floodingTestPeer) RequestHeadersByHash(hash common.Hash, count int, skip int, reverse bool) error {
  1296. return ftp.peer.RequestHeadersByHash(hash, count, skip, reverse)
  1297. }
  1298. func (ftp *floodingTestPeer) RequestBodies(hashes []common.Hash) error {
  1299. return ftp.peer.RequestBodies(hashes)
  1300. }
  1301. func (ftp *floodingTestPeer) RequestReceipts(hashes []common.Hash) error {
  1302. return ftp.peer.RequestReceipts(hashes)
  1303. }
  1304. func (ftp *floodingTestPeer) RequestNodeData(hashes []common.Hash) error {
  1305. return ftp.peer.RequestNodeData(hashes)
  1306. }
  1307. func (ftp *floodingTestPeer) RequestHeadersByNumber(from uint64, count, skip int, reverse bool) error {
  1308. deliveriesDone := make(chan struct{}, 500)
  1309. for i := 0; i < cap(deliveriesDone)-1; i++ {
  1310. peer := fmt.Sprintf("fake-peer%d", i)
  1311. go func() {
  1312. ftp.tester.downloader.DeliverHeaders(peer, []*types.Header{{}, {}, {}, {}})
  1313. deliveriesDone <- struct{}{}
  1314. }()
  1315. }
  1316. // None of the extra deliveries should block.
  1317. timeout := time.After(60 * time.Second)
  1318. launched := false
  1319. for i := 0; i < cap(deliveriesDone); i++ {
  1320. select {
  1321. case <-deliveriesDone:
  1322. if !launched {
  1323. // Start delivering the requested headers
  1324. // after one of the flooding responses has arrived.
  1325. go func() {
  1326. ftp.peer.RequestHeadersByNumber(from, count, skip, reverse)
  1327. deliveriesDone <- struct{}{}
  1328. }()
  1329. launched = true
  1330. }
  1331. case <-timeout:
  1332. panic("blocked")
  1333. }
  1334. }
  1335. return nil
  1336. }
  1337. func TestRemoteHeaderRequestSpan(t *testing.T) {
  1338. testCases := []struct {
  1339. remoteHeight uint64
  1340. localHeight uint64
  1341. expected []int
  1342. }{
  1343. // Remote is way higher. We should ask for the remote head and go backwards
  1344. {1500, 1000,
  1345. []int{1323, 1339, 1355, 1371, 1387, 1403, 1419, 1435, 1451, 1467, 1483, 1499},
  1346. },
  1347. {15000, 13006,
  1348. []int{14823, 14839, 14855, 14871, 14887, 14903, 14919, 14935, 14951, 14967, 14983, 14999},
  1349. },
  1350. // Remote is pretty close to us. We don't have to fetch as many
  1351. {1200, 1150,
  1352. []int{1149, 1154, 1159, 1164, 1169, 1174, 1179, 1184, 1189, 1194, 1199},
  1353. },
  1354. // Remote is equal to us (so on a fork with higher td)
  1355. // We should get the closest couple of ancestors
  1356. {1500, 1500,
  1357. []int{1497, 1499},
  1358. },
  1359. // We're higher than the remote! Odd
  1360. {1000, 1500,
  1361. []int{997, 999},
  1362. },
  1363. // Check some weird edgecases that it behaves somewhat rationally
  1364. {0, 1500,
  1365. []int{0, 2},
  1366. },
  1367. {6000000, 0,
  1368. []int{5999823, 5999839, 5999855, 5999871, 5999887, 5999903, 5999919, 5999935, 5999951, 5999967, 5999983, 5999999},
  1369. },
  1370. {0, 0,
  1371. []int{0, 2},
  1372. },
  1373. }
  1374. reqs := func(from, count, span int) []int {
  1375. var r []int
  1376. num := from
  1377. for len(r) < count {
  1378. r = append(r, num)
  1379. num += span + 1
  1380. }
  1381. return r
  1382. }
  1383. for i, tt := range testCases {
  1384. from, count, span, max := calculateRequestSpan(tt.remoteHeight, tt.localHeight)
  1385. data := reqs(int(from), count, span)
  1386. if max != uint64(data[len(data)-1]) {
  1387. t.Errorf("test %d: wrong last value %d != %d", i, data[len(data)-1], max)
  1388. }
  1389. failed := false
  1390. if len(data) != len(tt.expected) {
  1391. failed = true
  1392. t.Errorf("test %d: length wrong, expected %d got %d", i, len(tt.expected), len(data))
  1393. } else {
  1394. for j, n := range data {
  1395. if n != tt.expected[j] {
  1396. failed = true
  1397. break
  1398. }
  1399. }
  1400. }
  1401. if failed {
  1402. res := strings.Replace(fmt.Sprint(data), " ", ",", -1)
  1403. exp := strings.Replace(fmt.Sprint(tt.expected), " ", ",", -1)
  1404. t.Logf("got: %v\n", res)
  1405. t.Logf("exp: %v\n", exp)
  1406. t.Errorf("test %d: wrong values", i)
  1407. }
  1408. }
  1409. }
  1410. // Tests that peers below a pre-configured checkpoint block are prevented from
  1411. // being fast-synced from, avoiding potential cheap eclipse attacks.
  1412. func TestCheckpointEnforcement64Full(t *testing.T) { testCheckpointEnforcement(t, 64, FullSync) }
  1413. func TestCheckpointEnforcement64Fast(t *testing.T) { testCheckpointEnforcement(t, 64, FastSync) }
  1414. func TestCheckpointEnforcement65Full(t *testing.T) { testCheckpointEnforcement(t, 65, FullSync) }
  1415. func TestCheckpointEnforcement65Fast(t *testing.T) { testCheckpointEnforcement(t, 65, FastSync) }
  1416. func TestCheckpointEnforcement65Light(t *testing.T) { testCheckpointEnforcement(t, 65, LightSync) }
  1417. func testCheckpointEnforcement(t *testing.T, protocol uint, mode SyncMode) {
  1418. t.Parallel()
  1419. // Create a new tester with a particular hard coded checkpoint block
  1420. tester := newTester()
  1421. defer tester.terminate()
  1422. tester.downloader.checkpoint = uint64(fsMinFullBlocks) + 256
  1423. chain := testChainBase.shorten(int(tester.downloader.checkpoint) - 1)
  1424. // Attempt to sync with the peer and validate the result
  1425. tester.newPeer("peer", protocol, chain)
  1426. var expect error
  1427. if mode == FastSync || mode == LightSync {
  1428. expect = errUnsyncedPeer
  1429. }
  1430. if err := tester.sync("peer", nil, mode); !errors.Is(err, expect) {
  1431. t.Fatalf("block sync error mismatch: have %v, want %v", err, expect)
  1432. }
  1433. if mode == FastSync || mode == LightSync {
  1434. assertOwnChain(t, tester, 1)
  1435. } else {
  1436. assertOwnChain(t, tester, chain.len())
  1437. }
  1438. }