Beispiel #1
0
def from_bytes(cidbytes):
    """
    Creates a CID object from a encoded form

    :param bytes cidbytes: can be

        - base58-encoded multihash
        - multihash
        - multibase-encoded multihash
    :return: a CID object
    :rtype: :py:class:`cid.CIDv0` or :py:class:`cid.CIDv1`
    :raises: `ValueError` if the base58-encoded string is not a valid string
    """
    if multibase.is_encoded(cidbytes):
        # if the bytestream is multibase encoded
        cid = multibase.decode(cidbytes)
        data = cid[1:]
        version = int(cid[0])
        codec = multicodec.get_codec(data)
        multihash = multicodec.remove_prefix(data)
    elif cidbytes[0] in (b'0', b'1'):
        # if the bytestream is a CID
        version = cidbytes[0]
        data = cidbytes[1:]
        codec = multicodec.get_codec(data)
        multihash = multicodec.remove_prefix(data)
    else:
        # otherwise its just base58-encoded multihash
        try:
            version = 0
            codec = CIDv0.CODEC
            multihash = base58.b58decode(cidbytes)
        except ValueError:
            raise ValueError(
                'multihash is not a valid base58 encoded multihash')

    try:
        mh.decode(multihash)
    except ValueError:
        raise

    return make_cid(version, codec, multihash)
Beispiel #2
0
def test_decode_incorrect_encoding(encoded_data):
    with pytest.raises(ValueError) as excinfo:
        decode(encoded_data)
    assert 'Can not determine encoding' in str(excinfo.value)
Beispiel #3
0
def test_decode(_, data, encoded_data):
    assert decode(encoded_data) == ensure_bytes(data)