file-store/pkg/erasureencode/merkle.go

39 lines
801 B
Go
Raw Normal View History

2022-08-24 02:54:01 +00:00
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"))
}