Skip to content

Commit

Permalink
feat!: updates the HashNode and HashLeaf methods to return error inst…
Browse files Browse the repository at this point in the history
…ead of panic and refactors the code (#136)

## Overview
Closes #109 and #99.
This pull request ensures that the `HashNode` and `HashLeaf` functions
return errors instead of panicking, and that caller functions properly
handle any emitted errors. When generating proofs, any hashing errors
are propagated with additional context. During verification, hashing
errors are treated as unsuccessful proof verification.

Note that in this PR, the term `Irrecoverable errors` used to describe
errors that any number of retries can correct the them.

## Checklist


- [x] New and updated code has appropriate documentation
- [x] New and updated code has new and/or updated testing
- [x] Required CI checks are passing
- [x] Visual proof for any user facing features like CLI or
documentation updates
- [x] Linked issues closed with keywords
  • Loading branch information
staheri14 authored Mar 23, 2023
1 parent c63e970 commit b34f794
Show file tree
Hide file tree
Showing 7 changed files with 901 additions and 175 deletions.
5 changes: 4 additions & 1 deletion fuzz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"sort"
"testing"

"github.com/stretchr/testify/require"

"github.com/celestiaorg/nmt"
"github.com/celestiaorg/nmt/namespace"
fuzz "github.com/google/gofuzz"
Expand Down Expand Up @@ -44,7 +46,8 @@ func TestFuzzProveVerifyNameSpace(t *testing.T) {
}
}

treeRoot := tree.Root()
treeRoot, err := tree.Root()
require.NoError(t, err)
nonEmptyNsCount := 0
leafIdx := 0
for _, ns := range sortedKeys {
Expand Down
99 changes: 57 additions & 42 deletions hasher.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ var _ hash.Hash = (*Hasher)(nil)
var (
ErrUnorderedSiblings = errors.New("NMT sibling nodes should be ordered lexicographically by namespace IDs")
ErrInvalidNodeLen = errors.New("invalid NMT node size")
ErrInvalidLeafLen = errors.New("invalid NMT leaf size")
)

type Hasher struct {
Expand Down Expand Up @@ -65,6 +66,8 @@ func (n *Hasher) Size() int {
//
// Requires data of fixed size to match leaf or inner NMT nodes. Only a single
// write is allowed.
// It panics if more than one single write is attempted.
// If the data does not match the format of an NMT non-leaf node or leaf node, an error will be returned.
func (n *Hasher) Write(data []byte) (int, error) {
if n.data != nil {
panic("only a single Write is allowed")
Expand All @@ -74,9 +77,19 @@ func (n *Hasher) Write(data []byte) (int, error) {
switch ln {
// inner nodes are made up of the nmt hashes of the left and right children
case n.Size() * 2:
// check the format of the data
leftChild := data[:n.Size()]
rightChild := data[n.Size():]
if err := n.ValidateNodes(leftChild, rightChild); err != nil {
return 0, err
}
n.tp = NodePrefix
// leaf nodes contain the namespace length and a share
default:
// validate the format of the leaf
if err := n.ValidateLeaf(data); err != nil {
return 0, err
}
n.tp = LeafPrefix
}

Expand All @@ -86,16 +99,25 @@ func (n *Hasher) Write(data []byte) (int, error) {

// Sum computes the hash. Does not append the given suffix, violating the
// interface.
// It may panic if the data being hashed is invalid. This should never happen since the Write method refuses an invalid data and errors out.
func (n *Hasher) Sum([]byte) []byte {
switch n.tp {
case LeafPrefix:
return n.HashLeaf(n.data)
res, err := n.HashLeaf(n.data)
if err != nil {
panic(err) // this should never happen since the data is already validated in the Write method
}
return res
case NodePrefix:
flagLen := int(n.NamespaceLen) * 2
sha256Len := n.baseHasher.Size()
leftChild := n.data[:flagLen+sha256Len]
rightChild := n.data[flagLen+sha256Len:]
return n.HashNode(leftChild, rightChild)
res, err := n.HashNode(leftChild, rightChild)
if err != nil {
panic(err) // this should never happen since the data is already validated in the Write method
}
return res
default:
panic("nmt node type wasn't set")
}
Expand All @@ -120,30 +142,28 @@ func (n *Hasher) EmptyRoot() []byte {
return digest
}

// IsNamespacedData checks whether data is namespace prefixed.
func (n *Hasher) IsNamespacedData(data []byte) (err error) {
// ValidateLeaf verifies if data is namespaced and returns an error if not.
func (n *Hasher) ValidateLeaf(data []byte) (err error) {
nidSize := int(n.NamespaceSize())
lenData := len(data)
if lenData < nidSize {
return fmt.Errorf("%w: got: %v, want >= %v", ErrMismatchedNamespaceSize, lenData, nidSize)
return fmt.Errorf("%w: got: %v, want >= %v", ErrInvalidLeafLen, lenData, nidSize)
}
return nil
}

// HashLeaf computes namespace hash of the namespaced data item `ndata` as
// ns(ndata) || ns(ndata) || hash(leafPrefix || ndata), where ns(ndata) is the
// namespaceID inside the data item namely leaf[:n.NamespaceLen]). Note that for
// leaves minNs = maxNs = ns(leaf) = leaf[:NamespaceLen]. HashLeaf can panic if
// the input is not properly namespaced. To avoid panic, call IsNamespacedData
// on the input data `ndata` before invoking HashLeaf method.
// leaves minNs = maxNs = ns(leaf) = leaf[:NamespaceLen]. HashLeaf can return the ErrInvalidNodeLen error if the input is not namespaced.
//
//nolint:errcheck
func (n *Hasher) HashLeaf(ndata []byte) []byte {
func (n *Hasher) HashLeaf(ndata []byte) ([]byte, error) {
h := n.baseHasher
h.Reset()

if err := n.IsNamespacedData(ndata); err != nil {
panic(err)
if err := n.ValidateLeaf(ndata); err != nil {
return nil, err
}

nID := ndata[:n.NamespaceLen]
Expand All @@ -160,12 +180,12 @@ func (n *Hasher) HashLeaf(ndata []byte) []byte {

// compute h(LeafPrefix || ndata) and append it to the minMaxNIDs
nameSpacedHash := h.Sum(minMaxNIDs) // nID || nID || h(LeafPrefix || ndata)
return nameSpacedHash
return nameSpacedHash, nil
}

// validateNodeFormat checks whether the supplied node conforms to the
// namespaced hash format.
func (n *Hasher) validateNodeFormat(node []byte) (err error) {
// ValidateNodeFormat checks whether the supplied node conforms to the
// namespaced hash format and returns an error if it does not. Specifically, it returns ErrInvalidNodeLen if the length of the node is less than the 2*namespace length which indicates it does not match the namespaced hash format.
func (n *Hasher) ValidateNodeFormat(node []byte) (err error) {
totalNamespaceLen := 2 * n.NamespaceLen
nodeLen := len(node)
if nodeLen < int(totalNamespaceLen) {
Expand All @@ -177,9 +197,9 @@ func (n *Hasher) validateNodeFormat(node []byte) (err error) {
// validateSiblingsNamespaceOrder checks whether left and right as two sibling
// nodes in an NMT have correct namespace IDs relative to each other, more
// specifically, the maximum namespace ID of the left sibling should not exceed
// the minimum namespace ID of the right sibling. Note that the function assumes
// the minimum namespace ID of the right sibling. It returns ErrUnorderedSiblings error if the check fails. Note that the function assumes
// that the left and right nodes are in correct format, i.e., they are
// namespaced hash values.
// namespaced hash values. Otherwise, it panics.
func (n *Hasher) validateSiblingsNamespaceOrder(left, right []byte) (err error) {
// each NMT node has two namespace IDs for the min and max
totalNamespaceLen := 2 * n.NamespaceLen
Expand All @@ -193,55 +213,50 @@ func (n *Hasher) validateSiblingsNamespaceOrder(left, right []byte) (err error)
return nil
}

// ValidateNodes is helper function to be called prior to HashNode to verify the
// validity of the inputs of HashNode and avoid panics. It verifies whether left
// ValidateNodes is a helper function to verify the
// validity of the inputs of HashNode. It verifies whether left
// and right comply by the namespace hash format, and are correctly ordered
// according to their namespace IDs.
func (n *Hasher) ValidateNodes(left, right []byte) error {
if err := n.validateNodeFormat(left); err != nil {
if err := n.ValidateNodeFormat(left); err != nil {
return err
}
if err := n.validateNodeFormat(right); err != nil {
if err := n.ValidateNodeFormat(right); err != nil {
return err
}
if err := n.validateSiblingsNamespaceOrder(left, right); err != nil {
return err
}
return nil
return n.validateSiblingsNamespaceOrder(left, right)
}

// HashNode calculates a namespaced hash of a node using the supplied left and
// right children. The input values, "left" and "right," are namespaced hash
// values with the format "minNID || maxNID || hash." The HashNode function may
// panic if the inputs provided are invalid, i.e., when left and right are not
// in the namespaced hash format or when left.maxNID is greater than
// right.minNID. To avoid causing panic, it is recommended to first call
// ValidateNodes(left, right) to check if the criteria are met before invoking
// the HashNode function. By default, the normal namespace hash calculation is
// followed, which is "res = min(left.minNID, right.minNID) || max(left.maxNID,
// right.maxNID) || H(NodePrefix, left, right)". "res" refers to the return
// value of the HashNode. However, if the "ignoreMaxNs" property of the Hasher
// right children. The input values, `left` and `right,` are namespaced hash
// values with the format `minNID || maxNID || hash.`
// The HashNode function returns an error if the provided inputs are invalid. Specifically, it returns the ErrInvalidNodeLen error if the left and right inputs are not in the namespaced hash format,
// and the ErrUnorderedSiblings error if left.maxNID is greater than right.minNID.
// By default, the normal namespace hash calculation is
// followed, which is `res = min(left.minNID, right.minNID) || max(left.maxNID,
// right.maxNID) || H(NodePrefix, left, right)`. `res` refers to the return
// value of the HashNode. However, if the `ignoreMaxNs` property of the Hasher
// is set to true, the calculation of the namespace ID range of the node
// slightly changes. In this case, when setting the upper range, the maximum
// possible namespace ID (i.e., 2^NamespaceIDSize-1) should be ignored if
// possible. This is achieved by taking the maximum value among only those namespace
// IDs available in the range of its left and right children that are not
// equal to the maximum possible namespace ID value. If all the namespace IDs are equal
// to the maximum possible value, then the maximum possible value is used.
func (n *Hasher) HashNode(left, right []byte) []byte {
func (n *Hasher) HashNode(left, right []byte) ([]byte, error) {
h := n.baseHasher
h.Reset()

if err := n.validateNodeFormat(left); err != nil {
panic(err)
if err := n.ValidateNodeFormat(left); err != nil {
return nil, err
}
if err := n.validateNodeFormat(right); err != nil {
panic(err)
if err := n.ValidateNodeFormat(right); err != nil {
return nil, err
}

// check the namespace range of the left and right children
if err := n.validateSiblingsNamespaceOrder(left, right); err != nil {
panic(err)
return nil, err
}

// the actual hash result of the children got extended (or flagged) by their
Expand Down Expand Up @@ -273,7 +288,7 @@ func (n *Hasher) HashNode(left, right []byte) []byte {
data = append(data, right...)
//nolint:errcheck
h.Write(data)
return h.Sum(res)
return h.Sum(res), nil
}

func max(ns []byte, ns2 []byte) []byte {
Expand Down
Loading

0 comments on commit b34f794

Please sign in to comment.