downloader_test.go 63 KB

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