trie.go 13 KB

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