downloader.go 60 KB

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