diff --git a/cid/prefix.py b/cid/prefix.py index 8ff42a1..77efda3 100644 --- a/cid/prefix.py +++ b/cid/prefix.py @@ -215,40 +215,23 @@ def from_bytes(cls, data: bytes) -> "Prefix": @staticmethod def _mh_type_to_code(mh_type: str) -> int: """Convert multihash type name to code.""" - # Common multihash type codes - # These match the multiformats specification - mh_codes = { - "sha1": 0x11, - "sha2-256": 0x12, - "sha2-512": 0x13, - "sha3-224": 0x17, - "sha3-256": 0x16, - "sha3-512": 0x14, - "blake2b-256": 0xB220, - "blake2b-512": 0xB240, - } - if mh_type not in mh_codes: - msg = f"Unknown multihash type: {mh_type}" - raise ValueError(msg) - return mh_codes[mh_type] + try: + return multihash.Func[mh_type.replace("-", "_")].value # type: ignore + except KeyError: + try: + return int(multihash.coerce_code(mh_type)) # type: ignore + except (ValueError, TypeError): + msg = f"Unknown multihash type: {mh_type}" + raise ValueError(msg) @staticmethod def _mh_code_to_type(mh_code: int) -> str: """Convert multihash code to type name.""" - mh_types = { - 0x11: "sha1", - 0x12: "sha2-256", - 0x13: "sha2-512", - 0x17: "sha3-224", - 0x16: "sha3-256", - 0x14: "sha3-512", - 0xB220: "blake2b-256", - 0xB240: "blake2b-512", - } - if mh_code not in mh_types: + try: + return multihash.Func(mh_code).name.replace("_", "-") + except ValueError: msg = f"Unknown multihash code: {mh_code}" raise ValueError(msg) - return mh_types[mh_code] def __eq__(self, other: object) -> bool: """Check equality with another Prefix.""" diff --git a/newsfragments/65.bugfix.rst b/newsfragments/65.bugfix.rst new file mode 100644 index 0000000..b18ddbc --- /dev/null +++ b/newsfragments/65.bugfix.rst @@ -0,0 +1 @@ +Delegate multihash type mappings in Prefix to the multihash library.