Source code for fleetmesh_core.identity.cid

"""IPFS CIDv1 multibase 'b' (raw sha2-256 and dag-cbor) codec.

Standard library only. All identifiers here use canonical multibase 'b'
(lowercase Base32, RFC 4648 without padding), multicodec 0x55 (raw) or
0x71 (dag-cbor), and sha2-256 multihash (0x12, length 0x20).
"""
from __future__ import annotations

import base64
import functools
import hashlib
from typing import Any

from ..wire import varint

__all__ = [
    'CIDError',
    'CIDLink',
    'CODEC_RAW',
    'CODEC_DAG_CBOR',
    'sha256_to_cid',
    'cid_to_sha256',
]

CODEC_RAW = 0x55
CODEC_DAG_CBOR = 0x71
HASH_SHA2_256 = 0x12
DIGEST_LEN_SHA2_256 = 0x20


[docs]class CIDError(ValueError): """Raised when a CID cannot be parsed or violates canonical CIDv1 constraints."""
[docs]@functools.lru_cache(maxsize=4096) def sha256_to_cid(sha256_hex: str) -> str: """Map SHA-256 hex digest to standard IPFS CIDv1 multibase 'b' (raw sha2-256). CIDv1 format: - 0x01: CIDv1 - 0x55: raw codec (varint 0x55) - 0x12: sha2-256 multihash function - 0x20: 32 bytes digest length - raw 32-byte SHA-256 digest Encoded in lowercase RFC 4648 Base32 with 'b' multibase prefix. Produces canonical 'bafkrei...' prefix. """ return CIDLink.from_sha256(sha256_hex, codec=CODEC_RAW).cid_str
[docs]@functools.lru_cache(maxsize=4096) def cid_to_sha256(cid_str: str) -> str: """Extract SHA-256 hex digest from standard IPFS CIDv1 multibase 'b' string.""" link = CIDLink.from_str(cid_str) return link.digest_hex