trie.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. if v, _ := trie.db.Get(root[:]); len(v) == 0 {
  85. return nil, &MissingNodeError{
  86. RootHash: root,
  87. NodeHash: root,
  88. }
  89. }
  90. trie.root = hashNode(root.Bytes())
  91. }
  92. return trie, nil
  93. }
  94. // Iterator returns an iterator over all mappings in the trie.
  95. func (t *Trie) Iterator() *Iterator {
  96. return NewIterator(t)
  97. }
  98. // Get returns the value for key stored in the trie.
  99. // The value bytes must not be modified by the caller.
  100. func (t *Trie) Get(key []byte) []byte {
  101. res, err := t.TryGet(key)
  102. if err != nil && glog.V(logger.Error) {
  103. glog.Errorf("Unhandled trie error: %v", err)
  104. }
  105. return res
  106. }
  107. // TryGet returns the value for key stored in the trie.
  108. // The value bytes must not be modified by the caller.
  109. // If a node was not found in the database, a MissingNodeError is returned.
  110. func (t *Trie) TryGet(key []byte) ([]byte, error) {
  111. key = compactHexDecode(key)
  112. value, newroot, didResolve, err := t.tryGet(t.root, key, 0)
  113. if err == nil && didResolve {
  114. t.root = newroot
  115. }
  116. return value, err
  117. }
  118. func (t *Trie) tryGet(origNode node, key []byte, pos int) (value []byte, newnode node, didResolve bool, err error) {
  119. switch n := (origNode).(type) {
  120. case nil:
  121. return nil, nil, false, nil
  122. case valueNode:
  123. return n, n, false, nil
  124. case *shortNode:
  125. if len(key)-pos < len(n.Key) || !bytes.Equal(n.Key, key[pos:pos+len(n.Key)]) {
  126. // key not found in trie
  127. return nil, n, false, nil
  128. }
  129. value, newnode, didResolve, err = t.tryGet(n.Val, key, pos+len(n.Key))
  130. if err == nil && didResolve {
  131. n = n.copy()
  132. n.Val = newnode
  133. }
  134. return value, n, didResolve, err
  135. case *fullNode:
  136. value, newnode, didResolve, err = t.tryGet(n.Children[key[pos]], key, pos+1)
  137. if err == nil && didResolve {
  138. n = n.copy()
  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.Children[key[0]], n.flags.hash, n.flags.dirty = nn, nil, true
  232. return true, n, nil
  233. case nil:
  234. return true, &shortNode{key, value, t.newFlag()}, nil
  235. case hashNode:
  236. // We've hit a part of the trie that isn't loaded yet. Load
  237. // the node and insert into it. This leaves all child nodes on
  238. // the path to the value in the trie.
  239. rn, err := t.resolveHash(n, prefix, key)
  240. if err != nil {
  241. return false, nil, err
  242. }
  243. dirty, nn, err := t.insert(rn, prefix, key, value)
  244. if !dirty || err != nil {
  245. return false, rn, err
  246. }
  247. return true, nn, nil
  248. default:
  249. panic(fmt.Sprintf("%T: invalid node: %v", n, n))
  250. }
  251. }
  252. // Delete removes any existing value for key from the trie.
  253. func (t *Trie) Delete(key []byte) {
  254. if err := t.TryDelete(key); err != nil && glog.V(logger.Error) {
  255. glog.Errorf("Unhandled trie error: %v", err)
  256. }
  257. }
  258. // TryDelete removes any existing value for key from the trie.
  259. // If a node was not found in the database, a MissingNodeError is returned.
  260. func (t *Trie) TryDelete(key []byte) error {
  261. k := compactHexDecode(key)
  262. _, n, err := t.delete(t.root, nil, k)
  263. if err != nil {
  264. return err
  265. }
  266. t.root = n
  267. return nil
  268. }
  269. // delete returns the new root of the trie with key deleted.
  270. // It reduces the trie to minimal form by simplifying
  271. // nodes on the way up after deleting recursively.
  272. func (t *Trie) delete(n node, prefix, key []byte) (bool, node, error) {
  273. switch n := n.(type) {
  274. case *shortNode:
  275. matchlen := prefixLen(key, n.Key)
  276. if matchlen < len(n.Key) {
  277. return false, n, nil // don't replace n on mismatch
  278. }
  279. if matchlen == len(key) {
  280. return true, nil, nil // remove n entirely for whole matches
  281. }
  282. // The key is longer than n.Key. Remove the remaining suffix
  283. // from the subtrie. Child can never be nil here since the
  284. // subtrie must contain at least two other values with keys
  285. // longer than n.Key.
  286. dirty, child, err := t.delete(n.Val, append(prefix, key[:len(n.Key)]...), key[len(n.Key):])
  287. if !dirty || err != nil {
  288. return false, n, err
  289. }
  290. switch child := child.(type) {
  291. case *shortNode:
  292. // Deleting from the subtrie reduced it to another
  293. // short node. Merge the nodes to avoid creating a
  294. // shortNode{..., shortNode{...}}. Use concat (which
  295. // always creates a new slice) instead of append to
  296. // avoid modifying n.Key since it might be shared with
  297. // other nodes.
  298. return true, &shortNode{concat(n.Key, child.Key...), child.Val, t.newFlag()}, nil
  299. default:
  300. return true, &shortNode{n.Key, child, t.newFlag()}, nil
  301. }
  302. case *fullNode:
  303. dirty, nn, err := t.delete(n.Children[key[0]], append(prefix, key[0]), key[1:])
  304. if !dirty || err != nil {
  305. return false, n, err
  306. }
  307. n = n.copy()
  308. n.Children[key[0]], n.flags.hash, n.flags.dirty = nn, nil, true
  309. // Check how many non-nil entries are left after deleting and
  310. // reduce the full node to a short node if only one entry is
  311. // left. Since n must've contained at least two children
  312. // before deletion (otherwise it would not be a full node) n
  313. // can never be reduced to nil.
  314. //
  315. // When the loop is done, pos contains the index of the single
  316. // value that is left in n or -2 if n contains at least two
  317. // values.
  318. pos := -1
  319. for i, cld := range n.Children {
  320. if cld != nil {
  321. if pos == -1 {
  322. pos = i
  323. } else {
  324. pos = -2
  325. break
  326. }
  327. }
  328. }
  329. if pos >= 0 {
  330. if pos != 16 {
  331. // If the remaining entry is a short node, it replaces
  332. // n and its key gets the missing nibble tacked to the
  333. // front. This avoids creating an invalid
  334. // shortNode{..., shortNode{...}}. Since the entry
  335. // might not be loaded yet, resolve it just for this
  336. // check.
  337. cnode, err := t.resolve(n.Children[pos], prefix, []byte{byte(pos)})
  338. if err != nil {
  339. return false, nil, err
  340. }
  341. if cnode, ok := cnode.(*shortNode); ok {
  342. k := append([]byte{byte(pos)}, cnode.Key...)
  343. return true, &shortNode{k, cnode.Val, t.newFlag()}, nil
  344. }
  345. }
  346. // Otherwise, n is replaced by a one-nibble short node
  347. // containing the child.
  348. return true, &shortNode{[]byte{byte(pos)}, n.Children[pos], t.newFlag()}, nil
  349. }
  350. // n still contains at least two values and cannot be reduced.
  351. return true, n, nil
  352. case valueNode:
  353. return true, nil, nil
  354. case nil:
  355. return false, nil, nil
  356. case hashNode:
  357. // We've hit a part of the trie that isn't loaded yet. Load
  358. // the node and delete from it. This leaves all child nodes on
  359. // the path to the value in the trie.
  360. rn, err := t.resolveHash(n, prefix, key)
  361. if err != nil {
  362. return false, nil, err
  363. }
  364. dirty, nn, err := t.delete(rn, prefix, key)
  365. if !dirty || err != nil {
  366. return false, rn, err
  367. }
  368. return true, nn, nil
  369. default:
  370. panic(fmt.Sprintf("%T: invalid node: %v (%v)", n, n, key))
  371. }
  372. }
  373. func concat(s1 []byte, s2 ...byte) []byte {
  374. r := make([]byte, len(s1)+len(s2))
  375. copy(r, s1)
  376. copy(r[len(s1):], s2)
  377. return r
  378. }
  379. func (t *Trie) resolve(n node, prefix, suffix []byte) (node, error) {
  380. if n, ok := n.(hashNode); ok {
  381. return t.resolveHash(n, prefix, suffix)
  382. }
  383. return n, nil
  384. }
  385. func (t *Trie) resolveHash(n hashNode, prefix, suffix []byte) (node, error) {
  386. enc, err := t.db.Get(n)
  387. if err != nil || enc == nil {
  388. return nil, &MissingNodeError{
  389. RootHash: t.originalRoot,
  390. NodeHash: common.BytesToHash(n),
  391. Key: compactHexEncode(append(prefix, suffix...)),
  392. PrefixLen: len(prefix),
  393. SuffixLen: len(suffix),
  394. }
  395. }
  396. dec := mustDecodeNode(n, enc)
  397. return dec, nil
  398. }
  399. // Root returns the root hash of the trie.
  400. // Deprecated: use Hash instead.
  401. func (t *Trie) Root() []byte { return t.Hash().Bytes() }
  402. // Hash returns the root hash of the trie. It does not write to the
  403. // database and can be used even if the trie doesn't have one.
  404. func (t *Trie) Hash() common.Hash {
  405. hash, cached, _ := t.hashRoot(nil)
  406. t.root = cached
  407. return common.BytesToHash(hash.(hashNode))
  408. }
  409. // Commit writes all nodes to the trie's database.
  410. // Nodes are stored with their sha3 hash as the key.
  411. //
  412. // Committing flushes nodes from memory.
  413. // Subsequent Get calls will load nodes from the database.
  414. func (t *Trie) Commit() (root common.Hash, err error) {
  415. if t.db == nil {
  416. panic("Commit called on trie with nil database")
  417. }
  418. return t.CommitTo(t.db)
  419. }
  420. // CommitTo writes all nodes to the given database.
  421. // Nodes are stored with their sha3 hash as the key.
  422. //
  423. // Committing flushes nodes from memory. Subsequent Get calls will
  424. // load nodes from the trie's database. Calling code must ensure that
  425. // the changes made to db are written back to the trie's attached
  426. // database before using the trie.
  427. func (t *Trie) CommitTo(db DatabaseWriter) (root common.Hash, err error) {
  428. hash, cached, err := t.hashRoot(db)
  429. if err != nil {
  430. return (common.Hash{}), err
  431. }
  432. t.root = cached
  433. t.cachegen++
  434. return common.BytesToHash(hash.(hashNode)), nil
  435. }
  436. func (t *Trie) hashRoot(db DatabaseWriter) (node, node, error) {
  437. if t.root == nil {
  438. return hashNode(emptyRoot.Bytes()), nil, nil
  439. }
  440. h := newHasher(t.cachegen, t.cachelimit)
  441. defer returnHasherToPool(h)
  442. return h.hash(t.root, db, true)
  443. }