content_hash.get_codec()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 10
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 10
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 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