generate.go 28 KB

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