downloader.go 77 KB

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