statesync.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. // Copyright 2017 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. package downloader
  17. import (
  18. "fmt"
  19. "hash"
  20. "sync"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/rawdb"
  24. "github.com/ethereum/go-ethereum/core/state"
  25. "github.com/ethereum/go-ethereum/crypto/sha3"
  26. "github.com/ethereum/go-ethereum/ethdb"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/trie"
  29. )
  30. // stateReq represents a batch of state fetch requests grouped together into
  31. // a single data retrieval network packet.
  32. type stateReq struct {
  33. items []common.Hash // Hashes of the state items to download
  34. tasks map[common.Hash]*stateTask // Download tasks to track previous attempts
  35. timeout time.Duration // Maximum round trip time for this to complete
  36. timer *time.Timer // Timer to fire when the RTT timeout expires
  37. peer *peerConnection // Peer that we're requesting from
  38. response [][]byte // Response data of the peer (nil for timeouts)
  39. dropped bool // Flag whether the peer dropped off early
  40. }
  41. // timedOut returns if this request timed out.
  42. func (req *stateReq) timedOut() bool {
  43. return req.response == nil
  44. }
  45. // stateSyncStats is a collection of progress stats to report during a state trie
  46. // sync to RPC requests as well as to display in user logs.
  47. type stateSyncStats struct {
  48. processed uint64 // Number of state entries processed
  49. duplicate uint64 // Number of state entries downloaded twice
  50. unexpected uint64 // Number of non-requested state entries received
  51. pending uint64 // Number of still pending state entries
  52. }
  53. // syncState starts downloading state with the given root hash.
  54. func (d *Downloader) syncState(root common.Hash) *stateSync {
  55. s := newStateSync(d, root)
  56. select {
  57. case d.stateSyncStart <- s:
  58. case <-d.quitCh:
  59. s.err = errCancelStateFetch
  60. close(s.done)
  61. }
  62. return s
  63. }
  64. // stateFetcher manages the active state sync and accepts requests
  65. // on its behalf.
  66. func (d *Downloader) stateFetcher() {
  67. for {
  68. select {
  69. case s := <-d.stateSyncStart:
  70. for next := s; next != nil; {
  71. next = d.runStateSync(next)
  72. }
  73. case <-d.stateCh:
  74. // Ignore state responses while no sync is running.
  75. case <-d.quitCh:
  76. return
  77. }
  78. }
  79. }
  80. // runStateSync runs a state synchronisation until it completes or another root
  81. // hash is requested to be switched over to.
  82. func (d *Downloader) runStateSync(s *stateSync) *stateSync {
  83. var (
  84. active = make(map[string]*stateReq) // Currently in-flight requests
  85. finished []*stateReq // Completed or failed requests
  86. timeout = make(chan *stateReq) // Timed out active requests
  87. )
  88. defer func() {
  89. // Cancel active request timers on exit. Also set peers to idle so they're
  90. // available for the next sync.
  91. for _, req := range active {
  92. req.timer.Stop()
  93. req.peer.SetNodeDataIdle(len(req.items))
  94. }
  95. }()
  96. // Run the state sync.
  97. go s.run()
  98. defer s.Cancel()
  99. // Listen for peer departure events to cancel assigned tasks
  100. peerDrop := make(chan *peerConnection, 1024)
  101. peerSub := s.d.peers.SubscribePeerDrops(peerDrop)
  102. defer peerSub.Unsubscribe()
  103. for {
  104. // Enable sending of the first buffered element if there is one.
  105. var (
  106. deliverReq *stateReq
  107. deliverReqCh chan *stateReq
  108. )
  109. if len(finished) > 0 {
  110. deliverReq = finished[0]
  111. deliverReqCh = s.deliver
  112. }
  113. select {
  114. // The stateSync lifecycle:
  115. case next := <-d.stateSyncStart:
  116. return next
  117. case <-s.done:
  118. return nil
  119. // Send the next finished request to the current sync:
  120. case deliverReqCh <- deliverReq:
  121. // Shift out the first request, but also set the emptied slot to nil for GC
  122. copy(finished, finished[1:])
  123. finished[len(finished)-1] = nil
  124. finished = finished[:len(finished)-1]
  125. // Handle incoming state packs:
  126. case pack := <-d.stateCh:
  127. // Discard any data not requested (or previously timed out)
  128. req := active[pack.PeerId()]
  129. if req == nil {
  130. log.Debug("Unrequested node data", "peer", pack.PeerId(), "len", pack.Items())
  131. continue
  132. }
  133. // Finalize the request and queue up for processing
  134. req.timer.Stop()
  135. req.response = pack.(*statePack).states
  136. finished = append(finished, req)
  137. delete(active, pack.PeerId())
  138. // Handle dropped peer connections:
  139. case p := <-peerDrop:
  140. // Skip if no request is currently pending
  141. req := active[p.id]
  142. if req == nil {
  143. continue
  144. }
  145. // Finalize the request and queue up for processing
  146. req.timer.Stop()
  147. req.dropped = true
  148. finished = append(finished, req)
  149. delete(active, p.id)
  150. // Handle timed-out requests:
  151. case req := <-timeout:
  152. // If the peer is already requesting something else, ignore the stale timeout.
  153. // This can happen when the timeout and the delivery happens simultaneously,
  154. // causing both pathways to trigger.
  155. if active[req.peer.id] != req {
  156. continue
  157. }
  158. // Move the timed out data back into the download queue
  159. finished = append(finished, req)
  160. delete(active, req.peer.id)
  161. // Track outgoing state requests:
  162. case req := <-d.trackStateReq:
  163. // If an active request already exists for this peer, we have a problem. In
  164. // theory the trie node schedule must never assign two requests to the same
  165. // peer. In practice however, a peer might receive a request, disconnect and
  166. // immediately reconnect before the previous times out. In this case the first
  167. // request is never honored, alas we must not silently overwrite it, as that
  168. // causes valid requests to go missing and sync to get stuck.
  169. if old := active[req.peer.id]; old != nil {
  170. log.Warn("Busy peer assigned new state fetch", "peer", old.peer.id)
  171. // Make sure the previous one doesn't get siletly lost
  172. old.timer.Stop()
  173. old.dropped = true
  174. finished = append(finished, old)
  175. }
  176. // Start a timer to notify the sync loop if the peer stalled.
  177. req.timer = time.AfterFunc(req.timeout, func() {
  178. select {
  179. case timeout <- req:
  180. case <-s.done:
  181. // Prevent leaking of timer goroutines in the unlikely case where a
  182. // timer is fired just before exiting runStateSync.
  183. }
  184. })
  185. active[req.peer.id] = req
  186. }
  187. }
  188. }
  189. // stateSync schedules requests for downloading a particular state trie defined
  190. // by a given state root.
  191. type stateSync struct {
  192. d *Downloader // Downloader instance to access and manage current peerset
  193. sched *trie.Sync // State trie sync scheduler defining the tasks
  194. keccak hash.Hash // Keccak256 hasher to verify deliveries with
  195. tasks map[common.Hash]*stateTask // Set of tasks currently queued for retrieval
  196. numUncommitted int
  197. bytesUncommitted int
  198. deliver chan *stateReq // Delivery channel multiplexing peer responses
  199. cancel chan struct{} // Channel to signal a termination request
  200. cancelOnce sync.Once // Ensures cancel only ever gets called once
  201. done chan struct{} // Channel to signal termination completion
  202. err error // Any error hit during sync (set before completion)
  203. }
  204. // stateTask represents a single trie node download task, containing a set of
  205. // peers already attempted retrieval from to detect stalled syncs and abort.
  206. type stateTask struct {
  207. attempts map[string]struct{}
  208. }
  209. // newStateSync creates a new state trie download scheduler. This method does not
  210. // yet start the sync. The user needs to call run to initiate.
  211. func newStateSync(d *Downloader, root common.Hash) *stateSync {
  212. return &stateSync{
  213. d: d,
  214. sched: state.NewStateSync(root, d.stateDB),
  215. keccak: sha3.NewKeccak256(),
  216. tasks: make(map[common.Hash]*stateTask),
  217. deliver: make(chan *stateReq),
  218. cancel: make(chan struct{}),
  219. done: make(chan struct{}),
  220. }
  221. }
  222. // run starts the task assignment and response processing loop, blocking until
  223. // it finishes, and finally notifying any goroutines waiting for the loop to
  224. // finish.
  225. func (s *stateSync) run() {
  226. s.err = s.loop()
  227. close(s.done)
  228. }
  229. // Wait blocks until the sync is done or canceled.
  230. func (s *stateSync) Wait() error {
  231. <-s.done
  232. return s.err
  233. }
  234. // Cancel cancels the sync and waits until it has shut down.
  235. func (s *stateSync) Cancel() error {
  236. s.cancelOnce.Do(func() { close(s.cancel) })
  237. return s.Wait()
  238. }
  239. // loop is the main event loop of a state trie sync. It it responsible for the
  240. // assignment of new tasks to peers (including sending it to them) as well as
  241. // for the processing of inbound data. Note, that the loop does not directly
  242. // receive data from peers, rather those are buffered up in the downloader and
  243. // pushed here async. The reason is to decouple processing from data receipt
  244. // and timeouts.
  245. func (s *stateSync) loop() (err error) {
  246. // Listen for new peer events to assign tasks to them
  247. newPeer := make(chan *peerConnection, 1024)
  248. peerSub := s.d.peers.SubscribeNewPeers(newPeer)
  249. defer peerSub.Unsubscribe()
  250. defer func() {
  251. cerr := s.commit(true)
  252. if err == nil {
  253. err = cerr
  254. }
  255. }()
  256. // Keep assigning new tasks until the sync completes or aborts
  257. for s.sched.Pending() > 0 {
  258. if err = s.commit(false); err != nil {
  259. return err
  260. }
  261. s.assignTasks()
  262. // Tasks assigned, wait for something to happen
  263. select {
  264. case <-newPeer:
  265. // New peer arrived, try to assign it download tasks
  266. case <-s.cancel:
  267. return errCancelStateFetch
  268. case <-s.d.cancelCh:
  269. return errCancelStateFetch
  270. case req := <-s.deliver:
  271. // Response, disconnect or timeout triggered, drop the peer if stalling
  272. log.Trace("Received node data response", "peer", req.peer.id, "count", len(req.response), "dropped", req.dropped, "timeout", !req.dropped && req.timedOut())
  273. if len(req.items) <= 2 && !req.dropped && req.timedOut() {
  274. // 2 items are the minimum requested, if even that times out, we've no use of
  275. // this peer at the moment.
  276. log.Warn("Stalling state sync, dropping peer", "peer", req.peer.id)
  277. s.d.dropPeer(req.peer.id)
  278. }
  279. // Process all the received blobs and check for stale delivery
  280. if err = s.process(req); err != nil {
  281. log.Warn("Node data write error", "err", err)
  282. return err
  283. }
  284. req.peer.SetNodeDataIdle(len(req.response))
  285. }
  286. }
  287. return nil
  288. }
  289. func (s *stateSync) commit(force bool) error {
  290. if !force && s.bytesUncommitted < ethdb.IdealBatchSize {
  291. return nil
  292. }
  293. start := time.Now()
  294. b := s.d.stateDB.NewBatch()
  295. if written, err := s.sched.Commit(b); written == 0 || err != nil {
  296. return err
  297. }
  298. if err := b.Write(); err != nil {
  299. return fmt.Errorf("DB write error: %v", err)
  300. }
  301. s.updateStats(s.numUncommitted, 0, 0, time.Since(start))
  302. s.numUncommitted = 0
  303. s.bytesUncommitted = 0
  304. return nil
  305. }
  306. // assignTasks attempts to assign new tasks to all idle peers, either from the
  307. // batch currently being retried, or fetching new data from the trie sync itself.
  308. func (s *stateSync) assignTasks() {
  309. // Iterate over all idle peers and try to assign them state fetches
  310. peers, _ := s.d.peers.NodeDataIdlePeers()
  311. for _, p := range peers {
  312. // Assign a batch of fetches proportional to the estimated latency/bandwidth
  313. cap := p.NodeDataCapacity(s.d.requestRTT())
  314. req := &stateReq{peer: p, timeout: s.d.requestTTL()}
  315. s.fillTasks(cap, req)
  316. // If the peer was assigned tasks to fetch, send the network request
  317. if len(req.items) > 0 {
  318. req.peer.log.Trace("Requesting new batch of data", "type", "state", "count", len(req.items))
  319. select {
  320. case s.d.trackStateReq <- req:
  321. req.peer.FetchNodeData(req.items)
  322. case <-s.cancel:
  323. case <-s.d.cancelCh:
  324. }
  325. }
  326. }
  327. }
  328. // fillTasks fills the given request object with a maximum of n state download
  329. // tasks to send to the remote peer.
  330. func (s *stateSync) fillTasks(n int, req *stateReq) {
  331. // Refill available tasks from the scheduler.
  332. if len(s.tasks) < n {
  333. new := s.sched.Missing(n - len(s.tasks))
  334. for _, hash := range new {
  335. s.tasks[hash] = &stateTask{make(map[string]struct{})}
  336. }
  337. }
  338. // Find tasks that haven't been tried with the request's peer.
  339. req.items = make([]common.Hash, 0, n)
  340. req.tasks = make(map[common.Hash]*stateTask, n)
  341. for hash, t := range s.tasks {
  342. // Stop when we've gathered enough requests
  343. if len(req.items) == n {
  344. break
  345. }
  346. // Skip any requests we've already tried from this peer
  347. if _, ok := t.attempts[req.peer.id]; ok {
  348. continue
  349. }
  350. // Assign the request to this peer
  351. t.attempts[req.peer.id] = struct{}{}
  352. req.items = append(req.items, hash)
  353. req.tasks[hash] = t
  354. delete(s.tasks, hash)
  355. }
  356. }
  357. // process iterates over a batch of delivered state data, injecting each item
  358. // into a running state sync, re-queuing any items that were requested but not
  359. // delivered.
  360. func (s *stateSync) process(req *stateReq) error {
  361. // Collect processing stats and update progress if valid data was received
  362. duplicate, unexpected := 0, 0
  363. defer func(start time.Time) {
  364. if duplicate > 0 || unexpected > 0 {
  365. s.updateStats(0, duplicate, unexpected, time.Since(start))
  366. }
  367. }(time.Now())
  368. // Iterate over all the delivered data and inject one-by-one into the trie
  369. progress := false
  370. for _, blob := range req.response {
  371. prog, hash, err := s.processNodeData(blob)
  372. switch err {
  373. case nil:
  374. s.numUncommitted++
  375. s.bytesUncommitted += len(blob)
  376. progress = progress || prog
  377. case trie.ErrNotRequested:
  378. unexpected++
  379. case trie.ErrAlreadyProcessed:
  380. duplicate++
  381. default:
  382. return fmt.Errorf("invalid state node %s: %v", hash.TerminalString(), err)
  383. }
  384. if _, ok := req.tasks[hash]; ok {
  385. delete(req.tasks, hash)
  386. }
  387. }
  388. // Put unfulfilled tasks back into the retry queue
  389. npeers := s.d.peers.Len()
  390. for hash, task := range req.tasks {
  391. // If the node did deliver something, missing items may be due to a protocol
  392. // limit or a previous timeout + delayed delivery. Both cases should permit
  393. // the node to retry the missing items (to avoid single-peer stalls).
  394. if len(req.response) > 0 || req.timedOut() {
  395. delete(task.attempts, req.peer.id)
  396. }
  397. // If we've requested the node too many times already, it may be a malicious
  398. // sync where nobody has the right data. Abort.
  399. if len(task.attempts) >= npeers {
  400. return fmt.Errorf("state node %s failed with all peers (%d tries, %d peers)", hash.TerminalString(), len(task.attempts), npeers)
  401. }
  402. // Missing item, place into the retry queue.
  403. s.tasks[hash] = task
  404. }
  405. return nil
  406. }
  407. // processNodeData tries to inject a trie node data blob delivered from a remote
  408. // peer into the state trie, returning whether anything useful was written or any
  409. // error occurred.
  410. func (s *stateSync) processNodeData(blob []byte) (bool, common.Hash, error) {
  411. res := trie.SyncResult{Data: blob}
  412. s.keccak.Reset()
  413. s.keccak.Write(blob)
  414. s.keccak.Sum(res.Hash[:0])
  415. committed, _, err := s.sched.Process([]trie.SyncResult{res})
  416. return committed, res.Hash, err
  417. }
  418. // updateStats bumps the various state sync progress counters and displays a log
  419. // message for the user to see.
  420. func (s *stateSync) updateStats(written, duplicate, unexpected int, duration time.Duration) {
  421. s.d.syncStatsLock.Lock()
  422. defer s.d.syncStatsLock.Unlock()
  423. s.d.syncStatsState.pending = uint64(s.sched.Pending())
  424. s.d.syncStatsState.processed += uint64(written)
  425. s.d.syncStatsState.duplicate += uint64(duplicate)
  426. s.d.syncStatsState.unexpected += uint64(unexpected)
  427. if written > 0 || duplicate > 0 || unexpected > 0 {
  428. log.Info("Imported new state entries", "count", written, "elapsed", common.PrettyDuration(duration), "processed", s.d.syncStatsState.processed, "pending", s.d.syncStatsState.pending, "retry", len(s.tasks), "duplicate", s.d.syncStatsState.duplicate, "unexpected", s.d.syncStatsState.unexpected)
  429. }
  430. if written > 0 {
  431. rawdb.WriteFastTrieProgress(s.d.stateDB, s.d.syncStatsState.processed)
  432. }
  433. }