tth: working

--HG--
branch : adc
This commit is contained in:
mappu 2017-11-25 14:25:17 +13:00
parent 881286df39
commit 95cd5c85f0
2 changed files with 14 additions and 24 deletions

36
tth.go
View File

@ -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
}

View File

@ -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())
}