secure_trie.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. "github.com/ethereum/go-ethereum/common"
  19. "github.com/ethereum/go-ethereum/logger"
  20. "github.com/ethereum/go-ethereum/logger/glog"
  21. )
  22. var secureKeyPrefix = []byte("secure-key-")
  23. // SecureTrie wraps a trie with key hashing. In a secure trie, all
  24. // access operations hash the key using keccak256. This prevents
  25. // calling code from creating long chains of nodes that
  26. // increase the access time.
  27. //
  28. // Contrary to a regular trie, a SecureTrie can only be created with
  29. // New and must have an attached database. The database also stores
  30. // the preimage of each key.
  31. //
  32. // SecureTrie is not safe for concurrent use.
  33. type SecureTrie struct {
  34. trie Trie
  35. hashKeyBuf []byte
  36. secKeyBuf [200]byte
  37. secKeyCache map[string][]byte
  38. }
  39. // NewSecure creates a trie with an existing root node from db.
  40. //
  41. // If root is the zero hash or the sha3 hash of an empty string, the
  42. // trie is initially empty. Otherwise, New will panic if db is nil
  43. // and returns MissingNodeError if the root node cannot be found.
  44. // Accessing the trie loads nodes from db on demand.
  45. func NewSecure(root common.Hash, db Database) (*SecureTrie, error) {
  46. if db == nil {
  47. panic("NewSecure called with nil database")
  48. }
  49. trie, err := New(root, db)
  50. if err != nil {
  51. return nil, err
  52. }
  53. return &SecureTrie{
  54. trie: *trie,
  55. secKeyCache: make(map[string][]byte),
  56. }, nil
  57. }
  58. // Get returns the value for key stored in the trie.
  59. // The value bytes must not be modified by the caller.
  60. func (t *SecureTrie) Get(key []byte) []byte {
  61. res, err := t.TryGet(key)
  62. if err != nil && glog.V(logger.Error) {
  63. glog.Errorf("Unhandled trie error: %v", err)
  64. }
  65. return res
  66. }
  67. // TryGet returns the value for key stored in the trie.
  68. // The value bytes must not be modified by the caller.
  69. // If a node was not found in the database, a MissingNodeError is returned.
  70. func (t *SecureTrie) TryGet(key []byte) ([]byte, error) {
  71. return t.trie.TryGet(t.hashKey(key))
  72. }
  73. // Update associates key with value in the trie. Subsequent calls to
  74. // Get will return value. If value has length zero, any existing value
  75. // is deleted from the trie and calls to Get will return nil.
  76. //
  77. // The value bytes must not be modified by the caller while they are
  78. // stored in the trie.
  79. func (t *SecureTrie) Update(key, value []byte) {
  80. if err := t.TryUpdate(key, value); err != nil && glog.V(logger.Error) {
  81. glog.Errorf("Unhandled trie error: %v", err)
  82. }
  83. }
  84. // TryUpdate associates key with value in the trie. Subsequent calls to
  85. // Get will return value. If value has length zero, any existing value
  86. // is deleted from the trie and calls to Get will return nil.
  87. //
  88. // The value bytes must not be modified by the caller while they are
  89. // stored in the trie.
  90. //
  91. // If a node was not found in the database, a MissingNodeError is returned.
  92. func (t *SecureTrie) TryUpdate(key, value []byte) error {
  93. hk := t.hashKey(key)
  94. err := t.trie.TryUpdate(hk, value)
  95. if err != nil {
  96. return err
  97. }
  98. t.secKeyCache[string(hk)] = common.CopyBytes(key)
  99. return nil
  100. }
  101. // Delete removes any existing value for key from the trie.
  102. func (t *SecureTrie) Delete(key []byte) {
  103. if err := t.TryDelete(key); err != nil && glog.V(logger.Error) {
  104. glog.Errorf("Unhandled trie error: %v", err)
  105. }
  106. }
  107. // TryDelete removes any existing value for key from the trie.
  108. // If a node was not found in the database, a MissingNodeError is returned.
  109. func (t *SecureTrie) TryDelete(key []byte) error {
  110. hk := t.hashKey(key)
  111. delete(t.secKeyCache, string(hk))
  112. return t.trie.TryDelete(hk)
  113. }
  114. // GetKey returns the sha3 preimage of a hashed key that was
  115. // previously used to store a value.
  116. func (t *SecureTrie) GetKey(shaKey []byte) []byte {
  117. if key, ok := t.secKeyCache[string(shaKey)]; ok {
  118. return key
  119. }
  120. key, _ := t.trie.db.Get(t.secKey(shaKey))
  121. return key
  122. }
  123. // Commit writes all nodes and the secure hash pre-images to the trie's database.
  124. // Nodes are stored with their sha3 hash as the key.
  125. //
  126. // Committing flushes nodes from memory. Subsequent Get calls will load nodes
  127. // from the database.
  128. func (t *SecureTrie) Commit() (root common.Hash, err error) {
  129. return t.CommitTo(t.trie.db)
  130. }
  131. func (t *SecureTrie) Hash() common.Hash {
  132. return t.trie.Hash()
  133. }
  134. func (t *SecureTrie) Root() []byte {
  135. return t.trie.Root()
  136. }
  137. func (t *SecureTrie) Iterator() *Iterator {
  138. return t.trie.Iterator()
  139. }
  140. func (t *SecureTrie) NodeIterator() *NodeIterator {
  141. return NewNodeIterator(&t.trie)
  142. }
  143. // CommitTo writes all nodes and the secure hash pre-images to the given database.
  144. // Nodes are stored with their sha3 hash as the key.
  145. //
  146. // Committing flushes nodes from memory. Subsequent Get calls will load nodes from
  147. // the trie's database. Calling code must ensure that the changes made to db are
  148. // written back to the trie's attached database before using the trie.
  149. func (t *SecureTrie) CommitTo(db DatabaseWriter) (root common.Hash, err error) {
  150. if len(t.secKeyCache) > 0 {
  151. for hk, key := range t.secKeyCache {
  152. if err := db.Put(t.secKey([]byte(hk)), key); err != nil {
  153. return common.Hash{}, err
  154. }
  155. }
  156. t.secKeyCache = make(map[string][]byte)
  157. }
  158. return t.trie.CommitTo(db)
  159. }
  160. // secKey returns the database key for the preimage of key, as an ephemeral buffer.
  161. // The caller must not hold onto the return value because it will become
  162. // invalid on the next call to hashKey or secKey.
  163. func (t *SecureTrie) secKey(key []byte) []byte {
  164. buf := append(t.secKeyBuf[:0], secureKeyPrefix...)
  165. buf = append(buf, key...)
  166. return buf
  167. }
  168. // hashKey returns the hash of key as an ephemeral buffer.
  169. // The caller must not hold onto the return value because it will become
  170. // invalid on the next call to hashKey or secKey.
  171. func (t *SecureTrie) hashKey(key []byte) []byte {
  172. h := newHasher()
  173. h.sha.Reset()
  174. h.sha.Write(key)
  175. buf := h.sha.Sum(t.hashKeyBuf[:0])
  176. returnHasherToPool(h)
  177. return buf
  178. }