Each libp2p has a public/private key pair (if you dont know about asymetric cryptography you can for now think of like passwords). In the last section we said there could be multiple nodes running on the same ip / port and hence we need a PeerId
. The PeerId is actually the cryptographic hash of the node's public key.
check out the PeerId spec for details.
Libp2p by default assigns a PeerId
but you can also specify your own PeerId
by adding it to the options
let options = {
...
peerId: {
"id": "Qma3GsJmB47xYuyahPZPSadh1avvxfyYQwk8R3UnFrQ6aP",
"privKey": "CAASpwkwgg...",
"pubKey": "CAASpgIwggEiMA0G..."
}
})
Once you have a libp2p instance running, you can listen to several events to trigger certain actions. An example can be -
libp2p.on('error', (err) => {})
This is an instance for listening to an error in Libp2p. Another example could be if it finds a new peer to connect to -
libp2p.on('peer:discovery', (peer) => {})
Note - You can learn more about these listeners in the official documentation here
Try it yourself
- Add a new listener for the
peer:connect
and print out the PeerId for theremotePeer
in the body of the listener - Run it and you should see a list of your node's multiaddrs
peerInfo.id.toB58String()
returns thepeerId
as a string