2017-11-25 00:45:26 +00:00
|
|
|
package libnmdc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base32"
|
|
|
|
"errors"
|
2017-11-25 01:25:17 +00:00
|
|
|
"strings"
|
2017-11-25 00:45:26 +00:00
|
|
|
|
|
|
|
"github.com/cxmcc/tiger"
|
|
|
|
)
|
|
|
|
|
2017-11-26 00:29:32 +00:00
|
|
|
// Base32 encodes the input slice in BASE32 string format without any trailing
|
|
|
|
// padding equals characters.
|
|
|
|
func Base32(input []byte) string {
|
|
|
|
return strings.TrimRight(base32.StdEncoding.EncodeToString(input), "=")
|
|
|
|
}
|
|
|
|
|
|
|
|
// TTH returns the TTH hash of a string in raw byte format. Use the Base32()
|
|
|
|
// function to convert it to normal string format.
|
|
|
|
// This is a basic implementation that only supports content up to 1024 bytes in length.
|
|
|
|
func TTH(input string) ([]byte, error) {
|
2017-11-25 01:25:17 +00:00
|
|
|
|
|
|
|
// Short segments do not need to be padded.
|
|
|
|
// Content above 1024 bytes needs tree handling (0x00 prefix for leaf nodes,
|
|
|
|
// 0x01 prefix for hash nodes) but for content less than 1024 bytes, just
|
|
|
|
// return the leaf hash
|
|
|
|
// @ref http://adc.sourceforge.net/draft-jchapweske-thex-02.html
|
2017-11-25 00:45:26 +00:00
|
|
|
if len(input) > 1024 {
|
2017-11-26 00:29:32 +00:00
|
|
|
return nil, errors.New("TTH content exceeded 1024 bytes")
|
2017-11-25 00:45:26 +00:00
|
|
|
}
|
|
|
|
|
2017-11-25 01:25:17 +00:00
|
|
|
// Single leaf hash only
|
2017-11-25 00:45:26 +00:00
|
|
|
leafHash := tiger.New()
|
2017-11-25 01:25:17 +00:00
|
|
|
leafHash.Write([]byte("\x00" + input))
|
2017-11-26 00:29:32 +00:00
|
|
|
return leafHash.Sum(nil), nil
|
2017-11-25 00:45:26 +00:00
|
|
|
}
|