downloader_test.go 61 KB

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