Skip to content

Commit 86dd005

Browse files
authored
trie: polish commit function (#21692)
* trie: polish commit function * trie: fix typo
1 parent 706f5e3 commit 86dd005

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

trie/stacktrie.go

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package trie
1818

1919
import (
20+
"errors"
2021
"fmt"
2122
"sync"
2223

@@ -26,6 +27,8 @@ import (
2627
"github.com/ethereum/go-ethereum/rlp"
2728
)
2829

30+
var ErrCommitDisabled = errors.New("no database for committing")
31+
2932
var stPool = sync.Pool{
3033
New: func() interface{} {
3134
return NewStackTrie(nil)
@@ -391,14 +394,18 @@ func (st *StackTrie) Hash() (h common.Hash) {
391394
return common.BytesToHash(st.val)
392395
}
393396

394-
// Commit will commit the current node to database db
395-
func (st *StackTrie) Commit(db ethdb.KeyValueStore) common.Hash {
396-
oldDb := st.db
397-
st.db = db
398-
defer func() {
399-
st.db = oldDb
400-
}()
397+
// Commit will firstly hash the entrie trie if it's still not hashed
398+
// and then commit all nodes to the associated database. Actually most
399+
// of the trie nodes MAY have been committed already. The main purpose
400+
// here is to commit the root node.
401+
//
402+
// The associated database is expected, otherwise the whole commit
403+
// functionality should be disabled.
404+
func (st *StackTrie) Commit() (common.Hash, error) {
405+
if st.db == nil {
406+
return common.Hash{}, ErrCommitDisabled
407+
}
401408
st.hash()
402409
h := common.BytesToHash(st.val)
403-
return h
410+
return h, nil
404411
}

trie/trie_test.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -831,7 +831,10 @@ func TestCommitSequenceStackTrie(t *testing.T) {
831831
// Flush memdb -> disk (sponge)
832832
db.Commit(root, false, nil)
833833
// And flush stacktrie -> disk
834-
stRoot := stTrie.Commit(stTrie.db)
834+
stRoot, err := stTrie.Commit()
835+
if err != nil {
836+
t.Fatalf("Failed to commit stack trie %v", err)
837+
}
835838
if stRoot != root {
836839
t.Fatalf("root wrong, got %x exp %x", stRoot, root)
837840
}

0 commit comments

Comments
 (0)