downloader.go 69 KB

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