queue.go 40 KB

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