queue.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  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/common/prque"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/ethereum/go-ethereum/metrics"
  30. "github.com/ethereum/go-ethereum/trie"
  31. )
  32. const (
  33. bodyType = uint(0)
  34. receiptType = uint(1)
  35. )
  36. var (
  37. blockCacheMaxItems = 8192 // Maximum number of blocks to cache before throttling the download
  38. blockCacheInitialItems = 2048 // Initial number of blocks to start fetching, before we know the sizes of the blocks
  39. blockCacheMemory = 64 * 1024 * 1024 // Maximum amount of memory to use for block caching
  40. blockCacheSizeWeight = 0.1 // Multiplier to approximate the average block size based on past ones
  41. )
  42. var (
  43. errNoFetchesPending = errors.New("no fetches pending")
  44. errStaleDelivery = errors.New("stale delivery")
  45. )
  46. // fetchRequest is a currently running data retrieval operation.
  47. type fetchRequest struct {
  48. Peer *peerConnection // Peer to which the request was sent
  49. From uint64 // [eth/62] Requested chain element index (used for skeleton fills only)
  50. Headers []*types.Header // [eth/62] Requested headers, sorted by request order
  51. Time time.Time // Time when the request was made
  52. }
  53. // fetchResult is a struct collecting partial results from data fetchers until
  54. // all outstanding pieces complete and the result as a whole can be processed.
  55. type fetchResult struct {
  56. pending int32 // Flag telling what deliveries are outstanding
  57. pid string
  58. Header *types.Header
  59. Uncles []*types.Header
  60. Transactions types.Transactions
  61. Receipts types.Receipts
  62. }
  63. func newFetchResult(header *types.Header, fastSync bool, pid string) *fetchResult {
  64. item := &fetchResult{
  65. Header: header,
  66. pid: pid,
  67. }
  68. if !header.EmptyBody() {
  69. item.pending |= (1 << bodyType)
  70. }
  71. if fastSync && !header.EmptyReceipts() {
  72. item.pending |= (1 << receiptType)
  73. }
  74. return item
  75. }
  76. // SetBodyDone flags the body as finished.
  77. func (f *fetchResult) SetBodyDone() {
  78. if v := atomic.LoadInt32(&f.pending); (v & (1 << bodyType)) != 0 {
  79. atomic.AddInt32(&f.pending, -1)
  80. }
  81. }
  82. // AllDone checks if item is done.
  83. func (f *fetchResult) AllDone() bool {
  84. return atomic.LoadInt32(&f.pending) == 0
  85. }
  86. // SetReceiptsDone flags the receipts as finished.
  87. func (f *fetchResult) SetReceiptsDone() {
  88. if v := atomic.LoadInt32(&f.pending); (v & (1 << receiptType)) != 0 {
  89. atomic.AddInt32(&f.pending, -2)
  90. }
  91. }
  92. // Done checks if the given type is done already
  93. func (f *fetchResult) Done(kind uint) bool {
  94. v := atomic.LoadInt32(&f.pending)
  95. return v&(1<<kind) == 0
  96. }
  97. // queue represents hashes that are either need fetching or are being fetched
  98. type queue struct {
  99. mode SyncMode // Synchronisation mode to decide on the block parts to schedule for fetching
  100. // Headers are "special", they download in batches, supported by a skeleton chain
  101. headerHead common.Hash // Hash of the last queued header to verify order
  102. headerTaskPool map[uint64]*types.Header // Pending header retrieval tasks, mapping starting indexes to skeleton headers
  103. headerTaskQueue *prque.Prque // Priority queue of the skeleton indexes to fetch the filling headers for
  104. headerPeerMiss map[string]map[uint64]struct{} // Set of per-peer header batches known to be unavailable
  105. headerPendPool map[string]*fetchRequest // Currently pending header retrieval operations
  106. headerResults []*types.Header // Result cache accumulating the completed headers
  107. headerProced int // Number of headers already processed from the results
  108. headerOffset uint64 // Number of the first header in the result cache
  109. headerContCh chan bool // Channel to notify when header download finishes
  110. // All data retrievals below are based on an already assembles header chain
  111. blockTaskPool map[common.Hash]*types.Header // Pending block (body) retrieval tasks, mapping hashes to headers
  112. blockTaskQueue *prque.Prque // Priority queue of the headers to fetch the blocks (bodies) for
  113. blockPendPool map[string]*fetchRequest // Currently pending block (body) retrieval operations
  114. receiptTaskPool map[common.Hash]*types.Header // Pending receipt retrieval tasks, mapping hashes to headers
  115. receiptTaskQueue *prque.Prque // Priority queue of the headers to fetch the receipts for
  116. receiptPendPool map[string]*fetchRequest // Currently pending receipt retrieval operations
  117. resultCache *resultStore // Downloaded but not yet delivered fetch results
  118. resultSize common.StorageSize // Approximate size of a block (exponential moving average)
  119. lock *sync.RWMutex
  120. active *sync.Cond
  121. closed bool
  122. lastStatLog time.Time
  123. }
  124. // newQueue creates a new download queue for scheduling block retrieval.
  125. func newQueue(blockCacheLimit int, thresholdInitialSize int) *queue {
  126. lock := new(sync.RWMutex)
  127. q := &queue{
  128. headerContCh: make(chan bool),
  129. blockTaskQueue: prque.New(nil),
  130. receiptTaskQueue: prque.New(nil),
  131. active: sync.NewCond(lock),
  132. lock: lock,
  133. }
  134. q.Reset(blockCacheLimit, thresholdInitialSize)
  135. return q
  136. }
  137. // Reset clears out the queue contents.
  138. func (q *queue) Reset(blockCacheLimit int, thresholdInitialSize int) {
  139. q.lock.Lock()
  140. defer q.lock.Unlock()
  141. q.closed = false
  142. q.mode = FullSync
  143. q.headerHead = common.Hash{}
  144. q.headerPendPool = make(map[string]*fetchRequest)
  145. q.blockTaskPool = make(map[common.Hash]*types.Header)
  146. q.blockTaskQueue.Reset()
  147. q.blockPendPool = make(map[string]*fetchRequest)
  148. q.receiptTaskPool = make(map[common.Hash]*types.Header)
  149. q.receiptTaskQueue.Reset()
  150. q.receiptPendPool = make(map[string]*fetchRequest)
  151. q.resultCache = newResultStore(blockCacheLimit)
  152. q.resultCache.SetThrottleThreshold(uint64(thresholdInitialSize))
  153. }
  154. // Close marks the end of the sync, unblocking Results.
  155. // It may be called even if the queue is already closed.
  156. func (q *queue) Close() {
  157. q.lock.Lock()
  158. q.closed = true
  159. q.active.Signal()
  160. q.lock.Unlock()
  161. }
  162. // PendingHeaders retrieves the number of header requests pending for retrieval.
  163. func (q *queue) PendingHeaders() int {
  164. q.lock.Lock()
  165. defer q.lock.Unlock()
  166. return q.headerTaskQueue.Size()
  167. }
  168. // PendingBlocks retrieves the number of block (body) requests pending for retrieval.
  169. func (q *queue) PendingBlocks() int {
  170. q.lock.Lock()
  171. defer q.lock.Unlock()
  172. return q.blockTaskQueue.Size()
  173. }
  174. // PendingReceipts retrieves the number of block receipts pending for retrieval.
  175. func (q *queue) PendingReceipts() int {
  176. q.lock.Lock()
  177. defer q.lock.Unlock()
  178. return q.receiptTaskQueue.Size()
  179. }
  180. // InFlightHeaders retrieves whether there are header fetch requests currently
  181. // in flight.
  182. func (q *queue) InFlightHeaders() bool {
  183. q.lock.Lock()
  184. defer q.lock.Unlock()
  185. return len(q.headerPendPool) > 0
  186. }
  187. // InFlightBlocks retrieves whether there are block fetch requests currently in
  188. // flight.
  189. func (q *queue) InFlightBlocks() bool {
  190. q.lock.Lock()
  191. defer q.lock.Unlock()
  192. return len(q.blockPendPool) > 0
  193. }
  194. // InFlightReceipts retrieves whether there are receipt fetch requests currently
  195. // in flight.
  196. func (q *queue) InFlightReceipts() bool {
  197. q.lock.Lock()
  198. defer q.lock.Unlock()
  199. return len(q.receiptPendPool) > 0
  200. }
  201. // Idle returns if the queue is fully idle or has some data still inside.
  202. func (q *queue) Idle() bool {
  203. q.lock.Lock()
  204. defer q.lock.Unlock()
  205. queued := q.blockTaskQueue.Size() + q.receiptTaskQueue.Size()
  206. pending := len(q.blockPendPool) + len(q.receiptPendPool)
  207. return (queued + pending) == 0
  208. }
  209. // ScheduleSkeleton adds a batch of header retrieval tasks to the queue to fill
  210. // up an already retrieved header skeleton.
  211. func (q *queue) ScheduleSkeleton(from uint64, skeleton []*types.Header) {
  212. q.lock.Lock()
  213. defer q.lock.Unlock()
  214. // No skeleton retrieval can be in progress, fail hard if so (huge implementation bug)
  215. if q.headerResults != nil {
  216. panic("skeleton assembly already in progress")
  217. }
  218. // Schedule all the header retrieval tasks for the skeleton assembly
  219. q.headerTaskPool = make(map[uint64]*types.Header)
  220. q.headerTaskQueue = prque.New(nil)
  221. q.headerPeerMiss = make(map[string]map[uint64]struct{}) // Reset availability to correct invalid chains
  222. q.headerResults = make([]*types.Header, len(skeleton)*MaxHeaderFetch)
  223. q.headerProced = 0
  224. q.headerOffset = from
  225. q.headerContCh = make(chan bool, 1)
  226. for i, header := range skeleton {
  227. index := from + uint64(i*MaxHeaderFetch)
  228. q.headerTaskPool[index] = header
  229. q.headerTaskQueue.Push(index, -int64(index))
  230. }
  231. }
  232. // RetrieveHeaders retrieves the header chain assemble based on the scheduled
  233. // skeleton.
  234. func (q *queue) RetrieveHeaders() ([]*types.Header, int) {
  235. q.lock.Lock()
  236. defer q.lock.Unlock()
  237. headers, proced := q.headerResults, q.headerProced
  238. q.headerResults, q.headerProced = nil, 0
  239. return headers, proced
  240. }
  241. // Schedule adds a set of headers for the download queue for scheduling, returning
  242. // the new headers encountered.
  243. func (q *queue) Schedule(headers []*types.Header, from uint64) []*types.Header {
  244. q.lock.Lock()
  245. defer q.lock.Unlock()
  246. // Insert all the headers prioritised by the contained block number
  247. inserts := make([]*types.Header, 0, len(headers))
  248. for _, header := range headers {
  249. // Make sure chain order is honoured and preserved throughout
  250. hash := header.Hash()
  251. if header.Number == nil || header.Number.Uint64() != from {
  252. log.Warn("Header broke chain ordering", "number", header.Number, "hash", hash, "expected", from)
  253. break
  254. }
  255. if q.headerHead != (common.Hash{}) && q.headerHead != header.ParentHash {
  256. log.Warn("Header broke chain ancestry", "number", header.Number, "hash", hash)
  257. break
  258. }
  259. // Make sure no duplicate requests are executed
  260. // We cannot skip this, even if the block is empty, since this is
  261. // what triggers the fetchResult creation.
  262. if _, ok := q.blockTaskPool[hash]; ok {
  263. log.Warn("Header already scheduled for block fetch", "number", header.Number, "hash", hash)
  264. } else {
  265. q.blockTaskPool[hash] = header
  266. q.blockTaskQueue.Push(header, -int64(header.Number.Uint64()))
  267. }
  268. // Queue for receipt retrieval
  269. if q.mode == FastSync && !header.EmptyReceipts() {
  270. if _, ok := q.receiptTaskPool[hash]; ok {
  271. log.Warn("Header already scheduled for receipt fetch", "number", header.Number, "hash", hash)
  272. } else {
  273. q.receiptTaskPool[hash] = header
  274. q.receiptTaskQueue.Push(header, -int64(header.Number.Uint64()))
  275. }
  276. }
  277. inserts = append(inserts, header)
  278. q.headerHead = hash
  279. from++
  280. }
  281. return inserts
  282. }
  283. // Results retrieves and permanently removes a batch of fetch results from
  284. // the cache. the result slice will be empty if the queue has been closed.
  285. // Results can be called concurrently with Deliver and Schedule,
  286. // but assumes that there are not two simultaneous callers to Results
  287. func (q *queue) Results(block bool) []*fetchResult {
  288. // Abort early if there are no items and non-blocking requested
  289. if !block && !q.resultCache.HasCompletedItems() {
  290. return nil
  291. }
  292. closed := false
  293. for !closed && !q.resultCache.HasCompletedItems() {
  294. // In order to wait on 'active', we need to obtain the lock.
  295. // That may take a while, if someone is delivering at the same
  296. // time, so after obtaining the lock, we check again if there
  297. // are any results to fetch.
  298. // Also, in-between we ask for the lock and the lock is obtained,
  299. // someone can have closed the queue. In that case, we should
  300. // return the available results and stop blocking
  301. q.lock.Lock()
  302. if q.resultCache.HasCompletedItems() || q.closed {
  303. q.lock.Unlock()
  304. break
  305. }
  306. // No items available, and not closed
  307. q.active.Wait()
  308. closed = q.closed
  309. q.lock.Unlock()
  310. }
  311. // Regardless if closed or not, we can still deliver whatever we have
  312. results := q.resultCache.GetCompleted(maxResultsProcess)
  313. for _, result := range results {
  314. // Recalculate the result item weights to prevent memory exhaustion
  315. size := result.Header.Size()
  316. for _, uncle := range result.Uncles {
  317. size += uncle.Size()
  318. }
  319. for _, receipt := range result.Receipts {
  320. size += receipt.Size()
  321. }
  322. for _, tx := range result.Transactions {
  323. size += tx.Size()
  324. }
  325. q.resultSize = common.StorageSize(blockCacheSizeWeight)*size +
  326. (1-common.StorageSize(blockCacheSizeWeight))*q.resultSize
  327. }
  328. // Using the newly calibrated resultsize, figure out the new throttle limit
  329. // on the result cache
  330. throttleThreshold := uint64((common.StorageSize(blockCacheMemory) + q.resultSize - 1) / q.resultSize)
  331. throttleThreshold = q.resultCache.SetThrottleThreshold(throttleThreshold)
  332. // Log some info at certain times
  333. if time.Since(q.lastStatLog) > 60*time.Second {
  334. q.lastStatLog = time.Now()
  335. info := q.Stats()
  336. info = append(info, "throttle", throttleThreshold)
  337. log.Info("Downloader queue stats", info...)
  338. }
  339. return results
  340. }
  341. func (q *queue) Stats() []interface{} {
  342. q.lock.RLock()
  343. defer q.lock.RUnlock()
  344. return q.stats()
  345. }
  346. func (q *queue) stats() []interface{} {
  347. return []interface{}{
  348. "receiptTasks", q.receiptTaskQueue.Size(),
  349. "blockTasks", q.blockTaskQueue.Size(),
  350. "itemSize", q.resultSize,
  351. }
  352. }
  353. // ReserveHeaders reserves a set of headers for the given peer, skipping any
  354. // previously failed batches.
  355. func (q *queue) ReserveHeaders(p *peerConnection, count int) *fetchRequest {
  356. q.lock.Lock()
  357. defer q.lock.Unlock()
  358. // Short circuit if the peer's already downloading something (sanity check to
  359. // not corrupt state)
  360. if _, ok := q.headerPendPool[p.id]; ok {
  361. return nil
  362. }
  363. // Retrieve a batch of hashes, skipping previously failed ones
  364. send, skip := uint64(0), []uint64{}
  365. for send == 0 && !q.headerTaskQueue.Empty() {
  366. from, _ := q.headerTaskQueue.Pop()
  367. if q.headerPeerMiss[p.id] != nil {
  368. if _, ok := q.headerPeerMiss[p.id][from.(uint64)]; ok {
  369. skip = append(skip, from.(uint64))
  370. continue
  371. }
  372. }
  373. send = from.(uint64)
  374. }
  375. // Merge all the skipped batches back
  376. for _, from := range skip {
  377. q.headerTaskQueue.Push(from, -int64(from))
  378. }
  379. // Assemble and return the block download request
  380. if send == 0 {
  381. return nil
  382. }
  383. request := &fetchRequest{
  384. Peer: p,
  385. From: send,
  386. Time: time.Now(),
  387. }
  388. q.headerPendPool[p.id] = request
  389. return request
  390. }
  391. // ReserveBodies reserves a set of body fetches for the given peer, skipping any
  392. // previously failed downloads. Beside the next batch of needed fetches, it also
  393. // returns a flag whether empty blocks were queued requiring processing.
  394. func (q *queue) ReserveBodies(p *peerConnection, count int) (*fetchRequest, bool, bool) {
  395. q.lock.Lock()
  396. defer q.lock.Unlock()
  397. return q.reserveHeaders(p, count, q.blockTaskPool, q.blockTaskQueue, q.blockPendPool, bodyType)
  398. }
  399. // ReserveReceipts reserves a set of receipt fetches for the given peer, skipping
  400. // any previously failed downloads. Beside the next batch of needed fetches, it
  401. // also returns a flag whether empty receipts were queued requiring importing.
  402. func (q *queue) ReserveReceipts(p *peerConnection, count int) (*fetchRequest, bool, bool) {
  403. q.lock.Lock()
  404. defer q.lock.Unlock()
  405. return q.reserveHeaders(p, count, q.receiptTaskPool, q.receiptTaskQueue, q.receiptPendPool, receiptType)
  406. }
  407. // reserveHeaders reserves a set of data download operations for a given peer,
  408. // skipping any previously failed ones. This method is a generic version used
  409. // by the individual special reservation functions.
  410. //
  411. // Note, this method expects the queue lock to be already held for writing. The
  412. // reason the lock is not obtained in here is because the parameters already need
  413. // to access the queue, so they already need a lock anyway.
  414. //
  415. // Returns:
  416. // item - the fetchRequest
  417. // progress - whether any progress was made
  418. // throttle - if the caller should throttle for a while
  419. func (q *queue) reserveHeaders(p *peerConnection, count int, taskPool map[common.Hash]*types.Header, taskQueue *prque.Prque,
  420. pendPool map[string]*fetchRequest, kind uint) (*fetchRequest, bool, bool) {
  421. // Short circuit if the pool has been depleted, or if the peer's already
  422. // downloading something (sanity check not to corrupt state)
  423. if taskQueue.Empty() {
  424. return nil, false, true
  425. }
  426. if _, ok := pendPool[p.id]; ok {
  427. return nil, false, false
  428. }
  429. // Retrieve a batch of tasks, skipping previously failed ones
  430. send := make([]*types.Header, 0, count)
  431. skip := make([]*types.Header, 0)
  432. progress := false
  433. throttled := false
  434. for proc := 0; len(send) < count && !taskQueue.Empty(); proc++ {
  435. // the task queue will pop items in order, so the highest prio block
  436. // is also the lowest block number.
  437. h, _ := taskQueue.Peek()
  438. header := h.(*types.Header)
  439. // we can ask the resultcache if this header is within the
  440. // "prioritized" segment of blocks. If it is not, we need to throttle
  441. stale, throttle, item, err := q.resultCache.AddFetch(header, q.mode == FastSync, p.id)
  442. if stale {
  443. // Don't put back in the task queue, this item has already been
  444. // delivered upstream
  445. taskQueue.PopItem()
  446. progress = true
  447. delete(taskPool, header.Hash())
  448. proc = proc - 1
  449. log.Error("Fetch reservation already delivered", "number", header.Number.Uint64())
  450. continue
  451. }
  452. if throttle {
  453. // There are no resultslots available. Leave it in the task queue
  454. // However, if there are any left as 'skipped', we should not tell
  455. // the caller to throttle, since we still want some other
  456. // peer to fetch those for us
  457. throttled = len(skip) == 0
  458. break
  459. }
  460. if err != nil {
  461. // this most definitely should _not_ happen
  462. log.Warn("Failed to reserve headers", "err", err)
  463. // There are no resultslots available. Leave it in the task queue
  464. break
  465. }
  466. if item.Done(kind) {
  467. // If it's a noop, we can skip this task
  468. delete(taskPool, header.Hash())
  469. taskQueue.PopItem()
  470. proc = proc - 1
  471. progress = true
  472. continue
  473. }
  474. // Remove it from the task queue
  475. taskQueue.PopItem()
  476. // Otherwise unless the peer is known not to have the data, add to the retrieve list
  477. if p.Lacks(header.Hash()) {
  478. skip = append(skip, header)
  479. } else {
  480. send = append(send, header)
  481. }
  482. }
  483. // Merge all the skipped headers back
  484. for _, header := range skip {
  485. taskQueue.Push(header, -int64(header.Number.Uint64()))
  486. }
  487. if q.resultCache.HasCompletedItems() {
  488. // Wake Results, resultCache was modified
  489. q.active.Signal()
  490. }
  491. // Assemble and return the block download request
  492. if len(send) == 0 {
  493. return nil, progress, throttled
  494. }
  495. request := &fetchRequest{
  496. Peer: p,
  497. Headers: send,
  498. Time: time.Now(),
  499. }
  500. pendPool[p.id] = request
  501. return request, progress, throttled
  502. }
  503. // CancelHeaders aborts a fetch request, returning all pending skeleton indexes to the queue.
  504. func (q *queue) CancelHeaders(request *fetchRequest) {
  505. q.lock.Lock()
  506. defer q.lock.Unlock()
  507. q.cancel(request, q.headerTaskQueue, q.headerPendPool)
  508. }
  509. // CancelBodies aborts a body fetch request, returning all pending headers to the
  510. // task queue.
  511. func (q *queue) CancelBodies(request *fetchRequest) {
  512. q.lock.Lock()
  513. defer q.lock.Unlock()
  514. q.cancel(request, q.blockTaskQueue, q.blockPendPool)
  515. }
  516. // CancelReceipts aborts a body fetch request, returning all pending headers to
  517. // the task queue.
  518. func (q *queue) CancelReceipts(request *fetchRequest) {
  519. q.lock.Lock()
  520. defer q.lock.Unlock()
  521. q.cancel(request, q.receiptTaskQueue, q.receiptPendPool)
  522. }
  523. // Cancel aborts a fetch request, returning all pending hashes to the task queue.
  524. func (q *queue) cancel(request *fetchRequest, taskQueue *prque.Prque, pendPool map[string]*fetchRequest) {
  525. if request.From > 0 {
  526. taskQueue.Push(request.From, -int64(request.From))
  527. }
  528. for _, header := range request.Headers {
  529. taskQueue.Push(header, -int64(header.Number.Uint64()))
  530. }
  531. delete(pendPool, request.Peer.id)
  532. }
  533. // Revoke cancels all pending requests belonging to a given peer. This method is
  534. // meant to be called during a peer drop to quickly reassign owned data fetches
  535. // to remaining nodes.
  536. func (q *queue) Revoke(peerID string) {
  537. q.lock.Lock()
  538. defer q.lock.Unlock()
  539. if request, ok := q.blockPendPool[peerID]; ok {
  540. for _, header := range request.Headers {
  541. q.blockTaskQueue.Push(header, -int64(header.Number.Uint64()))
  542. }
  543. delete(q.blockPendPool, peerID)
  544. }
  545. if request, ok := q.receiptPendPool[peerID]; ok {
  546. for _, header := range request.Headers {
  547. q.receiptTaskQueue.Push(header, -int64(header.Number.Uint64()))
  548. }
  549. delete(q.receiptPendPool, peerID)
  550. }
  551. }
  552. // ExpireHeaders checks for in flight requests that exceeded a timeout allowance,
  553. // canceling them and returning the responsible peers for penalisation.
  554. func (q *queue) ExpireHeaders(timeout time.Duration) map[string]int {
  555. q.lock.Lock()
  556. defer q.lock.Unlock()
  557. return q.expire(timeout, q.headerPendPool, q.headerTaskQueue, headerTimeoutMeter)
  558. }
  559. // ExpireBodies checks for in flight block body requests that exceeded a timeout
  560. // allowance, canceling them and returning the responsible peers for penalisation.
  561. func (q *queue) ExpireBodies(timeout time.Duration) map[string]int {
  562. q.lock.Lock()
  563. defer q.lock.Unlock()
  564. return q.expire(timeout, q.blockPendPool, q.blockTaskQueue, bodyTimeoutMeter)
  565. }
  566. // ExpireReceipts checks for in flight receipt requests that exceeded a timeout
  567. // allowance, canceling them and returning the responsible peers for penalisation.
  568. func (q *queue) ExpireReceipts(timeout time.Duration) map[string]int {
  569. q.lock.Lock()
  570. defer q.lock.Unlock()
  571. return q.expire(timeout, q.receiptPendPool, q.receiptTaskQueue, receiptTimeoutMeter)
  572. }
  573. // expire is the generic check that move expired tasks from a pending pool back
  574. // into a task pool, returning all entities caught with expired tasks.
  575. //
  576. // Note, this method expects the queue lock to be already held. The
  577. // reason the lock is not obtained in here is because the parameters already need
  578. // to access the queue, so they already need a lock anyway.
  579. func (q *queue) expire(timeout time.Duration, pendPool map[string]*fetchRequest, taskQueue *prque.Prque, timeoutMeter metrics.Meter) map[string]int {
  580. // Iterate over the expired requests and return each to the queue
  581. expiries := make(map[string]int)
  582. for id, request := range pendPool {
  583. if time.Since(request.Time) > timeout {
  584. // Update the metrics with the timeout
  585. timeoutMeter.Mark(1)
  586. // Return any non satisfied requests to the pool
  587. if request.From > 0 {
  588. taskQueue.Push(request.From, -int64(request.From))
  589. }
  590. for _, header := range request.Headers {
  591. taskQueue.Push(header, -int64(header.Number.Uint64()))
  592. }
  593. // Add the peer to the expiry report along the number of failed requests
  594. expiries[id] = len(request.Headers)
  595. // Remove the expired requests from the pending pool directly
  596. delete(pendPool, id)
  597. }
  598. }
  599. return expiries
  600. }
  601. // DeliverHeaders injects a header retrieval response into the header results
  602. // cache. This method either accepts all headers it received, or none of them
  603. // if they do not map correctly to the skeleton.
  604. //
  605. // If the headers are accepted, the method makes an attempt to deliver the set
  606. // of ready headers to the processor to keep the pipeline full. However it will
  607. // not block to prevent stalling other pending deliveries.
  608. func (q *queue) DeliverHeaders(id string, headers []*types.Header, headerProcCh chan []*types.Header) (int, error) {
  609. q.lock.Lock()
  610. defer q.lock.Unlock()
  611. var logger log.Logger
  612. if len(id) < 16 {
  613. // Tests use short IDs, don't choke on them
  614. logger = log.New("peer", id)
  615. } else {
  616. logger = log.New("peer", id[:16])
  617. }
  618. // Short circuit if the data was never requested
  619. request := q.headerPendPool[id]
  620. if request == nil {
  621. return 0, errNoFetchesPending
  622. }
  623. headerReqTimer.UpdateSince(request.Time)
  624. delete(q.headerPendPool, id)
  625. // Ensure headers can be mapped onto the skeleton chain
  626. target := q.headerTaskPool[request.From].Hash()
  627. accepted := len(headers) == MaxHeaderFetch
  628. if accepted {
  629. if headers[0].Number.Uint64() != request.From {
  630. logger.Trace("First header broke chain ordering", "number", headers[0].Number, "hash", headers[0].Hash(), "expected", request.From)
  631. accepted = false
  632. } else if headers[len(headers)-1].Hash() != target {
  633. logger.Trace("Last header broke skeleton structure ", "number", headers[len(headers)-1].Number, "hash", headers[len(headers)-1].Hash(), "expected", target)
  634. accepted = false
  635. }
  636. }
  637. if accepted {
  638. parentHash := headers[0].Hash()
  639. for i, header := range headers[1:] {
  640. hash := header.Hash()
  641. if want := request.From + 1 + uint64(i); header.Number.Uint64() != want {
  642. logger.Warn("Header broke chain ordering", "number", header.Number, "hash", hash, "expected", want)
  643. accepted = false
  644. break
  645. }
  646. if parentHash != header.ParentHash {
  647. logger.Warn("Header broke chain ancestry", "number", header.Number, "hash", hash)
  648. accepted = false
  649. break
  650. }
  651. // Set-up parent hash for next round
  652. parentHash = hash
  653. }
  654. }
  655. // If the batch of headers wasn't accepted, mark as unavailable
  656. if !accepted {
  657. logger.Trace("Skeleton filling not accepted", "from", request.From)
  658. miss := q.headerPeerMiss[id]
  659. if miss == nil {
  660. q.headerPeerMiss[id] = make(map[uint64]struct{})
  661. miss = q.headerPeerMiss[id]
  662. }
  663. miss[request.From] = struct{}{}
  664. q.headerTaskQueue.Push(request.From, -int64(request.From))
  665. return 0, errors.New("delivery not accepted")
  666. }
  667. // Clean up a successful fetch and try to deliver any sub-results
  668. copy(q.headerResults[request.From-q.headerOffset:], headers)
  669. delete(q.headerTaskPool, request.From)
  670. ready := 0
  671. for q.headerProced+ready < len(q.headerResults) && q.headerResults[q.headerProced+ready] != nil {
  672. ready += MaxHeaderFetch
  673. }
  674. if ready > 0 {
  675. // Headers are ready for delivery, gather them and push forward (non blocking)
  676. process := make([]*types.Header, ready)
  677. copy(process, q.headerResults[q.headerProced:q.headerProced+ready])
  678. select {
  679. case headerProcCh <- process:
  680. logger.Trace("Pre-scheduled new headers", "count", len(process), "from", process[0].Number)
  681. q.headerProced += len(process)
  682. default:
  683. }
  684. }
  685. // Check for termination and return
  686. if len(q.headerTaskPool) == 0 {
  687. q.headerContCh <- false
  688. }
  689. return len(headers), nil
  690. }
  691. // DeliverBodies injects a block body retrieval response into the results queue.
  692. // The method returns the number of blocks bodies accepted from the delivery and
  693. // also wakes any threads waiting for data delivery.
  694. func (q *queue) DeliverBodies(id string, txLists [][]*types.Transaction, uncleLists [][]*types.Header) (int, error) {
  695. q.lock.Lock()
  696. defer q.lock.Unlock()
  697. validate := func(index int, header *types.Header) error {
  698. if types.DeriveSha(types.Transactions(txLists[index]), trie.NewStackTrie(nil)) != header.TxHash {
  699. return errInvalidBody
  700. }
  701. if types.CalcUncleHash(uncleLists[index]) != header.UncleHash {
  702. return errInvalidBody
  703. }
  704. return nil
  705. }
  706. reconstruct := func(index int, result *fetchResult) {
  707. result.Transactions = txLists[index]
  708. result.Uncles = uncleLists[index]
  709. result.SetBodyDone()
  710. }
  711. return q.deliver(id, q.blockTaskPool, q.blockTaskQueue, q.blockPendPool,
  712. bodyReqTimer, len(txLists), validate, reconstruct)
  713. }
  714. // DeliverReceipts injects a receipt retrieval response into the results queue.
  715. // The method returns the number of transaction receipts accepted from the delivery
  716. // and also wakes any threads waiting for data delivery.
  717. func (q *queue) DeliverReceipts(id string, receiptList [][]*types.Receipt) (int, error) {
  718. q.lock.Lock()
  719. defer q.lock.Unlock()
  720. validate := func(index int, header *types.Header) error {
  721. if types.DeriveSha(types.Receipts(receiptList[index]), trie.NewStackTrie(nil)) != header.ReceiptHash {
  722. return errInvalidReceipt
  723. }
  724. return nil
  725. }
  726. reconstruct := func(index int, result *fetchResult) {
  727. result.Receipts = receiptList[index]
  728. result.SetReceiptsDone()
  729. }
  730. return q.deliver(id, q.receiptTaskPool, q.receiptTaskQueue, q.receiptPendPool,
  731. receiptReqTimer, len(receiptList), validate, reconstruct)
  732. }
  733. // deliver injects a data retrieval response into the results queue.
  734. //
  735. // Note, this method expects the queue lock to be already held for writing. The
  736. // reason this lock is not obtained in here is because the parameters already need
  737. // to access the queue, so they already need a lock anyway.
  738. func (q *queue) deliver(id string, taskPool map[common.Hash]*types.Header,
  739. taskQueue *prque.Prque, pendPool map[string]*fetchRequest, reqTimer metrics.Timer,
  740. results int, validate func(index int, header *types.Header) error,
  741. reconstruct func(index int, result *fetchResult)) (int, error) {
  742. // Short circuit if the data was never requested
  743. request := pendPool[id]
  744. if request == nil {
  745. return 0, errNoFetchesPending
  746. }
  747. reqTimer.UpdateSince(request.Time)
  748. delete(pendPool, id)
  749. // If no data items were retrieved, mark them as unavailable for the origin peer
  750. if results == 0 {
  751. for _, header := range request.Headers {
  752. request.Peer.MarkLacking(header.Hash())
  753. }
  754. }
  755. // Assemble each of the results with their headers and retrieved data parts
  756. var (
  757. accepted int
  758. failure error
  759. i int
  760. hashes []common.Hash
  761. )
  762. for _, header := range request.Headers {
  763. // Short circuit assembly if no more fetch results are found
  764. if i >= results {
  765. break
  766. }
  767. // Validate the fields
  768. if err := validate(i, header); err != nil {
  769. failure = err
  770. break
  771. }
  772. hashes = append(hashes, header.Hash())
  773. i++
  774. }
  775. for _, header := range request.Headers[:i] {
  776. if res, stale, err := q.resultCache.GetDeliverySlot(header.Number.Uint64()); err == nil {
  777. reconstruct(accepted, res)
  778. } else {
  779. // else: betweeen here and above, some other peer filled this result,
  780. // or it was indeed a no-op. This should not happen, but if it does it's
  781. // not something to panic about
  782. log.Error("Delivery stale", "stale", stale, "number", header.Number.Uint64(), "err", err)
  783. failure = errStaleDelivery
  784. }
  785. // Clean up a successful fetch
  786. delete(taskPool, hashes[accepted])
  787. accepted++
  788. }
  789. // Return all failed or missing fetches to the queue
  790. for _, header := range request.Headers[accepted:] {
  791. taskQueue.Push(header, -int64(header.Number.Uint64()))
  792. }
  793. // Wake up Results
  794. if accepted > 0 {
  795. q.active.Signal()
  796. }
  797. if failure == nil {
  798. return accepted, nil
  799. }
  800. // If none of the data was good, it's a stale delivery
  801. if accepted > 0 {
  802. return accepted, fmt.Errorf("partial failure: %v", failure)
  803. }
  804. return accepted, fmt.Errorf("%w: %v", failure, errStaleDelivery)
  805. }
  806. // Prepare configures the result cache to allow accepting and caching inbound
  807. // fetch results.
  808. func (q *queue) Prepare(offset uint64, mode SyncMode) {
  809. q.lock.Lock()
  810. defer q.lock.Unlock()
  811. // Prepare the queue for sync results
  812. q.resultCache.Prepare(offset)
  813. q.mode = mode
  814. }