statesync.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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. "sync"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core/state"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/ethdb"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/trie"
  27. "golang.org/x/crypto/sha3"
  28. )
  29. // stateReq represents a batch of state fetch requests grouped together into
  30. // a single data retrieval network packet.
  31. type stateReq struct {
  32. nItems uint16 // Number of items requested for download (max is 384, so uint16 is sufficient)
  33. trieTasks map[string]*trieTask // Trie node download tasks to track previous attempts
  34. codeTasks map[common.Hash]*codeTask // Byte code 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. delivered time.Time // Time when the packet was delivered (independent when we process it)
  39. response [][]byte // Response data of the peer (nil for timeouts)
  40. dropped bool // Flag whether the peer dropped off early
  41. }
  42. // timedOut returns if this request timed out.
  43. func (req *stateReq) timedOut() bool {
  44. return req.response == nil
  45. }
  46. // stateSyncStats is a collection of progress stats to report during a state trie
  47. // sync to RPC requests as well as to display in user logs.
  48. type stateSyncStats struct {
  49. processed uint64 // Number of state entries processed
  50. duplicate uint64 // Number of state entries downloaded twice
  51. unexpected uint64 // Number of non-requested state entries received
  52. pending uint64 // Number of still pending state entries
  53. }
  54. // syncState starts downloading state with the given root hash.
  55. func (d *Downloader) syncState(root common.Hash) *stateSync {
  56. // Create the state sync
  57. s := newStateSync(d, root)
  58. select {
  59. case d.stateSyncStart <- s:
  60. // If we tell the statesync to restart with a new root, we also need
  61. // to wait for it to actually also start -- when old requests have timed
  62. // out or been delivered
  63. <-s.started
  64. case <-d.quitCh:
  65. s.err = errCancelStateFetch
  66. close(s.done)
  67. }
  68. return s
  69. }
  70. // stateFetcher manages the active state sync and accepts requests
  71. // on its behalf.
  72. func (d *Downloader) stateFetcher() {
  73. for {
  74. select {
  75. case s := <-d.stateSyncStart:
  76. for next := s; next != nil; {
  77. next = d.runStateSync(next)
  78. }
  79. case <-d.stateCh:
  80. // Ignore state responses while no sync is running.
  81. case <-d.quitCh:
  82. return
  83. }
  84. }
  85. }
  86. // runStateSync runs a state synchronisation until it completes or another root
  87. // hash is requested to be switched over to.
  88. func (d *Downloader) runStateSync(s *stateSync) *stateSync {
  89. var (
  90. active = make(map[string]*stateReq) // Currently in-flight requests
  91. finished []*stateReq // Completed or failed requests
  92. timeout = make(chan *stateReq) // Timed out active requests
  93. )
  94. log.Trace("State sync starting", "root", s.root)
  95. defer func() {
  96. // Cancel active request timers on exit. Also set peers to idle so they're
  97. // available for the next sync.
  98. for _, req := range active {
  99. req.timer.Stop()
  100. req.peer.SetNodeDataIdle(int(req.nItems), time.Now())
  101. }
  102. }()
  103. go s.run()
  104. defer s.Cancel()
  105. // Listen for peer departure events to cancel assigned tasks
  106. peerDrop := make(chan *peerConnection, 1024)
  107. peerSub := s.d.peers.SubscribePeerDrops(peerDrop)
  108. defer peerSub.Unsubscribe()
  109. for {
  110. // Enable sending of the first buffered element if there is one.
  111. var (
  112. deliverReq *stateReq
  113. deliverReqCh chan *stateReq
  114. )
  115. if len(finished) > 0 {
  116. deliverReq = finished[0]
  117. deliverReqCh = s.deliver
  118. }
  119. select {
  120. // The stateSync lifecycle:
  121. case next := <-d.stateSyncStart:
  122. d.spindownStateSync(active, finished, timeout, peerDrop)
  123. return next
  124. case <-s.done:
  125. d.spindownStateSync(active, finished, timeout, peerDrop)
  126. return nil
  127. // Send the next finished request to the current sync:
  128. case deliverReqCh <- deliverReq:
  129. // Shift out the first request, but also set the emptied slot to nil for GC
  130. copy(finished, finished[1:])
  131. finished[len(finished)-1] = nil
  132. finished = finished[:len(finished)-1]
  133. // Handle incoming state packs:
  134. case pack := <-d.stateCh:
  135. // Discard any data not requested (or previously timed out)
  136. req := active[pack.PeerId()]
  137. if req == nil {
  138. log.Debug("Unrequested node data", "peer", pack.PeerId(), "len", pack.Items())
  139. continue
  140. }
  141. // Finalize the request and queue up for processing
  142. req.timer.Stop()
  143. req.response = pack.(*statePack).states
  144. req.delivered = time.Now()
  145. finished = append(finished, req)
  146. delete(active, pack.PeerId())
  147. // Handle dropped peer connections:
  148. case p := <-peerDrop:
  149. // Skip if no request is currently pending
  150. req := active[p.id]
  151. if req == nil {
  152. continue
  153. }
  154. // Finalize the request and queue up for processing
  155. req.timer.Stop()
  156. req.dropped = true
  157. req.delivered = time.Now()
  158. finished = append(finished, req)
  159. delete(active, p.id)
  160. // Handle timed-out requests:
  161. case req := <-timeout:
  162. // If the peer is already requesting something else, ignore the stale timeout.
  163. // This can happen when the timeout and the delivery happens simultaneously,
  164. // causing both pathways to trigger.
  165. if active[req.peer.id] != req {
  166. continue
  167. }
  168. req.delivered = time.Now()
  169. // Move the timed out data back into the download queue
  170. finished = append(finished, req)
  171. delete(active, req.peer.id)
  172. // Track outgoing state requests:
  173. case req := <-d.trackStateReq:
  174. // If an active request already exists for this peer, we have a problem. In
  175. // theory the trie node schedule must never assign two requests to the same
  176. // peer. In practice however, a peer might receive a request, disconnect and
  177. // immediately reconnect before the previous times out. In this case the first
  178. // request is never honored, alas we must not silently overwrite it, as that
  179. // causes valid requests to go missing and sync to get stuck.
  180. if old := active[req.peer.id]; old != nil {
  181. log.Warn("Busy peer assigned new state fetch", "peer", old.peer.id)
  182. // Move the previous request to the finished set
  183. old.timer.Stop()
  184. old.dropped = true
  185. old.delivered = time.Now()
  186. finished = append(finished, old)
  187. }
  188. // Start a timer to notify the sync loop if the peer stalled.
  189. req.timer = time.AfterFunc(req.timeout, func() {
  190. timeout <- req
  191. })
  192. active[req.peer.id] = req
  193. }
  194. }
  195. }
  196. // spindownStateSync 'drains' the outstanding requests; some will be delivered and other
  197. // will time out. This is to ensure that when the next stateSync starts working, all peers
  198. // are marked as idle and de facto _are_ idle.
  199. func (d *Downloader) spindownStateSync(active map[string]*stateReq, finished []*stateReq, timeout chan *stateReq, peerDrop chan *peerConnection) {
  200. log.Trace("State sync spinning down", "active", len(active), "finished", len(finished))
  201. for len(active) > 0 {
  202. var (
  203. req *stateReq
  204. reason string
  205. )
  206. select {
  207. // Handle (drop) incoming state packs:
  208. case pack := <-d.stateCh:
  209. req = active[pack.PeerId()]
  210. reason = "delivered"
  211. // Handle dropped peer connections:
  212. case p := <-peerDrop:
  213. req = active[p.id]
  214. reason = "peerdrop"
  215. // Handle timed-out requests:
  216. case req = <-timeout:
  217. reason = "timeout"
  218. }
  219. if req == nil {
  220. continue
  221. }
  222. req.peer.log.Trace("State peer marked idle (spindown)", "req.items", int(req.nItems), "reason", reason)
  223. req.timer.Stop()
  224. delete(active, req.peer.id)
  225. req.peer.SetNodeDataIdle(int(req.nItems), time.Now())
  226. }
  227. // The 'finished' set contains deliveries that we were going to pass to processing.
  228. // Those are now moot, but we still need to set those peers as idle, which would
  229. // otherwise have been done after processing
  230. for _, req := range finished {
  231. req.peer.SetNodeDataIdle(int(req.nItems), time.Now())
  232. }
  233. }
  234. // stateSync schedules requests for downloading a particular state trie defined
  235. // by a given state root.
  236. type stateSync struct {
  237. d *Downloader // Downloader instance to access and manage current peerset
  238. root common.Hash // State root currently being synced
  239. sched *trie.Sync // State trie sync scheduler defining the tasks
  240. keccak crypto.KeccakState // Keccak256 hasher to verify deliveries with
  241. trieTasks map[string]*trieTask // Set of trie node tasks currently queued for retrieval, indexed by path
  242. codeTasks map[common.Hash]*codeTask // Set of byte code tasks currently queued for retrieval, indexed by hash
  243. numUncommitted int
  244. bytesUncommitted int
  245. started chan struct{} // Started is signalled once the sync loop starts
  246. deliver chan *stateReq // Delivery channel multiplexing peer responses
  247. cancel chan struct{} // Channel to signal a termination request
  248. cancelOnce sync.Once // Ensures cancel only ever gets called once
  249. done chan struct{} // Channel to signal termination completion
  250. err error // Any error hit during sync (set before completion)
  251. }
  252. // trieTask represents a single trie node download task, containing a set of
  253. // peers already attempted retrieval from to detect stalled syncs and abort.
  254. type trieTask struct {
  255. hash common.Hash
  256. path [][]byte
  257. attempts map[string]struct{}
  258. }
  259. // codeTask represents a single byte code download task, containing a set of
  260. // peers already attempted retrieval from to detect stalled syncs and abort.
  261. type codeTask struct {
  262. attempts map[string]struct{}
  263. }
  264. // newStateSync creates a new state trie download scheduler. This method does not
  265. // yet start the sync. The user needs to call run to initiate.
  266. func newStateSync(d *Downloader, root common.Hash) *stateSync {
  267. return &stateSync{
  268. d: d,
  269. root: root,
  270. sched: state.NewStateSync(root, d.stateDB, nil),
  271. keccak: sha3.NewLegacyKeccak256().(crypto.KeccakState),
  272. trieTasks: make(map[string]*trieTask),
  273. codeTasks: make(map[common.Hash]*codeTask),
  274. deliver: make(chan *stateReq),
  275. cancel: make(chan struct{}),
  276. done: make(chan struct{}),
  277. started: make(chan struct{}),
  278. }
  279. }
  280. // run starts the task assignment and response processing loop, blocking until
  281. // it finishes, and finally notifying any goroutines waiting for the loop to
  282. // finish.
  283. func (s *stateSync) run() {
  284. close(s.started)
  285. if s.d.snapSync {
  286. s.err = s.d.SnapSyncer.Sync(s.root, s.cancel)
  287. } else {
  288. s.err = s.loop()
  289. }
  290. close(s.done)
  291. }
  292. // Wait blocks until the sync is done or canceled.
  293. func (s *stateSync) Wait() error {
  294. <-s.done
  295. return s.err
  296. }
  297. // Cancel cancels the sync and waits until it has shut down.
  298. func (s *stateSync) Cancel() error {
  299. s.cancelOnce.Do(func() {
  300. close(s.cancel)
  301. })
  302. return s.Wait()
  303. }
  304. // loop is the main event loop of a state trie sync. It it responsible for the
  305. // assignment of new tasks to peers (including sending it to them) as well as
  306. // for the processing of inbound data. Note, that the loop does not directly
  307. // receive data from peers, rather those are buffered up in the downloader and
  308. // pushed here async. The reason is to decouple processing from data receipt
  309. // and timeouts.
  310. func (s *stateSync) loop() (err error) {
  311. // Listen for new peer events to assign tasks to them
  312. newPeer := make(chan *peerConnection, 1024)
  313. peerSub := s.d.peers.SubscribeNewPeers(newPeer)
  314. defer peerSub.Unsubscribe()
  315. defer func() {
  316. cerr := s.commit(true)
  317. if err == nil {
  318. err = cerr
  319. }
  320. }()
  321. // Keep assigning new tasks until the sync completes or aborts
  322. for s.sched.Pending() > 0 {
  323. if err = s.commit(false); err != nil {
  324. return err
  325. }
  326. s.assignTasks()
  327. // Tasks assigned, wait for something to happen
  328. select {
  329. case <-newPeer:
  330. // New peer arrived, try to assign it download tasks
  331. case <-s.cancel:
  332. return errCancelStateFetch
  333. case <-s.d.cancelCh:
  334. return errCanceled
  335. case req := <-s.deliver:
  336. // Response, disconnect or timeout triggered, drop the peer if stalling
  337. log.Trace("Received node data response", "peer", req.peer.id, "count", len(req.response), "dropped", req.dropped, "timeout", !req.dropped && req.timedOut())
  338. if req.nItems <= 2 && !req.dropped && req.timedOut() {
  339. // 2 items are the minimum requested, if even that times out, we've no use of
  340. // this peer at the moment.
  341. log.Warn("Stalling state sync, dropping peer", "peer", req.peer.id)
  342. if s.d.dropPeer == nil {
  343. // The dropPeer method is nil when `--copydb` is used for a local copy.
  344. // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
  345. req.peer.log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", req.peer.id)
  346. } else {
  347. s.d.dropPeer(req.peer.id)
  348. // If this peer was the master peer, abort sync immediately
  349. s.d.cancelLock.RLock()
  350. master := req.peer.id == s.d.cancelPeer
  351. s.d.cancelLock.RUnlock()
  352. if master {
  353. s.d.cancel()
  354. return errTimeout
  355. }
  356. }
  357. }
  358. // Process all the received blobs and check for stale delivery
  359. delivered, err := s.process(req)
  360. req.peer.SetNodeDataIdle(delivered, req.delivered)
  361. if err != nil {
  362. log.Warn("Node data write error", "err", err)
  363. return err
  364. }
  365. }
  366. }
  367. return nil
  368. }
  369. func (s *stateSync) commit(force bool) error {
  370. if !force && s.bytesUncommitted < ethdb.IdealBatchSize {
  371. return nil
  372. }
  373. start := time.Now()
  374. b := s.d.stateDB.NewBatch()
  375. if err := s.sched.Commit(b); err != nil {
  376. return err
  377. }
  378. if err := b.Write(); err != nil {
  379. return fmt.Errorf("DB write error: %v", err)
  380. }
  381. s.updateStats(s.numUncommitted, 0, 0, time.Since(start))
  382. s.numUncommitted = 0
  383. s.bytesUncommitted = 0
  384. return nil
  385. }
  386. // assignTasks attempts to assign new tasks to all idle peers, either from the
  387. // batch currently being retried, or fetching new data from the trie sync itself.
  388. func (s *stateSync) assignTasks() {
  389. // Iterate over all idle peers and try to assign them state fetches
  390. peers, _ := s.d.peers.NodeDataIdlePeers()
  391. for _, p := range peers {
  392. // Assign a batch of fetches proportional to the estimated latency/bandwidth
  393. cap := p.NodeDataCapacity(s.d.peers.rates.TargetRoundTrip())
  394. req := &stateReq{peer: p, timeout: s.d.peers.rates.TargetTimeout()}
  395. nodes, _, codes := s.fillTasks(cap, req)
  396. // If the peer was assigned tasks to fetch, send the network request
  397. if len(nodes)+len(codes) > 0 {
  398. req.peer.log.Trace("Requesting batch of state data", "nodes", len(nodes), "codes", len(codes), "root", s.root)
  399. select {
  400. case s.d.trackStateReq <- req:
  401. req.peer.FetchNodeData(append(nodes, codes...)) // Unified retrieval under eth/6x
  402. case <-s.cancel:
  403. case <-s.d.cancelCh:
  404. }
  405. }
  406. }
  407. }
  408. // fillTasks fills the given request object with a maximum of n state download
  409. // tasks to send to the remote peer.
  410. func (s *stateSync) fillTasks(n int, req *stateReq) (nodes []common.Hash, paths []trie.SyncPath, codes []common.Hash) {
  411. // Refill available tasks from the scheduler.
  412. if fill := n - (len(s.trieTasks) + len(s.codeTasks)); fill > 0 {
  413. paths, hashes, codes := s.sched.Missing(fill)
  414. for i, path := range paths {
  415. s.trieTasks[path] = &trieTask{
  416. hash: hashes[i],
  417. path: trie.NewSyncPath([]byte(path)),
  418. attempts: make(map[string]struct{}),
  419. }
  420. }
  421. for _, hash := range codes {
  422. s.codeTasks[hash] = &codeTask{
  423. attempts: make(map[string]struct{}),
  424. }
  425. }
  426. }
  427. // Find tasks that haven't been tried with the request's peer. Prefer code
  428. // over trie nodes as those can be written to disk and forgotten about.
  429. nodes = make([]common.Hash, 0, n)
  430. paths = make([]trie.SyncPath, 0, n)
  431. codes = make([]common.Hash, 0, n)
  432. req.trieTasks = make(map[string]*trieTask, n)
  433. req.codeTasks = make(map[common.Hash]*codeTask, n)
  434. for hash, t := range s.codeTasks {
  435. // Stop when we've gathered enough requests
  436. if len(nodes)+len(codes) == n {
  437. break
  438. }
  439. // Skip any requests we've already tried from this peer
  440. if _, ok := t.attempts[req.peer.id]; ok {
  441. continue
  442. }
  443. // Assign the request to this peer
  444. t.attempts[req.peer.id] = struct{}{}
  445. codes = append(codes, hash)
  446. req.codeTasks[hash] = t
  447. delete(s.codeTasks, hash)
  448. }
  449. for path, t := range s.trieTasks {
  450. // Stop when we've gathered enough requests
  451. if len(nodes)+len(codes) == n {
  452. break
  453. }
  454. // Skip any requests we've already tried from this peer
  455. if _, ok := t.attempts[req.peer.id]; ok {
  456. continue
  457. }
  458. // Assign the request to this peer
  459. t.attempts[req.peer.id] = struct{}{}
  460. nodes = append(nodes, t.hash)
  461. paths = append(paths, t.path)
  462. req.trieTasks[path] = t
  463. delete(s.trieTasks, path)
  464. }
  465. req.nItems = uint16(len(nodes) + len(codes))
  466. return nodes, paths, codes
  467. }
  468. // process iterates over a batch of delivered state data, injecting each item
  469. // into a running state sync, re-queuing any items that were requested but not
  470. // delivered. Returns whether the peer actually managed to deliver anything of
  471. // value, and any error that occurred.
  472. func (s *stateSync) process(req *stateReq) (int, error) {
  473. // Collect processing stats and update progress if valid data was received
  474. duplicate, unexpected, successful := 0, 0, 0
  475. defer func(start time.Time) {
  476. if duplicate > 0 || unexpected > 0 {
  477. s.updateStats(0, duplicate, unexpected, time.Since(start))
  478. }
  479. }(time.Now())
  480. // Iterate over all the delivered data and inject one-by-one into the trie
  481. for _, blob := range req.response {
  482. hash, err := s.processNodeData(req.trieTasks, req.codeTasks, blob)
  483. switch err {
  484. case nil:
  485. s.numUncommitted++
  486. s.bytesUncommitted += len(blob)
  487. successful++
  488. case trie.ErrNotRequested:
  489. unexpected++
  490. case trie.ErrAlreadyProcessed:
  491. duplicate++
  492. default:
  493. return successful, fmt.Errorf("invalid state node %s: %v", hash.TerminalString(), err)
  494. }
  495. }
  496. // Put unfulfilled tasks back into the retry queue
  497. npeers := s.d.peers.Len()
  498. for path, task := range req.trieTasks {
  499. // If the node did deliver something, missing items may be due to a protocol
  500. // limit or a previous timeout + delayed delivery. Both cases should permit
  501. // the node to retry the missing items (to avoid single-peer stalls).
  502. if len(req.response) > 0 || req.timedOut() {
  503. delete(task.attempts, req.peer.id)
  504. }
  505. // If we've requested the node too many times already, it may be a malicious
  506. // sync where nobody has the right data. Abort.
  507. if len(task.attempts) >= npeers {
  508. return successful, fmt.Errorf("trie node %s failed with all peers (%d tries, %d peers)", task.hash.TerminalString(), len(task.attempts), npeers)
  509. }
  510. // Missing item, place into the retry queue.
  511. s.trieTasks[path] = task
  512. }
  513. for hash, task := range req.codeTasks {
  514. // If the node did deliver something, missing items may be due to a protocol
  515. // limit or a previous timeout + delayed delivery. Both cases should permit
  516. // the node to retry the missing items (to avoid single-peer stalls).
  517. if len(req.response) > 0 || req.timedOut() {
  518. delete(task.attempts, req.peer.id)
  519. }
  520. // If we've requested the node too many times already, it may be a malicious
  521. // sync where nobody has the right data. Abort.
  522. if len(task.attempts) >= npeers {
  523. return successful, fmt.Errorf("byte code %s failed with all peers (%d tries, %d peers)", hash.TerminalString(), len(task.attempts), npeers)
  524. }
  525. // Missing item, place into the retry queue.
  526. s.codeTasks[hash] = task
  527. }
  528. return successful, nil
  529. }
  530. // processNodeData tries to inject a trie node data blob delivered from a remote
  531. // peer into the state trie, returning whether anything useful was written or any
  532. // error occurred.
  533. //
  534. // If multiple requests correspond to the same hash, this method will inject the
  535. // blob as a result for the first one only, leaving the remaining duplicates to
  536. // be fetched again.
  537. func (s *stateSync) processNodeData(nodeTasks map[string]*trieTask, codeTasks map[common.Hash]*codeTask, blob []byte) (common.Hash, error) {
  538. var hash common.Hash
  539. s.keccak.Reset()
  540. s.keccak.Write(blob)
  541. s.keccak.Read(hash[:])
  542. if _, present := codeTasks[hash]; present {
  543. err := s.sched.ProcessCode(trie.CodeSyncResult{
  544. Hash: hash,
  545. Data: blob,
  546. })
  547. delete(codeTasks, hash)
  548. return hash, err
  549. }
  550. for path, task := range nodeTasks {
  551. if task.hash == hash {
  552. err := s.sched.ProcessNode(trie.NodeSyncResult{
  553. Path: path,
  554. Data: blob,
  555. })
  556. delete(nodeTasks, path)
  557. return hash, err
  558. }
  559. }
  560. return common.Hash{}, trie.ErrNotRequested
  561. }
  562. // updateStats bumps the various state sync progress counters and displays a log
  563. // message for the user to see.
  564. func (s *stateSync) updateStats(written, duplicate, unexpected int, duration time.Duration) {
  565. s.d.syncStatsLock.Lock()
  566. defer s.d.syncStatsLock.Unlock()
  567. s.d.syncStatsState.pending = uint64(s.sched.Pending())
  568. s.d.syncStatsState.processed += uint64(written)
  569. s.d.syncStatsState.duplicate += uint64(duplicate)
  570. s.d.syncStatsState.unexpected += uint64(unexpected)
  571. if written > 0 || duplicate > 0 || unexpected > 0 {
  572. log.Info("Imported new state entries", "count", written, "elapsed", common.PrettyDuration(duration), "processed", s.d.syncStatsState.processed, "pending", s.d.syncStatsState.pending, "trieretry", len(s.trieTasks), "coderetry", len(s.codeTasks), "duplicate", s.d.syncStatsState.duplicate, "unexpected", s.d.syncStatsState.unexpected)
  573. }
  574. //if written > 0 {
  575. //rawdb.WriteFastTrieProgress(s.d.stateDB, s.d.syncStatsState.processed)
  576. //}
  577. }