trie.go 15 KB

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