Skip to content

Commit

Permalink
feat: enforce path length check in ClosestProof and its validation
Browse files Browse the repository at this point in the history
  • Loading branch information
h5law committed Mar 20, 2024
1 parent d58a69b commit 9ea65a3
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
3 changes: 3 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,7 @@ var (
ErrBadProof = errors.New("bad proof")
// ErrKeyNotFound is returned when a key is not found in the tree.
ErrKeyNotFound = errors.New("key not found")
// ErrInvalidClosestPath is returned when the path used in the ClosestProof
// method does not match the size of the trie's PathHasher
ErrInvalidClosestPath = errors.New("invalid path does not match path hasher size")
)
12 changes: 12 additions & 0 deletions proofs.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,12 @@ func (proof *SparseMerkleClosestProof) GetValueHash(spec *TrieSpec) []byte {
}

func (proof *SparseMerkleClosestProof) validateBasic(spec *TrieSpec) error {
// ensure the proof length is the same size (in bytes) as the path
// hasher of the spec provided
if len(proof.Path) != spec.PathHasherSize() {
return fmt.Errorf("invalid path length: got %d, want %d", len(proof.Path), spec.PathHasherSize())
}

// ensure the depth of the leaf node being proven is within the path size
if proof.Depth < 0 || proof.Depth > spec.ph.PathSize()*8 {
return fmt.Errorf("invalid depth: got %d, outside of [0, %d]", proof.Depth, spec.ph.PathSize()*8)
Expand Down Expand Up @@ -250,6 +256,12 @@ type SparseCompactMerkleClosestProof struct {
}

func (proof *SparseCompactMerkleClosestProof) validateBasic(spec *TrieSpec) error {
// Ensure the proof length is the same size (in bytes) as the path
// hasher of the spec provided
if len(proof.Path) != spec.PathHasherSize() {
return fmt.Errorf("invalid path length: got %d, want %d", len(proof.Path), spec.PathHasherSize())
}

// Do a basic sanity check on the proof on the fields of the proof specific to
// the compact proof only.
//
Expand Down
5 changes: 5 additions & 0 deletions smt.go
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,11 @@ func (smt *SMT) ProveClosest(path []byte) (
proof *SparseMerkleClosestProof, // proof of the key-value pair found
err error, // the error value encountered
) {
// Ensure the path provided is the correct length for the path hasher.
if len(path) != smt.Spec().PathHasherSize() {
return nil, ErrInvalidClosestPath
}

workingPath := make([]byte, len(path))
copy(workingPath, path)
var siblings []trieNode
Expand Down

0 comments on commit 9ea65a3

Please sign in to comment.