trie.go 16 KB

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