file-store/pkg/erasureencode/merkle.go
2022-08-23 21:56:32 -05:00

39 lines
801 B
Go

package erasureencode
import (
"fmt"
)
func merkleSha256(inputHashes [][]byte) []byte {
CHILD_NUM := 2
hashesLen := len(inputHashes)
if hashesLen == 0 {
panic(fmt.Errorf("input must be at least one hash"))
}
hashLen := len(inputHashes[0])
hashes := make([][]byte, hashesLen)
copy(hashes, inputHashes)
for true {
for i := 0; i < hashesLen; i += CHILD_NUM {
hashData := make([]byte, hashLen*CHILD_NUM)
for j := 0; j < CHILD_NUM && i+j < hashesLen; j++ {
copy(hashData[j*hashLen:], hashes[i+j])
}
hashes[i/CHILD_NUM] = sha256sum(hashData)
}
newLen := hashesLen / CHILD_NUM
if hashesLen%CHILD_NUM > 0 {
newLen += 1
}
hashes = hashes[0:newLen]
hashesLen = newLen
if hashesLen == 1 {
return hashes[0]
}
}
panic(fmt.Errorf("unexpected code path"))
}