trie.go 17 KB

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