trie: polish commit function (#21692)

* trie: polish commit function

* trie: fix typo
This commit is contained in:
gary rong 2020-10-12 18:08:04 +08:00 committed by GitHub
parent 706f5e3b98
commit 86dd005544
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 9 deletions

View File

@ -17,6 +17,7 @@
package trie package trie
import ( import (
"errors"
"fmt" "fmt"
"sync" "sync"
@ -26,6 +27,8 @@ import (
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
) )
var ErrCommitDisabled = errors.New("no database for committing")
var stPool = sync.Pool{ var stPool = sync.Pool{
New: func() interface{} { New: func() interface{} {
return NewStackTrie(nil) return NewStackTrie(nil)
@ -391,14 +394,18 @@ func (st *StackTrie) Hash() (h common.Hash) {
return common.BytesToHash(st.val) return common.BytesToHash(st.val)
} }
// Commit will commit the current node to database db // Commit will firstly hash the entrie trie if it's still not hashed
func (st *StackTrie) Commit(db ethdb.KeyValueStore) common.Hash { // and then commit all nodes to the associated database. Actually most
oldDb := st.db // of the trie nodes MAY have been committed already. The main purpose
st.db = db // here is to commit the root node.
defer func() { //
st.db = oldDb // The associated database is expected, otherwise the whole commit
}() // functionality should be disabled.
func (st *StackTrie) Commit() (common.Hash, error) {
if st.db == nil {
return common.Hash{}, ErrCommitDisabled
}
st.hash() st.hash()
h := common.BytesToHash(st.val) h := common.BytesToHash(st.val)
return h return h, nil
} }

View File

@ -831,7 +831,10 @@ func TestCommitSequenceStackTrie(t *testing.T) {
// Flush memdb -> disk (sponge) // Flush memdb -> disk (sponge)
db.Commit(root, false, nil) db.Commit(root, false, nil)
// And flush stacktrie -> disk // And flush stacktrie -> disk
stRoot := stTrie.Commit(stTrie.db) stRoot, err := stTrie.Commit()
if err != nil {
t.Fatalf("Failed to commit stack trie %v", err)
}
if stRoot != root { if stRoot != root {
t.Fatalf("root wrong, got %x exp %x", stRoot, root) t.Fatalf("root wrong, got %x exp %x", stRoot, root)
} }