How may one generate IPFS PeerID in Python without involving a working IPFS node?

60 views Asked by At

I need to find a clue about all steps of generation of the PeerID used to identify the IPFS node, and then to generate the third-party PeerID using Python script. Does someone have a working example or a link to a good explanation? I am interested in the generation of PeerID without the involvement of a working IPFS node.

1

There are 1 answers

0
Andrei Vukolov On

As it was already described here: https://discuss.ipfs.tech/t/how-can-i-set-my-own-ed25519-key/9183/14

To ensure IPFS compatibility the proper IPFS protocol buffer should be compiled:

wget https://github.com/libp2p/go-libp2p/blob/master/core/crypto/pb/crypto.proto
protoc --python_out=. crypto.proto

Then it is possible to formulate secret and shared keys using generated module:

import re, base58, base64, crypto_pb2
import cryptography.hazmat.primitives.asymmetric.ed25519 as ed25519
from cryptography.hazmat.primitives import serialization

secret_key = ed25519.Ed25519PrivateKey.generate()
shared_key = secret_key.public_key()

ipfs_shared_bytes = shared_key.public_bytes(encoding=serialization.Encoding.Raw,
                                             format=serialization.PublicFormat.Raw)
ipfs_secure_bytes = secret_key.private_bytes(encoding=serialization.Encoding.Raw,
                                              format=serialization.PrivateFormat.Raw,
                                              encryption_algorithm=serialization.NoEncryption())

# Formulating PeerID
ipfs_pid = base58.b58encode(b'\x00$\x08\x01\x12 ' + ipfs_shared_bytes)
PeerID = ipfs_pid.decode('ascii')
print('PeerID={};'.format(ipfs_pid.decode('ascii')))


# Serializing private key in IPFS-native mode, the private key contains public one
pkey = crypto_pb2.PrivateKey()
#pkey.Type = crypto_pb2.KeyType.Ed25519
pkey.Type = 1
pkey.Data = ipfs_secure_bytes + ipfs_shared_bytes
PrivKey = base64.b64encode(pkey.SerializeToString()).decode('ascii')
print('PrivKEY=' + base64.b64encode(pkey.SerializeToString()).decode('ascii'))