Private
#privateGets a list of topics the node is subscribed to.
const topics = libp2p.pubsub.getTopics()
The global signature policy controls whether or not we sill send and receive signed or unsigned messages.
Signed messages prevent spoofing message senders and should be preferred to using unsigned messages.
A list of multicodecs that contain the pubsub protocol name.
Publishes messages to the given topic.
const topic = 'topic'
const data = uint8ArrayFromString('data')
await libp2p.pubsub.publish(topic, data)
Subscribes to a pubsub topic.
const topic = 'topic'
const handler = (msg) => {
if (msg.topic === topic) {
// msg.data - pubsub data received
}
}
libp2p.pubsub.addEventListener('message', handler)
libp2p.pubsub.subscribe(topic)
Pubsub routers support message validators per topic, which will validate the message before its propagations. They are stored in a map where keys are the topic name and values are the validators.
const topic = 'topic'
const validateMessage = (msgTopic, msg) => {
const input = uint8ArrayToString(msg.data)
const validInputs = ['a', 'b', 'c']
if (!validInputs.includes(input)) {
throw new Error('no valid input received')
}
}
libp2p.pubsub.topicValidators.set(topic, validateMessage)
Unsubscribes from a pubsub topic.
const topic = 'topic'
const handler = (msg) => {
// msg.data - pubsub data received
}
libp2p.pubsub.removeEventListener(topic handler)
libp2p.pubsub.unsubscribe(topic)
Optional
options: boolean | AddEventListenerOptionsOptional
listener: null | EventHandler<Events[K]>Optional
options: boolean | EventListenerOptions
Adds types to the EventTarget class. Hopefully this won't be necessary forever.
https://github.com/microsoft/TypeScript/issues/28357 https://github.com/microsoft/TypeScript/issues/43477 https://github.com/microsoft/TypeScript/issues/299 etc