hasher.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. cacheUnloadCounter.Inc(1)
  56. return hash, hash, nil
  57. }
  58. if !dirty {
  59. return hash, n, nil
  60. }
  61. }
  62. // Trie not processed yet or needs storage, walk the children
  63. collapsed, cached, err := h.hashChildren(n, db)
  64. if err != nil {
  65. return hashNode{}, n, err
  66. }
  67. hashed, err := h.store(collapsed, db, force)
  68. if err != nil {
  69. return hashNode{}, n, err
  70. }
  71. // Cache the hash of the ndoe for later reuse and remove
  72. // the dirty flag in commit mode. It's fine to assign these values directly
  73. // without copying the node first because hashChildren copies it.
  74. cachedHash, _ := hashed.(hashNode)
  75. switch cn := cached.(type) {
  76. case *shortNode:
  77. cn.flags.hash = cachedHash
  78. if db != nil {
  79. cn.flags.dirty = false
  80. }
  81. case *fullNode:
  82. cn.flags.hash = cachedHash
  83. if db != nil {
  84. cn.flags.dirty = false
  85. }
  86. }
  87. return hashed, cached, nil
  88. }
  89. // hashChildren replaces the children of a node with their hashes if the encoded
  90. // size of the child is larger than a hash, returning the collapsed node as well
  91. // as a replacement for the original node with the child hashes cached in.
  92. func (h *hasher) hashChildren(original node, db DatabaseWriter) (node, node, error) {
  93. var err error
  94. switch n := original.(type) {
  95. case *shortNode:
  96. // Hash the short node's child, caching the newly hashed subtree
  97. collapsed, cached := n.copy(), n.copy()
  98. collapsed.Key = compactEncode(n.Key)
  99. cached.Key = common.CopyBytes(n.Key)
  100. if _, ok := n.Val.(valueNode); !ok {
  101. collapsed.Val, cached.Val, err = h.hash(n.Val, db, false)
  102. if err != nil {
  103. return original, original, err
  104. }
  105. }
  106. if collapsed.Val == nil {
  107. collapsed.Val = valueNode(nil) // Ensure that nil children are encoded as empty strings.
  108. }
  109. return collapsed, cached, nil
  110. case *fullNode:
  111. // Hash the full node's children, caching the newly hashed subtrees
  112. collapsed, cached := n.copy(), n.copy()
  113. for i := 0; i < 16; i++ {
  114. if n.Children[i] != nil {
  115. collapsed.Children[i], cached.Children[i], err = h.hash(n.Children[i], db, false)
  116. if err != nil {
  117. return original, original, err
  118. }
  119. } else {
  120. collapsed.Children[i] = valueNode(nil) // Ensure that nil children are encoded as empty strings.
  121. }
  122. }
  123. cached.Children[16] = n.Children[16]
  124. if collapsed.Children[16] == nil {
  125. collapsed.Children[16] = valueNode(nil)
  126. }
  127. return collapsed, cached, nil
  128. default:
  129. // Value and hash nodes don't have children so they're left as were
  130. return n, original, nil
  131. }
  132. }
  133. func (h *hasher) store(n node, db DatabaseWriter, force bool) (node, error) {
  134. // Don't store hashes or empty nodes.
  135. if _, isHash := n.(hashNode); n == nil || isHash {
  136. return n, nil
  137. }
  138. // Generate the RLP encoding of the node
  139. h.tmp.Reset()
  140. if err := rlp.Encode(h.tmp, n); err != nil {
  141. panic("encode error: " + err.Error())
  142. }
  143. if h.tmp.Len() < 32 && !force {
  144. return n, nil // Nodes smaller than 32 bytes are stored inside their parent
  145. }
  146. // Larger nodes are replaced by their hash and stored in the database.
  147. hash, _ := n.cache()
  148. if hash == nil {
  149. h.sha.Reset()
  150. h.sha.Write(h.tmp.Bytes())
  151. hash = hashNode(h.sha.Sum(nil))
  152. }
  153. if db != nil {
  154. return hash, db.Put(hash, h.tmp.Bytes())
  155. }
  156. return hash, nil
  157. }