downloader.go 73 KB

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