secure_trie.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // Copyright 2015 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 trie
  17. import (
  18. "fmt"
  19. "github.com/ethereum/go-ethereum/common"
  20. "github.com/ethereum/go-ethereum/core/types"
  21. "github.com/ethereum/go-ethereum/log"
  22. "github.com/ethereum/go-ethereum/rlp"
  23. )
  24. // SecureTrie is the old name of StateTrie.
  25. // Deprecated: use StateTrie.
  26. type SecureTrie = StateTrie
  27. // NewSecure creates a new StateTrie.
  28. // Deprecated: use NewStateTrie.
  29. func NewSecure(owner common.Hash, root common.Hash, db *Database) (*SecureTrie, error) {
  30. return NewStateTrie(owner, root, db)
  31. }
  32. // StateTrie wraps a trie with key hashing. In a secure trie, all
  33. // access operations hash the key using keccak256. This prevents
  34. // calling code from creating long chains of nodes that
  35. // increase the access time.
  36. //
  37. // Contrary to a regular trie, a StateTrie can only be created with
  38. // New and must have an attached database. The database also stores
  39. // the preimage of each key.
  40. //
  41. // StateTrie is not safe for concurrent use.
  42. type StateTrie struct {
  43. trie Trie
  44. preimages *preimageStore
  45. hashKeyBuf [common.HashLength]byte
  46. secKeyCache map[string][]byte
  47. secKeyCacheOwner *StateTrie // Pointer to self, replace the key cache on mismatch
  48. }
  49. // NewStateTrie creates a trie with an existing root node from a backing database
  50. // and optional intermediate in-memory node pool.
  51. //
  52. // If root is the zero hash or the sha3 hash of an empty string, the
  53. // trie is initially empty. Otherwise, New will panic if db is nil
  54. // and returns MissingNodeError if the root node cannot be found.
  55. //
  56. // Accessing the trie loads nodes from the database or node pool on demand.
  57. // Loaded nodes are kept around until their 'cache generation' expires.
  58. // A new cache generation is created by each call to Commit.
  59. // cachelimit sets the number of past cache generations to keep.
  60. func NewStateTrie(owner common.Hash, root common.Hash, db *Database) (*StateTrie, error) {
  61. if db == nil {
  62. panic("trie.NewSecure called without a database")
  63. }
  64. trie, err := New(owner, root, db)
  65. if err != nil {
  66. return nil, err
  67. }
  68. return &StateTrie{trie: *trie, preimages: db.preimages}, nil
  69. }
  70. // Get returns the value for key stored in the trie.
  71. // The value bytes must not be modified by the caller.
  72. func (t *StateTrie) Get(key []byte) []byte {
  73. res, err := t.TryGet(key)
  74. if err != nil {
  75. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  76. }
  77. return res
  78. }
  79. // TryGet returns the value for key stored in the trie.
  80. // The value bytes must not be modified by the caller.
  81. // If a node was not found in the database, a MissingNodeError is returned.
  82. func (t *StateTrie) TryGet(key []byte) ([]byte, error) {
  83. return t.trie.TryGet(t.hashKey(key))
  84. }
  85. func (t *StateTrie) TryGetAccount(key []byte) (*types.StateAccount, error) {
  86. var ret types.StateAccount
  87. res, err := t.trie.TryGet(t.hashKey(key))
  88. if err != nil {
  89. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  90. return &ret, err
  91. }
  92. if res == nil {
  93. return nil, nil
  94. }
  95. err = rlp.DecodeBytes(res, &ret)
  96. return &ret, err
  97. }
  98. // TryGetAccountWithPreHashedKey does the same thing as TryGetAccount, however
  99. // it expects a key that is already hashed. This constitutes an abstraction leak,
  100. // since the client code needs to know the key format.
  101. func (t *StateTrie) TryGetAccountWithPreHashedKey(key []byte) (*types.StateAccount, error) {
  102. var ret types.StateAccount
  103. res, err := t.trie.TryGet(key)
  104. if err != nil {
  105. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  106. return &ret, err
  107. }
  108. if res == nil {
  109. return nil, nil
  110. }
  111. err = rlp.DecodeBytes(res, &ret)
  112. return &ret, err
  113. }
  114. // TryGetNode attempts to retrieve a trie node by compact-encoded path. It is not
  115. // possible to use keybyte-encoding as the path might contain odd nibbles.
  116. func (t *StateTrie) TryGetNode(path []byte) ([]byte, int, error) {
  117. return t.trie.TryGetNode(path)
  118. }
  119. // TryUpdateAccount account will abstract the write of an account to the
  120. // secure trie.
  121. func (t *StateTrie) TryUpdateAccount(key []byte, acc *types.StateAccount) error {
  122. hk := t.hashKey(key)
  123. data, err := rlp.EncodeToBytes(acc)
  124. if err != nil {
  125. return err
  126. }
  127. if err := t.trie.TryUpdate(hk, data); err != nil {
  128. return err
  129. }
  130. t.getSecKeyCache()[string(hk)] = common.CopyBytes(key)
  131. return nil
  132. }
  133. // Update associates key with value in the trie. Subsequent calls to
  134. // Get will return value. If value has length zero, any existing value
  135. // is deleted from the trie and calls to Get will return nil.
  136. //
  137. // The value bytes must not be modified by the caller while they are
  138. // stored in the trie.
  139. func (t *StateTrie) Update(key, value []byte) {
  140. if err := t.TryUpdate(key, value); err != nil {
  141. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  142. }
  143. }
  144. // TryUpdate associates key with value in the trie. Subsequent calls to
  145. // Get will return value. If value has length zero, any existing value
  146. // is deleted from the trie and calls to Get will return nil.
  147. //
  148. // The value bytes must not be modified by the caller while they are
  149. // stored in the trie.
  150. //
  151. // If a node was not found in the database, a MissingNodeError is returned.
  152. func (t *StateTrie) TryUpdate(key, value []byte) error {
  153. hk := t.hashKey(key)
  154. err := t.trie.TryUpdate(hk, value)
  155. if err != nil {
  156. return err
  157. }
  158. t.getSecKeyCache()[string(hk)] = common.CopyBytes(key)
  159. return nil
  160. }
  161. // Delete removes any existing value for key from the trie.
  162. func (t *StateTrie) Delete(key []byte) {
  163. if err := t.TryDelete(key); err != nil {
  164. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  165. }
  166. }
  167. // TryDelete removes any existing value for key from the trie.
  168. // If a node was not found in the database, a MissingNodeError is returned.
  169. func (t *StateTrie) TryDelete(key []byte) error {
  170. hk := t.hashKey(key)
  171. delete(t.getSecKeyCache(), string(hk))
  172. return t.trie.TryDelete(hk)
  173. }
  174. // TryDeleteACcount abstracts an account deletion from the trie.
  175. func (t *StateTrie) TryDeleteAccount(key []byte) error {
  176. hk := t.hashKey(key)
  177. delete(t.getSecKeyCache(), string(hk))
  178. return t.trie.TryDelete(hk)
  179. }
  180. // GetKey returns the sha3 preimage of a hashed key that was
  181. // previously used to store a value.
  182. func (t *StateTrie) GetKey(shaKey []byte) []byte {
  183. if key, ok := t.getSecKeyCache()[string(shaKey)]; ok {
  184. return key
  185. }
  186. if t.preimages == nil {
  187. return nil
  188. }
  189. return t.preimages.preimage(common.BytesToHash(shaKey))
  190. }
  191. // Commit collects all dirty nodes in the trie and replace them with the
  192. // corresponding node hash. All collected nodes(including dirty leaves if
  193. // collectLeaf is true) will be encapsulated into a nodeset for return.
  194. // The returned nodeset can be nil if the trie is clean(nothing to commit).
  195. // All cached preimages will be also flushed if preimages recording is enabled.
  196. // Once the trie is committed, it's not usable anymore. A new trie must
  197. // be created with new root and updated trie database for following usage
  198. func (t *StateTrie) Commit(collectLeaf bool) (common.Hash, *NodeSet, error) {
  199. // Write all the pre-images to the actual disk database
  200. if len(t.getSecKeyCache()) > 0 {
  201. if t.preimages != nil {
  202. preimages := make(map[common.Hash][]byte)
  203. for hk, key := range t.secKeyCache {
  204. preimages[common.BytesToHash([]byte(hk))] = key
  205. }
  206. t.preimages.insertPreimage(preimages)
  207. }
  208. t.secKeyCache = make(map[string][]byte)
  209. }
  210. // Commit the trie to its intermediate node database
  211. return t.trie.Commit(collectLeaf)
  212. }
  213. // Hash returns the root hash of StateTrie. It does not write to the
  214. // database and can be used even if the trie doesn't have one.
  215. func (t *StateTrie) Hash() common.Hash {
  216. return t.trie.Hash()
  217. }
  218. // Copy returns a copy of StateTrie.
  219. func (t *StateTrie) Copy() *StateTrie {
  220. return &StateTrie{
  221. trie: *t.trie.Copy(),
  222. preimages: t.preimages,
  223. secKeyCache: t.secKeyCache,
  224. }
  225. }
  226. // NodeIterator returns an iterator that returns nodes of the underlying trie. Iteration
  227. // starts at the key after the given start key.
  228. func (t *StateTrie) NodeIterator(start []byte) NodeIterator {
  229. return t.trie.NodeIterator(start)
  230. }
  231. // hashKey returns the hash of key as an ephemeral buffer.
  232. // The caller must not hold onto the return value because it will become
  233. // invalid on the next call to hashKey or secKey.
  234. func (t *StateTrie) hashKey(key []byte) []byte {
  235. h := newHasher(false)
  236. h.sha.Reset()
  237. h.sha.Write(key)
  238. h.sha.Read(t.hashKeyBuf[:])
  239. returnHasherToPool(h)
  240. return t.hashKeyBuf[:]
  241. }
  242. // getSecKeyCache returns the current secure key cache, creating a new one if
  243. // ownership changed (i.e. the current secure trie is a copy of another owning
  244. // the actual cache).
  245. func (t *StateTrie) getSecKeyCache() map[string][]byte {
  246. if t != t.secKeyCacheOwner {
  247. t.secKeyCacheOwner = t
  248. t.secKeyCache = make(map[string][]byte)
  249. }
  250. return t.secKeyCache
  251. }