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