"""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]class CIDLink:
"""An IPLD Link (CID) represented as Tag 42 in DAG-CBOR and bafy.../bafk... string.
Supports CIDv1 with raw (0x55) or dag-cbor (0x71) multicodec and sha2-256 multihash.
"""
__slots__ = ('_bytes', '_codec', '_digest', '_cid_str')
[docs] def __init__(self, raw_bytes: bytes, codec: int, digest: bytes, cid_str: str | None = None):
self._bytes = raw_bytes
self._codec = codec
self._digest = digest
self._cid_str = cid_str
@property
def raw_bytes(self) -> bytes:
"""The binary CIDv1 representation (multicodec + multihash)."""
return self._bytes
@property
def codec(self) -> int:
"""The multicodec code (0x71 for dag-cbor, 0x55 for raw)."""
return self._codec
@property
def digest(self) -> bytes:
"""The multihash 32-byte digest."""
return self._digest
@property
def digest_hex(self) -> str:
"""The SHA-256 hex string."""
return self._digest.hex()
@property
def cid_str(self) -> str:
"""The Base32 multibase string starting with 'b'."""
if self._cid_str is None:
b32 = base64.b32encode(self._bytes).decode('ascii').lower().rstrip('=')
self._cid_str = 'b' + b32
return self._cid_str
[docs] def to_cbor_tag_bytes(self) -> bytes:
"""Produce the byte string value for CBOR Tag 42 (prefixed with null multibase byte)."""
return b'\x00' + self._bytes
[docs] def to_dict(self) -> dict[str, str]:
"""Convert to IPLD data-model JSON link dict."""
return {'$link': self.cid_str}
[docs] @classmethod
def from_cbor_tag_bytes(cls, data: bytes) -> CIDLink:
"""Parse from CBOR Tag 42 byte payload (stripping 0x00 multibase prefix)."""
if not data or data[0] != 0x00:
raise CIDError("CBOR tag 42 binary payload must begin with 0x00 null byte")
raw = data[1:]
link = cls.from_bytes(raw)
if len(link._bytes) != len(raw):
raise CIDError("trailing bytes in CBOR tag 42 CID")
return link
[docs] @classmethod
def from_bytes(cls, data: bytes) -> CIDLink:
"""Parse from raw binary CIDv1 bytes (or prefix of a CAR block)."""
if not data:
raise CIDError("empty CID bytes")
version, off = varint.read(data, 0)
if version != 1:
raise CIDError(f"unsupported CID version: {version}")
codec, off2 = varint.read(data, off)
off += off2
if codec not in (CODEC_RAW, CODEC_DAG_CBOR):
raise CIDError(f"unsupported CID codec: {codec:#x}")
hash_fn, off3 = varint.read(data, off)
off += off3
if hash_fn != HASH_SHA2_256:
raise CIDError(f"unsupported hash function: {hash_fn:#x}")
hash_len, off4 = varint.read(data, off)
off += off4
digest = data[off:off + hash_len]
if len(digest) != hash_len or len(digest) != DIGEST_LEN_SHA2_256:
raise CIDError(f"invalid digest length in CID: {len(digest)} != {hash_len}")
return cls(data[:off + hash_len], codec, digest)
[docs] @classmethod
def from_str(cls, s: str) -> CIDLink:
"""Parse from Base32 string (e.g. 'bafyre...' or 'bafkre...')."""
s = s.strip().lower()
if not s.startswith('b'):
raise CIDError(f"unsupported multibase prefix in CID: {s[:2]}")
b32 = s[1:].upper()
pad = '=' * (-len(b32) % 8)
try:
raw = base64.b32decode(b32 + pad)
except Exception as e:
raise CIDError(f"invalid base32 in CID: {e}")
link = cls.from_bytes(raw)
if len(link._bytes) != len(raw):
raise CIDError("trailing bytes in CID")
link._cid_str = s
return link
[docs] @classmethod
def from_sha256(cls, sha256_hex_or_bytes: str | bytes, codec: int = CODEC_DAG_CBOR) -> CIDLink:
"""Construct CIDLink from SHA-256 hash."""
if isinstance(sha256_hex_or_bytes, str):
digest = bytes.fromhex(sha256_hex_or_bytes)
else:
digest = bytes(sha256_hex_or_bytes)
if len(digest) != 32:
raise ValueError(f"invalid SHA-256 digest length: {len(digest)}")
raw_cid = varint.write(1) + varint.write(codec) + varint.write(HASH_SHA2_256) + varint.write(DIGEST_LEN_SHA2_256) + digest
return cls(raw_cid, codec, digest)
[docs] @classmethod
def from_dag_cbor(cls, cbor_bytes: bytes) -> CIDLink:
"""Compute DAG-CBOR CID for encoded CBOR bytes."""
h = hashlib.sha256(cbor_bytes).digest()
return cls.from_sha256(h, codec=CODEC_DAG_CBOR)
[docs] @classmethod
def from_raw_blob(cls, data: bytes) -> CIDLink:
"""Compute raw CID for binary blob data."""
h = hashlib.sha256(data).digest()
return cls.from_sha256(h, codec=CODEC_RAW)
def __str__(self) -> str:
return self.cid_str
def __repr__(self) -> str:
return f"CIDLink({self.cid_str!r})"
def __eq__(self, other: Any) -> bool:
if isinstance(other, CIDLink):
return self._bytes == other._bytes
if isinstance(other, str):
return self.cid_str == other
return False
def __hash__(self) -> int:
return hash(self._bytes)
[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