difflayer.go 9.9 KB

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