downloader.go 77 KB

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