hasher.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. "hash"
  19. "sync"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/crypto/sha3"
  22. "github.com/ethereum/go-ethereum/rlp"
  23. )
  24. type hasher struct {
  25. tmp sliceBuffer
  26. sha keccakState
  27. cachegen uint16
  28. cachelimit uint16
  29. onleaf LeafCallback
  30. }
  31. // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports
  32. // Read to get a variable amount of data from the hash state. Read is faster than Sum
  33. // because it doesn't copy the internal state, but also modifies the internal state.
  34. type keccakState interface {
  35. hash.Hash
  36. Read([]byte) (int, error)
  37. }
  38. type sliceBuffer []byte
  39. func (b *sliceBuffer) Write(data []byte) (n int, err error) {
  40. *b = append(*b, data...)
  41. return len(data), nil
  42. }
  43. func (b *sliceBuffer) Reset() {
  44. *b = (*b)[:0]
  45. }
  46. // hashers live in a global db.
  47. var hasherPool = sync.Pool{
  48. New: func() interface{} {
  49. return &hasher{
  50. tmp: make(sliceBuffer, 0, 550), // cap is as large as a full fullNode.
  51. sha: sha3.NewKeccak256().(keccakState),
  52. }
  53. },
  54. }
  55. func newHasher(cachegen, cachelimit uint16, onleaf LeafCallback) *hasher {
  56. h := hasherPool.Get().(*hasher)
  57. h.cachegen, h.cachelimit, h.onleaf = cachegen, cachelimit, onleaf
  58. return h
  59. }
  60. func returnHasherToPool(h *hasher) {
  61. hasherPool.Put(h)
  62. }
  63. // hash collapses a node down into a hash node, also returning a copy of the
  64. // original node initialized with the computed hash to replace the original one.
  65. func (h *hasher) hash(n node, db *Database, force bool) (node, node, error) {
  66. // If we're not storing the node, just hashing, use available cached data
  67. if hash, dirty := n.cache(); hash != nil {
  68. if db == nil {
  69. return hash, n, nil
  70. }
  71. if n.canUnload(h.cachegen, h.cachelimit) {
  72. // Unload the node from cache. All of its subnodes will have a lower or equal
  73. // cache generation number.
  74. cacheUnloadCounter.Inc(1)
  75. return hash, hash, nil
  76. }
  77. if !dirty {
  78. return hash, n, nil
  79. }
  80. }
  81. // Trie not processed yet or needs storage, walk the children
  82. collapsed, cached, err := h.hashChildren(n, db)
  83. if err != nil {
  84. return hashNode{}, n, err
  85. }
  86. hashed, err := h.store(collapsed, db, force)
  87. if err != nil {
  88. return hashNode{}, n, err
  89. }
  90. // Cache the hash of the node for later reuse and remove
  91. // the dirty flag in commit mode. It's fine to assign these values directly
  92. // without copying the node first because hashChildren copies it.
  93. cachedHash, _ := hashed.(hashNode)
  94. switch cn := cached.(type) {
  95. case *shortNode:
  96. cn.flags.hash = cachedHash
  97. if db != nil {
  98. cn.flags.dirty = false
  99. }
  100. case *fullNode:
  101. cn.flags.hash = cachedHash
  102. if db != nil {
  103. cn.flags.dirty = false
  104. }
  105. }
  106. return hashed, cached, nil
  107. }
  108. // hashChildren replaces the children of a node with their hashes if the encoded
  109. // size of the child is larger than a hash, returning the collapsed node as well
  110. // as a replacement for the original node with the child hashes cached in.
  111. func (h *hasher) hashChildren(original node, db *Database) (node, node, error) {
  112. var err error
  113. switch n := original.(type) {
  114. case *shortNode:
  115. // Hash the short node's child, caching the newly hashed subtree
  116. collapsed, cached := n.copy(), n.copy()
  117. collapsed.Key = hexToCompact(n.Key)
  118. cached.Key = common.CopyBytes(n.Key)
  119. if _, ok := n.Val.(valueNode); !ok {
  120. collapsed.Val, cached.Val, err = h.hash(n.Val, db, false)
  121. if err != nil {
  122. return original, original, err
  123. }
  124. }
  125. return collapsed, cached, nil
  126. case *fullNode:
  127. // Hash the full node's children, caching the newly hashed subtrees
  128. collapsed, cached := n.copy(), n.copy()
  129. for i := 0; i < 16; i++ {
  130. if n.Children[i] != nil {
  131. collapsed.Children[i], cached.Children[i], err = h.hash(n.Children[i], db, false)
  132. if err != nil {
  133. return original, original, err
  134. }
  135. }
  136. }
  137. cached.Children[16] = n.Children[16]
  138. return collapsed, cached, nil
  139. default:
  140. // Value and hash nodes don't have children so they're left as were
  141. return n, original, nil
  142. }
  143. }
  144. // store hashes the node n and if we have a storage layer specified, it writes
  145. // the key/value pair to it and tracks any node->child references as well as any
  146. // node->external trie references.
  147. func (h *hasher) store(n node, db *Database, force bool) (node, error) {
  148. // Don't store hashes or empty nodes.
  149. if _, isHash := n.(hashNode); n == nil || isHash {
  150. return n, nil
  151. }
  152. // Generate the RLP encoding of the node
  153. h.tmp.Reset()
  154. if err := rlp.Encode(&h.tmp, n); err != nil {
  155. panic("encode error: " + err.Error())
  156. }
  157. if len(h.tmp) < 32 && !force {
  158. return n, nil // Nodes smaller than 32 bytes are stored inside their parent
  159. }
  160. // Larger nodes are replaced by their hash and stored in the database.
  161. hash, _ := n.cache()
  162. if hash == nil {
  163. hash = h.makeHashNode(h.tmp)
  164. }
  165. if db != nil {
  166. // We are pooling the trie nodes into an intermediate memory cache
  167. hash := common.BytesToHash(hash)
  168. db.lock.Lock()
  169. db.insert(hash, h.tmp, n)
  170. db.lock.Unlock()
  171. // Track external references from account->storage trie
  172. if h.onleaf != nil {
  173. switch n := n.(type) {
  174. case *shortNode:
  175. if child, ok := n.Val.(valueNode); ok {
  176. h.onleaf(child, hash)
  177. }
  178. case *fullNode:
  179. for i := 0; i < 16; i++ {
  180. if child, ok := n.Children[i].(valueNode); ok {
  181. h.onleaf(child, hash)
  182. }
  183. }
  184. }
  185. }
  186. }
  187. return hash, nil
  188. }
  189. func (h *hasher) makeHashNode(data []byte) hashNode {
  190. n := make(hashNode, h.sha.Size())
  191. h.sha.Reset()
  192. h.sha.Write(data)
  193. h.sha.Read(n)
  194. return n
  195. }