From 95cd5c85f09e79b1d6cecdac7d5180c3483a05f0 Mon Sep 17 00:00:00 2001 From: mappu Date: Sat, 25 Nov 2017 14:25:17 +1300 Subject: [PATCH] tth: working --HG-- branch : adc --- tth.go | 36 +++++++++++++----------------------- tth_test.go | 2 +- 2 files changed, 14 insertions(+), 24 deletions(-) diff --git a/tth.go b/tth.go index b7c3892..8a245ec 100644 --- a/tth.go +++ b/tth.go @@ -3,38 +3,28 @@ package libnmdc import ( "encoding/base32" "errors" + "strings" "github.com/cxmcc/tiger" ) -func tth(input []byte) (string, error) { +// 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) { + + // 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 if len(input) > 1024 { return "", errors.New("TTH content exceeded 1024 bytes") } + // Single leaf hash only leafHash := tiger.New() - - //buff := make([]byte, 1024) - //leafHash.Write([]byte("\x00")) - //copy(buff[1:], []byte(input)) - //leafHash.Write(buff) - //fmt.Printf("%#v\n", buff) - - leafHash.Write([]byte("\x00" + string(input))) + leafHash.Write([]byte("\x00" + input)) leafHashBytes := leafHash.Sum(nil) - rootHash := tiger.New() - //rootHash.Write([]byte("\x01")) - //rootHash.Write(leafHashBytes) - rootHash.Write([]byte("\x01" + string(leafHashBytes))) - rootHashBytes := rootHash.Sum(nil) - - /* - * The Tiger Hash function, modified to prepend the specified byte to the input - * data. This is useful for the THEX algorithm which prepends a 0x00 to leaf - * nodes and 0x01 to the hash nodes. - **/ - - // Definitely StdEncoding - return base32.StdEncoding.EncodeToString(rootHashBytes), nil + return strings.TrimRight(base32.StdEncoding.EncodeToString(leafHashBytes), "="), nil } diff --git a/tth_test.go b/tth_test.go index 1756872..ca41ad3 100644 --- a/tth_test.go +++ b/tth_test.go @@ -24,7 +24,7 @@ func TestTTH(t *testing.T) { for _, testCase := range testCases { input, expected := testCase[0], testCase[1] - result, err := tth([]byte(input)) + result, err := TTH(input) if err != nil { t.Fatalf("Error getting TTH for '%s': %s", short(input), err.Error()) }