trie.go 15 KB

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