trie.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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 we reached the requested path, return the current node
  163. if pos >= len(path) {
  164. // Although we most probably have the original node expanded, encoding
  165. // that into consensus form can be nasty (needs to cascade down) and
  166. // time consuming. Instead, just pull the hash up from disk directly.
  167. var hash hashNode
  168. if node, ok := origNode.(hashNode); ok {
  169. hash = node
  170. } else {
  171. hash, _ = origNode.cache()
  172. }
  173. if hash == nil {
  174. return nil, origNode, 0, errors.New("non-consensus node")
  175. }
  176. blob, err := t.db.Node(common.BytesToHash(hash))
  177. return blob, origNode, 1, err
  178. }
  179. // Path still needs to be traversed, descend into children
  180. switch n := (origNode).(type) {
  181. case nil:
  182. // Non-existent path requested, abort
  183. return nil, nil, 0, nil
  184. case valueNode:
  185. // Path prematurely ended, abort
  186. return nil, nil, 0, nil
  187. case *shortNode:
  188. if len(path)-pos < len(n.Key) || !bytes.Equal(n.Key, path[pos:pos+len(n.Key)]) {
  189. // Path branches off from short node
  190. return nil, n, 0, nil
  191. }
  192. item, newnode, resolved, err = t.tryGetNode(n.Val, path, pos+len(n.Key))
  193. if err == nil && resolved > 0 {
  194. n = n.copy()
  195. n.Val = newnode
  196. }
  197. return item, n, resolved, err
  198. case *fullNode:
  199. item, newnode, resolved, err = t.tryGetNode(n.Children[path[pos]], path, pos+1)
  200. if err == nil && resolved > 0 {
  201. n = n.copy()
  202. n.Children[path[pos]] = newnode
  203. }
  204. return item, n, resolved, err
  205. case hashNode:
  206. child, err := t.resolveHash(n, path[:pos])
  207. if err != nil {
  208. return nil, n, 1, err
  209. }
  210. item, newnode, resolved, err := t.tryGetNode(child, path, pos)
  211. return item, newnode, resolved + 1, err
  212. default:
  213. panic(fmt.Sprintf("%T: invalid node: %v", origNode, origNode))
  214. }
  215. }
  216. // Update associates key with value in the trie. Subsequent calls to
  217. // Get will return value. If value has length zero, any existing value
  218. // is deleted from the trie and calls to Get will return nil.
  219. //
  220. // The value bytes must not be modified by the caller while they are
  221. // stored in the trie.
  222. func (t *Trie) Update(key, value []byte) {
  223. if err := t.TryUpdate(key, value); err != nil {
  224. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  225. }
  226. }
  227. // TryUpdate associates key with value in the trie. Subsequent calls to
  228. // Get will return value. If value has length zero, any existing value
  229. // is deleted from the trie and calls to Get will return nil.
  230. //
  231. // The value bytes must not be modified by the caller while they are
  232. // stored in the trie.
  233. //
  234. // If a node was not found in the database, a MissingNodeError is returned.
  235. func (t *Trie) TryUpdate(key, value []byte) error {
  236. t.unhashed++
  237. k := keybytesToHex(key)
  238. if len(value) != 0 {
  239. _, n, err := t.insert(t.root, nil, k, valueNode(value))
  240. if err != nil {
  241. return err
  242. }
  243. t.root = n
  244. } else {
  245. _, n, err := t.delete(t.root, nil, k)
  246. if err != nil {
  247. return err
  248. }
  249. t.root = n
  250. }
  251. return nil
  252. }
  253. func (t *Trie) insert(n node, prefix, key []byte, value node) (bool, node, error) {
  254. if len(key) == 0 {
  255. if v, ok := n.(valueNode); ok {
  256. return !bytes.Equal(v, value.(valueNode)), value, nil
  257. }
  258. return true, value, nil
  259. }
  260. switch n := n.(type) {
  261. case *shortNode:
  262. matchlen := prefixLen(key, n.Key)
  263. // If the whole key matches, keep this short node as is
  264. // and only update the value.
  265. if matchlen == len(n.Key) {
  266. dirty, nn, err := t.insert(n.Val, append(prefix, key[:matchlen]...), key[matchlen:], value)
  267. if !dirty || err != nil {
  268. return false, n, err
  269. }
  270. return true, &shortNode{n.Key, nn, t.newFlag()}, nil
  271. }
  272. // Otherwise branch out at the index where they differ.
  273. branch := &fullNode{flags: t.newFlag()}
  274. var err error
  275. _, branch.Children[n.Key[matchlen]], err = t.insert(nil, append(prefix, n.Key[:matchlen+1]...), n.Key[matchlen+1:], n.Val)
  276. if err != nil {
  277. return false, nil, err
  278. }
  279. _, branch.Children[key[matchlen]], err = t.insert(nil, append(prefix, key[:matchlen+1]...), key[matchlen+1:], value)
  280. if err != nil {
  281. return false, nil, err
  282. }
  283. // Replace this shortNode with the branch if it occurs at index 0.
  284. if matchlen == 0 {
  285. return true, branch, nil
  286. }
  287. // Otherwise, replace it with a short node leading up to the branch.
  288. return true, &shortNode{key[:matchlen], branch, t.newFlag()}, nil
  289. case *fullNode:
  290. dirty, nn, err := t.insert(n.Children[key[0]], append(prefix, key[0]), key[1:], value)
  291. if !dirty || err != nil {
  292. return false, n, err
  293. }
  294. n = n.copy()
  295. n.flags = t.newFlag()
  296. n.Children[key[0]] = nn
  297. return true, n, nil
  298. case nil:
  299. return true, &shortNode{key, value, t.newFlag()}, nil
  300. case hashNode:
  301. // We've hit a part of the trie that isn't loaded yet. Load
  302. // the node and insert into it. This leaves all child nodes on
  303. // the path to the value in the trie.
  304. rn, err := t.resolveHash(n, prefix)
  305. if err != nil {
  306. return false, nil, err
  307. }
  308. dirty, nn, err := t.insert(rn, prefix, key, value)
  309. if !dirty || err != nil {
  310. return false, rn, err
  311. }
  312. return true, nn, nil
  313. default:
  314. panic(fmt.Sprintf("%T: invalid node: %v", n, n))
  315. }
  316. }
  317. // Delete removes any existing value for key from the trie.
  318. func (t *Trie) Delete(key []byte) {
  319. if err := t.TryDelete(key); err != nil {
  320. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  321. }
  322. }
  323. // TryDelete removes any existing value for key from the trie.
  324. // If a node was not found in the database, a MissingNodeError is returned.
  325. func (t *Trie) TryDelete(key []byte) error {
  326. t.unhashed++
  327. k := keybytesToHex(key)
  328. _, n, err := t.delete(t.root, nil, k)
  329. if err != nil {
  330. return err
  331. }
  332. t.root = n
  333. return nil
  334. }
  335. // delete returns the new root of the trie with key deleted.
  336. // It reduces the trie to minimal form by simplifying
  337. // nodes on the way up after deleting recursively.
  338. func (t *Trie) delete(n node, prefix, key []byte) (bool, node, error) {
  339. switch n := n.(type) {
  340. case *shortNode:
  341. matchlen := prefixLen(key, n.Key)
  342. if matchlen < len(n.Key) {
  343. return false, n, nil // don't replace n on mismatch
  344. }
  345. if matchlen == len(key) {
  346. return true, nil, nil // remove n entirely for whole matches
  347. }
  348. // The key is longer than n.Key. Remove the remaining suffix
  349. // from the subtrie. Child can never be nil here since the
  350. // subtrie must contain at least two other values with keys
  351. // longer than n.Key.
  352. dirty, child, err := t.delete(n.Val, append(prefix, key[:len(n.Key)]...), key[len(n.Key):])
  353. if !dirty || err != nil {
  354. return false, n, err
  355. }
  356. switch child := child.(type) {
  357. case *shortNode:
  358. // Deleting from the subtrie reduced it to another
  359. // short node. Merge the nodes to avoid creating a
  360. // shortNode{..., shortNode{...}}. Use concat (which
  361. // always creates a new slice) instead of append to
  362. // avoid modifying n.Key since it might be shared with
  363. // other nodes.
  364. return true, &shortNode{concat(n.Key, child.Key...), child.Val, t.newFlag()}, nil
  365. default:
  366. return true, &shortNode{n.Key, child, t.newFlag()}, nil
  367. }
  368. case *fullNode:
  369. dirty, nn, err := t.delete(n.Children[key[0]], append(prefix, key[0]), key[1:])
  370. if !dirty || err != nil {
  371. return false, n, err
  372. }
  373. n = n.copy()
  374. n.flags = t.newFlag()
  375. n.Children[key[0]] = nn
  376. // Check how many non-nil entries are left after deleting and
  377. // reduce the full node to a short node if only one entry is
  378. // left. Since n must've contained at least two children
  379. // before deletion (otherwise it would not be a full node) n
  380. // can never be reduced to nil.
  381. //
  382. // When the loop is done, pos contains the index of the single
  383. // value that is left in n or -2 if n contains at least two
  384. // values.
  385. pos := -1
  386. for i, cld := range &n.Children {
  387. if cld != nil {
  388. if pos == -1 {
  389. pos = i
  390. } else {
  391. pos = -2
  392. break
  393. }
  394. }
  395. }
  396. if pos >= 0 {
  397. if pos != 16 {
  398. // If the remaining entry is a short node, it replaces
  399. // n and its key gets the missing nibble tacked to the
  400. // front. This avoids creating an invalid
  401. // shortNode{..., shortNode{...}}. Since the entry
  402. // might not be loaded yet, resolve it just for this
  403. // check.
  404. cnode, err := t.resolve(n.Children[pos], prefix)
  405. if err != nil {
  406. return false, nil, err
  407. }
  408. if cnode, ok := cnode.(*shortNode); ok {
  409. k := append([]byte{byte(pos)}, cnode.Key...)
  410. return true, &shortNode{k, cnode.Val, t.newFlag()}, nil
  411. }
  412. }
  413. // Otherwise, n is replaced by a one-nibble short node
  414. // containing the child.
  415. return true, &shortNode{[]byte{byte(pos)}, n.Children[pos], t.newFlag()}, nil
  416. }
  417. // n still contains at least two values and cannot be reduced.
  418. return true, n, nil
  419. case valueNode:
  420. return true, nil, nil
  421. case nil:
  422. return false, nil, nil
  423. case hashNode:
  424. // We've hit a part of the trie that isn't loaded yet. Load
  425. // the node and delete from it. This leaves all child nodes on
  426. // the path to the value in the trie.
  427. rn, err := t.resolveHash(n, prefix)
  428. if err != nil {
  429. return false, nil, err
  430. }
  431. dirty, nn, err := t.delete(rn, prefix, key)
  432. if !dirty || err != nil {
  433. return false, rn, err
  434. }
  435. return true, nn, nil
  436. default:
  437. panic(fmt.Sprintf("%T: invalid node: %v (%v)", n, n, key))
  438. }
  439. }
  440. func concat(s1 []byte, s2 ...byte) []byte {
  441. r := make([]byte, len(s1)+len(s2))
  442. copy(r, s1)
  443. copy(r[len(s1):], s2)
  444. return r
  445. }
  446. func (t *Trie) resolve(n node, prefix []byte) (node, error) {
  447. if n, ok := n.(hashNode); ok {
  448. return t.resolveHash(n, prefix)
  449. }
  450. return n, nil
  451. }
  452. func (t *Trie) resolveHash(n hashNode, prefix []byte) (node, error) {
  453. hash := common.BytesToHash(n)
  454. if node := t.db.node(hash); node != nil {
  455. return node, nil
  456. }
  457. return nil, &MissingNodeError{NodeHash: hash, Path: prefix}
  458. }
  459. // Hash returns the root hash of the trie. It does not write to the
  460. // database and can be used even if the trie doesn't have one.
  461. func (t *Trie) Hash() common.Hash {
  462. hash, cached, _ := t.hashRoot()
  463. t.root = cached
  464. return common.BytesToHash(hash.(hashNode))
  465. }
  466. // Commit writes all nodes to the trie's memory database, tracking the internal
  467. // and external (for account tries) references.
  468. func (t *Trie) Commit(onleaf LeafCallback) (root common.Hash, err error) {
  469. if t.db == nil {
  470. panic("commit called on trie with nil database")
  471. }
  472. if t.root == nil {
  473. return emptyRoot, nil
  474. }
  475. // Derive the hash for all dirty nodes first. We hold the assumption
  476. // in the following procedure that all nodes are hashed.
  477. rootHash := t.Hash()
  478. h := newCommitter()
  479. defer returnCommitterToPool(h)
  480. // Do a quick check if we really need to commit, before we spin
  481. // up goroutines. This can happen e.g. if we load a trie for reading storage
  482. // values, but don't write to it.
  483. if _, dirty := t.root.cache(); !dirty {
  484. return rootHash, nil
  485. }
  486. var wg sync.WaitGroup
  487. if onleaf != nil {
  488. h.onleaf = onleaf
  489. h.leafCh = make(chan *leaf, leafChanSize)
  490. wg.Add(1)
  491. go func() {
  492. defer wg.Done()
  493. h.commitLoop(t.db)
  494. }()
  495. }
  496. var newRoot hashNode
  497. newRoot, err = h.Commit(t.root, t.db)
  498. if onleaf != nil {
  499. // The leafch is created in newCommitter if there was an onleaf callback
  500. // provided. The commitLoop only _reads_ from it, and the commit
  501. // operation was the sole writer. Therefore, it's safe to close this
  502. // channel here.
  503. close(h.leafCh)
  504. wg.Wait()
  505. }
  506. if err != nil {
  507. return common.Hash{}, err
  508. }
  509. t.root = newRoot
  510. return rootHash, nil
  511. }
  512. // hashRoot calculates the root hash of the given trie
  513. func (t *Trie) hashRoot() (node, node, error) {
  514. if t.root == nil {
  515. return hashNode(emptyRoot.Bytes()), nil, nil
  516. }
  517. // If the number of changes is below 100, we let one thread handle it
  518. h := newHasher(t.unhashed >= 100)
  519. defer returnHasherToPool(h)
  520. hashed, cached := h.hash(t.root, true)
  521. t.unhashed = 0
  522. return hashed, cached, nil
  523. }
  524. // Reset drops the referenced root node and cleans all internal state.
  525. func (t *Trie) Reset() {
  526. t.root = nil
  527. t.unhashed = 0
  528. }