iterator.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. "sort"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core/rawdb"
  23. "github.com/ethereum/go-ethereum/ethdb"
  24. )
  25. // AccountIterator is an iterator to step over all the accounts in a snapshot,
  26. // which may or may npt be composed of multiple layers.
  27. type AccountIterator interface {
  28. // Next steps the iterator forward one element, returning false if exhausted,
  29. // or an error if iteration failed for some reason (e.g. root being iterated
  30. // becomes stale and garbage collected).
  31. Next() bool
  32. // Error returns any failure that occurred during iteration, which might have
  33. // caused a premature iteration exit (e.g. snapshot stack becoming stale).
  34. Error() error
  35. // Hash returns the hash of the account the iterator is currently at.
  36. Hash() common.Hash
  37. // Account returns the RLP encoded slim account the iterator is currently at.
  38. // An error will be returned if the iterator becomes invalid (e.g. snaph
  39. Account() []byte
  40. // Release releases associated resources. Release should always succeed and
  41. // can be called multiple times without causing error.
  42. Release()
  43. }
  44. // diffAccountIterator is an account iterator that steps over the accounts (both
  45. // live and deleted) contained within a single diff layer. Higher order iterators
  46. // will use the deleted accounts to skip deeper iterators.
  47. type diffAccountIterator struct {
  48. // curHash is the current hash the iterator is positioned on. The field is
  49. // explicitly tracked since the referenced diff layer might go stale after
  50. // the iterator was positioned and we don't want to fail accessing the old
  51. // hash as long as the iterator is not touched any more.
  52. curHash common.Hash
  53. layer *diffLayer // Live layer to retrieve values from
  54. keys []common.Hash // Keys left in the layer to iterate
  55. fail error // Any failures encountered (stale)
  56. }
  57. // AccountIterator creates an account iterator over a single diff layer.
  58. func (dl *diffLayer) AccountIterator(seek common.Hash) AccountIterator {
  59. // Seek out the requested starting account
  60. hashes := dl.AccountList()
  61. index := sort.Search(len(hashes), func(i int) bool {
  62. return bytes.Compare(seek[:], hashes[i][:]) < 0
  63. })
  64. // Assemble and returned the already seeked iterator
  65. return &diffAccountIterator{
  66. layer: dl,
  67. keys: hashes[index:],
  68. }
  69. }
  70. // Next steps the iterator forward one element, returning false if exhausted.
  71. func (it *diffAccountIterator) Next() bool {
  72. // If the iterator was already stale, consider it a programmer error. Although
  73. // we could just return false here, triggering this path would probably mean
  74. // somebody forgot to check for Error, so lets blow up instead of undefined
  75. // behavior that's hard to debug.
  76. if it.fail != nil {
  77. panic(fmt.Sprintf("called Next of failed iterator: %v", it.fail))
  78. }
  79. // Stop iterating if all keys were exhausted
  80. if len(it.keys) == 0 {
  81. return false
  82. }
  83. if it.layer.Stale() {
  84. it.fail, it.keys = ErrSnapshotStale, nil
  85. return false
  86. }
  87. // Iterator seems to be still alive, retrieve and cache the live hash
  88. it.curHash = it.keys[0]
  89. // key cached, shift the iterator and notify the user of success
  90. it.keys = it.keys[1:]
  91. return true
  92. }
  93. // Error returns any failure that occurred during iteration, which might have
  94. // caused a premature iteration exit (e.g. snapshot stack becoming stale).
  95. func (it *diffAccountIterator) Error() error {
  96. return it.fail
  97. }
  98. // Hash returns the hash of the account the iterator is currently at.
  99. func (it *diffAccountIterator) Hash() common.Hash {
  100. return it.curHash
  101. }
  102. // Account returns the RLP encoded slim account the iterator is currently at.
  103. // This method may _fail_, if the underlying layer has been flattened between
  104. // the call to Next and Acccount. That type of error will set it.Err.
  105. // This method assumes that flattening does not delete elements from
  106. // the accountdata mapping (writing nil into it is fine though), and will panic
  107. // if elements have been deleted.
  108. func (it *diffAccountIterator) Account() []byte {
  109. it.layer.lock.RLock()
  110. blob, ok := it.layer.accountData[it.curHash]
  111. if !ok {
  112. if _, ok := it.layer.destructSet[it.curHash]; ok {
  113. return nil
  114. }
  115. panic(fmt.Sprintf("iterator referenced non-existent account: %x", it.curHash))
  116. }
  117. it.layer.lock.RUnlock()
  118. if it.layer.Stale() {
  119. it.fail, it.keys = ErrSnapshotStale, nil
  120. }
  121. return blob
  122. }
  123. // Release is a noop for diff account iterators as there are no held resources.
  124. func (it *diffAccountIterator) Release() {}
  125. // diskAccountIterator is an account iterator that steps over the live accounts
  126. // contained within a disk layer.
  127. type diskAccountIterator struct {
  128. layer *diskLayer
  129. it ethdb.Iterator
  130. }
  131. // AccountIterator creates an account iterator over a disk layer.
  132. func (dl *diskLayer) AccountIterator(seek common.Hash) AccountIterator {
  133. // TODO: Fix seek position, or remove seek parameter
  134. return &diskAccountIterator{
  135. layer: dl,
  136. it: dl.diskdb.NewIteratorWithPrefix(rawdb.SnapshotAccountPrefix),
  137. }
  138. }
  139. // Next steps the iterator forward one element, returning false if exhausted.
  140. func (it *diskAccountIterator) Next() bool {
  141. // If the iterator was already exhausted, don't bother
  142. if it.it == nil {
  143. return false
  144. }
  145. // Try to advance the iterator and release it if we reached the end
  146. for {
  147. if !it.it.Next() || !bytes.HasPrefix(it.it.Key(), rawdb.SnapshotAccountPrefix) {
  148. it.it.Release()
  149. it.it = nil
  150. return false
  151. }
  152. if len(it.it.Key()) == len(rawdb.SnapshotAccountPrefix)+common.HashLength {
  153. break
  154. }
  155. }
  156. return true
  157. }
  158. // Error returns any failure that occurred during iteration, which might have
  159. // caused a premature iteration exit (e.g. snapshot stack becoming stale).
  160. //
  161. // A diff layer is immutable after creation content wise and can always be fully
  162. // iterated without error, so this method always returns nil.
  163. func (it *diskAccountIterator) Error() error {
  164. return it.it.Error()
  165. }
  166. // Hash returns the hash of the account the iterator is currently at.
  167. func (it *diskAccountIterator) Hash() common.Hash {
  168. return common.BytesToHash(it.it.Key())
  169. }
  170. // Account returns the RLP encoded slim account the iterator is currently at.
  171. func (it *diskAccountIterator) Account() []byte {
  172. return it.it.Value()
  173. }
  174. // Release releases the database snapshot held during iteration.
  175. func (it *diskAccountIterator) Release() {
  176. // The iterator is auto-released on exhaustion, so make sure it's still alive
  177. if it.it != nil {
  178. it.it.Release()
  179. it.it = nil
  180. }
  181. }