queue.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  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, switch the state retrieval to this
  327. glog.V(logger.Debug).Infof("Switching state downloads to %d [%x…]", header.Number.Uint64(), header.Hash().Bytes()[:4])
  328. q.stateTaskIndex = 0
  329. q.stateTaskPool = make(map[common.Hash]int)
  330. q.stateTaskQueue.Reset()
  331. for _, req := range q.statePendPool {
  332. req.Hashes = make(map[common.Hash]int) // Make sure executing requests fail, but don't disappear
  333. }
  334. q.stateSchedLock.Lock()
  335. q.stateScheduler = state.NewStateSync(header.Root, q.stateDatabase)
  336. q.stateSchedLock.Unlock()
  337. }
  338. inserts = append(inserts, header)
  339. q.headerHead = hash
  340. from++
  341. }
  342. return inserts
  343. }
  344. // WaitResults retrieves and permanently removes a batch of fetch
  345. // results from the cache. the result slice will be empty if the queue
  346. // has been closed.
  347. func (q *queue) WaitResults() []*fetchResult {
  348. q.lock.Lock()
  349. defer q.lock.Unlock()
  350. nproc := q.countProcessableItems()
  351. for nproc == 0 && !q.closed {
  352. q.active.Wait()
  353. nproc = q.countProcessableItems()
  354. }
  355. results := make([]*fetchResult, nproc)
  356. copy(results, q.resultCache[:nproc])
  357. if len(results) > 0 {
  358. // Mark results as done before dropping them from the cache.
  359. for _, result := range results {
  360. hash := result.Header.Hash()
  361. delete(q.blockDonePool, hash)
  362. delete(q.receiptDonePool, hash)
  363. }
  364. // Delete the results from the cache and clear the tail.
  365. copy(q.resultCache, q.resultCache[nproc:])
  366. for i := len(q.resultCache) - nproc; i < len(q.resultCache); i++ {
  367. q.resultCache[i] = nil
  368. }
  369. // Advance the expected block number of the first cache entry.
  370. q.resultOffset += uint64(nproc)
  371. }
  372. return results
  373. }
  374. // countProcessableItems counts the processable items.
  375. func (q *queue) countProcessableItems() int {
  376. for i, result := range q.resultCache {
  377. // Don't process incomplete or unavailable items.
  378. if result == nil || result.Pending > 0 {
  379. return i
  380. }
  381. // Special handling for the fast-sync pivot block:
  382. if q.mode == FastSync {
  383. bnum := result.Header.Number.Uint64()
  384. if bnum == q.fastSyncPivot {
  385. // If the state of the pivot block is not
  386. // available yet, we cannot proceed and return 0.
  387. //
  388. // Stop before processing the pivot block to ensure that
  389. // resultCache has space for fsHeaderForceVerify items. Not
  390. // doing this could leave us unable to download the required
  391. // amount of headers.
  392. if i > 0 || len(q.stateTaskPool) > 0 || q.PendingNodeData() > 0 {
  393. return i
  394. }
  395. for j := 0; j < fsHeaderForceVerify; j++ {
  396. if i+j+1 >= len(q.resultCache) || q.resultCache[i+j+1] == nil {
  397. return i
  398. }
  399. }
  400. }
  401. // If we're just the fast sync pivot, stop as well
  402. // because the following batch needs different insertion.
  403. // This simplifies handling the switchover in d.process.
  404. if bnum == q.fastSyncPivot+1 && i > 0 {
  405. return i
  406. }
  407. }
  408. }
  409. return len(q.resultCache)
  410. }
  411. // ReserveHeaders reserves a set of headers for the given peer, skipping any
  412. // previously failed batches.
  413. func (q *queue) ReserveHeaders(p *peer, count int) *fetchRequest {
  414. q.lock.Lock()
  415. defer q.lock.Unlock()
  416. // Short circuit if the peer's already downloading something (sanity check to
  417. // not corrupt state)
  418. if _, ok := q.headerPendPool[p.id]; ok {
  419. return nil
  420. }
  421. // Retrieve a batch of hashes, skipping previously failed ones
  422. send, skip := uint64(0), []uint64{}
  423. for send == 0 && !q.headerTaskQueue.Empty() {
  424. from, _ := q.headerTaskQueue.Pop()
  425. if q.headerPeerMiss[p.id] != nil {
  426. if _, ok := q.headerPeerMiss[p.id][from.(uint64)]; ok {
  427. skip = append(skip, from.(uint64))
  428. continue
  429. }
  430. }
  431. send = from.(uint64)
  432. }
  433. // Merge all the skipped batches back
  434. for _, from := range skip {
  435. q.headerTaskQueue.Push(from, -float32(from))
  436. }
  437. // Assemble and return the block download request
  438. if send == 0 {
  439. return nil
  440. }
  441. request := &fetchRequest{
  442. Peer: p,
  443. From: send,
  444. Time: time.Now(),
  445. }
  446. q.headerPendPool[p.id] = request
  447. return request
  448. }
  449. // ReserveNodeData reserves a set of node data hashes for the given peer, skipping
  450. // any previously failed download.
  451. func (q *queue) ReserveNodeData(p *peer, count int) *fetchRequest {
  452. // Create a task generator to fetch status-fetch tasks if all schedules ones are done
  453. generator := func(max int) {
  454. q.stateSchedLock.Lock()
  455. defer q.stateSchedLock.Unlock()
  456. if q.stateScheduler != nil {
  457. for _, hash := range q.stateScheduler.Missing(max) {
  458. q.stateTaskPool[hash] = q.stateTaskIndex
  459. q.stateTaskQueue.Push(hash, -float32(q.stateTaskIndex))
  460. q.stateTaskIndex++
  461. }
  462. }
  463. }
  464. q.lock.Lock()
  465. defer q.lock.Unlock()
  466. return q.reserveHashes(p, count, q.stateTaskQueue, generator, q.statePendPool, maxInFlightStates)
  467. }
  468. // reserveHashes reserves a set of hashes for the given peer, skipping previously
  469. // failed ones.
  470. //
  471. // Note, this method expects the queue lock to be already held for writing. The
  472. // reason the lock is not obtained in here is because the parameters already need
  473. // to access the queue, so they already need a lock anyway.
  474. func (q *queue) reserveHashes(p *peer, count int, taskQueue *prque.Prque, taskGen func(int), pendPool map[string]*fetchRequest, maxPending int) *fetchRequest {
  475. // Short circuit if the peer's already downloading something (sanity check to
  476. // not corrupt state)
  477. if _, ok := pendPool[p.id]; ok {
  478. return nil
  479. }
  480. // Calculate an upper limit on the hashes we might fetch (i.e. throttling)
  481. allowance := maxPending
  482. if allowance > 0 {
  483. for _, request := range pendPool {
  484. allowance -= len(request.Hashes)
  485. }
  486. }
  487. // If there's a task generator, ask it to fill our task queue
  488. if taskGen != nil && taskQueue.Size() < allowance {
  489. taskGen(allowance - taskQueue.Size())
  490. }
  491. if taskQueue.Empty() {
  492. return nil
  493. }
  494. // Retrieve a batch of hashes, skipping previously failed ones
  495. send := make(map[common.Hash]int)
  496. skip := make(map[common.Hash]int)
  497. for proc := 0; (allowance == 0 || proc < allowance) && len(send) < count && !taskQueue.Empty(); proc++ {
  498. hash, priority := taskQueue.Pop()
  499. if p.Lacks(hash.(common.Hash)) {
  500. skip[hash.(common.Hash)] = int(priority)
  501. } else {
  502. send[hash.(common.Hash)] = int(priority)
  503. }
  504. }
  505. // Merge all the skipped hashes back
  506. for hash, index := range skip {
  507. taskQueue.Push(hash, float32(index))
  508. }
  509. // Assemble and return the block download request
  510. if len(send) == 0 {
  511. return nil
  512. }
  513. request := &fetchRequest{
  514. Peer: p,
  515. Hashes: send,
  516. Time: time.Now(),
  517. }
  518. pendPool[p.id] = request
  519. return request
  520. }
  521. // ReserveBodies reserves a set of body fetches for the given peer, skipping any
  522. // previously failed downloads. Beside the next batch of needed fetches, it also
  523. // returns a flag whether empty blocks were queued requiring processing.
  524. func (q *queue) ReserveBodies(p *peer, count int) (*fetchRequest, bool, error) {
  525. isNoop := func(header *types.Header) bool {
  526. return header.TxHash == types.EmptyRootHash && header.UncleHash == types.EmptyUncleHash
  527. }
  528. q.lock.Lock()
  529. defer q.lock.Unlock()
  530. return q.reserveHeaders(p, count, q.blockTaskPool, q.blockTaskQueue, q.blockPendPool, q.blockDonePool, isNoop)
  531. }
  532. // ReserveReceipts reserves a set of receipt fetches for the given peer, skipping
  533. // any previously failed downloads. Beside the next batch of needed fetches, it
  534. // also returns a flag whether empty receipts were queued requiring importing.
  535. func (q *queue) ReserveReceipts(p *peer, count int) (*fetchRequest, bool, error) {
  536. isNoop := func(header *types.Header) bool {
  537. return header.ReceiptHash == types.EmptyRootHash
  538. }
  539. q.lock.Lock()
  540. defer q.lock.Unlock()
  541. return q.reserveHeaders(p, count, q.receiptTaskPool, q.receiptTaskQueue, q.receiptPendPool, q.receiptDonePool, isNoop)
  542. }
  543. // reserveHeaders reserves a set of data download operations for a given peer,
  544. // skipping any previously failed ones. This method is a generic version used
  545. // by the individual special reservation functions.
  546. //
  547. // Note, this method expects the queue lock to be already held for writing. The
  548. // reason the lock is not obtained in here is because the parameters already need
  549. // to access the queue, so they already need a lock anyway.
  550. func (q *queue) reserveHeaders(p *peer, count int, taskPool map[common.Hash]*types.Header, taskQueue *prque.Prque,
  551. pendPool map[string]*fetchRequest, donePool map[common.Hash]struct{}, isNoop func(*types.Header) bool) (*fetchRequest, bool, error) {
  552. // Short circuit if the pool has been depleted, or if the peer's already
  553. // downloading something (sanity check not to corrupt state)
  554. if taskQueue.Empty() {
  555. return nil, false, nil
  556. }
  557. if _, ok := pendPool[p.id]; ok {
  558. return nil, false, nil
  559. }
  560. // Calculate an upper limit on the items we might fetch (i.e. throttling)
  561. space := len(q.resultCache) - len(donePool)
  562. for _, request := range pendPool {
  563. space -= len(request.Headers)
  564. }
  565. // Retrieve a batch of tasks, skipping previously failed ones
  566. send := make([]*types.Header, 0, count)
  567. skip := make([]*types.Header, 0)
  568. progress := false
  569. for proc := 0; proc < space && len(send) < count && !taskQueue.Empty(); proc++ {
  570. header := taskQueue.PopItem().(*types.Header)
  571. // If we're the first to request this task, initialise the result container
  572. index := int(header.Number.Int64() - int64(q.resultOffset))
  573. if index >= len(q.resultCache) || index < 0 {
  574. common.Report("index allocation went beyond available resultCache space")
  575. return nil, false, errInvalidChain
  576. }
  577. if q.resultCache[index] == nil {
  578. components := 1
  579. if q.mode == FastSync && header.Number.Uint64() <= q.fastSyncPivot {
  580. components = 2
  581. }
  582. q.resultCache[index] = &fetchResult{
  583. Pending: components,
  584. Header: header,
  585. }
  586. }
  587. // If this fetch task is a noop, skip this fetch operation
  588. if isNoop(header) {
  589. donePool[header.Hash()] = struct{}{}
  590. delete(taskPool, header.Hash())
  591. space, proc = space-1, proc-1
  592. q.resultCache[index].Pending--
  593. progress = true
  594. continue
  595. }
  596. // Otherwise unless the peer is known not to have the data, add to the retrieve list
  597. if p.Lacks(header.Hash()) {
  598. skip = append(skip, header)
  599. } else {
  600. send = append(send, header)
  601. }
  602. }
  603. // Merge all the skipped headers back
  604. for _, header := range skip {
  605. taskQueue.Push(header, -float32(header.Number.Uint64()))
  606. }
  607. if progress {
  608. // Wake WaitResults, resultCache was modified
  609. q.active.Signal()
  610. }
  611. // Assemble and return the block download request
  612. if len(send) == 0 {
  613. return nil, progress, nil
  614. }
  615. request := &fetchRequest{
  616. Peer: p,
  617. Headers: send,
  618. Time: time.Now(),
  619. }
  620. pendPool[p.id] = request
  621. return request, progress, nil
  622. }
  623. // CancelHeaders aborts a fetch request, returning all pending skeleton indexes to the queue.
  624. func (q *queue) CancelHeaders(request *fetchRequest) {
  625. q.cancel(request, q.headerTaskQueue, q.headerPendPool)
  626. }
  627. // CancelBodies aborts a body fetch request, returning all pending headers to the
  628. // task queue.
  629. func (q *queue) CancelBodies(request *fetchRequest) {
  630. q.cancel(request, q.blockTaskQueue, q.blockPendPool)
  631. }
  632. // CancelReceipts aborts a body fetch request, returning all pending headers to
  633. // the task queue.
  634. func (q *queue) CancelReceipts(request *fetchRequest) {
  635. q.cancel(request, q.receiptTaskQueue, q.receiptPendPool)
  636. }
  637. // CancelNodeData aborts a node state data fetch request, returning all pending
  638. // hashes to the task queue.
  639. func (q *queue) CancelNodeData(request *fetchRequest) {
  640. q.cancel(request, q.stateTaskQueue, q.statePendPool)
  641. }
  642. // Cancel aborts a fetch request, returning all pending hashes to the task queue.
  643. func (q *queue) cancel(request *fetchRequest, taskQueue *prque.Prque, pendPool map[string]*fetchRequest) {
  644. q.lock.Lock()
  645. defer q.lock.Unlock()
  646. if request.From > 0 {
  647. taskQueue.Push(request.From, -float32(request.From))
  648. }
  649. for hash, index := range request.Hashes {
  650. taskQueue.Push(hash, float32(index))
  651. }
  652. for _, header := range request.Headers {
  653. taskQueue.Push(header, -float32(header.Number.Uint64()))
  654. }
  655. delete(pendPool, request.Peer.id)
  656. }
  657. // Revoke cancels all pending requests belonging to a given peer. This method is
  658. // meant to be called during a peer drop to quickly reassign owned data fetches
  659. // to remaining nodes.
  660. func (q *queue) Revoke(peerId string) {
  661. q.lock.Lock()
  662. defer q.lock.Unlock()
  663. if request, ok := q.blockPendPool[peerId]; ok {
  664. for _, header := range request.Headers {
  665. q.blockTaskQueue.Push(header, -float32(header.Number.Uint64()))
  666. }
  667. delete(q.blockPendPool, peerId)
  668. }
  669. if request, ok := q.receiptPendPool[peerId]; ok {
  670. for _, header := range request.Headers {
  671. q.receiptTaskQueue.Push(header, -float32(header.Number.Uint64()))
  672. }
  673. delete(q.receiptPendPool, peerId)
  674. }
  675. if request, ok := q.statePendPool[peerId]; ok {
  676. for hash, index := range request.Hashes {
  677. q.stateTaskQueue.Push(hash, float32(index))
  678. }
  679. delete(q.statePendPool, peerId)
  680. }
  681. }
  682. // ExpireHeaders checks for in flight requests that exceeded a timeout allowance,
  683. // canceling them and returning the responsible peers for penalisation.
  684. func (q *queue) ExpireHeaders(timeout time.Duration) map[string]int {
  685. q.lock.Lock()
  686. defer q.lock.Unlock()
  687. return q.expire(timeout, q.headerPendPool, q.headerTaskQueue, headerTimeoutMeter)
  688. }
  689. // ExpireBodies checks for in flight block body requests that exceeded a timeout
  690. // allowance, canceling them and returning the responsible peers for penalisation.
  691. func (q *queue) ExpireBodies(timeout time.Duration) map[string]int {
  692. q.lock.Lock()
  693. defer q.lock.Unlock()
  694. return q.expire(timeout, q.blockPendPool, q.blockTaskQueue, bodyTimeoutMeter)
  695. }
  696. // ExpireReceipts checks for in flight receipt requests that exceeded a timeout
  697. // allowance, canceling them and returning the responsible peers for penalisation.
  698. func (q *queue) ExpireReceipts(timeout time.Duration) map[string]int {
  699. q.lock.Lock()
  700. defer q.lock.Unlock()
  701. return q.expire(timeout, q.receiptPendPool, q.receiptTaskQueue, receiptTimeoutMeter)
  702. }
  703. // ExpireNodeData checks for in flight node data requests that exceeded a timeout
  704. // allowance, canceling them and returning the responsible peers for penalisation.
  705. func (q *queue) ExpireNodeData(timeout time.Duration) map[string]int {
  706. q.lock.Lock()
  707. defer q.lock.Unlock()
  708. return q.expire(timeout, q.statePendPool, q.stateTaskQueue, stateTimeoutMeter)
  709. }
  710. // expire is the generic check that move expired tasks from a pending pool back
  711. // into a task pool, returning all entities caught with expired tasks.
  712. //
  713. // Note, this method expects the queue lock to be already held. The
  714. // reason the lock is not obtained in here is because the parameters already need
  715. // to access the queue, so they already need a lock anyway.
  716. func (q *queue) expire(timeout time.Duration, pendPool map[string]*fetchRequest, taskQueue *prque.Prque, timeoutMeter metrics.Meter) map[string]int {
  717. // Iterate over the expired requests and return each to the queue
  718. expiries := make(map[string]int)
  719. for id, request := range pendPool {
  720. if time.Since(request.Time) > timeout {
  721. // Update the metrics with the timeout
  722. timeoutMeter.Mark(1)
  723. // Return any non satisfied requests to the pool
  724. if request.From > 0 {
  725. taskQueue.Push(request.From, -float32(request.From))
  726. }
  727. for hash, index := range request.Hashes {
  728. taskQueue.Push(hash, float32(index))
  729. }
  730. for _, header := range request.Headers {
  731. taskQueue.Push(header, -float32(header.Number.Uint64()))
  732. }
  733. // Add the peer to the expiry report along the the number of failed requests
  734. expirations := len(request.Hashes)
  735. if expirations < len(request.Headers) {
  736. expirations = len(request.Headers)
  737. }
  738. expiries[id] = expirations
  739. }
  740. }
  741. // Remove the expired requests from the pending pool
  742. for id, _ := range expiries {
  743. delete(pendPool, id)
  744. }
  745. return expiries
  746. }
  747. // DeliverHeaders injects a header retrieval response into the header results
  748. // cache. This method either accepts all headers it received, or none of them
  749. // if they do not map correctly to the skeleton.
  750. //
  751. // If the headers are accepted, the method makes an attempt to deliver the set
  752. // of ready headers to the processor to keep the pipeline full. However it will
  753. // not block to prevent stalling other pending deliveries.
  754. func (q *queue) DeliverHeaders(id string, headers []*types.Header, headerProcCh chan []*types.Header) (int, error) {
  755. q.lock.Lock()
  756. defer q.lock.Unlock()
  757. // Short circuit if the data was never requested
  758. request := q.headerPendPool[id]
  759. if request == nil {
  760. return 0, errNoFetchesPending
  761. }
  762. headerReqTimer.UpdateSince(request.Time)
  763. delete(q.headerPendPool, id)
  764. // Ensure headers can be mapped onto the skeleton chain
  765. target := q.headerTaskPool[request.From].Hash()
  766. accepted := len(headers) == MaxHeaderFetch
  767. if accepted {
  768. if headers[0].Number.Uint64() != request.From {
  769. 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)
  770. accepted = false
  771. } else if headers[len(headers)-1].Hash() != target {
  772. 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])
  773. accepted = false
  774. }
  775. }
  776. if accepted {
  777. for i, header := range headers[1:] {
  778. hash := header.Hash()
  779. if want := request.From + 1 + uint64(i); header.Number.Uint64() != want {
  780. glog.V(logger.Warn).Infof("Peer %s: header #%v [%x…] broke chain ordering, expected %d", id, header.Number, hash[:4], want)
  781. accepted = false
  782. break
  783. }
  784. if headers[i].Hash() != header.ParentHash {
  785. glog.V(logger.Warn).Infof("Peer %s: header #%v [%x…] broke chain ancestry", id, header.Number, hash[:4])
  786. accepted = false
  787. break
  788. }
  789. }
  790. }
  791. // If the batch of headers wasn't accepted, mark as unavailable
  792. if !accepted {
  793. glog.V(logger.Detail).Infof("Peer %s: skeleton filling from header #%d not accepted", id, request.From)
  794. miss := q.headerPeerMiss[id]
  795. if miss == nil {
  796. q.headerPeerMiss[id] = make(map[uint64]struct{})
  797. miss = q.headerPeerMiss[id]
  798. }
  799. miss[request.From] = struct{}{}
  800. q.headerTaskQueue.Push(request.From, -float32(request.From))
  801. return 0, errors.New("delivery not accepted")
  802. }
  803. // Clean up a successful fetch and try to deliver any sub-results
  804. copy(q.headerResults[request.From-q.headerOffset:], headers)
  805. delete(q.headerTaskPool, request.From)
  806. ready := 0
  807. for q.headerProced+ready < len(q.headerResults) && q.headerResults[q.headerProced+ready] != nil {
  808. ready += MaxHeaderFetch
  809. }
  810. if ready > 0 {
  811. // Headers are ready for delivery, gather them and push forward (non blocking)
  812. process := make([]*types.Header, ready)
  813. copy(process, q.headerResults[q.headerProced:q.headerProced+ready])
  814. select {
  815. case headerProcCh <- process:
  816. glog.V(logger.Detail).Infof("%s: pre-scheduled %d headers from #%v", id, len(process), process[0].Number)
  817. q.headerProced += len(process)
  818. default:
  819. }
  820. }
  821. // Check for termination and return
  822. if len(q.headerTaskPool) == 0 {
  823. q.headerContCh <- false
  824. }
  825. return len(headers), nil
  826. }
  827. // DeliverBodies injects a block body retrieval response into the results queue.
  828. // The method returns the number of blocks bodies accepted from the delivery and
  829. // also wakes any threads waiting for data delivery.
  830. func (q *queue) DeliverBodies(id string, txLists [][]*types.Transaction, uncleLists [][]*types.Header) (int, error) {
  831. q.lock.Lock()
  832. defer q.lock.Unlock()
  833. reconstruct := func(header *types.Header, index int, result *fetchResult) error {
  834. if types.DeriveSha(types.Transactions(txLists[index])) != header.TxHash || types.CalcUncleHash(uncleLists[index]) != header.UncleHash {
  835. return errInvalidBody
  836. }
  837. result.Transactions = txLists[index]
  838. result.Uncles = uncleLists[index]
  839. return nil
  840. }
  841. return q.deliver(id, q.blockTaskPool, q.blockTaskQueue, q.blockPendPool, q.blockDonePool, bodyReqTimer, len(txLists), reconstruct)
  842. }
  843. // DeliverReceipts injects a receipt retrieval response into the results queue.
  844. // The method returns the number of transaction receipts accepted from the delivery
  845. // and also wakes any threads waiting for data delivery.
  846. func (q *queue) DeliverReceipts(id string, receiptList [][]*types.Receipt) (int, error) {
  847. q.lock.Lock()
  848. defer q.lock.Unlock()
  849. reconstruct := func(header *types.Header, index int, result *fetchResult) error {
  850. if types.DeriveSha(types.Receipts(receiptList[index])) != header.ReceiptHash {
  851. return errInvalidReceipt
  852. }
  853. result.Receipts = receiptList[index]
  854. return nil
  855. }
  856. return q.deliver(id, q.receiptTaskPool, q.receiptTaskQueue, q.receiptPendPool, q.receiptDonePool, receiptReqTimer, len(receiptList), reconstruct)
  857. }
  858. // deliver injects a data retrieval response into the results queue.
  859. //
  860. // Note, this method expects the queue lock to be already held for writing. The
  861. // reason the lock is not obtained in here is because the parameters already need
  862. // to access the queue, so they already need a lock anyway.
  863. func (q *queue) deliver(id string, taskPool map[common.Hash]*types.Header, taskQueue *prque.Prque,
  864. pendPool map[string]*fetchRequest, donePool map[common.Hash]struct{}, reqTimer metrics.Timer,
  865. results int, reconstruct func(header *types.Header, index int, result *fetchResult) error) (int, error) {
  866. // Short circuit if the data was never requested
  867. request := pendPool[id]
  868. if request == nil {
  869. return 0, errNoFetchesPending
  870. }
  871. reqTimer.UpdateSince(request.Time)
  872. delete(pendPool, id)
  873. // If no data items were retrieved, mark them as unavailable for the origin peer
  874. if results == 0 {
  875. for _, header := range request.Headers {
  876. request.Peer.MarkLacking(header.Hash())
  877. }
  878. }
  879. // Assemble each of the results with their headers and retrieved data parts
  880. var (
  881. accepted int
  882. failure error
  883. useful bool
  884. )
  885. for i, header := range request.Headers {
  886. // Short circuit assembly if no more fetch results are found
  887. if i >= results {
  888. break
  889. }
  890. // Reconstruct the next result if contents match up
  891. index := int(header.Number.Int64() - int64(q.resultOffset))
  892. if index >= len(q.resultCache) || index < 0 || q.resultCache[index] == nil {
  893. failure = errInvalidChain
  894. break
  895. }
  896. if err := reconstruct(header, i, q.resultCache[index]); err != nil {
  897. failure = err
  898. break
  899. }
  900. donePool[header.Hash()] = struct{}{}
  901. q.resultCache[index].Pending--
  902. useful = true
  903. accepted++
  904. // Clean up a successful fetch
  905. request.Headers[i] = nil
  906. delete(taskPool, header.Hash())
  907. }
  908. // Return all failed or missing fetches to the queue
  909. for _, header := range request.Headers {
  910. if header != nil {
  911. taskQueue.Push(header, -float32(header.Number.Uint64()))
  912. }
  913. }
  914. // Wake up WaitResults
  915. if accepted > 0 {
  916. q.active.Signal()
  917. }
  918. // If none of the data was good, it's a stale delivery
  919. switch {
  920. case failure == nil || failure == errInvalidChain:
  921. return accepted, failure
  922. case useful:
  923. return accepted, fmt.Errorf("partial failure: %v", failure)
  924. default:
  925. return accepted, errStaleDelivery
  926. }
  927. }
  928. // DeliverNodeData injects a node state data retrieval response into the queue.
  929. // The method returns the number of node state accepted from the delivery.
  930. func (q *queue) DeliverNodeData(id string, data [][]byte, callback func(int, bool, error)) (int, error) {
  931. q.lock.Lock()
  932. defer q.lock.Unlock()
  933. // Short circuit if the data was never requested
  934. request := q.statePendPool[id]
  935. if request == nil {
  936. return 0, errNoFetchesPending
  937. }
  938. stateReqTimer.UpdateSince(request.Time)
  939. delete(q.statePendPool, id)
  940. // If no data was retrieved, mark their hashes as unavailable for the origin peer
  941. if len(data) == 0 {
  942. for hash, _ := range request.Hashes {
  943. request.Peer.MarkLacking(hash)
  944. }
  945. }
  946. // Iterate over the downloaded data and verify each of them
  947. accepted, errs := 0, make([]error, 0)
  948. process := []trie.SyncResult{}
  949. for _, blob := range data {
  950. // Skip any state trie entries that were not requested
  951. hash := common.BytesToHash(crypto.Keccak256(blob))
  952. if _, ok := request.Hashes[hash]; !ok {
  953. errs = append(errs, fmt.Errorf("non-requested state data %x", hash))
  954. continue
  955. }
  956. // Inject the next state trie item into the processing queue
  957. process = append(process, trie.SyncResult{Hash: hash, Data: blob})
  958. accepted++
  959. delete(request.Hashes, hash)
  960. delete(q.stateTaskPool, hash)
  961. }
  962. // Start the asynchronous node state data injection
  963. atomic.AddInt32(&q.stateProcessors, 1)
  964. go func() {
  965. defer atomic.AddInt32(&q.stateProcessors, -1)
  966. q.deliverNodeData(process, callback)
  967. }()
  968. // Return all failed or missing fetches to the queue
  969. for hash, index := range request.Hashes {
  970. q.stateTaskQueue.Push(hash, float32(index))
  971. }
  972. // If none of the data items were good, it's a stale delivery
  973. switch {
  974. case len(errs) == 0:
  975. return accepted, nil
  976. case len(errs) == len(request.Hashes):
  977. return accepted, errStaleDelivery
  978. default:
  979. return accepted, fmt.Errorf("multiple failures: %v", errs)
  980. }
  981. }
  982. // deliverNodeData is the asynchronous node data processor that injects a batch
  983. // of sync results into the state scheduler.
  984. func (q *queue) deliverNodeData(results []trie.SyncResult, callback func(int, bool, error)) {
  985. // Wake up WaitResults after the state has been written because it
  986. // might be waiting for the pivot block state to get completed.
  987. defer q.active.Signal()
  988. // Process results one by one to permit task fetches in between
  989. progressed := false
  990. for i, result := range results {
  991. q.stateSchedLock.Lock()
  992. if q.stateScheduler == nil {
  993. // Syncing aborted since this async delivery started, bail out
  994. q.stateSchedLock.Unlock()
  995. callback(i, progressed, errNoFetchesPending)
  996. return
  997. }
  998. batch := q.stateDatabase.NewBatch()
  999. prog, _, err := q.stateScheduler.Process([]trie.SyncResult{result}, batch)
  1000. if err != nil {
  1001. q.stateSchedLock.Unlock()
  1002. callback(i, progressed, err)
  1003. }
  1004. if err = batch.Write(); err != nil {
  1005. q.stateSchedLock.Unlock()
  1006. callback(i, progressed, err)
  1007. }
  1008. // Item processing succeeded, release the lock (temporarily)
  1009. progressed = progressed || prog
  1010. q.stateSchedLock.Unlock()
  1011. }
  1012. callback(len(results), progressed, nil)
  1013. }
  1014. // Prepare configures the result cache to allow accepting and caching inbound
  1015. // fetch results.
  1016. func (q *queue) Prepare(offset uint64, mode SyncMode, pivot uint64, head *types.Header) {
  1017. q.lock.Lock()
  1018. defer q.lock.Unlock()
  1019. // Prepare the queue for sync results
  1020. if q.resultOffset < offset {
  1021. q.resultOffset = offset
  1022. }
  1023. q.fastSyncPivot = pivot
  1024. q.mode = mode
  1025. // If long running fast sync, also start up a head stateretrieval immediately
  1026. if mode == FastSync && pivot > 0 {
  1027. q.stateScheduler = state.NewStateSync(head.Root, q.stateDatabase)
  1028. }
  1029. }