Skip to content
This repository has been archived by the owner on Feb 27, 2023. It is now read-only.

Commit

Permalink
GetLeaf returns LeafNode w/ ValueHash == nil
Browse files Browse the repository at this point in the history
  • Loading branch information
roysc committed Aug 1, 2021
1 parent f17d750 commit 56045a8
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
9 changes: 6 additions & 3 deletions smt.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ type SparseMerkleTree struct {
root []byte
}

// LeafNode represents the contents of a tree leaf.
// A LeafNode with ValueHash == nil represents an absent record.
type LeafNode struct {
Path []byte
ValueHash []byte
Expand Down Expand Up @@ -97,13 +99,14 @@ func (smt *SparseMerkleTree) Get(key []byte) ([]byte, error) {
}

// GetLeaf gets an entire leaf node from the tree.
// If the leaf is not found, a LeafNode is returned with ValueHash == nil
func (smt *SparseMerkleTree) GetLeaf(key []byte) (*LeafNode, error) {
path := smt.th.path(key)
if bytes.Equal(smt.root, smt.th.placeholder()) {
// The tree is empty, return the default value.
return nil, nil
return &LeafNode{Path: path, ValueHash: nil}, nil
}

path := smt.th.path(key)
currentHash := smt.root
for i := 0; i < smt.depth(); i++ {
currentData, err := smt.nodes.Get(currentHash)
Expand All @@ -114,7 +117,7 @@ func (smt *SparseMerkleTree) GetLeaf(key []byte) (*LeafNode, error) {
p, valueHash := smt.th.parseLeaf(currentData)
if !bytes.Equal(path, p) {
// Nope. Therefore the key is actually empty.
return nil, nil
return &LeafNode{Path: p, ValueHash: nil}, nil
}
// Otherwise, yes. Return the value.
return &LeafNode{Path: p, ValueHash: valueHash}, nil
Expand Down
7 changes: 5 additions & 2 deletions smt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -630,8 +630,11 @@ func TestGetLeaf(t *testing.T) {
if err != nil {
t.Errorf("returned error when getting empty key: %v", err)
}
if leaf != nil {
t.Error("did not get nil when getting empty key")
if leaf.ValueHash != nil {
t.Error("did not get nil ValueHash when getting empty key")
}
if leaf.Path == nil {
t.Error("got nil Path when getting empty key")
}

_, err = smt.Update([]byte("testKey"), []byte("testValue"))
Expand Down

0 comments on commit 56045a8

Please sign in to comment.