diff --git a/trie/hasher.go b/trie/hasher.go index 816a29857c..e333928ce6 100644 --- a/trie/hasher.go +++ b/trie/hasher.go @@ -70,10 +70,15 @@ var hasherPool = sync.Pool{ func newHasher(onleaf LeafCallback) *hasher { h := hasherPool.Get().(*hasher) h.onleaf = onleaf + if onleaf != nil { + h.leafCh = make(chan *Leaf, 200) // arbitrary number + } return h } func returnHasherToPool(h *hasher) { + h.onleaf = nil + h.leafCh = nil hasherPool.Put(h) } @@ -185,12 +190,21 @@ func (h *hasher) store(n node, db *Database, force bool) (node, error) { if hash == nil { hash = h.makeHashNode(h.tmp) } - if db != nil { + // If we're using channel-based leaf-reporting, send to channel. + // The leaf channel will be active only when there an active leaf-callback + if h.leafCh != nil { h.leafCh <- &Leaf{ size: len(h.tmp), hash: common.BytesToHash(hash), node: n, } + } else if db != nil { + // No leaf-callback used, but there's still a database. Do serial + // insertion + db.lock.Lock() + db.insert(common.BytesToHash(hash), len(h.tmp), n) + db.lock.Unlock() + } return hash, nil } diff --git a/trie/trie.go b/trie/trie.go index 9efc8657a3..60a96b02a3 100644 --- a/trie/trie.go +++ b/trie/trie.go @@ -420,14 +420,17 @@ func (t *Trie) Commit(onleaf LeafCallback) (root common.Hash, err error) { return emptyRoot, nil } h := newHasher(onleaf) - h.leafCh = make(chan *Leaf, 200) // arbitrary number defer returnHasherToPool(h) var wg sync.WaitGroup - wg.Add(1) - go h.commitLoop(t.db, &wg) - hash, cached, err := h.hash(t.root, t.db, true) - close(h.leafCh) - wg.Wait() + if onleaf != nil { + wg.Add(1) + go h.commitLoop(t.db, &wg) + } + hash, cached, err := h.hash(t.root, t.db, true) + if onleaf != nil { + close(h.leafCh) + wg.Wait() + } if err != nil { return common.Hash{}, err } @@ -443,4 +446,3 @@ func (t *Trie) hashRoot(db *Database, onleaf LeafCallback) (node, node, error) { defer returnHasherToPool(h) return h.hash(t.root, db, true) } - diff --git a/trie/trie_test.go b/trie/trie_test.go index 86bb831370..82c1421c3e 100644 --- a/trie/trie_test.go +++ b/trie/trie_test.go @@ -637,7 +637,7 @@ func benchmarkCommitAfterHashFixedSize(b *testing.B, addresses [][20]byte, accou // Insert the accounts into the trie and hash it trie.Hash() b.StartTimer() - trie.Commit(nil) + trie.Commit() b.StopTimer() }