Skip to content

Commit

Permalink
refactor: MerkleRoot#Sum() as MerkleRoot#MustSum()
Browse files Browse the repository at this point in the history
  • Loading branch information
bryanchriswhite committed Jul 10, 2024
1 parent ea585c6 commit 4b79025
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions root.go
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand Down

0 comments on commit 4b79025

Please sign in to comment.