Develop own Libp2p Protocol

Hi Team,

I am trying to implement my own protocol, specificially the contract net protocol (https://en.wikipedia.org/wiki/Contract_Net_Protocol)- allowing 2 nodes to negotaite over an asset. I’m quite new to new libp2p and have went over the tutorials for the ping and chat protocol. Can you please give me a guideline on how to do this? Do I need to use the interface transport API?(https://github.com/libp2p/interface-transport)

Thanks!

The protocol you’re looking at implementing doesn’t appear to need a customized way of speaking with one another, unless I am missing something, so you shouldn’t need a custom transport.

Your scenario seems to be, that once you are connected to a peer that speaks the contract protocol, you want to execute some form of negotiation. Is that correct?

If so, this is done by registering a handler for your protocol. The chat example does this, https://github.com/libp2p/js-libp2p/blob/v0.27.3/examples/chat/src/listener.js#L24-L29, although it’s a very simple protocol, it just pipes data from stdin and stdout.

Your protocol will be more complicated, as you need to do some level of negotiation. The registration would look something like this:

  libp2p.handle('/contract-net/1.0.0', ({ protocol, stream }) => {
    // We received an incoming `stream` on our `protocol`
    // 1. Read the initial message on `stream` from the sender
    // 2. Create a response and write it to the `stream`
    // 3. Repeat as needed for the protocol
  })

You can send whatever data you like, JSON, text, protobuf, etc, depending on what type of data you need to exchange and what your request/response process looks like. Internally in libp2p we use protobuf for most things.

With the protocol registered you can then dial to other peers in your application and create streams on your custom protocol to perform the asset negotiation.

const connection = await libp2p.dial(targetPeer)
const { stream } = await connection.newStream('/contract-net/1.0.0')
// 1. Write the initial payload to the `stream`
// 2. Read back the response from the handler above
// 3. Repeat as needed
2 Likes