Skip to content

A Publish-Subscribe library for peer to peer messaging within libp2p

Notifications You must be signed in to change notification settings

swift-libp2p/swift-libp2p-pubsub

Repository files navigation

LibP2PPubSub

Swift Package Manager compatible Build & Test (macos and linux)

A WIP implementation of FloodSub and GossipSub Routers for swift-libp2p

Warning This is a WIP. It probably won't work the way it's supposed to. Please file issues accordingly.

Table of Contents

Overview

This repo contains the pubsub implementation for swift-libp2p. We currently provide two message routers:

  • Floodsub, which is the baseline flooding protocol.
  • Gossipsub, which is a more advanced router with mesh formation and gossip propagation.

Note For more information check out the Libp2p PubSub Spec

Install

Include the following dependency in your Package.swift file

let package = Package(
    ...
    dependencies: [
        ...
        .package(name: "LibP2PPubSub", url: "https://github.com/swift-libp2p/swift-libp2p-pubsub.git", .upToNextMajor(from: "0.0.1"))
    ],
    
    ...
)

Usage

Example

check out the tests for more examples

import LibP2PPubSub

/// Configure libp2p
let app = Application(...)
// We have to use the `BasicConnectionLight` `Connection` implementation here! (the default `ARCConnection`, doesn't work due to the agressive timeout behaviour...)
app.connectionManager.use(connectionType: BasicConnectionLight.self)
// Tell it to use Floodsub
app.pubsub.use(.floodsub)
// Or tell it to use Gossipsub
app.pubsub.use(.gossipsub)

/// Subscribe
let subscription = try app.pubsub.gossipsub.subscribe(.init(topic: "news", signaturePolicy: .strictSign, validator: .acceptAll, messageIDFunc: .hashSequenceNumberAndFromFields))
subscription.on = { event -> EventLoopFuture<Void> in
    switch event {
    case .newPeer(let peer):
        ...
        
    case .data(let pubSubMessage):
        ...
        
    case .error(let error):
        ...
    }
    return app.eventLoopGroup.any().makeSucceededVoidFuture()
}


/// Publish Message
// Using a subscription
subscription.publish("Hello".data(using: .utf8))
// Without a subscription
app.pubsub.publish("Hello".data(using: .utf8), to: "topic")


/// Unsubscribe
// Using a subscription
subscription.unsubscribe()
// Without a subscription
app.pubsub.unsubscribe("topic")


/// Stop the app
app.shutdown()

API

/// Initializers

/// Properties

/// Methods

Contributing

Contributions are welcomed! This code is very much a proof of concept. I can guarantee you there's a better / safer way to accomplish the same results. Any suggestions, improvements, or even just critques, are welcome!

Let's make this code better together! 🤝

Credits

License

MIT © 2022 Breth Inc.

Releases

No releases published

Packages

No packages published

Languages