statesync.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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/rawdb"
  23. "github.com/ethereum/go-ethereum/core/state"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. "github.com/ethereum/go-ethereum/ethdb"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/ethereum/go-ethereum/trie"
  28. "golang.org/x/crypto/sha3"
  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. nItems uint16 // Number of items requested for download (max is 384, so uint16 is sufficient)
  34. trieTasks map[common.Hash]*trieTask // Trie node download tasks to track previous attempts
  35. codeTasks map[common.Hash]*codeTask // Byte code download tasks to track previous attempts
  36. timeout time.Duration // Maximum round trip time for this to complete
  37. timer *time.Timer // Timer to fire when the RTT timeout expires
  38. peer *peerConnection // Peer that we're requesting from
  39. delivered time.Time // Time when the packet was delivered (independent when we process it)
  40. response [][]byte // Response data of the peer (nil for timeouts)
  41. dropped bool // Flag whether the peer dropped off early
  42. }
  43. // timedOut returns if this request timed out.
  44. func (req *stateReq) timedOut() bool {
  45. return req.response == nil
  46. }
  47. // stateSyncStats is a collection of progress stats to report during a state trie
  48. // sync to RPC requests as well as to display in user logs.
  49. type stateSyncStats struct {
  50. processed uint64 // Number of state entries processed
  51. duplicate uint64 // Number of state entries downloaded twice
  52. unexpected uint64 // Number of non-requested state entries received
  53. pending uint64 // Number of still pending state entries
  54. }
  55. // syncState starts downloading state with the given root hash.
  56. func (d *Downloader) syncState(root common.Hash) *stateSync {
  57. // Create the state sync
  58. s := newStateSync(d, root)
  59. select {
  60. case d.stateSyncStart <- s:
  61. // If we tell the statesync to restart with a new root, we also need
  62. // to wait for it to actually also start -- when old requests have timed
  63. // out or been delivered
  64. <-s.started
  65. case <-d.quitCh:
  66. s.err = errCancelStateFetch
  67. close(s.done)
  68. }
  69. return s
  70. }
  71. // stateFetcher manages the active state sync and accepts requests
  72. // on its behalf.
  73. func (d *Downloader) stateFetcher() {
  74. for {
  75. select {
  76. case s := <-d.stateSyncStart:
  77. for next := s; next != nil; {
  78. next = d.runStateSync(next)
  79. }
  80. case <-d.stateCh:
  81. // Ignore state responses while no sync is running.
  82. case <-d.quitCh:
  83. return
  84. }
  85. }
  86. }
  87. // runStateSync runs a state synchronisation until it completes or another root
  88. // hash is requested to be switched over to.
  89. func (d *Downloader) runStateSync(s *stateSync) *stateSync {
  90. var (
  91. active = make(map[string]*stateReq) // Currently in-flight requests
  92. finished []*stateReq // Completed or failed requests
  93. timeout = make(chan *stateReq) // Timed out active requests
  94. )
  95. log.Trace("State sync starting", "root", s.root)
  96. defer func() {
  97. // Cancel active request timers on exit. Also set peers to idle so they're
  98. // available for the next sync.
  99. for _, req := range active {
  100. req.timer.Stop()
  101. req.peer.SetNodeDataIdle(int(req.nItems), time.Now())
  102. }
  103. }()
  104. go s.run()
  105. defer s.Cancel()
  106. // Listen for peer departure events to cancel assigned tasks
  107. peerDrop := make(chan *peerConnection, 1024)
  108. peerSub := s.d.peers.SubscribePeerDrops(peerDrop)
  109. defer peerSub.Unsubscribe()
  110. for {
  111. // Enable sending of the first buffered element if there is one.
  112. var (
  113. deliverReq *stateReq
  114. deliverReqCh chan *stateReq
  115. )
  116. if len(finished) > 0 {
  117. deliverReq = finished[0]
  118. deliverReqCh = s.deliver
  119. }
  120. select {
  121. // The stateSync lifecycle:
  122. case next := <-d.stateSyncStart:
  123. d.spindownStateSync(active, finished, timeout, peerDrop)
  124. return next
  125. case <-s.done:
  126. d.spindownStateSync(active, finished, timeout, peerDrop)
  127. return nil
  128. // Send the next finished request to the current sync:
  129. case deliverReqCh <- deliverReq:
  130. // Shift out the first request, but also set the emptied slot to nil for GC
  131. copy(finished, finished[1:])
  132. finished[len(finished)-1] = nil
  133. finished = finished[:len(finished)-1]
  134. // Handle incoming state packs:
  135. case pack := <-d.stateCh:
  136. // Discard any data not requested (or previously timed out)
  137. req := active[pack.PeerId()]
  138. if req == nil {
  139. log.Debug("Unrequested node data", "peer", pack.PeerId(), "len", pack.Items())
  140. continue
  141. }
  142. // Finalize the request and queue up for processing
  143. req.timer.Stop()
  144. req.response = pack.(*statePack).states
  145. req.delivered = time.Now()
  146. finished = append(finished, req)
  147. delete(active, pack.PeerId())
  148. // Handle dropped peer connections:
  149. case p := <-peerDrop:
  150. // Skip if no request is currently pending
  151. req := active[p.id]
  152. if req == nil {
  153. continue
  154. }
  155. // Finalize the request and queue up for processing
  156. req.timer.Stop()
  157. req.dropped = true
  158. req.delivered = time.Now()
  159. finished = append(finished, req)
  160. delete(active, p.id)
  161. // Handle timed-out requests:
  162. case req := <-timeout:
  163. // If the peer is already requesting something else, ignore the stale timeout.
  164. // This can happen when the timeout and the delivery happens simultaneously,
  165. // causing both pathways to trigger.
  166. if active[req.peer.id] != req {
  167. continue
  168. }
  169. req.delivered = time.Now()
  170. // Move the timed out data back into the download queue
  171. finished = append(finished, req)
  172. delete(active, req.peer.id)
  173. // Track outgoing state requests:
  174. case req := <-d.trackStateReq:
  175. // If an active request already exists for this peer, we have a problem. In
  176. // theory the trie node schedule must never assign two requests to the same
  177. // peer. In practice however, a peer might receive a request, disconnect and
  178. // immediately reconnect before the previous times out. In this case the first
  179. // request is never honored, alas we must not silently overwrite it, as that
  180. // causes valid requests to go missing and sync to get stuck.
  181. if old := active[req.peer.id]; old != nil {
  182. log.Warn("Busy peer assigned new state fetch", "peer", old.peer.id)
  183. // Move the previous request to the finished set
  184. old.timer.Stop()
  185. old.dropped = true
  186. old.delivered = time.Now()
  187. finished = append(finished, old)
  188. }
  189. // Start a timer to notify the sync loop if the peer stalled.
  190. req.timer = time.AfterFunc(req.timeout, func() {
  191. timeout <- req
  192. })
  193. active[req.peer.id] = req
  194. }
  195. }
  196. }
  197. // spindownStateSync 'drains' the outstanding requests; some will be delivered and other
  198. // will time out. This is to ensure that when the next stateSync starts working, all peers
  199. // are marked as idle and de facto _are_ idle.
  200. func (d *Downloader) spindownStateSync(active map[string]*stateReq, finished []*stateReq, timeout chan *stateReq, peerDrop chan *peerConnection) {
  201. log.Trace("State sync spinning down", "active", len(active), "finished", len(finished))
  202. for len(active) > 0 {
  203. var (
  204. req *stateReq
  205. reason string
  206. )
  207. select {
  208. // Handle (drop) incoming state packs:
  209. case pack := <-d.stateCh:
  210. req = active[pack.PeerId()]
  211. reason = "delivered"
  212. // Handle dropped peer connections:
  213. case p := <-peerDrop:
  214. req = active[p.id]
  215. reason = "peerdrop"
  216. // Handle timed-out requests:
  217. case req = <-timeout:
  218. reason = "timeout"
  219. }
  220. if req == nil {
  221. continue
  222. }
  223. req.peer.log.Trace("State peer marked idle (spindown)", "req.items", int(req.nItems), "reason", reason)
  224. req.timer.Stop()
  225. delete(active, req.peer.id)
  226. req.peer.SetNodeDataIdle(int(req.nItems), time.Now())
  227. }
  228. // The 'finished' set contains deliveries that we were going to pass to processing.
  229. // Those are now moot, but we still need to set those peers as idle, which would
  230. // otherwise have been done after processing
  231. for _, req := range finished {
  232. req.peer.SetNodeDataIdle(int(req.nItems), time.Now())
  233. }
  234. }
  235. // stateSync schedules requests for downloading a particular state trie defined
  236. // by a given state root.
  237. type stateSync struct {
  238. d *Downloader // Downloader instance to access and manage current peerset
  239. root common.Hash // State root currently being synced
  240. sched *trie.Sync // State trie sync scheduler defining the tasks
  241. keccak crypto.KeccakState // Keccak256 hasher to verify deliveries with
  242. trieTasks map[common.Hash]*trieTask // Set of trie node tasks currently queued for retrieval
  243. codeTasks map[common.Hash]*codeTask // Set of byte code tasks currently queued for retrieval
  244. numUncommitted int
  245. bytesUncommitted int
  246. started chan struct{} // Started is signalled once the sync loop starts
  247. deliver chan *stateReq // Delivery channel multiplexing peer responses
  248. cancel chan struct{} // Channel to signal a termination request
  249. cancelOnce sync.Once // Ensures cancel only ever gets called once
  250. done chan struct{} // Channel to signal termination completion
  251. err error // Any error hit during sync (set before completion)
  252. }
  253. // trieTask represents a single trie node download task, containing a set of
  254. // peers already attempted retrieval from to detect stalled syncs and abort.
  255. type trieTask struct {
  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, d.stateBloom, nil),
  271. keccak: sha3.NewLegacyKeccak256().(crypto.KeccakState),
  272. trieTasks: make(map[common.Hash]*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.requestRTT())
  394. req := &stateReq{peer: p, timeout: s.d.requestTTL()}
  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. nodes, paths, codes := s.sched.Missing(fill)
  414. for i, hash := range nodes {
  415. s.trieTasks[hash] = &trieTask{
  416. path: paths[i],
  417. attempts: make(map[string]struct{}),
  418. }
  419. }
  420. for _, hash := range codes {
  421. s.codeTasks[hash] = &codeTask{
  422. attempts: make(map[string]struct{}),
  423. }
  424. }
  425. }
  426. // Find tasks that haven't been tried with the request's peer. Prefer code
  427. // over trie nodes as those can be written to disk and forgotten about.
  428. nodes = make([]common.Hash, 0, n)
  429. paths = make([]trie.SyncPath, 0, n)
  430. codes = make([]common.Hash, 0, n)
  431. req.trieTasks = make(map[common.Hash]*trieTask, n)
  432. req.codeTasks = make(map[common.Hash]*codeTask, n)
  433. for hash, t := range s.codeTasks {
  434. // Stop when we've gathered enough requests
  435. if len(nodes)+len(codes) == n {
  436. break
  437. }
  438. // Skip any requests we've already tried from this peer
  439. if _, ok := t.attempts[req.peer.id]; ok {
  440. continue
  441. }
  442. // Assign the request to this peer
  443. t.attempts[req.peer.id] = struct{}{}
  444. codes = append(codes, hash)
  445. req.codeTasks[hash] = t
  446. delete(s.codeTasks, hash)
  447. }
  448. for hash, t := range s.trieTasks {
  449. // Stop when we've gathered enough requests
  450. if len(nodes)+len(codes) == n {
  451. break
  452. }
  453. // Skip any requests we've already tried from this peer
  454. if _, ok := t.attempts[req.peer.id]; ok {
  455. continue
  456. }
  457. // Assign the request to this peer
  458. t.attempts[req.peer.id] = struct{}{}
  459. nodes = append(nodes, hash)
  460. paths = append(paths, t.path)
  461. req.trieTasks[hash] = t
  462. delete(s.trieTasks, hash)
  463. }
  464. req.nItems = uint16(len(nodes) + len(codes))
  465. return nodes, paths, codes
  466. }
  467. // process iterates over a batch of delivered state data, injecting each item
  468. // into a running state sync, re-queuing any items that were requested but not
  469. // delivered. Returns whether the peer actually managed to deliver anything of
  470. // value, and any error that occurred.
  471. func (s *stateSync) process(req *stateReq) (int, error) {
  472. // Collect processing stats and update progress if valid data was received
  473. duplicate, unexpected, successful := 0, 0, 0
  474. defer func(start time.Time) {
  475. if duplicate > 0 || unexpected > 0 {
  476. s.updateStats(0, duplicate, unexpected, time.Since(start))
  477. }
  478. }(time.Now())
  479. // Iterate over all the delivered data and inject one-by-one into the trie
  480. for _, blob := range req.response {
  481. hash, err := s.processNodeData(blob)
  482. switch err {
  483. case nil:
  484. s.numUncommitted++
  485. s.bytesUncommitted += len(blob)
  486. successful++
  487. case trie.ErrNotRequested:
  488. unexpected++
  489. case trie.ErrAlreadyProcessed:
  490. duplicate++
  491. default:
  492. return successful, fmt.Errorf("invalid state node %s: %v", hash.TerminalString(), err)
  493. }
  494. // Delete from both queues (one delivery is enough for the syncer)
  495. delete(req.trieTasks, hash)
  496. delete(req.codeTasks, hash)
  497. }
  498. // Put unfulfilled tasks back into the retry queue
  499. npeers := s.d.peers.Len()
  500. for hash, task := range req.trieTasks {
  501. // If the node did deliver something, missing items may be due to a protocol
  502. // limit or a previous timeout + delayed delivery. Both cases should permit
  503. // the node to retry the missing items (to avoid single-peer stalls).
  504. if len(req.response) > 0 || req.timedOut() {
  505. delete(task.attempts, req.peer.id)
  506. }
  507. // If we've requested the node too many times already, it may be a malicious
  508. // sync where nobody has the right data. Abort.
  509. if len(task.attempts) >= npeers {
  510. return successful, fmt.Errorf("trie node %s failed with all peers (%d tries, %d peers)", hash.TerminalString(), len(task.attempts), npeers)
  511. }
  512. // Missing item, place into the retry queue.
  513. s.trieTasks[hash] = task
  514. }
  515. for hash, task := range req.codeTasks {
  516. // If the node did deliver something, missing items may be due to a protocol
  517. // limit or a previous timeout + delayed delivery. Both cases should permit
  518. // the node to retry the missing items (to avoid single-peer stalls).
  519. if len(req.response) > 0 || req.timedOut() {
  520. delete(task.attempts, req.peer.id)
  521. }
  522. // If we've requested the node too many times already, it may be a malicious
  523. // sync where nobody has the right data. Abort.
  524. if len(task.attempts) >= npeers {
  525. return successful, fmt.Errorf("byte code %s failed with all peers (%d tries, %d peers)", hash.TerminalString(), len(task.attempts), npeers)
  526. }
  527. // Missing item, place into the retry queue.
  528. s.codeTasks[hash] = task
  529. }
  530. return successful, nil
  531. }
  532. // processNodeData tries to inject a trie node data blob delivered from a remote
  533. // peer into the state trie, returning whether anything useful was written or any
  534. // error occurred.
  535. func (s *stateSync) processNodeData(blob []byte) (common.Hash, error) {
  536. res := trie.SyncResult{Data: blob}
  537. s.keccak.Reset()
  538. s.keccak.Write(blob)
  539. s.keccak.Read(res.Hash[:])
  540. err := s.sched.Process(res)
  541. return res.Hash, err
  542. }
  543. // updateStats bumps the various state sync progress counters and displays a log
  544. // message for the user to see.
  545. func (s *stateSync) updateStats(written, duplicate, unexpected int, duration time.Duration) {
  546. s.d.syncStatsLock.Lock()
  547. defer s.d.syncStatsLock.Unlock()
  548. s.d.syncStatsState.pending = uint64(s.sched.Pending())
  549. s.d.syncStatsState.processed += uint64(written)
  550. s.d.syncStatsState.duplicate += uint64(duplicate)
  551. s.d.syncStatsState.unexpected += uint64(unexpected)
  552. if written > 0 || duplicate > 0 || unexpected > 0 {
  553. 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)
  554. }
  555. if written > 0 {
  556. rawdb.WriteFastTrieProgress(s.d.stateDB, s.d.syncStatsState.processed)
  557. }
  558. }