downloader.go 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  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 contains the manual full chain synchronisation.
  17. package downloader
  18. import (
  19. "errors"
  20. "fmt"
  21. "math/big"
  22. "sync"
  23. "sync/atomic"
  24. "time"
  25. ethereum "github.com/ethereum/go-ethereum"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/ethdb"
  29. "github.com/ethereum/go-ethereum/event"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/metrics"
  32. "github.com/ethereum/go-ethereum/params"
  33. )
  34. var (
  35. MaxHashFetch = 512 // Amount of hashes to be fetched per retrieval request
  36. MaxBlockFetch = 128 // Amount of blocks to be fetched per retrieval request
  37. MaxHeaderFetch = 192 // Amount of block headers to be fetched per retrieval request
  38. MaxSkeletonSize = 128 // Number of header fetches to need for a skeleton assembly
  39. MaxBodyFetch = 128 // Amount of block bodies to be fetched per retrieval request
  40. MaxReceiptFetch = 256 // Amount of transaction receipts to allow fetching per request
  41. MaxStateFetch = 384 // Amount of node state values to allow fetching per request
  42. MaxForkAncestry = 3 * params.EpochDuration // Maximum chain reorganisation
  43. rttMinEstimate = 2 * time.Second // Minimum round-trip time to target for download requests
  44. rttMaxEstimate = 20 * time.Second // Maximum rount-trip time to target for download requests
  45. rttMinConfidence = 0.1 // Worse confidence factor in our estimated RTT value
  46. ttlScaling = 3 // Constant scaling factor for RTT -> TTL conversion
  47. ttlLimit = time.Minute // Maximum TTL allowance to prevent reaching crazy timeouts
  48. qosTuningPeers = 5 // Number of peers to tune based on (best peers)
  49. qosConfidenceCap = 10 // Number of peers above which not to modify RTT confidence
  50. qosTuningImpact = 0.25 // Impact that a new tuning target has on the previous value
  51. maxQueuedHeaders = 32 * 1024 // [eth/62] Maximum number of headers to queue for import (DOS protection)
  52. maxHeadersProcess = 2048 // Number of header download results to import at once into the chain
  53. maxResultsProcess = 2048 // Number of content download results to import at once into the chain
  54. fsHeaderCheckFrequency = 100 // Verification frequency of the downloaded headers during fast sync
  55. fsHeaderSafetyNet = 2048 // Number of headers to discard in case a chain violation is detected
  56. fsHeaderForceVerify = 24 // Number of headers to verify before and after the pivot to accept it
  57. fsHeaderContCheck = 3 * time.Second // Time interval to check for header continuations during state download
  58. fsMinFullBlocks = 64 // Number of blocks to retrieve fully even in fast sync
  59. )
  60. var (
  61. errBusy = errors.New("busy")
  62. errUnknownPeer = errors.New("peer is unknown or unhealthy")
  63. errBadPeer = errors.New("action from bad peer ignored")
  64. errStallingPeer = errors.New("peer is stalling")
  65. errNoPeers = errors.New("no peers to keep download active")
  66. errTimeout = errors.New("timeout")
  67. errEmptyHeaderSet = errors.New("empty header set by peer")
  68. errPeersUnavailable = errors.New("no peers available or all tried for download")
  69. errInvalidAncestor = errors.New("retrieved ancestor is invalid")
  70. errInvalidChain = errors.New("retrieved hash chain is invalid")
  71. errInvalidBlock = errors.New("retrieved block is invalid")
  72. errInvalidBody = errors.New("retrieved block body is invalid")
  73. errInvalidReceipt = errors.New("retrieved receipt is invalid")
  74. errCancelBlockFetch = errors.New("block download canceled (requested)")
  75. errCancelHeaderFetch = errors.New("block header download canceled (requested)")
  76. errCancelBodyFetch = errors.New("block body download canceled (requested)")
  77. errCancelReceiptFetch = errors.New("receipt download canceled (requested)")
  78. errCancelStateFetch = errors.New("state data download canceled (requested)")
  79. errCancelHeaderProcessing = errors.New("header processing canceled (requested)")
  80. errCancelContentProcessing = errors.New("content processing canceled (requested)")
  81. errNoSyncActive = errors.New("no sync active")
  82. errTooOld = errors.New("peer doesn't speak recent enough protocol version (need version >= 62)")
  83. )
  84. type Downloader struct {
  85. mode SyncMode // Synchronisation mode defining the strategy used (per sync cycle)
  86. mux *event.TypeMux // Event multiplexer to announce sync operation events
  87. queue *queue // Scheduler for selecting the hashes to download
  88. peers *peerSet // Set of active peers from which download can proceed
  89. stateDB ethdb.Database
  90. rttEstimate uint64 // Round trip time to target for download requests
  91. rttConfidence uint64 // Confidence in the estimated RTT (unit: millionths to allow atomic ops)
  92. // Statistics
  93. syncStatsChainOrigin uint64 // Origin block number where syncing started at
  94. syncStatsChainHeight uint64 // Highest block number known when syncing started
  95. syncStatsState stateSyncStats
  96. syncStatsLock sync.RWMutex // Lock protecting the sync stats fields
  97. lightchain LightChain
  98. blockchain BlockChain
  99. // Callbacks
  100. dropPeer peerDropFn // Drops a peer for misbehaving
  101. // Status
  102. synchroniseMock func(id string, hash common.Hash) error // Replacement for synchronise during testing
  103. synchronising int32
  104. notified int32
  105. committed int32
  106. // Channels
  107. headerCh chan dataPack // [eth/62] Channel receiving inbound block headers
  108. bodyCh chan dataPack // [eth/62] Channel receiving inbound block bodies
  109. receiptCh chan dataPack // [eth/63] Channel receiving inbound receipts
  110. bodyWakeCh chan bool // [eth/62] Channel to signal the block body fetcher of new tasks
  111. receiptWakeCh chan bool // [eth/63] Channel to signal the receipt fetcher of new tasks
  112. headerProcCh chan []*types.Header // [eth/62] Channel to feed the header processor new tasks
  113. // for stateFetcher
  114. stateSyncStart chan *stateSync
  115. trackStateReq chan *stateReq
  116. stateCh chan dataPack // [eth/63] Channel receiving inbound node state data
  117. // Cancellation and termination
  118. cancelPeer string // Identifier of the peer currently being used as the master (cancel on drop)
  119. cancelCh chan struct{} // Channel to cancel mid-flight syncs
  120. cancelLock sync.RWMutex // Lock to protect the cancel channel and peer in delivers
  121. quitCh chan struct{} // Quit channel to signal termination
  122. quitLock sync.RWMutex // Lock to prevent double closes
  123. // Testing hooks
  124. syncInitHook func(uint64, uint64) // Method to call upon initiating a new sync run
  125. bodyFetchHook func([]*types.Header) // Method to call upon starting a block body fetch
  126. receiptFetchHook func([]*types.Header) // Method to call upon starting a receipt fetch
  127. chainInsertHook func([]*fetchResult) // Method to call upon inserting a chain of blocks (possibly in multiple invocations)
  128. }
  129. // LightChain encapsulates functions required to synchronise a light chain.
  130. type LightChain interface {
  131. // HasHeader verifies a header's presence in the local chain.
  132. HasHeader(common.Hash, uint64) bool
  133. // GetHeaderByHash retrieves a header from the local chain.
  134. GetHeaderByHash(common.Hash) *types.Header
  135. // CurrentHeader retrieves the head header from the local chain.
  136. CurrentHeader() *types.Header
  137. // GetTd returns the total difficulty of a local block.
  138. GetTd(common.Hash, uint64) *big.Int
  139. // InsertHeaderChain inserts a batch of headers into the local chain.
  140. InsertHeaderChain([]*types.Header, int) (int, error)
  141. // Rollback removes a few recently added elements from the local chain.
  142. Rollback([]common.Hash)
  143. }
  144. // BlockChain encapsulates functions required to sync a (full or fast) blockchain.
  145. type BlockChain interface {
  146. LightChain
  147. // HasBlock verifies a block's presence in the local chain.
  148. HasBlock(common.Hash, uint64) bool
  149. // GetBlockByHash retrieves a block from the local chain.
  150. GetBlockByHash(common.Hash) *types.Block
  151. // CurrentBlock retrieves the head block from the local chain.
  152. CurrentBlock() *types.Block
  153. // CurrentFastBlock retrieves the head fast block from the local chain.
  154. CurrentFastBlock() *types.Block
  155. // FastSyncCommitHead directly commits the head block to a certain entity.
  156. FastSyncCommitHead(common.Hash) error
  157. // InsertChain inserts a batch of blocks into the local chain.
  158. InsertChain(types.Blocks) (int, error)
  159. // InsertReceiptChain inserts a batch of receipts into the local chain.
  160. InsertReceiptChain(types.Blocks, []types.Receipts) (int, error)
  161. }
  162. // New creates a new downloader to fetch hashes and blocks from remote peers.
  163. func New(mode SyncMode, stateDb ethdb.Database, mux *event.TypeMux, chain BlockChain, lightchain LightChain, dropPeer peerDropFn) *Downloader {
  164. if lightchain == nil {
  165. lightchain = chain
  166. }
  167. dl := &Downloader{
  168. mode: mode,
  169. stateDB: stateDb,
  170. mux: mux,
  171. queue: newQueue(),
  172. peers: newPeerSet(),
  173. rttEstimate: uint64(rttMaxEstimate),
  174. rttConfidence: uint64(1000000),
  175. blockchain: chain,
  176. lightchain: lightchain,
  177. dropPeer: dropPeer,
  178. headerCh: make(chan dataPack, 1),
  179. bodyCh: make(chan dataPack, 1),
  180. receiptCh: make(chan dataPack, 1),
  181. bodyWakeCh: make(chan bool, 1),
  182. receiptWakeCh: make(chan bool, 1),
  183. headerProcCh: make(chan []*types.Header, 1),
  184. quitCh: make(chan struct{}),
  185. stateCh: make(chan dataPack),
  186. stateSyncStart: make(chan *stateSync),
  187. trackStateReq: make(chan *stateReq),
  188. }
  189. go dl.qosTuner()
  190. go dl.stateFetcher()
  191. return dl
  192. }
  193. // Progress retrieves the synchronisation boundaries, specifically the origin
  194. // block where synchronisation started at (may have failed/suspended); the block
  195. // or header sync is currently at; and the latest known block which the sync targets.
  196. //
  197. // In addition, during the state download phase of fast synchronisation the number
  198. // of processed and the total number of known states are also returned. Otherwise
  199. // these are zero.
  200. func (d *Downloader) Progress() ethereum.SyncProgress {
  201. // Lock the current stats and return the progress
  202. d.syncStatsLock.RLock()
  203. defer d.syncStatsLock.RUnlock()
  204. current := uint64(0)
  205. switch d.mode {
  206. case FullSync:
  207. current = d.blockchain.CurrentBlock().NumberU64()
  208. case FastSync:
  209. current = d.blockchain.CurrentFastBlock().NumberU64()
  210. case LightSync:
  211. current = d.lightchain.CurrentHeader().Number.Uint64()
  212. }
  213. return ethereum.SyncProgress{
  214. StartingBlock: d.syncStatsChainOrigin,
  215. CurrentBlock: current,
  216. HighestBlock: d.syncStatsChainHeight,
  217. PulledStates: d.syncStatsState.processed,
  218. KnownStates: d.syncStatsState.processed + d.syncStatsState.pending,
  219. }
  220. }
  221. // Synchronising returns whether the downloader is currently retrieving blocks.
  222. func (d *Downloader) Synchronising() bool {
  223. return atomic.LoadInt32(&d.synchronising) > 0
  224. }
  225. // RegisterPeer injects a new download peer into the set of block source to be
  226. // used for fetching hashes and blocks from.
  227. func (d *Downloader) RegisterPeer(id string, version int, peer Peer) error {
  228. logger := log.New("peer", id)
  229. logger.Trace("Registering sync peer")
  230. if err := d.peers.Register(newPeerConnection(id, version, peer, logger)); err != nil {
  231. logger.Error("Failed to register sync peer", "err", err)
  232. return err
  233. }
  234. d.qosReduceConfidence()
  235. return nil
  236. }
  237. // RegisterLightPeer injects a light client peer, wrapping it so it appears as a regular peer.
  238. func (d *Downloader) RegisterLightPeer(id string, version int, peer LightPeer) error {
  239. return d.RegisterPeer(id, version, &lightPeerWrapper{peer})
  240. }
  241. // UnregisterPeer remove a peer from the known list, preventing any action from
  242. // the specified peer. An effort is also made to return any pending fetches into
  243. // the queue.
  244. func (d *Downloader) UnregisterPeer(id string) error {
  245. // Unregister the peer from the active peer set and revoke any fetch tasks
  246. logger := log.New("peer", id)
  247. logger.Trace("Unregistering sync peer")
  248. if err := d.peers.Unregister(id); err != nil {
  249. logger.Error("Failed to unregister sync peer", "err", err)
  250. return err
  251. }
  252. d.queue.Revoke(id)
  253. // If this peer was the master peer, abort sync immediately
  254. d.cancelLock.RLock()
  255. master := id == d.cancelPeer
  256. d.cancelLock.RUnlock()
  257. if master {
  258. d.Cancel()
  259. }
  260. return nil
  261. }
  262. // Synchronise tries to sync up our local block chain with a remote peer, both
  263. // adding various sanity checks as well as wrapping it with various log entries.
  264. func (d *Downloader) Synchronise(id string, head common.Hash, td *big.Int, mode SyncMode) error {
  265. err := d.synchronise(id, head, td, mode)
  266. switch err {
  267. case nil:
  268. case errBusy:
  269. case errTimeout, errBadPeer, errStallingPeer,
  270. errEmptyHeaderSet, errPeersUnavailable, errTooOld,
  271. errInvalidAncestor, errInvalidChain:
  272. log.Warn("Synchronisation failed, dropping peer", "peer", id, "err", err)
  273. if d.dropPeer == nil {
  274. // The dropPeer method is nil when `--copydb` is used for a local copy.
  275. // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
  276. log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", id)
  277. } else {
  278. d.dropPeer(id)
  279. }
  280. default:
  281. log.Warn("Synchronisation failed, retrying", "err", err)
  282. }
  283. return err
  284. }
  285. // synchronise will select the peer and use it for synchronising. If an empty string is given
  286. // it will use the best peer possible and synchronize if its TD is higher than our own. If any of the
  287. // checks fail an error will be returned. This method is synchronous
  288. func (d *Downloader) synchronise(id string, hash common.Hash, td *big.Int, mode SyncMode) error {
  289. // Mock out the synchronisation if testing
  290. if d.synchroniseMock != nil {
  291. return d.synchroniseMock(id, hash)
  292. }
  293. // Make sure only one goroutine is ever allowed past this point at once
  294. if !atomic.CompareAndSwapInt32(&d.synchronising, 0, 1) {
  295. return errBusy
  296. }
  297. defer atomic.StoreInt32(&d.synchronising, 0)
  298. // Post a user notification of the sync (only once per session)
  299. if atomic.CompareAndSwapInt32(&d.notified, 0, 1) {
  300. log.Info("Block synchronisation started")
  301. }
  302. // Reset the queue, peer set and wake channels to clean any internal leftover state
  303. d.queue.Reset()
  304. d.peers.Reset()
  305. for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  306. select {
  307. case <-ch:
  308. default:
  309. }
  310. }
  311. for _, ch := range []chan dataPack{d.headerCh, d.bodyCh, d.receiptCh} {
  312. for empty := false; !empty; {
  313. select {
  314. case <-ch:
  315. default:
  316. empty = true
  317. }
  318. }
  319. }
  320. for empty := false; !empty; {
  321. select {
  322. case <-d.headerProcCh:
  323. default:
  324. empty = true
  325. }
  326. }
  327. // Create cancel channel for aborting mid-flight and mark the master peer
  328. d.cancelLock.Lock()
  329. d.cancelCh = make(chan struct{})
  330. d.cancelPeer = id
  331. d.cancelLock.Unlock()
  332. defer d.Cancel() // No matter what, we can't leave the cancel channel open
  333. // Set the requested sync mode, unless it's forbidden
  334. d.mode = mode
  335. // Retrieve the origin peer and initiate the downloading process
  336. p := d.peers.Peer(id)
  337. if p == nil {
  338. return errUnknownPeer
  339. }
  340. return d.syncWithPeer(p, hash, td)
  341. }
  342. // syncWithPeer starts a block synchronization based on the hash chain from the
  343. // specified peer and head hash.
  344. func (d *Downloader) syncWithPeer(p *peerConnection, hash common.Hash, td *big.Int) (err error) {
  345. d.mux.Post(StartEvent{})
  346. defer func() {
  347. // reset on error
  348. if err != nil {
  349. d.mux.Post(FailedEvent{err})
  350. } else {
  351. d.mux.Post(DoneEvent{})
  352. }
  353. }()
  354. if p.version < 62 {
  355. return errTooOld
  356. }
  357. log.Debug("Synchronising with the network", "peer", p.id, "eth", p.version, "head", hash, "td", td, "mode", d.mode)
  358. defer func(start time.Time) {
  359. log.Debug("Synchronisation terminated", "elapsed", time.Since(start))
  360. }(time.Now())
  361. // Look up the sync boundaries: the common ancestor and the target block
  362. latest, err := d.fetchHeight(p)
  363. if err != nil {
  364. return err
  365. }
  366. height := latest.Number.Uint64()
  367. origin, err := d.findAncestor(p, height)
  368. if err != nil {
  369. return err
  370. }
  371. d.syncStatsLock.Lock()
  372. if d.syncStatsChainHeight <= origin || d.syncStatsChainOrigin > origin {
  373. d.syncStatsChainOrigin = origin
  374. }
  375. d.syncStatsChainHeight = height
  376. d.syncStatsLock.Unlock()
  377. // Ensure our origin point is below any fast sync pivot point
  378. pivot := uint64(0)
  379. if d.mode == FastSync {
  380. if height <= uint64(fsMinFullBlocks) {
  381. origin = 0
  382. } else {
  383. pivot = height - uint64(fsMinFullBlocks)
  384. if pivot <= origin {
  385. origin = pivot - 1
  386. }
  387. }
  388. }
  389. d.committed = 1
  390. if d.mode == FastSync && pivot != 0 {
  391. d.committed = 0
  392. }
  393. // Initiate the sync using a concurrent header and content retrieval algorithm
  394. d.queue.Prepare(origin+1, d.mode)
  395. if d.syncInitHook != nil {
  396. d.syncInitHook(origin, height)
  397. }
  398. fetchers := []func() error{
  399. func() error { return d.fetchHeaders(p, origin+1, pivot) }, // Headers are always retrieved
  400. func() error { return d.fetchBodies(origin + 1) }, // Bodies are retrieved during normal and fast sync
  401. func() error { return d.fetchReceipts(origin + 1) }, // Receipts are retrieved during fast sync
  402. func() error { return d.processHeaders(origin+1, pivot, td) },
  403. }
  404. if d.mode == FastSync {
  405. fetchers = append(fetchers, func() error { return d.processFastSyncContent(latest) })
  406. } else if d.mode == FullSync {
  407. fetchers = append(fetchers, d.processFullSyncContent)
  408. }
  409. return d.spawnSync(fetchers)
  410. }
  411. // spawnSync runs d.process and all given fetcher functions to completion in
  412. // separate goroutines, returning the first error that appears.
  413. func (d *Downloader) spawnSync(fetchers []func() error) error {
  414. var wg sync.WaitGroup
  415. errc := make(chan error, len(fetchers))
  416. wg.Add(len(fetchers))
  417. for _, fn := range fetchers {
  418. fn := fn
  419. go func() { defer wg.Done(); errc <- fn() }()
  420. }
  421. // Wait for the first error, then terminate the others.
  422. var err error
  423. for i := 0; i < len(fetchers); i++ {
  424. if i == len(fetchers)-1 {
  425. // Close the queue when all fetchers have exited.
  426. // This will cause the block processor to end when
  427. // it has processed the queue.
  428. d.queue.Close()
  429. }
  430. if err = <-errc; err != nil {
  431. break
  432. }
  433. }
  434. d.queue.Close()
  435. d.Cancel()
  436. wg.Wait()
  437. return err
  438. }
  439. // Cancel cancels all of the operations and resets the queue. It returns true
  440. // if the cancel operation was completed.
  441. func (d *Downloader) Cancel() {
  442. // Close the current cancel channel
  443. d.cancelLock.Lock()
  444. if d.cancelCh != nil {
  445. select {
  446. case <-d.cancelCh:
  447. // Channel was already closed
  448. default:
  449. close(d.cancelCh)
  450. }
  451. }
  452. d.cancelLock.Unlock()
  453. }
  454. // Terminate interrupts the downloader, canceling all pending operations.
  455. // The downloader cannot be reused after calling Terminate.
  456. func (d *Downloader) Terminate() {
  457. // Close the termination channel (make sure double close is allowed)
  458. d.quitLock.Lock()
  459. select {
  460. case <-d.quitCh:
  461. default:
  462. close(d.quitCh)
  463. }
  464. d.quitLock.Unlock()
  465. // Cancel any pending download requests
  466. d.Cancel()
  467. }
  468. // fetchHeight retrieves the head header of the remote peer to aid in estimating
  469. // the total time a pending synchronisation would take.
  470. func (d *Downloader) fetchHeight(p *peerConnection) (*types.Header, error) {
  471. p.log.Debug("Retrieving remote chain height")
  472. // Request the advertised remote head block and wait for the response
  473. head, _ := p.peer.Head()
  474. go p.peer.RequestHeadersByHash(head, 1, 0, false)
  475. ttl := d.requestTTL()
  476. timeout := time.After(ttl)
  477. for {
  478. select {
  479. case <-d.cancelCh:
  480. return nil, errCancelBlockFetch
  481. case packet := <-d.headerCh:
  482. // Discard anything not from the origin peer
  483. if packet.PeerId() != p.id {
  484. log.Debug("Received headers from incorrect peer", "peer", packet.PeerId())
  485. break
  486. }
  487. // Make sure the peer actually gave something valid
  488. headers := packet.(*headerPack).headers
  489. if len(headers) != 1 {
  490. p.log.Debug("Multiple headers for single request", "headers", len(headers))
  491. return nil, errBadPeer
  492. }
  493. head := headers[0]
  494. p.log.Debug("Remote head header identified", "number", head.Number, "hash", head.Hash())
  495. return head, nil
  496. case <-timeout:
  497. p.log.Debug("Waiting for head header timed out", "elapsed", ttl)
  498. return nil, errTimeout
  499. case <-d.bodyCh:
  500. case <-d.receiptCh:
  501. // Out of bounds delivery, ignore
  502. }
  503. }
  504. }
  505. // findAncestor tries to locate the common ancestor link of the local chain and
  506. // a remote peers blockchain. In the general case when our node was in sync and
  507. // on the correct chain, checking the top N links should already get us a match.
  508. // In the rare scenario when we ended up on a long reorganisation (i.e. none of
  509. // the head links match), we do a binary search to find the common ancestor.
  510. func (d *Downloader) findAncestor(p *peerConnection, height uint64) (uint64, error) {
  511. // Figure out the valid ancestor range to prevent rewrite attacks
  512. floor, ceil := int64(-1), d.lightchain.CurrentHeader().Number.Uint64()
  513. if d.mode == FullSync {
  514. ceil = d.blockchain.CurrentBlock().NumberU64()
  515. } else if d.mode == FastSync {
  516. ceil = d.blockchain.CurrentFastBlock().NumberU64()
  517. }
  518. if ceil >= MaxForkAncestry {
  519. floor = int64(ceil - MaxForkAncestry)
  520. }
  521. p.log.Debug("Looking for common ancestor", "local", ceil, "remote", height)
  522. // Request the topmost blocks to short circuit binary ancestor lookup
  523. head := ceil
  524. if head > height {
  525. head = height
  526. }
  527. from := int64(head) - int64(MaxHeaderFetch)
  528. if from < 0 {
  529. from = 0
  530. }
  531. // Span out with 15 block gaps into the future to catch bad head reports
  532. limit := 2 * MaxHeaderFetch / 16
  533. count := 1 + int((int64(ceil)-from)/16)
  534. if count > limit {
  535. count = limit
  536. }
  537. go p.peer.RequestHeadersByNumber(uint64(from), count, 15, false)
  538. // Wait for the remote response to the head fetch
  539. number, hash := uint64(0), common.Hash{}
  540. ttl := d.requestTTL()
  541. timeout := time.After(ttl)
  542. for finished := false; !finished; {
  543. select {
  544. case <-d.cancelCh:
  545. return 0, errCancelHeaderFetch
  546. case packet := <-d.headerCh:
  547. // Discard anything not from the origin peer
  548. if packet.PeerId() != p.id {
  549. log.Debug("Received headers from incorrect peer", "peer", packet.PeerId())
  550. break
  551. }
  552. // Make sure the peer actually gave something valid
  553. headers := packet.(*headerPack).headers
  554. if len(headers) == 0 {
  555. p.log.Warn("Empty head header set")
  556. return 0, errEmptyHeaderSet
  557. }
  558. // Make sure the peer's reply conforms to the request
  559. for i := 0; i < len(headers); i++ {
  560. if number := headers[i].Number.Int64(); number != from+int64(i)*16 {
  561. p.log.Warn("Head headers broke chain ordering", "index", i, "requested", from+int64(i)*16, "received", number)
  562. return 0, errInvalidChain
  563. }
  564. }
  565. // Check if a common ancestor was found
  566. finished = true
  567. for i := len(headers) - 1; i >= 0; i-- {
  568. // Skip any headers that underflow/overflow our requested set
  569. if headers[i].Number.Int64() < from || headers[i].Number.Uint64() > ceil {
  570. continue
  571. }
  572. // Otherwise check if we already know the header or not
  573. if (d.mode == FullSync && d.blockchain.HasBlock(headers[i].Hash(), headers[i].Number.Uint64())) || (d.mode != FullSync && d.lightchain.HasHeader(headers[i].Hash(), headers[i].Number.Uint64())) {
  574. number, hash = headers[i].Number.Uint64(), headers[i].Hash()
  575. // If every header is known, even future ones, the peer straight out lied about its head
  576. if number > height && i == limit-1 {
  577. p.log.Warn("Lied about chain head", "reported", height, "found", number)
  578. return 0, errStallingPeer
  579. }
  580. break
  581. }
  582. }
  583. case <-timeout:
  584. p.log.Debug("Waiting for head header timed out", "elapsed", ttl)
  585. return 0, errTimeout
  586. case <-d.bodyCh:
  587. case <-d.receiptCh:
  588. // Out of bounds delivery, ignore
  589. }
  590. }
  591. // If the head fetch already found an ancestor, return
  592. if !common.EmptyHash(hash) {
  593. if int64(number) <= floor {
  594. p.log.Warn("Ancestor below allowance", "number", number, "hash", hash, "allowance", floor)
  595. return 0, errInvalidAncestor
  596. }
  597. p.log.Debug("Found common ancestor", "number", number, "hash", hash)
  598. return number, nil
  599. }
  600. // Ancestor not found, we need to binary search over our chain
  601. start, end := uint64(0), head
  602. if floor > 0 {
  603. start = uint64(floor)
  604. }
  605. for start+1 < end {
  606. // Split our chain interval in two, and request the hash to cross check
  607. check := (start + end) / 2
  608. ttl := d.requestTTL()
  609. timeout := time.After(ttl)
  610. go p.peer.RequestHeadersByNumber(check, 1, 0, false)
  611. // Wait until a reply arrives to this request
  612. for arrived := false; !arrived; {
  613. select {
  614. case <-d.cancelCh:
  615. return 0, errCancelHeaderFetch
  616. case packer := <-d.headerCh:
  617. // Discard anything not from the origin peer
  618. if packer.PeerId() != p.id {
  619. log.Debug("Received headers from incorrect peer", "peer", packer.PeerId())
  620. break
  621. }
  622. // Make sure the peer actually gave something valid
  623. headers := packer.(*headerPack).headers
  624. if len(headers) != 1 {
  625. p.log.Debug("Multiple headers for single request", "headers", len(headers))
  626. return 0, errBadPeer
  627. }
  628. arrived = true
  629. // Modify the search interval based on the response
  630. if (d.mode == FullSync && !d.blockchain.HasBlock(headers[0].Hash(), headers[0].Number.Uint64())) || (d.mode != FullSync && !d.lightchain.HasHeader(headers[0].Hash(), headers[0].Number.Uint64())) {
  631. end = check
  632. break
  633. }
  634. header := d.lightchain.GetHeaderByHash(headers[0].Hash()) // Independent of sync mode, header surely exists
  635. if header.Number.Uint64() != check {
  636. p.log.Debug("Received non requested header", "number", header.Number, "hash", header.Hash(), "request", check)
  637. return 0, errBadPeer
  638. }
  639. start = check
  640. case <-timeout:
  641. p.log.Debug("Waiting for search header timed out", "elapsed", ttl)
  642. return 0, errTimeout
  643. case <-d.bodyCh:
  644. case <-d.receiptCh:
  645. // Out of bounds delivery, ignore
  646. }
  647. }
  648. }
  649. // Ensure valid ancestry and return
  650. if int64(start) <= floor {
  651. p.log.Warn("Ancestor below allowance", "number", start, "hash", hash, "allowance", floor)
  652. return 0, errInvalidAncestor
  653. }
  654. p.log.Debug("Found common ancestor", "number", start, "hash", hash)
  655. return start, nil
  656. }
  657. // fetchHeaders keeps retrieving headers concurrently from the number
  658. // requested, until no more are returned, potentially throttling on the way. To
  659. // facilitate concurrency but still protect against malicious nodes sending bad
  660. // headers, we construct a header chain skeleton using the "origin" peer we are
  661. // syncing with, and fill in the missing headers using anyone else. Headers from
  662. // other peers are only accepted if they map cleanly to the skeleton. If no one
  663. // can fill in the skeleton - not even the origin peer - it's assumed invalid and
  664. // the origin is dropped.
  665. func (d *Downloader) fetchHeaders(p *peerConnection, from uint64, pivot uint64) error {
  666. p.log.Debug("Directing header downloads", "origin", from)
  667. defer p.log.Debug("Header download terminated")
  668. // Create a timeout timer, and the associated header fetcher
  669. skeleton := true // Skeleton assembly phase or finishing up
  670. request := time.Now() // time of the last skeleton fetch request
  671. timeout := time.NewTimer(0) // timer to dump a non-responsive active peer
  672. <-timeout.C // timeout channel should be initially empty
  673. defer timeout.Stop()
  674. var ttl time.Duration
  675. getHeaders := func(from uint64) {
  676. request = time.Now()
  677. ttl = d.requestTTL()
  678. timeout.Reset(ttl)
  679. if skeleton {
  680. p.log.Trace("Fetching skeleton headers", "count", MaxHeaderFetch, "from", from)
  681. go p.peer.RequestHeadersByNumber(from+uint64(MaxHeaderFetch)-1, MaxSkeletonSize, MaxHeaderFetch-1, false)
  682. } else {
  683. p.log.Trace("Fetching full headers", "count", MaxHeaderFetch, "from", from)
  684. go p.peer.RequestHeadersByNumber(from, MaxHeaderFetch, 0, false)
  685. }
  686. }
  687. // Start pulling the header chain skeleton until all is done
  688. getHeaders(from)
  689. for {
  690. select {
  691. case <-d.cancelCh:
  692. return errCancelHeaderFetch
  693. case packet := <-d.headerCh:
  694. // Make sure the active peer is giving us the skeleton headers
  695. if packet.PeerId() != p.id {
  696. log.Debug("Received skeleton from incorrect peer", "peer", packet.PeerId())
  697. break
  698. }
  699. headerReqTimer.UpdateSince(request)
  700. timeout.Stop()
  701. // If the skeleton's finished, pull any remaining head headers directly from the origin
  702. if packet.Items() == 0 && skeleton {
  703. skeleton = false
  704. getHeaders(from)
  705. continue
  706. }
  707. // If no more headers are inbound, notify the content fetchers and return
  708. if packet.Items() == 0 {
  709. // Don't abort header fetches while the pivot is downloading
  710. if atomic.LoadInt32(&d.committed) == 0 && pivot <= from {
  711. p.log.Debug("No headers, waiting for pivot commit")
  712. select {
  713. case <-time.After(fsHeaderContCheck):
  714. getHeaders(from)
  715. continue
  716. case <-d.cancelCh:
  717. return errCancelHeaderFetch
  718. }
  719. }
  720. // Pivot done (or not in fast sync) and no more headers, terminate the process
  721. p.log.Debug("No more headers available")
  722. select {
  723. case d.headerProcCh <- nil:
  724. return nil
  725. case <-d.cancelCh:
  726. return errCancelHeaderFetch
  727. }
  728. }
  729. headers := packet.(*headerPack).headers
  730. // If we received a skeleton batch, resolve internals concurrently
  731. if skeleton {
  732. filled, proced, err := d.fillHeaderSkeleton(from, headers)
  733. if err != nil {
  734. p.log.Debug("Skeleton chain invalid", "err", err)
  735. return errInvalidChain
  736. }
  737. headers = filled[proced:]
  738. from += uint64(proced)
  739. }
  740. // Insert all the new headers and fetch the next batch
  741. if len(headers) > 0 {
  742. p.log.Trace("Scheduling new headers", "count", len(headers), "from", from)
  743. select {
  744. case d.headerProcCh <- headers:
  745. case <-d.cancelCh:
  746. return errCancelHeaderFetch
  747. }
  748. from += uint64(len(headers))
  749. }
  750. getHeaders(from)
  751. case <-timeout.C:
  752. if d.dropPeer == nil {
  753. // The dropPeer method is nil when `--copydb` is used for a local copy.
  754. // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
  755. p.log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", p.id)
  756. break
  757. }
  758. // Header retrieval timed out, consider the peer bad and drop
  759. p.log.Debug("Header request timed out", "elapsed", ttl)
  760. headerTimeoutMeter.Mark(1)
  761. d.dropPeer(p.id)
  762. // Finish the sync gracefully instead of dumping the gathered data though
  763. for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  764. select {
  765. case ch <- false:
  766. case <-d.cancelCh:
  767. }
  768. }
  769. select {
  770. case d.headerProcCh <- nil:
  771. case <-d.cancelCh:
  772. }
  773. return errBadPeer
  774. }
  775. }
  776. }
  777. // fillHeaderSkeleton concurrently retrieves headers from all our available peers
  778. // and maps them to the provided skeleton header chain.
  779. //
  780. // Any partial results from the beginning of the skeleton is (if possible) forwarded
  781. // immediately to the header processor to keep the rest of the pipeline full even
  782. // in the case of header stalls.
  783. //
  784. // The method returs the entire filled skeleton and also the number of headers
  785. // already forwarded for processing.
  786. func (d *Downloader) fillHeaderSkeleton(from uint64, skeleton []*types.Header) ([]*types.Header, int, error) {
  787. log.Debug("Filling up skeleton", "from", from)
  788. d.queue.ScheduleSkeleton(from, skeleton)
  789. var (
  790. deliver = func(packet dataPack) (int, error) {
  791. pack := packet.(*headerPack)
  792. return d.queue.DeliverHeaders(pack.peerId, pack.headers, d.headerProcCh)
  793. }
  794. expire = func() map[string]int { return d.queue.ExpireHeaders(d.requestTTL()) }
  795. throttle = func() bool { return false }
  796. reserve = func(p *peerConnection, count int) (*fetchRequest, bool, error) {
  797. return d.queue.ReserveHeaders(p, count), false, nil
  798. }
  799. fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchHeaders(req.From, MaxHeaderFetch) }
  800. capacity = func(p *peerConnection) int { return p.HeaderCapacity(d.requestRTT()) }
  801. setIdle = func(p *peerConnection, accepted int) { p.SetHeadersIdle(accepted) }
  802. )
  803. err := d.fetchParts(errCancelHeaderFetch, d.headerCh, deliver, d.queue.headerContCh, expire,
  804. d.queue.PendingHeaders, d.queue.InFlightHeaders, throttle, reserve,
  805. nil, fetch, d.queue.CancelHeaders, capacity, d.peers.HeaderIdlePeers, setIdle, "headers")
  806. log.Debug("Skeleton fill terminated", "err", err)
  807. filled, proced := d.queue.RetrieveHeaders()
  808. return filled, proced, err
  809. }
  810. // fetchBodies iteratively downloads the scheduled block bodies, taking any
  811. // available peers, reserving a chunk of blocks for each, waiting for delivery
  812. // and also periodically checking for timeouts.
  813. func (d *Downloader) fetchBodies(from uint64) error {
  814. log.Debug("Downloading block bodies", "origin", from)
  815. var (
  816. deliver = func(packet dataPack) (int, error) {
  817. pack := packet.(*bodyPack)
  818. return d.queue.DeliverBodies(pack.peerId, pack.transactions, pack.uncles)
  819. }
  820. expire = func() map[string]int { return d.queue.ExpireBodies(d.requestTTL()) }
  821. fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchBodies(req) }
  822. capacity = func(p *peerConnection) int { return p.BlockCapacity(d.requestRTT()) }
  823. setIdle = func(p *peerConnection, accepted int) { p.SetBodiesIdle(accepted) }
  824. )
  825. err := d.fetchParts(errCancelBodyFetch, d.bodyCh, deliver, d.bodyWakeCh, expire,
  826. d.queue.PendingBlocks, d.queue.InFlightBlocks, d.queue.ShouldThrottleBlocks, d.queue.ReserveBodies,
  827. d.bodyFetchHook, fetch, d.queue.CancelBodies, capacity, d.peers.BodyIdlePeers, setIdle, "bodies")
  828. log.Debug("Block body download terminated", "err", err)
  829. return err
  830. }
  831. // fetchReceipts iteratively downloads the scheduled block receipts, taking any
  832. // available peers, reserving a chunk of receipts for each, waiting for delivery
  833. // and also periodically checking for timeouts.
  834. func (d *Downloader) fetchReceipts(from uint64) error {
  835. log.Debug("Downloading transaction receipts", "origin", from)
  836. var (
  837. deliver = func(packet dataPack) (int, error) {
  838. pack := packet.(*receiptPack)
  839. return d.queue.DeliverReceipts(pack.peerId, pack.receipts)
  840. }
  841. expire = func() map[string]int { return d.queue.ExpireReceipts(d.requestTTL()) }
  842. fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchReceipts(req) }
  843. capacity = func(p *peerConnection) int { return p.ReceiptCapacity(d.requestRTT()) }
  844. setIdle = func(p *peerConnection, accepted int) { p.SetReceiptsIdle(accepted) }
  845. )
  846. err := d.fetchParts(errCancelReceiptFetch, d.receiptCh, deliver, d.receiptWakeCh, expire,
  847. d.queue.PendingReceipts, d.queue.InFlightReceipts, d.queue.ShouldThrottleReceipts, d.queue.ReserveReceipts,
  848. d.receiptFetchHook, fetch, d.queue.CancelReceipts, capacity, d.peers.ReceiptIdlePeers, setIdle, "receipts")
  849. log.Debug("Transaction receipt download terminated", "err", err)
  850. return err
  851. }
  852. // fetchParts iteratively downloads scheduled block parts, taking any available
  853. // peers, reserving a chunk of fetch requests for each, waiting for delivery and
  854. // also periodically checking for timeouts.
  855. //
  856. // As the scheduling/timeout logic mostly is the same for all downloaded data
  857. // types, this method is used by each for data gathering and is instrumented with
  858. // various callbacks to handle the slight differences between processing them.
  859. //
  860. // The instrumentation parameters:
  861. // - errCancel: error type to return if the fetch operation is cancelled (mostly makes logging nicer)
  862. // - deliveryCh: channel from which to retrieve downloaded data packets (merged from all concurrent peers)
  863. // - deliver: processing callback to deliver data packets into type specific download queues (usually within `queue`)
  864. // - wakeCh: notification channel for waking the fetcher when new tasks are available (or sync completed)
  865. // - expire: task callback method to abort requests that took too long and return the faulty peers (traffic shaping)
  866. // - pending: task callback for the number of requests still needing download (detect completion/non-completability)
  867. // - inFlight: task callback for the number of in-progress requests (wait for all active downloads to finish)
  868. // - throttle: task callback to check if the processing queue is full and activate throttling (bound memory use)
  869. // - reserve: task callback to reserve new download tasks to a particular peer (also signals partial completions)
  870. // - fetchHook: tester callback to notify of new tasks being initiated (allows testing the scheduling logic)
  871. // - fetch: network callback to actually send a particular download request to a physical remote peer
  872. // - cancel: task callback to abort an in-flight download request and allow rescheduling it (in case of lost peer)
  873. // - capacity: network callback to retrieve the estimated type-specific bandwidth capacity of a peer (traffic shaping)
  874. // - idle: network callback to retrieve the currently (type specific) idle peers that can be assigned tasks
  875. // - setIdle: network callback to set a peer back to idle and update its estimated capacity (traffic shaping)
  876. // - kind: textual label of the type being downloaded to display in log mesages
  877. func (d *Downloader) fetchParts(errCancel error, deliveryCh chan dataPack, deliver func(dataPack) (int, error), wakeCh chan bool,
  878. expire func() map[string]int, pending func() int, inFlight func() bool, throttle func() bool, reserve func(*peerConnection, int) (*fetchRequest, bool, error),
  879. fetchHook func([]*types.Header), fetch func(*peerConnection, *fetchRequest) error, cancel func(*fetchRequest), capacity func(*peerConnection) int,
  880. idle func() ([]*peerConnection, int), setIdle func(*peerConnection, int), kind string) error {
  881. // Create a ticker to detect expired retrieval tasks
  882. ticker := time.NewTicker(100 * time.Millisecond)
  883. defer ticker.Stop()
  884. update := make(chan struct{}, 1)
  885. // Prepare the queue and fetch block parts until the block header fetcher's done
  886. finished := false
  887. for {
  888. select {
  889. case <-d.cancelCh:
  890. return errCancel
  891. case packet := <-deliveryCh:
  892. // If the peer was previously banned and failed to deliver its pack
  893. // in a reasonable time frame, ignore its message.
  894. if peer := d.peers.Peer(packet.PeerId()); peer != nil {
  895. // Deliver the received chunk of data and check chain validity
  896. accepted, err := deliver(packet)
  897. if err == errInvalidChain {
  898. return err
  899. }
  900. // Unless a peer delivered something completely else than requested (usually
  901. // caused by a timed out request which came through in the end), set it to
  902. // idle. If the delivery's stale, the peer should have already been idled.
  903. if err != errStaleDelivery {
  904. setIdle(peer, accepted)
  905. }
  906. // Issue a log to the user to see what's going on
  907. switch {
  908. case err == nil && packet.Items() == 0:
  909. peer.log.Trace("Requested data not delivered", "type", kind)
  910. case err == nil:
  911. peer.log.Trace("Delivered new batch of data", "type", kind, "count", packet.Stats())
  912. default:
  913. peer.log.Trace("Failed to deliver retrieved data", "type", kind, "err", err)
  914. }
  915. }
  916. // Blocks assembled, try to update the progress
  917. select {
  918. case update <- struct{}{}:
  919. default:
  920. }
  921. case cont := <-wakeCh:
  922. // The header fetcher sent a continuation flag, check if it's done
  923. if !cont {
  924. finished = true
  925. }
  926. // Headers arrive, try to update the progress
  927. select {
  928. case update <- struct{}{}:
  929. default:
  930. }
  931. case <-ticker.C:
  932. // Sanity check update the progress
  933. select {
  934. case update <- struct{}{}:
  935. default:
  936. }
  937. case <-update:
  938. // Short circuit if we lost all our peers
  939. if d.peers.Len() == 0 {
  940. return errNoPeers
  941. }
  942. // Check for fetch request timeouts and demote the responsible peers
  943. for pid, fails := range expire() {
  944. if peer := d.peers.Peer(pid); peer != nil {
  945. // If a lot of retrieval elements expired, we might have overestimated the remote peer or perhaps
  946. // ourselves. Only reset to minimal throughput but don't drop just yet. If even the minimal times
  947. // out that sync wise we need to get rid of the peer.
  948. //
  949. // The reason the minimum threshold is 2 is because the downloader tries to estimate the bandwidth
  950. // and latency of a peer separately, which requires pushing the measures capacity a bit and seeing
  951. // how response times reacts, to it always requests one more than the minimum (i.e. min 2).
  952. if fails > 2 {
  953. peer.log.Trace("Data delivery timed out", "type", kind)
  954. setIdle(peer, 0)
  955. } else {
  956. peer.log.Debug("Stalling delivery, dropping", "type", kind)
  957. if d.dropPeer == nil {
  958. // The dropPeer method is nil when `--copydb` is used for a local copy.
  959. // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
  960. peer.log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", pid)
  961. } else {
  962. d.dropPeer(pid)
  963. }
  964. }
  965. }
  966. }
  967. // If there's nothing more to fetch, wait or terminate
  968. if pending() == 0 {
  969. if !inFlight() && finished {
  970. log.Debug("Data fetching completed", "type", kind)
  971. return nil
  972. }
  973. break
  974. }
  975. // Send a download request to all idle peers, until throttled
  976. progressed, throttled, running := false, false, inFlight()
  977. idles, total := idle()
  978. for _, peer := range idles {
  979. // Short circuit if throttling activated
  980. if throttle() {
  981. throttled = true
  982. break
  983. }
  984. // Short circuit if there is no more available task.
  985. if pending() == 0 {
  986. break
  987. }
  988. // Reserve a chunk of fetches for a peer. A nil can mean either that
  989. // no more headers are available, or that the peer is known not to
  990. // have them.
  991. request, progress, err := reserve(peer, capacity(peer))
  992. if err != nil {
  993. return err
  994. }
  995. if progress {
  996. progressed = true
  997. }
  998. if request == nil {
  999. continue
  1000. }
  1001. if request.From > 0 {
  1002. peer.log.Trace("Requesting new batch of data", "type", kind, "from", request.From)
  1003. } else {
  1004. peer.log.Trace("Requesting new batch of data", "type", kind, "count", len(request.Headers), "from", request.Headers[0].Number)
  1005. }
  1006. // Fetch the chunk and make sure any errors return the hashes to the queue
  1007. if fetchHook != nil {
  1008. fetchHook(request.Headers)
  1009. }
  1010. if err := fetch(peer, request); err != nil {
  1011. // Although we could try and make an attempt to fix this, this error really
  1012. // means that we've double allocated a fetch task to a peer. If that is the
  1013. // case, the internal state of the downloader and the queue is very wrong so
  1014. // better hard crash and note the error instead of silently accumulating into
  1015. // a much bigger issue.
  1016. panic(fmt.Sprintf("%v: %s fetch assignment failed", peer, kind))
  1017. }
  1018. running = true
  1019. }
  1020. // Make sure that we have peers available for fetching. If all peers have been tried
  1021. // and all failed throw an error
  1022. if !progressed && !throttled && !running && len(idles) == total && pending() > 0 {
  1023. return errPeersUnavailable
  1024. }
  1025. }
  1026. }
  1027. }
  1028. // processHeaders takes batches of retrieved headers from an input channel and
  1029. // keeps processing and scheduling them into the header chain and downloader's
  1030. // queue until the stream ends or a failure occurs.
  1031. func (d *Downloader) processHeaders(origin uint64, pivot uint64, td *big.Int) error {
  1032. // Keep a count of uncertain headers to roll back
  1033. rollback := []*types.Header{}
  1034. defer func() {
  1035. if len(rollback) > 0 {
  1036. // Flatten the headers and roll them back
  1037. hashes := make([]common.Hash, len(rollback))
  1038. for i, header := range rollback {
  1039. hashes[i] = header.Hash()
  1040. }
  1041. lastHeader, lastFastBlock, lastBlock := d.lightchain.CurrentHeader().Number, common.Big0, common.Big0
  1042. if d.mode != LightSync {
  1043. lastFastBlock = d.blockchain.CurrentFastBlock().Number()
  1044. lastBlock = d.blockchain.CurrentBlock().Number()
  1045. }
  1046. d.lightchain.Rollback(hashes)
  1047. curFastBlock, curBlock := common.Big0, common.Big0
  1048. if d.mode != LightSync {
  1049. curFastBlock = d.blockchain.CurrentFastBlock().Number()
  1050. curBlock = d.blockchain.CurrentBlock().Number()
  1051. }
  1052. log.Warn("Rolled back headers", "count", len(hashes),
  1053. "header", fmt.Sprintf("%d->%d", lastHeader, d.lightchain.CurrentHeader().Number),
  1054. "fast", fmt.Sprintf("%d->%d", lastFastBlock, curFastBlock),
  1055. "block", fmt.Sprintf("%d->%d", lastBlock, curBlock))
  1056. }
  1057. }()
  1058. // Wait for batches of headers to process
  1059. gotHeaders := false
  1060. for {
  1061. select {
  1062. case <-d.cancelCh:
  1063. return errCancelHeaderProcessing
  1064. case headers := <-d.headerProcCh:
  1065. // Terminate header processing if we synced up
  1066. if len(headers) == 0 {
  1067. // Notify everyone that headers are fully processed
  1068. for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1069. select {
  1070. case ch <- false:
  1071. case <-d.cancelCh:
  1072. }
  1073. }
  1074. // If no headers were retrieved at all, the peer violated its TD promise that it had a
  1075. // better chain compared to ours. The only exception is if its promised blocks were
  1076. // already imported by other means (e.g. fecher):
  1077. //
  1078. // R <remote peer>, L <local node>: Both at block 10
  1079. // R: Mine block 11, and propagate it to L
  1080. // L: Queue block 11 for import
  1081. // L: Notice that R's head and TD increased compared to ours, start sync
  1082. // L: Import of block 11 finishes
  1083. // L: Sync begins, and finds common ancestor at 11
  1084. // L: Request new headers up from 11 (R's TD was higher, it must have something)
  1085. // R: Nothing to give
  1086. if d.mode != LightSync {
  1087. head := d.blockchain.CurrentBlock()
  1088. if !gotHeaders && td.Cmp(d.blockchain.GetTd(head.Hash(), head.NumberU64())) > 0 {
  1089. return errStallingPeer
  1090. }
  1091. }
  1092. // If fast or light syncing, ensure promised headers are indeed delivered. This is
  1093. // needed to detect scenarios where an attacker feeds a bad pivot and then bails out
  1094. // of delivering the post-pivot blocks that would flag the invalid content.
  1095. //
  1096. // This check cannot be executed "as is" for full imports, since blocks may still be
  1097. // queued for processing when the header download completes. However, as long as the
  1098. // peer gave us something useful, we're already happy/progressed (above check).
  1099. if d.mode == FastSync || d.mode == LightSync {
  1100. head := d.lightchain.CurrentHeader()
  1101. if td.Cmp(d.lightchain.GetTd(head.Hash(), head.Number.Uint64())) > 0 {
  1102. return errStallingPeer
  1103. }
  1104. }
  1105. // Disable any rollback and return
  1106. rollback = nil
  1107. return nil
  1108. }
  1109. // Otherwise split the chunk of headers into batches and process them
  1110. gotHeaders = true
  1111. for len(headers) > 0 {
  1112. // Terminate if something failed in between processing chunks
  1113. select {
  1114. case <-d.cancelCh:
  1115. return errCancelHeaderProcessing
  1116. default:
  1117. }
  1118. // Select the next chunk of headers to import
  1119. limit := maxHeadersProcess
  1120. if limit > len(headers) {
  1121. limit = len(headers)
  1122. }
  1123. chunk := headers[:limit]
  1124. // In case of header only syncing, validate the chunk immediately
  1125. if d.mode == FastSync || d.mode == LightSync {
  1126. // Collect the yet unknown headers to mark them as uncertain
  1127. unknown := make([]*types.Header, 0, len(headers))
  1128. for _, header := range chunk {
  1129. if !d.lightchain.HasHeader(header.Hash(), header.Number.Uint64()) {
  1130. unknown = append(unknown, header)
  1131. }
  1132. }
  1133. // If we're importing pure headers, verify based on their recentness
  1134. frequency := fsHeaderCheckFrequency
  1135. if chunk[len(chunk)-1].Number.Uint64()+uint64(fsHeaderForceVerify) > pivot {
  1136. frequency = 1
  1137. }
  1138. if n, err := d.lightchain.InsertHeaderChain(chunk, frequency); err != nil {
  1139. // If some headers were inserted, add them too to the rollback list
  1140. if n > 0 {
  1141. rollback = append(rollback, chunk[:n]...)
  1142. }
  1143. log.Debug("Invalid header encountered", "number", chunk[n].Number, "hash", chunk[n].Hash(), "err", err)
  1144. return errInvalidChain
  1145. }
  1146. // All verifications passed, store newly found uncertain headers
  1147. rollback = append(rollback, unknown...)
  1148. if len(rollback) > fsHeaderSafetyNet {
  1149. rollback = append(rollback[:0], rollback[len(rollback)-fsHeaderSafetyNet:]...)
  1150. }
  1151. }
  1152. // Unless we're doing light chains, schedule the headers for associated content retrieval
  1153. if d.mode == FullSync || d.mode == FastSync {
  1154. // If we've reached the allowed number of pending headers, stall a bit
  1155. for d.queue.PendingBlocks() >= maxQueuedHeaders || d.queue.PendingReceipts() >= maxQueuedHeaders {
  1156. select {
  1157. case <-d.cancelCh:
  1158. return errCancelHeaderProcessing
  1159. case <-time.After(time.Second):
  1160. }
  1161. }
  1162. // Otherwise insert the headers for content retrieval
  1163. inserts := d.queue.Schedule(chunk, origin)
  1164. if len(inserts) != len(chunk) {
  1165. log.Debug("Stale headers")
  1166. return errBadPeer
  1167. }
  1168. }
  1169. headers = headers[limit:]
  1170. origin += uint64(limit)
  1171. }
  1172. // Signal the content downloaders of the availablility of new tasks
  1173. for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1174. select {
  1175. case ch <- true:
  1176. default:
  1177. }
  1178. }
  1179. }
  1180. }
  1181. }
  1182. // processFullSyncContent takes fetch results from the queue and imports them into the chain.
  1183. func (d *Downloader) processFullSyncContent() error {
  1184. for {
  1185. results := d.queue.Results(true)
  1186. if len(results) == 0 {
  1187. return nil
  1188. }
  1189. if d.chainInsertHook != nil {
  1190. d.chainInsertHook(results)
  1191. }
  1192. if err := d.importBlockResults(results); err != nil {
  1193. return err
  1194. }
  1195. }
  1196. }
  1197. func (d *Downloader) importBlockResults(results []*fetchResult) error {
  1198. // Check for any early termination requests
  1199. if len(results) == 0 {
  1200. return nil
  1201. }
  1202. select {
  1203. case <-d.quitCh:
  1204. return errCancelContentProcessing
  1205. default:
  1206. }
  1207. // Retrieve the a batch of results to import
  1208. first, last := results[0].Header, results[len(results)-1].Header
  1209. log.Debug("Inserting downloaded chain", "items", len(results),
  1210. "firstnum", first.Number, "firsthash", first.Hash(),
  1211. "lastnum", last.Number, "lasthash", last.Hash(),
  1212. )
  1213. blocks := make([]*types.Block, len(results))
  1214. for i, result := range results {
  1215. blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1216. }
  1217. if index, err := d.blockchain.InsertChain(blocks); err != nil {
  1218. log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err)
  1219. return errInvalidChain
  1220. }
  1221. return nil
  1222. }
  1223. // processFastSyncContent takes fetch results from the queue and writes them to the
  1224. // database. It also controls the synchronisation of state nodes of the pivot block.
  1225. func (d *Downloader) processFastSyncContent(latest *types.Header) error {
  1226. // Start syncing state of the reported head block. This should get us most of
  1227. // the state of the pivot block.
  1228. stateSync := d.syncState(latest.Root)
  1229. defer stateSync.Cancel()
  1230. go func() {
  1231. if err := stateSync.Wait(); err != nil && err != errCancelStateFetch {
  1232. d.queue.Close() // wake up WaitResults
  1233. }
  1234. }()
  1235. // Figure out the ideal pivot block. Note, that this goalpost may move if the
  1236. // sync takes long enough for the chain head to move significantly.
  1237. pivot := uint64(0)
  1238. if height := latest.Number.Uint64(); height > uint64(fsMinFullBlocks) {
  1239. pivot = height - uint64(fsMinFullBlocks)
  1240. }
  1241. // To cater for moving pivot points, track the pivot block and subsequently
  1242. // accumulated download results separatey.
  1243. var (
  1244. oldPivot *fetchResult // Locked in pivot block, might change eventually
  1245. oldTail []*fetchResult // Downloaded content after the pivot
  1246. )
  1247. for {
  1248. // Wait for the next batch of downloaded data to be available, and if the pivot
  1249. // block became stale, move the goalpost
  1250. results := d.queue.Results(oldPivot == nil) // Block if we're not monitoring pivot staleness
  1251. if len(results) == 0 {
  1252. // If pivot sync is done, stop
  1253. if oldPivot == nil {
  1254. return stateSync.Cancel()
  1255. }
  1256. // If sync failed, stop
  1257. select {
  1258. case <-d.cancelCh:
  1259. return stateSync.Cancel()
  1260. default:
  1261. }
  1262. }
  1263. if d.chainInsertHook != nil {
  1264. d.chainInsertHook(results)
  1265. }
  1266. if oldPivot != nil {
  1267. results = append(append([]*fetchResult{oldPivot}, oldTail...), results...)
  1268. }
  1269. // Split around the pivot block and process the two sides via fast/full sync
  1270. if atomic.LoadInt32(&d.committed) == 0 {
  1271. latest = results[len(results)-1].Header
  1272. if height := latest.Number.Uint64(); height > pivot+2*uint64(fsMinFullBlocks) {
  1273. log.Warn("Pivot became stale, moving", "old", pivot, "new", height-uint64(fsMinFullBlocks))
  1274. pivot = height - uint64(fsMinFullBlocks)
  1275. }
  1276. }
  1277. P, beforeP, afterP := splitAroundPivot(pivot, results)
  1278. if err := d.commitFastSyncData(beforeP, stateSync); err != nil {
  1279. return err
  1280. }
  1281. if P != nil {
  1282. // If new pivot block found, cancel old state retrieval and restart
  1283. if oldPivot != P {
  1284. stateSync.Cancel()
  1285. stateSync = d.syncState(P.Header.Root)
  1286. defer stateSync.Cancel()
  1287. go func() {
  1288. if err := stateSync.Wait(); err != nil && err != errCancelStateFetch {
  1289. d.queue.Close() // wake up WaitResults
  1290. }
  1291. }()
  1292. oldPivot = P
  1293. }
  1294. // Wait for completion, occasionally checking for pivot staleness
  1295. select {
  1296. case <-stateSync.done:
  1297. if stateSync.err != nil {
  1298. return stateSync.err
  1299. }
  1300. if err := d.commitPivotBlock(P); err != nil {
  1301. return err
  1302. }
  1303. oldPivot = nil
  1304. case <-time.After(time.Second):
  1305. oldTail = afterP
  1306. continue
  1307. }
  1308. }
  1309. // Fast sync done, pivot commit done, full import
  1310. if err := d.importBlockResults(afterP); err != nil {
  1311. return err
  1312. }
  1313. }
  1314. }
  1315. func splitAroundPivot(pivot uint64, results []*fetchResult) (p *fetchResult, before, after []*fetchResult) {
  1316. for _, result := range results {
  1317. num := result.Header.Number.Uint64()
  1318. switch {
  1319. case num < pivot:
  1320. before = append(before, result)
  1321. case num == pivot:
  1322. p = result
  1323. default:
  1324. after = append(after, result)
  1325. }
  1326. }
  1327. return p, before, after
  1328. }
  1329. func (d *Downloader) commitFastSyncData(results []*fetchResult, stateSync *stateSync) error {
  1330. // Check for any early termination requests
  1331. if len(results) == 0 {
  1332. return nil
  1333. }
  1334. select {
  1335. case <-d.quitCh:
  1336. return errCancelContentProcessing
  1337. case <-stateSync.done:
  1338. if err := stateSync.Wait(); err != nil {
  1339. return err
  1340. }
  1341. default:
  1342. }
  1343. // Retrieve the a batch of results to import
  1344. first, last := results[0].Header, results[len(results)-1].Header
  1345. log.Debug("Inserting fast-sync blocks", "items", len(results),
  1346. "firstnum", first.Number, "firsthash", first.Hash(),
  1347. "lastnumn", last.Number, "lasthash", last.Hash(),
  1348. )
  1349. blocks := make([]*types.Block, len(results))
  1350. receipts := make([]types.Receipts, len(results))
  1351. for i, result := range results {
  1352. blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1353. receipts[i] = result.Receipts
  1354. }
  1355. if index, err := d.blockchain.InsertReceiptChain(blocks, receipts); err != nil {
  1356. log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err)
  1357. return errInvalidChain
  1358. }
  1359. return nil
  1360. }
  1361. func (d *Downloader) commitPivotBlock(result *fetchResult) error {
  1362. block := types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1363. log.Debug("Committing fast sync pivot as new head", "number", block.Number(), "hash", block.Hash())
  1364. if _, err := d.blockchain.InsertReceiptChain([]*types.Block{block}, []types.Receipts{result.Receipts}); err != nil {
  1365. return err
  1366. }
  1367. if err := d.blockchain.FastSyncCommitHead(block.Hash()); err != nil {
  1368. return err
  1369. }
  1370. atomic.StoreInt32(&d.committed, 1)
  1371. return nil
  1372. }
  1373. // DeliverHeaders injects a new batch of block headers received from a remote
  1374. // node into the download schedule.
  1375. func (d *Downloader) DeliverHeaders(id string, headers []*types.Header) (err error) {
  1376. return d.deliver(id, d.headerCh, &headerPack{id, headers}, headerInMeter, headerDropMeter)
  1377. }
  1378. // DeliverBodies injects a new batch of block bodies received from a remote node.
  1379. func (d *Downloader) DeliverBodies(id string, transactions [][]*types.Transaction, uncles [][]*types.Header) (err error) {
  1380. return d.deliver(id, d.bodyCh, &bodyPack{id, transactions, uncles}, bodyInMeter, bodyDropMeter)
  1381. }
  1382. // DeliverReceipts injects a new batch of receipts received from a remote node.
  1383. func (d *Downloader) DeliverReceipts(id string, receipts [][]*types.Receipt) (err error) {
  1384. return d.deliver(id, d.receiptCh, &receiptPack{id, receipts}, receiptInMeter, receiptDropMeter)
  1385. }
  1386. // DeliverNodeData injects a new batch of node state data received from a remote node.
  1387. func (d *Downloader) DeliverNodeData(id string, data [][]byte) (err error) {
  1388. return d.deliver(id, d.stateCh, &statePack{id, data}, stateInMeter, stateDropMeter)
  1389. }
  1390. // deliver injects a new batch of data received from a remote node.
  1391. func (d *Downloader) deliver(id string, destCh chan dataPack, packet dataPack, inMeter, dropMeter metrics.Meter) (err error) {
  1392. // Update the delivery metrics for both good and failed deliveries
  1393. inMeter.Mark(int64(packet.Items()))
  1394. defer func() {
  1395. if err != nil {
  1396. dropMeter.Mark(int64(packet.Items()))
  1397. }
  1398. }()
  1399. // Deliver or abort if the sync is canceled while queuing
  1400. d.cancelLock.RLock()
  1401. cancel := d.cancelCh
  1402. d.cancelLock.RUnlock()
  1403. if cancel == nil {
  1404. return errNoSyncActive
  1405. }
  1406. select {
  1407. case destCh <- packet:
  1408. return nil
  1409. case <-cancel:
  1410. return errNoSyncActive
  1411. }
  1412. }
  1413. // qosTuner is the quality of service tuning loop that occasionally gathers the
  1414. // peer latency statistics and updates the estimated request round trip time.
  1415. func (d *Downloader) qosTuner() {
  1416. for {
  1417. // Retrieve the current median RTT and integrate into the previoust target RTT
  1418. rtt := time.Duration((1-qosTuningImpact)*float64(atomic.LoadUint64(&d.rttEstimate)) + qosTuningImpact*float64(d.peers.medianRTT()))
  1419. atomic.StoreUint64(&d.rttEstimate, uint64(rtt))
  1420. // A new RTT cycle passed, increase our confidence in the estimated RTT
  1421. conf := atomic.LoadUint64(&d.rttConfidence)
  1422. conf = conf + (1000000-conf)/2
  1423. atomic.StoreUint64(&d.rttConfidence, conf)
  1424. // Log the new QoS values and sleep until the next RTT
  1425. log.Debug("Recalculated downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL())
  1426. select {
  1427. case <-d.quitCh:
  1428. return
  1429. case <-time.After(rtt):
  1430. }
  1431. }
  1432. }
  1433. // qosReduceConfidence is meant to be called when a new peer joins the downloader's
  1434. // peer set, needing to reduce the confidence we have in out QoS estimates.
  1435. func (d *Downloader) qosReduceConfidence() {
  1436. // If we have a single peer, confidence is always 1
  1437. peers := uint64(d.peers.Len())
  1438. if peers == 0 {
  1439. // Ensure peer connectivity races don't catch us off guard
  1440. return
  1441. }
  1442. if peers == 1 {
  1443. atomic.StoreUint64(&d.rttConfidence, 1000000)
  1444. return
  1445. }
  1446. // If we have a ton of peers, don't drop confidence)
  1447. if peers >= uint64(qosConfidenceCap) {
  1448. return
  1449. }
  1450. // Otherwise drop the confidence factor
  1451. conf := atomic.LoadUint64(&d.rttConfidence) * (peers - 1) / peers
  1452. if float64(conf)/1000000 < rttMinConfidence {
  1453. conf = uint64(rttMinConfidence * 1000000)
  1454. }
  1455. atomic.StoreUint64(&d.rttConfidence, conf)
  1456. rtt := time.Duration(atomic.LoadUint64(&d.rttEstimate))
  1457. log.Debug("Relaxed downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL())
  1458. }
  1459. // requestRTT returns the current target round trip time for a download request
  1460. // to complete in.
  1461. //
  1462. // Note, the returned RTT is .9 of the actually estimated RTT. The reason is that
  1463. // the downloader tries to adapt queries to the RTT, so multiple RTT values can
  1464. // be adapted to, but smaller ones are preffered (stabler download stream).
  1465. func (d *Downloader) requestRTT() time.Duration {
  1466. return time.Duration(atomic.LoadUint64(&d.rttEstimate)) * 9 / 10
  1467. }
  1468. // requestTTL returns the current timeout allowance for a single download request
  1469. // to finish under.
  1470. func (d *Downloader) requestTTL() time.Duration {
  1471. var (
  1472. rtt = time.Duration(atomic.LoadUint64(&d.rttEstimate))
  1473. conf = float64(atomic.LoadUint64(&d.rttConfidence)) / 1000000.0
  1474. )
  1475. ttl := time.Duration(ttlScaling) * time.Duration(float64(rtt)/conf)
  1476. if ttl > ttlLimit {
  1477. ttl = ttlLimit
  1478. }
  1479. return ttl
  1480. }