queue.go 36 KB

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