tth: redesign api surface
--HG-- branch : adc
This commit is contained in:
parent
aabaa128c4
commit
ee91ca71c4
19
tth.go
19
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
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user