diff --git a/root.go b/root.go index ed1d83d..73dc4af 100644 --- a/root.go +++ b/root.go @@ -1,6 +1,9 @@ package smt -import "encoding/binary" +import ( + "encoding/binary" + "fmt" +) const ( // These are intentionally exposed to allow for for testing and custom @@ -9,19 +12,31 @@ const ( SmstRootSizeBytes = SmtRootSizeBytes + sumSizeBytes + countSizeBytes ) -// Sum returns the uint64 sum of the merkle root, it checks the length of the +// MustSum returns the uint64 sum of the merkle root, it checks the length of the // merkle root and if it is no the same as the size of the SMST's expected // root hash it will panic. -func (r MerkleRoot) Sum() uint64 { +func (r MerkleRoot) MustSum() uint64 { + sum, err := r.Sum() + if err != nil { + panic(err) + } + + return sum +} + +// Sum returns the uint64 sum of the merkle root, it checks the length of the +// merkle root and if it is no the same as the size of the SMST's expected +// root hash it will return an error. +func (r MerkleRoot) Sum() (uint64, error) { if len(r)%SmtRootSizeBytes == 0 { - panic("root#sum: not a merkle sum trie") + return 0, fmt.Errorf("root#sum: not a merkle sum trie") } firstSumByteIdx, firstCountByteIdx := getFirstMetaByteIdx([]byte(r)) var sumBz [sumSizeBytes]byte copy(sumBz[:], []byte(r)[firstSumByteIdx:firstCountByteIdx]) - return binary.BigEndian.Uint64(sumBz[:]) + return binary.BigEndian.Uint64(sumBz[:]), nil } // Count returns the uint64 count of the merkle root, a cryptographically secure