trie.go 14 KB

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