conversion.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. // Copyright 2020 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. "sync"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/ethdb/memorydb"
  24. "github.com/ethereum/go-ethereum/log"
  25. "github.com/ethereum/go-ethereum/rlp"
  26. "github.com/ethereum/go-ethereum/trie"
  27. )
  28. // trieKV represents a trie key-value pair
  29. type trieKV struct {
  30. key common.Hash
  31. value []byte
  32. }
  33. type (
  34. // trieGeneratorFn is the interface of trie generation which can
  35. // be implemented by different trie algorithm.
  36. trieGeneratorFn func(in chan trieKV, out chan common.Hash)
  37. // leafCallbackFn is the callback invoked at the leaves of the trie,
  38. // returns the subtrie root with the specified subtrie identifier.
  39. leafCallbackFn func(hash common.Hash, stat *generateStats) common.Hash
  40. )
  41. // GenerateAccountTrieRoot takes an account iterator and reproduces the root hash.
  42. func GenerateAccountTrieRoot(it AccountIterator) (common.Hash, error) {
  43. return generateTrieRoot(it, common.Hash{}, stdGenerate, nil, &generateStats{start: time.Now()}, true)
  44. }
  45. // GenerateStorageTrieRoot takes a storage iterator and reproduces the root hash.
  46. func GenerateStorageTrieRoot(account common.Hash, it StorageIterator) (common.Hash, error) {
  47. return generateTrieRoot(it, account, stdGenerate, nil, &generateStats{start: time.Now()}, true)
  48. }
  49. // VerifyState takes the whole snapshot tree as the input, traverses all the accounts
  50. // as well as the corresponding storages and compares the re-computed hash with the
  51. // original one(state root and the storage root).
  52. func VerifyState(snaptree *Tree, root common.Hash) error {
  53. acctIt, err := snaptree.AccountIterator(root, common.Hash{})
  54. if err != nil {
  55. return err
  56. }
  57. defer acctIt.Release()
  58. got, err := generateTrieRoot(acctIt, common.Hash{}, stdGenerate, func(account common.Hash, stat *generateStats) common.Hash {
  59. storageIt, err := snaptree.StorageIterator(root, account, common.Hash{})
  60. if err != nil {
  61. return common.Hash{}
  62. }
  63. defer storageIt.Release()
  64. hash, err := generateTrieRoot(storageIt, account, stdGenerate, nil, stat, false)
  65. if err != nil {
  66. return common.Hash{}
  67. }
  68. return hash
  69. }, &generateStats{start: time.Now()}, true)
  70. if err != nil {
  71. return err
  72. }
  73. if got != root {
  74. return fmt.Errorf("state root hash mismatch: got %x, want %x", got, root)
  75. }
  76. return nil
  77. }
  78. // generateStats is a collection of statistics gathered by the trie generator
  79. // for logging purposes.
  80. type generateStats struct {
  81. accounts uint64
  82. slots uint64
  83. curAccount common.Hash
  84. curSlot common.Hash
  85. start time.Time
  86. lock sync.RWMutex
  87. }
  88. // progress records the progress trie generator made recently.
  89. func (stat *generateStats) progress(accounts, slots uint64, curAccount common.Hash, curSlot common.Hash) {
  90. stat.lock.Lock()
  91. defer stat.lock.Unlock()
  92. stat.accounts += accounts
  93. stat.slots += slots
  94. stat.curAccount = curAccount
  95. stat.curSlot = curSlot
  96. }
  97. // report prints the cumulative progress statistic smartly.
  98. func (stat *generateStats) report() {
  99. stat.lock.RLock()
  100. defer stat.lock.RUnlock()
  101. var ctx []interface{}
  102. if stat.curSlot != (common.Hash{}) {
  103. ctx = append(ctx, []interface{}{
  104. "in", stat.curAccount,
  105. "at", stat.curSlot,
  106. }...)
  107. } else {
  108. ctx = append(ctx, []interface{}{"at", stat.curAccount}...)
  109. }
  110. // Add the usual measurements
  111. ctx = append(ctx, []interface{}{"accounts", stat.accounts}...)
  112. if stat.slots != 0 {
  113. ctx = append(ctx, []interface{}{"slots", stat.slots}...)
  114. }
  115. ctx = append(ctx, []interface{}{"elapsed", common.PrettyDuration(time.Since(stat.start))}...)
  116. log.Info("Generating trie hash from snapshot", ctx...)
  117. }
  118. // reportDone prints the last log when the whole generation is finished.
  119. func (stat *generateStats) reportDone() {
  120. stat.lock.RLock()
  121. defer stat.lock.RUnlock()
  122. var ctx []interface{}
  123. ctx = append(ctx, []interface{}{"accounts", stat.accounts}...)
  124. if stat.slots != 0 {
  125. ctx = append(ctx, []interface{}{"slots", stat.slots}...)
  126. }
  127. ctx = append(ctx, []interface{}{"elapsed", common.PrettyDuration(time.Since(stat.start))}...)
  128. log.Info("Generated trie hash from snapshot", ctx...)
  129. }
  130. // generateTrieRoot generates the trie hash based on the snapshot iterator.
  131. // It can be used for generating account trie, storage trie or even the
  132. // whole state which connects the accounts and the corresponding storages.
  133. func generateTrieRoot(it Iterator, account common.Hash, generatorFn trieGeneratorFn, leafCallback leafCallbackFn, stats *generateStats, report bool) (common.Hash, error) {
  134. var (
  135. in = make(chan trieKV) // chan to pass leaves
  136. out = make(chan common.Hash, 1) // chan to collect result
  137. stoplog = make(chan bool, 1) // 1-size buffer, works when logging is not enabled
  138. wg sync.WaitGroup
  139. )
  140. // Spin up a go-routine for trie hash re-generation
  141. wg.Add(1)
  142. go func() {
  143. defer wg.Done()
  144. generatorFn(in, out)
  145. }()
  146. // Spin up a go-routine for progress logging
  147. if report && stats != nil {
  148. wg.Add(1)
  149. go func() {
  150. defer wg.Done()
  151. timer := time.NewTimer(0)
  152. defer timer.Stop()
  153. for {
  154. select {
  155. case <-timer.C:
  156. stats.report()
  157. timer.Reset(time.Second * 8)
  158. case success := <-stoplog:
  159. if success {
  160. stats.reportDone()
  161. }
  162. return
  163. }
  164. }
  165. }()
  166. }
  167. // stop is a helper function to shutdown the background threads
  168. // and return the re-generated trie hash.
  169. stop := func(success bool) common.Hash {
  170. close(in)
  171. result := <-out
  172. stoplog <- success
  173. wg.Wait()
  174. return result
  175. }
  176. var (
  177. logged = time.Now()
  178. processed = uint64(0)
  179. leaf trieKV
  180. last common.Hash
  181. )
  182. // Start to feed leaves
  183. for it.Next() {
  184. if account == (common.Hash{}) {
  185. var (
  186. err error
  187. fullData []byte
  188. )
  189. if leafCallback == nil {
  190. fullData, err = FullAccountRLP(it.(AccountIterator).Account())
  191. if err != nil {
  192. stop(false)
  193. return common.Hash{}, err
  194. }
  195. } else {
  196. account, err := FullAccount(it.(AccountIterator).Account())
  197. if err != nil {
  198. stop(false)
  199. return common.Hash{}, err
  200. }
  201. // Apply the leaf callback. Normally the callback is used to traverse
  202. // the storage trie and re-generate the subtrie root.
  203. subroot := leafCallback(it.Hash(), stats)
  204. if !bytes.Equal(account.Root, subroot.Bytes()) {
  205. stop(false)
  206. return common.Hash{}, fmt.Errorf("invalid subroot(%x), want %x, got %x", it.Hash(), account.Root, subroot)
  207. }
  208. fullData, err = rlp.EncodeToBytes(account)
  209. if err != nil {
  210. stop(false)
  211. return common.Hash{}, err
  212. }
  213. }
  214. leaf = trieKV{it.Hash(), fullData}
  215. } else {
  216. leaf = trieKV{it.Hash(), common.CopyBytes(it.(StorageIterator).Slot())}
  217. }
  218. in <- leaf
  219. // Accumulate the generation statistic if it's required.
  220. processed++
  221. if time.Since(logged) > 3*time.Second && stats != nil {
  222. if account == (common.Hash{}) {
  223. stats.progress(processed, 0, it.Hash(), common.Hash{})
  224. } else {
  225. stats.progress(0, processed, account, it.Hash())
  226. }
  227. logged, processed = time.Now(), 0
  228. }
  229. last = it.Hash()
  230. }
  231. // Commit the last part statistic.
  232. if processed > 0 && stats != nil {
  233. if account == (common.Hash{}) {
  234. stats.progress(processed, 0, last, common.Hash{})
  235. } else {
  236. stats.progress(0, processed, account, last)
  237. }
  238. }
  239. result := stop(true)
  240. return result, nil
  241. }
  242. // stdGenerate is a very basic hexary trie builder which uses the same Trie
  243. // as the rest of geth, with no enhancements or optimizations
  244. func stdGenerate(in chan trieKV, out chan common.Hash) {
  245. t, _ := trie.New(common.Hash{}, trie.NewDatabase(memorydb.New()))
  246. for leaf := range in {
  247. t.TryUpdate(leaf.key[:], leaf.value)
  248. }
  249. out <- t.Hash()
  250. }