downloader.go 58 KB

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