hasher.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. // Copyright 2016 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
  17. import (
  18. "bytes"
  19. "hash"
  20. "sync"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/crypto/sha3"
  23. "github.com/ethereum/go-ethereum/rlp"
  24. )
  25. type hasher struct {
  26. tmp *bytes.Buffer
  27. sha hash.Hash
  28. cachegen, cachelimit uint16
  29. }
  30. // hashers live in a global pool.
  31. var hasherPool = sync.Pool{
  32. New: func() interface{} {
  33. return &hasher{tmp: new(bytes.Buffer), sha: sha3.NewKeccak256()}
  34. },
  35. }
  36. func newHasher(cachegen, cachelimit uint16) *hasher {
  37. h := hasherPool.Get().(*hasher)
  38. h.cachegen, h.cachelimit = cachegen, cachelimit
  39. return h
  40. }
  41. func returnHasherToPool(h *hasher) {
  42. hasherPool.Put(h)
  43. }
  44. // hash collapses a node down into a hash node, also returning a copy of the
  45. // original node initialzied with the computed hash to replace the original one.
  46. func (h *hasher) hash(n node, db DatabaseWriter, force bool) (node, node, error) {
  47. // If we're not storing the node, just hashing, use avaialble cached data
  48. if hash, dirty := n.cache(); hash != nil {
  49. if db == nil {
  50. return hash, n, nil
  51. }
  52. if n.canUnload(h.cachegen, h.cachelimit) {
  53. // Unload the node from cache. All of its subnodes will have a lower or equal
  54. // cache generation number.
  55. return hash, hash, nil
  56. }
  57. if !dirty {
  58. return hash, n, nil
  59. }
  60. }
  61. // Trie not processed yet or needs storage, walk the children
  62. collapsed, cached, err := h.hashChildren(n, db)
  63. if err != nil {
  64. return hashNode{}, n, err
  65. }
  66. hashed, err := h.store(collapsed, db, force)
  67. if err != nil {
  68. return hashNode{}, n, err
  69. }
  70. // Cache the hash of the ndoe for later reuse.
  71. if hash, ok := hashed.(hashNode); ok && !force {
  72. switch cached := cached.(type) {
  73. case *shortNode:
  74. cached = cached.copy()
  75. cached.flags.hash = hash
  76. if db != nil {
  77. cached.flags.dirty = false
  78. }
  79. return hashed, cached, nil
  80. case *fullNode:
  81. cached = cached.copy()
  82. cached.flags.hash = hash
  83. if db != nil {
  84. cached.flags.dirty = false
  85. }
  86. return hashed, cached, nil
  87. }
  88. }
  89. return hashed, cached, nil
  90. }
  91. // hashChildren replaces the children of a node with their hashes if the encoded
  92. // size of the child is larger than a hash, returning the collapsed node as well
  93. // as a replacement for the original node with the child hashes cached in.
  94. func (h *hasher) hashChildren(original node, db DatabaseWriter) (node, node, error) {
  95. var err error
  96. switch n := original.(type) {
  97. case *shortNode:
  98. // Hash the short node's child, caching the newly hashed subtree
  99. collapsed, cached := n.copy(), n.copy()
  100. collapsed.Key = compactEncode(n.Key)
  101. cached.Key = common.CopyBytes(n.Key)
  102. if _, ok := n.Val.(valueNode); !ok {
  103. collapsed.Val, cached.Val, err = h.hash(n.Val, db, false)
  104. if err != nil {
  105. return original, original, err
  106. }
  107. }
  108. if collapsed.Val == nil {
  109. collapsed.Val = valueNode(nil) // Ensure that nil children are encoded as empty strings.
  110. }
  111. return collapsed, cached, nil
  112. case *fullNode:
  113. // Hash the full node's children, caching the newly hashed subtrees
  114. collapsed, cached := n.copy(), n.copy()
  115. for i := 0; i < 16; i++ {
  116. if n.Children[i] != nil {
  117. collapsed.Children[i], cached.Children[i], err = h.hash(n.Children[i], db, false)
  118. if err != nil {
  119. return original, original, err
  120. }
  121. } else {
  122. collapsed.Children[i] = valueNode(nil) // Ensure that nil children are encoded as empty strings.
  123. }
  124. }
  125. cached.Children[16] = n.Children[16]
  126. if collapsed.Children[16] == nil {
  127. collapsed.Children[16] = valueNode(nil)
  128. }
  129. return collapsed, cached, nil
  130. default:
  131. // Value and hash nodes don't have children so they're left as were
  132. return n, original, nil
  133. }
  134. }
  135. func (h *hasher) store(n node, db DatabaseWriter, force bool) (node, error) {
  136. // Don't store hashes or empty nodes.
  137. if _, isHash := n.(hashNode); n == nil || isHash {
  138. return n, nil
  139. }
  140. // Generate the RLP encoding of the node
  141. h.tmp.Reset()
  142. if err := rlp.Encode(h.tmp, n); err != nil {
  143. panic("encode error: " + err.Error())
  144. }
  145. if h.tmp.Len() < 32 && !force {
  146. return n, nil // Nodes smaller than 32 bytes are stored inside their parent
  147. }
  148. // Larger nodes are replaced by their hash and stored in the database.
  149. hash, _ := n.cache()
  150. if hash == nil {
  151. h.sha.Reset()
  152. h.sha.Write(h.tmp.Bytes())
  153. hash = hashNode(h.sha.Sum(nil))
  154. }
  155. if db != nil {
  156. return hash, db.Put(hash, h.tmp.Bytes())
  157. }
  158. return hash, nil
  159. }