downloader.go 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154
  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. "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/state/snapshot"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/eth/protocols/eth"
  31. "github.com/ethereum/go-ethereum/eth/protocols/snap"
  32. "github.com/ethereum/go-ethereum/ethdb"
  33. "github.com/ethereum/go-ethereum/event"
  34. "github.com/ethereum/go-ethereum/log"
  35. "github.com/ethereum/go-ethereum/metrics"
  36. "github.com/ethereum/go-ethereum/params"
  37. "github.com/ethereum/go-ethereum/trie"
  38. )
  39. var (
  40. MaxBlockFetch = 128 // Amount of blocks to be fetched per retrieval request
  41. MaxHeaderFetch = 192 // Amount of block headers to be fetched per retrieval request
  42. MaxSkeletonSize = 128 // Number of header fetches to need for a skeleton assembly
  43. MaxReceiptFetch = 256 // Amount of transaction receipts to allow fetching per request
  44. MaxStateFetch = 384 // Amount of node state values to allow fetching per request
  45. rttMinEstimate = 2 * time.Second // Minimum round-trip time to target for download requests
  46. rttMaxEstimate = 20 * time.Second // Maximum round-trip time to target for download requests
  47. rttMinConfidence = 0.1 // Worse confidence factor in our estimated RTT value
  48. ttlScaling = 3 // Constant scaling factor for RTT -> TTL conversion
  49. ttlLimit = time.Minute // Maximum TTL allowance to prevent reaching crazy timeouts
  50. qosTuningPeers = 5 // Number of peers to tune based on (best peers)
  51. qosConfidenceCap = 10 // Number of peers above which not to modify RTT confidence
  52. qosTuningImpact = 0.25 // Impact that a new tuning target has on the previous value
  53. maxQueuedHeaders = 32 * 1024 // [eth/62] Maximum number of headers to queue for import (DOS protection)
  54. maxHeadersProcess = 2048 // Number of header download results to import at once into the chain
  55. maxResultsProcess = 2048 // Number of content download results to import at once into the chain
  56. fullMaxForkAncestry uint64 = params.FullImmutabilityThreshold // Maximum chain reorganisation (locally redeclared so tests can reduce it)
  57. lightMaxForkAncestry uint64 = params.LightImmutabilityThreshold // Maximum chain reorganisation (locally redeclared so tests can reduce it)
  58. reorgProtThreshold = 48 // Threshold number of recent blocks to disable mini reorg protection
  59. reorgProtHeaderDelay = 2 // Number of headers to delay delivering to cover mini reorgs
  60. fsHeaderCheckFrequency = 100 // Verification frequency of the downloaded headers during fast sync
  61. fsHeaderSafetyNet = 2048 // Number of headers to discard in case a chain violation is detected
  62. fsHeaderForceVerify = 24 // Number of headers to verify before and after the pivot to accept it
  63. fsHeaderContCheck = 3 * time.Second // Time interval to check for header continuations during state download
  64. fsMinFullBlocks = 64 // Number of blocks to retrieve fully even in fast sync
  65. )
  66. var (
  67. errBusy = errors.New("busy")
  68. errUnknownPeer = errors.New("peer is unknown or unhealthy")
  69. errBadPeer = errors.New("action from bad peer ignored")
  70. errStallingPeer = errors.New("peer is stalling")
  71. errUnsyncedPeer = errors.New("unsynced peer")
  72. errNoPeers = errors.New("no peers to keep download active")
  73. errTimeout = errors.New("timeout")
  74. errEmptyHeaderSet = errors.New("empty header set by peer")
  75. errPeersUnavailable = errors.New("no peers available or all tried for download")
  76. errInvalidAncestor = errors.New("retrieved ancestor is invalid")
  77. errInvalidChain = errors.New("retrieved hash chain is invalid")
  78. errInvalidBody = errors.New("retrieved block body is invalid")
  79. errInvalidReceipt = errors.New("retrieved receipt is invalid")
  80. errCancelStateFetch = errors.New("state data download canceled (requested)")
  81. errCancelContentProcessing = errors.New("content processing canceled (requested)")
  82. errCanceled = errors.New("syncing canceled (requested)")
  83. errNoSyncActive = errors.New("no sync active")
  84. errTooOld = errors.New("peer's protocol version too old")
  85. errNoAncestorFound = errors.New("no common ancestor found")
  86. )
  87. type Downloader struct {
  88. // WARNING: The `rttEstimate` and `rttConfidence` fields are accessed atomically.
  89. // On 32 bit platforms, only 64-bit aligned fields can be atomic. The struct is
  90. // guaranteed to be so aligned, so take advantage of that. For more information,
  91. // see https://golang.org/pkg/sync/atomic/#pkg-note-BUG.
  92. rttEstimate uint64 // Round trip time to target for download requests
  93. rttConfidence uint64 // Confidence in the estimated RTT (unit: millionths to allow atomic ops)
  94. mode uint32 // Synchronisation mode defining the strategy used (per sync cycle), use d.getMode() to get the SyncMode
  95. mux *event.TypeMux // Event multiplexer to announce sync operation events
  96. checkpoint uint64 // Checkpoint block number to enforce head against (e.g. fast sync)
  97. genesis uint64 // Genesis block number to limit sync to (e.g. light client CHT)
  98. queue *queue // Scheduler for selecting the hashes to download
  99. peers *peerSet // Set of active peers from which download can proceed
  100. stateDB ethdb.Database // Database to state sync into (and deduplicate via)
  101. stateBloom *trie.SyncBloom // Bloom filter for fast trie node and contract code existence checks
  102. // Statistics
  103. syncStatsChainOrigin uint64 // Origin block number where syncing started at
  104. syncStatsChainHeight uint64 // Highest block number known when syncing started
  105. syncStatsState stateSyncStats
  106. syncStatsLock sync.RWMutex // Lock protecting the sync stats fields
  107. lightchain LightChain
  108. blockchain BlockChain
  109. // Callbacks
  110. dropPeer peerDropFn // Drops a peer for misbehaving
  111. // Status
  112. synchroniseMock func(id string, hash common.Hash) error // Replacement for synchronise during testing
  113. synchronising int32
  114. notified int32
  115. committed int32
  116. ancientLimit uint64 // The maximum block number which can be regarded as ancient data.
  117. // Channels
  118. headerCh chan dataPack // Channel receiving inbound block headers
  119. bodyCh chan dataPack // Channel receiving inbound block bodies
  120. receiptCh chan dataPack // Channel receiving inbound receipts
  121. bodyWakeCh chan bool // Channel to signal the block body fetcher of new tasks
  122. receiptWakeCh chan bool // Channel to signal the receipt fetcher of new tasks
  123. headerProcCh chan []*types.Header // Channel to feed the header processor new tasks
  124. // State sync
  125. pivotHeader *types.Header // Pivot block header to dynamically push the syncing state root
  126. pivotLock sync.RWMutex // Lock protecting pivot header reads from updates
  127. snapSync bool // Whether to run state sync over the snap protocol
  128. SnapSyncer *snap.Syncer // TODO(karalabe): make private! hack for now
  129. stateSyncStart chan *stateSync
  130. trackStateReq chan *stateReq
  131. stateCh chan dataPack // Channel receiving inbound node state data
  132. // Cancellation and termination
  133. cancelPeer string // Identifier of the peer currently being used as the master (cancel on drop)
  134. cancelCh chan struct{} // Channel to cancel mid-flight syncs
  135. cancelLock sync.RWMutex // Lock to protect the cancel channel and peer in delivers
  136. cancelWg sync.WaitGroup // Make sure all fetcher goroutines have exited.
  137. quitCh chan struct{} // Quit channel to signal termination
  138. quitLock sync.Mutex // Lock to prevent double closes
  139. // Testing hooks
  140. syncInitHook func(uint64, uint64) // Method to call upon initiating a new sync run
  141. bodyFetchHook func([]*types.Header, ...interface{}) // Method to call upon starting a block body fetch
  142. receiptFetchHook func([]*types.Header, ...interface{}) // Method to call upon starting a receipt fetch
  143. chainInsertHook func([]*fetchResult) // Method to call upon inserting a chain of blocks (possibly in multiple invocations)
  144. }
  145. // LightChain encapsulates functions required to synchronise a light chain.
  146. type LightChain interface {
  147. // HasHeader verifies a header's presence in the local chain.
  148. HasHeader(common.Hash, uint64) bool
  149. // GetHeaderByHash retrieves a header from the local chain.
  150. GetHeaderByHash(common.Hash) *types.Header
  151. // CurrentHeader retrieves the head header from the local chain.
  152. CurrentHeader() *types.Header
  153. // GetTd returns the total difficulty of a local block.
  154. GetTd(common.Hash, uint64) *big.Int
  155. // InsertHeaderChain inserts a batch of headers into the local chain.
  156. InsertHeaderChain([]*types.Header, int) (int, error)
  157. // SetHead rewinds the local chain to a new head.
  158. SetHead(uint64) error
  159. }
  160. // BlockChain encapsulates functions required to sync a (full or fast) blockchain.
  161. type BlockChain interface {
  162. LightChain
  163. // HasBlock verifies a block's presence in the local chain.
  164. HasBlock(common.Hash, uint64) bool
  165. // HasFastBlock verifies a fast block's presence in the local chain.
  166. HasFastBlock(common.Hash, uint64) bool
  167. // GetBlockByHash retrieves a block from the local chain.
  168. GetBlockByHash(common.Hash) *types.Block
  169. // CurrentBlock retrieves the head block from the local chain.
  170. CurrentBlock() *types.Block
  171. // CurrentFastBlock retrieves the head fast block from the local chain.
  172. CurrentFastBlock() *types.Block
  173. // FastSyncCommitHead directly commits the head block to a certain entity.
  174. FastSyncCommitHead(common.Hash) error
  175. // InsertChain inserts a batch of blocks into the local chain.
  176. InsertChain(types.Blocks) (int, error)
  177. // InsertReceiptChain inserts a batch of receipts into the local chain.
  178. InsertReceiptChain(types.Blocks, []types.Receipts, uint64) (int, error)
  179. // Snapshots returns the blockchain snapshot tree to paused it during sync.
  180. Snapshots() *snapshot.Tree
  181. }
  182. type DownloadOption func(downloader *Downloader) *Downloader
  183. type IDiffPeer interface {
  184. RequestDiffLayers([]common.Hash) error
  185. }
  186. type IPeerSet interface {
  187. GetDiffPeer(string) IDiffPeer
  188. }
  189. func EnableDiffFetchOp(peers IPeerSet) DownloadOption {
  190. return func(dl *Downloader) *Downloader {
  191. var hook = func(headers []*types.Header, args ...interface{}) {
  192. if len(args) < 2 {
  193. return
  194. }
  195. peerID, ok := args[1].(string)
  196. if !ok {
  197. return
  198. }
  199. mode, ok := args[0].(SyncMode)
  200. if !ok {
  201. return
  202. }
  203. if ep := peers.GetDiffPeer(peerID); mode == FullSync && ep != nil {
  204. hashes := make([]common.Hash, 0, len(headers))
  205. for _, header := range headers {
  206. hashes = append(hashes, header.Hash())
  207. }
  208. ep.RequestDiffLayers(hashes)
  209. }
  210. }
  211. dl.bodyFetchHook = hook
  212. return dl
  213. }
  214. }
  215. // New creates a new downloader to fetch hashes and blocks from remote peers.
  216. func New(checkpoint uint64, stateDb ethdb.Database, stateBloom *trie.SyncBloom, mux *event.TypeMux, chain BlockChain, lightchain LightChain, dropPeer peerDropFn, options ...DownloadOption) *Downloader {
  217. if lightchain == nil {
  218. lightchain = chain
  219. }
  220. dl := &Downloader{
  221. stateDB: stateDb,
  222. stateBloom: stateBloom,
  223. mux: mux,
  224. checkpoint: checkpoint,
  225. queue: newQueue(blockCacheMaxItems, blockCacheInitialItems),
  226. peers: newPeerSet(),
  227. rttEstimate: uint64(rttMaxEstimate),
  228. rttConfidence: uint64(1000000),
  229. blockchain: chain,
  230. lightchain: lightchain,
  231. dropPeer: dropPeer,
  232. headerCh: make(chan dataPack, 1),
  233. bodyCh: make(chan dataPack, 1),
  234. receiptCh: make(chan dataPack, 1),
  235. bodyWakeCh: make(chan bool, 1),
  236. receiptWakeCh: make(chan bool, 1),
  237. headerProcCh: make(chan []*types.Header, 1),
  238. quitCh: make(chan struct{}),
  239. stateCh: make(chan dataPack),
  240. SnapSyncer: snap.NewSyncer(stateDb),
  241. stateSyncStart: make(chan *stateSync),
  242. syncStatsState: stateSyncStats{
  243. processed: rawdb.ReadFastTrieProgress(stateDb),
  244. },
  245. trackStateReq: make(chan *stateReq),
  246. }
  247. for _, option := range options {
  248. if dl != nil {
  249. dl = option(dl)
  250. }
  251. }
  252. go dl.qosTuner()
  253. go dl.stateFetcher()
  254. return dl
  255. }
  256. // Progress retrieves the synchronisation boundaries, specifically the origin
  257. // block where synchronisation started at (may have failed/suspended); the block
  258. // or header sync is currently at; and the latest known block which the sync targets.
  259. //
  260. // In addition, during the state download phase of fast synchronisation the number
  261. // of processed and the total number of known states are also returned. Otherwise
  262. // these are zero.
  263. func (d *Downloader) Progress() ethereum.SyncProgress {
  264. // Lock the current stats and return the progress
  265. d.syncStatsLock.RLock()
  266. defer d.syncStatsLock.RUnlock()
  267. current := uint64(0)
  268. mode := d.getMode()
  269. switch {
  270. case d.blockchain != nil && mode == FullSync:
  271. current = d.blockchain.CurrentBlock().NumberU64()
  272. case d.blockchain != nil && mode == FastSync:
  273. current = d.blockchain.CurrentFastBlock().NumberU64()
  274. case d.lightchain != nil:
  275. current = d.lightchain.CurrentHeader().Number.Uint64()
  276. default:
  277. log.Error("Unknown downloader chain/mode combo", "light", d.lightchain != nil, "full", d.blockchain != nil, "mode", mode)
  278. }
  279. return ethereum.SyncProgress{
  280. StartingBlock: d.syncStatsChainOrigin,
  281. CurrentBlock: current,
  282. HighestBlock: d.syncStatsChainHeight,
  283. PulledStates: d.syncStatsState.processed,
  284. KnownStates: d.syncStatsState.processed + d.syncStatsState.pending,
  285. }
  286. }
  287. // Synchronising returns whether the downloader is currently retrieving blocks.
  288. func (d *Downloader) Synchronising() bool {
  289. return atomic.LoadInt32(&d.synchronising) > 0
  290. }
  291. // RegisterPeer injects a new download peer into the set of block source to be
  292. // used for fetching hashes and blocks from.
  293. func (d *Downloader) RegisterPeer(id string, version uint, peer Peer) error {
  294. var logger log.Logger
  295. if len(id) < 16 {
  296. // Tests use short IDs, don't choke on them
  297. logger = log.New("peer", id)
  298. } else {
  299. logger = log.New("peer", id[:8])
  300. }
  301. logger.Trace("Registering sync peer")
  302. if err := d.peers.Register(newPeerConnection(id, version, peer, logger)); err != nil {
  303. logger.Error("Failed to register sync peer", "err", err)
  304. return err
  305. }
  306. d.qosReduceConfidence()
  307. return nil
  308. }
  309. // RegisterLightPeer injects a light client peer, wrapping it so it appears as a regular peer.
  310. func (d *Downloader) RegisterLightPeer(id string, version uint, peer LightPeer) error {
  311. return d.RegisterPeer(id, version, &lightPeerWrapper{peer})
  312. }
  313. // UnregisterPeer remove a peer from the known list, preventing any action from
  314. // the specified peer. An effort is also made to return any pending fetches into
  315. // the queue.
  316. func (d *Downloader) UnregisterPeer(id string) error {
  317. // Unregister the peer from the active peer set and revoke any fetch tasks
  318. var logger log.Logger
  319. if len(id) < 16 {
  320. // Tests use short IDs, don't choke on them
  321. logger = log.New("peer", id)
  322. } else {
  323. logger = log.New("peer", id[:8])
  324. }
  325. logger.Trace("Unregistering sync peer")
  326. if err := d.peers.Unregister(id); err != nil {
  327. logger.Error("Failed to unregister sync peer", "err", err)
  328. return err
  329. }
  330. d.queue.Revoke(id)
  331. return nil
  332. }
  333. // Synchronise tries to sync up our local block chain with a remote peer, both
  334. // adding various sanity checks as well as wrapping it with various log entries.
  335. func (d *Downloader) Synchronise(id string, head common.Hash, td *big.Int, mode SyncMode) error {
  336. err := d.synchronise(id, head, td, mode)
  337. switch err {
  338. case nil, errBusy, errCanceled:
  339. return err
  340. }
  341. if errors.Is(err, errInvalidChain) || errors.Is(err, errBadPeer) || errors.Is(err, errTimeout) ||
  342. errors.Is(err, errStallingPeer) || errors.Is(err, errUnsyncedPeer) || errors.Is(err, errEmptyHeaderSet) ||
  343. errors.Is(err, errPeersUnavailable) || errors.Is(err, errTooOld) || errors.Is(err, errInvalidAncestor) {
  344. log.Warn("Synchronisation failed, dropping peer", "peer", id, "err", err)
  345. if d.dropPeer == nil {
  346. // The dropPeer method is nil when `--copydb` is used for a local copy.
  347. // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
  348. log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", id)
  349. } else {
  350. d.dropPeer(id)
  351. }
  352. return err
  353. }
  354. log.Warn("Synchronisation failed, retrying", "err", err)
  355. return err
  356. }
  357. // synchronise will select the peer and use it for synchronising. If an empty string is given
  358. // it will use the best peer possible and synchronize if its TD is higher than our own. If any of the
  359. // checks fail an error will be returned. This method is synchronous
  360. func (d *Downloader) synchronise(id string, hash common.Hash, td *big.Int, mode SyncMode) error {
  361. // Mock out the synchronisation if testing
  362. if d.synchroniseMock != nil {
  363. return d.synchroniseMock(id, hash)
  364. }
  365. // Make sure only one goroutine is ever allowed past this point at once
  366. if !atomic.CompareAndSwapInt32(&d.synchronising, 0, 1) {
  367. return errBusy
  368. }
  369. defer atomic.StoreInt32(&d.synchronising, 0)
  370. // Post a user notification of the sync (only once per session)
  371. if atomic.CompareAndSwapInt32(&d.notified, 0, 1) {
  372. log.Info("Block synchronisation started")
  373. }
  374. // If we are already full syncing, but have a fast-sync bloom filter laying
  375. // around, make sure it doesn't use memory any more. This is a special case
  376. // when the user attempts to fast sync a new empty network.
  377. if mode == FullSync && d.stateBloom != nil {
  378. d.stateBloom.Close()
  379. }
  380. // If snap sync was requested, create the snap scheduler and switch to fast
  381. // sync mode. Long term we could drop fast sync or merge the two together,
  382. // but until snap becomes prevalent, we should support both. TODO(karalabe).
  383. if mode == SnapSync {
  384. if !d.snapSync {
  385. // Snap sync uses the snapshot namespace to store potentially flakey data until
  386. // sync completely heals and finishes. Pause snapshot maintenance in the mean
  387. // time to prevent access.
  388. if snapshots := d.blockchain.Snapshots(); snapshots != nil { // Only nil in tests
  389. snapshots.Disable()
  390. }
  391. log.Warn("Enabling snapshot sync prototype")
  392. d.snapSync = true
  393. }
  394. mode = FastSync
  395. }
  396. // Reset the queue, peer set and wake channels to clean any internal leftover state
  397. d.queue.Reset(blockCacheMaxItems, blockCacheInitialItems)
  398. d.peers.Reset()
  399. for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  400. select {
  401. case <-ch:
  402. default:
  403. }
  404. }
  405. for _, ch := range []chan dataPack{d.headerCh, d.bodyCh, d.receiptCh} {
  406. for empty := false; !empty; {
  407. select {
  408. case <-ch:
  409. default:
  410. empty = true
  411. }
  412. }
  413. }
  414. for empty := false; !empty; {
  415. select {
  416. case <-d.headerProcCh:
  417. default:
  418. empty = true
  419. }
  420. }
  421. // Create cancel channel for aborting mid-flight and mark the master peer
  422. d.cancelLock.Lock()
  423. d.cancelCh = make(chan struct{})
  424. d.cancelPeer = id
  425. d.cancelLock.Unlock()
  426. defer d.Cancel() // No matter what, we can't leave the cancel channel open
  427. // Atomically set the requested sync mode
  428. atomic.StoreUint32(&d.mode, uint32(mode))
  429. // Retrieve the origin peer and initiate the downloading process
  430. p := d.peers.Peer(id)
  431. if p == nil {
  432. return errUnknownPeer
  433. }
  434. return d.syncWithPeer(p, hash, td)
  435. }
  436. func (d *Downloader) getMode() SyncMode {
  437. return SyncMode(atomic.LoadUint32(&d.mode))
  438. }
  439. // syncWithPeer starts a block synchronization based on the hash chain from the
  440. // specified peer and head hash.
  441. func (d *Downloader) syncWithPeer(p *peerConnection, hash common.Hash, td *big.Int) (err error) {
  442. d.mux.Post(StartEvent{})
  443. defer func() {
  444. // reset on error
  445. if err != nil {
  446. d.mux.Post(FailedEvent{err})
  447. } else {
  448. latest := d.lightchain.CurrentHeader()
  449. d.mux.Post(DoneEvent{latest})
  450. }
  451. }()
  452. if p.version < eth.ETH65 {
  453. return fmt.Errorf("%w: advertized %d < required %d", errTooOld, p.version, eth.ETH65)
  454. }
  455. mode := d.getMode()
  456. log.Debug("Synchronising with the network", "peer", p.id, "eth", p.version, "head", hash, "td", td, "mode", mode)
  457. defer func(start time.Time) {
  458. log.Debug("Synchronisation terminated", "elapsed", common.PrettyDuration(time.Since(start)))
  459. }(time.Now())
  460. // Look up the sync boundaries: the common ancestor and the target block
  461. latest, pivot, err := d.fetchHead(p)
  462. if err != nil {
  463. return err
  464. }
  465. if mode == FastSync && pivot == nil {
  466. // If no pivot block was returned, the head is below the min full block
  467. // threshold (i.e. new chian). In that case we won't really fast sync
  468. // anyway, but still need a valid pivot block to avoid some code hitting
  469. // nil panics on an access.
  470. pivot = d.blockchain.CurrentBlock().Header()
  471. }
  472. height := latest.Number.Uint64()
  473. origin, err := d.findAncestor(p, latest)
  474. if err != nil {
  475. return err
  476. }
  477. d.syncStatsLock.Lock()
  478. if d.syncStatsChainHeight <= origin || d.syncStatsChainOrigin > origin {
  479. d.syncStatsChainOrigin = origin
  480. }
  481. d.syncStatsChainHeight = height
  482. d.syncStatsLock.Unlock()
  483. // Ensure our origin point is below any fast sync pivot point
  484. if mode == FastSync {
  485. if height <= uint64(fsMinFullBlocks) {
  486. origin = 0
  487. } else {
  488. pivotNumber := pivot.Number.Uint64()
  489. if pivotNumber <= origin {
  490. origin = pivotNumber - 1
  491. }
  492. // Write out the pivot into the database so a rollback beyond it will
  493. // reenable fast sync
  494. rawdb.WriteLastPivotNumber(d.stateDB, pivotNumber)
  495. }
  496. }
  497. d.committed = 1
  498. if mode == FastSync && pivot.Number.Uint64() != 0 {
  499. d.committed = 0
  500. }
  501. if mode == FastSync {
  502. // Set the ancient data limitation.
  503. // If we are running fast sync, all block data older than ancientLimit will be
  504. // written to the ancient store. More recent data will be written to the active
  505. // database and will wait for the freezer to migrate.
  506. //
  507. // If there is a checkpoint available, then calculate the ancientLimit through
  508. // that. Otherwise calculate the ancient limit through the advertised height
  509. // of the remote peer.
  510. //
  511. // The reason for picking checkpoint first is that a malicious peer can give us
  512. // a fake (very high) height, forcing the ancient limit to also be very high.
  513. // The peer would start to feed us valid blocks until head, resulting in all of
  514. // the blocks might be written into the ancient store. A following mini-reorg
  515. // could cause issues.
  516. if d.checkpoint != 0 && d.checkpoint > fullMaxForkAncestry+1 {
  517. d.ancientLimit = d.checkpoint
  518. } else if height > fullMaxForkAncestry+1 {
  519. d.ancientLimit = height - fullMaxForkAncestry - 1
  520. } else {
  521. d.ancientLimit = 0
  522. }
  523. frozen, _ := d.stateDB.Ancients() // Ignore the error here since light client can also hit here.
  524. // If a part of blockchain data has already been written into active store,
  525. // disable the ancient style insertion explicitly.
  526. if origin >= frozen && frozen != 0 {
  527. d.ancientLimit = 0
  528. log.Info("Disabling direct-ancient mode", "origin", origin, "ancient", frozen-1)
  529. } else if d.ancientLimit > 0 {
  530. log.Debug("Enabling direct-ancient mode", "ancient", d.ancientLimit)
  531. }
  532. // Rewind the ancient store and blockchain if reorg happens.
  533. if origin+1 < frozen {
  534. if err := d.lightchain.SetHead(origin + 1); err != nil {
  535. return err
  536. }
  537. }
  538. }
  539. // Initiate the sync using a concurrent header and content retrieval algorithm
  540. d.queue.Prepare(origin+1, mode)
  541. if d.syncInitHook != nil {
  542. d.syncInitHook(origin, height)
  543. }
  544. fetchers := []func() error{
  545. func() error { return d.fetchHeaders(p, origin+1) }, // Headers are always retrieved
  546. func() error { return d.fetchBodies(origin + 1) }, // Bodies are retrieved during normal and fast sync
  547. func() error { return d.fetchReceipts(origin + 1) }, // Receipts are retrieved during fast sync
  548. func() error { return d.processHeaders(origin+1, td) },
  549. }
  550. if mode == FastSync {
  551. d.pivotLock.Lock()
  552. d.pivotHeader = pivot
  553. d.pivotLock.Unlock()
  554. fetchers = append(fetchers, func() error { return d.processFastSyncContent() })
  555. } else if mode == FullSync {
  556. fetchers = append(fetchers, d.processFullSyncContent)
  557. }
  558. return d.spawnSync(fetchers)
  559. }
  560. // spawnSync runs d.process and all given fetcher functions to completion in
  561. // separate goroutines, returning the first error that appears.
  562. func (d *Downloader) spawnSync(fetchers []func() error) error {
  563. errc := make(chan error, len(fetchers))
  564. d.cancelWg.Add(len(fetchers))
  565. for _, fn := range fetchers {
  566. fn := fn
  567. go func() { defer d.cancelWg.Done(); errc <- fn() }()
  568. }
  569. // Wait for the first error, then terminate the others.
  570. var err error
  571. for i := 0; i < len(fetchers); i++ {
  572. if i == len(fetchers)-1 {
  573. // Close the queue when all fetchers have exited.
  574. // This will cause the block processor to end when
  575. // it has processed the queue.
  576. d.queue.Close()
  577. }
  578. if err = <-errc; err != nil && err != errCanceled {
  579. break
  580. }
  581. }
  582. d.queue.Close()
  583. d.Cancel()
  584. return err
  585. }
  586. // cancel aborts all of the operations and resets the queue. However, cancel does
  587. // not wait for the running download goroutines to finish. This method should be
  588. // used when cancelling the downloads from inside the downloader.
  589. func (d *Downloader) cancel() {
  590. // Close the current cancel channel
  591. d.cancelLock.Lock()
  592. defer d.cancelLock.Unlock()
  593. if d.cancelCh != nil {
  594. select {
  595. case <-d.cancelCh:
  596. // Channel was already closed
  597. default:
  598. close(d.cancelCh)
  599. }
  600. }
  601. }
  602. // Cancel aborts all of the operations and waits for all download goroutines to
  603. // finish before returning.
  604. func (d *Downloader) Cancel() {
  605. d.cancel()
  606. d.cancelWg.Wait()
  607. }
  608. // Terminate interrupts the downloader, canceling all pending operations.
  609. // The downloader cannot be reused after calling Terminate.
  610. func (d *Downloader) Terminate() {
  611. // Close the termination channel (make sure double close is allowed)
  612. d.quitLock.Lock()
  613. select {
  614. case <-d.quitCh:
  615. default:
  616. close(d.quitCh)
  617. }
  618. if d.stateBloom != nil {
  619. d.stateBloom.Close()
  620. }
  621. d.quitLock.Unlock()
  622. // Cancel any pending download requests
  623. d.Cancel()
  624. }
  625. // fetchHead retrieves the head header and prior pivot block (if available) from
  626. // a remote peer.
  627. func (d *Downloader) fetchHead(p *peerConnection) (head *types.Header, pivot *types.Header, err error) {
  628. p.log.Debug("Retrieving remote chain head")
  629. mode := d.getMode()
  630. // Request the advertised remote head block and wait for the response
  631. latest, _ := p.peer.Head()
  632. fetch := 1
  633. if mode == FastSync {
  634. fetch = 2 // head + pivot headers
  635. }
  636. go p.peer.RequestHeadersByHash(latest, fetch, fsMinFullBlocks-1, true)
  637. ttl := d.requestTTL()
  638. timeout := time.After(ttl)
  639. for {
  640. select {
  641. case <-d.cancelCh:
  642. return nil, nil, errCanceled
  643. case packet := <-d.headerCh:
  644. // Discard anything not from the origin peer
  645. if packet.PeerId() != p.id {
  646. log.Debug("Received headers from incorrect peer", "peer", packet.PeerId())
  647. break
  648. }
  649. // Make sure the peer gave us at least one and at most the requested headers
  650. headers := packet.(*headerPack).headers
  651. if len(headers) == 0 || len(headers) > fetch {
  652. return nil, nil, fmt.Errorf("%w: returned headers %d != requested %d", errBadPeer, len(headers), fetch)
  653. }
  654. // The first header needs to be the head, validate against the checkpoint
  655. // and request. If only 1 header was returned, make sure there's no pivot
  656. // or there was not one requested.
  657. head := headers[0]
  658. if (mode == FastSync || mode == LightSync) && head.Number.Uint64() < d.checkpoint {
  659. return nil, nil, fmt.Errorf("%w: remote head %d below checkpoint %d", errUnsyncedPeer, head.Number, d.checkpoint)
  660. }
  661. if len(headers) == 1 {
  662. if mode == FastSync && head.Number.Uint64() > uint64(fsMinFullBlocks) {
  663. return nil, nil, fmt.Errorf("%w: no pivot included along head header", errBadPeer)
  664. }
  665. p.log.Debug("Remote head identified, no pivot", "number", head.Number, "hash", head.Hash())
  666. return head, nil, nil
  667. }
  668. // At this point we have 2 headers in total and the first is the
  669. // validated head of the chian. Check the pivot number and return,
  670. pivot := headers[1]
  671. if pivot.Number.Uint64() != head.Number.Uint64()-uint64(fsMinFullBlocks) {
  672. return nil, nil, fmt.Errorf("%w: remote pivot %d != requested %d", errInvalidChain, pivot.Number, head.Number.Uint64()-uint64(fsMinFullBlocks))
  673. }
  674. return head, pivot, nil
  675. case <-timeout:
  676. p.log.Debug("Waiting for head header timed out", "elapsed", ttl)
  677. return nil, nil, errTimeout
  678. case <-d.bodyCh:
  679. case <-d.receiptCh:
  680. // Out of bounds delivery, ignore
  681. }
  682. }
  683. }
  684. // calculateRequestSpan calculates what headers to request from a peer when trying to determine the
  685. // common ancestor.
  686. // It returns parameters to be used for peer.RequestHeadersByNumber:
  687. // from - starting block number
  688. // count - number of headers to request
  689. // skip - number of headers to skip
  690. // and also returns 'max', the last block which is expected to be returned by the remote peers,
  691. // given the (from,count,skip)
  692. func calculateRequestSpan(remoteHeight, localHeight uint64) (int64, int, int, uint64) {
  693. var (
  694. from int
  695. count int
  696. MaxCount = MaxHeaderFetch / 16
  697. )
  698. // requestHead is the highest block that we will ask for. If requestHead is not offset,
  699. // the highest block that we will get is 16 blocks back from head, which means we
  700. // will fetch 14 or 15 blocks unnecessarily in the case the height difference
  701. // between us and the peer is 1-2 blocks, which is most common
  702. requestHead := int(remoteHeight) - 1
  703. if requestHead < 0 {
  704. requestHead = 0
  705. }
  706. // requestBottom is the lowest block we want included in the query
  707. // Ideally, we want to include the one just below our own head
  708. requestBottom := int(localHeight - 1)
  709. if requestBottom < 0 {
  710. requestBottom = 0
  711. }
  712. totalSpan := requestHead - requestBottom
  713. span := 1 + totalSpan/MaxCount
  714. if span < 2 {
  715. span = 2
  716. }
  717. if span > 16 {
  718. span = 16
  719. }
  720. count = 1 + totalSpan/span
  721. if count > MaxCount {
  722. count = MaxCount
  723. }
  724. if count < 2 {
  725. count = 2
  726. }
  727. from = requestHead - (count-1)*span
  728. if from < 0 {
  729. from = 0
  730. }
  731. max := from + (count-1)*span
  732. return int64(from), count, span - 1, uint64(max)
  733. }
  734. // findAncestor tries to locate the common ancestor link of the local chain and
  735. // a remote peers blockchain. In the general case when our node was in sync and
  736. // on the correct chain, checking the top N links should already get us a match.
  737. // In the rare scenario when we ended up on a long reorganisation (i.e. none of
  738. // the head links match), we do a binary search to find the common ancestor.
  739. func (d *Downloader) findAncestor(p *peerConnection, remoteHeader *types.Header) (uint64, error) {
  740. // Figure out the valid ancestor range to prevent rewrite attacks
  741. var (
  742. floor = int64(-1)
  743. localHeight uint64
  744. remoteHeight = remoteHeader.Number.Uint64()
  745. )
  746. mode := d.getMode()
  747. switch mode {
  748. case FullSync:
  749. localHeight = d.blockchain.CurrentBlock().NumberU64()
  750. case FastSync:
  751. localHeight = d.blockchain.CurrentFastBlock().NumberU64()
  752. default:
  753. localHeight = d.lightchain.CurrentHeader().Number.Uint64()
  754. }
  755. p.log.Debug("Looking for common ancestor", "local", localHeight, "remote", remoteHeight)
  756. // Recap floor value for binary search
  757. maxForkAncestry := fullMaxForkAncestry
  758. if d.getMode() == LightSync {
  759. maxForkAncestry = lightMaxForkAncestry
  760. }
  761. if localHeight >= maxForkAncestry {
  762. // We're above the max reorg threshold, find the earliest fork point
  763. floor = int64(localHeight - maxForkAncestry)
  764. }
  765. // If we're doing a light sync, ensure the floor doesn't go below the CHT, as
  766. // all headers before that point will be missing.
  767. if mode == LightSync {
  768. // If we don't know the current CHT position, find it
  769. if d.genesis == 0 {
  770. header := d.lightchain.CurrentHeader()
  771. for header != nil {
  772. d.genesis = header.Number.Uint64()
  773. if floor >= int64(d.genesis)-1 {
  774. break
  775. }
  776. header = d.lightchain.GetHeaderByHash(header.ParentHash)
  777. }
  778. }
  779. // We already know the "genesis" block number, cap floor to that
  780. if floor < int64(d.genesis)-1 {
  781. floor = int64(d.genesis) - 1
  782. }
  783. }
  784. ancestor, err := d.findAncestorSpanSearch(p, mode, remoteHeight, localHeight, floor)
  785. if err == nil {
  786. return ancestor, nil
  787. }
  788. // The returned error was not nil.
  789. // If the error returned does not reflect that a common ancestor was not found, return it.
  790. // If the error reflects that a common ancestor was not found, continue to binary search,
  791. // where the error value will be reassigned.
  792. if !errors.Is(err, errNoAncestorFound) {
  793. return 0, err
  794. }
  795. ancestor, err = d.findAncestorBinarySearch(p, mode, remoteHeight, floor)
  796. if err != nil {
  797. return 0, err
  798. }
  799. return ancestor, nil
  800. }
  801. func (d *Downloader) findAncestorSpanSearch(p *peerConnection, mode SyncMode, remoteHeight, localHeight uint64, floor int64) (commonAncestor uint64, err error) {
  802. from, count, skip, max := calculateRequestSpan(remoteHeight, localHeight)
  803. p.log.Trace("Span searching for common ancestor", "count", count, "from", from, "skip", skip)
  804. go p.peer.RequestHeadersByNumber(uint64(from), count, skip, false)
  805. // Wait for the remote response to the head fetch
  806. number, hash := uint64(0), common.Hash{}
  807. ttl := d.requestTTL()
  808. timeout := time.After(ttl)
  809. for finished := false; !finished; {
  810. select {
  811. case <-d.cancelCh:
  812. return 0, errCanceled
  813. case packet := <-d.headerCh:
  814. // Discard anything not from the origin peer
  815. if packet.PeerId() != p.id {
  816. log.Debug("Received headers from incorrect peer", "peer", packet.PeerId())
  817. break
  818. }
  819. // Make sure the peer actually gave something valid
  820. headers := packet.(*headerPack).headers
  821. if len(headers) == 0 {
  822. p.log.Warn("Empty head header set")
  823. return 0, errEmptyHeaderSet
  824. }
  825. // Make sure the peer's reply conforms to the request
  826. for i, header := range headers {
  827. expectNumber := from + int64(i)*int64(skip+1)
  828. if number := header.Number.Int64(); number != expectNumber {
  829. p.log.Warn("Head headers broke chain ordering", "index", i, "requested", expectNumber, "received", number)
  830. return 0, fmt.Errorf("%w: %v", errInvalidChain, errors.New("head headers broke chain ordering"))
  831. }
  832. }
  833. // Check if a common ancestor was found
  834. finished = true
  835. for i := len(headers) - 1; i >= 0; i-- {
  836. // Skip any headers that underflow/overflow our requested set
  837. if headers[i].Number.Int64() < from || headers[i].Number.Uint64() > max {
  838. continue
  839. }
  840. // Otherwise check if we already know the header or not
  841. h := headers[i].Hash()
  842. n := headers[i].Number.Uint64()
  843. var known bool
  844. switch mode {
  845. case FullSync:
  846. known = d.blockchain.HasBlock(h, n)
  847. case FastSync:
  848. known = d.blockchain.HasFastBlock(h, n)
  849. default:
  850. known = d.lightchain.HasHeader(h, n)
  851. }
  852. if known {
  853. number, hash = n, h
  854. break
  855. }
  856. }
  857. case <-timeout:
  858. p.log.Debug("Waiting for head header timed out", "elapsed", ttl)
  859. return 0, errTimeout
  860. case <-d.bodyCh:
  861. case <-d.receiptCh:
  862. // Out of bounds delivery, ignore
  863. }
  864. }
  865. // If the head fetch already found an ancestor, return
  866. if hash != (common.Hash{}) {
  867. if int64(number) <= floor {
  868. p.log.Warn("Ancestor below allowance", "number", number, "hash", hash, "allowance", floor)
  869. return 0, errInvalidAncestor
  870. }
  871. p.log.Debug("Found common ancestor", "number", number, "hash", hash)
  872. return number, nil
  873. }
  874. return 0, errNoAncestorFound
  875. }
  876. func (d *Downloader) findAncestorBinarySearch(p *peerConnection, mode SyncMode, remoteHeight uint64, floor int64) (commonAncestor uint64, err error) {
  877. hash := common.Hash{}
  878. // Ancestor not found, we need to binary search over our chain
  879. start, end := uint64(0), remoteHeight
  880. if floor > 0 {
  881. start = uint64(floor)
  882. }
  883. p.log.Trace("Binary searching for common ancestor", "start", start, "end", end)
  884. for start+1 < end {
  885. // Split our chain interval in two, and request the hash to cross check
  886. check := (start + end) / 2
  887. ttl := d.requestTTL()
  888. timeout := time.After(ttl)
  889. go p.peer.RequestHeadersByNumber(check, 1, 0, false)
  890. // Wait until a reply arrives to this request
  891. for arrived := false; !arrived; {
  892. select {
  893. case <-d.cancelCh:
  894. return 0, errCanceled
  895. case packet := <-d.headerCh:
  896. // Discard anything not from the origin peer
  897. if packet.PeerId() != p.id {
  898. log.Debug("Received headers from incorrect peer", "peer", packet.PeerId())
  899. break
  900. }
  901. // Make sure the peer actually gave something valid
  902. headers := packet.(*headerPack).headers
  903. if len(headers) != 1 {
  904. p.log.Warn("Multiple headers for single request", "headers", len(headers))
  905. return 0, fmt.Errorf("%w: multiple headers (%d) for single request", errBadPeer, len(headers))
  906. }
  907. arrived = true
  908. // Modify the search interval based on the response
  909. h := headers[0].Hash()
  910. n := headers[0].Number.Uint64()
  911. var known bool
  912. switch mode {
  913. case FullSync:
  914. known = d.blockchain.HasBlock(h, n)
  915. case FastSync:
  916. known = d.blockchain.HasFastBlock(h, n)
  917. default:
  918. known = d.lightchain.HasHeader(h, n)
  919. }
  920. if !known {
  921. end = check
  922. break
  923. }
  924. header := d.lightchain.GetHeaderByHash(h) // Independent of sync mode, header surely exists
  925. if header == nil {
  926. p.log.Error("header not found", "number", header.Number, "hash", header.Hash(), "request", check)
  927. return 0, fmt.Errorf("%w: header no found (%d)", errBadPeer, header.Number)
  928. }
  929. if header.Number.Uint64() != check {
  930. p.log.Warn("Received non requested header", "number", header.Number, "hash", header.Hash(), "request", check)
  931. return 0, fmt.Errorf("%w: non-requested header (%d)", errBadPeer, header.Number)
  932. }
  933. start = check
  934. hash = h
  935. case <-timeout:
  936. p.log.Debug("Waiting for search header timed out", "elapsed", ttl)
  937. return 0, errTimeout
  938. case <-d.bodyCh:
  939. case <-d.receiptCh:
  940. // Out of bounds delivery, ignore
  941. }
  942. }
  943. }
  944. // Ensure valid ancestry and return
  945. if int64(start) <= floor {
  946. p.log.Warn("Ancestor below allowance", "number", start, "hash", hash, "allowance", floor)
  947. return 0, errInvalidAncestor
  948. }
  949. p.log.Debug("Found common ancestor", "number", start, "hash", hash)
  950. return start, nil
  951. }
  952. // fetchHeaders keeps retrieving headers concurrently from the number
  953. // requested, until no more are returned, potentially throttling on the way. To
  954. // facilitate concurrency but still protect against malicious nodes sending bad
  955. // headers, we construct a header chain skeleton using the "origin" peer we are
  956. // syncing with, and fill in the missing headers using anyone else. Headers from
  957. // other peers are only accepted if they map cleanly to the skeleton. If no one
  958. // can fill in the skeleton - not even the origin peer - it's assumed invalid and
  959. // the origin is dropped.
  960. func (d *Downloader) fetchHeaders(p *peerConnection, from uint64) error {
  961. p.log.Debug("Directing header downloads", "origin", from)
  962. defer p.log.Debug("Header download terminated")
  963. // Create a timeout timer, and the associated header fetcher
  964. skeleton := true // Skeleton assembly phase or finishing up
  965. pivoting := false // Whether the next request is pivot verification
  966. request := time.Now() // time of the last skeleton fetch request
  967. timeout := time.NewTimer(0) // timer to dump a non-responsive active peer
  968. <-timeout.C // timeout channel should be initially empty
  969. defer timeout.Stop()
  970. var ttl time.Duration
  971. getHeaders := func(from uint64) {
  972. request = time.Now()
  973. ttl = d.requestTTL()
  974. timeout.Reset(ttl)
  975. if skeleton {
  976. p.log.Trace("Fetching skeleton headers", "count", MaxHeaderFetch, "from", from)
  977. go p.peer.RequestHeadersByNumber(from+uint64(MaxHeaderFetch)-1, MaxSkeletonSize, MaxHeaderFetch-1, false)
  978. } else {
  979. p.log.Trace("Fetching full headers", "count", MaxHeaderFetch, "from", from)
  980. go p.peer.RequestHeadersByNumber(from, MaxHeaderFetch, 0, false)
  981. }
  982. }
  983. getNextPivot := func() {
  984. pivoting = true
  985. request = time.Now()
  986. ttl = d.requestTTL()
  987. timeout.Reset(ttl)
  988. d.pivotLock.RLock()
  989. pivot := d.pivotHeader.Number.Uint64()
  990. d.pivotLock.RUnlock()
  991. p.log.Trace("Fetching next pivot header", "number", pivot+uint64(fsMinFullBlocks))
  992. go p.peer.RequestHeadersByNumber(pivot+uint64(fsMinFullBlocks), 2, fsMinFullBlocks-9, false) // move +64 when it's 2x64-8 deep
  993. }
  994. // Start pulling the header chain skeleton until all is done
  995. ancestor := from
  996. getHeaders(from)
  997. mode := d.getMode()
  998. for {
  999. select {
  1000. case <-d.cancelCh:
  1001. return errCanceled
  1002. case packet := <-d.headerCh:
  1003. // Make sure the active peer is giving us the skeleton headers
  1004. if packet.PeerId() != p.id {
  1005. log.Debug("Received skeleton from incorrect peer", "peer", packet.PeerId())
  1006. break
  1007. }
  1008. headerReqTimer.UpdateSince(request)
  1009. timeout.Stop()
  1010. // If the pivot is being checked, move if it became stale and run the real retrieval
  1011. var pivot uint64
  1012. d.pivotLock.RLock()
  1013. if d.pivotHeader != nil {
  1014. pivot = d.pivotHeader.Number.Uint64()
  1015. }
  1016. d.pivotLock.RUnlock()
  1017. if pivoting {
  1018. if packet.Items() == 2 {
  1019. // Retrieve the headers and do some sanity checks, just in case
  1020. headers := packet.(*headerPack).headers
  1021. if have, want := headers[0].Number.Uint64(), pivot+uint64(fsMinFullBlocks); have != want {
  1022. log.Warn("Peer sent invalid next pivot", "have", have, "want", want)
  1023. return fmt.Errorf("%w: next pivot number %d != requested %d", errInvalidChain, have, want)
  1024. }
  1025. if have, want := headers[1].Number.Uint64(), pivot+2*uint64(fsMinFullBlocks)-8; have != want {
  1026. log.Warn("Peer sent invalid pivot confirmer", "have", have, "want", want)
  1027. return fmt.Errorf("%w: next pivot confirmer number %d != requested %d", errInvalidChain, have, want)
  1028. }
  1029. log.Warn("Pivot seemingly stale, moving", "old", pivot, "new", headers[0].Number)
  1030. pivot = headers[0].Number.Uint64()
  1031. d.pivotLock.Lock()
  1032. d.pivotHeader = headers[0]
  1033. d.pivotLock.Unlock()
  1034. // Write out the pivot into the database so a rollback beyond
  1035. // it will reenable fast sync and update the state root that
  1036. // the state syncer will be downloading.
  1037. rawdb.WriteLastPivotNumber(d.stateDB, pivot)
  1038. }
  1039. pivoting = false
  1040. getHeaders(from)
  1041. continue
  1042. }
  1043. // If the skeleton's finished, pull any remaining head headers directly from the origin
  1044. if skeleton && packet.Items() == 0 {
  1045. skeleton = false
  1046. getHeaders(from)
  1047. continue
  1048. }
  1049. // If no more headers are inbound, notify the content fetchers and return
  1050. if packet.Items() == 0 {
  1051. // Don't abort header fetches while the pivot is downloading
  1052. if atomic.LoadInt32(&d.committed) == 0 && pivot <= from {
  1053. p.log.Debug("No headers, waiting for pivot commit")
  1054. select {
  1055. case <-time.After(fsHeaderContCheck):
  1056. getHeaders(from)
  1057. continue
  1058. case <-d.cancelCh:
  1059. return errCanceled
  1060. }
  1061. }
  1062. // Pivot done (or not in fast sync) and no more headers, terminate the process
  1063. p.log.Debug("No more headers available")
  1064. select {
  1065. case d.headerProcCh <- nil:
  1066. return nil
  1067. case <-d.cancelCh:
  1068. return errCanceled
  1069. }
  1070. }
  1071. headers := packet.(*headerPack).headers
  1072. // If we received a skeleton batch, resolve internals concurrently
  1073. if skeleton {
  1074. filled, proced, err := d.fillHeaderSkeleton(from, headers)
  1075. if err != nil {
  1076. p.log.Debug("Skeleton chain invalid", "err", err)
  1077. return fmt.Errorf("%w: %v", errInvalidChain, err)
  1078. }
  1079. headers = filled[proced:]
  1080. from += uint64(proced)
  1081. } else {
  1082. // If we're closing in on the chain head, but haven't yet reached it, delay
  1083. // the last few headers so mini reorgs on the head don't cause invalid hash
  1084. // chain errors.
  1085. if n := len(headers); n > 0 {
  1086. // Retrieve the current head we're at
  1087. var head uint64
  1088. if mode == LightSync {
  1089. head = d.lightchain.CurrentHeader().Number.Uint64()
  1090. } else {
  1091. head = d.blockchain.CurrentFastBlock().NumberU64()
  1092. if full := d.blockchain.CurrentBlock().NumberU64(); head < full {
  1093. head = full
  1094. }
  1095. }
  1096. // If the head is below the common ancestor, we're actually deduplicating
  1097. // already existing chain segments, so use the ancestor as the fake head.
  1098. // Otherwise we might end up delaying header deliveries pointlessly.
  1099. if head < ancestor {
  1100. head = ancestor
  1101. }
  1102. // If the head is way older than this batch, delay the last few headers
  1103. if head+uint64(reorgProtThreshold) < headers[n-1].Number.Uint64() {
  1104. delay := reorgProtHeaderDelay
  1105. if delay > n {
  1106. delay = n
  1107. }
  1108. headers = headers[:n-delay]
  1109. }
  1110. }
  1111. }
  1112. // Insert all the new headers and fetch the next batch
  1113. if len(headers) > 0 {
  1114. p.log.Trace("Scheduling new headers", "count", len(headers), "from", from)
  1115. select {
  1116. case d.headerProcCh <- headers:
  1117. case <-d.cancelCh:
  1118. return errCanceled
  1119. }
  1120. from += uint64(len(headers))
  1121. // If we're still skeleton filling fast sync, check pivot staleness
  1122. // before continuing to the next skeleton filling
  1123. if skeleton && pivot > 0 {
  1124. getNextPivot()
  1125. } else {
  1126. getHeaders(from)
  1127. }
  1128. } else {
  1129. // No headers delivered, or all of them being delayed, sleep a bit and retry
  1130. p.log.Trace("All headers delayed, waiting")
  1131. select {
  1132. case <-time.After(fsHeaderContCheck):
  1133. getHeaders(from)
  1134. continue
  1135. case <-d.cancelCh:
  1136. return errCanceled
  1137. }
  1138. }
  1139. case <-timeout.C:
  1140. if d.dropPeer == nil {
  1141. // The dropPeer method is nil when `--copydb` is used for a local copy.
  1142. // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
  1143. p.log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", p.id)
  1144. break
  1145. }
  1146. // Header retrieval timed out, consider the peer bad and drop
  1147. p.log.Debug("Header request timed out", "elapsed", ttl)
  1148. headerTimeoutMeter.Mark(1)
  1149. d.dropPeer(p.id)
  1150. // Finish the sync gracefully instead of dumping the gathered data though
  1151. for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1152. select {
  1153. case ch <- false:
  1154. case <-d.cancelCh:
  1155. }
  1156. }
  1157. select {
  1158. case d.headerProcCh <- nil:
  1159. case <-d.cancelCh:
  1160. }
  1161. return fmt.Errorf("%w: header request timed out", errBadPeer)
  1162. }
  1163. }
  1164. }
  1165. // fillHeaderSkeleton concurrently retrieves headers from all our available peers
  1166. // and maps them to the provided skeleton header chain.
  1167. //
  1168. // Any partial results from the beginning of the skeleton is (if possible) forwarded
  1169. // immediately to the header processor to keep the rest of the pipeline full even
  1170. // in the case of header stalls.
  1171. //
  1172. // The method returns the entire filled skeleton and also the number of headers
  1173. // already forwarded for processing.
  1174. func (d *Downloader) fillHeaderSkeleton(from uint64, skeleton []*types.Header) ([]*types.Header, int, error) {
  1175. log.Debug("Filling up skeleton", "from", from)
  1176. d.queue.ScheduleSkeleton(from, skeleton)
  1177. var (
  1178. deliver = func(packet dataPack) (int, error) {
  1179. pack := packet.(*headerPack)
  1180. return d.queue.DeliverHeaders(pack.peerID, pack.headers, d.headerProcCh)
  1181. }
  1182. expire = func() map[string]int { return d.queue.ExpireHeaders(d.requestTTL()) }
  1183. reserve = func(p *peerConnection, count int) (*fetchRequest, bool, bool) {
  1184. return d.queue.ReserveHeaders(p, count), false, false
  1185. }
  1186. fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchHeaders(req.From, MaxHeaderFetch) }
  1187. capacity = func(p *peerConnection) int { return p.HeaderCapacity(d.requestRTT()) }
  1188. setIdle = func(p *peerConnection, accepted int, deliveryTime time.Time) {
  1189. p.SetHeadersIdle(accepted, deliveryTime)
  1190. }
  1191. )
  1192. err := d.fetchParts(d.headerCh, deliver, d.queue.headerContCh, expire,
  1193. d.queue.PendingHeaders, d.queue.InFlightHeaders, reserve,
  1194. nil, fetch, d.queue.CancelHeaders, capacity, d.peers.HeaderIdlePeers, setIdle, "headers")
  1195. log.Debug("Skeleton fill terminated", "err", err)
  1196. filled, proced := d.queue.RetrieveHeaders()
  1197. return filled, proced, err
  1198. }
  1199. // fetchBodies iteratively downloads the scheduled block bodies, taking any
  1200. // available peers, reserving a chunk of blocks for each, waiting for delivery
  1201. // and also periodically checking for timeouts.
  1202. func (d *Downloader) fetchBodies(from uint64) error {
  1203. log.Debug("Downloading block bodies", "origin", from)
  1204. var (
  1205. deliver = func(packet dataPack) (int, error) {
  1206. pack := packet.(*bodyPack)
  1207. return d.queue.DeliverBodies(pack.peerID, pack.transactions, pack.uncles)
  1208. }
  1209. expire = func() map[string]int { return d.queue.ExpireBodies(d.requestTTL()) }
  1210. fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchBodies(req) }
  1211. capacity = func(p *peerConnection) int { return p.BlockCapacity(d.requestRTT()) }
  1212. setIdle = func(p *peerConnection, accepted int, deliveryTime time.Time) { p.SetBodiesIdle(accepted, deliveryTime) }
  1213. )
  1214. err := d.fetchParts(d.bodyCh, deliver, d.bodyWakeCh, expire,
  1215. d.queue.PendingBlocks, d.queue.InFlightBlocks, d.queue.ReserveBodies,
  1216. d.bodyFetchHook, fetch, d.queue.CancelBodies, capacity, d.peers.BodyIdlePeers, setIdle, "bodies")
  1217. log.Debug("Block body download terminated", "err", err)
  1218. return err
  1219. }
  1220. // fetchReceipts iteratively downloads the scheduled block receipts, taking any
  1221. // available peers, reserving a chunk of receipts for each, waiting for delivery
  1222. // and also periodically checking for timeouts.
  1223. func (d *Downloader) fetchReceipts(from uint64) error {
  1224. log.Debug("Downloading transaction receipts", "origin", from)
  1225. var (
  1226. deliver = func(packet dataPack) (int, error) {
  1227. pack := packet.(*receiptPack)
  1228. return d.queue.DeliverReceipts(pack.peerID, pack.receipts)
  1229. }
  1230. expire = func() map[string]int { return d.queue.ExpireReceipts(d.requestTTL()) }
  1231. fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchReceipts(req) }
  1232. capacity = func(p *peerConnection) int { return p.ReceiptCapacity(d.requestRTT()) }
  1233. setIdle = func(p *peerConnection, accepted int, deliveryTime time.Time) {
  1234. p.SetReceiptsIdle(accepted, deliveryTime)
  1235. }
  1236. )
  1237. err := d.fetchParts(d.receiptCh, deliver, d.receiptWakeCh, expire,
  1238. d.queue.PendingReceipts, d.queue.InFlightReceipts, d.queue.ReserveReceipts,
  1239. d.receiptFetchHook, fetch, d.queue.CancelReceipts, capacity, d.peers.ReceiptIdlePeers, setIdle, "receipts")
  1240. log.Debug("Transaction receipt download terminated", "err", err)
  1241. return err
  1242. }
  1243. // fetchParts iteratively downloads scheduled block parts, taking any available
  1244. // peers, reserving a chunk of fetch requests for each, waiting for delivery and
  1245. // also periodically checking for timeouts.
  1246. //
  1247. // As the scheduling/timeout logic mostly is the same for all downloaded data
  1248. // types, this method is used by each for data gathering and is instrumented with
  1249. // various callbacks to handle the slight differences between processing them.
  1250. //
  1251. // The instrumentation parameters:
  1252. // - errCancel: error type to return if the fetch operation is cancelled (mostly makes logging nicer)
  1253. // - deliveryCh: channel from which to retrieve downloaded data packets (merged from all concurrent peers)
  1254. // - deliver: processing callback to deliver data packets into type specific download queues (usually within `queue`)
  1255. // - wakeCh: notification channel for waking the fetcher when new tasks are available (or sync completed)
  1256. // - expire: task callback method to abort requests that took too long and return the faulty peers (traffic shaping)
  1257. // - pending: task callback for the number of requests still needing download (detect completion/non-completability)
  1258. // - inFlight: task callback for the number of in-progress requests (wait for all active downloads to finish)
  1259. // - throttle: task callback to check if the processing queue is full and activate throttling (bound memory use)
  1260. // - reserve: task callback to reserve new download tasks to a particular peer (also signals partial completions)
  1261. // - fetchHook: tester callback to notify of new tasks being initiated (allows testing the scheduling logic)
  1262. // - fetch: network callback to actually send a particular download request to a physical remote peer
  1263. // - cancel: task callback to abort an in-flight download request and allow rescheduling it (in case of lost peer)
  1264. // - capacity: network callback to retrieve the estimated type-specific bandwidth capacity of a peer (traffic shaping)
  1265. // - idle: network callback to retrieve the currently (type specific) idle peers that can be assigned tasks
  1266. // - setIdle: network callback to set a peer back to idle and update its estimated capacity (traffic shaping)
  1267. // - kind: textual label of the type being downloaded to display in log messages
  1268. func (d *Downloader) fetchParts(deliveryCh chan dataPack, deliver func(dataPack) (int, error), wakeCh chan bool,
  1269. expire func() map[string]int, pending func() int, inFlight func() bool, reserve func(*peerConnection, int) (*fetchRequest, bool, bool),
  1270. fetchHook func([]*types.Header, ...interface{}), fetch func(*peerConnection, *fetchRequest) error, cancel func(*fetchRequest), capacity func(*peerConnection) int,
  1271. idle func() ([]*peerConnection, int), setIdle func(*peerConnection, int, time.Time), kind string) error {
  1272. // Create a ticker to detect expired retrieval tasks
  1273. ticker := time.NewTicker(100 * time.Millisecond)
  1274. defer ticker.Stop()
  1275. update := make(chan struct{}, 1)
  1276. // Prepare the queue and fetch block parts until the block header fetcher's done
  1277. finished := false
  1278. for {
  1279. select {
  1280. case <-d.cancelCh:
  1281. return errCanceled
  1282. case packet := <-deliveryCh:
  1283. deliveryTime := time.Now()
  1284. // If the peer was previously banned and failed to deliver its pack
  1285. // in a reasonable time frame, ignore its message.
  1286. if peer := d.peers.Peer(packet.PeerId()); peer != nil {
  1287. // Deliver the received chunk of data and check chain validity
  1288. accepted, err := deliver(packet)
  1289. if errors.Is(err, errInvalidChain) {
  1290. return err
  1291. }
  1292. // Unless a peer delivered something completely else than requested (usually
  1293. // caused by a timed out request which came through in the end), set it to
  1294. // idle. If the delivery's stale, the peer should have already been idled.
  1295. if !errors.Is(err, errStaleDelivery) {
  1296. setIdle(peer, accepted, deliveryTime)
  1297. }
  1298. // Issue a log to the user to see what's going on
  1299. switch {
  1300. case err == nil && packet.Items() == 0:
  1301. peer.log.Trace("Requested data not delivered", "type", kind)
  1302. case err == nil:
  1303. peer.log.Trace("Delivered new batch of data", "type", kind, "count", packet.Stats())
  1304. default:
  1305. peer.log.Debug("Failed to deliver retrieved data", "type", kind, "err", err)
  1306. }
  1307. }
  1308. // Blocks assembled, try to update the progress
  1309. select {
  1310. case update <- struct{}{}:
  1311. default:
  1312. }
  1313. case cont := <-wakeCh:
  1314. // The header fetcher sent a continuation flag, check if it's done
  1315. if !cont {
  1316. finished = true
  1317. }
  1318. // Headers arrive, try to update the progress
  1319. select {
  1320. case update <- struct{}{}:
  1321. default:
  1322. }
  1323. case <-ticker.C:
  1324. // Sanity check update the progress
  1325. select {
  1326. case update <- struct{}{}:
  1327. default:
  1328. }
  1329. case <-update:
  1330. // Short circuit if we lost all our peers
  1331. if d.peers.Len() == 0 {
  1332. return errNoPeers
  1333. }
  1334. // Check for fetch request timeouts and demote the responsible peers
  1335. for pid, fails := range expire() {
  1336. if peer := d.peers.Peer(pid); peer != nil {
  1337. // If a lot of retrieval elements expired, we might have overestimated the remote peer or perhaps
  1338. // ourselves. Only reset to minimal throughput but don't drop just yet. If even the minimal times
  1339. // out that sync wise we need to get rid of the peer.
  1340. //
  1341. // The reason the minimum threshold is 2 is because the downloader tries to estimate the bandwidth
  1342. // and latency of a peer separately, which requires pushing the measures capacity a bit and seeing
  1343. // how response times reacts, to it always requests one more than the minimum (i.e. min 2).
  1344. if fails > 2 {
  1345. peer.log.Trace("Data delivery timed out", "type", kind)
  1346. setIdle(peer, 0, time.Now())
  1347. } else {
  1348. peer.log.Debug("Stalling delivery, dropping", "type", kind)
  1349. if d.dropPeer == nil {
  1350. // The dropPeer method is nil when `--copydb` is used for a local copy.
  1351. // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
  1352. peer.log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", pid)
  1353. } else {
  1354. d.dropPeer(pid)
  1355. // If this peer was the master peer, abort sync immediately
  1356. d.cancelLock.RLock()
  1357. master := pid == d.cancelPeer
  1358. d.cancelLock.RUnlock()
  1359. if master {
  1360. d.cancel()
  1361. return errTimeout
  1362. }
  1363. }
  1364. }
  1365. }
  1366. }
  1367. // If there's nothing more to fetch, wait or terminate
  1368. if pending() == 0 {
  1369. if !inFlight() && finished {
  1370. log.Debug("Data fetching completed", "type", kind)
  1371. return nil
  1372. }
  1373. break
  1374. }
  1375. // Send a download request to all idle peers, until throttled
  1376. progressed, throttled, running := false, false, inFlight()
  1377. idles, total := idle()
  1378. pendCount := pending()
  1379. for _, peer := range idles {
  1380. // Short circuit if throttling activated
  1381. if throttled {
  1382. break
  1383. }
  1384. // Short circuit if there is no more available task.
  1385. if pendCount = pending(); pendCount == 0 {
  1386. break
  1387. }
  1388. // Reserve a chunk of fetches for a peer. A nil can mean either that
  1389. // no more headers are available, or that the peer is known not to
  1390. // have them.
  1391. request, progress, throttle := reserve(peer, capacity(peer))
  1392. if progress {
  1393. progressed = true
  1394. }
  1395. if throttle {
  1396. throttled = true
  1397. throttleCounter.Inc(1)
  1398. }
  1399. if request == nil {
  1400. continue
  1401. }
  1402. if request.From > 0 {
  1403. peer.log.Trace("Requesting new batch of data", "type", kind, "from", request.From)
  1404. } else {
  1405. peer.log.Trace("Requesting new batch of data", "type", kind, "count", len(request.Headers), "from", request.Headers[0].Number)
  1406. }
  1407. // Fetch the chunk and make sure any errors return the hashes to the queue
  1408. if fetchHook != nil {
  1409. fetchHook(request.Headers, d.getMode(), peer.id)
  1410. }
  1411. if err := fetch(peer, request); err != nil {
  1412. // Although we could try and make an attempt to fix this, this error really
  1413. // means that we've double allocated a fetch task to a peer. If that is the
  1414. // case, the internal state of the downloader and the queue is very wrong so
  1415. // better hard crash and note the error instead of silently accumulating into
  1416. // a much bigger issue.
  1417. panic(fmt.Sprintf("%v: %s fetch assignment failed", peer, kind))
  1418. }
  1419. running = true
  1420. }
  1421. // Make sure that we have peers available for fetching. If all peers have been tried
  1422. // and all failed throw an error
  1423. if !progressed && !throttled && !running && len(idles) == total && pendCount > 0 {
  1424. return errPeersUnavailable
  1425. }
  1426. }
  1427. }
  1428. }
  1429. // processHeaders takes batches of retrieved headers from an input channel and
  1430. // keeps processing and scheduling them into the header chain and downloader's
  1431. // queue until the stream ends or a failure occurs.
  1432. func (d *Downloader) processHeaders(origin uint64, td *big.Int) error {
  1433. // Keep a count of uncertain headers to roll back
  1434. var (
  1435. rollback uint64 // Zero means no rollback (fine as you can't unroll the genesis)
  1436. rollbackErr error
  1437. mode = d.getMode()
  1438. )
  1439. defer func() {
  1440. if rollback > 0 {
  1441. lastHeader, lastFastBlock, lastBlock := d.lightchain.CurrentHeader().Number, common.Big0, common.Big0
  1442. if mode != LightSync {
  1443. lastFastBlock = d.blockchain.CurrentFastBlock().Number()
  1444. lastBlock = d.blockchain.CurrentBlock().Number()
  1445. }
  1446. if err := d.lightchain.SetHead(rollback - 1); err != nil { // -1 to target the parent of the first uncertain block
  1447. // We're already unwinding the stack, only print the error to make it more visible
  1448. log.Error("Failed to roll back chain segment", "head", rollback-1, "err", err)
  1449. }
  1450. curFastBlock, curBlock := common.Big0, common.Big0
  1451. if mode != LightSync {
  1452. curFastBlock = d.blockchain.CurrentFastBlock().Number()
  1453. curBlock = d.blockchain.CurrentBlock().Number()
  1454. }
  1455. log.Warn("Rolled back chain segment",
  1456. "header", fmt.Sprintf("%d->%d", lastHeader, d.lightchain.CurrentHeader().Number),
  1457. "fast", fmt.Sprintf("%d->%d", lastFastBlock, curFastBlock),
  1458. "block", fmt.Sprintf("%d->%d", lastBlock, curBlock), "reason", rollbackErr)
  1459. }
  1460. }()
  1461. // Wait for batches of headers to process
  1462. gotHeaders := false
  1463. for {
  1464. select {
  1465. case <-d.cancelCh:
  1466. rollbackErr = errCanceled
  1467. return errCanceled
  1468. case headers := <-d.headerProcCh:
  1469. // Terminate header processing if we synced up
  1470. if len(headers) == 0 {
  1471. // Notify everyone that headers are fully processed
  1472. for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1473. select {
  1474. case ch <- false:
  1475. case <-d.cancelCh:
  1476. }
  1477. }
  1478. // If no headers were retrieved at all, the peer violated its TD promise that it had a
  1479. // better chain compared to ours. The only exception is if its promised blocks were
  1480. // already imported by other means (e.g. fetcher):
  1481. //
  1482. // R <remote peer>, L <local node>: Both at block 10
  1483. // R: Mine block 11, and propagate it to L
  1484. // L: Queue block 11 for import
  1485. // L: Notice that R's head and TD increased compared to ours, start sync
  1486. // L: Import of block 11 finishes
  1487. // L: Sync begins, and finds common ancestor at 11
  1488. // L: Request new headers up from 11 (R's TD was higher, it must have something)
  1489. // R: Nothing to give
  1490. if mode != LightSync {
  1491. head := d.blockchain.CurrentBlock()
  1492. if !gotHeaders && td.Cmp(d.blockchain.GetTd(head.Hash(), head.NumberU64())) > 0 {
  1493. return errStallingPeer
  1494. }
  1495. }
  1496. // If fast or light syncing, ensure promised headers are indeed delivered. This is
  1497. // needed to detect scenarios where an attacker feeds a bad pivot and then bails out
  1498. // of delivering the post-pivot blocks that would flag the invalid content.
  1499. //
  1500. // This check cannot be executed "as is" for full imports, since blocks may still be
  1501. // queued for processing when the header download completes. However, as long as the
  1502. // peer gave us something useful, we're already happy/progressed (above check).
  1503. if mode == FastSync || mode == LightSync {
  1504. head := d.lightchain.CurrentHeader()
  1505. if td.Cmp(d.lightchain.GetTd(head.Hash(), head.Number.Uint64())) > 0 {
  1506. return errStallingPeer
  1507. }
  1508. }
  1509. // Disable any rollback and return
  1510. rollback = 0
  1511. return nil
  1512. }
  1513. // Otherwise split the chunk of headers into batches and process them
  1514. gotHeaders = true
  1515. for len(headers) > 0 {
  1516. // Terminate if something failed in between processing chunks
  1517. select {
  1518. case <-d.cancelCh:
  1519. rollbackErr = errCanceled
  1520. return errCanceled
  1521. default:
  1522. }
  1523. // Select the next chunk of headers to import
  1524. limit := maxHeadersProcess
  1525. if limit > len(headers) {
  1526. limit = len(headers)
  1527. }
  1528. chunk := headers[:limit]
  1529. // In case of header only syncing, validate the chunk immediately
  1530. if mode == FastSync || mode == LightSync {
  1531. // If we're importing pure headers, verify based on their recentness
  1532. var pivot uint64
  1533. d.pivotLock.RLock()
  1534. if d.pivotHeader != nil {
  1535. pivot = d.pivotHeader.Number.Uint64()
  1536. }
  1537. d.pivotLock.RUnlock()
  1538. frequency := fsHeaderCheckFrequency
  1539. if chunk[len(chunk)-1].Number.Uint64()+uint64(fsHeaderForceVerify) > pivot {
  1540. frequency = 1
  1541. }
  1542. if n, err := d.lightchain.InsertHeaderChain(chunk, frequency); err != nil {
  1543. rollbackErr = err
  1544. // If some headers were inserted, track them as uncertain
  1545. if (mode == FastSync || frequency > 1) && n > 0 && rollback == 0 {
  1546. rollback = chunk[0].Number.Uint64()
  1547. }
  1548. log.Warn("Invalid header encountered", "number", chunk[n].Number, "hash", chunk[n].Hash(), "parent", chunk[n].ParentHash, "err", err)
  1549. return fmt.Errorf("%w: %v", errInvalidChain, err)
  1550. }
  1551. // All verifications passed, track all headers within the alloted limits
  1552. if mode == FastSync {
  1553. head := chunk[len(chunk)-1].Number.Uint64()
  1554. if head-rollback > uint64(fsHeaderSafetyNet) {
  1555. rollback = head - uint64(fsHeaderSafetyNet)
  1556. } else {
  1557. rollback = 1
  1558. }
  1559. }
  1560. }
  1561. // Unless we're doing light chains, schedule the headers for associated content retrieval
  1562. if mode == FullSync || mode == FastSync {
  1563. // If we've reached the allowed number of pending headers, stall a bit
  1564. for d.queue.PendingBlocks() >= maxQueuedHeaders || d.queue.PendingReceipts() >= maxQueuedHeaders {
  1565. select {
  1566. case <-d.cancelCh:
  1567. rollbackErr = errCanceled
  1568. return errCanceled
  1569. case <-time.After(time.Second):
  1570. }
  1571. }
  1572. // Otherwise insert the headers for content retrieval
  1573. inserts := d.queue.Schedule(chunk, origin)
  1574. if len(inserts) != len(chunk) {
  1575. rollbackErr = fmt.Errorf("stale headers: len inserts %v len(chunk) %v", len(inserts), len(chunk))
  1576. return fmt.Errorf("%w: stale headers", errBadPeer)
  1577. }
  1578. }
  1579. headers = headers[limit:]
  1580. origin += uint64(limit)
  1581. }
  1582. // Update the highest block number we know if a higher one is found.
  1583. d.syncStatsLock.Lock()
  1584. if d.syncStatsChainHeight < origin {
  1585. d.syncStatsChainHeight = origin - 1
  1586. }
  1587. d.syncStatsLock.Unlock()
  1588. // Signal the content downloaders of the availablility of new tasks
  1589. for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1590. select {
  1591. case ch <- true:
  1592. default:
  1593. }
  1594. }
  1595. }
  1596. }
  1597. }
  1598. // processFullSyncContent takes fetch results from the queue and imports them into the chain.
  1599. func (d *Downloader) processFullSyncContent() error {
  1600. for {
  1601. results := d.queue.Results(true)
  1602. if len(results) == 0 {
  1603. return nil
  1604. }
  1605. if d.chainInsertHook != nil {
  1606. d.chainInsertHook(results)
  1607. }
  1608. if err := d.importBlockResults(results); err != nil {
  1609. return err
  1610. }
  1611. }
  1612. }
  1613. func (d *Downloader) importBlockResults(results []*fetchResult) error {
  1614. // Check for any early termination requests
  1615. if len(results) == 0 {
  1616. return nil
  1617. }
  1618. select {
  1619. case <-d.quitCh:
  1620. return errCancelContentProcessing
  1621. default:
  1622. }
  1623. // Retrieve the a batch of results to import
  1624. first, last := results[0].Header, results[len(results)-1].Header
  1625. log.Debug("Inserting downloaded chain", "items", len(results),
  1626. "firstnum", first.Number, "firsthash", first.Hash(),
  1627. "lastnum", last.Number, "lasthash", last.Hash(),
  1628. )
  1629. blocks := make([]*types.Block, len(results))
  1630. for i, result := range results {
  1631. blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1632. }
  1633. if index, err := d.blockchain.InsertChain(blocks); err != nil {
  1634. if index < len(results) {
  1635. log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err)
  1636. } else {
  1637. // The InsertChain method in blockchain.go will sometimes return an out-of-bounds index,
  1638. // when it needs to preprocess blocks to import a sidechain.
  1639. // The importer will put together a new list of blocks to import, which is a superset
  1640. // of the blocks delivered from the downloader, and the indexing will be off.
  1641. log.Debug("Downloaded item processing failed on sidechain import", "index", index, "err", err)
  1642. }
  1643. return fmt.Errorf("%w: %v", errInvalidChain, err)
  1644. }
  1645. return nil
  1646. }
  1647. // processFastSyncContent takes fetch results from the queue and writes them to the
  1648. // database. It also controls the synchronisation of state nodes of the pivot block.
  1649. func (d *Downloader) processFastSyncContent() error {
  1650. // Start syncing state of the reported head block. This should get us most of
  1651. // the state of the pivot block.
  1652. d.pivotLock.RLock()
  1653. sync := d.syncState(d.pivotHeader.Root)
  1654. d.pivotLock.RUnlock()
  1655. defer func() {
  1656. // The `sync` object is replaced every time the pivot moves. We need to
  1657. // defer close the very last active one, hence the lazy evaluation vs.
  1658. // calling defer sync.Cancel() !!!
  1659. sync.Cancel()
  1660. }()
  1661. closeOnErr := func(s *stateSync) {
  1662. if err := s.Wait(); err != nil && err != errCancelStateFetch && err != errCanceled && err != snap.ErrCancelled {
  1663. d.queue.Close() // wake up Results
  1664. }
  1665. }
  1666. go closeOnErr(sync)
  1667. // To cater for moving pivot points, track the pivot block and subsequently
  1668. // accumulated download results separately.
  1669. var (
  1670. oldPivot *fetchResult // Locked in pivot block, might change eventually
  1671. oldTail []*fetchResult // Downloaded content after the pivot
  1672. )
  1673. for {
  1674. // Wait for the next batch of downloaded data to be available, and if the pivot
  1675. // block became stale, move the goalpost
  1676. results := d.queue.Results(oldPivot == nil) // Block if we're not monitoring pivot staleness
  1677. if len(results) == 0 {
  1678. // If pivot sync is done, stop
  1679. if oldPivot == nil {
  1680. return sync.Cancel()
  1681. }
  1682. // If sync failed, stop
  1683. select {
  1684. case <-d.cancelCh:
  1685. sync.Cancel()
  1686. return errCanceled
  1687. default:
  1688. }
  1689. }
  1690. if d.chainInsertHook != nil {
  1691. d.chainInsertHook(results)
  1692. }
  1693. // If we haven't downloaded the pivot block yet, check pivot staleness
  1694. // notifications from the header downloader
  1695. d.pivotLock.RLock()
  1696. pivot := d.pivotHeader
  1697. d.pivotLock.RUnlock()
  1698. if oldPivot == nil {
  1699. if pivot.Root != sync.root {
  1700. sync.Cancel()
  1701. sync = d.syncState(pivot.Root)
  1702. go closeOnErr(sync)
  1703. }
  1704. } else {
  1705. results = append(append([]*fetchResult{oldPivot}, oldTail...), results...)
  1706. }
  1707. // Split around the pivot block and process the two sides via fast/full sync
  1708. if atomic.LoadInt32(&d.committed) == 0 {
  1709. latest := results[len(results)-1].Header
  1710. // If the height is above the pivot block by 2 sets, it means the pivot
  1711. // become stale in the network and it was garbage collected, move to a
  1712. // new pivot.
  1713. //
  1714. // Note, we have `reorgProtHeaderDelay` number of blocks withheld, Those
  1715. // need to be taken into account, otherwise we're detecting the pivot move
  1716. // late and will drop peers due to unavailable state!!!
  1717. if height := latest.Number.Uint64(); height >= pivot.Number.Uint64()+2*uint64(fsMinFullBlocks)-uint64(reorgProtHeaderDelay) {
  1718. log.Warn("Pivot became stale, moving", "old", pivot.Number.Uint64(), "new", height-uint64(fsMinFullBlocks)+uint64(reorgProtHeaderDelay))
  1719. pivot = results[len(results)-1-fsMinFullBlocks+reorgProtHeaderDelay].Header // must exist as lower old pivot is uncommitted
  1720. d.pivotLock.Lock()
  1721. d.pivotHeader = pivot
  1722. d.pivotLock.Unlock()
  1723. // Write out the pivot into the database so a rollback beyond it will
  1724. // reenable fast sync
  1725. rawdb.WriteLastPivotNumber(d.stateDB, pivot.Number.Uint64())
  1726. }
  1727. }
  1728. P, beforeP, afterP := splitAroundPivot(pivot.Number.Uint64(), results)
  1729. if err := d.commitFastSyncData(beforeP, sync); err != nil {
  1730. return err
  1731. }
  1732. if P != nil {
  1733. // If new pivot block found, cancel old state retrieval and restart
  1734. if oldPivot != P {
  1735. sync.Cancel()
  1736. sync = d.syncState(P.Header.Root)
  1737. go closeOnErr(sync)
  1738. oldPivot = P
  1739. }
  1740. // Wait for completion, occasionally checking for pivot staleness
  1741. select {
  1742. case <-sync.done:
  1743. if sync.err != nil {
  1744. return sync.err
  1745. }
  1746. if err := d.commitPivotBlock(P); err != nil {
  1747. return err
  1748. }
  1749. oldPivot = nil
  1750. case <-time.After(time.Second):
  1751. oldTail = afterP
  1752. continue
  1753. }
  1754. }
  1755. // Fast sync done, pivot commit done, full import
  1756. if err := d.importBlockResults(afterP); err != nil {
  1757. return err
  1758. }
  1759. }
  1760. }
  1761. func splitAroundPivot(pivot uint64, results []*fetchResult) (p *fetchResult, before, after []*fetchResult) {
  1762. if len(results) == 0 {
  1763. return nil, nil, nil
  1764. }
  1765. if lastNum := results[len(results)-1].Header.Number.Uint64(); lastNum < pivot {
  1766. // the pivot is somewhere in the future
  1767. return nil, results, nil
  1768. }
  1769. // This can also be optimized, but only happens very seldom
  1770. for _, result := range results {
  1771. num := result.Header.Number.Uint64()
  1772. switch {
  1773. case num < pivot:
  1774. before = append(before, result)
  1775. case num == pivot:
  1776. p = result
  1777. default:
  1778. after = append(after, result)
  1779. }
  1780. }
  1781. return p, before, after
  1782. }
  1783. func (d *Downloader) commitFastSyncData(results []*fetchResult, stateSync *stateSync) error {
  1784. // Check for any early termination requests
  1785. if len(results) == 0 {
  1786. return nil
  1787. }
  1788. select {
  1789. case <-d.quitCh:
  1790. return errCancelContentProcessing
  1791. case <-stateSync.done:
  1792. if err := stateSync.Wait(); err != nil {
  1793. return err
  1794. }
  1795. default:
  1796. }
  1797. // Retrieve the a batch of results to import
  1798. first, last := results[0].Header, results[len(results)-1].Header
  1799. log.Debug("Inserting fast-sync blocks", "items", len(results),
  1800. "firstnum", first.Number, "firsthash", first.Hash(),
  1801. "lastnumn", last.Number, "lasthash", last.Hash(),
  1802. )
  1803. blocks := make([]*types.Block, len(results))
  1804. receipts := make([]types.Receipts, len(results))
  1805. for i, result := range results {
  1806. blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1807. receipts[i] = result.Receipts
  1808. }
  1809. if index, err := d.blockchain.InsertReceiptChain(blocks, receipts, d.ancientLimit); err != nil {
  1810. log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err)
  1811. return fmt.Errorf("%w: %v", errInvalidChain, err)
  1812. }
  1813. return nil
  1814. }
  1815. func (d *Downloader) commitPivotBlock(result *fetchResult) error {
  1816. block := types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1817. log.Debug("Committing fast sync pivot as new head", "number", block.Number(), "hash", block.Hash())
  1818. // Commit the pivot block as the new head, will require full sync from here on
  1819. if _, err := d.blockchain.InsertReceiptChain([]*types.Block{block}, []types.Receipts{result.Receipts}, d.ancientLimit); err != nil {
  1820. return err
  1821. }
  1822. if err := d.blockchain.FastSyncCommitHead(block.Hash()); err != nil {
  1823. return err
  1824. }
  1825. atomic.StoreInt32(&d.committed, 1)
  1826. // If we had a bloom filter for the state sync, deallocate it now. Note, we only
  1827. // deallocate internally, but keep the empty wrapper. This ensures that if we do
  1828. // a rollback after committing the pivot and restarting fast sync, we don't end
  1829. // up using a nil bloom. Empty bloom is fine, it just returns that it does not
  1830. // have the info we need, so reach down to the database instead.
  1831. if d.stateBloom != nil {
  1832. d.stateBloom.Close()
  1833. }
  1834. return nil
  1835. }
  1836. // DeliverHeaders injects a new batch of block headers received from a remote
  1837. // node into the download schedule.
  1838. func (d *Downloader) DeliverHeaders(id string, headers []*types.Header) error {
  1839. return d.deliver(d.headerCh, &headerPack{id, headers}, headerInMeter, headerDropMeter)
  1840. }
  1841. // DeliverBodies injects a new batch of block bodies received from a remote node.
  1842. func (d *Downloader) DeliverBodies(id string, transactions [][]*types.Transaction, uncles [][]*types.Header) error {
  1843. return d.deliver(d.bodyCh, &bodyPack{id, transactions, uncles}, bodyInMeter, bodyDropMeter)
  1844. }
  1845. // DeliverReceipts injects a new batch of receipts received from a remote node.
  1846. func (d *Downloader) DeliverReceipts(id string, receipts [][]*types.Receipt) error {
  1847. return d.deliver(d.receiptCh, &receiptPack{id, receipts}, receiptInMeter, receiptDropMeter)
  1848. }
  1849. // DeliverNodeData injects a new batch of node state data received from a remote node.
  1850. func (d *Downloader) DeliverNodeData(id string, data [][]byte) error {
  1851. return d.deliver(d.stateCh, &statePack{id, data}, stateInMeter, stateDropMeter)
  1852. }
  1853. // DeliverSnapPacket is invoked from a peer's message handler when it transmits a
  1854. // data packet for the local node to consume.
  1855. func (d *Downloader) DeliverSnapPacket(peer *snap.Peer, packet snap.Packet) error {
  1856. switch packet := packet.(type) {
  1857. case *snap.AccountRangePacket:
  1858. hashes, accounts, err := packet.Unpack()
  1859. if err != nil {
  1860. return err
  1861. }
  1862. return d.SnapSyncer.OnAccounts(peer, packet.ID, hashes, accounts, packet.Proof)
  1863. case *snap.StorageRangesPacket:
  1864. hashset, slotset := packet.Unpack()
  1865. return d.SnapSyncer.OnStorage(peer, packet.ID, hashset, slotset, packet.Proof)
  1866. case *snap.ByteCodesPacket:
  1867. return d.SnapSyncer.OnByteCodes(peer, packet.ID, packet.Codes)
  1868. case *snap.TrieNodesPacket:
  1869. return d.SnapSyncer.OnTrieNodes(peer, packet.ID, packet.Nodes)
  1870. default:
  1871. return fmt.Errorf("unexpected snap packet type: %T", packet)
  1872. }
  1873. }
  1874. // deliver injects a new batch of data received from a remote node.
  1875. func (d *Downloader) deliver(destCh chan dataPack, packet dataPack, inMeter, dropMeter metrics.Meter) (err error) {
  1876. // Update the delivery metrics for both good and failed deliveries
  1877. inMeter.Mark(int64(packet.Items()))
  1878. defer func() {
  1879. if err != nil {
  1880. dropMeter.Mark(int64(packet.Items()))
  1881. }
  1882. }()
  1883. // Deliver or abort if the sync is canceled while queuing
  1884. d.cancelLock.RLock()
  1885. cancel := d.cancelCh
  1886. d.cancelLock.RUnlock()
  1887. if cancel == nil {
  1888. return errNoSyncActive
  1889. }
  1890. select {
  1891. case destCh <- packet:
  1892. return nil
  1893. case <-cancel:
  1894. return errNoSyncActive
  1895. }
  1896. }
  1897. // qosTuner is the quality of service tuning loop that occasionally gathers the
  1898. // peer latency statistics and updates the estimated request round trip time.
  1899. func (d *Downloader) qosTuner() {
  1900. for {
  1901. // Retrieve the current median RTT and integrate into the previoust target RTT
  1902. rtt := time.Duration((1-qosTuningImpact)*float64(atomic.LoadUint64(&d.rttEstimate)) + qosTuningImpact*float64(d.peers.medianRTT()))
  1903. atomic.StoreUint64(&d.rttEstimate, uint64(rtt))
  1904. // A new RTT cycle passed, increase our confidence in the estimated RTT
  1905. conf := atomic.LoadUint64(&d.rttConfidence)
  1906. conf = conf + (1000000-conf)/2
  1907. atomic.StoreUint64(&d.rttConfidence, conf)
  1908. // Log the new QoS values and sleep until the next RTT
  1909. log.Debug("Recalculated downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL())
  1910. select {
  1911. case <-d.quitCh:
  1912. return
  1913. case <-time.After(rtt):
  1914. }
  1915. }
  1916. }
  1917. // qosReduceConfidence is meant to be called when a new peer joins the downloader's
  1918. // peer set, needing to reduce the confidence we have in out QoS estimates.
  1919. func (d *Downloader) qosReduceConfidence() {
  1920. // If we have a single peer, confidence is always 1
  1921. peers := uint64(d.peers.Len())
  1922. if peers == 0 {
  1923. // Ensure peer connectivity races don't catch us off guard
  1924. return
  1925. }
  1926. if peers == 1 {
  1927. atomic.StoreUint64(&d.rttConfidence, 1000000)
  1928. return
  1929. }
  1930. // If we have a ton of peers, don't drop confidence)
  1931. if peers >= uint64(qosConfidenceCap) {
  1932. return
  1933. }
  1934. // Otherwise drop the confidence factor
  1935. conf := atomic.LoadUint64(&d.rttConfidence) * (peers - 1) / peers
  1936. if float64(conf)/1000000 < rttMinConfidence {
  1937. conf = uint64(rttMinConfidence * 1000000)
  1938. }
  1939. atomic.StoreUint64(&d.rttConfidence, conf)
  1940. rtt := time.Duration(atomic.LoadUint64(&d.rttEstimate))
  1941. log.Debug("Relaxed downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL())
  1942. }
  1943. // requestRTT returns the current target round trip time for a download request
  1944. // to complete in.
  1945. //
  1946. // Note, the returned RTT is .9 of the actually estimated RTT. The reason is that
  1947. // the downloader tries to adapt queries to the RTT, so multiple RTT values can
  1948. // be adapted to, but smaller ones are preferred (stabler download stream).
  1949. func (d *Downloader) requestRTT() time.Duration {
  1950. return time.Duration(atomic.LoadUint64(&d.rttEstimate)) * 9 / 10
  1951. }
  1952. // requestTTL returns the current timeout allowance for a single download request
  1953. // to finish under.
  1954. func (d *Downloader) requestTTL() time.Duration {
  1955. var (
  1956. rtt = time.Duration(atomic.LoadUint64(&d.rttEstimate))
  1957. conf = float64(atomic.LoadUint64(&d.rttConfidence)) / 1000000.0
  1958. )
  1959. ttl := time.Duration(ttlScaling) * time.Duration(float64(rtt)/conf)
  1960. if ttl > ttlLimit {
  1961. ttl = ttlLimit
  1962. }
  1963. return ttl
  1964. }