trie: make commit collapse into hashnode, don't touch dirtyness

This commit is contained in:
Martin Holst Swende 2020-01-08 11:49:38 +01:00
parent 692b758c75
commit 8e8e8d6444
No known key found for this signature in database
GPG key ID: 683B438C05A5DDF0
2 changed files with 22 additions and 6 deletions

View file

@ -79,6 +79,22 @@ func (c *committer) commitNeeded(n node) bool {
return hash == nil || dirty
}
// commit collapses a node down into a hash node and inserts it into the database
func (c *committer) Commit(n node, db *Database) (hashNode, error) {
if db == nil {
return nil, errors.New("no db provided")
}
h, err := c.commit(n, db, true)
if err != nil {
return nil, err
}
hn, ok := h.(hashNode)
if !ok {
panic("commit did not hash down to a hashnode!")
}
return hn, nil
}
// commit collapses a node down into a hash node and inserts it into the database
func (c *committer) commit(n node, db *Database, force bool) (node, error) {
// if this path is clean, use available cached data
@ -86,9 +102,6 @@ func (c *committer) commit(n node, db *Database, force bool) (node, error) {
if hash != nil && !dirty {
return hash, nil
}
if db == nil {
return nil, errors.New("no db provided")
}
// Commit children, then parent, and remove remove the dirty flag.
switch cn := n.(type) {
case *shortNode:
@ -105,7 +118,6 @@ func (c *committer) commit(n node, db *Database, force bool) (node, error) {
collapsed.Key = hexToCompact(cn.Key)
hashedNode := c.store(collapsed, db, force, true)
if hn, ok := hashedNode.(hashNode); ok {
cn.flags.dirty = false
return hn, nil
} else {
return collapsed, nil
@ -120,7 +132,6 @@ func (c *committer) commit(n node, db *Database, force bool) (node, error) {
hashedNode := c.store(collapsed, db, force, hasVnodes)
if hn, ok := hashedNode.(hashNode); ok {
cn.flags.dirty = false
return hn, nil
} else {
return collapsed, nil

View file

@ -438,7 +438,8 @@ func (t *Trie) Commit(onleaf LeafCallback) (root common.Hash, err error) {
h.commitLoop(t.db)
}()
}
_, err = h.commit(t.root, t.db, true)
var newRoot hashNode
newRoot, err = h.Commit(t.root, t.db)
if onleaf != nil {
// The leafch is created in newCommitter if there was an onleaf callback
// provided. The commitLoop only _reads_ from it, and the commit
@ -450,6 +451,10 @@ func (t *Trie) Commit(onleaf LeafCallback) (root common.Hash, err error) {
if err != nil {
return common.Hash{}, err
}
if common.BytesToHash(newRoot) != rootHash{
panic(fmt.Sprintf("Committed root %x != roothash %x", newRoot, rootHash))
}
t.root = newRoot
return rootHash, nil
}