trie.go 16 KB

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