Skip to content

Commit

Permalink
Reuse node.EncodeAndHash inside trie.Hash
Browse files Browse the repository at this point in the history
  • Loading branch information
kishansagathiya committed Mar 9, 2022
1 parent 9852ed0 commit 38d9157
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 32 deletions.
22 changes: 1 addition & 21 deletions lib/trie/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,16 +377,6 @@ func (t *Trie) writeDirty(db chaindb.Batch, n Node) error {
n.GetHash(), err)
}

if n == t.root {
// hash root node even if its encoding is under 32 bytes
encodingDigest, err := common.Blake2bHash(encoding)
if err != nil {
return fmt.Errorf("cannot hash root node encoding: %w", err)
}

hash = encodingDigest[:]
}

err = db.Put(hash, encoding)
if err != nil {
return fmt.Errorf(
Expand Down Expand Up @@ -446,23 +436,13 @@ func (t *Trie) getInsertedNodeHashes(n Node, hashes map[common.Hash]struct{}) (e
return nil
}

encoding, hash, err := n.EncodeAndHash(n == t.root)
_, hash, err := n.EncodeAndHash(n == t.root)
if err != nil {
return fmt.Errorf(
"cannot encode and hash node with hash 0x%x: %w",
n.GetHash(), err)
}

if n == t.root && len(encoding) < 32 {
// hash root node even if its encoding is under 32 bytes
encodingDigest, err := common.Blake2bHash(encoding)
if err != nil {
return fmt.Errorf("cannot hash root node encoding: %w", err)
}

hash = encodingDigest[:]
}

hashes[common.BytesToHash(hash)] = struct{}{}

switch n.Type() {
Expand Down
13 changes: 2 additions & 11 deletions lib/trie/trie.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (

"github.com/ChainSafe/gossamer/internal/trie/codec"
"github.com/ChainSafe/gossamer/internal/trie/node"
"github.com/ChainSafe/gossamer/internal/trie/pools"
"github.com/ChainSafe/gossamer/lib/common"
)

Expand Down Expand Up @@ -155,16 +154,8 @@ func (t *Trie) MustHash() common.Hash {

// Hash returns the hashed root of the trie.
func (t *Trie) Hash() (rootHash common.Hash, err error) {
buffer := pools.EncodingBuffers.Get().(*bytes.Buffer)
buffer.Reset()
defer pools.EncodingBuffers.Put(buffer)

err = encodeRoot(t.root, buffer)
if err != nil {
return [32]byte{}, err
}

return common.Blake2bHash(buffer.Bytes()) // TODO optimisation: use hashers sync pools
_, hash, err := t.root.EncodeAndHash(true)
return common.BytesToHash(hash), err
}

// Entries returns all the key-value pairs in the trie as a map of keys to values
Expand Down

0 comments on commit 38d9157

Please sign in to comment.