github.com/annchain/OG@v0.0.9/trie/trie.go (about) 1 // Copyright 2014 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 implements Merkle Patricia Tries. 18 package trie 19 20 import ( 21 "bytes" 22 "fmt" 23 "github.com/annchain/OG/arefactor/og/types" 24 ogcrypto2 "github.com/annchain/OG/deprecated/ogcrypto" 25 "github.com/annchain/OG/metrics" 26 log "github.com/sirupsen/logrus" 27 ) 28 29 var ( 30 // emptyRoot is the known root hash of an empty trie. 31 emptyRoot = types.HexToHashNoError("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421") 32 33 // emptyState is the known hash of an empty state trie entry. 34 emptyState = ogcrypto2.Keccak256Hash(nil) 35 ) 36 37 var ( 38 cacheMissCounter = metrics.NewRegisteredCounter("trie/cachemiss", nil) 39 cacheUnloadCounter = metrics.NewRegisteredCounter("trie/cacheunload", nil) 40 ) 41 42 // CacheMisses retrieves a global counter measuring the number of cache misses 43 // the trie had since process startup. This isn't useful for anything apart from 44 // trie debugging purposes. 45 func CacheMisses() int64 { 46 return cacheMissCounter.Count() 47 } 48 49 // CacheUnloads retrieves a global counter measuring the number of cache unloads 50 // the trie did since process startup. This isn't useful for anything apart from 51 // trie debugging purposes. 52 func CacheUnloads() int64 { 53 return cacheUnloadCounter.Count() 54 } 55 56 // LeafCallback is a callback type invoked when a trie operation reaches a leaf 57 // node. It's used by state sync and commit to allow handling external references 58 // between account and storage tries. 59 type LeafCallback func(leaf []byte, parent types.Hash) error 60 61 // Trie is a Merkle Patricia Trie. 62 // The zero value is an empty trie with no database. 63 // Use New to create a trie that sits on top of a database. 64 // 65 // Trie is not safe for concurrent use. 66 type Trie struct { 67 db *Database 68 root Node 69 originalRoot types.Hash 70 71 // Cache generation values. 72 // cachegen increases by one with each commit operation. 73 // new nodes are tagged with the current generation and unloaded 74 // when their generation is older than than cachegen-cachelimit. 75 cachegen, cachelimit uint16 76 } 77 78 // SetCacheLimit sets the number of 'cache generations' to keep. 79 // A cache generation is created by a call to Commit. 80 func (t *Trie) SetCacheLimit(l uint16) { 81 t.cachelimit = l 82 } 83 84 // newFlag returns the cache flag value for a newly created node. 85 func (t *Trie) newFlag() nodeFlag { 86 return nodeFlag{dirty: true, gen: t.cachegen} 87 } 88 89 // New creates a trie with an existing root node from db. 90 // 91 // If root is the zero hash or the sha3 hash of an empty string, the 92 // trie is initially empty and does not require a database. Otherwise, 93 // New will panic if db is nil and returns a MissingNodeError if root does 94 // not exist in the database. Accessing the trie loads nodes from db on demand. 95 func New(root types.Hash, db *Database) (*Trie, error) { 96 if db == nil { 97 panic("trie.New called without a database") 98 } 99 trie := &Trie{ 100 db: db, 101 originalRoot: root, 102 } 103 if root != (types.Hash{}) && root != emptyRoot { 104 rootnode, err := trie.resolveHash(root.ToBytes(), nil) 105 if err != nil { 106 return nil, err 107 } 108 trie.root = rootnode 109 } 110 return trie, nil 111 } 112 113 // NodeIterator returns an iterator that returns nodes of the trie. Iteration starts at 114 // the key after the given start key. 115 func (t *Trie) NodeIterator(start []byte) NodeIterator { 116 return newNodeIterator(t, start) 117 } 118 119 // Get returns the value for key stored in the trie. 120 // The value bytes must not be modified by the caller. 121 func (t *Trie) Get(key []byte) []byte { 122 res, err := t.TryGet(key) 123 if err != nil { 124 log.Error(fmt.Sprintf("Unhandled trie error: %v", err)) 125 } 126 return res 127 } 128 129 // TryGet returns the value for key stored in the trie. 130 // The value bytes must not be modified by the caller. 131 // If a node was not found in the database, a MissingNodeError is returned. 132 func (t *Trie) TryGet(key []byte) ([]byte, error) { 133 key = keybytesToHex(key) 134 value, newroot, didResolve, err := t.tryGet(t.root, key, 0) 135 if err == nil && didResolve { 136 t.root = newroot 137 } 138 return value, err 139 } 140 141 func (t *Trie) tryGet(origNode Node, key []byte, pos int) (value []byte, newnode Node, didResolve bool, err error) { 142 switch n := (origNode).(type) { 143 case nil: 144 return nil, nil, false, nil 145 case ValueNode: 146 return n, n, false, nil 147 case *ShortNode: 148 if len(key)-pos < len(n.Key) || !bytes.Equal(n.Key, key[pos:pos+len(n.Key)]) { 149 // key not found in trie 150 return nil, n, false, nil 151 } 152 value, newnode, didResolve, err = t.tryGet(n.Val, key, pos+len(n.Key)) 153 if err == nil && didResolve { 154 n = n.copy() 155 n.Val = newnode 156 n.flags.gen = t.cachegen 157 } 158 return value, n, didResolve, err 159 case *FullNode: 160 value, newnode, didResolve, err = t.tryGet(n.Children[key[pos]], key, pos+1) 161 if err == nil && didResolve { 162 n = n.copy() 163 n.flags.gen = t.cachegen 164 n.Children[key[pos]] = newnode 165 } 166 return value, n, didResolve, err 167 case HashNode: 168 child, err := t.resolveHash(n, key[:pos]) 169 if err != nil { 170 return nil, n, true, err 171 } 172 value, newnode, _, err := t.tryGet(child, key, pos) 173 return value, newnode, true, err 174 default: 175 panic(fmt.Sprintf("%T: invalid node: %v", origNode, origNode)) 176 } 177 } 178 179 // Update associates key with value in the trie. Subsequent calls to 180 // Get will return value. If value has length zero, any existing value 181 // is deleted from the trie and calls to Get will return nil. 182 // 183 // The value bytes must not be modified by the caller while they are 184 // stored in the trie. 185 func (t *Trie) Update(key, value []byte) { 186 if err := t.TryUpdate(key, value); err != nil { 187 log.Error(fmt.Sprintf("Unhandled trie error: %v", err)) 188 } 189 } 190 191 // TryUpdate associates key with value in the trie. Subsequent calls to 192 // Get will return value. If value has length zero, any existing value 193 // is deleted from the trie and calls to Get will return nil. 194 // 195 // The value bytes must not be modified by the caller while they are 196 // stored in the trie. 197 // 198 // If a node was not found in the database, a MissingNodeError is returned. 199 func (t *Trie) TryUpdate(key, value []byte) error { 200 k := keybytesToHex(key) 201 if len(value) != 0 { 202 _, n, err := t.insert(t.root, nil, k, ValueNode(value)) 203 if err != nil { 204 return err 205 } 206 t.root = n 207 } else { 208 _, n, err := t.delete(t.root, nil, k) 209 if err != nil { 210 return err 211 } 212 t.root = n 213 } 214 return nil 215 } 216 217 func (t *Trie) insert(n Node, prefix, key []byte, value Node) (bool, Node, error) { 218 //log.Tracef("Panic debug, start insert, prefix: %x, key: %x", prefix, key) 219 if len(key) == 0 { 220 if v, ok := n.(ValueNode); ok { 221 return !bytes.Equal(v, value.(ValueNode)), value, nil 222 } 223 return true, value, nil 224 } 225 switch n := n.(type) { 226 case *ShortNode: 227 //log.Tracef("Panic debug, insert meet Shortnode, shortnode key: %x, key: %x", n.Key, key) 228 matchlen := prefixLen(key, n.Key) 229 // If the whole key matches, keep this short node as is 230 // and only update the value. 231 if matchlen == len(n.Key) { 232 dirty, nn, err := t.insert(n.Val, append(prefix, key[:matchlen]...), key[matchlen:], value) 233 if !dirty || err != nil { 234 return false, n, err 235 } 236 sn := &ShortNode{n.Key, nn, t.newFlag()} 237 return true, sn, nil 238 } 239 // Otherwise branch out at the index where they differ. 240 branch := &FullNode{flags: t.newFlag()} 241 var err error 242 _, branch.Children[n.Key[matchlen]], err = t.insert(nil, append(prefix, n.Key[:matchlen+1]...), n.Key[matchlen+1:], n.Val) 243 if err != nil { 244 return false, nil, err 245 } 246 _, branch.Children[key[matchlen]], err = t.insert(nil, append(prefix, key[:matchlen+1]...), key[matchlen+1:], value) 247 if err != nil { 248 return false, nil, err 249 } 250 // Replace this shortNode with the branch if it occurs at index 0. 251 if matchlen == 0 { 252 return true, branch, nil 253 } 254 // Otherwise, replace it with a short node leading up to the branch. 255 sn := &ShortNode{key[:matchlen], branch, t.newFlag()} 256 return true, sn, nil 257 258 case *FullNode: 259 //log.Tracef("Panic debug, insert meet FullNode, key: %x", key) 260 dirty, nn, err := t.insert(n.Children[key[0]], append(prefix, key[0]), key[1:], value) 261 if !dirty || err != nil { 262 return false, n, err 263 } 264 n = n.copy() 265 n.flags = t.newFlag() 266 n.Children[key[0]] = nn 267 return true, n, nil 268 269 case nil: 270 //log.Tracef("Panic debug, insert meet nil, key: %x", key) 271 sn := &ShortNode{key, value, t.newFlag()} 272 return true, sn, nil 273 274 case HashNode: 275 // We've hit a part of the trie that isn't loaded yet. Load 276 // the node and insert into it. This leaves all child nodes on 277 // the path to the value in the trie. 278 279 //log.Tracef("Panic debug, insert meet HashNode, key: %x", key) 280 rn, err := t.resolveHash(n, prefix) 281 if err != nil { 282 return false, nil, err 283 } 284 dirty, nn, err := t.insert(rn, prefix, key, value) 285 if !dirty || err != nil { 286 return false, rn, err 287 } 288 return true, nn, nil 289 290 default: 291 panic(fmt.Sprintf("%T: invalid node: %v", n, n)) 292 } 293 } 294 295 // Delete removes any existing value for key from the trie. 296 func (t *Trie) Delete(key []byte) { 297 if err := t.TryDelete(key); err != nil { 298 log.Error(fmt.Sprintf("Unhandled trie error: %v", err)) 299 } 300 } 301 302 // TryDelete removes any existing value for key from the trie. 303 // If a node was not found in the database, a MissingNodeError is returned. 304 func (t *Trie) TryDelete(key []byte) error { 305 k := keybytesToHex(key) 306 _, n, err := t.delete(t.root, nil, k) 307 if err != nil { 308 return err 309 } 310 t.root = n 311 return nil 312 } 313 314 // delete returns the new root of the trie with key deleted. 315 // It reduces the trie to minimal form by simplifying 316 // nodes on the way up after deleting recursively. 317 func (t *Trie) delete(n Node, prefix, key []byte) (bool, Node, error) { 318 switch n := n.(type) { 319 case *ShortNode: 320 matchlen := prefixLen(key, n.Key) 321 if matchlen < len(n.Key) { 322 return false, n, nil // don't replace n on mismatch 323 } 324 if matchlen == len(key) { 325 return true, nil, nil // remove n entirely for whole matches 326 } 327 // The key is longer than n.Key. Remove the remaining suffix 328 // from the subtrie. Child can never be nil here since the 329 // subtrie must contain at least two other values with keys 330 // longer than n.Key. 331 dirty, child, err := t.delete(n.Val, append(prefix, key[:len(n.Key)]...), key[len(n.Key):]) 332 if !dirty || err != nil { 333 return false, n, err 334 } 335 switch child := child.(type) { 336 case *ShortNode: 337 // Deleting from the subtrie reduced it to another 338 // short node. Merge the nodes to avoid creating a 339 // shortNode{..., shortNode{...}}. Use concat (which 340 // always creates a new slice) instead of append to 341 // avoid modifying n.Key since it might be shared with 342 // other nodes. 343 return true, &ShortNode{concat(n.Key, child.Key...), child.Val, t.newFlag()}, nil 344 default: 345 return true, &ShortNode{n.Key, child, t.newFlag()}, nil 346 } 347 348 case *FullNode: 349 dirty, nn, err := t.delete(n.Children[key[0]], append(prefix, key[0]), key[1:]) 350 if !dirty || err != nil { 351 return false, n, err 352 } 353 n = n.copy() 354 n.flags = t.newFlag() 355 n.Children[key[0]] = nn 356 357 // Check how many non-nil entries are left after deleting and 358 // reduce the full node to a short node if only one entry is 359 // left. Since n must've contained at least two children 360 // before deletion (otherwise it would not be a full node) n 361 // can never be reduced to nil. 362 // 363 // When the loop is done, pos contains the index of the single 364 // value that is left in n or -2 if n contains at least two 365 // values. 366 pos := -1 367 for i, cld := range n.Children { 368 if cld != nil { 369 if pos == -1 { 370 pos = i 371 } else { 372 pos = -2 373 break 374 } 375 } 376 } 377 if pos >= 0 { 378 if pos != 16 { 379 // If the remaining entry is a short node, it replaces 380 // n and its key gets the missing nibble tacked to the 381 // front. This avoids creating an invalid 382 // shortNode{..., shortNode{...}}. Since the entry 383 // might not be loaded yet, resolve it just for this 384 // check. 385 cnode, err := t.resolve(n.Children[pos], prefix) 386 if err != nil { 387 return false, nil, err 388 } 389 if cnode, ok := cnode.(*ShortNode); ok { 390 k := append([]byte{byte(pos)}, cnode.Key...) 391 return true, &ShortNode{k, cnode.Val, t.newFlag()}, nil 392 } 393 } 394 // Otherwise, n is replaced by a one-nibble short node 395 // containing the child. 396 return true, &ShortNode{[]byte{byte(pos)}, n.Children[pos], t.newFlag()}, nil 397 } 398 // n still contains at least two values and cannot be reduced. 399 return true, n, nil 400 401 case ValueNode: 402 return true, nil, nil 403 404 case nil: 405 return false, nil, nil 406 407 case HashNode: 408 // We've hit a part of the trie that isn't loaded yet. Load 409 // the node and delete from it. This leaves all child nodes on 410 // the path to the value in the trie. 411 rn, err := t.resolveHash(n, prefix) 412 if err != nil { 413 return false, nil, err 414 } 415 dirty, nn, err := t.delete(rn, prefix, key) 416 if !dirty || err != nil { 417 return false, rn, err 418 } 419 return true, nn, nil 420 421 default: 422 panic(fmt.Sprintf("%T: invalid node: %v (%v)", n, n, key)) 423 } 424 } 425 426 func concat(s1 []byte, s2 ...byte) []byte { 427 r := make([]byte, len(s1)+len(s2)) 428 copy(r, s1) 429 copy(r[len(s1):], s2) 430 return r 431 } 432 433 func (t *Trie) resolve(n Node, prefix []byte) (Node, error) { 434 if n, ok := n.(HashNode); ok { 435 return t.resolveHash(n, prefix) 436 } 437 return n, nil 438 } 439 440 func (t *Trie) resolveHash(n HashNode, prefix []byte) (Node, error) { 441 cacheMissCounter.Inc(1) 442 443 hash := types.BytesToHash(n) 444 445 enc, err := t.db.Node(hash) 446 if err != nil || enc == nil { 447 return nil, &MissingNodeError{NodeHash: hash, Path: prefix} 448 } 449 return mustDecodeNode(n, enc, t.cachegen), nil 450 } 451 452 // Root returns the root hash of the trie. 453 // Deprecated: use Hash instead. 454 func (t *Trie) Root() []byte { return t.Hash().ToBytes() } 455 456 // Hash returns the root hash of the trie. It does not write to the 457 // database and can be used even if the trie doesn't have one. 458 func (t *Trie) Hash() types.Hash { 459 hash, cached, _ := t.hashRoot(nil, nil, false) 460 t.root = cached 461 return types.BytesToHash(hash.(HashNode)) 462 } 463 464 // Commit writes all nodes to the trie's memory database, tracking the internal 465 // and external (for account tries) references. 466 func (t *Trie) Commit(onleaf LeafCallback, preCommit bool) (root types.Hash, err error) { 467 if t.db == nil { 468 panic("commit called on trie with nil database") 469 } 470 hash, cached, err := t.hashRoot(t.db, onleaf, preCommit) 471 if err != nil { 472 return types.Hash{}, err 473 } 474 t.root = cached 475 t.cachegen++ 476 return types.BytesToHash(hash.(HashNode)), nil 477 } 478 479 func (t *Trie) hashRoot(db *Database, onleaf LeafCallback, preHash bool) (Node, Node, error) { 480 if t.root == nil { 481 return HashNode(emptyRoot.ToBytes()), nil, nil 482 } 483 h := newHasher(t.cachegen, t.cachelimit, onleaf) 484 defer returnHasherToPool(h) 485 return h.hash(t.root, db, true, preHash) 486 }