hasher.go 5.1 KB

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