CID Interface ExampleΒΆ

This example shows common CID operations for JSON-encoded content:

  • create a CIDv1 from deterministic JSON bytes,

  • encode CID strings in base32 and base64,

  • parse CIDs back from strings,

  • round-trip CID bytes back to a CID object,

  • compare outputs against values documented in the JS reference example.

Run it with:

python -m examples.cid_interface.cid_interface
python -m examples.cid_interface.cid_interface --json

Expected result:

  • printed CID string/codec/version information,

  • booleans showing string/bytes round-trips are equivalent to the original CID.

 1"""Equivalent of js-multiformats/examples/cid-interface.js."""
 2
 3import argparse
 4import json
 5
 6from dag.utils import bytes_to_cid, cid_to_bytes, create_cid, string_to_cid
 7
 8JS_EXPECTED = {
 9    "base32_cid": "bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea",
10    "base64_cid": "mAYAEEiCTojlxqRTl6svwqNJRVM2jCcPBxy+7mRTUfGDzy2gViA",
11}
12
13
14def build_report() -> dict[str, object]:
15    value = {"hello": "world"}
16    encoded_json = json.dumps(value, separators=(",", ":"), sort_keys=True).encode("utf-8")
17
18    # Use the plain "json" multicodec to mirror js-multiformats cid-interface.js.
19    cid = create_cid(encoded_json, codec="json", hasher="sha2-256", version=1)
20    base32_cid = cid.encode("base32").decode("ascii")
21    base64_cid = cid.encode("base64").decode("ascii")
22
23    parsed_from_base32 = string_to_cid(base32_cid)
24    parsed_from_base64 = string_to_cid(base64_cid)
25    restored_from_bytes = bytes_to_cid(cid_to_bytes(cid))
26
27    matches = {
28        "base32_cid": base32_cid == JS_EXPECTED["base32_cid"],
29        "base64_cid": base64_cid == JS_EXPECTED["base64_cid"],
30        "parsed_from_base32_equals_original": parsed_from_base32.buffer == cid.buffer,
31        "parsed_from_base64_equals_original": parsed_from_base64.buffer == cid.buffer,
32        "bytes_round_trip_equals_original": restored_from_bytes.buffer == cid.buffer,
33    }
34
35    return {
36        "input": value,
37        "codec": "json",
38        "codec_code_hex": "0x200",
39        "cid_version": cid.version,
40        "default_cid_string": str(cid),
41        "base32_cid": base32_cid,
42        "base64_cid": base64_cid,
43        "js_expected": JS_EXPECTED,
44        "matches_js_comments": matches,
45    }
46
47
48def main() -> None:
49    parser = argparse.ArgumentParser(description="CID interface example")
50    parser.add_argument("--json", action="store_true", help="Print structured JSON report")
51    args = parser.parse_args()
52
53    report = build_report()
54    if args.json:
55        print(json.dumps(report, indent=2, sort_keys=True))
56        return
57
58    print(f"Example CID (default string form): {report['default_cid_string']}")
59    print(f"Codec code: {report['codec_code_hex']}")
60    print(f"CID version: {report['cid_version']}")
61    print(f"base64 encoded CID: {report['base64_cid']}")
62    print(f"Parsed from base64 equals original: {report['matches_js_comments']['parsed_from_base64_equals_original']}")
63    print(f"base32 encoded CID: {report['base32_cid']}")
64    print(f"Parsed from base32 equals original: {report['matches_js_comments']['parsed_from_base32_equals_original']}")
65    print(f"CID bytes round-trip equal: {report['matches_js_comments']['bytes_round_trip_equals_original']}")
66    print(
67        "Matches js comments (base32/base64): "
68        f"{report['matches_js_comments']['base32_cid']}/"
69        f"{report['matches_js_comments']['base64_cid']}"
70    )
71
72
73if __name__ == "__main__":
74    main()