trie.go 17 KB

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