Skip to content

Commit 514395d

Browse files
committed
add compute root with basic validation
1 parent 9f7b17a commit 514395d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

proof.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,48 @@ func (proof Proof) ValidateCompleteness(nth *NmtHasher, nID namespace.ID) error
338338
return nil
339339
}
340340

341+
// ComputeRootWithBasicValidation computes the Merkle root from a given proof and a set of leaf hashes,
342+
// performing basic validation steps prior to computing the root.
343+
//
344+
// If isNamespace is true, it additionally validates:
345+
// - That the leaf hashes belong to the specified namespace.
346+
// - That the proof is complete for the given namespace.
347+
//
348+
// Parameters:
349+
// - nth: The NMT hasher instance used for validation and root computation.
350+
// - nID: The namespace ID that the proof is expected to correspond to.
351+
// - leafHashes: The hashes of the leaves being proven.
352+
// - isNamespace: A flag indicating whether namespace-specific validation should be performed.
353+
//
354+
// Returns:
355+
// - The computed root hash if all checks pass.
356+
// - An error if any validation fails or root computation fails.
357+
func (proof Proof) ComputeRootWithBasicValidation(nth *NmtHasher, nID namespace.ID, leafHashes [][]byte, isNamespace bool) ([]byte, error) {
358+
if err := proof.ValidateProofStructure(nth, nID, leafHashes); err != nil {
359+
return nil, err
360+
}
361+
362+
if isNamespace {
363+
if err := proof.ValidateNamespace(nth, nID, leafHashes); err != nil {
364+
return nil, fmt.Errorf("failed namespace check: %w", err)
365+
}
366+
if err := proof.ValidateCompleteness(nth, nID); err != nil {
367+
return nil, fmt.Errorf("failed completeness check: %w", err)
368+
}
369+
}
370+
371+
rootHash, err := proof.ComputeRoot(nth, leafHashes)
372+
if err != nil {
373+
return nil, fmt.Errorf("failed to compute root: %w", err)
374+
}
375+
376+
if err := nth.ValidateNodeFormat(rootHash); err != nil {
377+
return nil, fmt.Errorf("root does not match the NMT hasher's hash format: %w", err)
378+
}
379+
380+
return rootHash, nil
381+
}
382+
341383
// ComputeRoot reconstructs the Merkle root from a given proof and a set of leaf hashes.
342384
// It recursively computes the root hash by combining leaf nodes and proof nodes using the NMT hasher.
343385
//

0 commit comments

Comments
 (0)