downloader.go 75 KB

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