Skip to content

Instantly share code, notes, and snippets.

@AndreaCensi
Created April 22, 2019 12:49
Show Gist options
  • Save AndreaCensi/b509f5b5de9ace3cfd6f08a9c619ce16 to your computer and use it in GitHub Desktop.
Save AndreaCensi/b509f5b5de9ace3cfd6f08a9c619ce16 to your computer and use it in GitHub Desktop.
Computing the PeerID
import base64
import hashlib
import base58
import multihash
ipfs_id_output = {
"ID": "QmTn4XvjcA2ZCaWmr3fRZ3MKVj4CzTNVZyjY16Dni5NFc2",
"PublicKey": "CAASpgIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDp5zHxCAqW6mU4bKvwhi2TCZwdga5IkhdTxHnIA9IdagB/IevNhe0O+O7Rc7czC+0tqWLLDS99oM1FjDqmHbMGiGsEmsVDrkWgx4d7+aHaHQWzNvxTd96gP6mY/ww6tvA5k6Tnow6pgUGvIl32GYDd+n4XqWnt/heoDXTenASnXh7aEBMhXXosZelxme6Bfwqmd0YO/Y4J1oNeHprgzJlZ901AwpcITfZCQuUCiGyot72kmD5wdAQu31KMXI0Rf7rMr20cnQI5SE9hoXR7NWtZ3zEg+4ODsP2ssn7QcIepm7WXeb1EO9GXsL6eMqkDSiVmUF23h5BJDirucZ7fDnPHAgMBAAE=",
"Addresses": [
"/ip4/127.0.0.1/tcp/4001/ipfs/QmTn4XvjcA2ZCaWmr3fRZ3MKVj4CzTNVZyjY16Dni5NFc2",
"/ip4/192.168.0.94/tcp/4001/ipfs/QmTn4XvjcA2ZCaWmr3fRZ3MKVj4CzTNVZyjY16Dni5NFc2",
"/ip6/::1/tcp/4001/ipfs/QmTn4XvjcA2ZCaWmr3fRZ3MKVj4CzTNVZyjY16Dni5NFc2",
"/ip4/178.83.157.226/tcp/64069/ipfs/QmTn4XvjcA2ZCaWmr3fRZ3MKVj4CzTNVZyjY16Dni5NFc2"
],
"AgentVersion": "go-ipfs/0.4.20/",
"ProtocolVersion": "ipfs/0.1.0"
}
public_key_base64 = ipfs_id_output['PublicKey']
public_key_bytes = base64.b64decode(public_key_base64)
digest = hashlib.sha256(public_key_bytes).digest()
mh = bytes(multihash.encode(digest=digest, code=18))
peer_id_computed = base58.b58encode(mh).decode()
peer_id_expected = ipfs_id_output["ID"]
print(f'Computed: {peer_id_computed}')
print(f'Expected: {peer_id_expected}')
# Obtained: QmPY9cTB72kGik7hZog99MZ74zTegdHv5QCX3oYqeT1Exi
# Expected: QmTn4XvjcA2ZCaWmr3fRZ3MKVj4CzTNVZyjY16Dni5NFc2
assert peer_id_computed == peer_id_expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment