The cid module implements the Content IDentifier spec.

>>> from multiformats import CID


Core functionality is provided by the CID class. CIDs can be created programmatically from a choice of multibase, CID version, multicodec and multihash digest:

>>> digest = \
... "12206e6ff7950a36187a801613426e858dce686cd7d7e3c0fc42ee0330072d245c95"
>>> cid = CID("base58btc", 1, "raw", digest)
>>> cid.base
Multibase(name='base58btc', code='z',
          status='default', description='base58 bitcoin')
>>> cid.codec
Multicodec(name='raw', tag='ipld', code='0x55',
           status='permanent', description='raw binary')
>>> cid.digest.hex()

Additionally, the hashfun and raw_digest properties can be used to access the multihash multicodec and raw digest that form the multihash digest:

>>> cid.hashfun
Multicodec(name='sha2-256', tag='multihash', code='0x12',
           status='permanent', description='')
>>> cid.raw_digest.hex()


The decode method can be used to decode CIDs from bytestrings or (multi)base encoded strings:

>>> cid = CID.decode("zb2rhe5P4gXftAwvA4eXQ5HJwsER2owDyS9sKaQRRVQPn93bA")
>>> cid
CID('base58btc', 1, 'raw',

str, bytes

CIDs can be converted to bytestrings or (multi)base encoded strings:

>>> bytes(cid).hex()
>>> str(cid) # encode with own multibase 'base58btc'
>>> cid.encode("base32") # encode with different multibase


The peer_id static method can be used to pack the raw hash of a public key into a CIDv1 PeerID, according to the PeerID spec:

>>> pk_bytes = bytes.fromhex( # hex-string of 32-byte Ed25519 public key
... "1498b5467a63dffa2dc9d9e069caf075d16fc33fdd4c3b01bfadae6433767d93")
>>> peer_id = CID.peer_id(pk_bytes)
>>> peer_id
CID('base32', 1, 'libp2p-key',
#^^   0x00 = 'identity' multihash used (public key length <= 42)
#  ^^ 0x20 = 32-bytes of raw hash digest length
>>> str(peer_id)