You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
get_prefix() returns multihash[:2], assuming the code and length varints are each exactly 1 byte. For hash codes > 127 (e.g., sha2-224 at 0x1013, blake2b-256 at 0xB220), the varint encoding is multi-byte, so [:2] returns incorrect/incomplete data.
For codes that fit in a single varint byte (0x00–0x7F), this works. But for codes > 0x7F, the varint encoding uses multiple bytes:
Hash function
Code
Varint bytes
[:2] returns
Correct prefix
sha2-256
0x12
b'\x12' (1 byte)
b'\x12\x20' ✅
b'\x12\x20'
sha2-224
0x1013
b'\x93 ' (2 bytes)
b'\x93 ' ❌
b'\x93 \x1c'
blake2b-256
0xB220
b'\xa0\xe4\x02' (3 bytes)
b'\xa0\xe4' ❌
b'\xa0\xe4\x02\x20'
ripemd-160
0x1053
b'\xd3 ' (2 bytes)
b'\xd3 ' ❌
b'\xd3 \x14'
The "prefix" of a multihash is the varint-encoded code + varint-encoded length. Its size varies depending on the code and digest length.
Proposed Solution
Replace the hardcoded slice with proper varint decoding:
defget_prefix(multihash):
ifnotisinstance(multihash, bytes):
raiseTypeError("multihash should be bytes")
ifnotis_valid(multihash):
raiseValueError("invalid multihash")
buffer=BytesIO(multihash)
# Read code varintvarint.decode_stream(buffer)
# Read length varintvarint.decode_stream(buffer)
# Everything up to current position is the prefixreturnmultihash[:buffer.tell()]
Activity
Add newsfragment for multiformats#46
Add newsfragment for multiformats#46