CID.fromData constructor

CID.fromData(
  1. int version,
  2. String codecName,
  3. Uint8List data, [
  4. String multihashName = 'sha2-256',
])

Creates a CID by hashing the input data.

This is a convenience factory for creating CIDs directly from content. It first computes the digest of the data using the specified multihashName, then wraps it in a multihash, and finally constructs the CID.

  • version: The CID version (CID.V0 or CID.V1).
  • codecName: The string name of the multicodec for the content type (e.g., "dag-pb", "raw").
  • data: The Uint8List of raw data to be hashed.
  • multihashName: (Optional) The string name of the multihash algorithm to use. Defaults to 'sha2-256'. Currently supports 'sha2-256' and 'sha2-512' for automatic hashing.

For CIDv0, codecName must be 'dag-pb' and multihashName must be 'sha2-256'. Throws ArgumentError if parameters are invalid or multihashName is unsupported.

Example:

final data = utf8.encode('Hello IPFS!');
final cid = CID.fromData(CID.V1, 'raw', data, 'sha2-256');
print(cid.toString()); // e.g., bafkreicysg23kiwv34eg2d7qweipxw2w72v2edxywccodvrscfwb7na2i4

Implementation

factory CID.fromData(int version, String codecName, Uint8List data, [String multihashName = 'sha2-256']) {
  final codecCode = codecNameToCode[codecName];
  if (codecCode == null) {
    throw ArgumentError('Unknown codec name: $codecName');
  }

  if (version == V0) {
    if (codecName != 'dag-pb') {
      throw ArgumentError('CIDv0 codec must be "dag-pb", got "$codecName"');
    }
    if (multihashName != 'sha2-256') {
      throw ArgumentError('CIDv0 multihash algorithm must be "sha2-256", got "$multihashName"');
    }
  }

  // 1. Compute the digest of the data
  Uint8List digest;
  if (multihashName == 'sha2-256') {
    digest = Uint8List.fromList(crypto.sha256.convert(data).bytes);
  } else if (multihashName == 'sha2-512') {
    digest = Uint8List.fromList(crypto.sha512.convert(data).bytes);
  }
  // Add other hash algorithms as needed from package:crypto
  else {
    throw ArgumentError('Unsupported multihash algorithm for CID.fromData: $multihashName. Only sha2-256 and sha2-512 are currently supported for automatic hashing.');
  }

  // 2. Encode this digest into a multihash using dart_multihash
  final mh.MultihashInfo multihashInfo = mh.Multihash.encode(multihashName, digest);
  return CID(version, codecCode, multihashInfo.toBytes());
}