downloader.go 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894
  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. // Rollback removes a few recently added elements from the local chain.
  151. Rollback([]common.Hash)
  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. }
  411. }
  412. d.committed = 1
  413. if mode == FastSync && pivot != 0 {
  414. d.committed = 0
  415. }
  416. if mode == FastSync {
  417. // Set the ancient data limitation.
  418. // If we are running fast sync, all block data older than ancientLimit will be
  419. // written to the ancient store. More recent data will be written to the active
  420. // database and will wait for the freezer to migrate.
  421. //
  422. // If there is a checkpoint available, then calculate the ancientLimit through
  423. // that. Otherwise calculate the ancient limit through the advertised height
  424. // of the remote peer.
  425. //
  426. // The reason for picking checkpoint first is that a malicious peer can give us
  427. // a fake (very high) height, forcing the ancient limit to also be very high.
  428. // The peer would start to feed us valid blocks until head, resulting in all of
  429. // the blocks might be written into the ancient store. A following mini-reorg
  430. // could cause issues.
  431. if d.checkpoint != 0 && d.checkpoint > fullMaxForkAncestry+1 {
  432. d.ancientLimit = d.checkpoint
  433. } else if height > fullMaxForkAncestry+1 {
  434. d.ancientLimit = height - fullMaxForkAncestry - 1
  435. }
  436. frozen, _ := d.stateDB.Ancients() // Ignore the error here since light client can also hit here.
  437. // If a part of blockchain data has already been written into active store,
  438. // disable the ancient style insertion explicitly.
  439. if origin >= frozen && frozen != 0 {
  440. d.ancientLimit = 0
  441. log.Info("Disabling direct-ancient mode", "origin", origin, "ancient", frozen-1)
  442. } else if d.ancientLimit > 0 {
  443. log.Debug("Enabling direct-ancient mode", "ancient", d.ancientLimit)
  444. }
  445. // Rewind the ancient store and blockchain if reorg happens.
  446. if origin+1 < frozen {
  447. var hashes []common.Hash
  448. for i := origin + 1; i < d.lightchain.CurrentHeader().Number.Uint64(); i++ {
  449. hashes = append(hashes, rawdb.ReadCanonicalHash(d.stateDB, i))
  450. }
  451. d.lightchain.Rollback(hashes)
  452. }
  453. }
  454. // Initiate the sync using a concurrent header and content retrieval algorithm
  455. d.queue.Prepare(origin+1, mode)
  456. if d.syncInitHook != nil {
  457. d.syncInitHook(origin, height)
  458. }
  459. fetchers := []func() error{
  460. func() error { return d.fetchHeaders(p, origin+1, pivot) }, // Headers are always retrieved
  461. func() error { return d.fetchBodies(origin + 1) }, // Bodies are retrieved during normal and fast sync
  462. func() error { return d.fetchReceipts(origin + 1) }, // Receipts are retrieved during fast sync
  463. func() error { return d.processHeaders(origin+1, pivot, td) },
  464. }
  465. if mode == FastSync {
  466. fetchers = append(fetchers, func() error { return d.processFastSyncContent(latest) })
  467. } else if mode == FullSync {
  468. fetchers = append(fetchers, d.processFullSyncContent)
  469. }
  470. return d.spawnSync(fetchers)
  471. }
  472. // spawnSync runs d.process and all given fetcher functions to completion in
  473. // separate goroutines, returning the first error that appears.
  474. func (d *Downloader) spawnSync(fetchers []func() error) error {
  475. errc := make(chan error, len(fetchers))
  476. d.cancelWg.Add(len(fetchers))
  477. for _, fn := range fetchers {
  478. fn := fn
  479. go func() { defer d.cancelWg.Done(); errc <- fn() }()
  480. }
  481. // Wait for the first error, then terminate the others.
  482. var err error
  483. for i := 0; i < len(fetchers); i++ {
  484. if i == len(fetchers)-1 {
  485. // Close the queue when all fetchers have exited.
  486. // This will cause the block processor to end when
  487. // it has processed the queue.
  488. d.queue.Close()
  489. }
  490. if err = <-errc; err != nil && err != errCanceled {
  491. break
  492. }
  493. }
  494. d.queue.Close()
  495. d.Cancel()
  496. return err
  497. }
  498. // cancel aborts all of the operations and resets the queue. However, cancel does
  499. // not wait for the running download goroutines to finish. This method should be
  500. // used when cancelling the downloads from inside the downloader.
  501. func (d *Downloader) cancel() {
  502. // Close the current cancel channel
  503. d.cancelLock.Lock()
  504. defer d.cancelLock.Unlock()
  505. if d.cancelCh != nil {
  506. select {
  507. case <-d.cancelCh:
  508. // Channel was already closed
  509. default:
  510. close(d.cancelCh)
  511. }
  512. }
  513. }
  514. // Cancel aborts all of the operations and waits for all download goroutines to
  515. // finish before returning.
  516. func (d *Downloader) Cancel() {
  517. d.cancel()
  518. d.cancelWg.Wait()
  519. d.ancientLimit = 0
  520. log.Debug("Reset ancient limit to zero")
  521. }
  522. // Terminate interrupts the downloader, canceling all pending operations.
  523. // The downloader cannot be reused after calling Terminate.
  524. func (d *Downloader) Terminate() {
  525. // Close the termination channel (make sure double close is allowed)
  526. d.quitLock.Lock()
  527. select {
  528. case <-d.quitCh:
  529. default:
  530. close(d.quitCh)
  531. }
  532. if d.stateBloom != nil {
  533. d.stateBloom.Close()
  534. }
  535. d.quitLock.Unlock()
  536. // Cancel any pending download requests
  537. d.Cancel()
  538. }
  539. // fetchHeight retrieves the head header of the remote peer to aid in estimating
  540. // the total time a pending synchronisation would take.
  541. func (d *Downloader) fetchHeight(p *peerConnection) (*types.Header, error) {
  542. p.log.Debug("Retrieving remote chain height")
  543. // Request the advertised remote head block and wait for the response
  544. head, _ := p.peer.Head()
  545. go p.peer.RequestHeadersByHash(head, 1, 0, false)
  546. ttl := d.requestTTL()
  547. timeout := time.After(ttl)
  548. mode := d.getMode()
  549. for {
  550. select {
  551. case <-d.cancelCh:
  552. return nil, errCanceled
  553. case packet := <-d.headerCh:
  554. // Discard anything not from the origin peer
  555. if packet.PeerId() != p.id {
  556. log.Debug("Received headers from incorrect peer", "peer", packet.PeerId())
  557. break
  558. }
  559. // Make sure the peer actually gave something valid
  560. headers := packet.(*headerPack).headers
  561. if len(headers) != 1 {
  562. p.log.Warn("Multiple headers for single request", "headers", len(headers))
  563. return nil, fmt.Errorf("%w: multiple headers (%d) for single request", errBadPeer, len(headers))
  564. }
  565. head := headers[0]
  566. if (mode == FastSync || mode == LightSync) && head.Number.Uint64() < d.checkpoint {
  567. p.log.Warn("Remote head below checkpoint", "number", head.Number, "hash", head.Hash())
  568. return nil, errUnsyncedPeer
  569. }
  570. p.log.Debug("Remote head header identified", "number", head.Number, "hash", head.Hash())
  571. return head, nil
  572. case <-timeout:
  573. p.log.Debug("Waiting for head header timed out", "elapsed", ttl)
  574. return nil, errTimeout
  575. case <-d.bodyCh:
  576. case <-d.receiptCh:
  577. // Out of bounds delivery, ignore
  578. }
  579. }
  580. }
  581. // calculateRequestSpan calculates what headers to request from a peer when trying to determine the
  582. // common ancestor.
  583. // It returns parameters to be used for peer.RequestHeadersByNumber:
  584. // from - starting block number
  585. // count - number of headers to request
  586. // skip - number of headers to skip
  587. // and also returns 'max', the last block which is expected to be returned by the remote peers,
  588. // given the (from,count,skip)
  589. func calculateRequestSpan(remoteHeight, localHeight uint64) (int64, int, int, uint64) {
  590. var (
  591. from int
  592. count int
  593. MaxCount = MaxHeaderFetch / 16
  594. )
  595. // requestHead is the highest block that we will ask for. If requestHead is not offset,
  596. // the highest block that we will get is 16 blocks back from head, which means we
  597. // will fetch 14 or 15 blocks unnecessarily in the case the height difference
  598. // between us and the peer is 1-2 blocks, which is most common
  599. requestHead := int(remoteHeight) - 1
  600. if requestHead < 0 {
  601. requestHead = 0
  602. }
  603. // requestBottom is the lowest block we want included in the query
  604. // Ideally, we want to include the one just below our own head
  605. requestBottom := int(localHeight - 1)
  606. if requestBottom < 0 {
  607. requestBottom = 0
  608. }
  609. totalSpan := requestHead - requestBottom
  610. span := 1 + totalSpan/MaxCount
  611. if span < 2 {
  612. span = 2
  613. }
  614. if span > 16 {
  615. span = 16
  616. }
  617. count = 1 + totalSpan/span
  618. if count > MaxCount {
  619. count = MaxCount
  620. }
  621. if count < 2 {
  622. count = 2
  623. }
  624. from = requestHead - (count-1)*span
  625. if from < 0 {
  626. from = 0
  627. }
  628. max := from + (count-1)*span
  629. return int64(from), count, span - 1, uint64(max)
  630. }
  631. // findAncestor tries to locate the common ancestor link of the local chain and
  632. // a remote peers blockchain. In the general case when our node was in sync and
  633. // on the correct chain, checking the top N links should already get us a match.
  634. // In the rare scenario when we ended up on a long reorganisation (i.e. none of
  635. // the head links match), we do a binary search to find the common ancestor.
  636. func (d *Downloader) findAncestor(p *peerConnection, remoteHeader *types.Header) (uint64, error) {
  637. // Figure out the valid ancestor range to prevent rewrite attacks
  638. var (
  639. floor = int64(-1)
  640. localHeight uint64
  641. remoteHeight = remoteHeader.Number.Uint64()
  642. )
  643. mode := d.getMode()
  644. switch mode {
  645. case FullSync:
  646. localHeight = d.blockchain.CurrentBlock().NumberU64()
  647. case FastSync:
  648. localHeight = d.blockchain.CurrentFastBlock().NumberU64()
  649. default:
  650. localHeight = d.lightchain.CurrentHeader().Number.Uint64()
  651. }
  652. p.log.Debug("Looking for common ancestor", "local", localHeight, "remote", remoteHeight)
  653. // Recap floor value for binary search
  654. maxForkAncestry := fullMaxForkAncestry
  655. if d.getMode() == LightSync {
  656. maxForkAncestry = lightMaxForkAncestry
  657. }
  658. if localHeight >= maxForkAncestry {
  659. // We're above the max reorg threshold, find the earliest fork point
  660. floor = int64(localHeight - maxForkAncestry)
  661. }
  662. // If we're doing a light sync, ensure the floor doesn't go below the CHT, as
  663. // all headers before that point will be missing.
  664. if mode == LightSync {
  665. // If we don't know the current CHT position, find it
  666. if d.genesis == 0 {
  667. header := d.lightchain.CurrentHeader()
  668. for header != nil {
  669. d.genesis = header.Number.Uint64()
  670. if floor >= int64(d.genesis)-1 {
  671. break
  672. }
  673. header = d.lightchain.GetHeaderByHash(header.ParentHash)
  674. }
  675. }
  676. // We already know the "genesis" block number, cap floor to that
  677. if floor < int64(d.genesis)-1 {
  678. floor = int64(d.genesis) - 1
  679. }
  680. }
  681. from, count, skip, max := calculateRequestSpan(remoteHeight, localHeight)
  682. p.log.Trace("Span searching for common ancestor", "count", count, "from", from, "skip", skip)
  683. go p.peer.RequestHeadersByNumber(uint64(from), count, skip, false)
  684. // Wait for the remote response to the head fetch
  685. number, hash := uint64(0), common.Hash{}
  686. ttl := d.requestTTL()
  687. timeout := time.After(ttl)
  688. for finished := false; !finished; {
  689. select {
  690. case <-d.cancelCh:
  691. return 0, errCanceled
  692. case packet := <-d.headerCh:
  693. // Discard anything not from the origin peer
  694. if packet.PeerId() != p.id {
  695. log.Debug("Received headers from incorrect peer", "peer", packet.PeerId())
  696. break
  697. }
  698. // Make sure the peer actually gave something valid
  699. headers := packet.(*headerPack).headers
  700. if len(headers) == 0 {
  701. p.log.Warn("Empty head header set")
  702. return 0, errEmptyHeaderSet
  703. }
  704. // Make sure the peer's reply conforms to the request
  705. for i, header := range headers {
  706. expectNumber := from + int64(i)*int64(skip+1)
  707. if number := header.Number.Int64(); number != expectNumber {
  708. p.log.Warn("Head headers broke chain ordering", "index", i, "requested", expectNumber, "received", number)
  709. return 0, fmt.Errorf("%w: %v", errInvalidChain, errors.New("head headers broke chain ordering"))
  710. }
  711. }
  712. // Check if a common ancestor was found
  713. finished = true
  714. for i := len(headers) - 1; i >= 0; i-- {
  715. // Skip any headers that underflow/overflow our requested set
  716. if headers[i].Number.Int64() < from || headers[i].Number.Uint64() > max {
  717. continue
  718. }
  719. // Otherwise check if we already know the header or not
  720. h := headers[i].Hash()
  721. n := headers[i].Number.Uint64()
  722. var known bool
  723. switch mode {
  724. case FullSync:
  725. known = d.blockchain.HasBlock(h, n)
  726. case FastSync:
  727. known = d.blockchain.HasFastBlock(h, n)
  728. default:
  729. known = d.lightchain.HasHeader(h, n)
  730. }
  731. if known {
  732. number, hash = n, h
  733. break
  734. }
  735. }
  736. case <-timeout:
  737. p.log.Debug("Waiting for head header timed out", "elapsed", ttl)
  738. return 0, errTimeout
  739. case <-d.bodyCh:
  740. case <-d.receiptCh:
  741. // Out of bounds delivery, ignore
  742. }
  743. }
  744. // If the head fetch already found an ancestor, return
  745. if hash != (common.Hash{}) {
  746. if int64(number) <= floor {
  747. p.log.Warn("Ancestor below allowance", "number", number, "hash", hash, "allowance", floor)
  748. return 0, errInvalidAncestor
  749. }
  750. p.log.Debug("Found common ancestor", "number", number, "hash", hash)
  751. return number, nil
  752. }
  753. // Ancestor not found, we need to binary search over our chain
  754. start, end := uint64(0), remoteHeight
  755. if floor > 0 {
  756. start = uint64(floor)
  757. }
  758. p.log.Trace("Binary searching for common ancestor", "start", start, "end", end)
  759. for start+1 < end {
  760. // Split our chain interval in two, and request the hash to cross check
  761. check := (start + end) / 2
  762. ttl := d.requestTTL()
  763. timeout := time.After(ttl)
  764. go p.peer.RequestHeadersByNumber(check, 1, 0, false)
  765. // Wait until a reply arrives to this request
  766. for arrived := false; !arrived; {
  767. select {
  768. case <-d.cancelCh:
  769. return 0, errCanceled
  770. case packer := <-d.headerCh:
  771. // Discard anything not from the origin peer
  772. if packer.PeerId() != p.id {
  773. log.Debug("Received headers from incorrect peer", "peer", packer.PeerId())
  774. break
  775. }
  776. // Make sure the peer actually gave something valid
  777. headers := packer.(*headerPack).headers
  778. if len(headers) != 1 {
  779. p.log.Warn("Multiple headers for single request", "headers", len(headers))
  780. return 0, fmt.Errorf("%w: multiple headers (%d) for single request", errBadPeer, len(headers))
  781. }
  782. arrived = true
  783. // Modify the search interval based on the response
  784. h := headers[0].Hash()
  785. n := headers[0].Number.Uint64()
  786. var known bool
  787. switch mode {
  788. case FullSync:
  789. known = d.blockchain.HasBlock(h, n)
  790. case FastSync:
  791. known = d.blockchain.HasFastBlock(h, n)
  792. default:
  793. known = d.lightchain.HasHeader(h, n)
  794. }
  795. if !known {
  796. end = check
  797. break
  798. }
  799. header := d.lightchain.GetHeaderByHash(h) // Independent of sync mode, header surely exists
  800. if header.Number.Uint64() != check {
  801. p.log.Warn("Received non requested header", "number", header.Number, "hash", header.Hash(), "request", check)
  802. return 0, fmt.Errorf("%w: non-requested header (%d)", errBadPeer, header.Number)
  803. }
  804. start = check
  805. hash = h
  806. case <-timeout:
  807. p.log.Debug("Waiting for search header timed out", "elapsed", ttl)
  808. return 0, errTimeout
  809. case <-d.bodyCh:
  810. case <-d.receiptCh:
  811. // Out of bounds delivery, ignore
  812. }
  813. }
  814. }
  815. // Ensure valid ancestry and return
  816. if int64(start) <= floor {
  817. p.log.Warn("Ancestor below allowance", "number", start, "hash", hash, "allowance", floor)
  818. return 0, errInvalidAncestor
  819. }
  820. p.log.Debug("Found common ancestor", "number", start, "hash", hash)
  821. return start, nil
  822. }
  823. // fetchHeaders keeps retrieving headers concurrently from the number
  824. // requested, until no more are returned, potentially throttling on the way. To
  825. // facilitate concurrency but still protect against malicious nodes sending bad
  826. // headers, we construct a header chain skeleton using the "origin" peer we are
  827. // syncing with, and fill in the missing headers using anyone else. Headers from
  828. // other peers are only accepted if they map cleanly to the skeleton. If no one
  829. // can fill in the skeleton - not even the origin peer - it's assumed invalid and
  830. // the origin is dropped.
  831. func (d *Downloader) fetchHeaders(p *peerConnection, from uint64, pivot uint64) error {
  832. p.log.Debug("Directing header downloads", "origin", from)
  833. defer p.log.Debug("Header download terminated")
  834. // Create a timeout timer, and the associated header fetcher
  835. skeleton := true // Skeleton assembly phase or finishing up
  836. request := time.Now() // time of the last skeleton fetch request
  837. timeout := time.NewTimer(0) // timer to dump a non-responsive active peer
  838. <-timeout.C // timeout channel should be initially empty
  839. defer timeout.Stop()
  840. var ttl time.Duration
  841. getHeaders := func(from uint64) {
  842. request = time.Now()
  843. ttl = d.requestTTL()
  844. timeout.Reset(ttl)
  845. if skeleton {
  846. p.log.Trace("Fetching skeleton headers", "count", MaxHeaderFetch, "from", from)
  847. go p.peer.RequestHeadersByNumber(from+uint64(MaxHeaderFetch)-1, MaxSkeletonSize, MaxHeaderFetch-1, false)
  848. } else {
  849. p.log.Trace("Fetching full headers", "count", MaxHeaderFetch, "from", from)
  850. go p.peer.RequestHeadersByNumber(from, MaxHeaderFetch, 0, false)
  851. }
  852. }
  853. // Start pulling the header chain skeleton until all is done
  854. ancestor := from
  855. getHeaders(from)
  856. mode := d.getMode()
  857. for {
  858. select {
  859. case <-d.cancelCh:
  860. return errCanceled
  861. case packet := <-d.headerCh:
  862. // Make sure the active peer is giving us the skeleton headers
  863. if packet.PeerId() != p.id {
  864. log.Debug("Received skeleton from incorrect peer", "peer", packet.PeerId())
  865. break
  866. }
  867. headerReqTimer.UpdateSince(request)
  868. timeout.Stop()
  869. // If the skeleton's finished, pull any remaining head headers directly from the origin
  870. if packet.Items() == 0 && skeleton {
  871. skeleton = false
  872. getHeaders(from)
  873. continue
  874. }
  875. // If no more headers are inbound, notify the content fetchers and return
  876. if packet.Items() == 0 {
  877. // Don't abort header fetches while the pivot is downloading
  878. if atomic.LoadInt32(&d.committed) == 0 && pivot <= from {
  879. p.log.Debug("No headers, waiting for pivot commit")
  880. select {
  881. case <-time.After(fsHeaderContCheck):
  882. getHeaders(from)
  883. continue
  884. case <-d.cancelCh:
  885. return errCanceled
  886. }
  887. }
  888. // Pivot done (or not in fast sync) and no more headers, terminate the process
  889. p.log.Debug("No more headers available")
  890. select {
  891. case d.headerProcCh <- nil:
  892. return nil
  893. case <-d.cancelCh:
  894. return errCanceled
  895. }
  896. }
  897. headers := packet.(*headerPack).headers
  898. // If we received a skeleton batch, resolve internals concurrently
  899. if skeleton {
  900. filled, proced, err := d.fillHeaderSkeleton(from, headers)
  901. if err != nil {
  902. p.log.Debug("Skeleton chain invalid", "err", err)
  903. return fmt.Errorf("%w: %v", errInvalidChain, err)
  904. }
  905. headers = filled[proced:]
  906. from += uint64(proced)
  907. } else {
  908. // If we're closing in on the chain head, but haven't yet reached it, delay
  909. // the last few headers so mini reorgs on the head don't cause invalid hash
  910. // chain errors.
  911. if n := len(headers); n > 0 {
  912. // Retrieve the current head we're at
  913. var head uint64
  914. if mode == LightSync {
  915. head = d.lightchain.CurrentHeader().Number.Uint64()
  916. } else {
  917. head = d.blockchain.CurrentFastBlock().NumberU64()
  918. if full := d.blockchain.CurrentBlock().NumberU64(); head < full {
  919. head = full
  920. }
  921. }
  922. // If the head is below the common ancestor, we're actually deduplicating
  923. // already existing chain segments, so use the ancestor as the fake head.
  924. // Otherwise we might end up delaying header deliveries pointlessly.
  925. if head < ancestor {
  926. head = ancestor
  927. }
  928. // If the head is way older than this batch, delay the last few headers
  929. if head+uint64(reorgProtThreshold) < headers[n-1].Number.Uint64() {
  930. delay := reorgProtHeaderDelay
  931. if delay > n {
  932. delay = n
  933. }
  934. headers = headers[:n-delay]
  935. }
  936. }
  937. }
  938. // Insert all the new headers and fetch the next batch
  939. if len(headers) > 0 {
  940. p.log.Trace("Scheduling new headers", "count", len(headers), "from", from)
  941. select {
  942. case d.headerProcCh <- headers:
  943. case <-d.cancelCh:
  944. return errCanceled
  945. }
  946. from += uint64(len(headers))
  947. getHeaders(from)
  948. } else {
  949. // No headers delivered, or all of them being delayed, sleep a bit and retry
  950. p.log.Trace("All headers delayed, waiting")
  951. select {
  952. case <-time.After(fsHeaderContCheck):
  953. getHeaders(from)
  954. continue
  955. case <-d.cancelCh:
  956. return errCanceled
  957. }
  958. }
  959. case <-timeout.C:
  960. if d.dropPeer == nil {
  961. // The dropPeer method is nil when `--copydb` is used for a local copy.
  962. // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
  963. p.log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", p.id)
  964. break
  965. }
  966. // Header retrieval timed out, consider the peer bad and drop
  967. p.log.Debug("Header request timed out", "elapsed", ttl)
  968. headerTimeoutMeter.Mark(1)
  969. d.dropPeer(p.id)
  970. // Finish the sync gracefully instead of dumping the gathered data though
  971. for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  972. select {
  973. case ch <- false:
  974. case <-d.cancelCh:
  975. }
  976. }
  977. select {
  978. case d.headerProcCh <- nil:
  979. case <-d.cancelCh:
  980. }
  981. return fmt.Errorf("%w: header request timed out", errBadPeer)
  982. }
  983. }
  984. }
  985. // fillHeaderSkeleton concurrently retrieves headers from all our available peers
  986. // and maps them to the provided skeleton header chain.
  987. //
  988. // Any partial results from the beginning of the skeleton is (if possible) forwarded
  989. // immediately to the header processor to keep the rest of the pipeline full even
  990. // in the case of header stalls.
  991. //
  992. // The method returns the entire filled skeleton and also the number of headers
  993. // already forwarded for processing.
  994. func (d *Downloader) fillHeaderSkeleton(from uint64, skeleton []*types.Header) ([]*types.Header, int, error) {
  995. log.Debug("Filling up skeleton", "from", from)
  996. d.queue.ScheduleSkeleton(from, skeleton)
  997. var (
  998. deliver = func(packet dataPack) (int, error) {
  999. pack := packet.(*headerPack)
  1000. return d.queue.DeliverHeaders(pack.peerID, pack.headers, d.headerProcCh)
  1001. }
  1002. expire = func() map[string]int { return d.queue.ExpireHeaders(d.requestTTL()) }
  1003. reserve = func(p *peerConnection, count int) (*fetchRequest, bool, bool) {
  1004. return d.queue.ReserveHeaders(p, count), false, false
  1005. }
  1006. fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchHeaders(req.From, MaxHeaderFetch) }
  1007. capacity = func(p *peerConnection) int { return p.HeaderCapacity(d.requestRTT()) }
  1008. setIdle = func(p *peerConnection, accepted int, deliveryTime time.Time) {
  1009. p.SetHeadersIdle(accepted, deliveryTime)
  1010. }
  1011. )
  1012. err := d.fetchParts(d.headerCh, deliver, d.queue.headerContCh, expire,
  1013. d.queue.PendingHeaders, d.queue.InFlightHeaders, reserve,
  1014. nil, fetch, d.queue.CancelHeaders, capacity, d.peers.HeaderIdlePeers, setIdle, "headers")
  1015. log.Debug("Skeleton fill terminated", "err", err)
  1016. filled, proced := d.queue.RetrieveHeaders()
  1017. return filled, proced, err
  1018. }
  1019. // fetchBodies iteratively downloads the scheduled block bodies, taking any
  1020. // available peers, reserving a chunk of blocks for each, waiting for delivery
  1021. // and also periodically checking for timeouts.
  1022. func (d *Downloader) fetchBodies(from uint64) error {
  1023. log.Debug("Downloading block bodies", "origin", from)
  1024. var (
  1025. deliver = func(packet dataPack) (int, error) {
  1026. pack := packet.(*bodyPack)
  1027. return d.queue.DeliverBodies(pack.peerID, pack.transactions, pack.uncles)
  1028. }
  1029. expire = func() map[string]int { return d.queue.ExpireBodies(d.requestTTL()) }
  1030. fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchBodies(req) }
  1031. capacity = func(p *peerConnection) int { return p.BlockCapacity(d.requestRTT()) }
  1032. setIdle = func(p *peerConnection, accepted int, deliveryTime time.Time) { p.SetBodiesIdle(accepted, deliveryTime) }
  1033. )
  1034. err := d.fetchParts(d.bodyCh, deliver, d.bodyWakeCh, expire,
  1035. d.queue.PendingBlocks, d.queue.InFlightBlocks, d.queue.ReserveBodies,
  1036. d.bodyFetchHook, fetch, d.queue.CancelBodies, capacity, d.peers.BodyIdlePeers, setIdle, "bodies")
  1037. log.Debug("Block body download terminated", "err", err)
  1038. return err
  1039. }
  1040. // fetchReceipts iteratively downloads the scheduled block receipts, taking any
  1041. // available peers, reserving a chunk of receipts for each, waiting for delivery
  1042. // and also periodically checking for timeouts.
  1043. func (d *Downloader) fetchReceipts(from uint64) error {
  1044. log.Debug("Downloading transaction receipts", "origin", from)
  1045. var (
  1046. deliver = func(packet dataPack) (int, error) {
  1047. pack := packet.(*receiptPack)
  1048. return d.queue.DeliverReceipts(pack.peerID, pack.receipts)
  1049. }
  1050. expire = func() map[string]int { return d.queue.ExpireReceipts(d.requestTTL()) }
  1051. fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchReceipts(req) }
  1052. capacity = func(p *peerConnection) int { return p.ReceiptCapacity(d.requestRTT()) }
  1053. setIdle = func(p *peerConnection, accepted int, deliveryTime time.Time) {
  1054. p.SetReceiptsIdle(accepted, deliveryTime)
  1055. }
  1056. )
  1057. err := d.fetchParts(d.receiptCh, deliver, d.receiptWakeCh, expire,
  1058. d.queue.PendingReceipts, d.queue.InFlightReceipts, d.queue.ReserveReceipts,
  1059. d.receiptFetchHook, fetch, d.queue.CancelReceipts, capacity, d.peers.ReceiptIdlePeers, setIdle, "receipts")
  1060. log.Debug("Transaction receipt download terminated", "err", err)
  1061. return err
  1062. }
  1063. // fetchParts iteratively downloads scheduled block parts, taking any available
  1064. // peers, reserving a chunk of fetch requests for each, waiting for delivery and
  1065. // also periodically checking for timeouts.
  1066. //
  1067. // As the scheduling/timeout logic mostly is the same for all downloaded data
  1068. // types, this method is used by each for data gathering and is instrumented with
  1069. // various callbacks to handle the slight differences between processing them.
  1070. //
  1071. // The instrumentation parameters:
  1072. // - errCancel: error type to return if the fetch operation is cancelled (mostly makes logging nicer)
  1073. // - deliveryCh: channel from which to retrieve downloaded data packets (merged from all concurrent peers)
  1074. // - deliver: processing callback to deliver data packets into type specific download queues (usually within `queue`)
  1075. // - wakeCh: notification channel for waking the fetcher when new tasks are available (or sync completed)
  1076. // - expire: task callback method to abort requests that took too long and return the faulty peers (traffic shaping)
  1077. // - pending: task callback for the number of requests still needing download (detect completion/non-completability)
  1078. // - inFlight: task callback for the number of in-progress requests (wait for all active downloads to finish)
  1079. // - throttle: task callback to check if the processing queue is full and activate throttling (bound memory use)
  1080. // - reserve: task callback to reserve new download tasks to a particular peer (also signals partial completions)
  1081. // - fetchHook: tester callback to notify of new tasks being initiated (allows testing the scheduling logic)
  1082. // - fetch: network callback to actually send a particular download request to a physical remote peer
  1083. // - cancel: task callback to abort an in-flight download request and allow rescheduling it (in case of lost peer)
  1084. // - capacity: network callback to retrieve the estimated type-specific bandwidth capacity of a peer (traffic shaping)
  1085. // - idle: network callback to retrieve the currently (type specific) idle peers that can be assigned tasks
  1086. // - setIdle: network callback to set a peer back to idle and update its estimated capacity (traffic shaping)
  1087. // - kind: textual label of the type being downloaded to display in log messages
  1088. func (d *Downloader) fetchParts(deliveryCh chan dataPack, deliver func(dataPack) (int, error), wakeCh chan bool,
  1089. expire func() map[string]int, pending func() int, inFlight func() bool, reserve func(*peerConnection, int) (*fetchRequest, bool, bool),
  1090. fetchHook func([]*types.Header), fetch func(*peerConnection, *fetchRequest) error, cancel func(*fetchRequest), capacity func(*peerConnection) int,
  1091. idle func() ([]*peerConnection, int), setIdle func(*peerConnection, int, time.Time), kind string) error {
  1092. // Create a ticker to detect expired retrieval tasks
  1093. ticker := time.NewTicker(100 * time.Millisecond)
  1094. defer ticker.Stop()
  1095. update := make(chan struct{}, 1)
  1096. // Prepare the queue and fetch block parts until the block header fetcher's done
  1097. finished := false
  1098. for {
  1099. select {
  1100. case <-d.cancelCh:
  1101. return errCanceled
  1102. case packet := <-deliveryCh:
  1103. deliveryTime := time.Now()
  1104. // If the peer was previously banned and failed to deliver its pack
  1105. // in a reasonable time frame, ignore its message.
  1106. if peer := d.peers.Peer(packet.PeerId()); peer != nil {
  1107. // Deliver the received chunk of data and check chain validity
  1108. accepted, err := deliver(packet)
  1109. if errors.Is(err, errInvalidChain) {
  1110. return err
  1111. }
  1112. // Unless a peer delivered something completely else than requested (usually
  1113. // caused by a timed out request which came through in the end), set it to
  1114. // idle. If the delivery's stale, the peer should have already been idled.
  1115. if !errors.Is(err, errStaleDelivery) {
  1116. setIdle(peer, accepted, deliveryTime)
  1117. }
  1118. // Issue a log to the user to see what's going on
  1119. switch {
  1120. case err == nil && packet.Items() == 0:
  1121. peer.log.Trace("Requested data not delivered", "type", kind)
  1122. case err == nil:
  1123. peer.log.Trace("Delivered new batch of data", "type", kind, "count", packet.Stats())
  1124. default:
  1125. peer.log.Trace("Failed to deliver retrieved data", "type", kind, "err", err)
  1126. }
  1127. }
  1128. // Blocks assembled, try to update the progress
  1129. select {
  1130. case update <- struct{}{}:
  1131. default:
  1132. }
  1133. case cont := <-wakeCh:
  1134. // The header fetcher sent a continuation flag, check if it's done
  1135. if !cont {
  1136. finished = true
  1137. }
  1138. // Headers arrive, try to update the progress
  1139. select {
  1140. case update <- struct{}{}:
  1141. default:
  1142. }
  1143. case <-ticker.C:
  1144. // Sanity check update the progress
  1145. select {
  1146. case update <- struct{}{}:
  1147. default:
  1148. }
  1149. case <-update:
  1150. // Short circuit if we lost all our peers
  1151. if d.peers.Len() == 0 {
  1152. return errNoPeers
  1153. }
  1154. // Check for fetch request timeouts and demote the responsible peers
  1155. for pid, fails := range expire() {
  1156. if peer := d.peers.Peer(pid); peer != nil {
  1157. // If a lot of retrieval elements expired, we might have overestimated the remote peer or perhaps
  1158. // ourselves. Only reset to minimal throughput but don't drop just yet. If even the minimal times
  1159. // out that sync wise we need to get rid of the peer.
  1160. //
  1161. // The reason the minimum threshold is 2 is because the downloader tries to estimate the bandwidth
  1162. // and latency of a peer separately, which requires pushing the measures capacity a bit and seeing
  1163. // how response times reacts, to it always requests one more than the minimum (i.e. min 2).
  1164. if fails > 2 {
  1165. peer.log.Trace("Data delivery timed out", "type", kind)
  1166. setIdle(peer, 0, time.Now())
  1167. } else {
  1168. peer.log.Debug("Stalling delivery, dropping", "type", kind)
  1169. if d.dropPeer == nil {
  1170. // The dropPeer method is nil when `--copydb` is used for a local copy.
  1171. // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
  1172. peer.log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", pid)
  1173. } else {
  1174. d.dropPeer(pid)
  1175. // If this peer was the master peer, abort sync immediately
  1176. d.cancelLock.RLock()
  1177. master := pid == d.cancelPeer
  1178. d.cancelLock.RUnlock()
  1179. if master {
  1180. d.cancel()
  1181. return errTimeout
  1182. }
  1183. }
  1184. }
  1185. }
  1186. }
  1187. // If there's nothing more to fetch, wait or terminate
  1188. if pending() == 0 {
  1189. if !inFlight() && finished {
  1190. log.Debug("Data fetching completed", "type", kind)
  1191. return nil
  1192. }
  1193. break
  1194. }
  1195. // Send a download request to all idle peers, until throttled
  1196. progressed, throttled, running := false, false, inFlight()
  1197. idles, total := idle()
  1198. pendCount := pending()
  1199. for _, peer := range idles {
  1200. // Short circuit if throttling activated
  1201. if throttled {
  1202. break
  1203. }
  1204. // Short circuit if there is no more available task.
  1205. if pendCount = pending(); pendCount == 0 {
  1206. break
  1207. }
  1208. // Reserve a chunk of fetches for a peer. A nil can mean either that
  1209. // no more headers are available, or that the peer is known not to
  1210. // have them.
  1211. request, progress, throttle := reserve(peer, capacity(peer))
  1212. if progress {
  1213. progressed = true
  1214. }
  1215. if throttle {
  1216. throttled = true
  1217. throttleCounter.Inc(1)
  1218. }
  1219. if request == nil {
  1220. continue
  1221. }
  1222. if request.From > 0 {
  1223. peer.log.Trace("Requesting new batch of data", "type", kind, "from", request.From)
  1224. } else {
  1225. peer.log.Trace("Requesting new batch of data", "type", kind, "count", len(request.Headers), "from", request.Headers[0].Number)
  1226. }
  1227. // Fetch the chunk and make sure any errors return the hashes to the queue
  1228. if fetchHook != nil {
  1229. fetchHook(request.Headers)
  1230. }
  1231. if err := fetch(peer, request); err != nil {
  1232. // Although we could try and make an attempt to fix this, this error really
  1233. // means that we've double allocated a fetch task to a peer. If that is the
  1234. // case, the internal state of the downloader and the queue is very wrong so
  1235. // better hard crash and note the error instead of silently accumulating into
  1236. // a much bigger issue.
  1237. panic(fmt.Sprintf("%v: %s fetch assignment failed", peer, kind))
  1238. }
  1239. running = true
  1240. }
  1241. // Make sure that we have peers available for fetching. If all peers have been tried
  1242. // and all failed throw an error
  1243. if !progressed && !throttled && !running && len(idles) == total && pendCount > 0 {
  1244. return errPeersUnavailable
  1245. }
  1246. }
  1247. }
  1248. }
  1249. // processHeaders takes batches of retrieved headers from an input channel and
  1250. // keeps processing and scheduling them into the header chain and downloader's
  1251. // queue until the stream ends or a failure occurs.
  1252. func (d *Downloader) processHeaders(origin uint64, pivot uint64, td *big.Int) error {
  1253. // Keep a count of uncertain headers to roll back
  1254. var (
  1255. rollback []*types.Header
  1256. rollbackErr error
  1257. mode = d.getMode()
  1258. )
  1259. defer func() {
  1260. if len(rollback) > 0 {
  1261. // Flatten the headers and roll them back
  1262. hashes := make([]common.Hash, len(rollback))
  1263. for i, header := range rollback {
  1264. hashes[i] = header.Hash()
  1265. }
  1266. lastHeader, lastFastBlock, lastBlock := d.lightchain.CurrentHeader().Number, common.Big0, common.Big0
  1267. if mode != LightSync {
  1268. lastFastBlock = d.blockchain.CurrentFastBlock().Number()
  1269. lastBlock = d.blockchain.CurrentBlock().Number()
  1270. }
  1271. d.lightchain.Rollback(hashes)
  1272. curFastBlock, curBlock := common.Big0, common.Big0
  1273. if mode != LightSync {
  1274. curFastBlock = d.blockchain.CurrentFastBlock().Number()
  1275. curBlock = d.blockchain.CurrentBlock().Number()
  1276. }
  1277. log.Warn("Rolled back headers", "count", len(hashes),
  1278. "header", fmt.Sprintf("%d->%d", lastHeader, d.lightchain.CurrentHeader().Number),
  1279. "fast", fmt.Sprintf("%d->%d", lastFastBlock, curFastBlock),
  1280. "block", fmt.Sprintf("%d->%d", lastBlock, curBlock), "reason", rollbackErr)
  1281. }
  1282. }()
  1283. // Wait for batches of headers to process
  1284. gotHeaders := false
  1285. for {
  1286. select {
  1287. case <-d.cancelCh:
  1288. rollbackErr = errCanceled
  1289. return errCanceled
  1290. case headers := <-d.headerProcCh:
  1291. // Terminate header processing if we synced up
  1292. if len(headers) == 0 {
  1293. // Notify everyone that headers are fully processed
  1294. for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1295. select {
  1296. case ch <- false:
  1297. case <-d.cancelCh:
  1298. }
  1299. }
  1300. // If no headers were retrieved at all, the peer violated its TD promise that it had a
  1301. // better chain compared to ours. The only exception is if its promised blocks were
  1302. // already imported by other means (e.g. fetcher):
  1303. //
  1304. // R <remote peer>, L <local node>: Both at block 10
  1305. // R: Mine block 11, and propagate it to L
  1306. // L: Queue block 11 for import
  1307. // L: Notice that R's head and TD increased compared to ours, start sync
  1308. // L: Import of block 11 finishes
  1309. // L: Sync begins, and finds common ancestor at 11
  1310. // L: Request new headers up from 11 (R's TD was higher, it must have something)
  1311. // R: Nothing to give
  1312. if mode != LightSync {
  1313. head := d.blockchain.CurrentBlock()
  1314. if !gotHeaders && td.Cmp(d.blockchain.GetTd(head.Hash(), head.NumberU64())) > 0 {
  1315. return errStallingPeer
  1316. }
  1317. }
  1318. // If fast or light syncing, ensure promised headers are indeed delivered. This is
  1319. // needed to detect scenarios where an attacker feeds a bad pivot and then bails out
  1320. // of delivering the post-pivot blocks that would flag the invalid content.
  1321. //
  1322. // This check cannot be executed "as is" for full imports, since blocks may still be
  1323. // queued for processing when the header download completes. However, as long as the
  1324. // peer gave us something useful, we're already happy/progressed (above check).
  1325. if mode == FastSync || mode == LightSync {
  1326. head := d.lightchain.CurrentHeader()
  1327. if td.Cmp(d.lightchain.GetTd(head.Hash(), head.Number.Uint64())) > 0 {
  1328. return errStallingPeer
  1329. }
  1330. }
  1331. // Disable any rollback and return
  1332. rollback = nil
  1333. return nil
  1334. }
  1335. // Otherwise split the chunk of headers into batches and process them
  1336. gotHeaders = true
  1337. for len(headers) > 0 {
  1338. // Terminate if something failed in between processing chunks
  1339. select {
  1340. case <-d.cancelCh:
  1341. rollbackErr = errCanceled
  1342. return errCanceled
  1343. default:
  1344. }
  1345. // Select the next chunk of headers to import
  1346. limit := maxHeadersProcess
  1347. if limit > len(headers) {
  1348. limit = len(headers)
  1349. }
  1350. chunk := headers[:limit]
  1351. // In case of header only syncing, validate the chunk immediately
  1352. if mode == FastSync || mode == LightSync {
  1353. // Collect the yet unknown headers to mark them as uncertain
  1354. unknown := make([]*types.Header, 0, len(chunk))
  1355. for _, header := range chunk {
  1356. if !d.lightchain.HasHeader(header.Hash(), header.Number.Uint64()) {
  1357. unknown = append(unknown, header)
  1358. }
  1359. }
  1360. // If we're importing pure headers, verify based on their recentness
  1361. frequency := fsHeaderCheckFrequency
  1362. if chunk[len(chunk)-1].Number.Uint64()+uint64(fsHeaderForceVerify) > pivot {
  1363. frequency = 1
  1364. }
  1365. if n, err := d.lightchain.InsertHeaderChain(chunk, frequency); err != nil {
  1366. rollbackErr = err
  1367. // If some headers were inserted, add them too to the rollback list
  1368. if n > 0 {
  1369. rollback = append(rollback, chunk[:n]...)
  1370. }
  1371. log.Debug("Invalid header encountered", "number", chunk[n].Number, "hash", chunk[n].Hash(), "parent", chunk[n].ParentHash, "err", err)
  1372. return fmt.Errorf("%w: %v", errInvalidChain, err)
  1373. }
  1374. // All verifications passed, store newly found uncertain headers
  1375. rollback = append(rollback, unknown...)
  1376. if len(rollback) > fsHeaderSafetyNet {
  1377. rollback = append(rollback[:0], rollback[len(rollback)-fsHeaderSafetyNet:]...)
  1378. }
  1379. }
  1380. // Unless we're doing light chains, schedule the headers for associated content retrieval
  1381. if mode == FullSync || mode == FastSync {
  1382. // If we've reached the allowed number of pending headers, stall a bit
  1383. for d.queue.PendingBlocks() >= maxQueuedHeaders || d.queue.PendingReceipts() >= maxQueuedHeaders {
  1384. select {
  1385. case <-d.cancelCh:
  1386. rollbackErr = errCanceled
  1387. return errCanceled
  1388. case <-time.After(time.Second):
  1389. }
  1390. }
  1391. // Otherwise insert the headers for content retrieval
  1392. inserts := d.queue.Schedule(chunk, origin)
  1393. if len(inserts) != len(chunk) {
  1394. rollbackErr = fmt.Errorf("stale headers: len inserts %v len(chunk) %v", len(inserts), len(chunk))
  1395. return fmt.Errorf("%w: stale headers", errBadPeer)
  1396. }
  1397. }
  1398. headers = headers[limit:]
  1399. origin += uint64(limit)
  1400. }
  1401. // Update the highest block number we know if a higher one is found.
  1402. d.syncStatsLock.Lock()
  1403. if d.syncStatsChainHeight < origin {
  1404. d.syncStatsChainHeight = origin - 1
  1405. }
  1406. d.syncStatsLock.Unlock()
  1407. // Signal the content downloaders of the availablility of new tasks
  1408. for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1409. select {
  1410. case ch <- true:
  1411. default:
  1412. }
  1413. }
  1414. }
  1415. }
  1416. }
  1417. // processFullSyncContent takes fetch results from the queue and imports them into the chain.
  1418. func (d *Downloader) processFullSyncContent() error {
  1419. for {
  1420. results := d.queue.Results(true)
  1421. if len(results) == 0 {
  1422. return nil
  1423. }
  1424. if d.chainInsertHook != nil {
  1425. d.chainInsertHook(results)
  1426. }
  1427. if err := d.importBlockResults(results); err != nil {
  1428. return err
  1429. }
  1430. }
  1431. }
  1432. func (d *Downloader) importBlockResults(results []*fetchResult) error {
  1433. // Check for any early termination requests
  1434. if len(results) == 0 {
  1435. return nil
  1436. }
  1437. select {
  1438. case <-d.quitCh:
  1439. return errCancelContentProcessing
  1440. default:
  1441. }
  1442. // Retrieve the a batch of results to import
  1443. first, last := results[0].Header, results[len(results)-1].Header
  1444. log.Debug("Inserting downloaded chain", "items", len(results),
  1445. "firstnum", first.Number, "firsthash", first.Hash(),
  1446. "lastnum", last.Number, "lasthash", last.Hash(),
  1447. )
  1448. blocks := make([]*types.Block, len(results))
  1449. for i, result := range results {
  1450. blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1451. }
  1452. if index, err := d.blockchain.InsertChain(blocks); err != nil {
  1453. if index < len(results) {
  1454. log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err)
  1455. } else {
  1456. // The InsertChain method in blockchain.go will sometimes return an out-of-bounds index,
  1457. // when it needs to preprocess blocks to import a sidechain.
  1458. // The importer will put together a new list of blocks to import, which is a superset
  1459. // of the blocks delivered from the downloader, and the indexing will be off.
  1460. log.Debug("Downloaded item processing failed on sidechain import", "index", index, "err", err)
  1461. }
  1462. return fmt.Errorf("%w: %v", errInvalidChain, err)
  1463. }
  1464. return nil
  1465. }
  1466. // processFastSyncContent takes fetch results from the queue and writes them to the
  1467. // database. It also controls the synchronisation of state nodes of the pivot block.
  1468. func (d *Downloader) processFastSyncContent(latest *types.Header) error {
  1469. // Start syncing state of the reported head block. This should get us most of
  1470. // the state of the pivot block.
  1471. sync := d.syncState(latest.Root)
  1472. defer sync.Cancel()
  1473. closeOnErr := func(s *stateSync) {
  1474. if err := s.Wait(); err != nil && err != errCancelStateFetch && err != errCanceled {
  1475. d.queue.Close() // wake up Results
  1476. }
  1477. }
  1478. go closeOnErr(sync)
  1479. // Figure out the ideal pivot block. Note, that this goalpost may move if the
  1480. // sync takes long enough for the chain head to move significantly.
  1481. pivot := uint64(0)
  1482. if height := latest.Number.Uint64(); height > uint64(fsMinFullBlocks) {
  1483. pivot = height - uint64(fsMinFullBlocks)
  1484. }
  1485. // To cater for moving pivot points, track the pivot block and subsequently
  1486. // accumulated download results separately.
  1487. var (
  1488. oldPivot *fetchResult // Locked in pivot block, might change eventually
  1489. oldTail []*fetchResult // Downloaded content after the pivot
  1490. )
  1491. for {
  1492. // Wait for the next batch of downloaded data to be available, and if the pivot
  1493. // block became stale, move the goalpost
  1494. results := d.queue.Results(oldPivot == nil) // Block if we're not monitoring pivot staleness
  1495. if len(results) == 0 {
  1496. // If pivot sync is done, stop
  1497. if oldPivot == nil {
  1498. return sync.Cancel()
  1499. }
  1500. // If sync failed, stop
  1501. select {
  1502. case <-d.cancelCh:
  1503. sync.Cancel()
  1504. return errCanceled
  1505. default:
  1506. }
  1507. }
  1508. if d.chainInsertHook != nil {
  1509. d.chainInsertHook(results)
  1510. }
  1511. if oldPivot != nil {
  1512. results = append(append([]*fetchResult{oldPivot}, oldTail...), results...)
  1513. }
  1514. // Split around the pivot block and process the two sides via fast/full sync
  1515. if atomic.LoadInt32(&d.committed) == 0 {
  1516. latest = results[len(results)-1].Header
  1517. if height := latest.Number.Uint64(); height > pivot+2*uint64(fsMinFullBlocks) {
  1518. log.Warn("Pivot became stale, moving", "old", pivot, "new", height-uint64(fsMinFullBlocks))
  1519. pivot = height - uint64(fsMinFullBlocks)
  1520. }
  1521. }
  1522. P, beforeP, afterP := splitAroundPivot(pivot, results)
  1523. if err := d.commitFastSyncData(beforeP, sync); err != nil {
  1524. return err
  1525. }
  1526. if P != nil {
  1527. // If new pivot block found, cancel old state retrieval and restart
  1528. if oldPivot != P {
  1529. sync.Cancel()
  1530. sync = d.syncState(P.Header.Root)
  1531. defer sync.Cancel()
  1532. go closeOnErr(sync)
  1533. oldPivot = P
  1534. }
  1535. // Wait for completion, occasionally checking for pivot staleness
  1536. select {
  1537. case <-sync.done:
  1538. if sync.err != nil {
  1539. return sync.err
  1540. }
  1541. if err := d.commitPivotBlock(P); err != nil {
  1542. return err
  1543. }
  1544. oldPivot = nil
  1545. case <-time.After(time.Second):
  1546. oldTail = afterP
  1547. continue
  1548. }
  1549. }
  1550. // Fast sync done, pivot commit done, full import
  1551. if err := d.importBlockResults(afterP); err != nil {
  1552. return err
  1553. }
  1554. }
  1555. }
  1556. func splitAroundPivot(pivot uint64, results []*fetchResult) (p *fetchResult, before, after []*fetchResult) {
  1557. if len(results) == 0 {
  1558. return nil, nil, nil
  1559. }
  1560. if lastNum := results[len(results)-1].Header.Number.Uint64(); lastNum < pivot {
  1561. // the pivot is somewhere in the future
  1562. return nil, results, nil
  1563. }
  1564. // This can also be optimized, but only happens very seldom
  1565. for _, result := range results {
  1566. num := result.Header.Number.Uint64()
  1567. switch {
  1568. case num < pivot:
  1569. before = append(before, result)
  1570. case num == pivot:
  1571. p = result
  1572. default:
  1573. after = append(after, result)
  1574. }
  1575. }
  1576. return p, before, after
  1577. }
  1578. func (d *Downloader) commitFastSyncData(results []*fetchResult, stateSync *stateSync) error {
  1579. // Check for any early termination requests
  1580. if len(results) == 0 {
  1581. return nil
  1582. }
  1583. select {
  1584. case <-d.quitCh:
  1585. return errCancelContentProcessing
  1586. case <-stateSync.done:
  1587. if err := stateSync.Wait(); err != nil {
  1588. return err
  1589. }
  1590. default:
  1591. }
  1592. // Retrieve the a batch of results to import
  1593. first, last := results[0].Header, results[len(results)-1].Header
  1594. log.Debug("Inserting fast-sync blocks", "items", len(results),
  1595. "firstnum", first.Number, "firsthash", first.Hash(),
  1596. "lastnumn", last.Number, "lasthash", last.Hash(),
  1597. )
  1598. blocks := make([]*types.Block, len(results))
  1599. receipts := make([]types.Receipts, len(results))
  1600. for i, result := range results {
  1601. blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1602. receipts[i] = result.Receipts
  1603. }
  1604. if index, err := d.blockchain.InsertReceiptChain(blocks, receipts, d.ancientLimit); err != nil {
  1605. log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err)
  1606. return fmt.Errorf("%w: %v", errInvalidChain, err)
  1607. }
  1608. return nil
  1609. }
  1610. func (d *Downloader) commitPivotBlock(result *fetchResult) error {
  1611. block := types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1612. log.Debug("Committing fast sync pivot as new head", "number", block.Number(), "hash", block.Hash())
  1613. // Commit the pivot block as the new head, will require full sync from here on
  1614. if _, err := d.blockchain.InsertReceiptChain([]*types.Block{block}, []types.Receipts{result.Receipts}, d.ancientLimit); err != nil {
  1615. return err
  1616. }
  1617. if err := d.blockchain.FastSyncCommitHead(block.Hash()); err != nil {
  1618. return err
  1619. }
  1620. atomic.StoreInt32(&d.committed, 1)
  1621. // If we had a bloom filter for the state sync, deallocate it now. Note, we only
  1622. // deallocate internally, but keep the empty wrapper. This ensures that if we do
  1623. // a rollback after committing the pivot and restarting fast sync, we don't end
  1624. // up using a nil bloom. Empty bloom is fine, it just returns that it does not
  1625. // have the info we need, so reach down to the database instead.
  1626. if d.stateBloom != nil {
  1627. d.stateBloom.Close()
  1628. }
  1629. return nil
  1630. }
  1631. // DeliverHeaders injects a new batch of block headers received from a remote
  1632. // node into the download schedule.
  1633. func (d *Downloader) DeliverHeaders(id string, headers []*types.Header) (err error) {
  1634. return d.deliver(id, d.headerCh, &headerPack{id, headers}, headerInMeter, headerDropMeter)
  1635. }
  1636. // DeliverBodies injects a new batch of block bodies received from a remote node.
  1637. func (d *Downloader) DeliverBodies(id string, transactions [][]*types.Transaction, uncles [][]*types.Header) (err error) {
  1638. return d.deliver(id, d.bodyCh, &bodyPack{id, transactions, uncles}, bodyInMeter, bodyDropMeter)
  1639. }
  1640. // DeliverReceipts injects a new batch of receipts received from a remote node.
  1641. func (d *Downloader) DeliverReceipts(id string, receipts [][]*types.Receipt) (err error) {
  1642. return d.deliver(id, d.receiptCh, &receiptPack{id, receipts}, receiptInMeter, receiptDropMeter)
  1643. }
  1644. // DeliverNodeData injects a new batch of node state data received from a remote node.
  1645. func (d *Downloader) DeliverNodeData(id string, data [][]byte) (err error) {
  1646. return d.deliver(id, d.stateCh, &statePack{id, data}, stateInMeter, stateDropMeter)
  1647. }
  1648. // deliver injects a new batch of data received from a remote node.
  1649. func (d *Downloader) deliver(id string, destCh chan dataPack, packet dataPack, inMeter, dropMeter metrics.Meter) (err error) {
  1650. // Update the delivery metrics for both good and failed deliveries
  1651. inMeter.Mark(int64(packet.Items()))
  1652. defer func() {
  1653. if err != nil {
  1654. dropMeter.Mark(int64(packet.Items()))
  1655. }
  1656. }()
  1657. // Deliver or abort if the sync is canceled while queuing
  1658. d.cancelLock.RLock()
  1659. cancel := d.cancelCh
  1660. d.cancelLock.RUnlock()
  1661. if cancel == nil {
  1662. return errNoSyncActive
  1663. }
  1664. select {
  1665. case destCh <- packet:
  1666. return nil
  1667. case <-cancel:
  1668. return errNoSyncActive
  1669. }
  1670. }
  1671. // qosTuner is the quality of service tuning loop that occasionally gathers the
  1672. // peer latency statistics and updates the estimated request round trip time.
  1673. func (d *Downloader) qosTuner() {
  1674. for {
  1675. // Retrieve the current median RTT and integrate into the previoust target RTT
  1676. rtt := time.Duration((1-qosTuningImpact)*float64(atomic.LoadUint64(&d.rttEstimate)) + qosTuningImpact*float64(d.peers.medianRTT()))
  1677. atomic.StoreUint64(&d.rttEstimate, uint64(rtt))
  1678. // A new RTT cycle passed, increase our confidence in the estimated RTT
  1679. conf := atomic.LoadUint64(&d.rttConfidence)
  1680. conf = conf + (1000000-conf)/2
  1681. atomic.StoreUint64(&d.rttConfidence, conf)
  1682. // Log the new QoS values and sleep until the next RTT
  1683. log.Debug("Recalculated downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL())
  1684. select {
  1685. case <-d.quitCh:
  1686. return
  1687. case <-time.After(rtt):
  1688. }
  1689. }
  1690. }
  1691. // qosReduceConfidence is meant to be called when a new peer joins the downloader's
  1692. // peer set, needing to reduce the confidence we have in out QoS estimates.
  1693. func (d *Downloader) qosReduceConfidence() {
  1694. // If we have a single peer, confidence is always 1
  1695. peers := uint64(d.peers.Len())
  1696. if peers == 0 {
  1697. // Ensure peer connectivity races don't catch us off guard
  1698. return
  1699. }
  1700. if peers == 1 {
  1701. atomic.StoreUint64(&d.rttConfidence, 1000000)
  1702. return
  1703. }
  1704. // If we have a ton of peers, don't drop confidence)
  1705. if peers >= uint64(qosConfidenceCap) {
  1706. return
  1707. }
  1708. // Otherwise drop the confidence factor
  1709. conf := atomic.LoadUint64(&d.rttConfidence) * (peers - 1) / peers
  1710. if float64(conf)/1000000 < rttMinConfidence {
  1711. conf = uint64(rttMinConfidence * 1000000)
  1712. }
  1713. atomic.StoreUint64(&d.rttConfidence, conf)
  1714. rtt := time.Duration(atomic.LoadUint64(&d.rttEstimate))
  1715. log.Debug("Relaxed downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL())
  1716. }
  1717. // requestRTT returns the current target round trip time for a download request
  1718. // to complete in.
  1719. //
  1720. // Note, the returned RTT is .9 of the actually estimated RTT. The reason is that
  1721. // the downloader tries to adapt queries to the RTT, so multiple RTT values can
  1722. // be adapted to, but smaller ones are preferred (stabler download stream).
  1723. func (d *Downloader) requestRTT() time.Duration {
  1724. return time.Duration(atomic.LoadUint64(&d.rttEstimate)) * 9 / 10
  1725. }
  1726. // requestTTL returns the current timeout allowance for a single download request
  1727. // to finish under.
  1728. func (d *Downloader) requestTTL() time.Duration {
  1729. var (
  1730. rtt = time.Duration(atomic.LoadUint64(&d.rttEstimate))
  1731. conf = float64(atomic.LoadUint64(&d.rttConfidence)) / 1000000.0
  1732. )
  1733. ttl := time.Duration(ttlScaling) * time.Duration(float64(rtt)/conf)
  1734. if ttl > ttlLimit {
  1735. ttl = ttlLimit
  1736. }
  1737. return ttl
  1738. }