downloader.go 67 KB

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