Source code for fleetmesh_core.wire.cbor

"""CBOR (RFC 8949) and DAG-CBOR (IPLD), standard library only.

Supports the data types needed across Fleetmesh:
- Hardware Enclave COSE keys and WebAuthn attestation documents.
- Cashu V4 tokens and NUT-18 payment requests.
- ATProto / IPLD repositories and records: Merkle Search Trees (MST),
  commit blocks, and IPLD Link CIDs via Major Type 6 Tag 42.

Enforces deterministic canonical sorting for maps (length-first, then
bytewise lexicographical per RFC 7049 / DAG-CBOR specification).
"""
from __future__ import annotations

import struct
from typing import Any

from ..conformance.errors import FleetmeshError


[docs]class CBORError(FleetmeshError, ValueError): pass
[docs]def cbor_encode(val: Any, *, canonical: bool = False) -> bytes: """Minimal, deterministic CBOR encoder with Tag 42 IPLD Link and COSE support. If canonical is True (or via dag_cbor_encode), map keys are sorted length-first, then bytewise per RFC 7049 / DAG-CBOR. Otherwise, dictionary insertion order is preserved (as required by Cashu V4 / COSE). """ if isinstance(val, bool): return b'\xf5' if val else b'\xf4' if val is None: return b'\xf6' if isinstance(val, int): if val >= 0: return _encode_type_num(0, val) else: return _encode_type_num(1, -1 - val) if isinstance(val, (bytes, bytearray)): return _encode_type_num(2, len(val)) + bytes(val) from ..identity.cid import CIDLink # noqa: PLC0415 if isinstance(val, CIDLink): tag_bytes = val.to_cbor_tag_bytes() return _encode_type_num(6, 42) + _encode_type_num(2, len(tag_bytes)) + tag_bytes if isinstance(val, str): utf8 = val.encode('utf-8') return _encode_type_num(3, len(utf8)) + utf8 if isinstance(val, (list, tuple)): hdr = _encode_type_num(4, len(val)) return hdr + b''.join(cbor_encode(item, canonical=canonical) for item in val) if isinstance(val, dict): # Recognize IPLD JSON link representation {"$link": "bafy..."} if len(val) == 1 and '$link' in val and isinstance(val['$link'], str) and val['$link'].startswith('b'): try: link = CIDLink.from_str(val['$link']) tag_bytes = link.to_cbor_tag_bytes() return _encode_type_num(6, 42) + _encode_type_num(2, len(tag_bytes)) + tag_bytes except Exception: pass hdr = _encode_type_num(5, len(val)) out = [hdr] if canonical: # Deterministic canonical sorting (RFC 7049 / DAG-CBOR): length-first, then bytewise encoded_pairs = [] for k, v in val.items(): encoded_k = cbor_encode(k, canonical=True) encoded_v = cbor_encode(v, canonical=True) encoded_pairs.append((encoded_k, encoded_v)) encoded_pairs.sort(key=lambda pair: (len(pair[0]), pair[0])) for k_bytes, v_bytes in encoded_pairs: out.append(k_bytes) out.append(v_bytes) else: for k, v in val.items(): out.append(cbor_encode(k, canonical=False)) out.append(cbor_encode(v, canonical=False)) return b''.join(out) raise CBORError(f"unsupported CBOR type: {type(val)}")
[docs]def dag_cbor_encode(val: Any) -> bytes: """Encode value to canonical DAG-CBOR bytes.""" return cbor_encode(val, canonical=True)
[docs]def dag_cbor_decode(data: bytes) -> Any: """Decode exact DAG-CBOR bytes, ensuring entire buffer is consumed.""" val, consumed = cbor_decode(data) if consumed != len(data): raise CBORError(f"unconsumed trailing bytes in DAG-CBOR buffer: {len(data) - consumed}") return val
def _encode_type_num(major_type: int, num: int) -> bytes: lead = major_type << 5 if num < 24: return bytes([lead | num]) if num < 256: return bytes([lead | 24, num]) if num < 65536: return bytes([lead | 25]) + struct.pack('>H', num) if num < 4294967296: return bytes([lead | 26]) + struct.pack('>I', num) try: return bytes([lead | 27]) + struct.pack('>Q', num) except struct.error as e: raise CBORError(f"CBOR integer out of 64-bit unsigned range: {num}") from e def _decode_at(data: bytes, offset: int) -> tuple[Any, int]: if offset >= len(data): raise CBORError("empty CBOR buffer") lead = data[offset] major_type = lead >> 5 info = lead & 0x1f offset += 1 def read_num(inf: int) -> int: nonlocal offset if inf < 24: return inf if inf == 24: if len(data) < offset + 1: raise CBORError("truncated CBOR int8") val = data[offset] offset += 1 return val if inf == 25: if len(data) < offset + 2: raise CBORError("truncated CBOR int16") val = struct.unpack('>H', data[offset:offset + 2])[0] offset += 2 return val if inf == 26: if len(data) < offset + 4: raise CBORError("truncated CBOR int32") val = struct.unpack('>I', data[offset:offset + 4])[0] offset += 4 return val if inf == 27: if len(data) < offset + 8: raise CBORError("truncated CBOR int64") val = struct.unpack('>Q', data[offset:offset + 8])[0] offset += 8 return val raise CBORError(f"unsupported CBOR length indicator: {inf}") match major_type: case 0: # unsigned int val = read_num(info) return val, offset case 1: # negative int val = read_num(info) return -1 - val, offset case 2: # byte string length = read_num(info) if len(data) < offset + length: raise CBORError("truncated CBOR byte string") bs = data[offset:offset + length] return bs, offset + length case 3: # text string length = read_num(info) if len(data) < offset + length: raise CBORError("truncated CBOR text string") try: ts = data[offset:offset + length].decode('utf-8') except UnicodeDecodeError as e: raise CBORError(f"invalid UTF-8 in CBOR text string: {e}") from e return ts, offset + length case 4: # array count = read_num(info) if count > len(data) - offset: raise CBORError("truncated container") arr = [] for _ in range(count): item, offset = _decode_at(data, offset) arr.append(item) return arr, offset case 5: # map count = read_num(info) if count > len(data) - offset: raise CBORError("truncated container") mapping: dict[Any, Any] = {} for _ in range(count): k, offset = _decode_at(data, offset) v, offset = _decode_at(data, offset) if k in mapping: raise CBORError(f"duplicate map key: {k!r}") mapping[k] = v return mapping, offset case 6: # Tag tag_num = read_num(info) if tag_num == 42: val, offset = _decode_at(data, offset) if not isinstance(val, (bytes, bytearray)): raise CBORError("CBOR tag 42 content must be byte string") if len(val) == 0 or val[0] != 0: raise CBORError("CBOR tag 42 byte string must start with null multibase byte (0x00)") try: from ..identity.cid import CIDLink # noqa: PLC0415 link = CIDLink.from_cbor_tag_bytes(bytes(val)) except Exception as e: raise CBORError(f"invalid CID in CBOR tag 42: {e}") from e return link, offset raise CBORError(f"unhandled CBOR tag: {tag_num}") case 7: # primitives if info == 20: return False, offset if info == 21: return True, offset if info == 22: return None, offset raise CBORError(f"unhandled CBOR major type: {major_type}")
[docs]def cbor_decode(data: bytes) -> tuple[Any, int]: """Minimal CBOR decoder. Returns (decoded_value, bytes_consumed).""" if not data: raise CBORError("empty CBOR buffer") return _decode_at(data, 0)