generate.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. "math/big"
  21. "time"
  22. "github.com/VictoriaMetrics/fastcache"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/common/math"
  25. "github.com/ethereum/go-ethereum/core/rawdb"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/ethereum/go-ethereum/ethdb"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/ethereum/go-ethereum/rlp"
  30. "github.com/ethereum/go-ethereum/trie"
  31. )
  32. var (
  33. // emptyRoot is the known root hash of an empty trie.
  34. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  35. // emptyCode is the known hash of the empty EVM bytecode.
  36. emptyCode = crypto.Keccak256Hash(nil)
  37. )
  38. // generatorStats is a collection of statistics gathered by the snapshot generator
  39. // for logging purposes.
  40. type generatorStats struct {
  41. wiping chan struct{} // Notification channel if wiping is in progress
  42. origin uint64 // Origin prefix where generation started
  43. start time.Time // Timestamp when generation started
  44. accounts uint64 // Number of accounts indexed
  45. slots uint64 // Number of storage slots indexed
  46. storage common.StorageSize // Account and storage slot size
  47. }
  48. // Log creates an contextual log with the given message and the context pulled
  49. // from the internally maintained statistics.
  50. func (gs *generatorStats) Log(msg string, marker []byte) {
  51. var ctx []interface{}
  52. // Figure out whether we're after or within an account
  53. switch len(marker) {
  54. case common.HashLength:
  55. ctx = append(ctx, []interface{}{"at", common.BytesToHash(marker)}...)
  56. case 2 * common.HashLength:
  57. ctx = append(ctx, []interface{}{
  58. "in", common.BytesToHash(marker[:common.HashLength]),
  59. "at", common.BytesToHash(marker[common.HashLength:]),
  60. }...)
  61. }
  62. // Add the usual measurements
  63. ctx = append(ctx, []interface{}{
  64. "accounts", gs.accounts,
  65. "slots", gs.slots,
  66. "storage", gs.storage,
  67. "elapsed", common.PrettyDuration(time.Since(gs.start)),
  68. }...)
  69. // Calculate the estimated indexing time based on current stats
  70. if len(marker) > 0 {
  71. if done := binary.BigEndian.Uint64(marker[:8]) - gs.origin; done > 0 {
  72. left := math.MaxUint64 - binary.BigEndian.Uint64(marker[:8])
  73. speed := done/uint64(time.Since(gs.start)/time.Millisecond+1) + 1 // +1s to avoid division by zero
  74. ctx = append(ctx, []interface{}{
  75. "eta", common.PrettyDuration(time.Duration(left/speed) * time.Millisecond),
  76. }...)
  77. }
  78. }
  79. log.Info(msg, ctx...)
  80. }
  81. // generateSnapshot regenerates a brand new snapshot based on an existing state
  82. // database and head block asynchronously. The snapshot is returned immediately
  83. // and generation is continued in the background until done.
  84. func generateSnapshot(diskdb ethdb.KeyValueStore, triedb *trie.Database, cache int, root common.Hash, wiper chan struct{}) *diskLayer {
  85. // Wipe any previously existing snapshot from the database if no wiper is
  86. // currently in progress.
  87. if wiper == nil {
  88. wiper = wipeSnapshot(diskdb, true)
  89. }
  90. // Create a new disk layer with an initialized state marker at zero
  91. rawdb.WriteSnapshotRoot(diskdb, root)
  92. base := &diskLayer{
  93. diskdb: diskdb,
  94. triedb: triedb,
  95. root: root,
  96. cache: fastcache.New(cache * 1024 * 1024),
  97. genMarker: []byte{}, // Initialized but empty!
  98. genPending: make(chan struct{}),
  99. genAbort: make(chan chan *generatorStats),
  100. }
  101. go base.generate(&generatorStats{wiping: wiper, start: time.Now()})
  102. return base
  103. }
  104. // generate is a background thread that iterates over the state and storage tries,
  105. // constructing the state snapshot. All the arguments are purely for statistics
  106. // gethering and logging, since the method surfs the blocks as they arrive, often
  107. // being restarted.
  108. func (dl *diskLayer) generate(stats *generatorStats) {
  109. // If a database wipe is in operation, wait until it's done
  110. if stats.wiping != nil {
  111. stats.Log("Wiper running, state snapshotting paused", dl.genMarker)
  112. select {
  113. // If wiper is done, resume normal mode of operation
  114. case <-stats.wiping:
  115. stats.wiping = nil
  116. stats.start = time.Now()
  117. // If generator was aboted during wipe, return
  118. case abort := <-dl.genAbort:
  119. abort <- stats
  120. return
  121. }
  122. }
  123. // Create an account and state iterator pointing to the current generator marker
  124. accTrie, err := trie.NewSecure(dl.root, dl.triedb)
  125. if err != nil {
  126. // The account trie is missing (GC), surf the chain until one becomes available
  127. stats.Log("Trie missing, state snapshotting paused", dl.genMarker)
  128. abort := <-dl.genAbort
  129. abort <- stats
  130. return
  131. }
  132. stats.Log("Resuming state snapshot generation", dl.genMarker)
  133. var accMarker []byte
  134. if len(dl.genMarker) > 0 { // []byte{} is the start, use nil for that
  135. accMarker = dl.genMarker[:common.HashLength]
  136. }
  137. accIt := trie.NewIterator(accTrie.NodeIterator(accMarker))
  138. batch := dl.diskdb.NewBatch()
  139. // Iterate from the previous marker and continue generating the state snapshot
  140. logged := time.Now()
  141. for accIt.Next() {
  142. // Retrieve the current account and flatten it into the internal format
  143. accountHash := common.BytesToHash(accIt.Key)
  144. var acc struct {
  145. Nonce uint64
  146. Balance *big.Int
  147. Root common.Hash
  148. CodeHash []byte
  149. }
  150. if err := rlp.DecodeBytes(accIt.Value, &acc); err != nil {
  151. log.Crit("Invalid account encountered during snapshot creation", "err", err)
  152. }
  153. data := SlimAccountRLP(acc.Nonce, acc.Balance, acc.Root, acc.CodeHash)
  154. // If the account is not yet in-progress, write it out
  155. if accMarker == nil || !bytes.Equal(accountHash[:], accMarker) {
  156. rawdb.WriteAccountSnapshot(batch, accountHash, data)
  157. stats.storage += common.StorageSize(1 + common.HashLength + len(data))
  158. stats.accounts++
  159. }
  160. // If we've exceeded our batch allowance or termination was requested, flush to disk
  161. var abort chan *generatorStats
  162. select {
  163. case abort = <-dl.genAbort:
  164. default:
  165. }
  166. if batch.ValueSize() > ethdb.IdealBatchSize || abort != nil {
  167. // Only write and set the marker if we actually did something useful
  168. if batch.ValueSize() > 0 {
  169. batch.Write()
  170. batch.Reset()
  171. dl.lock.Lock()
  172. dl.genMarker = accountHash[:]
  173. dl.lock.Unlock()
  174. }
  175. if abort != nil {
  176. stats.Log("Aborting state snapshot generation", accountHash[:])
  177. abort <- stats
  178. return
  179. }
  180. }
  181. // If the account is in-progress, continue where we left off (otherwise iterate all)
  182. if acc.Root != emptyRoot {
  183. storeTrie, err := trie.NewSecure(acc.Root, dl.triedb)
  184. if err != nil {
  185. log.Crit("Storage trie inaccessible for snapshot generation", "err", err)
  186. }
  187. var storeMarker []byte
  188. if accMarker != nil && bytes.Equal(accountHash[:], accMarker) && len(dl.genMarker) > common.HashLength {
  189. storeMarker = dl.genMarker[common.HashLength:]
  190. }
  191. storeIt := trie.NewIterator(storeTrie.NodeIterator(storeMarker))
  192. for storeIt.Next() {
  193. rawdb.WriteStorageSnapshot(batch, accountHash, common.BytesToHash(storeIt.Key), storeIt.Value)
  194. stats.storage += common.StorageSize(1 + 2*common.HashLength + len(storeIt.Value))
  195. stats.slots++
  196. // If we've exceeded our batch allowance or termination was requested, flush to disk
  197. var abort chan *generatorStats
  198. select {
  199. case abort = <-dl.genAbort:
  200. default:
  201. }
  202. if batch.ValueSize() > ethdb.IdealBatchSize || abort != nil {
  203. // Only write and set the marker if we actually did something useful
  204. if batch.ValueSize() > 0 {
  205. batch.Write()
  206. batch.Reset()
  207. dl.lock.Lock()
  208. dl.genMarker = append(accountHash[:], storeIt.Key...)
  209. dl.lock.Unlock()
  210. }
  211. if abort != nil {
  212. stats.Log("Aborting state snapshot generation", append(accountHash[:], storeIt.Key...))
  213. abort <- stats
  214. return
  215. }
  216. }
  217. }
  218. }
  219. if time.Since(logged) > 8*time.Second {
  220. stats.Log("Generating state snapshot", accIt.Key)
  221. logged = time.Now()
  222. }
  223. // Some account processed, unmark the marker
  224. accMarker = nil
  225. }
  226. // Snapshot fully generated, set the marker to nil
  227. if batch.ValueSize() > 0 {
  228. batch.Write()
  229. }
  230. log.Info("Generated state snapshot", "accounts", stats.accounts, "slots", stats.slots,
  231. "storage", stats.storage, "elapsed", common.PrettyDuration(time.Since(stats.start)))
  232. dl.lock.Lock()
  233. dl.genMarker = nil
  234. close(dl.genPending)
  235. dl.lock.Unlock()
  236. // Someone will be looking for us, wait it out
  237. abort := <-dl.genAbort
  238. abort <- nil
  239. }