Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions multihash/multihash.py
Original file line number Diff line number Diff line change
Expand Up @@ -969,12 +969,18 @@ def get_prefix(multihash):
:param bytes multihash: input multihash
:return: multihash prefix
:rtype: bytes
:raises TypeError: when multihash is not bytes
:raises ValueError: when the multihash is invalid
"""
if is_valid(multihash):
return multihash[:2]
if not isinstance(multihash, bytes):
raise TypeError(f"multihash should be bytes, not {type(multihash)}")
if not is_valid(multihash):
raise ValueError("invalid multihash")

raise ValueError("invalid multihash")
buffer = BytesIO(multihash)
varint.decode_stream(buffer) # Read code varint
varint.decode_stream(buffer) # Read length varint
return multihash[: buffer.tell()]


def sum(data: bytes, code: Func | str | int, length: int | None = None) -> Multihash:
Expand Down
1 change: 1 addition & 0 deletions newsfragments/46.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix :func:`~multihash.get_prefix` to decode both the hash-code and digest-length varints instead of assuming a two-byte prefix, so prefixes are correct for hash codes above ``0x7F`` (such as ``sha2-224`` and ``blake2b-*``). ``get_prefix`` now also raises ``TypeError`` when passed a non-``bytes`` value.
28 changes: 28 additions & 0 deletions tests/test_multihash.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,3 +349,31 @@ def test_get_prefix_invalid(self):
"""get_prefix: raises ValueError for invalid cases"""
with pytest.raises(ValueError):
get_prefix(b"foobar")

def test_get_prefix_multi_byte_code(self):
"""get_prefix: correctly parses multi-byte varints"""
from multihash.funcs import Func
from multihash.multihash import sum as mh_sum

# sha2_224 code is 0x1013, which takes 2 bytes for the varint.
# Length 28 takes 1 byte. Total prefix = 3 bytes.
mh = mh_sum(b"test", Func.sha2_224)
prefix = get_prefix(mh.encode())
assert prefix == mh.encode()[:3]

def test_get_prefix_three_byte_code(self):
"""get_prefix: correctly parses 3-byte code varints (blake2b-256)"""
from multihash.funcs import Func
from multihash.multihash import sum as mh_sum

# blake2b-256 code is 0xB220 (3-byte varint); length 32 is 1 byte.
mh = mh_sum(b"test", Func.blake2b_256)
encoded = mh.encode()
prefix = get_prefix(encoded)
assert prefix == encoded[:4]
assert len(prefix) == 4

def test_get_prefix_type_error(self):
"""get_prefix: raises TypeError when not passed bytes"""
with pytest.raises(TypeError, match="multihash should be bytes"):
get_prefix("not bytes")
Loading