downloader_test.go 59 KB

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