downloader.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. package downloader
  2. import (
  3. "errors"
  4. "fmt"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "github.com/ethereum/go-ethereum/common"
  9. "github.com/ethereum/go-ethereum/core/types"
  10. "github.com/ethereum/go-ethereum/event"
  11. "github.com/ethereum/go-ethereum/logger"
  12. "github.com/ethereum/go-ethereum/logger/glog"
  13. )
  14. const (
  15. maxBlockFetch = 128 // Amount of max blocks to be fetched per chunk
  16. peerCountTimeout = 12 * time.Second // Amount of time it takes for the peer handler to ignore minDesiredPeerCount
  17. hashTtl = 20 * time.Second // The amount of time it takes for a hash request to time out
  18. )
  19. var (
  20. minDesiredPeerCount = 5 // Amount of peers desired to start syncing
  21. blockTtl = 20 * time.Second // The amount of time it takes for a block request to time out
  22. errLowTd = errors.New("peer's TD is too low")
  23. ErrBusy = errors.New("busy")
  24. errUnknownPeer = errors.New("peer's unknown or unhealthy")
  25. errBadPeer = errors.New("action from bad peer ignored")
  26. errNoPeers = errors.New("no peers to keep download active")
  27. ErrPendingQueue = errors.New("pending items in queue")
  28. ErrTimeout = errors.New("timeout")
  29. errEmptyHashSet = errors.New("empty hash set by peer")
  30. errPeersUnavailable = errors.New("no peers available or all peers tried for block download process")
  31. errAlreadyInPool = errors.New("hash already in pool")
  32. errBlockNumberOverflow = errors.New("received block which overflows")
  33. errCancelHashFetch = errors.New("hash fetching cancelled (requested)")
  34. errCancelBlockFetch = errors.New("block downloading cancelled (requested)")
  35. errNoSyncActive = errors.New("no sync active")
  36. )
  37. type hashCheckFn func(common.Hash) bool
  38. type getBlockFn func(common.Hash) *types.Block
  39. type chainInsertFn func(types.Blocks) (int, error)
  40. type hashIterFn func() (common.Hash, error)
  41. type blockPack struct {
  42. peerId string
  43. blocks []*types.Block
  44. }
  45. type hashPack struct {
  46. peerId string
  47. hashes []common.Hash
  48. }
  49. type Downloader struct {
  50. mux *event.TypeMux
  51. mu sync.RWMutex
  52. queue *queue
  53. peers *peerSet
  54. // Callbacks
  55. hasBlock hashCheckFn
  56. getBlock getBlockFn
  57. // Status
  58. synchronising int32
  59. notified int32
  60. // Channels
  61. newPeerCh chan *peer
  62. hashCh chan hashPack
  63. blockCh chan blockPack
  64. cancelCh chan struct{} // Channel to cancel mid-flight syncs
  65. cancelLock sync.RWMutex // Lock to protect the cancel channel in delivers
  66. }
  67. func New(mux *event.TypeMux, hasBlock hashCheckFn, getBlock getBlockFn) *Downloader {
  68. downloader := &Downloader{
  69. mux: mux,
  70. queue: newQueue(),
  71. peers: newPeerSet(),
  72. hasBlock: hasBlock,
  73. getBlock: getBlock,
  74. newPeerCh: make(chan *peer, 1),
  75. hashCh: make(chan hashPack, 1),
  76. blockCh: make(chan blockPack, 1),
  77. }
  78. return downloader
  79. }
  80. func (d *Downloader) Stats() (current int, max int) {
  81. return d.queue.Size()
  82. }
  83. // Synchronising returns the state of the downloader
  84. func (d *Downloader) Synchronising() bool {
  85. return atomic.LoadInt32(&d.synchronising) > 0
  86. }
  87. // RegisterPeer injects a new download peer into the set of block source to be
  88. // used for fetching hashes and blocks from.
  89. func (d *Downloader) RegisterPeer(id string, head common.Hash, getHashes hashFetcherFn, getBlocks blockFetcherFn) error {
  90. glog.V(logger.Detail).Infoln("Registering peer", id)
  91. if err := d.peers.Register(newPeer(id, head, getHashes, getBlocks)); err != nil {
  92. glog.V(logger.Error).Infoln("Register failed:", err)
  93. return err
  94. }
  95. return nil
  96. }
  97. // UnregisterPeer remove a peer from the known list, preventing any action from
  98. // the specified peer.
  99. func (d *Downloader) UnregisterPeer(id string) error {
  100. glog.V(logger.Detail).Infoln("Unregistering peer", id)
  101. if err := d.peers.Unregister(id); err != nil {
  102. glog.V(logger.Error).Infoln("Unregister failed:", err)
  103. return err
  104. }
  105. return nil
  106. }
  107. // Synchronise will select the peer and use it for synchronising. If an empty string is given
  108. // it will use the best peer possible and synchronize if it's TD is higher than our own. If any of the
  109. // checks fail an error will be returned. This method is synchronous
  110. func (d *Downloader) Synchronise(id string, hash common.Hash) error {
  111. // Make sure only one goroutine is ever allowed past this point at once
  112. if !atomic.CompareAndSwapInt32(&d.synchronising, 0, 1) {
  113. return ErrBusy
  114. }
  115. defer atomic.StoreInt32(&d.synchronising, 0)
  116. // Post a user notification of the sync (only once per session)
  117. if atomic.CompareAndSwapInt32(&d.notified, 0, 1) {
  118. glog.V(logger.Info).Infoln("Block synchronisation started")
  119. }
  120. d.mux.Post(StartEvent{})
  121. // Create cancel channel for aborting mid-flight
  122. d.cancelLock.Lock()
  123. d.cancelCh = make(chan struct{})
  124. d.cancelLock.Unlock()
  125. // Abort if the queue still contains some leftover data
  126. if _, cached := d.queue.Size(); cached > 0 && d.queue.GetHeadBlock() != nil {
  127. return ErrPendingQueue
  128. }
  129. // Reset the queue and peer set to clean any internal leftover state
  130. d.queue.Reset()
  131. d.peers.Reset()
  132. // Retrieve the origin peer and initiate the downloading process
  133. p := d.peers.Peer(id)
  134. if p == nil {
  135. return errUnknownPeer
  136. }
  137. return d.syncWithPeer(p, hash)
  138. }
  139. // TakeBlocks takes blocks from the queue and yields them to the caller.
  140. func (d *Downloader) TakeBlocks() types.Blocks {
  141. return d.queue.TakeBlocks()
  142. }
  143. func (d *Downloader) Has(hash common.Hash) bool {
  144. return d.queue.Has(hash)
  145. }
  146. // syncWithPeer starts a block synchronization based on the hash chain from the
  147. // specified peer and head hash.
  148. func (d *Downloader) syncWithPeer(p *peer, hash common.Hash) (err error) {
  149. defer func() {
  150. // reset on error
  151. if err != nil {
  152. d.queue.Reset()
  153. d.mux.Post(FailedEvent{err})
  154. } else {
  155. d.mux.Post(DoneEvent{})
  156. }
  157. }()
  158. glog.V(logger.Debug).Infoln("Synchronizing with the network using:", p.id)
  159. if err = d.fetchHashes(p, hash); err != nil {
  160. return err
  161. }
  162. if err = d.fetchBlocks(); err != nil {
  163. return err
  164. }
  165. glog.V(logger.Debug).Infoln("Synchronization completed")
  166. return nil
  167. }
  168. // Cancel cancels all of the operations and resets the queue. It returns true
  169. // if the cancel operation was completed.
  170. func (d *Downloader) Cancel() bool {
  171. // If we're not syncing just return.
  172. hs, bs := d.queue.Size()
  173. if atomic.LoadInt32(&d.synchronising) == 0 && hs == 0 && bs == 0 {
  174. return false
  175. }
  176. // Close the current cancel channel
  177. d.cancelLock.RLock()
  178. close(d.cancelCh)
  179. d.cancelLock.RUnlock()
  180. // reset the queue
  181. d.queue.Reset()
  182. return true
  183. }
  184. // XXX Make synchronous
  185. func (d *Downloader) fetchHashes(p *peer, h common.Hash) error {
  186. glog.V(logger.Debug).Infof("Downloading hashes (%x) from %s", h[:4], p.id)
  187. start := time.Now()
  188. // Add the hash to the queue first
  189. d.queue.Insert([]common.Hash{h})
  190. // Get the first batch of hashes
  191. p.getHashes(h)
  192. var (
  193. failureResponseTimer = time.NewTimer(hashTtl)
  194. attemptedPeers = make(map[string]bool) // attempted peers will help with retries
  195. activePeer = p // active peer will help determine the current active peer
  196. hash common.Hash // common and last hash
  197. )
  198. attemptedPeers[p.id] = true
  199. out:
  200. for {
  201. select {
  202. case <-d.cancelCh:
  203. return errCancelHashFetch
  204. case hashPack := <-d.hashCh:
  205. // Make sure the active peer is giving us the hashes
  206. if hashPack.peerId != activePeer.id {
  207. glog.V(logger.Debug).Infof("Received hashes from incorrect peer(%s)\n", hashPack.peerId)
  208. break
  209. }
  210. failureResponseTimer.Reset(hashTtl)
  211. // Make sure the peer actually gave something valid
  212. if len(hashPack.hashes) == 0 {
  213. glog.V(logger.Debug).Infof("Peer (%s) responded with empty hash set\n", activePeer.id)
  214. d.queue.Reset()
  215. return errEmptyHashSet
  216. }
  217. // Determine if we're done fetching hashes (queue up all pending), and continue if not done
  218. done, index := false, 0
  219. for index, hash = range hashPack.hashes {
  220. if d.hasBlock(hash) || d.queue.GetBlock(hash) != nil {
  221. glog.V(logger.Debug).Infof("Found common hash %x\n", hash[:4])
  222. hashPack.hashes = hashPack.hashes[:index]
  223. done = true
  224. break
  225. }
  226. }
  227. d.queue.Insert(hashPack.hashes)
  228. if !done {
  229. activePeer.getHashes(hash)
  230. continue
  231. }
  232. // We're done, allocate the download cache and proceed pulling the blocks
  233. offset := 0
  234. if block := d.getBlock(hash); block != nil {
  235. offset = int(block.NumberU64() + 1)
  236. }
  237. d.queue.Alloc(offset)
  238. break out
  239. case <-failureResponseTimer.C:
  240. glog.V(logger.Debug).Infof("Peer (%s) didn't respond in time for hash request\n", p.id)
  241. var p *peer // p will be set if a peer can be found
  242. // Attempt to find a new peer by checking inclusion of peers best hash in our
  243. // already fetched hash list. This can't guarantee 100% correctness but does
  244. // a fair job. This is always either correct or false incorrect.
  245. for _, peer := range d.peers.AllPeers() {
  246. if d.queue.Has(peer.head) && !attemptedPeers[peer.id] {
  247. p = peer
  248. break
  249. }
  250. }
  251. // if all peers have been tried, abort the process entirely or if the hash is
  252. // the zero hash.
  253. if p == nil || (hash == common.Hash{}) {
  254. d.queue.Reset()
  255. return ErrTimeout
  256. }
  257. // set p to the active peer. this will invalidate any hashes that may be returned
  258. // by our previous (delayed) peer.
  259. activePeer = p
  260. p.getHashes(hash)
  261. glog.V(logger.Debug).Infof("Hash fetching switched to new peer(%s)\n", p.id)
  262. }
  263. }
  264. glog.V(logger.Debug).Infof("Downloaded hashes (%d) in %v\n", d.queue.Pending(), time.Since(start))
  265. return nil
  266. }
  267. // fetchBlocks iteratively downloads the entire schedules block-chain, taking
  268. // any available peers, reserving a chunk of blocks for each, wait for delivery
  269. // and periodically checking for timeouts.
  270. func (d *Downloader) fetchBlocks() error {
  271. glog.V(logger.Debug).Infoln("Downloading", d.queue.Pending(), "block(s)")
  272. start := time.Now()
  273. // default ticker for re-fetching blocks every now and then
  274. ticker := time.NewTicker(20 * time.Millisecond)
  275. out:
  276. for {
  277. select {
  278. case <-d.cancelCh:
  279. return errCancelBlockFetch
  280. case blockPack := <-d.blockCh:
  281. // If the peer was previously banned and failed to deliver it's pack
  282. // in a reasonable time frame, ignore it's message.
  283. if peer := d.peers.Peer(blockPack.peerId); peer != nil {
  284. // Deliver the received chunk of blocks, but drop the peer if invalid
  285. if err := d.queue.Deliver(blockPack.peerId, blockPack.blocks); err != nil {
  286. glog.V(logger.Debug).Infof("Failed delivery for peer %s: %v\n", blockPack.peerId, err)
  287. peer.Demote()
  288. break
  289. }
  290. if glog.V(logger.Debug) {
  291. glog.Infof("Added %d blocks from: %s\n", len(blockPack.blocks), blockPack.peerId)
  292. }
  293. // Promote the peer and update it's idle state
  294. peer.Promote()
  295. peer.SetIdle()
  296. }
  297. case <-ticker.C:
  298. // Check for bad peers. Bad peers may indicate a peer not responding
  299. // to a `getBlocks` message. A timeout of 5 seconds is set. Peers
  300. // that badly or poorly behave are removed from the peer set (not banned).
  301. // Bad peers are excluded from the available peer set and therefor won't be
  302. // reused. XXX We could re-introduce peers after X time.
  303. badPeers := d.queue.Expire(blockTtl)
  304. for _, pid := range badPeers {
  305. // XXX We could make use of a reputation system here ranking peers
  306. // in their performance
  307. // 1) Time for them to respond;
  308. // 2) Measure their speed;
  309. // 3) Amount and availability.
  310. if peer := d.peers.Peer(pid); peer != nil {
  311. peer.Demote()
  312. }
  313. }
  314. // After removing bad peers make sure we actually have sufficient peer left to keep downloading
  315. if d.peers.Len() == 0 {
  316. d.queue.Reset()
  317. return errNoPeers
  318. }
  319. // If there are unrequested hashes left start fetching
  320. // from the available peers.
  321. if d.queue.Pending() > 0 {
  322. // Throttle the download if block cache is full and waiting processing
  323. if d.queue.Throttle() {
  324. continue
  325. }
  326. // Send a download request to all idle peers, until throttled
  327. idlePeers := d.peers.IdlePeers()
  328. for _, peer := range idlePeers {
  329. // Short circuit if throttling activated since above
  330. if d.queue.Throttle() {
  331. break
  332. }
  333. // Get a possible chunk. If nil is returned no chunk
  334. // could be returned due to no hashes available.
  335. request := d.queue.Reserve(peer, maxBlockFetch)
  336. if request == nil {
  337. continue
  338. }
  339. // Fetch the chunk and check for error. If the peer was somehow
  340. // already fetching a chunk due to a bug, it will be returned to
  341. // the queue
  342. if err := peer.Fetch(request); err != nil {
  343. glog.V(logger.Error).Infof("Peer %s received double work\n", peer.id)
  344. d.queue.Cancel(request)
  345. }
  346. }
  347. // Make sure that we have peers available for fetching. If all peers have been tried
  348. // and all failed throw an error
  349. if d.queue.InFlight() == 0 {
  350. d.queue.Reset()
  351. return fmt.Errorf("%v peers available = %d. total peers = %d. hashes needed = %d", errPeersUnavailable, len(idlePeers), d.peers.Len(), d.queue.Pending())
  352. }
  353. } else if d.queue.InFlight() == 0 {
  354. // When there are no more queue and no more in flight, We can
  355. // safely assume we're done. Another part of the process will check
  356. // for parent errors and will re-request anything that's missing
  357. break out
  358. }
  359. }
  360. }
  361. glog.V(logger.Detail).Infoln("Downloaded block(s) in", time.Since(start))
  362. return nil
  363. }
  364. // DeliverBlocks injects a new batch of blocks received from a remote node.
  365. // This is usually invoked through the BlocksMsg by the protocol handler.
  366. func (d *Downloader) DeliverBlocks(id string, blocks []*types.Block) error {
  367. // Make sure the downloader is active
  368. if atomic.LoadInt32(&d.synchronising) == 0 {
  369. return errNoSyncActive
  370. }
  371. // Deliver or abort if the sync is canceled while queuing
  372. d.cancelLock.RLock()
  373. cancel := d.cancelCh
  374. d.cancelLock.RUnlock()
  375. select {
  376. case d.blockCh <- blockPack{id, blocks}:
  377. return nil
  378. case <-cancel:
  379. return errNoSyncActive
  380. }
  381. }
  382. // DeliverHashes injects a new batch of hashes received from a remote node into
  383. // the download schedule. This is usually invoked through the BlockHashesMsg by
  384. // the protocol handler.
  385. func (d *Downloader) DeliverHashes(id string, hashes []common.Hash) error {
  386. // Make sure the downloader is active
  387. if atomic.LoadInt32(&d.synchronising) == 0 {
  388. return errNoSyncActive
  389. }
  390. // Deliver or abort if the sync is canceled while queuing
  391. d.cancelLock.RLock()
  392. cancel := d.cancelCh
  393. d.cancelLock.RUnlock()
  394. select {
  395. case d.hashCh <- hashPack{id, hashes}:
  396. return nil
  397. case <-cancel:
  398. return errNoSyncActive
  399. }
  400. }