trie.go 13 KB

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