Multihash for Python
py-multihash is a Python implementation of the Multihash specification, providing functions to encode and decode self-describing cryptographic hashes. The current version is 3.0.0. Releases are infrequent, tied to updates in the Multiformats specification.
Common errors
-
AttributeError: module 'multihash' has no attribute 'Multihash'
cause Attempting to use the `Multihash` class which was removed in v3.0.0.fixThe `encode` and `decode` functions are now top-level. Use `multihash.encode(...)` and `multihash.decode(...)` directly. -
ImportError: cannot import name 'constants' from 'multihash'
cause Attempting to import the `constants` module which was removed in v3.0.0.fixAlgorithm constants are now part of the `py-multicodec` library. Use `import multicodec` and access constants like `multicodec.SHA2_256`. -
TypeError: encode() missing 1 required positional argument: 'data' (if called as `Multihash.encode(alg)`) or AttributeError: type object 'Multihash' has no attribute 'encode'
cause Attempting to call `encode` or `decode` as a method of the removed `Multihash` class, or statically without providing `self`.fixThese are now top-level functions. Call them as `multihash.encode(data, alg)` or `multihash.decode(mh)`.
Warnings
- breaking The `Multihash` class has been removed in version 3.0.0. `encode` and `decode` are now top-level functions in the `multihash` module, and `Digest` is a directly exposed class.
- breaking The `multihash.constants` module was removed in version 3.0.0. All algorithm constants (e.g., `SHA2_256`) are now provided by the `py-multicodec` library.
- breaking Python 3.10 or newer is now required for `py-multihash` version 3.0.0 and above.
- gotcha The `multihash.encode` function expects the hash algorithm to be specified by its string name (e.g., 'sha2-256') or its integer code, not a `py-multicodec` constant directly for the algorithm parameter.
Install
-
pip install py-multihash
Imports
- encode
from multihash import encode
- decode
from multihash import decode
- Digest
from multihash import Digest
- Multihash
from multihash import Multihash
from multihash import encode, decode, Digest
Quickstart
import multihash
import multicodec
# Encode a byte string with a specific hash algorithm
data = b'Hello multihash world!'
mh = multihash.encode(data, 'sha2-256')
print(f"Encoded multihash: {mh.hex()}")
# Decode a multihash digest
decoded_digest = multihash.decode(mh)
print(f"Decoded digest name: {decoded_digest.name}")
print(f"Decoded digest code: {hex(decoded_digest.code)}")
print(f"Decoded digest length: {decoded_digest.length}")
print(f"Original digest: {decoded_digest.digest.hex()}")
# Verify the algorithm code using multicodec constants
assert decoded_digest.code == multicodec.SHA2_256
print("Verification successful!")