tth: redesign api surface

--HG--
branch : adc
This commit is contained in:
mappu 2017-11-26 13:29:32 +13:00
parent aabaa128c4
commit ee91ca71c4
2 changed files with 14 additions and 8 deletions

19
tth.go
View File

@ -8,9 +8,16 @@ import (
"github.com/cxmcc/tiger" "github.com/cxmcc/tiger"
) )
// TTH returns the TTH hash of a string. This is a rudimentary implementation // Base32 encodes the input slice in BASE32 string format without any trailing
// that only supports content up to 1024 bytes in length. // padding equals characters.
func TTH(input string) (string, error) { 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) {
// Short segments do not need to be padded. // Short segments do not need to be padded.
// Content above 1024 bytes needs tree handling (0x00 prefix for leaf nodes, // Content above 1024 bytes needs tree handling (0x00 prefix for leaf nodes,
@ -18,13 +25,11 @@ func TTH(input string) (string, error) {
// return the leaf hash // return the leaf hash
// @ref http://adc.sourceforge.net/draft-jchapweske-thex-02.html // @ref http://adc.sourceforge.net/draft-jchapweske-thex-02.html
if len(input) > 1024 { if len(input) > 1024 {
return "", errors.New("TTH content exceeded 1024 bytes") return nil, errors.New("TTH content exceeded 1024 bytes")
} }
// Single leaf hash only // Single leaf hash only
leafHash := tiger.New() leafHash := tiger.New()
leafHash.Write([]byte("\x00" + input)) leafHash.Write([]byte("\x00" + input))
leafHashBytes := leafHash.Sum(nil) return leafHash.Sum(nil), nil
return strings.TrimRight(base32.StdEncoding.EncodeToString(leafHashBytes), "="), nil
} }

View File

@ -28,7 +28,8 @@ func TestTTH(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("Error getting TTH for '%s': %s", short(input), err.Error()) t.Fatalf("Error getting TTH for '%s': %s", short(input), err.Error())
} }
if result != expected {
if Base32(result) != expected {
t.Fatalf("Wrong TTH for '%s' (got '%s' expected '%s')", short(input), result, expected) t.Fatalf("Wrong TTH for '%s' (got '%s' expected '%s')", short(input), result, expected)
} }
} }