Total Complexity | 3 |
Total Lines | 44 |
Duplicated Lines | 0 % |
Coverage | 0% |
Changes | 0 |
1 | """Python implementation of EIP 1577 content hash.""" |
||
2 | |||
3 | from multiformats import multihash, multicodec, CID |
||
4 | |||
5 | from .profiles import get_profile |
||
6 | |||
7 | |||
8 | def decode(chash: str) -> str: |
||
9 | """ |
||
10 | Decode a content hash. |
||
11 | |||
12 | :param hash: a hex string containing a content hash |
||
13 | |||
14 | :return: the decoded content |
||
15 | """ |
||
16 | codec, raw_data = multicodec.unwrap(bytes.fromhex(chash.lstrip('0x'))) |
||
17 | profile = get_profile(codec.name) |
||
18 | return profile.decode(raw_data) |
||
19 | |||
20 | |||
21 | def encode(codec: str, value: str) -> str: |
||
22 | """ |
||
23 | Encode a content hash. |
||
24 | |||
25 | :param codec: a codec of a content hash |
||
26 | :param value: a value of a content hash |
||
27 | |||
28 | :return: the resulting content hash |
||
29 | """ |
||
30 | value = get_profile(codec).encode(value) |
||
31 | return multicodec.wrap(codec, value).hex() |
||
32 | |||
33 | |||
34 | def get_codec(chash: str) -> str: |
||
35 | """ |
||
36 | Extract the codec of a content hash |
||
37 | |||
38 | :param hash: a hex string containing a content hash |
||
39 | |||
40 | :return: the extracted codec |
||
41 | """ |
||
42 | codec, _ = multicodec.unwrap(bytes.fromhex(chash.lstrip('0x'))) |
||
43 | return codec.name |
||
44 |