fromBytes static method

CID fromBytes(
  1. Uint8List bytes
)

Parses a CID from its raw binary representation.

Implementation

static CID fromBytes(Uint8List bytes) {
  if (bytes.isEmpty) throw ArgumentError('Empty bytes');

  // CIDv0: 34 bytes starting with 0x12 0x20 (sha2-256, 32-byte digest)
  if (bytes.length >= 34 && bytes[0] == 0x12 && bytes[1] == 0x20) {
    return CID(
      version: 0,
      multihash: MultihashUtils.decode(bytes.sublist(0, 34)),
      codec: 'dag-pb',
      multibaseType: mb.Multibase.base58btc,
    );
  }

  // CIDv1: first byte is 0x01
  if (bytes[0] == 0x01) {
    var index = 1;
    final (codecCode, codecLen) = readVarint(bytes, index);
    index += codecLen;

    final mhStart = index;
    final (hashCode, codeLen) = readVarint(bytes, index);
    index += codeLen;
    final (digestLen, lenLen) = readVarint(bytes, index);
    index += lenLen;
    final mhEnd = index + digestLen;
    if (mhEnd > bytes.length) {
      throw const FormatException('Invalid CID bytes: multihash truncated');
    }
    final mh = MultihashUtils.decode(bytes.sublist(mhStart, mhEnd));

    final codecStr = Multicodec.supportsByCode(codecCode)
        ? Multicodec.name(codecCode)
        : 'unknown';

    return CID(
      version: 1,
      multihash: mh,
      codec: codecStr,
      multibaseType: mb.Multibase.base32,
    );
  }

  throw const FormatException('Invalid CID version');
}