trie.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/crypto"
  23. "github.com/ethereum/go-ethereum/log"
  24. "github.com/ethereum/go-ethereum/metrics"
  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. var (
  33. cacheMissCounter = metrics.NewRegisteredCounter("trie/cachemiss", nil)
  34. cacheUnloadCounter = metrics.NewRegisteredCounter("trie/cacheunload", nil)
  35. )
  36. // CacheMisses retrieves a global counter measuring the number of cache misses
  37. // the trie had since process startup. This isn't useful for anything apart from
  38. // trie debugging purposes.
  39. func CacheMisses() int64 {
  40. return cacheMissCounter.Count()
  41. }
  42. // CacheUnloads retrieves a global counter measuring the number of cache unloads
  43. // the trie did since process startup. This isn't useful for anything apart from
  44. // trie debugging purposes.
  45. func CacheUnloads() int64 {
  46. return cacheUnloadCounter.Count()
  47. }
  48. // LeafCallback is a callback type invoked when a trie operation reaches a leaf
  49. // node. It's used by state sync and commit to allow handling external references
  50. // between account and storage tries.
  51. type LeafCallback func(leaf []byte, parent common.Hash) error
  52. // Trie is a Merkle Patricia Trie.
  53. // The zero value is an empty trie with no database.
  54. // Use New to create a trie that sits on top of a database.
  55. //
  56. // Trie is not safe for concurrent use.
  57. type Trie struct {
  58. db *Database
  59. root node
  60. originalRoot common.Hash
  61. // Cache generation values.
  62. // cachegen increases by one with each commit operation.
  63. // new nodes are tagged with the current generation and unloaded
  64. // when their generation is older than than cachegen-cachelimit.
  65. cachegen, cachelimit uint16
  66. }
  67. // SetCacheLimit sets the number of 'cache generations' to keep.
  68. // A cache generation is created by a call to Commit.
  69. func (t *Trie) SetCacheLimit(l uint16) {
  70. t.cachelimit = l
  71. }
  72. // newFlag returns the cache flag value for a newly created node.
  73. func (t *Trie) newFlag() nodeFlag {
  74. return nodeFlag{dirty: true, gen: t.cachegen}
  75. }
  76. // New creates a trie with an existing root node from db.
  77. //
  78. // If root is the zero hash or the sha3 hash of an empty string, the
  79. // trie is initially empty and does not require a database. Otherwise,
  80. // New will panic if db is nil and returns a MissingNodeError if root does
  81. // not exist in the database. Accessing the trie loads nodes from db on demand.
  82. func New(root common.Hash, db *Database) (*Trie, error) {
  83. if db == nil {
  84. panic("trie.New called without a database")
  85. }
  86. trie := &Trie{
  87. db: db,
  88. originalRoot: root,
  89. }
  90. if root != (common.Hash{}) && root != emptyRoot {
  91. rootnode, err := trie.resolveHash(root[:], nil)
  92. if err != nil {
  93. return nil, err
  94. }
  95. trie.root = rootnode
  96. }
  97. return trie, nil
  98. }
  99. // NodeIterator returns an iterator that returns nodes of the trie. Iteration starts at
  100. // the key after the given start key.
  101. func (t *Trie) NodeIterator(start []byte) NodeIterator {
  102. return newNodeIterator(t, start)
  103. }
  104. // Get returns the value for key stored in the trie.
  105. // The value bytes must not be modified by the caller.
  106. func (t *Trie) Get(key []byte) []byte {
  107. res, err := t.TryGet(key)
  108. if err != nil {
  109. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  110. }
  111. return res
  112. }
  113. // TryGet returns the value for key stored in the trie.
  114. // The value bytes must not be modified by the caller.
  115. // If a node was not found in the database, a MissingNodeError is returned.
  116. func (t *Trie) TryGet(key []byte) ([]byte, error) {
  117. key = keybytesToHex(key)
  118. value, newroot, didResolve, err := t.tryGet(t.root, key, 0)
  119. if err == nil && didResolve {
  120. t.root = newroot
  121. }
  122. return value, err
  123. }
  124. func (t *Trie) tryGet(origNode node, key []byte, pos int) (value []byte, newnode node, didResolve bool, err error) {
  125. switch n := (origNode).(type) {
  126. case nil:
  127. return nil, nil, false, nil
  128. case valueNode:
  129. return n, n, false, nil
  130. case *shortNode:
  131. if len(key)-pos < len(n.Key) || !bytes.Equal(n.Key, key[pos:pos+len(n.Key)]) {
  132. // key not found in trie
  133. return nil, n, false, nil
  134. }
  135. value, newnode, didResolve, err = t.tryGet(n.Val, key, pos+len(n.Key))
  136. if err == nil && didResolve {
  137. n = n.copy()
  138. n.Val = newnode
  139. n.flags.gen = t.cachegen
  140. }
  141. return value, n, didResolve, err
  142. case *fullNode:
  143. value, newnode, didResolve, err = t.tryGet(n.Children[key[pos]], key, pos+1)
  144. if err == nil && didResolve {
  145. n = n.copy()
  146. n.flags.gen = t.cachegen
  147. n.Children[key[pos]] = newnode
  148. }
  149. return value, n, didResolve, err
  150. case hashNode:
  151. child, err := t.resolveHash(n, key[:pos])
  152. if err != nil {
  153. return nil, n, true, err
  154. }
  155. value, newnode, _, err := t.tryGet(child, key, pos)
  156. return value, newnode, true, err
  157. default:
  158. panic(fmt.Sprintf("%T: invalid node: %v", origNode, origNode))
  159. }
  160. }
  161. // Update associates key with value in the trie. Subsequent calls to
  162. // Get will return value. If value has length zero, any existing value
  163. // is deleted from the trie and calls to Get will return nil.
  164. //
  165. // The value bytes must not be modified by the caller while they are
  166. // stored in the trie.
  167. func (t *Trie) Update(key, value []byte) {
  168. if err := t.TryUpdate(key, value); err != nil {
  169. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  170. }
  171. }
  172. // TryUpdate associates key with value in the trie. Subsequent calls to
  173. // Get will return value. If value has length zero, any existing value
  174. // is deleted from the trie and calls to Get will return nil.
  175. //
  176. // The value bytes must not be modified by the caller while they are
  177. // stored in the trie.
  178. //
  179. // If a node was not found in the database, a MissingNodeError is returned.
  180. func (t *Trie) TryUpdate(key, value []byte) error {
  181. k := keybytesToHex(key)
  182. if len(value) != 0 {
  183. _, n, err := t.insert(t.root, nil, k, valueNode(value))
  184. if err != nil {
  185. return err
  186. }
  187. t.root = n
  188. } else {
  189. _, n, err := t.delete(t.root, nil, k)
  190. if err != nil {
  191. return err
  192. }
  193. t.root = n
  194. }
  195. return nil
  196. }
  197. func (t *Trie) insert(n node, prefix, key []byte, value node) (bool, node, error) {
  198. if len(key) == 0 {
  199. if v, ok := n.(valueNode); ok {
  200. return !bytes.Equal(v, value.(valueNode)), value, nil
  201. }
  202. return true, value, nil
  203. }
  204. switch n := n.(type) {
  205. case *shortNode:
  206. matchlen := prefixLen(key, n.Key)
  207. // If the whole key matches, keep this short node as is
  208. // and only update the value.
  209. if matchlen == len(n.Key) {
  210. dirty, nn, err := t.insert(n.Val, append(prefix, key[:matchlen]...), key[matchlen:], value)
  211. if !dirty || err != nil {
  212. return false, n, err
  213. }
  214. return true, &shortNode{n.Key, nn, t.newFlag()}, nil
  215. }
  216. // Otherwise branch out at the index where they differ.
  217. branch := &fullNode{flags: t.newFlag()}
  218. var err error
  219. _, branch.Children[n.Key[matchlen]], err = t.insert(nil, append(prefix, n.Key[:matchlen+1]...), n.Key[matchlen+1:], n.Val)
  220. if err != nil {
  221. return false, nil, err
  222. }
  223. _, branch.Children[key[matchlen]], err = t.insert(nil, append(prefix, key[:matchlen+1]...), key[matchlen+1:], value)
  224. if err != nil {
  225. return false, nil, err
  226. }
  227. // Replace this shortNode with the branch if it occurs at index 0.
  228. if matchlen == 0 {
  229. return true, branch, nil
  230. }
  231. // Otherwise, replace it with a short node leading up to the branch.
  232. return true, &shortNode{key[:matchlen], branch, t.newFlag()}, nil
  233. case *fullNode:
  234. dirty, nn, err := t.insert(n.Children[key[0]], append(prefix, key[0]), key[1:], value)
  235. if !dirty || err != nil {
  236. return false, n, err
  237. }
  238. n = n.copy()
  239. n.flags = t.newFlag()
  240. n.Children[key[0]] = nn
  241. return true, n, nil
  242. case nil:
  243. return true, &shortNode{key, value, t.newFlag()}, nil
  244. case hashNode:
  245. // We've hit a part of the trie that isn't loaded yet. Load
  246. // the node and insert into it. This leaves all child nodes on
  247. // the path to the value in the trie.
  248. rn, err := t.resolveHash(n, prefix)
  249. if err != nil {
  250. return false, nil, err
  251. }
  252. dirty, nn, err := t.insert(rn, prefix, key, value)
  253. if !dirty || err != nil {
  254. return false, rn, err
  255. }
  256. return true, nn, nil
  257. default:
  258. panic(fmt.Sprintf("%T: invalid node: %v", n, n))
  259. }
  260. }
  261. // Delete removes any existing value for key from the trie.
  262. func (t *Trie) Delete(key []byte) {
  263. if err := t.TryDelete(key); err != nil {
  264. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  265. }
  266. }
  267. // TryDelete removes any existing value for key from the trie.
  268. // If a node was not found in the database, a MissingNodeError is returned.
  269. func (t *Trie) TryDelete(key []byte) error {
  270. k := keybytesToHex(key)
  271. _, n, err := t.delete(t.root, nil, k)
  272. if err != nil {
  273. return err
  274. }
  275. t.root = n
  276. return nil
  277. }
  278. // delete returns the new root of the trie with key deleted.
  279. // It reduces the trie to minimal form by simplifying
  280. // nodes on the way up after deleting recursively.
  281. func (t *Trie) delete(n node, prefix, key []byte) (bool, node, error) {
  282. switch n := n.(type) {
  283. case *shortNode:
  284. matchlen := prefixLen(key, n.Key)
  285. if matchlen < len(n.Key) {
  286. return false, n, nil // don't replace n on mismatch
  287. }
  288. if matchlen == len(key) {
  289. return true, nil, nil // remove n entirely for whole matches
  290. }
  291. // The key is longer than n.Key. Remove the remaining suffix
  292. // from the subtrie. Child can never be nil here since the
  293. // subtrie must contain at least two other values with keys
  294. // longer than n.Key.
  295. dirty, child, err := t.delete(n.Val, append(prefix, key[:len(n.Key)]...), key[len(n.Key):])
  296. if !dirty || err != nil {
  297. return false, n, err
  298. }
  299. switch child := child.(type) {
  300. case *shortNode:
  301. // Deleting from the subtrie reduced it to another
  302. // short node. Merge the nodes to avoid creating a
  303. // shortNode{..., shortNode{...}}. Use concat (which
  304. // always creates a new slice) instead of append to
  305. // avoid modifying n.Key since it might be shared with
  306. // other nodes.
  307. return true, &shortNode{concat(n.Key, child.Key...), child.Val, t.newFlag()}, nil
  308. default:
  309. return true, &shortNode{n.Key, child, t.newFlag()}, nil
  310. }
  311. case *fullNode:
  312. dirty, nn, err := t.delete(n.Children[key[0]], append(prefix, key[0]), key[1:])
  313. if !dirty || err != nil {
  314. return false, n, err
  315. }
  316. n = n.copy()
  317. n.flags = t.newFlag()
  318. n.Children[key[0]] = nn
  319. // Check how many non-nil entries are left after deleting and
  320. // reduce the full node to a short node if only one entry is
  321. // left. Since n must've contained at least two children
  322. // before deletion (otherwise it would not be a full node) n
  323. // can never be reduced to nil.
  324. //
  325. // When the loop is done, pos contains the index of the single
  326. // value that is left in n or -2 if n contains at least two
  327. // values.
  328. pos := -1
  329. for i, cld := range n.Children {
  330. if cld != nil {
  331. if pos == -1 {
  332. pos = i
  333. } else {
  334. pos = -2
  335. break
  336. }
  337. }
  338. }
  339. if pos >= 0 {
  340. if pos != 16 {
  341. // If the remaining entry is a short node, it replaces
  342. // n and its key gets the missing nibble tacked to the
  343. // front. This avoids creating an invalid
  344. // shortNode{..., shortNode{...}}. Since the entry
  345. // might not be loaded yet, resolve it just for this
  346. // check.
  347. cnode, err := t.resolve(n.Children[pos], prefix)
  348. if err != nil {
  349. return false, nil, err
  350. }
  351. if cnode, ok := cnode.(*shortNode); ok {
  352. k := append([]byte{byte(pos)}, cnode.Key...)
  353. return true, &shortNode{k, cnode.Val, t.newFlag()}, nil
  354. }
  355. }
  356. // Otherwise, n is replaced by a one-nibble short node
  357. // containing the child.
  358. return true, &shortNode{[]byte{byte(pos)}, n.Children[pos], t.newFlag()}, nil
  359. }
  360. // n still contains at least two values and cannot be reduced.
  361. return true, n, nil
  362. case valueNode:
  363. return true, nil, nil
  364. case nil:
  365. return false, nil, nil
  366. case hashNode:
  367. // We've hit a part of the trie that isn't loaded yet. Load
  368. // the node and delete from it. This leaves all child nodes on
  369. // the path to the value in the trie.
  370. rn, err := t.resolveHash(n, prefix)
  371. if err != nil {
  372. return false, nil, err
  373. }
  374. dirty, nn, err := t.delete(rn, prefix, key)
  375. if !dirty || err != nil {
  376. return false, rn, err
  377. }
  378. return true, nn, nil
  379. default:
  380. panic(fmt.Sprintf("%T: invalid node: %v (%v)", n, n, key))
  381. }
  382. }
  383. func concat(s1 []byte, s2 ...byte) []byte {
  384. r := make([]byte, len(s1)+len(s2))
  385. copy(r, s1)
  386. copy(r[len(s1):], s2)
  387. return r
  388. }
  389. func (t *Trie) resolve(n node, prefix []byte) (node, error) {
  390. if n, ok := n.(hashNode); ok {
  391. return t.resolveHash(n, prefix)
  392. }
  393. return n, nil
  394. }
  395. func (t *Trie) resolveHash(n hashNode, prefix []byte) (node, error) {
  396. cacheMissCounter.Inc(1)
  397. hash := common.BytesToHash(n)
  398. enc, err := t.db.Node(hash)
  399. if err != nil || enc == nil {
  400. return nil, &MissingNodeError{NodeHash: hash, Path: prefix}
  401. }
  402. return mustDecodeNode(n, enc, t.cachegen), nil
  403. }
  404. // Root returns the root hash of the trie.
  405. // Deprecated: use Hash instead.
  406. func (t *Trie) Root() []byte { return t.Hash().Bytes() }
  407. // Hash returns the root hash of the trie. It does not write to the
  408. // database and can be used even if the trie doesn't have one.
  409. func (t *Trie) Hash() common.Hash {
  410. hash, cached, _ := t.hashRoot(nil, nil)
  411. t.root = cached
  412. return common.BytesToHash(hash.(hashNode))
  413. }
  414. // Commit writes all nodes to the trie's memory database, tracking the internal
  415. // and external (for account tries) references.
  416. func (t *Trie) Commit(onleaf LeafCallback) (root common.Hash, err error) {
  417. if t.db == nil {
  418. panic("commit called on trie with nil database")
  419. }
  420. hash, cached, err := t.hashRoot(t.db, onleaf)
  421. if err != nil {
  422. return common.Hash{}, err
  423. }
  424. t.root = cached
  425. t.cachegen++
  426. return common.BytesToHash(hash.(hashNode)), nil
  427. }
  428. func (t *Trie) hashRoot(db *Database, onleaf LeafCallback) (node, node, error) {
  429. if t.root == nil {
  430. return hashNode(emptyRoot.Bytes()), nil, nil
  431. }
  432. h := newHasher(t.cachegen, t.cachelimit, onleaf)
  433. defer returnHasherToPool(h)
  434. return h.hash(t.root, db, true)
  435. }