difflayer.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. "fmt"
  19. "sort"
  20. "sync"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/log"
  23. "github.com/ethereum/go-ethereum/rlp"
  24. )
  25. // diffLayer represents a collection of modifications made to a state snapshot
  26. // after running a block on top. It contains one sorted list for the account trie
  27. // and one-one list for each storage tries.
  28. //
  29. // The goal of a diff layer is to act as a journal, tracking recent modifications
  30. // made to the state, that have not yet graduated into a semi-immutable state.
  31. type diffLayer struct {
  32. parent snapshot // Parent snapshot modified by this one, never nil
  33. memory uint64 // Approximate guess as to how much memory we use
  34. root common.Hash // Root hash to which this snapshot diff belongs to
  35. stale bool // Signals that the layer became stale (state progressed)
  36. accountList []common.Hash // List of account for iteration. If it exists, it's sorted, otherwise it's nil
  37. accountData map[common.Hash][]byte // Keyed accounts for direct retrival (nil means deleted)
  38. storageList map[common.Hash][]common.Hash // List of storage slots for iterated retrievals, one per account. Any existing lists are sorted if non-nil
  39. storageData map[common.Hash]map[common.Hash][]byte // Keyed storage slots for direct retrival. one per account (nil means deleted)
  40. lock sync.RWMutex
  41. }
  42. // newDiffLayer creates a new diff on top of an existing snapshot, whether that's a low
  43. // level persistent database or a hierarchical diff already.
  44. func newDiffLayer(parent snapshot, root common.Hash, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer {
  45. // Create the new layer with some pre-allocated data segments
  46. dl := &diffLayer{
  47. parent: parent,
  48. root: root,
  49. accountData: accounts,
  50. storageData: storage,
  51. }
  52. // Determine mem size
  53. for _, data := range accounts {
  54. dl.memory += uint64(len(data))
  55. }
  56. // Fill the storage hashes and sort them for the iterator
  57. dl.storageList = make(map[common.Hash][]common.Hash)
  58. for accountHash, slots := range storage {
  59. // If the slots are nil, sanity check that it's a deleted account
  60. if slots == nil {
  61. // Ensure that the account was just marked as deleted
  62. if account, ok := accounts[accountHash]; account != nil || !ok {
  63. panic(fmt.Sprintf("storage in %#x nil, but account conflicts (%#x, exists: %v)", accountHash, account, ok))
  64. }
  65. // Everything ok, store the deletion mark and continue
  66. dl.storageList[accountHash] = nil
  67. continue
  68. }
  69. // Storage slots are not nil so entire contract was not deleted, ensure the
  70. // account was just updated.
  71. if account, ok := accounts[accountHash]; account == nil || !ok {
  72. log.Error(fmt.Sprintf("storage in %#x exists, but account nil (exists: %v)", accountHash, ok))
  73. }
  74. // Determine mem size
  75. for _, data := range slots {
  76. dl.memory += uint64(len(data))
  77. }
  78. }
  79. dl.memory += uint64(len(dl.storageList) * common.HashLength)
  80. return dl
  81. }
  82. // Root returns the root hash for which this snapshot was made.
  83. func (dl *diffLayer) Root() common.Hash {
  84. return dl.root
  85. }
  86. // Stale return whether this layer has become stale (was flattened across) or if
  87. // it's still live.
  88. func (dl *diffLayer) Stale() bool {
  89. dl.lock.RLock()
  90. defer dl.lock.RUnlock()
  91. return dl.stale
  92. }
  93. // Account directly retrieves the account associated with a particular hash in
  94. // the snapshot slim data format.
  95. func (dl *diffLayer) Account(hash common.Hash) (*Account, error) {
  96. data, err := dl.AccountRLP(hash)
  97. if err != nil {
  98. return nil, err
  99. }
  100. if len(data) == 0 { // can be both nil and []byte{}
  101. return nil, nil
  102. }
  103. account := new(Account)
  104. if err := rlp.DecodeBytes(data, account); err != nil {
  105. panic(err)
  106. }
  107. return account, nil
  108. }
  109. // AccountRLP directly retrieves the account RLP associated with a particular
  110. // hash in the snapshot slim data format.
  111. func (dl *diffLayer) AccountRLP(hash common.Hash) ([]byte, error) {
  112. dl.lock.RLock()
  113. defer dl.lock.RUnlock()
  114. // If the layer was flattened into, consider it invalid (any live reference to
  115. // the original should be marked as unusable).
  116. if dl.stale {
  117. return nil, ErrSnapshotStale
  118. }
  119. // If the account is known locally, return it. Note, a nil account means it was
  120. // deleted, and is a different notion than an unknown account!
  121. if data, ok := dl.accountData[hash]; ok {
  122. return data, nil
  123. }
  124. // Account unknown to this diff, resolve from parent
  125. return dl.parent.AccountRLP(hash)
  126. }
  127. // Storage directly retrieves the storage data associated with a particular hash,
  128. // within a particular account. If the slot is unknown to this diff, it's parent
  129. // is consulted.
  130. func (dl *diffLayer) Storage(accountHash, storageHash common.Hash) ([]byte, error) {
  131. dl.lock.RLock()
  132. defer dl.lock.RUnlock()
  133. // If the layer was flattened into, consider it invalid (any live reference to
  134. // the original should be marked as unusable).
  135. if dl.stale {
  136. return nil, ErrSnapshotStale
  137. }
  138. // If the account is known locally, try to resolve the slot locally. Note, a nil
  139. // account means it was deleted, and is a different notion than an unknown account!
  140. if storage, ok := dl.storageData[accountHash]; ok {
  141. if storage == nil {
  142. return nil, nil
  143. }
  144. if data, ok := storage[storageHash]; ok {
  145. return data, nil
  146. }
  147. }
  148. // Account - or slot within - unknown to this diff, resolve from parent
  149. return dl.parent.Storage(accountHash, storageHash)
  150. }
  151. // Update creates a new layer on top of the existing snapshot diff tree with
  152. // the specified data items.
  153. func (dl *diffLayer) Update(blockRoot common.Hash, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer {
  154. return newDiffLayer(dl, blockRoot, accounts, storage)
  155. }
  156. // flatten pushes all data from this point downwards, flattening everything into
  157. // a single diff at the bottom. Since usually the lowermost diff is the largest,
  158. // the flattening bulds up from there in reverse.
  159. func (dl *diffLayer) flatten() snapshot {
  160. // If the parent is not diff, we're the first in line, return unmodified
  161. parent, ok := dl.parent.(*diffLayer)
  162. if !ok {
  163. return dl
  164. }
  165. // Parent is a diff, flatten it first (note, apart from weird corned cases,
  166. // flatten will realistically only ever merge 1 layer, so there's no need to
  167. // be smarter about grouping flattens together).
  168. parent = parent.flatten().(*diffLayer)
  169. parent.lock.Lock()
  170. defer parent.lock.Unlock()
  171. // Before actually writing all our data to the parent, first ensure that the
  172. // parent hasn't been 'corrupted' by someone else already flattening into it
  173. if parent.stale {
  174. panic("parent diff layer is stale") // we've flattened into the same parent from two children, boo
  175. }
  176. parent.stale = true
  177. // Overwrite all the updated accounts blindly, merge the sorted list
  178. for hash, data := range dl.accountData {
  179. parent.accountData[hash] = data
  180. }
  181. // Overwrite all the updates storage slots (individually)
  182. for accountHash, storage := range dl.storageData {
  183. // If storage didn't exist (or was deleted) in the parent; or if the storage
  184. // was freshly deleted in the child, overwrite blindly
  185. if parent.storageData[accountHash] == nil || storage == nil {
  186. parent.storageData[accountHash] = storage
  187. continue
  188. }
  189. // Storage exists in both parent and child, merge the slots
  190. comboData := parent.storageData[accountHash]
  191. for storageHash, data := range storage {
  192. comboData[storageHash] = data
  193. }
  194. parent.storageData[accountHash] = comboData
  195. }
  196. // Return the combo parent
  197. return &diffLayer{
  198. parent: parent.parent,
  199. root: dl.root,
  200. storageList: parent.storageList,
  201. storageData: parent.storageData,
  202. accountList: parent.accountList,
  203. accountData: parent.accountData,
  204. memory: parent.memory + dl.memory,
  205. }
  206. }
  207. // Journal commits an entire diff hierarchy to disk into a single journal file.
  208. // This is meant to be used during shutdown to persist the snapshot without
  209. // flattening everything down (bad for reorgs).
  210. func (dl *diffLayer) Journal() error {
  211. writer, err := dl.journal()
  212. if err != nil {
  213. return err
  214. }
  215. writer.Close()
  216. return nil
  217. }
  218. // AccountList returns a sorted list of all accounts in this difflayer.
  219. func (dl *diffLayer) AccountList() []common.Hash {
  220. dl.lock.Lock()
  221. defer dl.lock.Unlock()
  222. if dl.accountList != nil {
  223. return dl.accountList
  224. }
  225. accountList := make([]common.Hash, len(dl.accountData))
  226. i := 0
  227. for k, _ := range dl.accountData {
  228. accountList[i] = k
  229. i++
  230. // This would be a pretty good opportunity to also
  231. // calculate the size, if we want to
  232. }
  233. sort.Sort(hashes(accountList))
  234. dl.accountList = accountList
  235. return dl.accountList
  236. }
  237. // StorageList returns a sorted list of all storage slot hashes
  238. // in this difflayer for the given account.
  239. func (dl *diffLayer) StorageList(accountHash common.Hash) []common.Hash {
  240. dl.lock.Lock()
  241. defer dl.lock.Unlock()
  242. if dl.storageList[accountHash] != nil {
  243. return dl.storageList[accountHash]
  244. }
  245. accountStorageMap := dl.storageData[accountHash]
  246. accountStorageList := make([]common.Hash, len(accountStorageMap))
  247. i := 0
  248. for k, _ := range accountStorageMap {
  249. accountStorageList[i] = k
  250. i++
  251. // This would be a pretty good opportunity to also
  252. // calculate the size, if we want to
  253. }
  254. sort.Sort(hashes(accountStorageList))
  255. dl.storageList[accountHash] = accountStorageList
  256. return accountStorageList
  257. }