generate.go 9.7 KB

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