From ee91ca71c41a3e35827d322152e048ebd2c533d0 Mon Sep 17 00:00:00 2001 From: mappu Date: Sun, 26 Nov 2017 13:29:32 +1300 Subject: [PATCH] tth: redesign api surface --HG-- branch : adc --- tth.go | 19 ++++++++++++------- tth_test.go | 3 ++- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/tth.go b/tth.go index 8a245ec..fe2c175 100644 --- a/tth.go +++ b/tth.go @@ -8,9 +8,16 @@ import ( "github.com/cxmcc/tiger" ) -// TTH returns the TTH hash of a string. This is a rudimentary implementation -// that only supports content up to 1024 bytes in length. -func TTH(input string) (string, error) { +// 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) { // Short segments do not need to be padded. // 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 // @ref http://adc.sourceforge.net/draft-jchapweske-thex-02.html 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 leafHash := tiger.New() leafHash.Write([]byte("\x00" + input)) - leafHashBytes := leafHash.Sum(nil) - - return strings.TrimRight(base32.StdEncoding.EncodeToString(leafHashBytes), "="), nil + return leafHash.Sum(nil), nil } diff --git a/tth_test.go b/tth_test.go index ca41ad3..817c61e 100644 --- a/tth_test.go +++ b/tth_test.go @@ -28,7 +28,8 @@ func TestTTH(t *testing.T) { if err != nil { 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) } }