8 g "github.com/anacrolix/generics"
11 // The leaf block size for BitTorrent v2 Merkle trees.
12 const BlockSize = 1 << 14 // 16KiB
14 func Root(hashes [][sha256.Size]byte) [sha256.Size]byte {
17 return sha256.Sum256(nil)
21 numHashes := uint(len(hashes))
22 if numHashes != RoundUpToPowerOfTwo(uint(len(hashes))) {
23 panic(fmt.Sprintf("expected power of two number of hashes, got %d", numHashes))
25 var next [][sha256.Size]byte
26 for i := 0; i < len(hashes); i += 2 {
29 h := sha256.Sum256(append(left[:], right[:]...))
30 next = append(next, h)
35 func RootWithPadHash(hashes [][sha256.Size]byte, padHash [sha256.Size]byte) [sha256.Size]byte {
36 for uint(len(hashes)) < RoundUpToPowerOfTwo(uint(len(hashes))) {
37 hashes = append(hashes, padHash)
42 func CompactLayerToSliceHashes(compactLayer string) (hashes [][sha256.Size]byte, err error) {
43 g.MakeSliceWithLength(&hashes, len(compactLayer)/sha256.Size)
44 for i := range hashes {
45 n := copy(hashes[i][:], compactLayer[i*sha256.Size:])
47 err = fmt.Errorf("compact layer has incomplete hash at index %d", i)
54 func RoundUpToPowerOfTwo(n uint) (ret uint) {
55 return 1 << bits.Len(n-1)
58 func Log2RoundingUp(n uint) (ret uint) {
59 return uint(bits.Len(n - 1))