downloader.go 68 KB

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