generate.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. "fmt"
  20. "math/big"
  21. "time"
  22. "github.com/allegro/bigcache"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core/rawdb"
  25. "github.com/ethereum/go-ethereum/crypto"
  26. "github.com/ethereum/go-ethereum/ethdb"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/rlp"
  29. "github.com/ethereum/go-ethereum/trie"
  30. )
  31. var (
  32. // emptyRoot is the known root hash of an empty trie.
  33. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  34. // emptyCode is the known hash of the empty EVM bytecode.
  35. emptyCode = crypto.Keccak256Hash(nil)
  36. )
  37. // wipeSnapshot iterates over the entire key-value database and deletes all the
  38. // data associated with the snapshot (accounts, storage, metadata). After all is
  39. // done, the snapshot range of the database is compacted to free up unused data
  40. // blocks.
  41. func wipeSnapshot(db ethdb.KeyValueStore) error {
  42. // Batch deletions together to avoid holding an iterator for too long
  43. var (
  44. batch = db.NewBatch()
  45. items int
  46. )
  47. // Iterate over the snapshot key-range and delete all of them
  48. log.Info("Deleting previous snapshot leftovers")
  49. start, logged := time.Now(), time.Now()
  50. it := db.NewIteratorWithStart(rawdb.StateSnapshotPrefix)
  51. for it.Next() {
  52. // Skip any keys with the correct prefix but wrong lenth (trie nodes)
  53. key := it.Key()
  54. if !bytes.HasPrefix(key, rawdb.StateSnapshotPrefix) {
  55. break
  56. }
  57. if len(key) != len(rawdb.StateSnapshotPrefix)+common.HashLength && len(key) != len(rawdb.StateSnapshotPrefix)+2*common.HashLength {
  58. continue
  59. }
  60. // Delete the key and periodically recreate the batch and iterator
  61. batch.Delete(key)
  62. items++
  63. if items%10000 == 0 {
  64. // Batch too large (or iterator too long lived, flush and recreate)
  65. it.Release()
  66. if err := batch.Write(); err != nil {
  67. return err
  68. }
  69. batch.Reset()
  70. it = db.NewIteratorWithStart(key)
  71. if time.Since(logged) > 8*time.Second {
  72. log.Info("Deleting previous snapshot leftovers", "wiped", items, "elapsed", time.Since(start))
  73. logged = time.Now()
  74. }
  75. }
  76. }
  77. it.Release()
  78. rawdb.DeleteSnapshotBlock(batch)
  79. if err := batch.Write(); err != nil {
  80. return err
  81. }
  82. log.Info("Deleted previous snapshot leftovers", "wiped", items, "elapsed", time.Since(start))
  83. // Compact the snapshot section of the database to get rid of unused space
  84. log.Info("Compacting snapshot area in database")
  85. start = time.Now()
  86. end := common.CopyBytes(rawdb.StateSnapshotPrefix)
  87. end[len(end)-1]++
  88. if err := db.Compact(rawdb.StateSnapshotPrefix, end); err != nil {
  89. return err
  90. }
  91. log.Info("Compacted snapshot area in database", "elapsed", time.Since(start))
  92. return nil
  93. }
  94. // generateSnapshot regenerates a brand new snapshot based on an existing state database and head block.
  95. func generateSnapshot(db ethdb.KeyValueStore, journal string, headNumber uint64, headRoot common.Hash) (snapshot, error) {
  96. // Wipe any previously existing snapshot from the database
  97. if err := wipeSnapshot(db); err != nil {
  98. return nil, err
  99. }
  100. // Iterate the entire storage trie and re-generate the state snapshot
  101. var (
  102. accountCount int
  103. storageCount int
  104. storageNodes int
  105. accountSize common.StorageSize
  106. storageSize common.StorageSize
  107. logged time.Time
  108. )
  109. batch := db.NewBatch()
  110. triedb := trie.NewDatabase(db)
  111. accTrie, err := trie.NewSecure(headRoot, triedb)
  112. if err != nil {
  113. return nil, err
  114. }
  115. accIt := trie.NewIterator(accTrie.NodeIterator(nil))
  116. for accIt.Next() {
  117. var (
  118. curStorageCount int
  119. curStorageNodes int
  120. curAccountSize common.StorageSize
  121. curStorageSize common.StorageSize
  122. accountHash = common.BytesToHash(accIt.Key)
  123. )
  124. var acc struct {
  125. Nonce uint64
  126. Balance *big.Int
  127. Root common.Hash
  128. CodeHash []byte
  129. }
  130. if err := rlp.DecodeBytes(accIt.Value, &acc); err != nil {
  131. return nil, err
  132. }
  133. data := AccountRLP(acc.Nonce, acc.Balance, acc.Root, acc.CodeHash)
  134. curAccountSize += common.StorageSize(1 + common.HashLength + len(data))
  135. rawdb.WriteAccountSnapshot(batch, accountHash, data)
  136. if batch.ValueSize() > ethdb.IdealBatchSize {
  137. batch.Write()
  138. batch.Reset()
  139. }
  140. if acc.Root != emptyRoot {
  141. storeTrie, err := trie.NewSecure(acc.Root, triedb)
  142. if err != nil {
  143. return nil, err
  144. }
  145. storeIt := trie.NewIterator(storeTrie.NodeIterator(nil))
  146. for storeIt.Next() {
  147. curStorageSize += common.StorageSize(1 + 2*common.HashLength + len(storeIt.Value))
  148. curStorageCount++
  149. rawdb.WriteStorageSnapshot(batch, accountHash, common.BytesToHash(storeIt.Key), storeIt.Value)
  150. if batch.ValueSize() > ethdb.IdealBatchSize {
  151. batch.Write()
  152. batch.Reset()
  153. }
  154. }
  155. curStorageNodes = storeIt.Nodes
  156. }
  157. accountCount++
  158. storageCount += curStorageCount
  159. accountSize += curAccountSize
  160. storageSize += curStorageSize
  161. storageNodes += curStorageNodes
  162. if time.Since(logged) > 8*time.Second {
  163. fmt.Printf("%#x: %9s + %9s (%6d slots, %6d nodes), total %9s (%d accs, %d nodes) + %9s (%d slots, %d nodes)\n", accIt.Key, curAccountSize.TerminalString(), curStorageSize.TerminalString(), curStorageCount, curStorageNodes, accountSize.TerminalString(), accountCount, accIt.Nodes, storageSize.TerminalString(), storageCount, storageNodes)
  164. logged = time.Now()
  165. }
  166. }
  167. fmt.Printf("Totals: %9s (%d accs, %d nodes) + %9s (%d slots, %d nodes)\n", accountSize.TerminalString(), accountCount, accIt.Nodes, storageSize.TerminalString(), storageCount, storageNodes)
  168. // Update the snapshot block marker and write any remainder data
  169. rawdb.WriteSnapshotBlock(batch, headNumber, headRoot)
  170. batch.Write()
  171. batch.Reset()
  172. // Compact the snapshot section of the database to get rid of unused space
  173. log.Info("Compacting snapshot in chain database")
  174. if err := db.Compact([]byte{'s'}, []byte{'s' + 1}); err != nil {
  175. return nil, err
  176. }
  177. // New snapshot generated, construct a brand new base layer
  178. cache, _ := bigcache.NewBigCache(bigcache.Config{ // TODO(karalabe): dedup
  179. Shards: 1024,
  180. LifeWindow: time.Hour,
  181. MaxEntriesInWindow: 512 * 1024,
  182. MaxEntrySize: 512,
  183. HardMaxCacheSize: 512,
  184. })
  185. return &diskLayer{
  186. journal: journal,
  187. db: db,
  188. cache: cache,
  189. number: headNumber,
  190. root: headRoot,
  191. }, nil
  192. }