trie.go 15 KB

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