trie.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. // Package trie implements Merkle Patricia Tries.
  17. package trie
  18. import (
  19. "bytes"
  20. "fmt"
  21. "hash"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/crypto/sha3"
  25. "github.com/ethereum/go-ethereum/logger"
  26. "github.com/ethereum/go-ethereum/logger/glog"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. )
  29. const defaultCacheCapacity = 800
  30. var (
  31. // The global cache stores decoded trie nodes by hash as they get loaded.
  32. globalCache = newARC(defaultCacheCapacity)
  33. // This is the known root hash of an empty trie.
  34. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  35. // This is the known hash of an empty state trie entry.
  36. emptyState = crypto.Keccak256Hash(nil)
  37. )
  38. // ClearGlobalCache clears the global trie cache
  39. func ClearGlobalCache() {
  40. globalCache.Clear()
  41. }
  42. // Database must be implemented by backing stores for the trie.
  43. type Database interface {
  44. DatabaseWriter
  45. // Get returns the value for key from the database.
  46. Get(key []byte) (value []byte, err error)
  47. }
  48. // DatabaseWriter wraps the Put method of a backing store for the trie.
  49. type DatabaseWriter interface {
  50. // Put stores the mapping key->value in the database.
  51. // Implementations must not hold onto the value bytes, the trie
  52. // will reuse the slice across calls to Put.
  53. Put(key, value []byte) error
  54. }
  55. // Trie is a Merkle Patricia Trie.
  56. // The zero value is an empty trie with no database.
  57. // Use New to create a trie that sits on top of a database.
  58. //
  59. // Trie is not safe for concurrent use.
  60. type Trie struct {
  61. root node
  62. db Database
  63. originalRoot common.Hash
  64. *hasher
  65. }
  66. // New creates a trie with an existing root node from db.
  67. //
  68. // If root is the zero hash or the sha3 hash of an empty string, the
  69. // trie is initially empty and does not require a database. Otherwise,
  70. // New will panic if db is nil and returns a MissingNodeError if root does
  71. // not exist in the database. Accessing the trie loads nodes from db on demand.
  72. func New(root common.Hash, db Database) (*Trie, error) {
  73. trie := &Trie{db: db, originalRoot: root}
  74. if (root != common.Hash{}) && root != emptyRoot {
  75. if db == nil {
  76. panic("trie.New: cannot use existing root without a database")
  77. }
  78. if v, _ := trie.db.Get(root[:]); len(v) == 0 {
  79. return nil, &MissingNodeError{
  80. RootHash: root,
  81. NodeHash: root,
  82. }
  83. }
  84. trie.root = hashNode(root.Bytes())
  85. }
  86. return trie, nil
  87. }
  88. // Iterator returns an iterator over all mappings in the trie.
  89. func (t *Trie) Iterator() *Iterator {
  90. return NewIterator(t)
  91. }
  92. // Get returns the value for key stored in the trie.
  93. // The value bytes must not be modified by the caller.
  94. func (t *Trie) Get(key []byte) []byte {
  95. res, err := t.TryGet(key)
  96. if err != nil && glog.V(logger.Error) {
  97. glog.Errorf("Unhandled trie error: %v", err)
  98. }
  99. return res
  100. }
  101. // TryGet returns the value for key stored in the trie.
  102. // The value bytes must not be modified by the caller.
  103. // If a node was not found in the database, a MissingNodeError is returned.
  104. func (t *Trie) TryGet(key []byte) ([]byte, error) {
  105. key = compactHexDecode(key)
  106. pos := 0
  107. tn := t.root
  108. for pos < len(key) {
  109. switch n := tn.(type) {
  110. case shortNode:
  111. if len(key)-pos < len(n.Key) || !bytes.Equal(n.Key, key[pos:pos+len(n.Key)]) {
  112. return nil, nil
  113. }
  114. tn = n.Val
  115. pos += len(n.Key)
  116. case fullNode:
  117. tn = n.Children[key[pos]]
  118. pos++
  119. case nil:
  120. return nil, nil
  121. case hashNode:
  122. var err error
  123. tn, err = t.resolveHash(n, key[:pos], key[pos:])
  124. if err != nil {
  125. return nil, err
  126. }
  127. default:
  128. panic(fmt.Sprintf("%T: invalid node: %v", tn, tn))
  129. }
  130. }
  131. return tn.(valueNode), 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 *Trie) Update(key, value []byte) {
  140. if err := t.TryUpdate(key, value); err != nil && glog.V(logger.Error) {
  141. glog.Errorf("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 *Trie) TryUpdate(key, value []byte) error {
  153. k := compactHexDecode(key)
  154. if len(value) != 0 {
  155. _, n, err := t.insert(t.root, nil, k, valueNode(value))
  156. if err != nil {
  157. return err
  158. }
  159. t.root = n
  160. } else {
  161. _, n, err := t.delete(t.root, nil, k)
  162. if err != nil {
  163. return err
  164. }
  165. t.root = n
  166. }
  167. return nil
  168. }
  169. func (t *Trie) insert(n node, prefix, key []byte, value node) (bool, node, error) {
  170. if len(key) == 0 {
  171. if v, ok := n.(valueNode); ok {
  172. return !bytes.Equal(v, value.(valueNode)), value, nil
  173. }
  174. return true, value, nil
  175. }
  176. switch n := n.(type) {
  177. case shortNode:
  178. matchlen := prefixLen(key, n.Key)
  179. // If the whole key matches, keep this short node as is
  180. // and only update the value.
  181. if matchlen == len(n.Key) {
  182. dirty, nn, err := t.insert(n.Val, append(prefix, key[:matchlen]...), key[matchlen:], value)
  183. if err != nil {
  184. return false, nil, err
  185. }
  186. if !dirty {
  187. return false, n, nil
  188. }
  189. return true, shortNode{n.Key, nn, nil, true}, nil
  190. }
  191. // Otherwise branch out at the index where they differ.
  192. branch := fullNode{dirty: true}
  193. var err error
  194. _, branch.Children[n.Key[matchlen]], err = t.insert(nil, append(prefix, n.Key[:matchlen+1]...), n.Key[matchlen+1:], n.Val)
  195. if err != nil {
  196. return false, nil, err
  197. }
  198. _, branch.Children[key[matchlen]], err = t.insert(nil, append(prefix, key[:matchlen+1]...), key[matchlen+1:], value)
  199. if err != nil {
  200. return false, nil, err
  201. }
  202. // Replace this shortNode with the branch if it occurs at index 0.
  203. if matchlen == 0 {
  204. return true, branch, nil
  205. }
  206. // Otherwise, replace it with a short node leading up to the branch.
  207. return true, shortNode{key[:matchlen], branch, nil, true}, nil
  208. case fullNode:
  209. dirty, nn, err := t.insert(n.Children[key[0]], append(prefix, key[0]), key[1:], value)
  210. if err != nil {
  211. return false, nil, err
  212. }
  213. if !dirty {
  214. return false, n, nil
  215. }
  216. n.Children[key[0]], n.hash, n.dirty = nn, nil, true
  217. return true, n, nil
  218. case nil:
  219. return true, shortNode{key, value, nil, true}, nil
  220. case hashNode:
  221. // We've hit a part of the trie that isn't loaded yet. Load
  222. // the node and insert into it. This leaves all child nodes on
  223. // the path to the value in the trie.
  224. rn, err := t.resolveHash(n, prefix, key)
  225. if err != nil {
  226. return false, nil, err
  227. }
  228. dirty, nn, err := t.insert(rn, prefix, key, value)
  229. if err != nil {
  230. return false, nil, err
  231. }
  232. if !dirty {
  233. return false, rn, nil
  234. }
  235. return true, nn, nil
  236. default:
  237. panic(fmt.Sprintf("%T: invalid node: %v", n, n))
  238. }
  239. }
  240. // Delete removes any existing value for key from the trie.
  241. func (t *Trie) Delete(key []byte) {
  242. if err := t.TryDelete(key); err != nil && glog.V(logger.Error) {
  243. glog.Errorf("Unhandled trie error: %v", err)
  244. }
  245. }
  246. // TryDelete removes any existing value for key from the trie.
  247. // If a node was not found in the database, a MissingNodeError is returned.
  248. func (t *Trie) TryDelete(key []byte) error {
  249. k := compactHexDecode(key)
  250. _, n, err := t.delete(t.root, nil, k)
  251. if err != nil {
  252. return err
  253. }
  254. t.root = n
  255. return nil
  256. }
  257. // delete returns the new root of the trie with key deleted.
  258. // It reduces the trie to minimal form by simplifying
  259. // nodes on the way up after deleting recursively.
  260. func (t *Trie) delete(n node, prefix, key []byte) (bool, node, error) {
  261. switch n := n.(type) {
  262. case shortNode:
  263. matchlen := prefixLen(key, n.Key)
  264. if matchlen < len(n.Key) {
  265. return false, n, nil // don't replace n on mismatch
  266. }
  267. if matchlen == len(key) {
  268. return true, nil, nil // remove n entirely for whole matches
  269. }
  270. // The key is longer than n.Key. Remove the remaining suffix
  271. // from the subtrie. Child can never be nil here since the
  272. // subtrie must contain at least two other values with keys
  273. // longer than n.Key.
  274. dirty, child, err := t.delete(n.Val, append(prefix, key[:len(n.Key)]...), key[len(n.Key):])
  275. if err != nil {
  276. return false, nil, err
  277. }
  278. if !dirty {
  279. return false, n, nil
  280. }
  281. switch child := child.(type) {
  282. case shortNode:
  283. // Deleting from the subtrie reduced it to another
  284. // short node. Merge the nodes to avoid creating a
  285. // shortNode{..., shortNode{...}}. Use concat (which
  286. // always creates a new slice) instead of append to
  287. // avoid modifying n.Key since it might be shared with
  288. // other nodes.
  289. return true, shortNode{concat(n.Key, child.Key...), child.Val, nil, true}, nil
  290. default:
  291. return true, shortNode{n.Key, child, nil, true}, nil
  292. }
  293. case fullNode:
  294. dirty, nn, err := t.delete(n.Children[key[0]], append(prefix, key[0]), key[1:])
  295. if err != nil {
  296. return false, nil, err
  297. }
  298. if !dirty {
  299. return false, n, nil
  300. }
  301. n.Children[key[0]], n.hash, n.dirty = nn, nil, true
  302. // Check how many non-nil entries are left after deleting and
  303. // reduce the full node to a short node if only one entry is
  304. // left. Since n must've contained at least two children
  305. // before deletion (otherwise it would not be a full node) n
  306. // can never be reduced to nil.
  307. //
  308. // When the loop is done, pos contains the index of the single
  309. // value that is left in n or -2 if n contains at least two
  310. // values.
  311. pos := -1
  312. for i, cld := range n.Children {
  313. if cld != nil {
  314. if pos == -1 {
  315. pos = i
  316. } else {
  317. pos = -2
  318. break
  319. }
  320. }
  321. }
  322. if pos >= 0 {
  323. if pos != 16 {
  324. // If the remaining entry is a short node, it replaces
  325. // n and its key gets the missing nibble tacked to the
  326. // front. This avoids creating an invalid
  327. // shortNode{..., shortNode{...}}. Since the entry
  328. // might not be loaded yet, resolve it just for this
  329. // check.
  330. cnode, err := t.resolve(n.Children[pos], prefix, []byte{byte(pos)})
  331. if err != nil {
  332. return false, nil, err
  333. }
  334. if cnode, ok := cnode.(shortNode); ok {
  335. k := append([]byte{byte(pos)}, cnode.Key...)
  336. return true, shortNode{k, cnode.Val, nil, true}, nil
  337. }
  338. }
  339. // Otherwise, n is replaced by a one-nibble short node
  340. // containing the child.
  341. return true, shortNode{[]byte{byte(pos)}, n.Children[pos], nil, true}, nil
  342. }
  343. // n still contains at least two values and cannot be reduced.
  344. return true, n, nil
  345. case nil:
  346. return false, nil, nil
  347. case hashNode:
  348. // We've hit a part of the trie that isn't loaded yet. Load
  349. // the node and delete from it. This leaves all child nodes on
  350. // the path to the value in the trie.
  351. rn, err := t.resolveHash(n, prefix, key)
  352. if err != nil {
  353. return false, nil, err
  354. }
  355. dirty, nn, err := t.delete(rn, prefix, key)
  356. if err != nil {
  357. return false, nil, err
  358. }
  359. if !dirty {
  360. return false, rn, nil
  361. }
  362. return true, nn, nil
  363. default:
  364. panic(fmt.Sprintf("%T: invalid node: %v (%v)", n, n, key))
  365. }
  366. }
  367. func concat(s1 []byte, s2 ...byte) []byte {
  368. r := make([]byte, len(s1)+len(s2))
  369. copy(r, s1)
  370. copy(r[len(s1):], s2)
  371. return r
  372. }
  373. func (t *Trie) resolve(n node, prefix, suffix []byte) (node, error) {
  374. if n, ok := n.(hashNode); ok {
  375. return t.resolveHash(n, prefix, suffix)
  376. }
  377. return n, nil
  378. }
  379. func (t *Trie) resolveHash(n hashNode, prefix, suffix []byte) (node, error) {
  380. if v, ok := globalCache.Get(n); ok {
  381. return v, nil
  382. }
  383. enc, err := t.db.Get(n)
  384. if err != nil || enc == nil {
  385. return nil, &MissingNodeError{
  386. RootHash: t.originalRoot,
  387. NodeHash: common.BytesToHash(n),
  388. Key: compactHexEncode(append(prefix, suffix...)),
  389. PrefixLen: len(prefix),
  390. SuffixLen: len(suffix),
  391. }
  392. }
  393. dec := mustDecodeNode(n, enc)
  394. if dec != nil {
  395. globalCache.Put(n, dec)
  396. }
  397. return dec, nil
  398. }
  399. // Root returns the root hash of the trie.
  400. // Deprecated: use Hash instead.
  401. func (t *Trie) Root() []byte { return t.Hash().Bytes() }
  402. // Hash returns the root hash of the trie. It does not write to the
  403. // database and can be used even if the trie doesn't have one.
  404. func (t *Trie) Hash() common.Hash {
  405. hash, cached, _ := t.hashRoot(nil)
  406. t.root = cached
  407. return common.BytesToHash(hash.(hashNode))
  408. }
  409. // Commit writes all nodes to the trie's database.
  410. // Nodes are stored with their sha3 hash as the key.
  411. //
  412. // Committing flushes nodes from memory.
  413. // Subsequent Get calls will load nodes from the database.
  414. func (t *Trie) Commit() (root common.Hash, err error) {
  415. if t.db == nil {
  416. panic("Commit called on trie with nil database")
  417. }
  418. return t.CommitTo(t.db)
  419. }
  420. // CommitTo writes all nodes to the given database.
  421. // Nodes are stored with their sha3 hash as the key.
  422. //
  423. // Committing flushes nodes from memory. Subsequent Get calls will
  424. // load nodes from the trie's database. Calling code must ensure that
  425. // the changes made to db are written back to the trie's attached
  426. // database before using the trie.
  427. func (t *Trie) CommitTo(db DatabaseWriter) (root common.Hash, err error) {
  428. hash, cached, err := t.hashRoot(db)
  429. if err != nil {
  430. return (common.Hash{}), err
  431. }
  432. t.root = cached
  433. return common.BytesToHash(hash.(hashNode)), nil
  434. }
  435. func (t *Trie) hashRoot(db DatabaseWriter) (node, node, error) {
  436. if t.root == nil {
  437. return hashNode(emptyRoot.Bytes()), nil, nil
  438. }
  439. if t.hasher == nil {
  440. t.hasher = newHasher()
  441. }
  442. return t.hasher.hash(t.root, db, true)
  443. }
  444. type hasher struct {
  445. tmp *bytes.Buffer
  446. sha hash.Hash
  447. }
  448. func newHasher() *hasher {
  449. return &hasher{tmp: new(bytes.Buffer), sha: sha3.NewKeccak256()}
  450. }
  451. // hash collapses a node down into a hash node, also returning a copy of the
  452. // original node initialzied with the computed hash to replace the original one.
  453. func (h *hasher) hash(n node, db DatabaseWriter, force bool) (node, node, error) {
  454. // If we're not storing the node, just hashing, use avaialble cached data
  455. if hash, dirty := n.cache(); hash != nil && (db == nil || !dirty) {
  456. return hash, n, nil
  457. }
  458. // Trie not processed yet or needs storage, walk the children
  459. collapsed, cached, err := h.hashChildren(n, db)
  460. if err != nil {
  461. return hashNode{}, n, err
  462. }
  463. hashed, err := h.store(collapsed, db, force)
  464. if err != nil {
  465. return hashNode{}, n, err
  466. }
  467. // Cache the hash and RLP blob of the ndoe for later reuse
  468. if hash, ok := hashed.(hashNode); ok && !force {
  469. switch cached := cached.(type) {
  470. case shortNode:
  471. cached.hash = hash
  472. if db != nil {
  473. cached.dirty = false
  474. }
  475. return hashed, cached, nil
  476. case fullNode:
  477. cached.hash = hash
  478. if db != nil {
  479. cached.dirty = false
  480. }
  481. return hashed, cached, nil
  482. }
  483. }
  484. return hashed, cached, nil
  485. }
  486. // hashChildren replaces the children of a node with their hashes if the encoded
  487. // size of the child is larger than a hash, returning the collapsed node as well
  488. // as a replacement for the original node with the child hashes cached in.
  489. func (h *hasher) hashChildren(original node, db DatabaseWriter) (node, node, error) {
  490. var err error
  491. switch n := original.(type) {
  492. case shortNode:
  493. // Hash the short node's child, caching the newly hashed subtree
  494. cached := n
  495. cached.Key = common.CopyBytes(cached.Key)
  496. n.Key = compactEncode(n.Key)
  497. if _, ok := n.Val.(valueNode); !ok {
  498. if n.Val, cached.Val, err = h.hash(n.Val, db, false); err != nil {
  499. return n, original, err
  500. }
  501. }
  502. if n.Val == nil {
  503. n.Val = valueNode(nil) // Ensure that nil children are encoded as empty strings.
  504. }
  505. return n, cached, nil
  506. case fullNode:
  507. // Hash the full node's children, caching the newly hashed subtrees
  508. cached := fullNode{dirty: n.dirty}
  509. for i := 0; i < 16; i++ {
  510. if n.Children[i] != nil {
  511. if n.Children[i], cached.Children[i], err = h.hash(n.Children[i], db, false); err != nil {
  512. return n, original, err
  513. }
  514. } else {
  515. n.Children[i] = valueNode(nil) // Ensure that nil children are encoded as empty strings.
  516. }
  517. }
  518. cached.Children[16] = n.Children[16]
  519. if n.Children[16] == nil {
  520. n.Children[16] = valueNode(nil)
  521. }
  522. return n, cached, nil
  523. default:
  524. // Value and hash nodes don't have children so they're left as were
  525. return n, original, nil
  526. }
  527. }
  528. func (h *hasher) store(n node, db DatabaseWriter, force bool) (node, error) {
  529. // Don't store hashes or empty nodes.
  530. if _, isHash := n.(hashNode); n == nil || isHash {
  531. return n, nil
  532. }
  533. // Generate the RLP encoding of the node
  534. h.tmp.Reset()
  535. if err := rlp.Encode(h.tmp, n); err != nil {
  536. panic("encode error: " + err.Error())
  537. }
  538. if h.tmp.Len() < 32 && !force {
  539. return n, nil // Nodes smaller than 32 bytes are stored inside their parent
  540. }
  541. // Larger nodes are replaced by their hash and stored in the database.
  542. hash, _ := n.cache()
  543. if hash == nil {
  544. h.sha.Reset()
  545. h.sha.Write(h.tmp.Bytes())
  546. hash = hashNode(h.sha.Sum(nil))
  547. }
  548. if db != nil {
  549. return hash, db.Put(hash, h.tmp.Bytes())
  550. }
  551. return hash, nil
  552. }