Skip to content

Commit 393ba0d

Browse files
committed
Revive TestSmallerLengthHashID, and add a special case for identity multihash that rejects truncations.
See #136 (comment) for discussion. This change means Sum behaves slightly differently for identity multihashes than it does for any other multihash. I'm not keeping score on the number of ways identity multihash is weird anymore, just documenting it and keeping tests passing. The error message is lifted from the old `sumID` function verbatim.
1 parent cbd218c commit 393ba0d

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

sum.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package multihash
22

33
import (
44
"errors"
5+
"fmt"
56
)
67

78
// ErrSumNotSupported is returned when the Sum function code is not implemented
@@ -27,13 +28,19 @@ func Sum(data []byte, code uint64, length int) (Multihash, error) {
2728
sum := hasher.Sum(nil)
2829

2930
// Deal with any truncation.
31+
// Unless it's an identity multihash. Those have different rules.
3032
if length < 0 {
3133
length = hasher.Size()
3234
}
3335
if len(sum) < length {
3436
return nil, ErrLenTooLarge
3537
}
3638
if length >= 0 {
39+
if code == IDENTITY {
40+
if length != len(sum) {
41+
return nil, fmt.Errorf("the length of the identity hash (%d) must be equal to the length of the data (%d)", length, len(sum))
42+
}
43+
}
3744
sum = sum[:length]
3845
}
3946

sum_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,33 @@ func BenchmarkBlake2B(b *testing.B) {
123123
}
124124
}
125125

126+
func TestSmallerLengthHashID(t *testing.T) {
127+
128+
data := []byte("Identity hash input data.")
129+
dataLength := len(data)
130+
131+
// Normal case: `length == len(data)`.
132+
_, err := multihash.Sum(data, multihash.ID, dataLength)
133+
if err != nil {
134+
t.Fatal(err)
135+
}
136+
137+
// Unconstrained length (-1): also allowed.
138+
_, err = multihash.Sum(data, multihash.ID, -1)
139+
if err != nil {
140+
t.Fatal(err)
141+
}
142+
143+
// Any other variation of those two scenarios should fail.
144+
for l := (dataLength - 1); l >= 0; l-- {
145+
_, err = multihash.Sum(data, multihash.ID, l)
146+
if err == nil {
147+
t.Fatal(fmt.Sprintf("identity hash of length %d smaller than data length %d didn't fail",
148+
l, dataLength))
149+
}
150+
}
151+
}
152+
126153
func TestTooLargeLength(t *testing.T) {
127154
_, err := multihash.Sum([]byte("test"), multihash.SHA2_256, 33)
128155
if err != multihash.ErrLenTooLarge {

0 commit comments

Comments
 (0)