queue.go 33 KB

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