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 check (SHA2-256)
  // 0x12 0x20 ... (34 bytes total)
  if (bytes.length == 34 && bytes[0] == 0x12 && bytes[1] == 0x20) {
    return CID(
      version: 0,
      multihash: Multihash.decode(bytes),
      codec: 'dag-pb',
      multibaseType: Multibase.base58btc,
    );
  }

  // CIDv1 check
  if (bytes[0] == 0x01) {
    int index = 1;
    int codecCode = 0;
    int shift = 0;
    while (true) {
      if (index >= bytes.length) {
        throw const FormatException('Invalid CID bytes');
      }
      int byte = bytes[index++];
      codecCode |= (byte & 0x7f) << shift;
      if ((byte & 0x80) == 0) break;
      shift += 7;
    }

    final mh = Multihash.decode(bytes.sublist(index));

    String codecStr;
    try {
      codecStr = EncodingUtils.getCodecFromCode(codecCode);
    } catch (e) {
      codecStr = 'unknown'; // Or throw?
      // If unknown, 'unknown' might break equal check if original was 'unknown' or asserted?
      // But better to use string 'unknown' than failing if that's what we want.
      // But wait, `EncodingUtils` throws ArgumentError if unknown.
      // If I catch it, I can default to 'unknown'.
      // But better to let it throw or return unknown?
      // The previous code returned 'unknown' if not matched.
      // So keeping 'unknown' is safe fallback for now.
    }

    // Special case: if getCodecFromCode doesn't have it, we fall back to 'unknown'.
    // But if we want to SUPPORT 'dag-cbor', EncodingUtils MUST have it.
    // I tested EncodingUtils has 'dag-cbor'. So it will return 'dag-cbor'.

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

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