hasher.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. // Copyright 2019 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/rlp"
  21. "golang.org/x/crypto/sha3"
  22. )
  23. // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports
  24. // Read to get a variable amount of data from the hash state. Read is faster than Sum
  25. // because it doesn't copy the internal state, but also modifies the internal state.
  26. type keccakState interface {
  27. hash.Hash
  28. Read([]byte) (int, error)
  29. }
  30. type sliceBuffer []byte
  31. func (b *sliceBuffer) Write(data []byte) (n int, err error) {
  32. *b = append(*b, data...)
  33. return len(data), nil
  34. }
  35. func (b *sliceBuffer) Reset() {
  36. *b = (*b)[:0]
  37. }
  38. // hasher is a type used for the trie Hash operation. A hasher has some
  39. // internal preallocated temp space
  40. type hasher struct {
  41. sha keccakState
  42. tmp sliceBuffer
  43. parallel bool // Whether to use paralallel threads when hashing
  44. }
  45. // hasherPool holds pureHashers
  46. var hasherPool = sync.Pool{
  47. New: func() interface{} {
  48. return &hasher{
  49. tmp: make(sliceBuffer, 0, 550), // cap is as large as a full fullNode.
  50. sha: sha3.NewLegacyKeccak256().(keccakState),
  51. }
  52. },
  53. }
  54. func newHasher(parallel bool) *hasher {
  55. h := hasherPool.Get().(*hasher)
  56. h.parallel = parallel
  57. return h
  58. }
  59. func returnHasherToPool(h *hasher) {
  60. hasherPool.Put(h)
  61. }
  62. // hash collapses a node down into a hash node, also returning a copy of the
  63. // original node initialized with the computed hash to replace the original one.
  64. func (h *hasher) hash(n node, force bool) (hashed node, cached node) {
  65. // We're not storing the node, just hashing, use available cached data
  66. if hash, _ := n.cache(); hash != nil {
  67. return hash, n
  68. }
  69. // Trie not processed yet or needs storage, walk the children
  70. switch n := n.(type) {
  71. case *shortNode:
  72. collapsed, cached := h.hashShortNodeChildren(n)
  73. hashed := h.shortnodeToHash(collapsed, force)
  74. // We need to retain the possibly _not_ hashed node, in case it was too
  75. // small to be hashed
  76. if hn, ok := hashed.(hashNode); ok {
  77. cached.flags.hash = hn
  78. } else {
  79. cached.flags.hash = nil
  80. }
  81. return hashed, cached
  82. case *fullNode:
  83. collapsed, cached := h.hashFullNodeChildren(n)
  84. hashed = h.fullnodeToHash(collapsed, force)
  85. if hn, ok := hashed.(hashNode); ok {
  86. cached.flags.hash = hn
  87. } else {
  88. cached.flags.hash = nil
  89. }
  90. return hashed, cached
  91. default:
  92. // Value and hash nodes don't have children so they're left as were
  93. return n, n
  94. }
  95. }
  96. // hashShortNodeChildren collapses the short node. The returned collapsed node
  97. // holds a live reference to the Key, and must not be modified.
  98. // The cached
  99. func (h *hasher) hashShortNodeChildren(n *shortNode) (collapsed, cached *shortNode) {
  100. // Hash the short node's child, caching the newly hashed subtree
  101. collapsed, cached = n.copy(), n.copy()
  102. // Previously, we did copy this one. We don't seem to need to actually
  103. // do that, since we don't overwrite/reuse keys
  104. //cached.Key = common.CopyBytes(n.Key)
  105. collapsed.Key = hexToCompact(n.Key)
  106. // Unless the child is a valuenode or hashnode, hash it
  107. switch n.Val.(type) {
  108. case *fullNode, *shortNode:
  109. collapsed.Val, cached.Val = h.hash(n.Val, false)
  110. }
  111. return collapsed, cached
  112. }
  113. func (h *hasher) hashFullNodeChildren(n *fullNode) (collapsed *fullNode, cached *fullNode) {
  114. // Hash the full node's children, caching the newly hashed subtrees
  115. cached = n.copy()
  116. collapsed = n.copy()
  117. if h.parallel {
  118. var wg sync.WaitGroup
  119. wg.Add(16)
  120. for i := 0; i < 16; i++ {
  121. go func(i int) {
  122. hasher := newHasher(false)
  123. if child := n.Children[i]; child != nil {
  124. collapsed.Children[i], cached.Children[i] = hasher.hash(child, false)
  125. } else {
  126. collapsed.Children[i] = nilValueNode
  127. }
  128. returnHasherToPool(hasher)
  129. wg.Done()
  130. }(i)
  131. }
  132. wg.Wait()
  133. } else {
  134. for i := 0; i < 16; i++ {
  135. if child := n.Children[i]; child != nil {
  136. collapsed.Children[i], cached.Children[i] = h.hash(child, false)
  137. } else {
  138. collapsed.Children[i] = nilValueNode
  139. }
  140. }
  141. }
  142. return collapsed, cached
  143. }
  144. // shortnodeToHash creates a hashNode from a shortNode. The supplied shortnode
  145. // should have hex-type Key, which will be converted (without modification)
  146. // into compact form for RLP encoding.
  147. // If the rlp data is smaller than 32 bytes, `nil` is returned.
  148. func (h *hasher) shortnodeToHash(n *shortNode, force bool) node {
  149. h.tmp.Reset()
  150. if err := rlp.Encode(&h.tmp, n); err != nil {
  151. panic("encode error: " + err.Error())
  152. }
  153. if len(h.tmp) < 32 && !force {
  154. return n // Nodes smaller than 32 bytes are stored inside their parent
  155. }
  156. return h.hashData(h.tmp)
  157. }
  158. // shortnodeToHash is used to creates a hashNode from a set of hashNodes, (which
  159. // may contain nil values)
  160. func (h *hasher) fullnodeToHash(n *fullNode, force bool) node {
  161. h.tmp.Reset()
  162. // Generate the RLP encoding of the node
  163. if err := n.EncodeRLP(&h.tmp); err != nil {
  164. panic("encode error: " + err.Error())
  165. }
  166. if len(h.tmp) < 32 && !force {
  167. return n // Nodes smaller than 32 bytes are stored inside their parent
  168. }
  169. return h.hashData(h.tmp)
  170. }
  171. // hashData hashes the provided data
  172. func (h *hasher) hashData(data []byte) hashNode {
  173. n := make(hashNode, 32)
  174. h.sha.Reset()
  175. h.sha.Write(data)
  176. h.sha.Read(n)
  177. return n
  178. }
  179. // proofHash is used to construct trie proofs, and returns the 'collapsed'
  180. // node (for later RLP encoding) aswell as the hashed node -- unless the
  181. // node is smaller than 32 bytes, in which case it will be returned as is.
  182. // This method does not do anything on value- or hash-nodes.
  183. func (h *hasher) proofHash(original node) (collapsed, hashed node) {
  184. switch n := original.(type) {
  185. case *shortNode:
  186. sn, _ := h.hashShortNodeChildren(n)
  187. return sn, h.shortnodeToHash(sn, false)
  188. case *fullNode:
  189. fn, _ := h.hashFullNodeChildren(n)
  190. return fn, h.fullnodeToHash(fn, false)
  191. default:
  192. // Value and hash nodes don't have children so they're left as were
  193. return n, n
  194. }
  195. }