tth: working
--HG-- branch : adc
This commit is contained in:
parent
881286df39
commit
95cd5c85f0
36
tth.go
36
tth.go
@ -3,38 +3,28 @@ package libnmdc
|
|||||||
import (
|
import (
|
||||||
"encoding/base32"
|
"encoding/base32"
|
||||||
"errors"
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/cxmcc/tiger"
|
"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 {
|
if len(input) > 1024 {
|
||||||
return "", errors.New("TTH content exceeded 1024 bytes")
|
return "", errors.New("TTH content exceeded 1024 bytes")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Single leaf hash only
|
||||||
leafHash := tiger.New()
|
leafHash := tiger.New()
|
||||||
|
leafHash.Write([]byte("\x00" + input))
|
||||||
//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)))
|
|
||||||
leafHashBytes := leafHash.Sum(nil)
|
leafHashBytes := leafHash.Sum(nil)
|
||||||
|
|
||||||
rootHash := tiger.New()
|
return strings.TrimRight(base32.StdEncoding.EncodeToString(leafHashBytes), "="), nil
|
||||||
//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
|
|
||||||
}
|
}
|
||||||
|
@ -24,7 +24,7 @@ func TestTTH(t *testing.T) {
|
|||||||
|
|
||||||
for _, testCase := range testCases {
|
for _, testCase := range testCases {
|
||||||
input, expected := testCase[0], testCase[1]
|
input, expected := testCase[0], testCase[1]
|
||||||
result, err := tth([]byte(input))
|
result, err := TTH(input)
|
||||||
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())
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user