Multicodec Interface ExampleΒΆ
This example demonstrates custom codec registration and lookup:
define a
BlockCodecimplementation (JsonCodec),register it in the codec registry,
look it up by name,
use it with
Block.encodeandBlock.decodefor round-trip verification.
Run it with:
python -m examples.multicodec_interface.multicodec_interface
Expected result:
the registered codec name/code is printed,
a block CID is produced,
a final boolean confirms decoded value equals the input value.
1"""Equivalent of js-multiformats/examples/multicodec-interface.js."""
2
3import json
4from typing import Any
5
6from dag import Block, BlockCodec, lookup_codec, register_codec
7
8
9class JsonCodec(BlockCodec):
10 """Simple JSON codec example (UTF-8 encoded)."""
11
12 @property
13 def name(self) -> str:
14 return "json"
15
16 @property
17 def code(self) -> int:
18 return 0x0200
19
20 def encode(self, node: Any) -> bytes:
21 return json.dumps(node, separators=(",", ":"), sort_keys=True).encode("utf-8")
22
23 def decode(self, data: bytes) -> Any:
24 return json.loads(data.decode("utf-8"))
25
26
27def main() -> None:
28 codec = JsonCodec()
29 register_codec(codec)
30
31 looked_up = lookup_codec("json")
32 print(f"Registered codec: {looked_up.name} (0x{looked_up.code:x})")
33
34 value = {"hello": "world"}
35 block = Block.encode(value=value, codec=looked_up)
36 restored = Block.decode(data=block.bytes, codec=looked_up)
37
38 print(f"Block CID: {block.cid}")
39 print(f"Round-trip value equal: {restored.value == value}")
40
41
42if __name__ == "__main__":
43 main()