Block Interface ExampleΒΆ
This example demonstrates the core Block workflow with dag-cbor:
encode a Python value into block bytes + CID,
decode block bytes back into a value,
re-create a block from known pieces (CID + bytes + value),
verify all resulting CIDs are equivalent.
Run it with:
python -m examples.block_interface.block_interface
python -m examples.block_interface.block_interface --json
Expected result:
a printed CID for the encoded block,
boolean checks confirming decoded/recreated blocks match the original CID.
1"""Equivalent of js-multiformats/examples/block-interface.js."""
2
3import argparse
4import json
5
6from dag import Block
7from dag.codecs import dag_cbor
8
9
10def build_report() -> dict[str, object]:
11 value = {"hello": "world"}
12
13 # Encode a block.
14 block = Block.encode(value=value, codec=dag_cbor.codec, hasher="sha2-256")
15
16 # Decode from bytes.
17 block2 = Block.decode(data=block.bytes, codec=dag_cbor.codec, hasher="sha2-256")
18
19 # Re-create from known pieces (bytes + cid + decoded value).
20 block3 = Block.create(data=block.bytes, cid=block.cid, value=block2.value, codec=dag_cbor.codec)
21 return {
22 "input": value,
23 "codec": "dag-cbor",
24 "cid": str(block.cid),
25 "checks": {
26 "decoded_cid_equals_original": block.cid.buffer == block2.cid.buffer,
27 "created_cid_equals_original": block.cid.buffer == block3.cid.buffer,
28 },
29 }
30
31
32def main() -> None:
33 parser = argparse.ArgumentParser(description="Block interface example")
34 parser.add_argument("--json", action="store_true", help="Print structured JSON report")
35 args = parser.parse_args()
36
37 report = build_report()
38 if args.json:
39 print(json.dumps(report, indent=2, sort_keys=True))
40 return
41
42 print(f"Example block CID: {report['cid']}")
43 print(f"CID equal to decoded block: {report['checks']['decoded_cid_equals_original']}")
44 print(f"CID equal to block created from CID + bytes: {report['checks']['created_cid_equals_original']}")
45
46
47if __name__ == "__main__":
48 main()