downloader.go 70 KB

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