trie.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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. "errors"
  21. "fmt"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/log"
  25. )
  26. var (
  27. // emptyRoot is the known root hash of an empty trie.
  28. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  29. // emptyState is the known hash of an empty state trie entry.
  30. emptyState = crypto.Keccak256Hash(nil)
  31. )
  32. // LeafCallback is a callback type invoked when a trie operation reaches a leaf
  33. // node.
  34. //
  35. // The keys is a path tuple identifying a particular trie node either in a single
  36. // trie (account) or a layered trie (account -> storage). Each key in the tuple
  37. // is in the raw format(32 bytes).
  38. //
  39. // The path is a composite hexary path identifying the trie node. All the key
  40. // bytes are converted to the hexary nibbles and composited with the parent path
  41. // if the trie node is in a layered trie.
  42. //
  43. // It's used by state sync and commit to allow handling external references
  44. // between account and storage tries. And also it's used in the state healing
  45. // for extracting the raw states(leaf nodes) with corresponding paths.
  46. type LeafCallback func(keys [][]byte, path []byte, leaf []byte, parent common.Hash, parentPath []byte) error
  47. // Trie is a Merkle Patricia Trie. Use New to create a trie that sits on
  48. // top of a database. Whenever trie performs a commit operation, the generated
  49. // nodes will be gathered and returned in a set. Once the trie is committed,
  50. // it's not usable anymore. Callers have to re-create the trie with new root
  51. // based on the updated trie database.
  52. //
  53. // Trie is not safe for concurrent use.
  54. type Trie struct {
  55. root node
  56. owner common.Hash
  57. // Keep track of the number leaves which have been inserted since the last
  58. // hashing operation. This number will not directly map to the number of
  59. // actually unhashed nodes.
  60. unhashed int
  61. // db is the handler trie can retrieve nodes from. It's
  62. // only for reading purpose and not available for writing.
  63. db *Database
  64. // tracer is the tool to track the trie changes.
  65. // It will be reset after each commit operation.
  66. tracer *tracer
  67. }
  68. // newFlag returns the cache flag value for a newly created node.
  69. func (t *Trie) newFlag() nodeFlag {
  70. return nodeFlag{dirty: true}
  71. }
  72. // Copy returns a copy of Trie.
  73. func (t *Trie) Copy() *Trie {
  74. return &Trie{
  75. root: t.root,
  76. owner: t.owner,
  77. unhashed: t.unhashed,
  78. db: t.db,
  79. tracer: t.tracer.copy(),
  80. }
  81. }
  82. // New creates a trie with an existing root node from db and an assigned
  83. // owner for storage proximity.
  84. //
  85. // If root is the zero hash or the sha3 hash of an empty string, the
  86. // trie is initially empty and does not require a database. Otherwise,
  87. // New will panic if db is nil and returns a MissingNodeError if root does
  88. // not exist in the database. Accessing the trie loads nodes from db on demand.
  89. func New(owner common.Hash, root common.Hash, db *Database) (*Trie, error) {
  90. trie := &Trie{
  91. owner: owner,
  92. db: db,
  93. //tracer: newTracer(),
  94. }
  95. if root != (common.Hash{}) && root != emptyRoot {
  96. rootnode, err := trie.resolveHash(root[:], nil)
  97. if err != nil {
  98. return nil, err
  99. }
  100. trie.root = rootnode
  101. }
  102. return trie, nil
  103. }
  104. // NewEmpty is a shortcut to create empty tree. It's mostly used in tests.
  105. func NewEmpty(db *Database) *Trie {
  106. tr, _ := New(common.Hash{}, common.Hash{}, db)
  107. return tr
  108. }
  109. // NodeIterator returns an iterator that returns nodes of the trie. Iteration starts at
  110. // the key after the given start key.
  111. func (t *Trie) NodeIterator(start []byte) NodeIterator {
  112. return newNodeIterator(t, start)
  113. }
  114. // Get returns the value for key stored in the trie.
  115. // The value bytes must not be modified by the caller.
  116. func (t *Trie) Get(key []byte) []byte {
  117. res, err := t.TryGet(key)
  118. if err != nil {
  119. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  120. }
  121. return res
  122. }
  123. // TryGet returns the value for key stored in the trie.
  124. // The value bytes must not be modified by the caller.
  125. // If a node was not found in the database, a MissingNodeError is returned.
  126. func (t *Trie) TryGet(key []byte) ([]byte, error) {
  127. value, newroot, didResolve, err := t.tryGet(t.root, keybytesToHex(key), 0)
  128. if err == nil && didResolve {
  129. t.root = newroot
  130. }
  131. return value, err
  132. }
  133. func (t *Trie) tryGet(origNode node, key []byte, pos int) (value []byte, newnode node, didResolve bool, err error) {
  134. switch n := (origNode).(type) {
  135. case nil:
  136. return nil, nil, false, nil
  137. case valueNode:
  138. return n, n, false, nil
  139. case *shortNode:
  140. if len(key)-pos < len(n.Key) || !bytes.Equal(n.Key, key[pos:pos+len(n.Key)]) {
  141. // key not found in trie
  142. return nil, n, false, nil
  143. }
  144. value, newnode, didResolve, err = t.tryGet(n.Val, key, pos+len(n.Key))
  145. if err == nil && didResolve {
  146. n = n.copy()
  147. n.Val = newnode
  148. }
  149. return value, n, didResolve, err
  150. case *fullNode:
  151. value, newnode, didResolve, err = t.tryGet(n.Children[key[pos]], key, pos+1)
  152. if err == nil && didResolve {
  153. n = n.copy()
  154. n.Children[key[pos]] = newnode
  155. }
  156. return value, n, didResolve, err
  157. case hashNode:
  158. child, err := t.resolveHash(n, key[:pos])
  159. if err != nil {
  160. return nil, n, true, err
  161. }
  162. value, newnode, _, err := t.tryGet(child, key, pos)
  163. return value, newnode, true, err
  164. default:
  165. panic(fmt.Sprintf("%T: invalid node: %v", origNode, origNode))
  166. }
  167. }
  168. // TryGetNode attempts to retrieve a trie node by compact-encoded path. It is not
  169. // possible to use keybyte-encoding as the path might contain odd nibbles.
  170. func (t *Trie) TryGetNode(path []byte) ([]byte, int, error) {
  171. item, newroot, resolved, err := t.tryGetNode(t.root, compactToHex(path), 0)
  172. if err != nil {
  173. return nil, resolved, err
  174. }
  175. if resolved > 0 {
  176. t.root = newroot
  177. }
  178. if item == nil {
  179. return nil, resolved, nil
  180. }
  181. return item, resolved, err
  182. }
  183. func (t *Trie) tryGetNode(origNode node, path []byte, pos int) (item []byte, newnode node, resolved int, err error) {
  184. // If non-existent path requested, abort
  185. if origNode == nil {
  186. return nil, nil, 0, nil
  187. }
  188. // If we reached the requested path, return the current node
  189. if pos >= len(path) {
  190. // Although we most probably have the original node expanded, encoding
  191. // that into consensus form can be nasty (needs to cascade down) and
  192. // time consuming. Instead, just pull the hash up from disk directly.
  193. var hash hashNode
  194. if node, ok := origNode.(hashNode); ok {
  195. hash = node
  196. } else {
  197. hash, _ = origNode.cache()
  198. }
  199. if hash == nil {
  200. return nil, origNode, 0, errors.New("non-consensus node")
  201. }
  202. blob, err := t.db.Node(common.BytesToHash(hash))
  203. return blob, origNode, 1, err
  204. }
  205. // Path still needs to be traversed, descend into children
  206. switch n := (origNode).(type) {
  207. case valueNode:
  208. // Path prematurely ended, abort
  209. return nil, nil, 0, nil
  210. case *shortNode:
  211. if len(path)-pos < len(n.Key) || !bytes.Equal(n.Key, path[pos:pos+len(n.Key)]) {
  212. // Path branches off from short node
  213. return nil, n, 0, nil
  214. }
  215. item, newnode, resolved, err = t.tryGetNode(n.Val, path, pos+len(n.Key))
  216. if err == nil && resolved > 0 {
  217. n = n.copy()
  218. n.Val = newnode
  219. }
  220. return item, n, resolved, err
  221. case *fullNode:
  222. item, newnode, resolved, err = t.tryGetNode(n.Children[path[pos]], path, pos+1)
  223. if err == nil && resolved > 0 {
  224. n = n.copy()
  225. n.Children[path[pos]] = newnode
  226. }
  227. return item, n, resolved, err
  228. case hashNode:
  229. child, err := t.resolveHash(n, path[:pos])
  230. if err != nil {
  231. return nil, n, 1, err
  232. }
  233. item, newnode, resolved, err := t.tryGetNode(child, path, pos)
  234. return item, newnode, resolved + 1, err
  235. default:
  236. panic(fmt.Sprintf("%T: invalid node: %v", origNode, origNode))
  237. }
  238. }
  239. // Update associates key with value in the trie. Subsequent calls to
  240. // Get will return value. If value has length zero, any existing value
  241. // is deleted from the trie and calls to Get will return nil.
  242. //
  243. // The value bytes must not be modified by the caller while they are
  244. // stored in the trie.
  245. func (t *Trie) Update(key, value []byte) {
  246. if err := t.TryUpdate(key, value); err != nil {
  247. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  248. }
  249. }
  250. // TryUpdate associates key with value in the trie. Subsequent calls to
  251. // Get will return value. If value has length zero, any existing value
  252. // is deleted from the trie and calls to Get will return nil.
  253. //
  254. // The value bytes must not be modified by the caller while they are
  255. // stored in the trie.
  256. //
  257. // If a node was not found in the database, a MissingNodeError is returned.
  258. func (t *Trie) TryUpdate(key, value []byte) error {
  259. return t.tryUpdate(key, value)
  260. }
  261. // tryUpdate expects an RLP-encoded value and performs the core function
  262. // for TryUpdate and TryUpdateAccount.
  263. func (t *Trie) tryUpdate(key, value []byte) error {
  264. t.unhashed++
  265. k := keybytesToHex(key)
  266. if len(value) != 0 {
  267. _, n, err := t.insert(t.root, nil, k, valueNode(value))
  268. if err != nil {
  269. return err
  270. }
  271. t.root = n
  272. } else {
  273. _, n, err := t.delete(t.root, nil, k)
  274. if err != nil {
  275. return err
  276. }
  277. t.root = n
  278. }
  279. return nil
  280. }
  281. func (t *Trie) insert(n node, prefix, key []byte, value node) (bool, node, error) {
  282. if len(key) == 0 {
  283. if v, ok := n.(valueNode); ok {
  284. return !bytes.Equal(v, value.(valueNode)), value, nil
  285. }
  286. return true, value, nil
  287. }
  288. switch n := n.(type) {
  289. case *shortNode:
  290. matchlen := prefixLen(key, n.Key)
  291. // If the whole key matches, keep this short node as is
  292. // and only update the value.
  293. if matchlen == len(n.Key) {
  294. dirty, nn, err := t.insert(n.Val, append(prefix, key[:matchlen]...), key[matchlen:], value)
  295. if !dirty || err != nil {
  296. return false, n, err
  297. }
  298. return true, &shortNode{n.Key, nn, t.newFlag()}, nil
  299. }
  300. // Otherwise branch out at the index where they differ.
  301. branch := &fullNode{flags: t.newFlag()}
  302. var err error
  303. _, branch.Children[n.Key[matchlen]], err = t.insert(nil, append(prefix, n.Key[:matchlen+1]...), n.Key[matchlen+1:], n.Val)
  304. if err != nil {
  305. return false, nil, err
  306. }
  307. _, branch.Children[key[matchlen]], err = t.insert(nil, append(prefix, key[:matchlen+1]...), key[matchlen+1:], value)
  308. if err != nil {
  309. return false, nil, err
  310. }
  311. // Replace this shortNode with the branch if it occurs at index 0.
  312. if matchlen == 0 {
  313. return true, branch, nil
  314. }
  315. // New branch node is created as a child of the original short node.
  316. // Track the newly inserted node in the tracer. The node identifier
  317. // passed is the path from the root node.
  318. t.tracer.onInsert(append(prefix, key[:matchlen]...))
  319. // Replace it with a short node leading up to the branch.
  320. return true, &shortNode{key[:matchlen], branch, t.newFlag()}, nil
  321. case *fullNode:
  322. dirty, nn, err := t.insert(n.Children[key[0]], append(prefix, key[0]), key[1:], value)
  323. if !dirty || err != nil {
  324. return false, n, err
  325. }
  326. n = n.copy()
  327. n.flags = t.newFlag()
  328. n.Children[key[0]] = nn
  329. return true, n, nil
  330. case nil:
  331. // New short node is created and track it in the tracer. The node identifier
  332. // passed is the path from the root node. Note the valueNode won't be tracked
  333. // since it's always embedded in its parent.
  334. t.tracer.onInsert(prefix)
  335. return true, &shortNode{key, value, t.newFlag()}, nil
  336. case hashNode:
  337. // We've hit a part of the trie that isn't loaded yet. Load
  338. // the node and insert into it. This leaves all child nodes on
  339. // the path to the value in the trie.
  340. rn, err := t.resolveHash(n, prefix)
  341. if err != nil {
  342. return false, nil, err
  343. }
  344. dirty, nn, err := t.insert(rn, prefix, key, value)
  345. if !dirty || err != nil {
  346. return false, rn, err
  347. }
  348. return true, nn, nil
  349. default:
  350. panic(fmt.Sprintf("%T: invalid node: %v", n, n))
  351. }
  352. }
  353. // Delete removes any existing value for key from the trie.
  354. func (t *Trie) Delete(key []byte) {
  355. if err := t.TryDelete(key); err != nil {
  356. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  357. }
  358. }
  359. // TryDelete removes any existing value for key from the trie.
  360. // If a node was not found in the database, a MissingNodeError is returned.
  361. func (t *Trie) TryDelete(key []byte) error {
  362. t.unhashed++
  363. k := keybytesToHex(key)
  364. _, n, err := t.delete(t.root, nil, k)
  365. if err != nil {
  366. return err
  367. }
  368. t.root = n
  369. return nil
  370. }
  371. // delete returns the new root of the trie with key deleted.
  372. // It reduces the trie to minimal form by simplifying
  373. // nodes on the way up after deleting recursively.
  374. func (t *Trie) delete(n node, prefix, key []byte) (bool, node, error) {
  375. switch n := n.(type) {
  376. case *shortNode:
  377. matchlen := prefixLen(key, n.Key)
  378. if matchlen < len(n.Key) {
  379. return false, n, nil // don't replace n on mismatch
  380. }
  381. if matchlen == len(key) {
  382. // The matched short node is deleted entirely and track
  383. // it in the deletion set. The same the valueNode doesn't
  384. // need to be tracked at all since it's always embedded.
  385. t.tracer.onDelete(prefix)
  386. return true, nil, nil // remove n entirely for whole matches
  387. }
  388. // The key is longer than n.Key. Remove the remaining suffix
  389. // from the subtrie. Child can never be nil here since the
  390. // subtrie must contain at least two other values with keys
  391. // longer than n.Key.
  392. dirty, child, err := t.delete(n.Val, append(prefix, key[:len(n.Key)]...), key[len(n.Key):])
  393. if !dirty || err != nil {
  394. return false, n, err
  395. }
  396. switch child := child.(type) {
  397. case *shortNode:
  398. // The child shortNode is merged into its parent, track
  399. // is deleted as well.
  400. t.tracer.onDelete(append(prefix, n.Key...))
  401. // Deleting from the subtrie reduced it to another
  402. // short node. Merge the nodes to avoid creating a
  403. // shortNode{..., shortNode{...}}. Use concat (which
  404. // always creates a new slice) instead of append to
  405. // avoid modifying n.Key since it might be shared with
  406. // other nodes.
  407. return true, &shortNode{concat(n.Key, child.Key...), child.Val, t.newFlag()}, nil
  408. default:
  409. return true, &shortNode{n.Key, child, t.newFlag()}, nil
  410. }
  411. case *fullNode:
  412. dirty, nn, err := t.delete(n.Children[key[0]], append(prefix, key[0]), key[1:])
  413. if !dirty || err != nil {
  414. return false, n, err
  415. }
  416. n = n.copy()
  417. n.flags = t.newFlag()
  418. n.Children[key[0]] = nn
  419. // Because n is a full node, it must've contained at least two children
  420. // before the delete operation. If the new child value is non-nil, n still
  421. // has at least two children after the deletion, and cannot be reduced to
  422. // a short node.
  423. if nn != nil {
  424. return true, n, nil
  425. }
  426. // Reduction:
  427. // Check how many non-nil entries are left after deleting and
  428. // reduce the full node to a short node if only one entry is
  429. // left. Since n must've contained at least two children
  430. // before deletion (otherwise it would not be a full node) n
  431. // can never be reduced to nil.
  432. //
  433. // When the loop is done, pos contains the index of the single
  434. // value that is left in n or -2 if n contains at least two
  435. // values.
  436. pos := -1
  437. for i, cld := range &n.Children {
  438. if cld != nil {
  439. if pos == -1 {
  440. pos = i
  441. } else {
  442. pos = -2
  443. break
  444. }
  445. }
  446. }
  447. if pos >= 0 {
  448. if pos != 16 {
  449. // If the remaining entry is a short node, it replaces
  450. // n and its key gets the missing nibble tacked to the
  451. // front. This avoids creating an invalid
  452. // shortNode{..., shortNode{...}}. Since the entry
  453. // might not be loaded yet, resolve it just for this
  454. // check.
  455. cnode, err := t.resolve(n.Children[pos], append(prefix, byte(pos)))
  456. if err != nil {
  457. return false, nil, err
  458. }
  459. if cnode, ok := cnode.(*shortNode); ok {
  460. // Replace the entire full node with the short node.
  461. // Mark the original short node as deleted since the
  462. // value is embedded into the parent now.
  463. t.tracer.onDelete(append(prefix, byte(pos)))
  464. k := append([]byte{byte(pos)}, cnode.Key...)
  465. return true, &shortNode{k, cnode.Val, t.newFlag()}, nil
  466. }
  467. }
  468. // Otherwise, n is replaced by a one-nibble short node
  469. // containing the child.
  470. return true, &shortNode{[]byte{byte(pos)}, n.Children[pos], t.newFlag()}, nil
  471. }
  472. // n still contains at least two values and cannot be reduced.
  473. return true, n, nil
  474. case valueNode:
  475. return true, nil, nil
  476. case nil:
  477. return false, nil, nil
  478. case hashNode:
  479. // We've hit a part of the trie that isn't loaded yet. Load
  480. // the node and delete from it. This leaves all child nodes on
  481. // the path to the value in the trie.
  482. rn, err := t.resolveHash(n, prefix)
  483. if err != nil {
  484. return false, nil, err
  485. }
  486. dirty, nn, err := t.delete(rn, prefix, key)
  487. if !dirty || err != nil {
  488. return false, rn, err
  489. }
  490. return true, nn, nil
  491. default:
  492. panic(fmt.Sprintf("%T: invalid node: %v (%v)", n, n, key))
  493. }
  494. }
  495. func concat(s1 []byte, s2 ...byte) []byte {
  496. r := make([]byte, len(s1)+len(s2))
  497. copy(r, s1)
  498. copy(r[len(s1):], s2)
  499. return r
  500. }
  501. func (t *Trie) resolve(n node, prefix []byte) (node, error) {
  502. if n, ok := n.(hashNode); ok {
  503. return t.resolveHash(n, prefix)
  504. }
  505. return n, nil
  506. }
  507. // resolveHash loads node from the underlying database with the provided
  508. // node hash and path prefix.
  509. func (t *Trie) resolveHash(n hashNode, prefix []byte) (node, error) {
  510. hash := common.BytesToHash(n)
  511. if node := t.db.node(hash); node != nil {
  512. return node, nil
  513. }
  514. return nil, &MissingNodeError{Owner: t.owner, NodeHash: hash, Path: prefix}
  515. }
  516. // resolveHash loads rlp-encoded node blob from the underlying database
  517. // with the provided node hash and path prefix.
  518. func (t *Trie) resolveBlob(n hashNode, prefix []byte) ([]byte, error) {
  519. hash := common.BytesToHash(n)
  520. blob, _ := t.db.Node(hash)
  521. if len(blob) != 0 {
  522. return blob, nil
  523. }
  524. return nil, &MissingNodeError{Owner: t.owner, NodeHash: hash, Path: prefix}
  525. }
  526. // Hash returns the root hash of the trie. It does not write to the
  527. // database and can be used even if the trie doesn't have one.
  528. func (t *Trie) Hash() common.Hash {
  529. hash, cached, _ := t.hashRoot()
  530. t.root = cached
  531. return common.BytesToHash(hash.(hashNode))
  532. }
  533. // Commit collects all dirty nodes in the trie and replace them with the
  534. // corresponding node hash. All collected nodes(including dirty leaves if
  535. // collectLeaf is true) will be encapsulated into a nodeset for return.
  536. // The returned nodeset can be nil if the trie is clean(nothing to commit).
  537. // Once the trie is committed, it's not usable anymore. A new trie must
  538. // be created with new root and updated trie database for following usage
  539. func (t *Trie) Commit(collectLeaf bool) (common.Hash, *NodeSet, error) {
  540. defer t.tracer.reset()
  541. if t.root == nil {
  542. return emptyRoot, nil, nil
  543. }
  544. // Derive the hash for all dirty nodes first. We hold the assumption
  545. // in the following procedure that all nodes are hashed.
  546. rootHash := t.Hash()
  547. // Do a quick check if we really need to commit. This can happen e.g.
  548. // if we load a trie for reading storage values, but don't write to it.
  549. if hashedNode, dirty := t.root.cache(); !dirty {
  550. // Replace the root node with the origin hash in order to
  551. // ensure all resolved nodes are dropped after the commit.
  552. t.root = hashedNode
  553. return rootHash, nil, nil
  554. }
  555. h := newCommitter(t.owner, collectLeaf)
  556. newRoot, nodes, err := h.Commit(t.root)
  557. if err != nil {
  558. return common.Hash{}, nil, err
  559. }
  560. t.root = newRoot
  561. return rootHash, nodes, nil
  562. }
  563. // hashRoot calculates the root hash of the given trie
  564. func (t *Trie) hashRoot() (node, node, error) {
  565. if t.root == nil {
  566. return hashNode(emptyRoot.Bytes()), nil, nil
  567. }
  568. // If the number of changes is below 100, we let one thread handle it
  569. h := newHasher(t.unhashed >= 100)
  570. defer returnHasherToPool(h)
  571. hashed, cached := h.hash(t.root, true)
  572. t.unhashed = 0
  573. return hashed, cached, nil
  574. }
  575. // Reset drops the referenced root node and cleans all internal state.
  576. func (t *Trie) Reset() {
  577. t.root = nil
  578. t.owner = common.Hash{}
  579. t.unhashed = 0
  580. //t.db = nil
  581. t.tracer.reset()
  582. }