downloader.go 85 KB

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