github.com/googgoog/go-ethereum@v1.9.7/trie/secure_trie.go (about) 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 17 package trie 18 19 import ( 20 "fmt" 21 22 "github.com/ethereum/go-ethereum/common" 23 "github.com/ethereum/go-ethereum/log" 24 ) 25 26 // SecureTrie wraps a trie with key hashing. In a secure trie, all 27 // access operations hash the key using keccak256. This prevents 28 // calling code from creating long chains of nodes that 29 // increase the access time. 30 // 31 // Contrary to a regular trie, a SecureTrie can only be created with 32 // New and must have an attached database. The database also stores 33 // the preimage of each key. 34 // 35 // SecureTrie is not safe for concurrent use. 36 type SecureTrie struct { 37 trie Trie 38 hashKeyBuf [common.HashLength]byte 39 secKeyCache map[string][]byte 40 secKeyCacheOwner *SecureTrie // Pointer to self, replace the key cache on mismatch 41 } 42 43 // NewSecure creates a trie with an existing root node from a backing database 44 // and optional intermediate in-memory node pool. 45 // 46 // If root is the zero hash or the sha3 hash of an empty string, the 47 // trie is initially empty. Otherwise, New will panic if db is nil 48 // and returns MissingNodeError if the root node cannot be found. 49 // 50 // Accessing the trie loads nodes from the database or node pool on demand. 51 // Loaded nodes are kept around until their 'cache generation' expires. 52 // A new cache generation is created by each call to Commit. 53 // cachelimit sets the number of past cache generations to keep. 54 func NewSecure(root common.Hash, db *Database) (*SecureTrie, error) { 55 if db == nil { 56 panic("trie.NewSecure called without a database") 57 } 58 trie, err := New(root, db) 59 if err != nil { 60 return nil, err 61 } 62 return &SecureTrie{trie: *trie}, nil 63 } 64 65 // Get returns the value for key stored in the trie. 66 // The value bytes must not be modified by the caller. 67 func (t *SecureTrie) Get(key []byte) []byte { 68 res, err := t.TryGet(key) 69 if err != nil { 70 log.Error(fmt.Sprintf("Unhandled trie error: %v", err)) 71 } 72 return res 73 } 74 75 // TryGet returns the value for key stored in the trie. 76 // The value bytes must not be modified by the caller. 77 // If a node was not found in the database, a MissingNodeError is returned. 78 func (t *SecureTrie) TryGet(key []byte) ([]byte, error) { 79 return t.trie.TryGet(t.hashKey(key)) 80 } 81 82 // Update associates key with value in the trie. Subsequent calls to 83 // Get will return value. If value has length zero, any existing value 84 // is deleted from the trie and calls to Get will return nil. 85 // 86 // The value bytes must not be modified by the caller while they are 87 // stored in the trie. 88 func (t *SecureTrie) Update(key, value []byte) { 89 if err := t.TryUpdate(key, value); err != nil { 90 log.Error(fmt.Sprintf("Unhandled trie error: %v", err)) 91 } 92 } 93 94 // TryUpdate associates key with value in the trie. Subsequent calls to 95 // Get will return value. If value has length zero, any existing value 96 // is deleted from the trie and calls to Get will return nil. 97 // 98 // The value bytes must not be modified by the caller while they are 99 // stored in the trie. 100 // 101 // If a node was not found in the database, a MissingNodeError is returned. 102 func (t *SecureTrie) TryUpdate(key, value []byte) error { 103 hk := t.hashKey(key) 104 err := t.trie.TryUpdate(hk, value) 105 if err != nil { 106 return err 107 } 108 t.getSecKeyCache()[string(hk)] = common.CopyBytes(key) 109 return nil 110 } 111 112 // Delete removes any existing value for key from the trie. 113 func (t *SecureTrie) Delete(key []byte) { 114 if err := t.TryDelete(key); err != nil { 115 log.Error(fmt.Sprintf("Unhandled trie error: %v", err)) 116 } 117 } 118 119 // TryDelete removes any existing value for key from the trie. 120 // If a node was not found in the database, a MissingNodeError is returned. 121 func (t *SecureTrie) TryDelete(key []byte) error { 122 hk := t.hashKey(key) 123 delete(t.getSecKeyCache(), string(hk)) 124 return t.trie.TryDelete(hk) 125 } 126 127 // GetKey returns the sha3 preimage of a hashed key that was 128 // previously used to store a value. 129 func (t *SecureTrie) GetKey(shaKey []byte) []byte { 130 if key, ok := t.getSecKeyCache()[string(shaKey)]; ok { 131 return key 132 } 133 key, _ := t.trie.db.preimage(common.BytesToHash(shaKey)) 134 return key 135 } 136 137 // Commit writes all nodes and the secure hash pre-images to the trie's database. 138 // Nodes are stored with their sha3 hash as the key. 139 // 140 // Committing flushes nodes from memory. Subsequent Get calls will load nodes 141 // from the database. 142 func (t *SecureTrie) Commit(onleaf LeafCallback) (root common.Hash, err error) { 143 // Write all the pre-images to the actual disk database 144 if len(t.getSecKeyCache()) > 0 { 145 t.trie.db.lock.Lock() 146 for hk, key := range t.secKeyCache { 147 t.trie.db.insertPreimage(common.BytesToHash([]byte(hk)), key) 148 } 149 t.trie.db.lock.Unlock() 150 151 t.secKeyCache = make(map[string][]byte) 152 } 153 // Commit the trie to its intermediate node database 154 return t.trie.Commit(onleaf) 155 } 156 157 // Hash returns the root hash of SecureTrie. It does not write to the 158 // database and can be used even if the trie doesn't have one. 159 func (t *SecureTrie) Hash() common.Hash { 160 return t.trie.Hash() 161 } 162 163 // Copy returns a copy of SecureTrie. 164 func (t *SecureTrie) Copy() *SecureTrie { 165 cpy := *t 166 return &cpy 167 } 168 169 // NodeIterator returns an iterator that returns nodes of the underlying trie. Iteration 170 // starts at the key after the given start key. 171 func (t *SecureTrie) NodeIterator(start []byte) NodeIterator { 172 return t.trie.NodeIterator(start) 173 } 174 175 // hashKey returns the hash of key as an ephemeral buffer. 176 // The caller must not hold onto the return value because it will become 177 // invalid on the next call to hashKey or secKey. 178 func (t *SecureTrie) hashKey(key []byte) []byte { 179 h := newHasher(nil) 180 h.sha.Reset() 181 h.sha.Write(key) 182 buf := h.sha.Sum(t.hashKeyBuf[:0]) 183 returnHasherToPool(h) 184 return buf 185 } 186 187 // getSecKeyCache returns the current secure key cache, creating a new one if 188 // ownership changed (i.e. the current secure trie is a copy of another owning 189 // the actual cache). 190 func (t *SecureTrie) getSecKeyCache() map[string][]byte { 191 if t != t.secKeyCacheOwner { 192 t.secKeyCacheOwner = t 193 t.secKeyCache = make(map[string][]byte) 194 } 195 return t.secKeyCache 196 }