generate.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. // Copyright 2019 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 snapshot
  17. import (
  18. "bytes"
  19. "encoding/binary"
  20. "errors"
  21. "fmt"
  22. "math/big"
  23. "time"
  24. "github.com/VictoriaMetrics/fastcache"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/common/hexutil"
  27. "github.com/ethereum/go-ethereum/common/math"
  28. "github.com/ethereum/go-ethereum/core/rawdb"
  29. "github.com/ethereum/go-ethereum/crypto"
  30. "github.com/ethereum/go-ethereum/ethdb"
  31. "github.com/ethereum/go-ethereum/ethdb/memorydb"
  32. "github.com/ethereum/go-ethereum/log"
  33. "github.com/ethereum/go-ethereum/metrics"
  34. "github.com/ethereum/go-ethereum/rlp"
  35. "github.com/ethereum/go-ethereum/trie"
  36. )
  37. var (
  38. // emptyRoot is the known root hash of an empty trie.
  39. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  40. // emptyCode is the known hash of the empty EVM bytecode.
  41. emptyCode = crypto.Keccak256Hash(nil)
  42. // accountCheckRange is the upper limit of the number of accounts involved in
  43. // each range check. This is a value estimated based on experience. If this
  44. // value is too large, the failure rate of range prove will increase. Otherwise
  45. // the the value is too small, the efficiency of the state recovery will decrease.
  46. accountCheckRange = 128
  47. // storageCheckRange is the upper limit of the number of storage slots involved
  48. // in each range check. This is a value estimated based on experience. If this
  49. // value is too large, the failure rate of range prove will increase. Otherwise
  50. // the the value is too small, the efficiency of the state recovery will decrease.
  51. storageCheckRange = 1024
  52. // errMissingTrie is returned if the target trie is missing while the generation
  53. // is running. In this case the generation is aborted and wait the new signal.
  54. errMissingTrie = errors.New("missing trie")
  55. )
  56. // Metrics in generation
  57. var (
  58. snapGeneratedAccountMeter = metrics.NewRegisteredMeter("state/snapshot/generation/account/generated", nil)
  59. snapRecoveredAccountMeter = metrics.NewRegisteredMeter("state/snapshot/generation/account/recovered", nil)
  60. snapWipedAccountMeter = metrics.NewRegisteredMeter("state/snapshot/generation/account/wiped", nil)
  61. snapMissallAccountMeter = metrics.NewRegisteredMeter("state/snapshot/generation/account/missall", nil)
  62. snapGeneratedStorageMeter = metrics.NewRegisteredMeter("state/snapshot/generation/storage/generated", nil)
  63. snapRecoveredStorageMeter = metrics.NewRegisteredMeter("state/snapshot/generation/storage/recovered", nil)
  64. snapWipedStorageMeter = metrics.NewRegisteredMeter("state/snapshot/generation/storage/wiped", nil)
  65. snapMissallStorageMeter = metrics.NewRegisteredMeter("state/snapshot/generation/storage/missall", nil)
  66. snapSuccessfulRangeProofMeter = metrics.NewRegisteredMeter("state/snapshot/generation/proof/success", nil)
  67. snapFailedRangeProofMeter = metrics.NewRegisteredMeter("state/snapshot/generation/proof/failure", nil)
  68. // snapAccountProveCounter measures time spent on the account proving
  69. snapAccountProveCounter = metrics.NewRegisteredCounter("state/snapshot/generation/duration/account/prove", nil)
  70. // snapAccountTrieReadCounter measures time spent on the account trie iteration
  71. snapAccountTrieReadCounter = metrics.NewRegisteredCounter("state/snapshot/generation/duration/account/trieread", nil)
  72. // snapAccountSnapReadCounter measues time spent on the snapshot account iteration
  73. snapAccountSnapReadCounter = metrics.NewRegisteredCounter("state/snapshot/generation/duration/account/snapread", nil)
  74. // snapAccountWriteCounter measures time spent on writing/updating/deleting accounts
  75. snapAccountWriteCounter = metrics.NewRegisteredCounter("state/snapshot/generation/duration/account/write", nil)
  76. // snapStorageProveCounter measures time spent on storage proving
  77. snapStorageProveCounter = metrics.NewRegisteredCounter("state/snapshot/generation/duration/storage/prove", nil)
  78. // snapStorageTrieReadCounter measures time spent on the storage trie iteration
  79. snapStorageTrieReadCounter = metrics.NewRegisteredCounter("state/snapshot/generation/duration/storage/trieread", nil)
  80. // snapStorageSnapReadCounter measures time spent on the snapshot storage iteration
  81. snapStorageSnapReadCounter = metrics.NewRegisteredCounter("state/snapshot/generation/duration/storage/snapread", nil)
  82. // snapStorageWriteCounter measures time spent on writing/updating/deleting storages
  83. snapStorageWriteCounter = metrics.NewRegisteredCounter("state/snapshot/generation/duration/storage/write", nil)
  84. )
  85. // generatorStats is a collection of statistics gathered by the snapshot generator
  86. // for logging purposes.
  87. type generatorStats struct {
  88. origin uint64 // Origin prefix where generation started
  89. start time.Time // Timestamp when generation started
  90. accounts uint64 // Number of accounts indexed(generated or recovered)
  91. slots uint64 // Number of storage slots indexed(generated or recovered)
  92. storage common.StorageSize // Total account and storage slot size(generation or recovery)
  93. }
  94. // Log creates an contextual log with the given message and the context pulled
  95. // from the internally maintained statistics.
  96. func (gs *generatorStats) Log(msg string, root common.Hash, marker []byte) {
  97. var ctx []interface{}
  98. if root != (common.Hash{}) {
  99. ctx = append(ctx, []interface{}{"root", root}...)
  100. }
  101. // Figure out whether we're after or within an account
  102. switch len(marker) {
  103. case common.HashLength:
  104. ctx = append(ctx, []interface{}{"at", common.BytesToHash(marker)}...)
  105. case 2 * common.HashLength:
  106. ctx = append(ctx, []interface{}{
  107. "in", common.BytesToHash(marker[:common.HashLength]),
  108. "at", common.BytesToHash(marker[common.HashLength:]),
  109. }...)
  110. }
  111. // Add the usual measurements
  112. ctx = append(ctx, []interface{}{
  113. "accounts", gs.accounts,
  114. "slots", gs.slots,
  115. "storage", gs.storage,
  116. "elapsed", common.PrettyDuration(time.Since(gs.start)),
  117. }...)
  118. // Calculate the estimated indexing time based on current stats
  119. if len(marker) > 0 {
  120. if done := binary.BigEndian.Uint64(marker[:8]) - gs.origin; done > 0 {
  121. left := math.MaxUint64 - binary.BigEndian.Uint64(marker[:8])
  122. speed := done/uint64(time.Since(gs.start)/time.Millisecond+1) + 1 // +1s to avoid division by zero
  123. ctx = append(ctx, []interface{}{
  124. "eta", common.PrettyDuration(time.Duration(left/speed) * time.Millisecond),
  125. }...)
  126. }
  127. }
  128. log.Info(msg, ctx...)
  129. }
  130. // generateSnapshot regenerates a brand new snapshot based on an existing state
  131. // database and head block asynchronously. The snapshot is returned immediately
  132. // and generation is continued in the background until done.
  133. func generateSnapshot(diskdb ethdb.KeyValueStore, triedb *trie.Database, cache int, root common.Hash) *diskLayer {
  134. // Create a new disk layer with an initialized state marker at zero
  135. var (
  136. stats = &generatorStats{start: time.Now()}
  137. batch = diskdb.NewBatch()
  138. genMarker = []byte{} // Initialized but empty!
  139. )
  140. rawdb.WriteSnapshotRoot(batch, root)
  141. journalProgress(batch, genMarker, stats)
  142. if err := batch.Write(); err != nil {
  143. log.Crit("Failed to write initialized state marker", "err", err)
  144. }
  145. base := &diskLayer{
  146. diskdb: diskdb,
  147. triedb: triedb,
  148. root: root,
  149. cache: fastcache.New(cache * 1024 * 1024),
  150. genMarker: genMarker,
  151. genPending: make(chan struct{}),
  152. genAbort: make(chan chan *generatorStats),
  153. }
  154. go base.generate(stats)
  155. log.Debug("Start snapshot generation", "root", root)
  156. return base
  157. }
  158. // journalProgress persists the generator stats into the database to resume later.
  159. func journalProgress(db ethdb.KeyValueWriter, marker []byte, stats *generatorStats) {
  160. // Write out the generator marker. Note it's a standalone disk layer generator
  161. // which is not mixed with journal. It's ok if the generator is persisted while
  162. // journal is not.
  163. entry := journalGenerator{
  164. Done: marker == nil,
  165. Marker: marker,
  166. }
  167. if stats != nil {
  168. entry.Accounts = stats.accounts
  169. entry.Slots = stats.slots
  170. entry.Storage = uint64(stats.storage)
  171. }
  172. blob, err := rlp.EncodeToBytes(entry)
  173. if err != nil {
  174. panic(err) // Cannot happen, here to catch dev errors
  175. }
  176. var logstr string
  177. switch {
  178. case marker == nil:
  179. logstr = "done"
  180. case bytes.Equal(marker, []byte{}):
  181. logstr = "empty"
  182. case len(marker) == common.HashLength:
  183. logstr = fmt.Sprintf("%#x", marker)
  184. default:
  185. logstr = fmt.Sprintf("%#x:%#x", marker[:common.HashLength], marker[common.HashLength:])
  186. }
  187. log.Debug("Journalled generator progress", "progress", logstr)
  188. rawdb.WriteSnapshotGenerator(db, blob)
  189. }
  190. // proofResult contains the output of range proving which can be used
  191. // for further processing regardless if it is successful or not.
  192. type proofResult struct {
  193. keys [][]byte // The key set of all elements being iterated, even proving is failed
  194. vals [][]byte // The val set of all elements being iterated, even proving is failed
  195. diskMore bool // Set when the database has extra snapshot states since last iteration
  196. trieMore bool // Set when the trie has extra snapshot states(only meaningful for successful proving)
  197. proofErr error // Indicator whether the given state range is valid or not
  198. tr *trie.Trie // The trie, in case the trie was resolved by the prover (may be nil)
  199. }
  200. // valid returns the indicator that range proof is successful or not.
  201. func (result *proofResult) valid() bool {
  202. return result.proofErr == nil
  203. }
  204. // last returns the last verified element key regardless of whether the range proof is
  205. // successful or not. Nil is returned if nothing involved in the proving.
  206. func (result *proofResult) last() []byte {
  207. var last []byte
  208. if len(result.keys) > 0 {
  209. last = result.keys[len(result.keys)-1]
  210. }
  211. return last
  212. }
  213. // forEach iterates all the visited elements and applies the given callback on them.
  214. // The iteration is aborted if the callback returns non-nil error.
  215. func (result *proofResult) forEach(callback func(key []byte, val []byte) error) error {
  216. for i := 0; i < len(result.keys); i++ {
  217. key, val := result.keys[i], result.vals[i]
  218. if err := callback(key, val); err != nil {
  219. return err
  220. }
  221. }
  222. return nil
  223. }
  224. // proveRange proves the snapshot segment with particular prefix is "valid".
  225. // The iteration start point will be assigned if the iterator is restored from
  226. // the last interruption. Max will be assigned in order to limit the maximum
  227. // amount of data involved in each iteration.
  228. //
  229. // The proof result will be returned if the range proving is finished, otherwise
  230. // the error will be returned to abort the entire procedure.
  231. func (dl *diskLayer) proveRange(stats *generatorStats, root common.Hash, prefix []byte, kind string, origin []byte, max int, valueConvertFn func([]byte) ([]byte, error)) (*proofResult, error) {
  232. var (
  233. keys [][]byte
  234. vals [][]byte
  235. proof = rawdb.NewMemoryDatabase()
  236. diskMore = false
  237. )
  238. iter := dl.diskdb.NewIterator(prefix, origin)
  239. defer iter.Release()
  240. var start = time.Now()
  241. for iter.Next() {
  242. key := iter.Key()
  243. if len(key) != len(prefix)+common.HashLength {
  244. continue
  245. }
  246. if len(keys) == max {
  247. // Break if we've reached the max size, and signal that we're not
  248. // done yet.
  249. diskMore = true
  250. break
  251. }
  252. keys = append(keys, common.CopyBytes(key[len(prefix):]))
  253. if valueConvertFn == nil {
  254. vals = append(vals, common.CopyBytes(iter.Value()))
  255. } else {
  256. val, err := valueConvertFn(iter.Value())
  257. if err != nil {
  258. // Special case, the state data is corrupted (invalid slim-format account),
  259. // don't abort the entire procedure directly. Instead, let the fallback
  260. // generation to heal the invalid data.
  261. //
  262. // Here append the original value to ensure that the number of key and
  263. // value are the same.
  264. vals = append(vals, common.CopyBytes(iter.Value()))
  265. log.Error("Failed to convert account state data", "err", err)
  266. } else {
  267. vals = append(vals, val)
  268. }
  269. }
  270. }
  271. // Update metrics for database iteration and merkle proving
  272. if kind == "storage" {
  273. snapStorageSnapReadCounter.Inc(time.Since(start).Nanoseconds())
  274. } else {
  275. snapAccountSnapReadCounter.Inc(time.Since(start).Nanoseconds())
  276. }
  277. defer func(start time.Time) {
  278. if kind == "storage" {
  279. snapStorageProveCounter.Inc(time.Since(start).Nanoseconds())
  280. } else {
  281. snapAccountProveCounter.Inc(time.Since(start).Nanoseconds())
  282. }
  283. }(time.Now())
  284. // The snap state is exhausted, pass the entire key/val set for verification
  285. if origin == nil && !diskMore {
  286. stackTr := trie.NewStackTrie(nil)
  287. for i, key := range keys {
  288. stackTr.TryUpdate(key, vals[i])
  289. }
  290. if gotRoot := stackTr.Hash(); gotRoot != root {
  291. return &proofResult{
  292. keys: keys,
  293. vals: vals,
  294. proofErr: fmt.Errorf("wrong root: have %#x want %#x", gotRoot, root),
  295. }, nil
  296. }
  297. return &proofResult{keys: keys, vals: vals}, nil
  298. }
  299. // Snap state is chunked, generate edge proofs for verification.
  300. tr, err := trie.New(root, dl.triedb)
  301. if err != nil {
  302. stats.Log("Trie missing, state snapshotting paused", dl.root, dl.genMarker)
  303. return nil, errMissingTrie
  304. }
  305. // Firstly find out the key of last iterated element.
  306. var last []byte
  307. if len(keys) > 0 {
  308. last = keys[len(keys)-1]
  309. }
  310. // Generate the Merkle proofs for the first and last element
  311. if origin == nil {
  312. origin = common.Hash{}.Bytes()
  313. }
  314. if err := tr.Prove(origin, 0, proof); err != nil {
  315. log.Debug("Failed to prove range", "kind", kind, "origin", origin, "err", err)
  316. return &proofResult{
  317. keys: keys,
  318. vals: vals,
  319. diskMore: diskMore,
  320. proofErr: err,
  321. tr: tr,
  322. }, nil
  323. }
  324. if last != nil {
  325. if err := tr.Prove(last, 0, proof); err != nil {
  326. log.Debug("Failed to prove range", "kind", kind, "last", last, "err", err)
  327. return &proofResult{
  328. keys: keys,
  329. vals: vals,
  330. diskMore: diskMore,
  331. proofErr: err,
  332. tr: tr,
  333. }, nil
  334. }
  335. }
  336. // Verify the snapshot segment with range prover, ensure that all flat states
  337. // in this range correspond to merkle trie.
  338. cont, err := trie.VerifyRangeProof(root, origin, last, keys, vals, proof)
  339. return &proofResult{
  340. keys: keys,
  341. vals: vals,
  342. diskMore: diskMore,
  343. trieMore: cont,
  344. proofErr: err,
  345. tr: tr},
  346. nil
  347. }
  348. // onStateCallback is a function that is called by generateRange, when processing a range of
  349. // accounts or storage slots. For each element, the callback is invoked.
  350. // If 'delete' is true, then this element (and potential slots) needs to be deleted from the snapshot.
  351. // If 'write' is true, then this element needs to be updated with the 'val'.
  352. // If 'write' is false, then this element is already correct, and needs no update. However,
  353. // for accounts, the storage trie of the account needs to be checked.
  354. // The 'val' is the canonical encoding of the value (not the slim format for accounts)
  355. type onStateCallback func(key []byte, val []byte, write bool, delete bool) error
  356. // generateRange generates the state segment with particular prefix. Generation can
  357. // either verify the correctness of existing state through rangeproof and skip
  358. // generation, or iterate trie to regenerate state on demand.
  359. func (dl *diskLayer) generateRange(root common.Hash, prefix []byte, kind string, origin []byte, max int, stats *generatorStats, onState onStateCallback, valueConvertFn func([]byte) ([]byte, error)) (bool, []byte, error) {
  360. // Use range prover to check the validity of the flat state in the range
  361. result, err := dl.proveRange(stats, root, prefix, kind, origin, max, valueConvertFn)
  362. if err != nil {
  363. return false, nil, err
  364. }
  365. last := result.last()
  366. // Construct contextual logger
  367. logCtx := []interface{}{"kind", kind, "prefix", hexutil.Encode(prefix)}
  368. if len(origin) > 0 {
  369. logCtx = append(logCtx, "origin", hexutil.Encode(origin))
  370. }
  371. logger := log.New(logCtx...)
  372. // The range prover says the range is correct, skip trie iteration
  373. if result.valid() {
  374. snapSuccessfulRangeProofMeter.Mark(1)
  375. logger.Trace("Proved state range", "last", hexutil.Encode(last))
  376. // The verification is passed, process each state with the given
  377. // callback function. If this state represents a contract, the
  378. // corresponding storage check will be performed in the callback
  379. if err := result.forEach(func(key []byte, val []byte) error { return onState(key, val, false, false) }); err != nil {
  380. return false, nil, err
  381. }
  382. // Only abort the iteration when both database and trie are exhausted
  383. return !result.diskMore && !result.trieMore, last, nil
  384. }
  385. logger.Trace("Detected outdated state range", "last", hexutil.Encode(last), "err", result.proofErr)
  386. snapFailedRangeProofMeter.Mark(1)
  387. // Special case, the entire trie is missing. In the original trie scheme,
  388. // all the duplicated subtries will be filter out(only one copy of data
  389. // will be stored). While in the snapshot model, all the storage tries
  390. // belong to different contracts will be kept even they are duplicated.
  391. // Track it to a certain extent remove the noise data used for statistics.
  392. if origin == nil && last == nil {
  393. meter := snapMissallAccountMeter
  394. if kind == "storage" {
  395. meter = snapMissallStorageMeter
  396. }
  397. meter.Mark(1)
  398. }
  399. // We use the snap data to build up a cache which can be used by the
  400. // main account trie as a primary lookup when resolving hashes
  401. var snapNodeCache ethdb.KeyValueStore
  402. if len(result.keys) > 0 {
  403. snapNodeCache = memorydb.New()
  404. snapTrieDb := trie.NewDatabase(snapNodeCache)
  405. snapTrie, _ := trie.New(common.Hash{}, snapTrieDb)
  406. for i, key := range result.keys {
  407. snapTrie.Update(key, result.vals[i])
  408. }
  409. root, _ := snapTrie.Commit(nil)
  410. snapTrieDb.Commit(root, false, nil)
  411. }
  412. tr := result.tr
  413. if tr == nil {
  414. tr, err = trie.New(root, dl.triedb)
  415. if err != nil {
  416. stats.Log("Trie missing, state snapshotting paused", dl.root, dl.genMarker)
  417. return false, nil, errMissingTrie
  418. }
  419. }
  420. var (
  421. trieMore bool
  422. nodeIt = tr.NodeIterator(origin)
  423. iter = trie.NewIterator(nodeIt)
  424. kvkeys, kvvals = result.keys, result.vals
  425. // counters
  426. count = 0 // number of states delivered by iterator
  427. created = 0 // states created from the trie
  428. updated = 0 // states updated from the trie
  429. deleted = 0 // states not in trie, but were in snapshot
  430. untouched = 0 // states already correct
  431. // timers
  432. start = time.Now()
  433. internal time.Duration
  434. )
  435. nodeIt.AddResolver(snapNodeCache)
  436. for iter.Next() {
  437. if last != nil && bytes.Compare(iter.Key, last) > 0 {
  438. trieMore = true
  439. break
  440. }
  441. count++
  442. write := true
  443. created++
  444. for len(kvkeys) > 0 {
  445. if cmp := bytes.Compare(kvkeys[0], iter.Key); cmp < 0 {
  446. // delete the key
  447. istart := time.Now()
  448. if err := onState(kvkeys[0], nil, false, true); err != nil {
  449. return false, nil, err
  450. }
  451. kvkeys = kvkeys[1:]
  452. kvvals = kvvals[1:]
  453. deleted++
  454. internal += time.Since(istart)
  455. continue
  456. } else if cmp == 0 {
  457. // the snapshot key can be overwritten
  458. created--
  459. if write = !bytes.Equal(kvvals[0], iter.Value); write {
  460. updated++
  461. } else {
  462. untouched++
  463. }
  464. kvkeys = kvkeys[1:]
  465. kvvals = kvvals[1:]
  466. }
  467. break
  468. }
  469. istart := time.Now()
  470. if err := onState(iter.Key, iter.Value, write, false); err != nil {
  471. return false, nil, err
  472. }
  473. internal += time.Since(istart)
  474. }
  475. if iter.Err != nil {
  476. return false, nil, iter.Err
  477. }
  478. // Delete all stale snapshot states remaining
  479. istart := time.Now()
  480. for _, key := range kvkeys {
  481. if err := onState(key, nil, false, true); err != nil {
  482. return false, nil, err
  483. }
  484. deleted += 1
  485. }
  486. internal += time.Since(istart)
  487. // Update metrics for counting trie iteration
  488. if kind == "storage" {
  489. snapStorageTrieReadCounter.Inc((time.Since(start) - internal).Nanoseconds())
  490. } else {
  491. snapAccountTrieReadCounter.Inc((time.Since(start) - internal).Nanoseconds())
  492. }
  493. logger.Debug("Regenerated state range", "root", root, "last", hexutil.Encode(last),
  494. "count", count, "created", created, "updated", updated, "untouched", untouched, "deleted", deleted)
  495. // If there are either more trie items, or there are more snap items
  496. // (in the next segment), then we need to keep working
  497. return !trieMore && !result.diskMore, last, nil
  498. }
  499. // generate is a background thread that iterates over the state and storage tries,
  500. // constructing the state snapshot. All the arguments are purely for statistics
  501. // gathering and logging, since the method surfs the blocks as they arrive, often
  502. // being restarted.
  503. func (dl *diskLayer) generate(stats *generatorStats) {
  504. var (
  505. accMarker []byte
  506. accountRange = accountCheckRange
  507. )
  508. if len(dl.genMarker) > 0 { // []byte{} is the start, use nil for that
  509. // Always reset the initial account range as 1
  510. // whenever recover from the interruption.
  511. accMarker, accountRange = dl.genMarker[:common.HashLength], 1
  512. }
  513. var (
  514. batch = dl.diskdb.NewBatch()
  515. logged = time.Now()
  516. accOrigin = common.CopyBytes(accMarker)
  517. abort chan *generatorStats
  518. )
  519. stats.Log("Resuming state snapshot generation", dl.root, dl.genMarker)
  520. checkAndFlush := func(currentLocation []byte) error {
  521. select {
  522. case abort = <-dl.genAbort:
  523. default:
  524. }
  525. if batch.ValueSize() > ethdb.IdealBatchSize || abort != nil {
  526. // Flush out the batch anyway no matter it's empty or not.
  527. // It's possible that all the states are recovered and the
  528. // generation indeed makes progress.
  529. journalProgress(batch, currentLocation, stats)
  530. if err := batch.Write(); err != nil {
  531. return err
  532. }
  533. batch.Reset()
  534. dl.lock.Lock()
  535. dl.genMarker = currentLocation
  536. dl.lock.Unlock()
  537. if abort != nil {
  538. stats.Log("Aborting state snapshot generation", dl.root, currentLocation)
  539. return errors.New("aborted")
  540. }
  541. }
  542. if time.Since(logged) > 8*time.Second {
  543. stats.Log("Generating state snapshot", dl.root, currentLocation)
  544. logged = time.Now()
  545. }
  546. return nil
  547. }
  548. onAccount := func(key []byte, val []byte, write bool, delete bool) error {
  549. var (
  550. start = time.Now()
  551. accountHash = common.BytesToHash(key)
  552. )
  553. if delete {
  554. rawdb.DeleteAccountSnapshot(batch, accountHash)
  555. snapWipedAccountMeter.Mark(1)
  556. // Ensure that any previous snapshot storage values are cleared
  557. prefix := append(rawdb.SnapshotStoragePrefix, accountHash.Bytes()...)
  558. keyLen := len(rawdb.SnapshotStoragePrefix) + 2*common.HashLength
  559. if err := wipeKeyRange(dl.diskdb, "storage", prefix, nil, nil, keyLen, snapWipedStorageMeter, false); err != nil {
  560. return err
  561. }
  562. snapAccountWriteCounter.Inc(time.Since(start).Nanoseconds())
  563. return nil
  564. }
  565. // Retrieve the current account and flatten it into the internal format
  566. var acc struct {
  567. Nonce uint64
  568. Balance *big.Int
  569. Root common.Hash
  570. CodeHash []byte
  571. }
  572. if err := rlp.DecodeBytes(val, &acc); err != nil {
  573. log.Crit("Invalid account encountered during snapshot creation", "err", err)
  574. }
  575. // If the account is not yet in-progress, write it out
  576. if accMarker == nil || !bytes.Equal(accountHash[:], accMarker) {
  577. dataLen := len(val) // Approximate size, saves us a round of RLP-encoding
  578. if !write {
  579. if bytes.Equal(acc.CodeHash, emptyCode[:]) {
  580. dataLen -= 32
  581. }
  582. if acc.Root == emptyRoot {
  583. dataLen -= 32
  584. }
  585. snapRecoveredAccountMeter.Mark(1)
  586. } else {
  587. data := SlimAccountRLP(acc.Nonce, acc.Balance, acc.Root, acc.CodeHash)
  588. dataLen = len(data)
  589. rawdb.WriteAccountSnapshot(batch, accountHash, data)
  590. snapGeneratedAccountMeter.Mark(1)
  591. }
  592. stats.storage += common.StorageSize(1 + common.HashLength + dataLen)
  593. stats.accounts++
  594. }
  595. // If we've exceeded our batch allowance or termination was requested, flush to disk
  596. if err := checkAndFlush(accountHash[:]); err != nil {
  597. return err
  598. }
  599. // If the iterated account is the contract, create a further loop to
  600. // verify or regenerate the contract storage.
  601. if acc.Root == emptyRoot {
  602. // If the root is empty, we still need to ensure that any previous snapshot
  603. // storage values are cleared
  604. // TODO: investigate if this can be avoided, this will be very costly since it
  605. // affects every single EOA account
  606. // - Perhaps we can avoid if where codeHash is emptyCode
  607. prefix := append(rawdb.SnapshotStoragePrefix, accountHash.Bytes()...)
  608. keyLen := len(rawdb.SnapshotStoragePrefix) + 2*common.HashLength
  609. if err := wipeKeyRange(dl.diskdb, "storage", prefix, nil, nil, keyLen, snapWipedStorageMeter, false); err != nil {
  610. return err
  611. }
  612. snapAccountWriteCounter.Inc(time.Since(start).Nanoseconds())
  613. } else {
  614. snapAccountWriteCounter.Inc(time.Since(start).Nanoseconds())
  615. var storeMarker []byte
  616. if accMarker != nil && bytes.Equal(accountHash[:], accMarker) && len(dl.genMarker) > common.HashLength {
  617. storeMarker = dl.genMarker[common.HashLength:]
  618. }
  619. onStorage := func(key []byte, val []byte, write bool, delete bool) error {
  620. defer func(start time.Time) {
  621. snapStorageWriteCounter.Inc(time.Since(start).Nanoseconds())
  622. }(time.Now())
  623. if delete {
  624. rawdb.DeleteStorageSnapshot(batch, accountHash, common.BytesToHash(key))
  625. snapWipedStorageMeter.Mark(1)
  626. return nil
  627. }
  628. if write {
  629. rawdb.WriteStorageSnapshot(batch, accountHash, common.BytesToHash(key), val)
  630. snapGeneratedStorageMeter.Mark(1)
  631. } else {
  632. snapRecoveredStorageMeter.Mark(1)
  633. }
  634. stats.storage += common.StorageSize(1 + 2*common.HashLength + len(val))
  635. stats.slots++
  636. // If we've exceeded our batch allowance or termination was requested, flush to disk
  637. if err := checkAndFlush(append(accountHash[:], key...)); err != nil {
  638. return err
  639. }
  640. return nil
  641. }
  642. var storeOrigin = common.CopyBytes(storeMarker)
  643. for {
  644. exhausted, last, err := dl.generateRange(acc.Root, append(rawdb.SnapshotStoragePrefix, accountHash.Bytes()...), "storage", storeOrigin, storageCheckRange, stats, onStorage, nil)
  645. if err != nil {
  646. return err
  647. }
  648. if exhausted {
  649. break
  650. }
  651. if storeOrigin = increaseKey(last); storeOrigin == nil {
  652. break // special case, the last is 0xffffffff...fff
  653. }
  654. }
  655. }
  656. // Some account processed, unmark the marker
  657. accMarker = nil
  658. return nil
  659. }
  660. // Global loop for regerating the entire state trie + all layered storage tries.
  661. for {
  662. exhausted, last, err := dl.generateRange(dl.root, rawdb.SnapshotAccountPrefix, "account", accOrigin, accountRange, stats, onAccount, FullAccountRLP)
  663. // The procedure it aborted, either by external signal or internal error
  664. if err != nil {
  665. if abort == nil { // aborted by internal error, wait the signal
  666. abort = <-dl.genAbort
  667. }
  668. abort <- stats
  669. return
  670. }
  671. // Abort the procedure if the entire snapshot is generated
  672. if exhausted {
  673. break
  674. }
  675. if accOrigin = increaseKey(last); accOrigin == nil {
  676. break // special case, the last is 0xffffffff...fff
  677. }
  678. accountRange = accountCheckRange
  679. }
  680. // Snapshot fully generated, set the marker to nil.
  681. // Note even there is nothing to commit, persist the
  682. // generator anyway to mark the snapshot is complete.
  683. journalProgress(batch, nil, stats)
  684. if err := batch.Write(); err != nil {
  685. log.Error("Failed to flush batch", "err", err)
  686. abort = <-dl.genAbort
  687. abort <- stats
  688. return
  689. }
  690. batch.Reset()
  691. log.Info("Generated state snapshot", "accounts", stats.accounts, "slots", stats.slots,
  692. "storage", stats.storage, "elapsed", common.PrettyDuration(time.Since(stats.start)))
  693. dl.lock.Lock()
  694. dl.genMarker = nil
  695. close(dl.genPending)
  696. dl.lock.Unlock()
  697. // Someone will be looking for us, wait it out
  698. abort = <-dl.genAbort
  699. abort <- nil
  700. }
  701. // increaseKey increase the input key by one bit. Return nil if the entire
  702. // addition operation overflows,
  703. func increaseKey(key []byte) []byte {
  704. for i := len(key) - 1; i >= 0; i-- {
  705. key[i]++
  706. if key[i] != 0x0 {
  707. return key
  708. }
  709. }
  710. return nil
  711. }