committer.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. "errors"
  19. "fmt"
  20. "sync"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/rlp"
  23. "golang.org/x/crypto/sha3"
  24. )
  25. // leafChanSize is the size of the leafCh. It's a pretty arbitrary number, to allow
  26. // some parallelism but not incur too much memory overhead.
  27. const leafChanSize = 200
  28. // leaf represents a trie leaf value
  29. type leaf struct {
  30. size int // size of the rlp data (estimate)
  31. hash common.Hash // hash of rlp data
  32. node node // the node to commit
  33. vnodes bool // set to true if the node (possibly) contains a valueNode
  34. }
  35. // committer is a type used for the trie Commit operation. A committer has some
  36. // internal preallocated temp space, and also a callback that is invoked when
  37. // leaves are committed. The leafs are passed through the `leafCh`, to allow
  38. // some level of parallelism.
  39. // By 'some level' of parallelism, it's still the case that all leaves will be
  40. // processed sequentially - onleaf will never be called in parallel or out of order.
  41. type committer struct {
  42. tmp sliceBuffer
  43. sha keccakState
  44. onleaf LeafCallback
  45. leafCh chan *leaf
  46. }
  47. // committers live in a global sync.Pool
  48. var committerPool = sync.Pool{
  49. New: func() interface{} {
  50. return &committer{
  51. tmp: make(sliceBuffer, 0, 550), // cap is as large as a full fullNode.
  52. sha: sha3.NewLegacyKeccak256().(keccakState),
  53. }
  54. },
  55. }
  56. // newCommitter creates a new committer or picks one from the pool.
  57. func newCommitter() *committer {
  58. return committerPool.Get().(*committer)
  59. }
  60. func returnCommitterToPool(h *committer) {
  61. h.onleaf = nil
  62. h.leafCh = nil
  63. committerPool.Put(h)
  64. }
  65. // commitNeeded returns 'false' if the given node is already in sync with db
  66. func (c *committer) commitNeeded(n node) bool {
  67. hash, dirty := n.cache()
  68. return hash == nil || dirty
  69. }
  70. // commit collapses a node down into a hash node and inserts it into the database
  71. func (c *committer) Commit(n node, db *Database) (hashNode, error) {
  72. if db == nil {
  73. return nil, errors.New("no db provided")
  74. }
  75. h, err := c.commit(n, db, true)
  76. if err != nil {
  77. return nil, err
  78. }
  79. return h.(hashNode), nil
  80. }
  81. // commit collapses a node down into a hash node and inserts it into the database
  82. func (c *committer) commit(n node, db *Database, force bool) (node, error) {
  83. // if this path is clean, use available cached data
  84. hash, dirty := n.cache()
  85. if hash != nil && !dirty {
  86. return hash, nil
  87. }
  88. // Commit children, then parent, and remove remove the dirty flag.
  89. switch cn := n.(type) {
  90. case *shortNode:
  91. // Commit child
  92. collapsed := cn.copy()
  93. if _, ok := cn.Val.(valueNode); !ok {
  94. if childV, err := c.commit(cn.Val, db, false); err != nil {
  95. return nil, err
  96. } else {
  97. collapsed.Val = childV
  98. }
  99. }
  100. // The key needs to be copied, since we're delivering it to database
  101. collapsed.Key = hexToCompact(cn.Key)
  102. hashedNode := c.store(collapsed, db, force, true)
  103. if hn, ok := hashedNode.(hashNode); ok {
  104. return hn, nil
  105. } else {
  106. return collapsed, nil
  107. }
  108. case *fullNode:
  109. hashedKids, hasVnodes, err := c.commitChildren(cn, db, force)
  110. if err != nil {
  111. return nil, err
  112. }
  113. collapsed := cn.copy()
  114. collapsed.Children = hashedKids
  115. hashedNode := c.store(collapsed, db, force, hasVnodes)
  116. if hn, ok := hashedNode.(hashNode); ok {
  117. return hn, nil
  118. } else {
  119. return collapsed, nil
  120. }
  121. case valueNode:
  122. return c.store(cn, db, force, false), nil
  123. // hashnodes aren't stored
  124. case hashNode:
  125. return cn, nil
  126. }
  127. return hash, nil
  128. }
  129. // commitChildren commits the children of the given fullnode
  130. func (c *committer) commitChildren(n *fullNode, db *Database, force bool) ([17]node, bool, error) {
  131. var children [17]node
  132. var hasValueNodeChildren = false
  133. for i, child := range n.Children {
  134. if child == nil {
  135. continue
  136. }
  137. hnode, err := c.commit(child, db, false)
  138. if err != nil {
  139. return children, false, err
  140. }
  141. children[i] = hnode
  142. if _, ok := hnode.(valueNode); ok {
  143. hasValueNodeChildren = true
  144. }
  145. }
  146. return children, hasValueNodeChildren, nil
  147. }
  148. // store hashes the node n and if we have a storage layer specified, it writes
  149. // the key/value pair to it and tracks any node->child references as well as any
  150. // node->external trie references.
  151. func (c *committer) store(n node, db *Database, force bool, hasVnodeChildren bool) node {
  152. // Larger nodes are replaced by their hash and stored in the database.
  153. var (
  154. hash, _ = n.cache()
  155. size int
  156. )
  157. if hash == nil {
  158. if vn, ok := n.(valueNode); ok {
  159. c.tmp.Reset()
  160. if err := rlp.Encode(&c.tmp, vn); err != nil {
  161. panic("encode error: " + err.Error())
  162. }
  163. size = len(c.tmp)
  164. if size < 32 && !force {
  165. return n // Nodes smaller than 32 bytes are stored inside their parent
  166. }
  167. hash = c.makeHashNode(c.tmp)
  168. } else {
  169. // This was not generated - must be a small node stored in the parent
  170. // No need to do anything here
  171. return n
  172. }
  173. } else {
  174. // We have the hash already, estimate the RLP encoding-size of the node.
  175. // The size is used for mem tracking, does not need to be exact
  176. size = estimateSize(n)
  177. }
  178. // If we're using channel-based leaf-reporting, send to channel.
  179. // The leaf channel will be active only when there an active leaf-callback
  180. if c.leafCh != nil {
  181. c.leafCh <- &leaf{
  182. size: size,
  183. hash: common.BytesToHash(hash),
  184. node: n,
  185. vnodes: hasVnodeChildren,
  186. }
  187. } else if db != nil {
  188. // No leaf-callback used, but there's still a database. Do serial
  189. // insertion
  190. db.lock.Lock()
  191. db.insert(common.BytesToHash(hash), size, n)
  192. db.lock.Unlock()
  193. }
  194. return hash
  195. }
  196. // commitLoop does the actual insert + leaf callback for nodes
  197. func (c *committer) commitLoop(db *Database) {
  198. for item := range c.leafCh {
  199. var (
  200. hash = item.hash
  201. size = item.size
  202. n = item.node
  203. hasVnodes = item.vnodes
  204. )
  205. // We are pooling the trie nodes into an intermediate memory cache
  206. db.lock.Lock()
  207. db.insert(hash, size, n)
  208. db.lock.Unlock()
  209. if c.onleaf != nil && hasVnodes {
  210. switch n := n.(type) {
  211. case *shortNode:
  212. if child, ok := n.Val.(valueNode); ok {
  213. c.onleaf(child, hash)
  214. }
  215. case *fullNode:
  216. for i := 0; i < 16; i++ {
  217. if child, ok := n.Children[i].(valueNode); ok {
  218. c.onleaf(child, hash)
  219. }
  220. }
  221. }
  222. }
  223. }
  224. }
  225. func (c *committer) makeHashNode(data []byte) hashNode {
  226. n := make(hashNode, c.sha.Size())
  227. c.sha.Reset()
  228. c.sha.Write(data)
  229. c.sha.Read(n)
  230. return n
  231. }
  232. // estimateSize estimates the size of an rlp-encoded node, without actually
  233. // rlp-encoding it (zero allocs). This method has been experimentally tried, and with a trie
  234. // with 1000 leafs, the only errors above 1% are on small shortnodes, where this
  235. // method overestimates by 2 or 3 bytes (e.g. 37 instead of 35)
  236. func estimateSize(n node) int {
  237. switch n := n.(type) {
  238. case *shortNode:
  239. // A short node contains a compacted key, and a value.
  240. return 3 + len(n.Key) + estimateSize(n.Val)
  241. case *fullNode:
  242. // A full node contains up to 16 hashes (some nils), and a key
  243. s := 3
  244. for i := 0; i < 16; i++ {
  245. if child := n.Children[i]; child != nil {
  246. s += estimateSize(child)
  247. } else {
  248. s += 1
  249. }
  250. }
  251. return s
  252. case valueNode:
  253. return 1 + len(n)
  254. case hashNode:
  255. return 1 + len(n)
  256. default:
  257. panic(fmt.Sprintf("node type %T", n))
  258. }
  259. }