queue.go 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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. // Contains the block download scheduler to collect download tasks and schedule
  17. // them in an ordered, and throttled way.
  18. package downloader
  19. import (
  20. "errors"
  21. "fmt"
  22. "sync"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/core/state"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/crypto"
  28. "github.com/ethereum/go-ethereum/ethdb"
  29. "github.com/ethereum/go-ethereum/log"
  30. "github.com/ethereum/go-ethereum/trie"
  31. "github.com/rcrowley/go-metrics"
  32. "gopkg.in/karalabe/cookiejar.v2/collections/prque"
  33. )
  34. var (
  35. blockCacheLimit = 8192 // Maximum number of blocks to cache before throttling the download
  36. maxInFlightStates = 8192 // Maximum number of state downloads to allow concurrently
  37. )
  38. var (
  39. errNoFetchesPending = errors.New("no fetches pending")
  40. errStaleDelivery = errors.New("stale delivery")
  41. )
  42. // fetchRequest is a currently running data retrieval operation.
  43. type fetchRequest struct {
  44. Peer *peer // Peer to which the request was sent
  45. From uint64 // [eth/62] Requested chain element index (used for skeleton fills only)
  46. Hashes map[common.Hash]int // [eth/61] Requested hashes with their insertion index (priority)
  47. Headers []*types.Header // [eth/62] Requested headers, sorted by request order
  48. Time time.Time // Time when the request was made
  49. }
  50. // fetchResult is a struct collecting partial results from data fetchers until
  51. // all outstanding pieces complete and the result as a whole can be processed.
  52. type fetchResult struct {
  53. Pending int // Number of data fetches still pending
  54. Header *types.Header
  55. Uncles []*types.Header
  56. Transactions types.Transactions
  57. Receipts types.Receipts
  58. }
  59. // queue represents hashes that are either need fetching or are being fetched
  60. type queue struct {
  61. mode SyncMode // Synchronisation mode to decide on the block parts to schedule for fetching
  62. fastSyncPivot uint64 // Block number where the fast sync pivots into archive synchronisation mode
  63. headerHead common.Hash // [eth/62] Hash of the last queued header to verify order
  64. // Headers are "special", they download in batches, supported by a skeleton chain
  65. headerTaskPool map[uint64]*types.Header // [eth/62] Pending header retrieval tasks, mapping starting indexes to skeleton headers
  66. headerTaskQueue *prque.Prque // [eth/62] Priority queue of the skeleton indexes to fetch the filling headers for
  67. headerPeerMiss map[string]map[uint64]struct{} // [eth/62] Set of per-peer header batches known to be unavailable
  68. headerPendPool map[string]*fetchRequest // [eth/62] Currently pending header retrieval operations
  69. headerResults []*types.Header // [eth/62] Result cache accumulating the completed headers
  70. headerProced int // [eth/62] Number of headers already processed from the results
  71. headerOffset uint64 // [eth/62] Number of the first header in the result cache
  72. headerContCh chan bool // [eth/62] Channel to notify when header download finishes
  73. // All data retrievals below are based on an already assembles header chain
  74. blockTaskPool map[common.Hash]*types.Header // [eth/62] Pending block (body) retrieval tasks, mapping hashes to headers
  75. blockTaskQueue *prque.Prque // [eth/62] Priority queue of the headers to fetch the blocks (bodies) for
  76. blockPendPool map[string]*fetchRequest // [eth/62] Currently pending block (body) retrieval operations
  77. blockDonePool map[common.Hash]struct{} // [eth/62] Set of the completed block (body) fetches
  78. receiptTaskPool map[common.Hash]*types.Header // [eth/63] Pending receipt retrieval tasks, mapping hashes to headers
  79. receiptTaskQueue *prque.Prque // [eth/63] Priority queue of the headers to fetch the receipts for
  80. receiptPendPool map[string]*fetchRequest // [eth/63] Currently pending receipt retrieval operations
  81. receiptDonePool map[common.Hash]struct{} // [eth/63] Set of the completed receipt fetches
  82. stateTaskIndex int // [eth/63] Counter indexing the added hashes to ensure prioritised retrieval order
  83. stateTaskPool map[common.Hash]int // [eth/63] Pending node data retrieval tasks, mapping to their priority
  84. stateTaskQueue *prque.Prque // [eth/63] Priority queue of the hashes to fetch the node data for
  85. statePendPool map[string]*fetchRequest // [eth/63] Currently pending node data retrieval operations
  86. stateDatabase ethdb.Database // [eth/63] Trie database to populate during state reassembly
  87. stateScheduler *state.StateSync // [eth/63] State trie synchronisation scheduler and integrator
  88. stateWriters int // [eth/63] Number of running state DB writer goroutines
  89. resultCache []*fetchResult // Downloaded but not yet delivered fetch results
  90. resultOffset uint64 // Offset of the first cached fetch result in the block chain
  91. lock *sync.Mutex
  92. active *sync.Cond
  93. closed bool
  94. }
  95. // newQueue creates a new download queue for scheduling block retrieval.
  96. func newQueue(stateDb ethdb.Database) *queue {
  97. lock := new(sync.Mutex)
  98. return &queue{
  99. headerPendPool: make(map[string]*fetchRequest),
  100. headerContCh: make(chan bool),
  101. blockTaskPool: make(map[common.Hash]*types.Header),
  102. blockTaskQueue: prque.New(),
  103. blockPendPool: make(map[string]*fetchRequest),
  104. blockDonePool: make(map[common.Hash]struct{}),
  105. receiptTaskPool: make(map[common.Hash]*types.Header),
  106. receiptTaskQueue: prque.New(),
  107. receiptPendPool: make(map[string]*fetchRequest),
  108. receiptDonePool: make(map[common.Hash]struct{}),
  109. stateTaskPool: make(map[common.Hash]int),
  110. stateTaskQueue: prque.New(),
  111. statePendPool: make(map[string]*fetchRequest),
  112. stateDatabase: stateDb,
  113. resultCache: make([]*fetchResult, blockCacheLimit),
  114. active: sync.NewCond(lock),
  115. lock: lock,
  116. }
  117. }
  118. // Reset clears out the queue contents.
  119. func (q *queue) Reset() {
  120. q.lock.Lock()
  121. defer q.lock.Unlock()
  122. q.closed = false
  123. q.mode = FullSync
  124. q.fastSyncPivot = 0
  125. q.headerHead = common.Hash{}
  126. q.headerPendPool = make(map[string]*fetchRequest)
  127. q.blockTaskPool = make(map[common.Hash]*types.Header)
  128. q.blockTaskQueue.Reset()
  129. q.blockPendPool = make(map[string]*fetchRequest)
  130. q.blockDonePool = make(map[common.Hash]struct{})
  131. q.receiptTaskPool = make(map[common.Hash]*types.Header)
  132. q.receiptTaskQueue.Reset()
  133. q.receiptPendPool = make(map[string]*fetchRequest)
  134. q.receiptDonePool = make(map[common.Hash]struct{})
  135. q.stateTaskIndex = 0
  136. q.stateTaskPool = make(map[common.Hash]int)
  137. q.stateTaskQueue.Reset()
  138. q.statePendPool = make(map[string]*fetchRequest)
  139. q.stateScheduler = nil
  140. q.resultCache = make([]*fetchResult, blockCacheLimit)
  141. q.resultOffset = 0
  142. }
  143. // Close marks the end of the sync, unblocking WaitResults.
  144. // It may be called even if the queue is already closed.
  145. func (q *queue) Close() {
  146. q.lock.Lock()
  147. q.closed = true
  148. q.lock.Unlock()
  149. q.active.Broadcast()
  150. }
  151. // PendingHeaders retrieves the number of header requests pending for retrieval.
  152. func (q *queue) PendingHeaders() int {
  153. q.lock.Lock()
  154. defer q.lock.Unlock()
  155. return q.headerTaskQueue.Size()
  156. }
  157. // PendingBlocks retrieves the number of block (body) requests pending for retrieval.
  158. func (q *queue) PendingBlocks() int {
  159. q.lock.Lock()
  160. defer q.lock.Unlock()
  161. return q.blockTaskQueue.Size()
  162. }
  163. // PendingReceipts retrieves the number of block receipts pending for retrieval.
  164. func (q *queue) PendingReceipts() int {
  165. q.lock.Lock()
  166. defer q.lock.Unlock()
  167. return q.receiptTaskQueue.Size()
  168. }
  169. // PendingNodeData retrieves the number of node data entries pending for retrieval.
  170. func (q *queue) PendingNodeData() int {
  171. q.lock.Lock()
  172. defer q.lock.Unlock()
  173. return q.pendingNodeDataLocked()
  174. }
  175. // pendingNodeDataLocked retrieves the number of node data entries pending for retrieval.
  176. // The caller must hold q.lock.
  177. func (q *queue) pendingNodeDataLocked() int {
  178. var n int
  179. if q.stateScheduler != nil {
  180. n = q.stateScheduler.Pending()
  181. }
  182. // Ensure that PendingNodeData doesn't return 0 until all state is written.
  183. if q.stateWriters > 0 {
  184. n++
  185. }
  186. return n
  187. }
  188. // InFlightHeaders retrieves whether there are header fetch requests currently
  189. // in flight.
  190. func (q *queue) InFlightHeaders() bool {
  191. q.lock.Lock()
  192. defer q.lock.Unlock()
  193. return len(q.headerPendPool) > 0
  194. }
  195. // InFlightBlocks retrieves whether there are block fetch requests currently in
  196. // flight.
  197. func (q *queue) InFlightBlocks() bool {
  198. q.lock.Lock()
  199. defer q.lock.Unlock()
  200. return len(q.blockPendPool) > 0
  201. }
  202. // InFlightReceipts retrieves whether there are receipt fetch requests currently
  203. // in flight.
  204. func (q *queue) InFlightReceipts() bool {
  205. q.lock.Lock()
  206. defer q.lock.Unlock()
  207. return len(q.receiptPendPool) > 0
  208. }
  209. // InFlightNodeData retrieves whether there are node data entry fetch requests
  210. // currently in flight.
  211. func (q *queue) InFlightNodeData() bool {
  212. q.lock.Lock()
  213. defer q.lock.Unlock()
  214. return len(q.statePendPool)+q.stateWriters > 0
  215. }
  216. // Idle returns if the queue is fully idle or has some data still inside. This
  217. // method is used by the tester to detect termination events.
  218. func (q *queue) Idle() bool {
  219. q.lock.Lock()
  220. defer q.lock.Unlock()
  221. queued := q.blockTaskQueue.Size() + q.receiptTaskQueue.Size() + q.stateTaskQueue.Size()
  222. pending := len(q.blockPendPool) + len(q.receiptPendPool) + len(q.statePendPool)
  223. cached := len(q.blockDonePool) + len(q.receiptDonePool)
  224. if q.stateScheduler != nil {
  225. queued += q.stateScheduler.Pending()
  226. }
  227. return (queued + pending + cached) == 0
  228. }
  229. // FastSyncPivot retrieves the currently used fast sync pivot point.
  230. func (q *queue) FastSyncPivot() uint64 {
  231. q.lock.Lock()
  232. defer q.lock.Unlock()
  233. return q.fastSyncPivot
  234. }
  235. // ShouldThrottleBlocks checks if the download should be throttled (active block (body)
  236. // fetches exceed block cache).
  237. func (q *queue) ShouldThrottleBlocks() bool {
  238. q.lock.Lock()
  239. defer q.lock.Unlock()
  240. // Calculate the currently in-flight block (body) requests
  241. pending := 0
  242. for _, request := range q.blockPendPool {
  243. pending += len(request.Hashes) + len(request.Headers)
  244. }
  245. // Throttle if more blocks (bodies) are in-flight than free space in the cache
  246. return pending >= len(q.resultCache)-len(q.blockDonePool)
  247. }
  248. // ShouldThrottleReceipts checks if the download should be throttled (active receipt
  249. // fetches exceed block cache).
  250. func (q *queue) ShouldThrottleReceipts() bool {
  251. q.lock.Lock()
  252. defer q.lock.Unlock()
  253. // Calculate the currently in-flight receipt requests
  254. pending := 0
  255. for _, request := range q.receiptPendPool {
  256. pending += len(request.Headers)
  257. }
  258. // Throttle if more receipts are in-flight than free space in the cache
  259. return pending >= len(q.resultCache)-len(q.receiptDonePool)
  260. }
  261. // ScheduleSkeleton adds a batch of header retrieval tasks to the queue to fill
  262. // up an already retrieved header skeleton.
  263. func (q *queue) ScheduleSkeleton(from uint64, skeleton []*types.Header) {
  264. q.lock.Lock()
  265. defer q.lock.Unlock()
  266. // No skeleton retrieval can be in progress, fail hard if so (huge implementation bug)
  267. if q.headerResults != nil {
  268. panic("skeleton assembly already in progress")
  269. }
  270. // Shedule all the header retrieval tasks for the skeleton assembly
  271. q.headerTaskPool = make(map[uint64]*types.Header)
  272. q.headerTaskQueue = prque.New()
  273. q.headerPeerMiss = make(map[string]map[uint64]struct{}) // Reset availability to correct invalid chains
  274. q.headerResults = make([]*types.Header, len(skeleton)*MaxHeaderFetch)
  275. q.headerProced = 0
  276. q.headerOffset = from
  277. q.headerContCh = make(chan bool, 1)
  278. for i, header := range skeleton {
  279. index := from + uint64(i*MaxHeaderFetch)
  280. q.headerTaskPool[index] = header
  281. q.headerTaskQueue.Push(index, -float32(index))
  282. }
  283. }
  284. // RetrieveHeaders retrieves the header chain assemble based on the scheduled
  285. // skeleton.
  286. func (q *queue) RetrieveHeaders() ([]*types.Header, int) {
  287. q.lock.Lock()
  288. defer q.lock.Unlock()
  289. headers, proced := q.headerResults, q.headerProced
  290. q.headerResults, q.headerProced = nil, 0
  291. return headers, proced
  292. }
  293. // Schedule adds a set of headers for the download queue for scheduling, returning
  294. // the new headers encountered.
  295. func (q *queue) Schedule(headers []*types.Header, from uint64) []*types.Header {
  296. q.lock.Lock()
  297. defer q.lock.Unlock()
  298. // Insert all the headers prioritised by the contained block number
  299. inserts := make([]*types.Header, 0, len(headers))
  300. for _, header := range headers {
  301. // Make sure chain order is honoured and preserved throughout
  302. hash := header.Hash()
  303. if header.Number == nil || header.Number.Uint64() != from {
  304. log.Warn(fmt.Sprintf("Header #%v [%x…] broke chain ordering, expected %d", header.Number, hash[:4], from))
  305. break
  306. }
  307. if q.headerHead != (common.Hash{}) && q.headerHead != header.ParentHash {
  308. log.Warn(fmt.Sprintf("Header #%v [%x…] broke chain ancestry", header.Number, hash[:4]))
  309. break
  310. }
  311. // Make sure no duplicate requests are executed
  312. if _, ok := q.blockTaskPool[hash]; ok {
  313. log.Warn(fmt.Sprintf("Header #%d [%x…] already scheduled for block fetch", header.Number.Uint64(), hash[:4]))
  314. continue
  315. }
  316. if _, ok := q.receiptTaskPool[hash]; ok {
  317. log.Warn(fmt.Sprintf("Header #%d [%x…] already scheduled for receipt fetch", header.Number.Uint64(), hash[:4]))
  318. continue
  319. }
  320. // Queue the header for content retrieval
  321. q.blockTaskPool[hash] = header
  322. q.blockTaskQueue.Push(header, -float32(header.Number.Uint64()))
  323. if q.mode == FastSync && header.Number.Uint64() <= q.fastSyncPivot {
  324. // Fast phase of the fast sync, retrieve receipts too
  325. q.receiptTaskPool[hash] = header
  326. q.receiptTaskQueue.Push(header, -float32(header.Number.Uint64()))
  327. }
  328. if q.mode == FastSync && header.Number.Uint64() == q.fastSyncPivot {
  329. // Pivoting point of the fast sync, switch the state retrieval to this
  330. log.Debug(fmt.Sprintf("Switching state downloads to %d [%x…]", header.Number.Uint64(), header.Hash().Bytes()[:4]))
  331. q.stateTaskIndex = 0
  332. q.stateTaskPool = make(map[common.Hash]int)
  333. q.stateTaskQueue.Reset()
  334. for _, req := range q.statePendPool {
  335. req.Hashes = make(map[common.Hash]int) // Make sure executing requests fail, but don't disappear
  336. }
  337. q.stateScheduler = state.NewStateSync(header.Root, q.stateDatabase)
  338. }
  339. inserts = append(inserts, header)
  340. q.headerHead = hash
  341. from++
  342. }
  343. return inserts
  344. }
  345. // WaitResults retrieves and permanently removes a batch of fetch
  346. // results from the cache. the result slice will be empty if the queue
  347. // has been closed.
  348. func (q *queue) WaitResults() []*fetchResult {
  349. q.lock.Lock()
  350. defer q.lock.Unlock()
  351. nproc := q.countProcessableItems()
  352. for nproc == 0 && !q.closed {
  353. q.active.Wait()
  354. nproc = q.countProcessableItems()
  355. }
  356. results := make([]*fetchResult, nproc)
  357. copy(results, q.resultCache[:nproc])
  358. if len(results) > 0 {
  359. // Mark results as done before dropping them from the cache.
  360. for _, result := range results {
  361. hash := result.Header.Hash()
  362. delete(q.blockDonePool, hash)
  363. delete(q.receiptDonePool, hash)
  364. }
  365. // Delete the results from the cache and clear the tail.
  366. copy(q.resultCache, q.resultCache[nproc:])
  367. for i := len(q.resultCache) - nproc; i < len(q.resultCache); i++ {
  368. q.resultCache[i] = nil
  369. }
  370. // Advance the expected block number of the first cache entry.
  371. q.resultOffset += uint64(nproc)
  372. }
  373. return results
  374. }
  375. // countProcessableItems counts the processable items.
  376. func (q *queue) countProcessableItems() int {
  377. for i, result := range q.resultCache {
  378. // Don't process incomplete or unavailable items.
  379. if result == nil || result.Pending > 0 {
  380. return i
  381. }
  382. // Special handling for the fast-sync pivot block:
  383. if q.mode == FastSync {
  384. bnum := result.Header.Number.Uint64()
  385. if bnum == q.fastSyncPivot {
  386. // If the state of the pivot block is not
  387. // available yet, we cannot proceed and return 0.
  388. //
  389. // Stop before processing the pivot block to ensure that
  390. // resultCache has space for fsHeaderForceVerify items. Not
  391. // doing this could leave us unable to download the required
  392. // amount of headers.
  393. if i > 0 || len(q.stateTaskPool) > 0 || q.pendingNodeDataLocked() > 0 {
  394. return i
  395. }
  396. for j := 0; j < fsHeaderForceVerify; j++ {
  397. if i+j+1 >= len(q.resultCache) || q.resultCache[i+j+1] == nil {
  398. return i
  399. }
  400. }
  401. }
  402. // If we're just the fast sync pivot, stop as well
  403. // because the following batch needs different insertion.
  404. // This simplifies handling the switchover in d.process.
  405. if bnum == q.fastSyncPivot+1 && i > 0 {
  406. return i
  407. }
  408. }
  409. }
  410. return len(q.resultCache)
  411. }
  412. // ReserveHeaders reserves a set of headers for the given peer, skipping any
  413. // previously failed batches.
  414. func (q *queue) ReserveHeaders(p *peer, count int) *fetchRequest {
  415. q.lock.Lock()
  416. defer q.lock.Unlock()
  417. // Short circuit if the peer's already downloading something (sanity check to
  418. // not corrupt state)
  419. if _, ok := q.headerPendPool[p.id]; ok {
  420. return nil
  421. }
  422. // Retrieve a batch of hashes, skipping previously failed ones
  423. send, skip := uint64(0), []uint64{}
  424. for send == 0 && !q.headerTaskQueue.Empty() {
  425. from, _ := q.headerTaskQueue.Pop()
  426. if q.headerPeerMiss[p.id] != nil {
  427. if _, ok := q.headerPeerMiss[p.id][from.(uint64)]; ok {
  428. skip = append(skip, from.(uint64))
  429. continue
  430. }
  431. }
  432. send = from.(uint64)
  433. }
  434. // Merge all the skipped batches back
  435. for _, from := range skip {
  436. q.headerTaskQueue.Push(from, -float32(from))
  437. }
  438. // Assemble and return the block download request
  439. if send == 0 {
  440. return nil
  441. }
  442. request := &fetchRequest{
  443. Peer: p,
  444. From: send,
  445. Time: time.Now(),
  446. }
  447. q.headerPendPool[p.id] = request
  448. return request
  449. }
  450. // ReserveNodeData reserves a set of node data hashes for the given peer, skipping
  451. // any previously failed download.
  452. func (q *queue) ReserveNodeData(p *peer, count int) *fetchRequest {
  453. // Create a task generator to fetch status-fetch tasks if all schedules ones are done
  454. generator := func(max int) {
  455. if q.stateScheduler != nil {
  456. for _, hash := range q.stateScheduler.Missing(max) {
  457. q.stateTaskPool[hash] = q.stateTaskIndex
  458. q.stateTaskQueue.Push(hash, -float32(q.stateTaskIndex))
  459. q.stateTaskIndex++
  460. }
  461. }
  462. }
  463. q.lock.Lock()
  464. defer q.lock.Unlock()
  465. return q.reserveHashes(p, count, q.stateTaskQueue, generator, q.statePendPool, maxInFlightStates)
  466. }
  467. // reserveHashes reserves a set of hashes for the given peer, skipping previously
  468. // failed ones.
  469. //
  470. // Note, this method expects the queue lock to be already held for writing. The
  471. // reason the lock is not obtained in here is because the parameters already need
  472. // to access the queue, so they already need a lock anyway.
  473. func (q *queue) reserveHashes(p *peer, count int, taskQueue *prque.Prque, taskGen func(int), pendPool map[string]*fetchRequest, maxPending int) *fetchRequest {
  474. // Short circuit if the peer's already downloading something (sanity check to
  475. // not corrupt state)
  476. if _, ok := pendPool[p.id]; ok {
  477. return nil
  478. }
  479. // Calculate an upper limit on the hashes we might fetch (i.e. throttling)
  480. allowance := maxPending
  481. if allowance > 0 {
  482. for _, request := range pendPool {
  483. allowance -= len(request.Hashes)
  484. }
  485. }
  486. // If there's a task generator, ask it to fill our task queue
  487. if taskGen != nil && taskQueue.Size() < allowance {
  488. taskGen(allowance - taskQueue.Size())
  489. }
  490. if taskQueue.Empty() {
  491. return nil
  492. }
  493. // Retrieve a batch of hashes, skipping previously failed ones
  494. send := make(map[common.Hash]int)
  495. skip := make(map[common.Hash]int)
  496. for proc := 0; (allowance == 0 || proc < allowance) && len(send) < count && !taskQueue.Empty(); proc++ {
  497. hash, priority := taskQueue.Pop()
  498. if p.Lacks(hash.(common.Hash)) {
  499. skip[hash.(common.Hash)] = int(priority)
  500. } else {
  501. send[hash.(common.Hash)] = int(priority)
  502. }
  503. }
  504. // Merge all the skipped hashes back
  505. for hash, index := range skip {
  506. taskQueue.Push(hash, float32(index))
  507. }
  508. // Assemble and return the block download request
  509. if len(send) == 0 {
  510. return nil
  511. }
  512. request := &fetchRequest{
  513. Peer: p,
  514. Hashes: send,
  515. Time: time.Now(),
  516. }
  517. pendPool[p.id] = request
  518. return request
  519. }
  520. // ReserveBodies reserves a set of body fetches for the given peer, skipping any
  521. // previously failed downloads. Beside the next batch of needed fetches, it also
  522. // returns a flag whether empty blocks were queued requiring processing.
  523. func (q *queue) ReserveBodies(p *peer, count int) (*fetchRequest, bool, error) {
  524. isNoop := func(header *types.Header) bool {
  525. return header.TxHash == types.EmptyRootHash && header.UncleHash == types.EmptyUncleHash
  526. }
  527. q.lock.Lock()
  528. defer q.lock.Unlock()
  529. return q.reserveHeaders(p, count, q.blockTaskPool, q.blockTaskQueue, q.blockPendPool, q.blockDonePool, isNoop)
  530. }
  531. // ReserveReceipts reserves a set of receipt fetches for the given peer, skipping
  532. // any previously failed downloads. Beside the next batch of needed fetches, it
  533. // also returns a flag whether empty receipts were queued requiring importing.
  534. func (q *queue) ReserveReceipts(p *peer, count int) (*fetchRequest, bool, error) {
  535. isNoop := func(header *types.Header) bool {
  536. return header.ReceiptHash == types.EmptyRootHash
  537. }
  538. q.lock.Lock()
  539. defer q.lock.Unlock()
  540. return q.reserveHeaders(p, count, q.receiptTaskPool, q.receiptTaskQueue, q.receiptPendPool, q.receiptDonePool, isNoop)
  541. }
  542. // reserveHeaders reserves a set of data download operations for a given peer,
  543. // skipping any previously failed ones. This method is a generic version used
  544. // by the individual special reservation functions.
  545. //
  546. // Note, this method expects the queue lock to be already held for writing. The
  547. // reason the lock is not obtained in here is because the parameters already need
  548. // to access the queue, so they already need a lock anyway.
  549. func (q *queue) reserveHeaders(p *peer, count int, taskPool map[common.Hash]*types.Header, taskQueue *prque.Prque,
  550. pendPool map[string]*fetchRequest, donePool map[common.Hash]struct{}, isNoop func(*types.Header) bool) (*fetchRequest, bool, error) {
  551. // Short circuit if the pool has been depleted, or if the peer's already
  552. // downloading something (sanity check not to corrupt state)
  553. if taskQueue.Empty() {
  554. return nil, false, nil
  555. }
  556. if _, ok := pendPool[p.id]; ok {
  557. return nil, false, nil
  558. }
  559. // Calculate an upper limit on the items we might fetch (i.e. throttling)
  560. space := len(q.resultCache) - len(donePool)
  561. for _, request := range pendPool {
  562. space -= len(request.Headers)
  563. }
  564. // Retrieve a batch of tasks, skipping previously failed ones
  565. send := make([]*types.Header, 0, count)
  566. skip := make([]*types.Header, 0)
  567. progress := false
  568. for proc := 0; proc < space && len(send) < count && !taskQueue.Empty(); proc++ {
  569. header := taskQueue.PopItem().(*types.Header)
  570. // If we're the first to request this task, initialise the result container
  571. index := int(header.Number.Int64() - int64(q.resultOffset))
  572. if index >= len(q.resultCache) || index < 0 {
  573. common.Report("index allocation went beyond available resultCache space")
  574. return nil, false, errInvalidChain
  575. }
  576. if q.resultCache[index] == nil {
  577. components := 1
  578. if q.mode == FastSync && header.Number.Uint64() <= q.fastSyncPivot {
  579. components = 2
  580. }
  581. q.resultCache[index] = &fetchResult{
  582. Pending: components,
  583. Header: header,
  584. }
  585. }
  586. // If this fetch task is a noop, skip this fetch operation
  587. if isNoop(header) {
  588. donePool[header.Hash()] = struct{}{}
  589. delete(taskPool, header.Hash())
  590. space, proc = space-1, proc-1
  591. q.resultCache[index].Pending--
  592. progress = true
  593. continue
  594. }
  595. // Otherwise unless the peer is known not to have the data, add to the retrieve list
  596. if p.Lacks(header.Hash()) {
  597. skip = append(skip, header)
  598. } else {
  599. send = append(send, header)
  600. }
  601. }
  602. // Merge all the skipped headers back
  603. for _, header := range skip {
  604. taskQueue.Push(header, -float32(header.Number.Uint64()))
  605. }
  606. if progress {
  607. // Wake WaitResults, resultCache was modified
  608. q.active.Signal()
  609. }
  610. // Assemble and return the block download request
  611. if len(send) == 0 {
  612. return nil, progress, nil
  613. }
  614. request := &fetchRequest{
  615. Peer: p,
  616. Headers: send,
  617. Time: time.Now(),
  618. }
  619. pendPool[p.id] = request
  620. return request, progress, nil
  621. }
  622. // CancelHeaders aborts a fetch request, returning all pending skeleton indexes to the queue.
  623. func (q *queue) CancelHeaders(request *fetchRequest) {
  624. q.cancel(request, q.headerTaskQueue, q.headerPendPool)
  625. }
  626. // CancelBodies aborts a body fetch request, returning all pending headers to the
  627. // task queue.
  628. func (q *queue) CancelBodies(request *fetchRequest) {
  629. q.cancel(request, q.blockTaskQueue, q.blockPendPool)
  630. }
  631. // CancelReceipts aborts a body fetch request, returning all pending headers to
  632. // the task queue.
  633. func (q *queue) CancelReceipts(request *fetchRequest) {
  634. q.cancel(request, q.receiptTaskQueue, q.receiptPendPool)
  635. }
  636. // CancelNodeData aborts a node state data fetch request, returning all pending
  637. // hashes to the task queue.
  638. func (q *queue) CancelNodeData(request *fetchRequest) {
  639. q.cancel(request, q.stateTaskQueue, q.statePendPool)
  640. }
  641. // Cancel aborts a fetch request, returning all pending hashes to the task queue.
  642. func (q *queue) cancel(request *fetchRequest, taskQueue *prque.Prque, pendPool map[string]*fetchRequest) {
  643. q.lock.Lock()
  644. defer q.lock.Unlock()
  645. if request.From > 0 {
  646. taskQueue.Push(request.From, -float32(request.From))
  647. }
  648. for hash, index := range request.Hashes {
  649. taskQueue.Push(hash, float32(index))
  650. }
  651. for _, header := range request.Headers {
  652. taskQueue.Push(header, -float32(header.Number.Uint64()))
  653. }
  654. delete(pendPool, request.Peer.id)
  655. }
  656. // Revoke cancels all pending requests belonging to a given peer. This method is
  657. // meant to be called during a peer drop to quickly reassign owned data fetches
  658. // to remaining nodes.
  659. func (q *queue) Revoke(peerId string) {
  660. q.lock.Lock()
  661. defer q.lock.Unlock()
  662. if request, ok := q.blockPendPool[peerId]; ok {
  663. for _, header := range request.Headers {
  664. q.blockTaskQueue.Push(header, -float32(header.Number.Uint64()))
  665. }
  666. delete(q.blockPendPool, peerId)
  667. }
  668. if request, ok := q.receiptPendPool[peerId]; ok {
  669. for _, header := range request.Headers {
  670. q.receiptTaskQueue.Push(header, -float32(header.Number.Uint64()))
  671. }
  672. delete(q.receiptPendPool, peerId)
  673. }
  674. if request, ok := q.statePendPool[peerId]; ok {
  675. for hash, index := range request.Hashes {
  676. q.stateTaskQueue.Push(hash, float32(index))
  677. }
  678. delete(q.statePendPool, peerId)
  679. }
  680. }
  681. // ExpireHeaders checks for in flight requests that exceeded a timeout allowance,
  682. // canceling them and returning the responsible peers for penalisation.
  683. func (q *queue) ExpireHeaders(timeout time.Duration) map[string]int {
  684. q.lock.Lock()
  685. defer q.lock.Unlock()
  686. return q.expire(timeout, q.headerPendPool, q.headerTaskQueue, headerTimeoutMeter)
  687. }
  688. // ExpireBodies checks for in flight block body requests that exceeded a timeout
  689. // allowance, canceling them and returning the responsible peers for penalisation.
  690. func (q *queue) ExpireBodies(timeout time.Duration) map[string]int {
  691. q.lock.Lock()
  692. defer q.lock.Unlock()
  693. return q.expire(timeout, q.blockPendPool, q.blockTaskQueue, bodyTimeoutMeter)
  694. }
  695. // ExpireReceipts checks for in flight receipt requests that exceeded a timeout
  696. // allowance, canceling them and returning the responsible peers for penalisation.
  697. func (q *queue) ExpireReceipts(timeout time.Duration) map[string]int {
  698. q.lock.Lock()
  699. defer q.lock.Unlock()
  700. return q.expire(timeout, q.receiptPendPool, q.receiptTaskQueue, receiptTimeoutMeter)
  701. }
  702. // ExpireNodeData checks for in flight node data requests that exceeded a timeout
  703. // allowance, canceling them and returning the responsible peers for penalisation.
  704. func (q *queue) ExpireNodeData(timeout time.Duration) map[string]int {
  705. q.lock.Lock()
  706. defer q.lock.Unlock()
  707. return q.expire(timeout, q.statePendPool, q.stateTaskQueue, stateTimeoutMeter)
  708. }
  709. // expire is the generic check that move expired tasks from a pending pool back
  710. // into a task pool, returning all entities caught with expired tasks.
  711. //
  712. // Note, this method expects the queue lock to be already held. The
  713. // reason the lock is not obtained in here is because the parameters already need
  714. // to access the queue, so they already need a lock anyway.
  715. func (q *queue) expire(timeout time.Duration, pendPool map[string]*fetchRequest, taskQueue *prque.Prque, timeoutMeter metrics.Meter) map[string]int {
  716. // Iterate over the expired requests and return each to the queue
  717. expiries := make(map[string]int)
  718. for id, request := range pendPool {
  719. if time.Since(request.Time) > timeout {
  720. // Update the metrics with the timeout
  721. timeoutMeter.Mark(1)
  722. // Return any non satisfied requests to the pool
  723. if request.From > 0 {
  724. taskQueue.Push(request.From, -float32(request.From))
  725. }
  726. for hash, index := range request.Hashes {
  727. taskQueue.Push(hash, float32(index))
  728. }
  729. for _, header := range request.Headers {
  730. taskQueue.Push(header, -float32(header.Number.Uint64()))
  731. }
  732. // Add the peer to the expiry report along the the number of failed requests
  733. expirations := len(request.Hashes)
  734. if expirations < len(request.Headers) {
  735. expirations = len(request.Headers)
  736. }
  737. expiries[id] = expirations
  738. }
  739. }
  740. // Remove the expired requests from the pending pool
  741. for id := range expiries {
  742. delete(pendPool, id)
  743. }
  744. return expiries
  745. }
  746. // DeliverHeaders injects a header retrieval response into the header results
  747. // cache. This method either accepts all headers it received, or none of them
  748. // if they do not map correctly to the skeleton.
  749. //
  750. // If the headers are accepted, the method makes an attempt to deliver the set
  751. // of ready headers to the processor to keep the pipeline full. However it will
  752. // not block to prevent stalling other pending deliveries.
  753. func (q *queue) DeliverHeaders(id string, headers []*types.Header, headerProcCh chan []*types.Header) (int, error) {
  754. q.lock.Lock()
  755. defer q.lock.Unlock()
  756. // Short circuit if the data was never requested
  757. request := q.headerPendPool[id]
  758. if request == nil {
  759. return 0, errNoFetchesPending
  760. }
  761. headerReqTimer.UpdateSince(request.Time)
  762. delete(q.headerPendPool, id)
  763. // Ensure headers can be mapped onto the skeleton chain
  764. target := q.headerTaskPool[request.From].Hash()
  765. accepted := len(headers) == MaxHeaderFetch
  766. if accepted {
  767. if headers[0].Number.Uint64() != request.From {
  768. log.Trace(fmt.Sprintf("Peer %s: first header #%v [%x…] broke chain ordering, expected %d", id, headers[0].Number, headers[0].Hash().Bytes()[:4], request.From))
  769. accepted = false
  770. } else if headers[len(headers)-1].Hash() != target {
  771. log.Trace(fmt.Sprintf("Peer %s: last header #%v [%x…] broke skeleton structure, expected %x", id, headers[len(headers)-1].Number, headers[len(headers)-1].Hash().Bytes()[:4], target[:4]))
  772. accepted = false
  773. }
  774. }
  775. if accepted {
  776. for i, header := range headers[1:] {
  777. hash := header.Hash()
  778. if want := request.From + 1 + uint64(i); header.Number.Uint64() != want {
  779. log.Warn(fmt.Sprintf("Peer %s: header #%v [%x…] broke chain ordering, expected %d", id, header.Number, hash[:4], want))
  780. accepted = false
  781. break
  782. }
  783. if headers[i].Hash() != header.ParentHash {
  784. log.Warn(fmt.Sprintf("Peer %s: header #%v [%x…] broke chain ancestry", id, header.Number, hash[:4]))
  785. accepted = false
  786. break
  787. }
  788. }
  789. }
  790. // If the batch of headers wasn't accepted, mark as unavailable
  791. if !accepted {
  792. log.Trace(fmt.Sprintf("Peer %s: skeleton filling from header #%d not accepted", id, request.From))
  793. miss := q.headerPeerMiss[id]
  794. if miss == nil {
  795. q.headerPeerMiss[id] = make(map[uint64]struct{})
  796. miss = q.headerPeerMiss[id]
  797. }
  798. miss[request.From] = struct{}{}
  799. q.headerTaskQueue.Push(request.From, -float32(request.From))
  800. return 0, errors.New("delivery not accepted")
  801. }
  802. // Clean up a successful fetch and try to deliver any sub-results
  803. copy(q.headerResults[request.From-q.headerOffset:], headers)
  804. delete(q.headerTaskPool, request.From)
  805. ready := 0
  806. for q.headerProced+ready < len(q.headerResults) && q.headerResults[q.headerProced+ready] != nil {
  807. ready += MaxHeaderFetch
  808. }
  809. if ready > 0 {
  810. // Headers are ready for delivery, gather them and push forward (non blocking)
  811. process := make([]*types.Header, ready)
  812. copy(process, q.headerResults[q.headerProced:q.headerProced+ready])
  813. select {
  814. case headerProcCh <- process:
  815. log.Trace(fmt.Sprintf("%s: pre-scheduled %d headers from #%v", id, len(process), process[0].Number))
  816. q.headerProced += len(process)
  817. default:
  818. }
  819. }
  820. // Check for termination and return
  821. if len(q.headerTaskPool) == 0 {
  822. q.headerContCh <- false
  823. }
  824. return len(headers), nil
  825. }
  826. // DeliverBodies injects a block body retrieval response into the results queue.
  827. // The method returns the number of blocks bodies accepted from the delivery and
  828. // also wakes any threads waiting for data delivery.
  829. func (q *queue) DeliverBodies(id string, txLists [][]*types.Transaction, uncleLists [][]*types.Header) (int, error) {
  830. q.lock.Lock()
  831. defer q.lock.Unlock()
  832. reconstruct := func(header *types.Header, index int, result *fetchResult) error {
  833. if types.DeriveSha(types.Transactions(txLists[index])) != header.TxHash || types.CalcUncleHash(uncleLists[index]) != header.UncleHash {
  834. return errInvalidBody
  835. }
  836. result.Transactions = txLists[index]
  837. result.Uncles = uncleLists[index]
  838. return nil
  839. }
  840. return q.deliver(id, q.blockTaskPool, q.blockTaskQueue, q.blockPendPool, q.blockDonePool, bodyReqTimer, len(txLists), reconstruct)
  841. }
  842. // DeliverReceipts injects a receipt retrieval response into the results queue.
  843. // The method returns the number of transaction receipts accepted from the delivery
  844. // and also wakes any threads waiting for data delivery.
  845. func (q *queue) DeliverReceipts(id string, receiptList [][]*types.Receipt) (int, error) {
  846. q.lock.Lock()
  847. defer q.lock.Unlock()
  848. reconstruct := func(header *types.Header, index int, result *fetchResult) error {
  849. if types.DeriveSha(types.Receipts(receiptList[index])) != header.ReceiptHash {
  850. return errInvalidReceipt
  851. }
  852. result.Receipts = receiptList[index]
  853. return nil
  854. }
  855. return q.deliver(id, q.receiptTaskPool, q.receiptTaskQueue, q.receiptPendPool, q.receiptDonePool, receiptReqTimer, len(receiptList), reconstruct)
  856. }
  857. // deliver injects a data retrieval response into the results queue.
  858. //
  859. // Note, this method expects the queue lock to be already held for writing. The
  860. // reason the lock is not obtained in here is because the parameters already need
  861. // to access the queue, so they already need a lock anyway.
  862. func (q *queue) deliver(id string, taskPool map[common.Hash]*types.Header, taskQueue *prque.Prque,
  863. pendPool map[string]*fetchRequest, donePool map[common.Hash]struct{}, reqTimer metrics.Timer,
  864. results int, reconstruct func(header *types.Header, index int, result *fetchResult) error) (int, error) {
  865. // Short circuit if the data was never requested
  866. request := pendPool[id]
  867. if request == nil {
  868. return 0, errNoFetchesPending
  869. }
  870. reqTimer.UpdateSince(request.Time)
  871. delete(pendPool, id)
  872. // If no data items were retrieved, mark them as unavailable for the origin peer
  873. if results == 0 {
  874. for _, header := range request.Headers {
  875. request.Peer.MarkLacking(header.Hash())
  876. }
  877. }
  878. // Assemble each of the results with their headers and retrieved data parts
  879. var (
  880. accepted int
  881. failure error
  882. useful bool
  883. )
  884. for i, header := range request.Headers {
  885. // Short circuit assembly if no more fetch results are found
  886. if i >= results {
  887. break
  888. }
  889. // Reconstruct the next result if contents match up
  890. index := int(header.Number.Int64() - int64(q.resultOffset))
  891. if index >= len(q.resultCache) || index < 0 || q.resultCache[index] == nil {
  892. failure = errInvalidChain
  893. break
  894. }
  895. if err := reconstruct(header, i, q.resultCache[index]); err != nil {
  896. failure = err
  897. break
  898. }
  899. donePool[header.Hash()] = struct{}{}
  900. q.resultCache[index].Pending--
  901. useful = true
  902. accepted++
  903. // Clean up a successful fetch
  904. request.Headers[i] = nil
  905. delete(taskPool, header.Hash())
  906. }
  907. // Return all failed or missing fetches to the queue
  908. for _, header := range request.Headers {
  909. if header != nil {
  910. taskQueue.Push(header, -float32(header.Number.Uint64()))
  911. }
  912. }
  913. // Wake up WaitResults
  914. if accepted > 0 {
  915. q.active.Signal()
  916. }
  917. // If none of the data was good, it's a stale delivery
  918. switch {
  919. case failure == nil || failure == errInvalidChain:
  920. return accepted, failure
  921. case useful:
  922. return accepted, fmt.Errorf("partial failure: %v", failure)
  923. default:
  924. return accepted, errStaleDelivery
  925. }
  926. }
  927. // DeliverNodeData injects a node state data retrieval response into the queue.
  928. // The method returns the number of node state accepted from the delivery.
  929. func (q *queue) DeliverNodeData(id string, data [][]byte, callback func(int, bool, error)) (int, error) {
  930. q.lock.Lock()
  931. defer q.lock.Unlock()
  932. // Short circuit if the data was never requested
  933. request := q.statePendPool[id]
  934. if request == nil {
  935. return 0, errNoFetchesPending
  936. }
  937. stateReqTimer.UpdateSince(request.Time)
  938. delete(q.statePendPool, id)
  939. // If no data was retrieved, mark their hashes as unavailable for the origin peer
  940. if len(data) == 0 {
  941. for hash := range request.Hashes {
  942. request.Peer.MarkLacking(hash)
  943. }
  944. }
  945. // Iterate over the downloaded data and verify each of them
  946. errs := make([]error, 0)
  947. process := []trie.SyncResult{}
  948. for _, blob := range data {
  949. // Skip any state trie entries that were not requested
  950. hash := common.BytesToHash(crypto.Keccak256(blob))
  951. if _, ok := request.Hashes[hash]; !ok {
  952. errs = append(errs, fmt.Errorf("non-requested state data %x", hash))
  953. continue
  954. }
  955. // Inject the next state trie item into the processing queue
  956. process = append(process, trie.SyncResult{Hash: hash, Data: blob})
  957. delete(request.Hashes, hash)
  958. delete(q.stateTaskPool, hash)
  959. }
  960. // Return all failed or missing fetches to the queue
  961. for hash, index := range request.Hashes {
  962. q.stateTaskQueue.Push(hash, float32(index))
  963. }
  964. if q.stateScheduler == nil {
  965. return 0, errNoFetchesPending
  966. }
  967. // Run valid nodes through the trie download scheduler. It writes completed nodes to a
  968. // batch, which is committed asynchronously. This may lead to over-fetches because the
  969. // scheduler treats everything as written after Process has returned, but it's
  970. // unlikely to be an issue in practice.
  971. batch := q.stateDatabase.NewBatch()
  972. progressed, nproc, procerr := q.stateScheduler.Process(process, batch)
  973. q.stateWriters += 1
  974. go func() {
  975. if procerr == nil {
  976. nproc = len(process)
  977. procerr = batch.Write()
  978. }
  979. // Return processing errors through the callback so the sync gets canceled. The
  980. // number of writers is decremented prior to the call so PendingNodeData will
  981. // return zero when the callback runs.
  982. q.lock.Lock()
  983. q.stateWriters -= 1
  984. q.lock.Unlock()
  985. callback(nproc, progressed, procerr)
  986. // Wake up WaitResults after the state has been written because it might be
  987. // waiting for completion of the pivot block's state download.
  988. q.active.Signal()
  989. }()
  990. // If none of the data items were good, it's a stale delivery
  991. switch {
  992. case len(errs) == 0:
  993. return len(process), nil
  994. case len(errs) == len(request.Hashes):
  995. return len(process), errStaleDelivery
  996. default:
  997. return len(process), fmt.Errorf("multiple failures: %v", errs)
  998. }
  999. }
  1000. // Prepare configures the result cache to allow accepting and caching inbound
  1001. // fetch results.
  1002. func (q *queue) Prepare(offset uint64, mode SyncMode, pivot uint64, head *types.Header) {
  1003. q.lock.Lock()
  1004. defer q.lock.Unlock()
  1005. // Prepare the queue for sync results
  1006. if q.resultOffset < offset {
  1007. q.resultOffset = offset
  1008. }
  1009. q.fastSyncPivot = pivot
  1010. q.mode = mode
  1011. // If long running fast sync, also start up a head stateretrieval immediately
  1012. if mode == FastSync && pivot > 0 {
  1013. q.stateScheduler = state.NewStateSync(head.Root, q.stateDatabase)
  1014. }
  1015. }