downloader_test.go 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608
  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. 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, 0, 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. {errUnsyncedPeer, true}, // Peer was detected to be unsynced, drop it
  905. {errNoPeers, false}, // No peers to download from, soft race, no issue
  906. {errTimeout, true}, // No hashes received in due time, drop the peer
  907. {errEmptyHeaderSet, true}, // No headers were returned as a response, drop as it's a dead end
  908. {errPeersUnavailable, true}, // Nobody had the advertised blocks, drop the advertiser
  909. {errInvalidAncestor, true}, // Agreed upon ancestor is not acceptable, drop the chain rewriter
  910. {errInvalidChain, true}, // Hash chain was detected as invalid, definitely drop
  911. {errInvalidBlock, false}, // A bad peer was detected, but not the sync origin
  912. {errInvalidBody, false}, // A bad peer was detected, but not the sync origin
  913. {errInvalidReceipt, false}, // A bad peer was detected, but not the sync origin
  914. {errCancelBlockFetch, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  915. {errCancelHeaderFetch, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  916. {errCancelBodyFetch, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  917. {errCancelReceiptFetch, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  918. {errCancelHeaderProcessing, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  919. {errCancelContentProcessing, false}, // Synchronisation was canceled, origin may be innocent, don't drop
  920. }
  921. // Run the tests and check disconnection status
  922. tester := newTester()
  923. defer tester.terminate()
  924. chain := testChainBase.shorten(1)
  925. for i, tt := range tests {
  926. // Register a new peer and ensure it's presence
  927. id := fmt.Sprintf("test %d", i)
  928. if err := tester.newPeer(id, protocol, chain); err != nil {
  929. t.Fatalf("test %d: failed to register new peer: %v", i, err)
  930. }
  931. if _, ok := tester.peers[id]; !ok {
  932. t.Fatalf("test %d: registered peer not found", i)
  933. }
  934. // Simulate a synchronisation and check the required result
  935. tester.downloader.synchroniseMock = func(string, common.Hash) error { return tt.result }
  936. tester.downloader.Synchronise(id, tester.genesis.Hash(), big.NewInt(1000), FullSync)
  937. if _, ok := tester.peers[id]; !ok != tt.drop {
  938. t.Errorf("test %d: peer drop mismatch for %v: have %v, want %v", i, tt.result, !ok, tt.drop)
  939. }
  940. }
  941. }
  942. // Tests that synchronisation progress (origin block number, current block number
  943. // and highest block number) is tracked and updated correctly.
  944. func TestSyncProgress62(t *testing.T) { testSyncProgress(t, 62, FullSync) }
  945. func TestSyncProgress63Full(t *testing.T) { testSyncProgress(t, 63, FullSync) }
  946. func TestSyncProgress63Fast(t *testing.T) { testSyncProgress(t, 63, FastSync) }
  947. func TestSyncProgress64Full(t *testing.T) { testSyncProgress(t, 64, FullSync) }
  948. func TestSyncProgress64Fast(t *testing.T) { testSyncProgress(t, 64, FastSync) }
  949. func TestSyncProgress64Light(t *testing.T) { testSyncProgress(t, 64, LightSync) }
  950. func testSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  951. t.Parallel()
  952. tester := newTester()
  953. defer tester.terminate()
  954. chain := testChainBase.shorten(blockCacheItems - 15)
  955. // Set a sync init hook to catch progress changes
  956. starting := make(chan struct{})
  957. progress := make(chan struct{})
  958. tester.downloader.syncInitHook = func(origin, latest uint64) {
  959. starting <- struct{}{}
  960. <-progress
  961. }
  962. checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  963. // Synchronise half the blocks and check initial progress
  964. tester.newPeer("peer-half", protocol, chain.shorten(chain.len()/2))
  965. pending := new(sync.WaitGroup)
  966. pending.Add(1)
  967. go func() {
  968. defer pending.Done()
  969. if err := tester.sync("peer-half", nil, mode); err != nil {
  970. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  971. }
  972. }()
  973. <-starting
  974. checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  975. HighestBlock: uint64(chain.len()/2 - 1),
  976. })
  977. progress <- struct{}{}
  978. pending.Wait()
  979. // Synchronise all the blocks and check continuation progress
  980. tester.newPeer("peer-full", protocol, chain)
  981. pending.Add(1)
  982. go func() {
  983. defer pending.Done()
  984. if err := tester.sync("peer-full", nil, mode); err != nil {
  985. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  986. }
  987. }()
  988. <-starting
  989. checkProgress(t, tester.downloader, "completing", ethereum.SyncProgress{
  990. StartingBlock: uint64(chain.len()/2 - 1),
  991. CurrentBlock: uint64(chain.len()/2 - 1),
  992. HighestBlock: uint64(chain.len() - 1),
  993. })
  994. // Check final progress after successful sync
  995. progress <- struct{}{}
  996. pending.Wait()
  997. checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  998. StartingBlock: uint64(chain.len()/2 - 1),
  999. CurrentBlock: uint64(chain.len() - 1),
  1000. HighestBlock: uint64(chain.len() - 1),
  1001. })
  1002. }
  1003. func checkProgress(t *testing.T, d *Downloader, stage string, want ethereum.SyncProgress) {
  1004. // Mark this method as a helper to report errors at callsite, not in here
  1005. t.Helper()
  1006. p := d.Progress()
  1007. p.KnownStates, p.PulledStates = 0, 0
  1008. want.KnownStates, want.PulledStates = 0, 0
  1009. if p != want {
  1010. t.Fatalf("%s progress mismatch:\nhave %+v\nwant %+v", stage, p, want)
  1011. }
  1012. }
  1013. // Tests that synchronisation progress (origin block number and highest block
  1014. // number) is tracked and updated correctly in case of a fork (or manual head
  1015. // revertal).
  1016. func TestForkedSyncProgress62(t *testing.T) { testForkedSyncProgress(t, 62, FullSync) }
  1017. func TestForkedSyncProgress63Full(t *testing.T) { testForkedSyncProgress(t, 63, FullSync) }
  1018. func TestForkedSyncProgress63Fast(t *testing.T) { testForkedSyncProgress(t, 63, FastSync) }
  1019. func TestForkedSyncProgress64Full(t *testing.T) { testForkedSyncProgress(t, 64, FullSync) }
  1020. func TestForkedSyncProgress64Fast(t *testing.T) { testForkedSyncProgress(t, 64, FastSync) }
  1021. func TestForkedSyncProgress64Light(t *testing.T) { testForkedSyncProgress(t, 64, LightSync) }
  1022. func testForkedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1023. t.Parallel()
  1024. tester := newTester()
  1025. defer tester.terminate()
  1026. chainA := testChainForkLightA.shorten(testChainBase.len() + MaxHashFetch)
  1027. chainB := testChainForkLightB.shorten(testChainBase.len() + MaxHashFetch)
  1028. // Set a sync init hook to catch progress changes
  1029. starting := make(chan struct{})
  1030. progress := make(chan struct{})
  1031. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1032. starting <- struct{}{}
  1033. <-progress
  1034. }
  1035. checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1036. // Synchronise with one of the forks and check progress
  1037. tester.newPeer("fork A", protocol, chainA)
  1038. pending := new(sync.WaitGroup)
  1039. pending.Add(1)
  1040. go func() {
  1041. defer pending.Done()
  1042. if err := tester.sync("fork A", nil, mode); err != nil {
  1043. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1044. }
  1045. }()
  1046. <-starting
  1047. checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1048. HighestBlock: uint64(chainA.len() - 1),
  1049. })
  1050. progress <- struct{}{}
  1051. pending.Wait()
  1052. // Simulate a successful sync above the fork
  1053. tester.downloader.syncStatsChainOrigin = tester.downloader.syncStatsChainHeight
  1054. // Synchronise with the second fork and check progress resets
  1055. tester.newPeer("fork B", protocol, chainB)
  1056. pending.Add(1)
  1057. go func() {
  1058. defer pending.Done()
  1059. if err := tester.sync("fork B", nil, mode); err != nil {
  1060. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1061. }
  1062. }()
  1063. <-starting
  1064. checkProgress(t, tester.downloader, "forking", ethereum.SyncProgress{
  1065. StartingBlock: uint64(testChainBase.len()) - 1,
  1066. CurrentBlock: uint64(chainA.len() - 1),
  1067. HighestBlock: uint64(chainB.len() - 1),
  1068. })
  1069. // Check final progress after successful sync
  1070. progress <- struct{}{}
  1071. pending.Wait()
  1072. checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1073. StartingBlock: uint64(testChainBase.len()) - 1,
  1074. CurrentBlock: uint64(chainB.len() - 1),
  1075. HighestBlock: uint64(chainB.len() - 1),
  1076. })
  1077. }
  1078. // Tests that if synchronisation is aborted due to some failure, then the progress
  1079. // origin is not updated in the next sync cycle, as it should be considered the
  1080. // continuation of the previous sync and not a new instance.
  1081. func TestFailedSyncProgress62(t *testing.T) { testFailedSyncProgress(t, 62, FullSync) }
  1082. func TestFailedSyncProgress63Full(t *testing.T) { testFailedSyncProgress(t, 63, FullSync) }
  1083. func TestFailedSyncProgress63Fast(t *testing.T) { testFailedSyncProgress(t, 63, FastSync) }
  1084. func TestFailedSyncProgress64Full(t *testing.T) { testFailedSyncProgress(t, 64, FullSync) }
  1085. func TestFailedSyncProgress64Fast(t *testing.T) { testFailedSyncProgress(t, 64, FastSync) }
  1086. func TestFailedSyncProgress64Light(t *testing.T) { testFailedSyncProgress(t, 64, LightSync) }
  1087. func testFailedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1088. t.Parallel()
  1089. tester := newTester()
  1090. defer tester.terminate()
  1091. chain := testChainBase.shorten(blockCacheItems - 15)
  1092. // Set a sync init hook to catch progress changes
  1093. starting := make(chan struct{})
  1094. progress := make(chan struct{})
  1095. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1096. starting <- struct{}{}
  1097. <-progress
  1098. }
  1099. checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1100. // Attempt a full sync with a faulty peer
  1101. brokenChain := chain.shorten(chain.len())
  1102. missing := brokenChain.len() / 2
  1103. delete(brokenChain.headerm, brokenChain.chain[missing])
  1104. delete(brokenChain.blockm, brokenChain.chain[missing])
  1105. delete(brokenChain.receiptm, brokenChain.chain[missing])
  1106. tester.newPeer("faulty", protocol, brokenChain)
  1107. pending := new(sync.WaitGroup)
  1108. pending.Add(1)
  1109. go func() {
  1110. defer pending.Done()
  1111. if err := tester.sync("faulty", nil, mode); err == nil {
  1112. panic("succeeded faulty synchronisation")
  1113. }
  1114. }()
  1115. <-starting
  1116. checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1117. HighestBlock: uint64(brokenChain.len() - 1),
  1118. })
  1119. progress <- struct{}{}
  1120. pending.Wait()
  1121. afterFailedSync := tester.downloader.Progress()
  1122. // Synchronise with a good peer and check that the progress origin remind the same
  1123. // after a failure
  1124. tester.newPeer("valid", protocol, chain)
  1125. pending.Add(1)
  1126. go func() {
  1127. defer pending.Done()
  1128. if err := tester.sync("valid", nil, mode); err != nil {
  1129. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1130. }
  1131. }()
  1132. <-starting
  1133. checkProgress(t, tester.downloader, "completing", afterFailedSync)
  1134. // Check final progress after successful sync
  1135. progress <- struct{}{}
  1136. pending.Wait()
  1137. checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1138. CurrentBlock: uint64(chain.len() - 1),
  1139. HighestBlock: uint64(chain.len() - 1),
  1140. })
  1141. }
  1142. // Tests that if an attacker fakes a chain height, after the attack is detected,
  1143. // the progress height is successfully reduced at the next sync invocation.
  1144. func TestFakedSyncProgress62(t *testing.T) { testFakedSyncProgress(t, 62, FullSync) }
  1145. func TestFakedSyncProgress63Full(t *testing.T) { testFakedSyncProgress(t, 63, FullSync) }
  1146. func TestFakedSyncProgress63Fast(t *testing.T) { testFakedSyncProgress(t, 63, FastSync) }
  1147. func TestFakedSyncProgress64Full(t *testing.T) { testFakedSyncProgress(t, 64, FullSync) }
  1148. func TestFakedSyncProgress64Fast(t *testing.T) { testFakedSyncProgress(t, 64, FastSync) }
  1149. func TestFakedSyncProgress64Light(t *testing.T) { testFakedSyncProgress(t, 64, LightSync) }
  1150. func testFakedSyncProgress(t *testing.T, protocol int, mode SyncMode) {
  1151. t.Parallel()
  1152. tester := newTester()
  1153. defer tester.terminate()
  1154. chain := testChainBase.shorten(blockCacheItems - 15)
  1155. // Set a sync init hook to catch progress changes
  1156. starting := make(chan struct{})
  1157. progress := make(chan struct{})
  1158. tester.downloader.syncInitHook = func(origin, latest uint64) {
  1159. starting <- struct{}{}
  1160. <-progress
  1161. }
  1162. checkProgress(t, tester.downloader, "pristine", ethereum.SyncProgress{})
  1163. // Create and sync with an attacker that promises a higher chain than available.
  1164. brokenChain := chain.shorten(chain.len())
  1165. numMissing := 5
  1166. for i := brokenChain.len() - 2; i > brokenChain.len()-numMissing; i-- {
  1167. delete(brokenChain.headerm, brokenChain.chain[i])
  1168. }
  1169. tester.newPeer("attack", protocol, brokenChain)
  1170. pending := new(sync.WaitGroup)
  1171. pending.Add(1)
  1172. go func() {
  1173. defer pending.Done()
  1174. if err := tester.sync("attack", nil, mode); err == nil {
  1175. panic("succeeded attacker synchronisation")
  1176. }
  1177. }()
  1178. <-starting
  1179. checkProgress(t, tester.downloader, "initial", ethereum.SyncProgress{
  1180. HighestBlock: uint64(brokenChain.len() - 1),
  1181. })
  1182. progress <- struct{}{}
  1183. pending.Wait()
  1184. afterFailedSync := tester.downloader.Progress()
  1185. // Synchronise with a good peer and check that the progress height has been reduced to
  1186. // the true value.
  1187. validChain := chain.shorten(chain.len() - numMissing)
  1188. tester.newPeer("valid", protocol, validChain)
  1189. pending.Add(1)
  1190. go func() {
  1191. defer pending.Done()
  1192. if err := tester.sync("valid", nil, mode); err != nil {
  1193. panic(fmt.Sprintf("failed to synchronise blocks: %v", err))
  1194. }
  1195. }()
  1196. <-starting
  1197. checkProgress(t, tester.downloader, "completing", ethereum.SyncProgress{
  1198. CurrentBlock: afterFailedSync.CurrentBlock,
  1199. HighestBlock: uint64(validChain.len() - 1),
  1200. })
  1201. // Check final progress after successful sync.
  1202. progress <- struct{}{}
  1203. pending.Wait()
  1204. checkProgress(t, tester.downloader, "final", ethereum.SyncProgress{
  1205. CurrentBlock: uint64(validChain.len() - 1),
  1206. HighestBlock: uint64(validChain.len() - 1),
  1207. })
  1208. }
  1209. // This test reproduces an issue where unexpected deliveries would
  1210. // block indefinitely if they arrived at the right time.
  1211. func TestDeliverHeadersHang(t *testing.T) {
  1212. t.Parallel()
  1213. testCases := []struct {
  1214. protocol int
  1215. syncMode SyncMode
  1216. }{
  1217. {62, FullSync},
  1218. {63, FullSync},
  1219. {63, FastSync},
  1220. {64, FullSync},
  1221. {64, FastSync},
  1222. {64, LightSync},
  1223. }
  1224. for _, tc := range testCases {
  1225. t.Run(fmt.Sprintf("protocol %d mode %v", tc.protocol, tc.syncMode), func(t *testing.T) {
  1226. t.Parallel()
  1227. testDeliverHeadersHang(t, tc.protocol, tc.syncMode)
  1228. })
  1229. }
  1230. }
  1231. func testDeliverHeadersHang(t *testing.T, protocol int, mode SyncMode) {
  1232. master := newTester()
  1233. defer master.terminate()
  1234. chain := testChainBase.shorten(15)
  1235. for i := 0; i < 200; i++ {
  1236. tester := newTester()
  1237. tester.peerDb = master.peerDb
  1238. tester.newPeer("peer", protocol, chain)
  1239. // Whenever the downloader requests headers, flood it with
  1240. // a lot of unrequested header deliveries.
  1241. tester.downloader.peers.peers["peer"].peer = &floodingTestPeer{
  1242. peer: tester.downloader.peers.peers["peer"].peer,
  1243. tester: tester,
  1244. }
  1245. if err := tester.sync("peer", nil, mode); err != nil {
  1246. t.Errorf("test %d: sync failed: %v", i, err)
  1247. }
  1248. tester.terminate()
  1249. }
  1250. }
  1251. type floodingTestPeer struct {
  1252. peer Peer
  1253. tester *downloadTester
  1254. }
  1255. func (ftp *floodingTestPeer) Head() (common.Hash, *big.Int) { return ftp.peer.Head() }
  1256. func (ftp *floodingTestPeer) RequestHeadersByHash(hash common.Hash, count int, skip int, reverse bool) error {
  1257. return ftp.peer.RequestHeadersByHash(hash, count, skip, reverse)
  1258. }
  1259. func (ftp *floodingTestPeer) RequestBodies(hashes []common.Hash) error {
  1260. return ftp.peer.RequestBodies(hashes)
  1261. }
  1262. func (ftp *floodingTestPeer) RequestReceipts(hashes []common.Hash) error {
  1263. return ftp.peer.RequestReceipts(hashes)
  1264. }
  1265. func (ftp *floodingTestPeer) RequestNodeData(hashes []common.Hash) error {
  1266. return ftp.peer.RequestNodeData(hashes)
  1267. }
  1268. func (ftp *floodingTestPeer) RequestHeadersByNumber(from uint64, count, skip int, reverse bool) error {
  1269. deliveriesDone := make(chan struct{}, 500)
  1270. for i := 0; i < cap(deliveriesDone)-1; i++ {
  1271. peer := fmt.Sprintf("fake-peer%d", i)
  1272. go func() {
  1273. ftp.tester.downloader.DeliverHeaders(peer, []*types.Header{{}, {}, {}, {}})
  1274. deliveriesDone <- struct{}{}
  1275. }()
  1276. }
  1277. // None of the extra deliveries should block.
  1278. timeout := time.After(60 * time.Second)
  1279. launched := false
  1280. for i := 0; i < cap(deliveriesDone); i++ {
  1281. select {
  1282. case <-deliveriesDone:
  1283. if !launched {
  1284. // Start delivering the requested headers
  1285. // after one of the flooding responses has arrived.
  1286. go func() {
  1287. ftp.peer.RequestHeadersByNumber(from, count, skip, reverse)
  1288. deliveriesDone <- struct{}{}
  1289. }()
  1290. launched = true
  1291. }
  1292. case <-timeout:
  1293. panic("blocked")
  1294. }
  1295. }
  1296. return nil
  1297. }
  1298. func TestRemoteHeaderRequestSpan(t *testing.T) {
  1299. testCases := []struct {
  1300. remoteHeight uint64
  1301. localHeight uint64
  1302. expected []int
  1303. }{
  1304. // Remote is way higher. We should ask for the remote head and go backwards
  1305. {1500, 1000,
  1306. []int{1323, 1339, 1355, 1371, 1387, 1403, 1419, 1435, 1451, 1467, 1483, 1499},
  1307. },
  1308. {15000, 13006,
  1309. []int{14823, 14839, 14855, 14871, 14887, 14903, 14919, 14935, 14951, 14967, 14983, 14999},
  1310. },
  1311. //Remote is pretty close to us. We don't have to fetch as many
  1312. {1200, 1150,
  1313. []int{1149, 1154, 1159, 1164, 1169, 1174, 1179, 1184, 1189, 1194, 1199},
  1314. },
  1315. // Remote is equal to us (so on a fork with higher td)
  1316. // We should get the closest couple of ancestors
  1317. {1500, 1500,
  1318. []int{1497, 1499},
  1319. },
  1320. // We're higher than the remote! Odd
  1321. {1000, 1500,
  1322. []int{997, 999},
  1323. },
  1324. // Check some weird edgecases that it behaves somewhat rationally
  1325. {0, 1500,
  1326. []int{0, 2},
  1327. },
  1328. {6000000, 0,
  1329. []int{5999823, 5999839, 5999855, 5999871, 5999887, 5999903, 5999919, 5999935, 5999951, 5999967, 5999983, 5999999},
  1330. },
  1331. {0, 0,
  1332. []int{0, 2},
  1333. },
  1334. }
  1335. reqs := func(from, count, span int) []int {
  1336. var r []int
  1337. num := from
  1338. for len(r) < count {
  1339. r = append(r, num)
  1340. num += span + 1
  1341. }
  1342. return r
  1343. }
  1344. for i, tt := range testCases {
  1345. from, count, span, max := calculateRequestSpan(tt.remoteHeight, tt.localHeight)
  1346. data := reqs(int(from), count, span)
  1347. if max != uint64(data[len(data)-1]) {
  1348. t.Errorf("test %d: wrong last value %d != %d", i, data[len(data)-1], max)
  1349. }
  1350. failed := false
  1351. if len(data) != len(tt.expected) {
  1352. failed = true
  1353. t.Errorf("test %d: length wrong, expected %d got %d", i, len(tt.expected), len(data))
  1354. } else {
  1355. for j, n := range data {
  1356. if n != tt.expected[j] {
  1357. failed = true
  1358. break
  1359. }
  1360. }
  1361. }
  1362. if failed {
  1363. res := strings.Replace(fmt.Sprint(data), " ", ",", -1)
  1364. exp := strings.Replace(fmt.Sprint(tt.expected), " ", ",", -1)
  1365. fmt.Printf("got: %v\n", res)
  1366. fmt.Printf("exp: %v\n", exp)
  1367. t.Errorf("test %d: wrong values", i)
  1368. }
  1369. }
  1370. }
  1371. // Tests that peers below a pre-configured checkpoint block are prevented from
  1372. // being fast-synced from, avoiding potential cheap eclipse attacks.
  1373. func TestCheckpointEnforcement62(t *testing.T) { testCheckpointEnforcement(t, 62, FullSync) }
  1374. func TestCheckpointEnforcement63Full(t *testing.T) { testCheckpointEnforcement(t, 63, FullSync) }
  1375. func TestCheckpointEnforcement63Fast(t *testing.T) { testCheckpointEnforcement(t, 63, FastSync) }
  1376. func TestCheckpointEnforcement64Full(t *testing.T) { testCheckpointEnforcement(t, 64, FullSync) }
  1377. func TestCheckpointEnforcement64Fast(t *testing.T) { testCheckpointEnforcement(t, 64, FastSync) }
  1378. func TestCheckpointEnforcement64Light(t *testing.T) { testCheckpointEnforcement(t, 64, LightSync) }
  1379. func testCheckpointEnforcement(t *testing.T, protocol int, mode SyncMode) {
  1380. t.Parallel()
  1381. // Create a new tester with a particular hard coded checkpoint block
  1382. tester := newTester()
  1383. defer tester.terminate()
  1384. tester.downloader.checkpoint = uint64(fsMinFullBlocks) + 256
  1385. chain := testChainBase.shorten(int(tester.downloader.checkpoint) - 1)
  1386. // Attempt to sync with the peer and validate the result
  1387. tester.newPeer("peer", protocol, chain)
  1388. var expect error
  1389. if mode == FastSync {
  1390. expect = errUnsyncedPeer
  1391. }
  1392. if err := tester.sync("peer", nil, mode); err != expect {
  1393. t.Fatalf("block sync error mismatch: have %v, want %v", err, expect)
  1394. }
  1395. if mode == FastSync {
  1396. assertOwnChain(t, tester, 1)
  1397. } else {
  1398. assertOwnChain(t, tester, chain.len())
  1399. }
  1400. }