downloader_test.go 65 KB

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